-
Notifications
You must be signed in to change notification settings - Fork 848
Expand file tree
/
Copy pathacp226.go
More file actions
70 lines (58 loc) · 2.4 KB
/
acp226.go
File metadata and controls
70 lines (58 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright (C) 2019-2025, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
// ACP-226 implements the dynamic minimum block delay mechanism specified here:
// https://github.com/avalanche-foundation/ACPs/blob/main/ACPs/226-dynamic-minimum-block-times/README.md
package acp226
import (
"sort"
"github.com/ava-labs/avalanchego/vms/components/gas"
safemath "github.com/ava-labs/avalanchego/utils/math"
)
const (
// MinDelayMilliseconds (M) is the minimum block delay in milliseconds
MinDelayMilliseconds = 1 // ms
// ConversionRate (D) is the conversion factor for exponential calculations
ConversionRate = 1 << 20
// MaxDelayExcessDiff (Q) is the maximum change in excess per update
MaxDelayExcessDiff = 200
DefaultDelayExcess = 7_970_124
maxDelayExcess = 46_516_320 // ConversionRate * ln(MaxUint64 / MinDelayMilliseconds) + 1
)
// DelayExcess represents the excess for delay calculation in the dynamic minimum block delay mechanism.
type DelayExcess uint64
// Delay returns the minimum block delay in milliseconds, `m`.
//
// Delay = MinDelayMilliseconds * e^(DelayExcess / ConversionRate)
func (t DelayExcess) Delay() uint64 {
return uint64(gas.CalculatePrice(
MinDelayMilliseconds,
gas.Gas(t),
ConversionRate,
))
}
// UpdateDelayExcess updates the DelayExcess to be as close as possible to the
// desiredDelayExcess without exceeding the maximum DelayExcess change.
func (t *DelayExcess) UpdateDelayExcess(desiredDelayExcess uint64) {
*t = DelayExcess(calculateDelayExcess(uint64(*t), desiredDelayExcess))
}
// DesiredDelayExcess calculates the optimal delay excess given the desired
// delay.
func DesiredDelayExcess(desiredDelay uint64) uint64 {
// This could be solved directly by calculating D * ln(desired / M)
// using floating point math. However, it introduces inaccuracies. So, we
// use a binary search to find the closest integer solution.
return uint64(sort.Search(maxDelayExcess, func(delayExcessGuess int) bool {
excess := DelayExcess(delayExcessGuess)
return excess.Delay() >= desiredDelay
}))
}
// calculateDelayExcess calculates the optimal new DelayExcess for a block proposer to
// include given the current and desired excess values.
func calculateDelayExcess(excess, desired uint64) uint64 {
change := safemath.AbsDiff(excess, desired)
change = min(change, MaxDelayExcessDiff)
if excess < desired {
return excess + change
}
return excess - change
}