-
Notifications
You must be signed in to change notification settings - Fork 228
Expand file tree
/
Copy pathcommon.go
More file actions
733 lines (611 loc) · 22.5 KB
/
common.go
File metadata and controls
733 lines (611 loc) · 22.5 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
package common
import (
"encoding/hex"
"encoding/json"
"fmt"
"math/big"
"math/bits"
"os"
"reflect"
"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-core-go/data/block"
logger "github.com/multiversx/mx-chain-logger-go"
"github.com/multiversx/mx-chain-go/config"
"github.com/multiversx/mx-chain-go/errors"
)
const (
keySeparator = "-"
expectedKeyLen = 2
hashIndex = 0
shardIndex = 1
nonceIndex = 0
)
type executionResultHandler interface {
GetMiniBlockHeadersHandlers() []data.MiniBlockHeaderHandler
}
type chainParametersHandler interface {
CurrentChainParameters() config.ChainParametersByEpochConfig
ChainParametersForEpoch(epoch uint32) (config.ChainParametersByEpochConfig, error)
IsInterfaceNil() bool
}
// PrepareLogEventsKey will prepare logs key for cacher
func PrepareLogEventsKey(headerHash []byte) []byte {
return append([]byte("logs"), headerHash...)
}
// PrepareOrderedTxHashesKey will prepare transactions execution order key for cacher
func PrepareOrderedTxHashesKey(headerHash []byte) []byte {
return append([]byte("execution"), headerHash...)
}
// PrepareHeaderGasDataKey will prepare header gas data key for cacher
func PrepareHeaderGasDataKey(headerHash []byte) []byte {
return append([]byte("gas"), headerHash...)
}
// PrepareUnexecutableTxHashesKey will prepare unexecutable transaction hashes key for cacher
func PrepareUnexecutableTxHashesKey(headerHash []byte) []byte {
return append([]byte("unexecutable"), headerHash...)
}
// 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
}
// IsAsyncExecutionEnabledForEpochAndRound returns true if both Supernova epochs and Supernova rounds are enabled for the provided epoch and round
func IsAsyncExecutionEnabledForEpochAndRound(
enableEpochsHandler EnableEpochsHandler,
enableRoundsHandler EnableRoundsHandler,
epoch uint32,
round uint64,
) bool {
return enableEpochsHandler.IsFlagEnabledInEpoch(SupernovaFlag, epoch) &&
enableRoundsHandler.IsFlagEnabledInRound(SupernovaRoundFlag, round)
}
// IsAsyncExecutionEnabled returns true if both Supernova epochs and Supernova rounds are enabled
func IsAsyncExecutionEnabled(enableEpochsHandler EnableEpochsHandler, enableRoundsHandler EnableRoundsHandler) bool {
return enableEpochsHandler.IsFlagEnabled(SupernovaFlag) &&
enableRoundsHandler.IsFlagEnabled(SupernovaRoundFlag)
}
// 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
}
// PrettifyStruct returns a JSON string representation of a struct, converting byte slices to hex
// and formatting big number values into readable strings. Useful for logging or debugging.
func PrettifyStruct(x interface{}) (string, error) {
if x == nil {
return "nil", nil
}
val := reflect.ValueOf(x)
result := prettifyValue(val, val.Type())
jsonBytes, err := json.Marshal(result)
if err != nil {
return "", err
}
return string(jsonBytes), nil
}
// prettifyValue recursively converts a reflect.Value into a representation suitable for JSON serialization,
// handling pointers, slices, structs, and special formatting for big numeric types.
func prettifyValue(val reflect.Value, typ reflect.Type) interface{} {
if bigValue, isBig := prettifyBigNumbers(val); isBig {
return bigValue
}
if val.Kind() == reflect.Ptr {
if val.IsNil() {
return nil
}
val = val.Elem()
typ = val.Type()
}
switch val.Kind() {
case reflect.Struct:
return prettifyStructFields(val, typ)
case reflect.Slice, reflect.Array:
return prettifySliceOrArray(val)
default:
return val.Interface()
}
}
func prettifyStructFields(val reflect.Value, typ reflect.Type) map[string]interface{} {
out := make(map[string]interface{})
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
fieldType := typ.Field(i)
name := fieldType.Tag.Get("json")
if name == "" {
name = fieldType.Name
} else {
name = strings.Split(name, ",")[0]
}
if fieldType.PkgPath != "" {
out[name] = "<unexported>"
continue
}
if field.Kind() == reflect.Slice && field.Type() == reflect.TypeOf([]byte{}) {
out[name] = fmt.Sprintf("%x", field.Bytes())
} else {
out[name] = prettifyValue(field, field.Type())
}
}
return out
}
func prettifySliceOrArray(val reflect.Value) interface{} {
if val.Type().Elem().Kind() == reflect.Uint8 {
b := make([]byte, val.Len())
for i := 0; i < val.Len(); i++ {
b[i] = byte(val.Index(i).Uint())
}
return fmt.Sprintf("%x", b)
}
out := make([]interface{}, val.Len())
for i := 0; i < val.Len(); i++ {
out[i] = prettifyValue(val.Index(i), val.Index(i).Type())
}
return out
}
func prettifyBigNumbers(val reflect.Value) (string, bool) {
if val.CanInterface() {
switch v := val.Interface().(type) {
case *big.Int:
if v != nil {
return v.String(), true
}
case big.Int:
return v.String(), true
case *big.Float:
if v != nil {
return v.Text('g', -1), true
}
case big.Float:
return v.Text('g', -1), true
case *big.Rat:
if v != nil {
return v.RatString(), true
}
case big.Rat:
return v.RatString(), true
}
}
return "", false
}
// GetLastBaseExecutionResultHandler extracts the BaseExecutionResultHandler from the provided header, based on its type
func GetLastBaseExecutionResultHandler(header data.HeaderHandler) (data.BaseExecutionResultHandler, error) {
if check.IfNil(header) {
return nil, ErrNilHeaderHandler
}
lastExecResultsHandler := header.GetLastExecutionResultHandler()
return ExtractBaseExecutionResultHandler(lastExecResultsHandler)
}
// GetOrCreateLastExecutionResultForPrevHeader extracts base execution result from
// header if header v3. Otherwise, it will create last execution result based
// on the provided header
func GetOrCreateLastExecutionResultForPrevHeader(
prevHeader data.HeaderHandler,
prevHeaderHash []byte,
) (data.BaseExecutionResultHandler, error) {
if prevHeader.IsHeaderV3() {
return ExtractBaseExecutionResultHandler(prevHeader.GetLastExecutionResultHandler())
}
lastExecResult, err := CreateLastExecutionResultFromPrevHeader(prevHeader, prevHeaderHash)
if err != nil {
return nil, err
}
return ExtractBaseExecutionResultHandler(lastExecResult)
}
func isValidHeaderBeforeV3(header data.HeaderHandler) error {
_, isHeaderV2 := header.(*block.HeaderV2)
if isHeaderV2 {
return nil
}
_, isHeaderV1 := header.(*block.Header)
if !isHeaderV1 {
return ErrWrongTypeAssertion
}
return nil
}
// CreateLastExecutionResultFromPrevHeader creates a LastExecutionResultInfo object from the given previous header
func CreateLastExecutionResultFromPrevHeader(prevHeader data.HeaderHandler, prevHeaderHash []byte) (data.LastExecutionResultHandler, error) {
if check.IfNil(prevHeader) {
return nil, ErrNilHeaderHandler
}
if len(prevHeaderHash) == 0 {
return nil, ErrInvalidHeaderHash
}
if prevHeader.GetShardID() != core.MetachainShardId {
err := isValidHeaderBeforeV3(prevHeader)
if err != nil {
return nil, err
}
return &block.ExecutionResultInfo{
NotarizedInRound: prevHeader.GetRound(),
ExecutionResult: &block.BaseExecutionResult{
HeaderHash: prevHeaderHash,
HeaderNonce: prevHeader.GetNonce(),
HeaderRound: prevHeader.GetRound(),
HeaderEpoch: prevHeader.GetEpoch(),
RootHash: prevHeader.GetRootHash(),
GasUsed: 0, // we don't have this information in previous header
},
}, nil
}
prevMetaHeader, ok := prevHeader.(data.MetaHeaderHandler)
if !ok {
return nil, ErrWrongTypeAssertion
}
return &block.MetaExecutionResultInfo{
NotarizedInRound: prevHeader.GetRound(),
ExecutionResult: &block.BaseMetaExecutionResult{
BaseExecutionResult: &block.BaseExecutionResult{
HeaderHash: prevHeaderHash,
HeaderNonce: prevMetaHeader.GetNonce(),
HeaderRound: prevMetaHeader.GetRound(),
HeaderEpoch: prevMetaHeader.GetEpoch(),
RootHash: prevMetaHeader.GetRootHash(),
GasUsed: 0, // we don't have this information in previous header
},
ValidatorStatsRootHash: prevMetaHeader.GetValidatorStatsRootHash(),
AccumulatedFeesInEpoch: prevMetaHeader.GetAccumulatedFeesInEpoch(),
DevFeesInEpoch: prevMetaHeader.GetDevFeesInEpoch(),
},
}, nil
}
// ExtractBaseExecutionResultHandler extracts the base execution result handler from a last execution result handler
func ExtractBaseExecutionResultHandler(lastExecResultsHandler data.LastExecutionResultHandler) (data.BaseExecutionResultHandler, error) {
if check.IfNil(lastExecResultsHandler) {
log.Error("ExtractBaseExecutionResultHandler: nil exec")
return nil, ErrNilLastExecutionResultHandler
}
var baseExecutionResultsHandler data.BaseExecutionResultHandler
var ok bool
switch executionResultsHandlerType := lastExecResultsHandler.(type) {
case data.LastMetaExecutionResultHandler:
metaBaseExecutionResults := executionResultsHandlerType.GetExecutionResultHandler()
if check.IfNil(metaBaseExecutionResults) {
return nil, ErrNilBaseExecutionResult
}
baseExecutionResultsHandler, ok = metaBaseExecutionResults.(data.BaseExecutionResultHandler)
if !ok {
return nil, ErrWrongTypeAssertion
}
case data.LastShardExecutionResultHandler:
baseExecutionResultsHandler = executionResultsHandlerType.GetExecutionResultHandler()
default:
return nil, fmt.Errorf("%w: unsupported execution result handler type", ErrWrongTypeAssertion)
}
if check.IfNil(baseExecutionResultsHandler) {
return nil, ErrNilBaseExecutionResult
}
return baseExecutionResultsHandler, nil
}
// GetMiniBlocksHeaderHandlersFromExecResult returns miniblock handlers based on execution result
func GetMiniBlocksHeaderHandlersFromExecResult(
baseExecResult data.BaseExecutionResultHandler,
) ([]data.MiniBlockHeaderHandler, error) {
if check.IfNil(baseExecResult) {
return nil, ErrNilBaseExecutionResult
}
execResult, ok := baseExecResult.(executionResultHandler)
if !ok {
return nil, ErrWrongTypeAssertion
}
return execResult.GetMiniBlockHeadersHandlers(), nil
}
// GetLastExecutionResultNonce returns last execution result nonce if header v3 enabled, otherwise it returns provided header nonce
func GetLastExecutionResultNonce(
header data.HeaderHandler,
) uint64 {
nonce := header.GetNonce()
if !header.IsHeaderV3() {
return nonce
}
lastExecutionResult, err := GetLastBaseExecutionResultHandler(header)
if err != nil {
return nonce
}
return lastExecutionResult.GetHeaderNonce()
}
// GetFirstExecutionResultNonce returns first execution result nonce if header v3 enabled, otherwise it returns provided header nonce.
// For header v3, it returns first execution result if there are any, otherwise it returns last execution results on the header
func GetFirstExecutionResultNonce(
header data.HeaderHandler,
) uint64 {
nonce := header.GetNonce()
if !header.IsHeaderV3() {
return nonce
}
if len(header.GetExecutionResultsHandlers()) > 0 {
firstExecResult := header.GetExecutionResultsHandlers()[0]
return firstExecResult.GetHeaderNonce()
}
return GetLastExecutionResultNonce(header)
}
// GetMiniBlockHeadersFromExecResult returns mb headers from meta header if v3, otherwise, returns mini block headers
func GetMiniBlockHeadersFromExecResult(header data.HeaderHandler) ([]data.MiniBlockHeaderHandler, error) {
if !header.IsHeaderV3() {
return header.GetMiniBlockHeaderHandlers(), nil
}
mbHeaderHandlers := make([]data.MiniBlockHeaderHandler, 0)
for _, execResult := range header.GetExecutionResultsHandlers() {
mbHeaders, err := GetMiniBlocksHeaderHandlersFromExecResult(execResult)
if err != nil {
return nil, fmt.Errorf("%w in GetMiniBlockHeadersFromExecResult.GetMiniBlocksHeaderHandlersFromExecResult", err)
}
mbHeaderHandlers = append(mbHeaderHandlers, mbHeaders...)
}
return mbHeaderHandlers, nil
}
// GetFeePayer returns the address that pays the fee for this transaction.
// For relayed v3 transactions, the fee payer is the relayer; otherwise it is the sender.
func GetFeePayer(tx data.TransactionHandler) []byte {
if check.IfNil(tx) {
return nil
}
relayedTx, ok := tx.(data.RelayedTransactionHandler)
if ok && len(relayedTx.GetRelayerAddr()) > 0 {
return relayedTx.GetRelayerAddr()
}
return tx.GetSndAddr()
}
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)
}
type VersionsConfigWithSet interface {
SetActivationRound(round uint64, log logger.Logger)
}
type AntifloodConfigsHandlerWithSet interface {
SetActivationRound(round uint64, log logger.Logger)
}
var erh EnableEpochsHandlerWithSet
var eeh EnableEpochsHandler
var pch ProcessConfigsHandlerWithSet
var cch CommonConfigsHandlerWithSet
var vch VersionsConfigWithSet
var ach AntifloodConfigsHandlerWithSet
var mainConfigPath string
var roundConfigPath string
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 SetVersionsConfigHandler(versions *config.VersionsConfig) {
vch = versions
}
func SetAntifloodConfigsHandler(handler AntifloodConfigsHandler) {
ach = handler
}
// SetConfigPaths sets the file paths for the main config and round activation config files
func SetConfigPaths(mainPath, roundPath string) {
mainConfigPath = mainPath
roundConfigPath = roundPath
}
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)
vch.SetActivationRound(supernovaRound, log)
ach.SetActivationRound(supernovaRound, log)
persistSupernovaRoundToConfigs(supernovaRound)
}
}
func persistSupernovaRoundToConfigs(round uint64) {
roundStr := strconv.FormatUint(round, 10)
if mainConfigPath != "" {
patchFileRoundValues(mainConfigPath, roundStr, false)
}
if roundConfigPath != "" {
patchFileRoundValues(roundConfigPath, roundStr, true)
}
}
func patchFileRoundValues(filePath string, roundStr string, isRoundConfig bool) {
data, err := os.ReadFile(filePath)
if err != nil {
log.Warn("failed to read config file for round persistence", "path", filePath, "error", err)
return
}
original := string(data)
modified := original
if isRoundConfig {
modified = strings.ReplaceAll(modified, `Round = "99999999"`, `Round = "`+roundStr+`"`)
} else {
modified = strings.ReplaceAll(modified, "EnableRound = 99999999", "EnableRound = "+roundStr)
modified = strings.ReplaceAll(modified, "StartRound = 99999999", "StartRound = "+roundStr)
modified = strings.ReplaceAll(modified, "Round = 99999999", "Round = "+roundStr)
}
if modified == original {
log.Debug("no round placeholder found to replace", "path", filePath)
return
}
err = os.WriteFile(filePath, []byte(modified), 0644)
if err != nil {
log.Warn("failed to write config file for round persistence", "path", filePath, "error", err)
return
}
log.Info("persisted supernova round to config file", "path", filePath, "round", roundStr)
}