forked from ethereum/go-ethereum
-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathconfig_xdpos.go
More file actions
770 lines (695 loc) · 27.4 KB
/
Copy pathconfig_xdpos.go
File metadata and controls
770 lines (695 loc) · 27.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
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package params
// This file owns the XDPoS-side missing-field semantics that backfill relies
// on. UnmarshalJSON records which XDPoS, V2, V2Config, and ExpTimeoutConfig
// keys were present so BackfillMissingFieldsFrom can copy only omitted nested
// fields from a source config into the destination while preserving explicit
// zero and null values; CloneForBackfill is the fallback for programmatic
// configs that need inferred presence before that copy. The legacy
// BackfillCustomMigratedFieldsFrom path reaches into this tree only for the
// historical MaxMasternodesV2 migration and does not hydrate the broader XDPoS
// schedule.
import (
"cmp"
"encoding/json"
"fmt"
"maps"
"math/big"
"slices"
"strings"
"sync"
"github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/log"
)
// XDPoSConfig is the consensus engine configs for delegated-proof-of-stake based sealing.
type XDPoSConfig struct {
Period uint64 `json:"period"` // Number of seconds between blocks to enforce
Epoch uint64 `json:"epoch"` // Epoch length to reset votes and checkpoint
Reward uint64 `json:"reward"` // Block reward - unit Ether
RewardCheckpoint uint64 `json:"rewardCheckpoint"` // Checkpoint block for calculate rewards.
Gap uint64 `json:"gap"` // Gap time preparing for the next epoch
FoundationWalletAddr common.Address `json:"foundationWalletAddr"` // Foundation Address Wallet
MaxMasternodesV2 int `json:"maxMasternodesV2"` // Last v1 masternodes after TIPIncrease
SkipV1Validation bool //Skip Block Validation for testing purpose, V1 consensus only
V2 *V2 `json:"v2"`
json jsonFieldPresence `json:"-"`
}
// UnmarshalJSON supports both the current and legacy typo-ed JSON key for
// foundation wallet address to keep old on-disk chain configs compatible.
func (c *XDPoSConfig) UnmarshalJSON(data []byte) error {
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
type xdpJSON struct {
Period uint64 `json:"period"`
Epoch uint64 `json:"epoch"`
Reward uint64 `json:"reward"`
RewardCheckpoint uint64 `json:"rewardCheckpoint"`
Gap uint64 `json:"gap"`
MaxMasternodesV2 int `json:"maxMasternodesV2"`
FoundationWalletAddr common.Address `json:"foundationWalletAddr"`
LegacyFoudationWalletAddr common.Address `json:"foudationWalletAddr"`
SkipV1Validation bool `json:"SkipV1Validation"`
V2 *V2 `json:"v2"`
}
var decoded xdpJSON
if err := json.Unmarshal(data, &decoded); err != nil {
return err
}
c.Period = decoded.Period
c.Epoch = decoded.Epoch
c.Reward = decoded.Reward
c.RewardCheckpoint = decoded.RewardCheckpoint
c.Gap = decoded.Gap
c.MaxMasternodesV2 = decoded.MaxMasternodesV2
c.FoundationWalletAddr = decoded.FoundationWalletAddr
if c.FoundationWalletAddr.IsZero() && !decoded.LegacyFoudationWalletAddr.IsZero() {
c.FoundationWalletAddr = decoded.LegacyFoudationWalletAddr
}
c.SkipV1Validation = decoded.SkipV1Validation
c.V2 = decoded.V2
c.json.capture(raw)
return nil
}
// V2 stores the round-indexed XDPoS v2 runtime configs.
//
// BuildConfigIndex is the freeze point for AllConfigs. Callers must finish
// populating AllConfigs before calling BuildConfigIndex and before exposing v2
// for concurrent use. After BuildConfigIndex returns, AllConfigs, its map keys,
// and the pointed *V2Config values are treated as immutable and must not be
// mutated, replaced, added, or deleted.
//
// The lock protects read/write access to CurrentConfig and configIndex, plus
// map traversal of AllConfigs. The only allowed concurrent write after
// BuildConfigIndex is swapping CurrentConfig to point at one of the prebuilt
// immutable entries, and that pointer replacement must hold v2.lock with Lock.
// Read APIs such as Clone, GetCurrentConfig and Config take the read lock and
// return clones so callers cannot mutate shared state. WithReadOnlySnapshot
// must likewise hand out a deep-copy snapshot rather than shared internal
// pointers, maps, or slices.
type V2 struct {
lock sync.RWMutex // Protects CurrentConfig, configIndex, and AllConfigs traversal
SwitchEpoch uint64 `json:"switchEpoch"`
SwitchBlock *big.Int `json:"switchBlock"`
CurrentConfig *V2Config `json:"config"`
AllConfigs map[uint64]*V2Config `json:"allConfigs"`
configIndex []uint64 // list of switch block of configs
json jsonFieldPresence `json:"-"`
}
type V2Config struct {
MaxMasternodes int `json:"maxMasternodes"` // v2 max masternodes
MaxProtectorNodes int `json:"maxProtectorNodes"` // v2 max ProtectorNodes
MaxObverserNodes int `json:"maxObserverNodes"` // v2 max ObserverNodes
SwitchRound uint64 `json:"switchRound"` // v1 to v2 switch block number
MinePeriod int `json:"minePeriod"` // Miner mine period to mine a block
TimeoutSyncThreshold int `json:"timeoutSyncThreshold"` // send syncInfo after number of timeout
TimeoutPeriod int `json:"timeoutPeriod"` // Duration in ms
CertThreshold float64 `json:"certificateThreshold"` // Necessary number of messages from master nodes to form a certificate
MasternodeReward float64 `json:"masternodeReward"` // Block reward per master node (core validator) - unit Ether
ProtectorReward float64 `json:"protectorReward"` // Block reward per protector - unit Ether
ObserverReward float64 `json:"observerReward"` // Block reward per observer - unit Ether
MinimumMinerBlockPerEpoch int `json:"minimumMinerBlockPerEpoch"` // Minimum block per epoch for a miner to not be penalized
LimitPenaltyEpoch int `json:"limitPenaltyEpoch"` // Epochs in a row that a penalty node needs to be penalized
MinimumSigningTx int `json:"minimumSigningTx"` // Signing txs that a node needs to produce to get out of penalty, after `LimitPenaltyEpoch`
ExpTimeoutConfig ExpTimeoutConfig `json:"expTimeoutConfig"`
json jsonFieldPresence `json:"-"`
}
type ExpTimeoutConfig struct {
Base float64 `json:"base"` // base in base^exponent
MaxExponent uint8 `json:"maxExponent"` // max exponent in base^exponent
json jsonFieldPresence `json:"-"`
}
// UnmarshalJSON captures raw key presence for later v2 backfill decisions.
// It supports both "switchEpoch" and legacy "SwitchEpoch" JSON keys for compatibility.
func (v2 *V2) UnmarshalJSON(data []byte) error {
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
type v2Alias struct {
SwitchEpoch uint64 `json:"switchEpoch"`
LegacySwitchEpoch uint64 `json:"SwitchEpoch"`
SwitchBlock *big.Int `json:"switchBlock"`
CurrentConfig *V2Config `json:"config"`
AllConfigs map[uint64]*V2Config `json:"allConfigs"`
configIndex []uint64 // not from JSON, but for completeness
}
var decoded v2Alias
if err := json.Unmarshal(data, &decoded); err != nil {
return err
}
// Prefer new key, fallback to legacy if zero
v2.SwitchEpoch = decoded.SwitchEpoch
if v2.SwitchEpoch == 0 && decoded.LegacySwitchEpoch != 0 {
v2.SwitchEpoch = decoded.LegacySwitchEpoch
}
v2.SwitchBlock = decoded.SwitchBlock
v2.CurrentConfig = decoded.CurrentConfig
v2.AllConfigs = decoded.AllConfigs
v2.configIndex = decoded.configIndex
v2.json.capture(raw)
return nil
}
// UnmarshalJSON captures raw key presence for later v2 config backfill decisions.
func (c *V2Config) UnmarshalJSON(data []byte) error {
type v2ConfigAlias V2Config
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
var decoded v2ConfigAlias
if err := json.Unmarshal(data, &decoded); err != nil {
return err
}
*c = V2Config(decoded)
c.json.capture(raw)
return nil
}
// UnmarshalJSON captures raw key presence for later timeout backfill decisions.
func (c *ExpTimeoutConfig) UnmarshalJSON(data []byte) error {
type expTimeoutConfigAlias ExpTimeoutConfig
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
var decoded expTimeoutConfigAlias
if err := json.Unmarshal(data, &decoded); err != nil {
return err
}
*c = ExpTimeoutConfig(decoded)
c.json.capture(raw)
return nil
}
// Clone returns an independent copy of the v2 config.
func (c *V2Config) Clone() *V2Config {
if c == nil {
return nil
}
clone := *c
clone.ExpTimeoutConfig.json = c.ExpTimeoutConfig.json.clone()
clone.json = c.json.clone()
return &clone
}
// cloneWithInferredFieldPresence marks only non-zero ExpTimeoutConfig fields as
// explicitly present.
func (c *ExpTimeoutConfig) cloneWithInferredFieldPresence() *ExpTimeoutConfig {
if c == nil {
return nil
}
clone := *c
clone.json.startInferredTracking()
if clone.Base != 0 {
clone.json.mark("base")
}
if clone.MaxExponent != 0 {
clone.json.mark("maxExponent")
}
return &clone
}
// cloneWithInferredFieldPresence marks only non-zero V2Config fields as
// explicitly present so partial programmatic configs can still inherit
// defaults during backfill.
func (c *V2Config) cloneWithInferredFieldPresence() *V2Config {
if c == nil {
return nil
}
clone := c.Clone()
clone.json.startInferredTracking()
intFields := []struct {
key string
val int
}{
{"maxMasternodes", clone.MaxMasternodes},
{"maxProtectorNodes", clone.MaxProtectorNodes},
{"maxObserverNodes", clone.MaxObverserNodes},
{"minePeriod", clone.MinePeriod},
{"timeoutSyncThreshold", clone.TimeoutSyncThreshold},
{"timeoutPeriod", clone.TimeoutPeriod},
{"minimumMinerBlockPerEpoch", clone.MinimumMinerBlockPerEpoch},
{"limitPenaltyEpoch", clone.LimitPenaltyEpoch},
{"minimumSigningTx", clone.MinimumSigningTx},
}
for _, field := range intFields {
if field.val != 0 {
clone.json.mark(field.key)
}
}
if clone.SwitchRound != 0 {
clone.json.mark("switchRound")
}
floatFields := []struct {
key string
val float64
}{
{"certificateThreshold", clone.CertThreshold},
{"masternodeReward", clone.MasternodeReward},
{"protectorReward", clone.ProtectorReward},
{"observerReward", clone.ObserverReward},
}
for _, field := range floatFields {
if field.val != 0 {
clone.json.mark(field.key)
}
}
clone.ExpTimeoutConfig = *clone.ExpTimeoutConfig.cloneWithInferredFieldPresence()
if len(clone.ExpTimeoutConfig.json.keys) > 0 {
clone.json.mark("expTimeoutConfig")
}
return clone
}
// cloneWithInferredFieldPresence marks only populated V2 fields as explicitly
// present, which keeps absent fields eligible for later default backfill.
func (v2 *V2) cloneWithInferredFieldPresence() *V2 {
if v2 == nil {
return nil
}
clone := v2.Clone()
clone.json.startInferredTracking()
if clone.SwitchEpoch != 0 {
clone.json.mark("switchEpoch")
}
if clone.SwitchBlock != nil {
clone.json.mark("switchBlock")
}
if clone.CurrentConfig != nil {
clone.json.mark("config")
clone.CurrentConfig = clone.CurrentConfig.cloneWithInferredFieldPresence()
}
if len(clone.AllConfigs) > 0 {
clone.json.mark("allConfigs")
for key, cfg := range clone.AllConfigs {
clone.AllConfigs[key] = cfg.cloneWithInferredFieldPresence()
}
}
return clone
}
// Clone returns a read-locked deep copy of the V2 state.
// It clones the current config, indexed configs and key order so callers can
// safely mutate the returned copy without affecting the shared runtime state.
func (v2 *V2) Clone() *V2 {
if v2 == nil {
return nil
}
v2.lock.RLock()
defer v2.lock.RUnlock()
clone := &V2{
SwitchEpoch: v2.SwitchEpoch,
SwitchBlock: common.CloneBigInt(v2.SwitchBlock),
}
clone.json = v2.json.clone()
if v2.CurrentConfig != nil {
clone.CurrentConfig = v2.CurrentConfig.Clone()
}
if v2.AllConfigs != nil {
clone.AllConfigs = make(map[uint64]*V2Config, len(v2.AllConfigs))
for key, cfg := range v2.AllConfigs {
clone.AllConfigs[key] = cfg.Clone()
}
}
if v2.configIndex != nil {
clone.configIndex = append([]uint64(nil), v2.configIndex...)
}
return clone
}
// Clone returns an independent copy of the XDPoS config.
func (c *XDPoSConfig) Clone() *XDPoSConfig {
if c == nil {
return nil
}
clone := *c
clone.V2 = c.V2.Clone()
clone.json = c.json.clone()
return &clone
}
func XDPoSConfigEqual(a, b *XDPoSConfig) bool {
if a == nil || b == nil {
if a != b {
log.Warn("[XDPoSConfigEqual] One of the configs is nil", "a", a, "b", b)
return false
}
return true
}
if a.Period != b.Period {
log.Warn("[XDPoSConfigEqual] Period mismatch", "a.Period", a.Period, "b.Period", b.Period)
return false
}
if a.Epoch != b.Epoch {
log.Warn("[XDPoSConfigEqual] Epoch mismatch", "a.Epoch", a.Epoch, "b.Epoch", b.Epoch)
return false
}
if a.Reward != b.Reward {
log.Warn("[XDPoSConfigEqual] Reward mismatch", "a.Reward", a.Reward, "b.Reward", b.Reward)
return false
}
if a.RewardCheckpoint != b.RewardCheckpoint {
log.Warn("[XDPoSConfigEqual] RewardCheckpoint mismatch", "a.RewardCheckpoint", a.RewardCheckpoint, "b.RewardCheckpoint", b.RewardCheckpoint)
return false
}
if a.Gap != b.Gap {
log.Warn("[XDPoSConfigEqual] Gap mismatch", "a.Gap", a.Gap, "b.Gap", b.Gap)
return false
}
if a.FoundationWalletAddr != b.FoundationWalletAddr {
log.Warn("[XDPoSConfigEqual] FoundationWalletAddr mismatch", "a.FoundationWalletAddr", a.FoundationWalletAddr.Hex(), "b.FoundationWalletAddr", b.FoundationWalletAddr.Hex())
return false
}
if a.MaxMasternodesV2 != b.MaxMasternodesV2 {
log.Warn("[XDPoSConfigEqual] MaxMasternodesV2 mismatch", "a.MaxMasternodesV2", a.MaxMasternodesV2, "b.MaxMasternodesV2", b.MaxMasternodesV2)
return false
}
if a.SkipV1Validation != b.SkipV1Validation {
log.Warn("[XDPoSConfigEqual] SkipV1Validation mismatch", "a.SkipV1Validation", a.SkipV1Validation, "b.SkipV1Validation", b.SkipV1Validation)
return false
}
return V2Equal(a.V2, b.V2)
}
func V2Equal(a, b *V2) bool {
if a == nil || b == nil {
if a != b {
log.Warn("[V2Equal] One of the configs is nil", "a", a, "b", b)
return false
}
return true
}
left := snapshotV2ReadOnly(a)
right := snapshotV2ReadOnly(b)
if left.switchEpoch != right.switchEpoch {
log.Warn("[V2Equal] SwitchEpoch mismatch", "a.SwitchEpoch", left.switchEpoch, "b.SwitchEpoch", right.switchEpoch)
return false
}
if !configNumEqual(left.switchBlock, right.switchBlock) {
log.Warn("[V2Equal] SwitchBlock mismatch", "a.SwitchBlock", left.switchBlock, "b.SwitchBlock", right.switchBlock)
return false
}
// Only check configs in both of AllConfigs
for k1, cfg1 := range left.allConfigs {
if cfg2, ok := right.allConfigs[k1]; ok {
if !V2ConfigEqual(cfg1, cfg2) {
return false
}
}
}
return true
}
func V2ConfigEqual(a, b *V2Config) bool {
if a == nil || b == nil {
if a != b {
log.Warn("[V2ConfigEqual] One of the configs is nil", "a", a, "b", b)
return false
}
return true
}
if a.MaxMasternodes != b.MaxMasternodes {
log.Warn("[V2ConfigEqual] MaxMasternodes mismatch", "a.MaxMasternodes", a.MaxMasternodes, "b.MaxMasternodes", b.MaxMasternodes)
return false
}
if a.SwitchRound != b.SwitchRound {
log.Warn("[V2ConfigEqual] SwitchRound mismatch", "a.SwitchRound", a.SwitchRound, "b.SwitchRound", b.SwitchRound)
return false
}
if a.CertThreshold != b.CertThreshold {
log.Warn("[V2ConfigEqual] CertThreshold mismatch", "a.CertThreshold", a.CertThreshold, "b.CertThreshold", b.CertThreshold)
return false
}
return true
}
func sameV2RuntimeConfig(a, b *V2Config) bool {
if a == nil || b == nil {
return a == b
}
return a.MaxMasternodes == b.MaxMasternodes &&
a.MaxProtectorNodes == b.MaxProtectorNodes &&
a.MaxObverserNodes == b.MaxObverserNodes &&
a.SwitchRound == b.SwitchRound &&
a.MinePeriod == b.MinePeriod &&
a.TimeoutSyncThreshold == b.TimeoutSyncThreshold &&
a.TimeoutPeriod == b.TimeoutPeriod &&
a.CertThreshold == b.CertThreshold &&
a.MasternodeReward == b.MasternodeReward &&
a.ProtectorReward == b.ProtectorReward &&
a.ObserverReward == b.ObserverReward &&
a.MinimumMinerBlockPerEpoch == b.MinimumMinerBlockPerEpoch &&
a.LimitPenaltyEpoch == b.LimitPenaltyEpoch &&
a.MinimumSigningTx == b.MinimumSigningTx &&
a.ExpTimeoutConfig.Base == b.ExpTimeoutConfig.Base &&
a.ExpTimeoutConfig.MaxExponent == b.ExpTimeoutConfig.MaxExponent
}
func (c *XDPoSConfig) String() string {
if c == nil {
return "XDPoSConfig: <nil>"
}
return fmt.Sprintf("XDPoSConfig{Period: %v, Epoch: %v, Reward: %v, RewardCheckpoint: %v, Gap: %v, MaxMasternodesV2: %v, FoundationWalletAddr: %v, SkipV1Validation: %v, V2: %s}", c.Period, c.Epoch, c.Reward, c.RewardCheckpoint, c.Gap, c.MaxMasternodesV2, c.FoundationWalletAddr.String0x(), c.SkipV1Validation, c.V2.String())
}
// Description returns a human-readable description of XDPoSConfig
// NOTE: don't append "\n" to end
func (c *XDPoSConfig) Description(indent int) string {
if c == nil {
return "XDPoS: <nil>"
}
banner := "XDPoS\n"
prefix := strings.Repeat(" ", indent)
banner += fmt.Sprintf("%s- Period: %v\n", prefix, c.Period)
banner += fmt.Sprintf("%s- Epoch: %v\n", prefix, c.Epoch)
banner += fmt.Sprintf("%s- Reward: %v\n", prefix, c.Reward)
banner += fmt.Sprintf("%s- RewardCheckpoint: %v\n", prefix, c.RewardCheckpoint)
banner += fmt.Sprintf("%s- Gap: %v\n", prefix, c.Gap)
banner += fmt.Sprintf("%s- MaxMasternodesV2: %v\n", prefix, c.MaxMasternodesV2)
banner += fmt.Sprintf("%s- FoundationWalletAddr: %v\n", prefix, c.FoundationWalletAddr.Hex())
banner += fmt.Sprintf("%s- SkipV1Validation: %v\n", prefix, c.SkipV1Validation)
banner += fmt.Sprintf("%s- %s", prefix, c.V2.Description(indent+2))
return banner
}
func (v2 *V2) String() string {
if v2 == nil {
return "V2: <nil>"
}
snapshot := snapshotV2ReadOnly(v2)
return fmt.Sprintf("V2{SwitchEpoch: %v, SwitchBlock: %v, %s}", snapshot.switchEpoch, snapshot.switchBlock, snapshot.currentConfig.String())
}
type stableLogConfigEntry struct {
Round uint64 `json:"round"`
Config *V2Config `json:"config"`
}
type stableLogView struct {
SwitchEpoch uint64 `json:"switchEpoch"`
SwitchBlock string `json:"switchBlock"`
CurrentConfig *V2Config `json:"currentConfig"`
AllConfigs []stableLogConfigEntry `json:"allConfigs"`
ConfigIndex []uint64 `json:"configIndex"`
}
// StableLogValue returns a full, deterministic structured value for startup
// logs. Callers can pass the returned object directly as a field value to
// avoid JSON string escaping in terminal log output.
func (v2 *V2) StableLogValue() stableLogView {
if v2 == nil {
return stableLogView{}
}
snapshot := snapshotV2ReadOnly(v2)
keys := slices.Collect(maps.Keys(snapshot.allConfigs))
slices.Sort(keys)
allConfigs := make([]stableLogConfigEntry, 0, len(keys))
for _, round := range keys {
allConfigs = append(allConfigs, stableLogConfigEntry{
Round: round,
Config: snapshot.allConfigs[round].Clone(),
})
}
var switchBlock string
if snapshot.switchBlock != nil {
switchBlock = snapshot.switchBlock.String()
}
return stableLogView{
SwitchEpoch: snapshot.switchEpoch,
SwitchBlock: switchBlock,
CurrentConfig: snapshot.currentConfig.Clone(),
AllConfigs: allConfigs,
ConfigIndex: append([]uint64(nil), snapshot.configIndex...),
}
}
// Description returns a human-readable description of V2
// NOTE: don't append "\n" to end
func (v2 *V2) Description(indent int) string {
if v2 == nil {
return "V2: <nil>"
}
snapshot := snapshotV2ReadOnly(v2)
banner := "V2:\n"
prefix := strings.Repeat(" ", indent)
banner += fmt.Sprintf("%s- SwitchEpoch: %v\n", prefix, snapshot.switchEpoch)
banner += fmt.Sprintf("%s- SwitchBlock: %v\n", prefix, snapshot.switchBlock)
banner += fmt.Sprintf("%s- %s", prefix, snapshot.currentConfig.Description("CurrentConfig", indent+2))
return banner
}
func (c *V2Config) String() string {
if c == nil {
return "V2Config: <nil>"
}
return fmt.Sprintf("V2{MaxMasternodes: %v, MaxProtectorNodes: %v, MaxObverserNodes: %v, SwitchRound: %v, MinePeriod: %v, TimeoutSyncThreshold: %v, TimeoutPeriod: %v, CertThreshold: %v, MasternodeReward: %v, ProtectorReward: %v, ObserverReward: %v, MinimumMinerBlockPerEpoch: %v, LimitPenaltyEpoch: %v, MinimumSigningTx: %v, %s}", c.MaxMasternodes, c.MaxProtectorNodes, c.MaxObverserNodes, c.SwitchRound, c.MinePeriod, c.TimeoutSyncThreshold, c.TimeoutPeriod, c.CertThreshold, c.MasternodeReward, c.ProtectorReward, c.ObserverReward, c.MinimumMinerBlockPerEpoch, c.LimitPenaltyEpoch, c.MinimumSigningTx, c.ExpTimeoutConfig.String())
}
// Description returns a human-readable description of V2Config
// NOTE: don't append "\n" to end
func (c *V2Config) Description(name string, indent int) string {
if c == nil {
return name + ": <nil>"
}
banner := name + ":\n"
prefix := strings.Repeat(" ", indent)
banner += fmt.Sprintf("%s- MaxMasternodes: %v\n", prefix, c.MaxMasternodes)
banner += fmt.Sprintf("%s- SwitchRound: %v\n", prefix, c.SwitchRound)
banner += fmt.Sprintf("%s- MinePeriod: %v\n", prefix, c.MinePeriod)
banner += fmt.Sprintf("%s- TimeoutSyncThreshold: %v\n", prefix, c.TimeoutSyncThreshold)
banner += fmt.Sprintf("%s- TimeoutPeriod: %v\n", prefix, c.TimeoutPeriod)
banner += fmt.Sprintf("%s- CertThreshold: %v\n", prefix, c.CertThreshold)
banner += fmt.Sprintf("%s- MasternodeReward: %v\n", prefix, c.MasternodeReward)
banner += fmt.Sprintf("%s- ProtectorReward: %v\n", prefix, c.ProtectorReward)
banner += fmt.Sprintf("%s- ObserverReward: %v\n", prefix, c.ObserverReward)
banner += fmt.Sprintf("%s- MinimumMinerBlockPerEpoch: %v\n", prefix, c.MinimumMinerBlockPerEpoch)
banner += fmt.Sprintf("%s- LimitPenaltyEpoch: %v\n", prefix, c.LimitPenaltyEpoch)
banner += fmt.Sprintf("%s- MinimumSigningTx: %v\n", prefix, c.MinimumSigningTx)
banner += fmt.Sprintf("%s- ExpTimeoutBase: %v\n", prefix, c.ExpTimeoutConfig.Base)
banner += fmt.Sprintf("%s- ExpTimeoutMaxExponent: %v", prefix, c.ExpTimeoutConfig.MaxExponent)
return banner
}
func (c ExpTimeoutConfig) String() string {
return fmt.Sprintf("ExpTimeoutConfig{Base: %v, MaxExponent: %v}", c.Base, c.MaxExponent)
}
func (c *XDPoSConfig) BlockConsensusVersion(num *big.Int) string {
if c.V2 != nil && c.V2.SwitchBlock != nil && num.Cmp(c.V2.SwitchBlock) > 0 {
return ConsensusEngineVersion2
}
return ConsensusEngineVersion1
}
// UpdateConfig repoints CurrentConfig to the indexed config that applies at
// round. It assumes BuildConfigIndex has already been called and that
// AllConfigs entries are immutable once v2 is exposed to concurrent readers.
func (v2 *V2) UpdateConfig(round uint64) {
v2.lock.Lock()
defer v2.lock.Unlock()
var index uint64
//find the right config
for i := range v2.configIndex {
if v2.configIndex[i] <= round {
index = v2.configIndex[i]
break
}
}
// update to current config
log.Info("[updateV2Config] Update config", "index", index, "round", round, "SwitchRound", v2.AllConfigs[index].SwitchRound)
v2.CurrentConfig = v2.AllConfigs[index]
}
// GetCurrentConfig returns a deep copy of the current config. It assumes v2 is
// not nil and relies on AllConfigs entries remaining immutable after
// BuildConfigIndex, apart from CurrentConfig being repointed under UpdateConfig.
func (v2 *V2) GetCurrentConfig() *V2Config {
v2.lock.RLock()
defer v2.lock.RUnlock()
if v2.CurrentConfig == nil {
return nil
}
// Return a clone so callers cannot mutate shared nested metadata maps.
return v2.CurrentConfig.Clone()
}
// Config returns a deep copy of the v2 config that applies at the given round.
// It relies on AllConfigs entries being immutable once BuildConfigIndex has
// finished, apart from CurrentConfig being repointed under UpdateConfig.
func (v2 *V2) Config(round uint64) *V2Config {
v2.lock.RLock()
defer v2.lock.RUnlock()
configRound := round
var index uint64
//find the right config
for i := range v2.configIndex {
if v2.configIndex[i] <= configRound {
index = v2.configIndex[i]
break
}
}
// Return a clone so callers cannot mutate shared nested metadata maps.
return v2.AllConfigs[index].Clone()
}
// BuildConfigIndex snapshots the current AllConfigs keys into descending round
// order for later lookups. Callers are expected to finish populating AllConfigs
// before exposing v2 for concurrent use; after this point, the map entries and
// pointed *V2Config values are treated as immutable.
func (v2 *V2) BuildConfigIndex() {
v2.lock.Lock()
defer v2.lock.Unlock()
list := slices.Collect(maps.Keys(v2.AllConfigs))
// Make it descending order
slices.SortFunc(list, func(a, b uint64) int {
return cmp.Compare(b, a)
})
log.Info("[BuildConfigIndex] config list", "list", list)
v2.configIndex = list
}
// ConfigIndex returns a copy of the cached descending config-index list built
// from AllConfigs.
func (v2 *V2) ConfigIndex() []uint64 {
v2.lock.RLock()
defer v2.lock.RUnlock()
if v2.configIndex == nil {
return nil
}
return append([]uint64(nil), v2.configIndex...)
}
// WithReadOnlySnapshot invokes fn with a detached deep copy of the V2 state.
// The callback receives stable snapshot data for read-only workflows such as
// hashing without exposing shared internal pointers, maps, or slices.
func (v2 *V2) WithReadOnlySnapshot(fn func(switchEpoch uint64, switchBlock *big.Int, currentConfig *V2Config, allConfigs map[uint64]*V2Config, configIndex []uint64)) {
if v2 == nil {
fn(0, nil, nil, nil, nil)
return
}
s := v2.Clone()
fn(s.SwitchEpoch, s.SwitchBlock, s.CurrentConfig, s.AllConfigs, s.configIndex)
}
// WithReadOnlyView invokes fn while holding the read lock and exposes the
// current V2 state without cloning. Callers must treat the provided pointers,
// maps, and slices as ephemeral read-only views and must not retain them.
func (v2 *V2) WithReadOnlyView(fn func(switchEpoch uint64, switchBlock *big.Int, currentConfig *V2Config, allConfigs map[uint64]*V2Config, configIndex []uint64)) {
if v2 == nil {
fn(0, nil, nil, nil, nil)
return
}
v2.lock.RLock()
defer v2.lock.RUnlock()
fn(v2.SwitchEpoch, v2.SwitchBlock, v2.CurrentConfig, v2.AllConfigs, v2.configIndex)
}
type v2ReadOnlySnapshot struct {
switchEpoch uint64
switchBlock *big.Int
currentConfig *V2Config
allConfigs map[uint64]*V2Config
configIndex []uint64
}
func snapshotV2ReadOnly(v2 *V2) v2ReadOnlySnapshot {
if v2 == nil {
return v2ReadOnlySnapshot{}
}
var snapshot v2ReadOnlySnapshot
v2.WithReadOnlySnapshot(func(switchEpoch uint64, switchBlock *big.Int, currentConfig *V2Config, allConfigs map[uint64]*V2Config, configIndex []uint64) {
snapshot = v2ReadOnlySnapshot{
switchEpoch: switchEpoch,
switchBlock: switchBlock,
currentConfig: currentConfig,
allConfigs: allConfigs,
configIndex: configIndex,
}
})
return snapshot
}