-
Notifications
You must be signed in to change notification settings - Fork 228
Expand file tree
/
Copy pathcommon.go
More file actions
289 lines (238 loc) · 9.2 KB
/
common.go
File metadata and controls
289 lines (238 loc) · 9.2 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package common
import (
"encoding/hex"
"fmt"
"math/bits"
"strconv"
"strings"
"github.com/multiversx/mx-chain-core-go/core"
"github.com/multiversx/mx-chain-core-go/core/check"
"github.com/multiversx/mx-chain-core-go/data"
"github.com/multiversx/mx-chain-go/config"
"github.com/multiversx/mx-chain-go/errors"
logger "github.com/multiversx/mx-chain-logger-go"
)
const (
keySeparator = "-"
expectedKeyLen = 2
hashIndex = 0
shardIndex = 1
nonceIndex = 0
)
type chainParametersHandler interface {
CurrentChainParameters() config.ChainParametersByEpochConfig
ChainParametersForEpoch(epoch uint32) (config.ChainParametersByEpochConfig, error)
IsInterfaceNil() bool
}
// IsValidRelayedTxV3 returns true if the provided transaction is a valid transaction of type relayed v3
func IsValidRelayedTxV3(tx data.TransactionHandler) bool {
relayedTx, isRelayedV3 := tx.(data.RelayedTransactionHandler)
if !isRelayedV3 {
return false
}
hasValidRelayer := len(relayedTx.GetRelayerAddr()) == len(tx.GetSndAddr()) && len(relayedTx.GetRelayerAddr()) > 0
hasValidRelayerSignature := len(relayedTx.GetRelayerSignature()) == len(relayedTx.GetSignature()) && len(relayedTx.GetRelayerSignature()) > 0
return hasValidRelayer && hasValidRelayerSignature
}
// IsRelayedTxV3 returns true if the provided transaction is a transaction of type relayed v3, without any further checks
func IsRelayedTxV3(tx data.TransactionHandler) bool {
relayedTx, isRelayedV3 := tx.(data.RelayedTransactionHandler)
if !isRelayedV3 {
return false
}
hasRelayer := len(relayedTx.GetRelayerAddr()) > 0
hasRelayerSignature := len(relayedTx.GetRelayerSignature()) > 0
return hasRelayer || hasRelayerSignature
}
// IsEpochChangeBlockForFlagActivation returns true if the provided header is the first one after the specified flag's activation
func IsEpochChangeBlockForFlagActivation(header data.HeaderHandler, enableEpochsHandler EnableEpochsHandler, flag core.EnableEpochFlag) bool {
isStartOfEpochBlock := header.IsStartOfEpochBlock()
isBlockInActivationEpoch := header.GetEpoch() == enableEpochsHandler.GetActivationEpoch(flag)
return isStartOfEpochBlock && isBlockInActivationEpoch
}
// IsFlagEnabledAfterEpochsStartBlock returns true if the flag is enabled for the header, but it is not the epoch start block
func IsFlagEnabledAfterEpochsStartBlock(header data.HeaderHandler, enableEpochsHandler EnableEpochsHandler, flag core.EnableEpochFlag) bool {
isFlagEnabled := enableEpochsHandler.IsFlagEnabledInEpoch(flag, header.GetEpoch())
isEpochStartBlock := IsEpochChangeBlockForFlagActivation(header, enableEpochsHandler, flag)
return isFlagEnabled && !isEpochStartBlock
}
// GetShardIDs returns a map of shard IDs based on the number of shards
func GetShardIDs(numShards uint32) map[uint32]struct{} {
shardIdentifiers := make(map[uint32]struct{})
for i := uint32(0); i < numShards; i++ {
shardIdentifiers[i] = struct{}{}
}
shardIdentifiers[core.MetachainShardId] = struct{}{}
return shardIdentifiers
}
// GetBitmapSize will return expected bitmap size based on provided consensus size
func GetBitmapSize(
consensusSize int,
) int {
expectedBitmapSize := consensusSize / 8
if consensusSize%8 != 0 {
expectedBitmapSize++
}
return expectedBitmapSize
}
// IsConsensusBitmapValid checks if the provided keys and bitmap match the consensus requirements
func IsConsensusBitmapValid(
log logger.Logger,
consensusPubKeys []string,
bitmap []byte,
shouldApplyFallbackValidation bool,
) error {
consensusSize := len(consensusPubKeys)
expectedBitmapSize := GetBitmapSize(consensusSize)
if len(bitmap) != expectedBitmapSize {
log.Debug("wrong size bitmap",
"expected number of bytes", expectedBitmapSize,
"actual", len(bitmap))
return ErrWrongSizeBitmap
}
numOfOnesInBitmap := 0
for index := range bitmap {
numOfOnesInBitmap += bits.OnesCount8(bitmap[index])
}
minNumRequiredSignatures := core.GetPBFTThreshold(consensusSize)
if shouldApplyFallbackValidation {
minNumRequiredSignatures = core.GetPBFTFallbackThreshold(consensusSize)
log.Warn("IsConsensusBitmapValid: fallback validation has been applied",
"minimum number of signatures required", minNumRequiredSignatures,
"actual number of signatures in bitmap", numOfOnesInBitmap,
)
}
if numOfOnesInBitmap >= minNumRequiredSignatures {
return nil
}
log.Debug("not enough signatures",
"minimum expected", minNumRequiredSignatures,
"actual", numOfOnesInBitmap)
return ErrNotEnoughSignatures
}
// ConsensusGroupSizeForShardAndEpoch returns the consensus group size for a specific shard in a given epoch
func ConsensusGroupSizeForShardAndEpoch(
log logger.Logger,
chainParametersHandler chainParametersHandler,
shardID uint32,
epoch uint32,
) int {
currentChainParameters, err := chainParametersHandler.ChainParametersForEpoch(epoch)
if err != nil {
log.Warn("ConsensusGroupSizeForShardAndEpoch: could not compute chain params for epoch. "+
"Will use the current chain parameters", "epoch", epoch, "error", err)
currentChainParameters = chainParametersHandler.CurrentChainParameters()
}
if shardID == core.MetachainShardId {
return int(currentChainParameters.MetachainConsensusGroupSize)
}
return int(currentChainParameters.ShardConsensusGroupSize)
}
// GetEquivalentProofNonceShardKey returns a string key nonce-shardID
func GetEquivalentProofNonceShardKey(nonce uint64, shardID uint32) string {
return fmt.Sprintf("%d%s%d", nonce, keySeparator, shardID)
}
// GetEquivalentProofHashShardKey returns a string key hash-shardID
func GetEquivalentProofHashShardKey(hash []byte, shardID uint32) string {
return fmt.Sprintf("%s%s%d", hex.EncodeToString(hash), keySeparator, shardID)
}
// GetHashAndShardFromKey returns the hash and shard from the provided key
func GetHashAndShardFromKey(hashShardKey []byte) ([]byte, uint32, error) {
hashShardKeyStr := string(hashShardKey)
result := strings.Split(hashShardKeyStr, keySeparator)
if len(result) != expectedKeyLen {
return nil, 0, ErrInvalidHashShardKey
}
hash, err := hex.DecodeString(result[hashIndex])
if err != nil {
return nil, 0, err
}
shard, err := strconv.Atoi(result[shardIndex])
if err != nil {
return nil, 0, err
}
return hash, uint32(shard), nil
}
// GetNonceAndShardFromKey returns the nonce and shard from the provided key
func GetNonceAndShardFromKey(nonceShardKey []byte) (uint64, uint32, error) {
nonceShardKeyStr := string(nonceShardKey)
result := strings.Split(nonceShardKeyStr, keySeparator)
if len(result) != expectedKeyLen {
return 0, 0, ErrInvalidNonceShardKey
}
nonce, err := strconv.Atoi(result[nonceIndex])
if err != nil {
return 0, 0, err
}
shard, err := strconv.Atoi(result[shardIndex])
if err != nil {
return 0, 0, err
}
return uint64(nonce), uint32(shard), nil
}
// ConvertTimeStampSecToMs will convert unix timestamp from seconds to milliseconds
func ConvertTimeStampSecToMs(timeStamp uint64) uint64 {
return timeStamp * 1000
}
func convertTimeStampMsToSec(timeStamp uint64) uint64 {
return timeStamp / 1000
}
// GetHeaderTimestamps will return timestamps as seconds and milliseconds based on supernova round activation
func GetHeaderTimestamps(
header data.HeaderHandler,
enableEpochsHandler EnableEpochsHandler,
) (uint64, uint64, error) {
if check.IfNil(header) {
return 0, 0, ErrNilHeaderHandler
}
if check.IfNil(enableEpochsHandler) {
return 0, 0, errors.ErrNilEnableEpochsHandler
}
headerTimestamp := header.GetTimeStamp()
timestampSec := headerTimestamp
timestampMs := headerTimestamp
if !enableEpochsHandler.IsFlagEnabledInEpoch(SupernovaFlag, header.GetEpoch()) {
timestampMs = ConvertTimeStampSecToMs(headerTimestamp)
return timestampSec, timestampMs, nil
}
// reduce block timestamp (which now comes as milliseconds) to seconds to keep backwards compatibility
// from now on timestampMs will be used for milliseconds granularity
timestampSec = convertTimeStampMsToSec(headerTimestamp)
return timestampSec, timestampMs, nil
}
type EnableEpochsHandlerWithSet interface {
SetActivationRound(flag EnableRoundFlag, round uint64)
}
type ProcessConfigsHandlerWithSet interface {
SetActivationRound(round uint64, log logger.Logger)
}
type CommonConfigsHandlerWithSet interface {
SetActivationRound(round uint64, log logger.Logger)
}
var erh EnableEpochsHandlerWithSet
var eeh EnableEpochsHandler
var pch ProcessConfigsHandlerWithSet
var cch CommonConfigsHandlerWithSet
var log = logger.GetOrCreate("common")
func SetEnableRoundsHandler(enableRoundsHandler EnableEpochsHandlerWithSet) {
erh = enableRoundsHandler
}
func SetProcessConfigsHandler(pcHandler ProcessConfigsHandler) {
pch = pcHandler
}
func SetCommonConfigsHandler(ccHandler CommonConfigsHandler) {
cch = ccHandler
}
func SetEnableEpochsHandler(enableEpochsHandler EnableEpochsHandler) {
eeh = enableEpochsHandler
}
func SetSuperNovaActivationRound(epoch uint32, round uint64) {
isEnabled := eeh.GetActivationEpoch(SupernovaFlag) == epoch && eeh.IsFlagEnabledInEpoch(SupernovaFlag, epoch)
log.Info("SetSuperNovaActivationRound", "currentRound", round, "activationRound", round+20, "epoch", epoch, "is enabled in current round", isEnabled)
if isEnabled {
supernovaRound := round + 20
erh.SetActivationRound(SupernovaRoundFlag, supernovaRound)
pch.SetActivationRound(supernovaRound, log)
cch.SetActivationRound(supernovaRound, log)
}
}