forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
state.go
2442 lines (2096 loc) · 68.2 KB
/
state.go
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package state
import (
"context"
"errors"
"fmt"
"math"
"sync"
"time"
"github.com/google/btree"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"github.com/MetalBlockchain/metalgo/cache"
"github.com/MetalBlockchain/metalgo/cache/metercacher"
"github.com/MetalBlockchain/metalgo/database"
"github.com/MetalBlockchain/metalgo/database/linkeddb"
"github.com/MetalBlockchain/metalgo/database/prefixdb"
"github.com/MetalBlockchain/metalgo/database/versiondb"
"github.com/MetalBlockchain/metalgo/ids"
"github.com/MetalBlockchain/metalgo/snow"
"github.com/MetalBlockchain/metalgo/snow/choices"
"github.com/MetalBlockchain/metalgo/snow/uptime"
"github.com/MetalBlockchain/metalgo/snow/validators"
"github.com/MetalBlockchain/metalgo/utils/constants"
"github.com/MetalBlockchain/metalgo/utils/crypto/bls"
"github.com/MetalBlockchain/metalgo/utils/hashing"
"github.com/MetalBlockchain/metalgo/utils/logging"
"github.com/MetalBlockchain/metalgo/utils/timer"
"github.com/MetalBlockchain/metalgo/utils/wrappers"
"github.com/MetalBlockchain/metalgo/vms/components/avax"
"github.com/MetalBlockchain/metalgo/vms/platformvm/block"
"github.com/MetalBlockchain/metalgo/vms/platformvm/config"
"github.com/MetalBlockchain/metalgo/vms/platformvm/fx"
"github.com/MetalBlockchain/metalgo/vms/platformvm/genesis"
"github.com/MetalBlockchain/metalgo/vms/platformvm/metrics"
"github.com/MetalBlockchain/metalgo/vms/platformvm/reward"
"github.com/MetalBlockchain/metalgo/vms/platformvm/status"
"github.com/MetalBlockchain/metalgo/vms/platformvm/txs"
safemath "github.com/MetalBlockchain/metalgo/utils/math"
)
const (
indexIterationLimit = 4096
indexIterationSleepMultiplier = 5
indexIterationSleepCap = 10 * time.Second
indexLogFrequency = 30 * time.Second
)
var (
_ State = (*state)(nil)
errValidatorSetAlreadyPopulated = errors.New("validator set already populated")
errIsNotSubnet = errors.New("is not a subnet")
BlockIDPrefix = []byte("blockID")
BlockPrefix = []byte("block")
ValidatorsPrefix = []byte("validators")
CurrentPrefix = []byte("current")
PendingPrefix = []byte("pending")
ValidatorPrefix = []byte("validator")
DelegatorPrefix = []byte("delegator")
SubnetValidatorPrefix = []byte("subnetValidator")
SubnetDelegatorPrefix = []byte("subnetDelegator")
ValidatorWeightDiffsPrefix = []byte("flatValidatorDiffs")
ValidatorPublicKeyDiffsPrefix = []byte("flatPublicKeyDiffs")
TxPrefix = []byte("tx")
RewardUTXOsPrefix = []byte("rewardUTXOs")
UTXOPrefix = []byte("utxo")
SubnetPrefix = []byte("subnet")
SubnetOwnerPrefix = []byte("subnetOwner")
TransformedSubnetPrefix = []byte("transformedSubnet")
SupplyPrefix = []byte("supply")
ChainPrefix = []byte("chain")
SingletonPrefix = []byte("singleton")
TimestampKey = []byte("timestamp")
CurrentSupplyKey = []byte("current supply")
LastAcceptedKey = []byte("last accepted")
HeightsIndexedKey = []byte("heights indexed")
InitializedKey = []byte("initialized")
BlocksReindexedKey = []byte("blocks reindexed")
)
// Chain collects all methods to manage the state of the chain for block
// execution.
type Chain interface {
Stakers
avax.UTXOAdder
avax.UTXOGetter
avax.UTXODeleter
GetTimestamp() time.Time
SetTimestamp(tm time.Time)
GetCurrentSupply(subnetID ids.ID) (uint64, error)
SetCurrentSupply(subnetID ids.ID, cs uint64)
AddRewardUTXO(txID ids.ID, utxo *avax.UTXO)
AddSubnet(subnetID ids.ID)
GetSubnetOwner(subnetID ids.ID) (fx.Owner, error)
SetSubnetOwner(subnetID ids.ID, owner fx.Owner)
GetSubnetTransformation(subnetID ids.ID) (*txs.Tx, error)
AddSubnetTransformation(transformSubnetTx *txs.Tx)
AddChain(createChainTx *txs.Tx)
GetTx(txID ids.ID) (*txs.Tx, status.Status, error)
AddTx(tx *txs.Tx, status status.Status)
}
type State interface {
Chain
uptime.State
avax.UTXOReader
GetLastAccepted() ids.ID
SetLastAccepted(blkID ids.ID)
GetStatelessBlock(blockID ids.ID) (block.Block, error)
// Invariant: [block] is an accepted block.
AddStatelessBlock(block block.Block)
GetBlockIDAtHeight(height uint64) (ids.ID, error)
GetRewardUTXOs(txID ids.ID) ([]*avax.UTXO, error)
GetSubnetIDs() ([]ids.ID, error)
GetChains(subnetID ids.ID) ([]*txs.Tx, error)
// ApplyValidatorWeightDiffs iterates from [startHeight] towards the genesis
// block until it has applied all of the diffs up to and including
// [endHeight]. Applying the diffs modifies [validators].
//
// Invariant: If attempting to generate the validator set for
// [endHeight - 1], [validators] must initially contain the validator
// weights for [startHeight].
//
// Note: Because this function iterates towards the genesis, [startHeight]
// will typically be greater than or equal to [endHeight]. If [startHeight]
// is less than [endHeight], no diffs will be applied.
ApplyValidatorWeightDiffs(
ctx context.Context,
validators map[ids.NodeID]*validators.GetValidatorOutput,
startHeight uint64,
endHeight uint64,
subnetID ids.ID,
) error
// ApplyValidatorPublicKeyDiffs iterates from [startHeight] towards the
// genesis block until it has applied all of the diffs up to and including
// [endHeight]. Applying the diffs modifies [validators].
//
// Invariant: If attempting to generate the validator set for
// [endHeight - 1], [validators] must initially contain the validator
// weights for [startHeight].
//
// Note: Because this function iterates towards the genesis, [startHeight]
// will typically be greater than or equal to [endHeight]. If [startHeight]
// is less than [endHeight], no diffs will be applied.
ApplyValidatorPublicKeyDiffs(
ctx context.Context,
validators map[ids.NodeID]*validators.GetValidatorOutput,
startHeight uint64,
endHeight uint64,
) error
SetHeight(height uint64)
// Discard uncommitted changes to the database.
Abort()
// ReindexBlocks converts any block indices using the legacy storage format
// to the new format. If this database has already updated the indices,
// this function will return immediately, without iterating over the
// database.
//
// TODO: Remove after v1.12.x is activated
ReindexBlocks(lock sync.Locker, log logging.Logger) error
// Commit changes to the base database.
Commit() error
// Returns a batch of unwritten changes that, when written, will commit all
// pending changes to the base database.
CommitBatch() (database.Batch, error)
Checksum() ids.ID
Close() error
}
// Prior to https://github.com/MetalBlockchain/metalgo/pull/1719, blocks were
// stored as a map from blkID to stateBlk. Nodes synced prior to this PR may
// still have blocks partially stored using this legacy format.
//
// TODO: Remove after v1.12.x is activated
type stateBlk struct {
Bytes []byte `serialize:"true"`
Status choices.Status `serialize:"true"`
}
/*
* VMDB
* |-. validators
* | |-. current
* | | |-. validator
* | | | '-. list
* | | | '-- txID -> uptime + potential reward + potential delegatee reward
* | | |-. delegator
* | | | '-. list
* | | | '-- txID -> potential reward
* | | |-. subnetValidator
* | | | '-. list
* | | | '-- txID -> uptime + potential reward + potential delegatee reward
* | | '-. subnetDelegator
* | | '-. list
* | | '-- txID -> potential reward
* | |-. pending
* | | |-. validator
* | | | '-. list
* | | | '-- txID -> nil
* | | |-. delegator
* | | | '-. list
* | | | '-- txID -> nil
* | | |-. subnetValidator
* | | | '-. list
* | | | '-- txID -> nil
* | | '-. subnetDelegator
* | | '-. list
* | | '-- txID -> nil
* | |-. weight diffs
* | | '-- subnet+height+nodeID -> weightChange
* | '-. pub key diffs
* | '-- subnet+height+nodeID -> uncompressed public key or nil
* |-. blockIDs
* | '-- height -> blockID
* |-. blocks
* | '-- blockID -> block bytes
* |-. txs
* | '-- txID -> tx bytes + tx status
* |- rewardUTXOs
* | '-. txID
* | '-. list
* | '-- utxoID -> utxo bytes
* |- utxos
* | '-- utxoDB
* |-. subnets
* | '-. list
* | '-- txID -> nil
* |-. subnetOwners
* | '-. subnetID -> owner
* |-. chains
* | '-. subnetID
* | '-. list
* | '-- txID -> nil
* '-. singletons
* |-- initializedKey -> nil
* |-- blocksReindexedKey -> nil
* |-- timestampKey -> timestamp
* |-- currentSupplyKey -> currentSupply
* |-- lastAcceptedKey -> lastAccepted
* '-- heightsIndexKey -> startIndexHeight + endIndexHeight
*/
type state struct {
validatorState
validators validators.Manager
ctx *snow.Context
cfg *config.Config
metrics metrics.Metrics
rewards reward.Calculator
baseDB *versiondb.Database
currentStakers *baseStakers
pendingStakers *baseStakers
currentHeight uint64
addedBlockIDs map[uint64]ids.ID // map of height -> blockID
blockIDCache cache.Cacher[uint64, ids.ID] // cache of height -> blockID; if the entry is ids.Empty, it is not in the database
blockIDDB database.Database
addedBlocks map[ids.ID]block.Block // map of blockID -> Block
blockCache cache.Cacher[ids.ID, block.Block] // cache of blockID -> Block; if the entry is nil, it is not in the database
blockDB database.Database
validatorsDB database.Database
currentValidatorsDB database.Database
currentValidatorBaseDB database.Database
currentValidatorList linkeddb.LinkedDB
currentDelegatorBaseDB database.Database
currentDelegatorList linkeddb.LinkedDB
currentSubnetValidatorBaseDB database.Database
currentSubnetValidatorList linkeddb.LinkedDB
currentSubnetDelegatorBaseDB database.Database
currentSubnetDelegatorList linkeddb.LinkedDB
pendingValidatorsDB database.Database
pendingValidatorBaseDB database.Database
pendingValidatorList linkeddb.LinkedDB
pendingDelegatorBaseDB database.Database
pendingDelegatorList linkeddb.LinkedDB
pendingSubnetValidatorBaseDB database.Database
pendingSubnetValidatorList linkeddb.LinkedDB
pendingSubnetDelegatorBaseDB database.Database
pendingSubnetDelegatorList linkeddb.LinkedDB
validatorWeightDiffsDB database.Database
validatorPublicKeyDiffsDB database.Database
addedTxs map[ids.ID]*txAndStatus // map of txID -> {*txs.Tx, Status}
txCache cache.Cacher[ids.ID, *txAndStatus] // txID -> {*txs.Tx, Status}; if the entry is nil, it is not in the database
txDB database.Database
addedRewardUTXOs map[ids.ID][]*avax.UTXO // map of txID -> []*UTXO
rewardUTXOsCache cache.Cacher[ids.ID, []*avax.UTXO] // txID -> []*UTXO
rewardUTXODB database.Database
modifiedUTXOs map[ids.ID]*avax.UTXO // map of modified UTXOID -> *UTXO; if the UTXO is nil, it has been removed
utxoDB database.Database
utxoState avax.UTXOState
cachedSubnetIDs []ids.ID // nil if the subnets haven't been loaded
addedSubnetIDs []ids.ID
subnetBaseDB database.Database
subnetDB linkeddb.LinkedDB
subnetOwners map[ids.ID]fx.Owner // map of subnetID -> owner
subnetOwnerCache cache.Cacher[ids.ID, fxOwnerAndSize] // cache of subnetID -> owner; if the entry is nil, it is not in the database
subnetOwnerDB database.Database
transformedSubnets map[ids.ID]*txs.Tx // map of subnetID -> transformSubnetTx
transformedSubnetCache cache.Cacher[ids.ID, *txs.Tx] // cache of subnetID -> transformSubnetTx; if the entry is nil, it is not in the database
transformedSubnetDB database.Database
modifiedSupplies map[ids.ID]uint64 // map of subnetID -> current supply
supplyCache cache.Cacher[ids.ID, *uint64] // cache of subnetID -> current supply; if the entry is nil, it is not in the database
supplyDB database.Database
addedChains map[ids.ID][]*txs.Tx // maps subnetID -> the newly added chains to the subnet
chainCache cache.Cacher[ids.ID, []*txs.Tx] // cache of subnetID -> the chains after all local modifications []*txs.Tx
chainDBCache cache.Cacher[ids.ID, linkeddb.LinkedDB] // cache of subnetID -> linkedDB
chainDB database.Database
// The persisted fields represent the current database value
timestamp, persistedTimestamp time.Time
currentSupply, persistedCurrentSupply uint64
// [lastAccepted] is the most recently accepted block.
lastAccepted, persistedLastAccepted ids.ID
// TODO: Remove indexedHeights once v1.11.3 has been released.
indexedHeights *heightRange
singletonDB database.Database
}
// heightRange is used to track which heights are safe to use the native DB
// iterator for querying validator diffs.
//
// TODO: Remove once we are guaranteed nodes can not rollback to not support the
// new indexing mechanism.
type heightRange struct {
LowerBound uint64 `serialize:"true"`
UpperBound uint64 `serialize:"true"`
}
type ValidatorWeightDiff struct {
Decrease bool `serialize:"true"`
Amount uint64 `serialize:"true"`
}
func (v *ValidatorWeightDiff) Add(negative bool, amount uint64) error {
if v.Decrease == negative {
var err error
v.Amount, err = safemath.Add64(v.Amount, amount)
return err
}
if v.Amount > amount {
v.Amount -= amount
} else {
v.Amount = safemath.AbsDiff(v.Amount, amount)
v.Decrease = negative
}
return nil
}
type txBytesAndStatus struct {
Tx []byte `serialize:"true"`
Status status.Status `serialize:"true"`
}
type txAndStatus struct {
tx *txs.Tx
status status.Status
}
type fxOwnerAndSize struct {
owner fx.Owner
size int
}
func txSize(_ ids.ID, tx *txs.Tx) int {
if tx == nil {
return ids.IDLen + constants.PointerOverhead
}
return ids.IDLen + len(tx.Bytes()) + constants.PointerOverhead
}
func txAndStatusSize(_ ids.ID, t *txAndStatus) int {
if t == nil {
return ids.IDLen + constants.PointerOverhead
}
return ids.IDLen + len(t.tx.Bytes()) + wrappers.IntLen + 2*constants.PointerOverhead
}
func blockSize(_ ids.ID, blk block.Block) int {
if blk == nil {
return ids.IDLen + constants.PointerOverhead
}
return ids.IDLen + len(blk.Bytes()) + constants.PointerOverhead
}
func New(
db database.Database,
genesisBytes []byte,
metricsReg prometheus.Registerer,
cfg *config.Config,
execCfg *config.ExecutionConfig,
ctx *snow.Context,
metrics metrics.Metrics,
rewards reward.Calculator,
) (State, error) {
s, err := newState(
db,
metrics,
cfg,
execCfg,
ctx,
metricsReg,
rewards,
)
if err != nil {
return nil, err
}
if err := s.sync(genesisBytes); err != nil {
// Drop any errors on close to return the first error
_ = s.Close()
return nil, err
}
return s, nil
}
func newState(
db database.Database,
metrics metrics.Metrics,
cfg *config.Config,
execCfg *config.ExecutionConfig,
ctx *snow.Context,
metricsReg prometheus.Registerer,
rewards reward.Calculator,
) (*state, error) {
blockIDCache, err := metercacher.New[uint64, ids.ID](
"block_id_cache",
metricsReg,
&cache.LRU[uint64, ids.ID]{Size: execCfg.BlockIDCacheSize},
)
if err != nil {
return nil, err
}
blockCache, err := metercacher.New[ids.ID, block.Block](
"block_cache",
metricsReg,
cache.NewSizedLRU[ids.ID, block.Block](execCfg.BlockCacheSize, blockSize),
)
if err != nil {
return nil, err
}
baseDB := versiondb.New(db)
validatorsDB := prefixdb.New(ValidatorsPrefix, baseDB)
currentValidatorsDB := prefixdb.New(CurrentPrefix, validatorsDB)
currentValidatorBaseDB := prefixdb.New(ValidatorPrefix, currentValidatorsDB)
currentDelegatorBaseDB := prefixdb.New(DelegatorPrefix, currentValidatorsDB)
currentSubnetValidatorBaseDB := prefixdb.New(SubnetValidatorPrefix, currentValidatorsDB)
currentSubnetDelegatorBaseDB := prefixdb.New(SubnetDelegatorPrefix, currentValidatorsDB)
pendingValidatorsDB := prefixdb.New(PendingPrefix, validatorsDB)
pendingValidatorBaseDB := prefixdb.New(ValidatorPrefix, pendingValidatorsDB)
pendingDelegatorBaseDB := prefixdb.New(DelegatorPrefix, pendingValidatorsDB)
pendingSubnetValidatorBaseDB := prefixdb.New(SubnetValidatorPrefix, pendingValidatorsDB)
pendingSubnetDelegatorBaseDB := prefixdb.New(SubnetDelegatorPrefix, pendingValidatorsDB)
validatorWeightDiffsDB := prefixdb.New(ValidatorWeightDiffsPrefix, validatorsDB)
validatorPublicKeyDiffsDB := prefixdb.New(ValidatorPublicKeyDiffsPrefix, validatorsDB)
txCache, err := metercacher.New(
"tx_cache",
metricsReg,
cache.NewSizedLRU[ids.ID, *txAndStatus](execCfg.TxCacheSize, txAndStatusSize),
)
if err != nil {
return nil, err
}
rewardUTXODB := prefixdb.New(RewardUTXOsPrefix, baseDB)
rewardUTXOsCache, err := metercacher.New[ids.ID, []*avax.UTXO](
"reward_utxos_cache",
metricsReg,
&cache.LRU[ids.ID, []*avax.UTXO]{Size: execCfg.RewardUTXOsCacheSize},
)
if err != nil {
return nil, err
}
utxoDB := prefixdb.New(UTXOPrefix, baseDB)
utxoState, err := avax.NewMeteredUTXOState(utxoDB, txs.GenesisCodec, metricsReg, execCfg.ChecksumsEnabled)
if err != nil {
return nil, err
}
subnetBaseDB := prefixdb.New(SubnetPrefix, baseDB)
subnetOwnerDB := prefixdb.New(SubnetOwnerPrefix, baseDB)
subnetOwnerCache, err := metercacher.New[ids.ID, fxOwnerAndSize](
"subnet_owner_cache",
metricsReg,
cache.NewSizedLRU[ids.ID, fxOwnerAndSize](execCfg.FxOwnerCacheSize, func(_ ids.ID, f fxOwnerAndSize) int {
return ids.IDLen + f.size
}),
)
if err != nil {
return nil, err
}
transformedSubnetCache, err := metercacher.New(
"transformed_subnet_cache",
metricsReg,
cache.NewSizedLRU[ids.ID, *txs.Tx](execCfg.TransformedSubnetTxCacheSize, txSize),
)
if err != nil {
return nil, err
}
supplyCache, err := metercacher.New[ids.ID, *uint64](
"supply_cache",
metricsReg,
&cache.LRU[ids.ID, *uint64]{Size: execCfg.ChainCacheSize},
)
if err != nil {
return nil, err
}
chainCache, err := metercacher.New[ids.ID, []*txs.Tx](
"chain_cache",
metricsReg,
&cache.LRU[ids.ID, []*txs.Tx]{Size: execCfg.ChainCacheSize},
)
if err != nil {
return nil, err
}
chainDBCache, err := metercacher.New[ids.ID, linkeddb.LinkedDB](
"chain_db_cache",
metricsReg,
&cache.LRU[ids.ID, linkeddb.LinkedDB]{Size: execCfg.ChainDBCacheSize},
)
if err != nil {
return nil, err
}
return &state{
validatorState: newValidatorState(),
validators: cfg.Validators,
ctx: ctx,
cfg: cfg,
metrics: metrics,
rewards: rewards,
baseDB: baseDB,
addedBlockIDs: make(map[uint64]ids.ID),
blockIDCache: blockIDCache,
blockIDDB: prefixdb.New(BlockIDPrefix, baseDB),
addedBlocks: make(map[ids.ID]block.Block),
blockCache: blockCache,
blockDB: prefixdb.New(BlockPrefix, baseDB),
currentStakers: newBaseStakers(),
pendingStakers: newBaseStakers(),
validatorsDB: validatorsDB,
currentValidatorsDB: currentValidatorsDB,
currentValidatorBaseDB: currentValidatorBaseDB,
currentValidatorList: linkeddb.NewDefault(currentValidatorBaseDB),
currentDelegatorBaseDB: currentDelegatorBaseDB,
currentDelegatorList: linkeddb.NewDefault(currentDelegatorBaseDB),
currentSubnetValidatorBaseDB: currentSubnetValidatorBaseDB,
currentSubnetValidatorList: linkeddb.NewDefault(currentSubnetValidatorBaseDB),
currentSubnetDelegatorBaseDB: currentSubnetDelegatorBaseDB,
currentSubnetDelegatorList: linkeddb.NewDefault(currentSubnetDelegatorBaseDB),
pendingValidatorsDB: pendingValidatorsDB,
pendingValidatorBaseDB: pendingValidatorBaseDB,
pendingValidatorList: linkeddb.NewDefault(pendingValidatorBaseDB),
pendingDelegatorBaseDB: pendingDelegatorBaseDB,
pendingDelegatorList: linkeddb.NewDefault(pendingDelegatorBaseDB),
pendingSubnetValidatorBaseDB: pendingSubnetValidatorBaseDB,
pendingSubnetValidatorList: linkeddb.NewDefault(pendingSubnetValidatorBaseDB),
pendingSubnetDelegatorBaseDB: pendingSubnetDelegatorBaseDB,
pendingSubnetDelegatorList: linkeddb.NewDefault(pendingSubnetDelegatorBaseDB),
validatorWeightDiffsDB: validatorWeightDiffsDB,
validatorPublicKeyDiffsDB: validatorPublicKeyDiffsDB,
addedTxs: make(map[ids.ID]*txAndStatus),
txDB: prefixdb.New(TxPrefix, baseDB),
txCache: txCache,
addedRewardUTXOs: make(map[ids.ID][]*avax.UTXO),
rewardUTXODB: rewardUTXODB,
rewardUTXOsCache: rewardUTXOsCache,
modifiedUTXOs: make(map[ids.ID]*avax.UTXO),
utxoDB: utxoDB,
utxoState: utxoState,
subnetBaseDB: subnetBaseDB,
subnetDB: linkeddb.NewDefault(subnetBaseDB),
subnetOwners: make(map[ids.ID]fx.Owner),
subnetOwnerDB: subnetOwnerDB,
subnetOwnerCache: subnetOwnerCache,
transformedSubnets: make(map[ids.ID]*txs.Tx),
transformedSubnetCache: transformedSubnetCache,
transformedSubnetDB: prefixdb.New(TransformedSubnetPrefix, baseDB),
modifiedSupplies: make(map[ids.ID]uint64),
supplyCache: supplyCache,
supplyDB: prefixdb.New(SupplyPrefix, baseDB),
addedChains: make(map[ids.ID][]*txs.Tx),
chainDB: prefixdb.New(ChainPrefix, baseDB),
chainCache: chainCache,
chainDBCache: chainDBCache,
singletonDB: prefixdb.New(SingletonPrefix, baseDB),
}, nil
}
func (s *state) GetCurrentValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker, error) {
return s.currentStakers.GetValidator(subnetID, nodeID)
}
func (s *state) PutCurrentValidator(staker *Staker) {
s.currentStakers.PutValidator(staker)
}
func (s *state) DeleteCurrentValidator(staker *Staker) {
s.currentStakers.DeleteValidator(staker)
}
func (s *state) GetCurrentDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (StakerIterator, error) {
return s.currentStakers.GetDelegatorIterator(subnetID, nodeID), nil
}
func (s *state) PutCurrentDelegator(staker *Staker) {
s.currentStakers.PutDelegator(staker)
}
func (s *state) DeleteCurrentDelegator(staker *Staker) {
s.currentStakers.DeleteDelegator(staker)
}
func (s *state) GetCurrentStakerIterator() (StakerIterator, error) {
return s.currentStakers.GetStakerIterator(), nil
}
func (s *state) GetPendingValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker, error) {
return s.pendingStakers.GetValidator(subnetID, nodeID)
}
func (s *state) PutPendingValidator(staker *Staker) {
s.pendingStakers.PutValidator(staker)
}
func (s *state) DeletePendingValidator(staker *Staker) {
s.pendingStakers.DeleteValidator(staker)
}
func (s *state) GetPendingDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (StakerIterator, error) {
return s.pendingStakers.GetDelegatorIterator(subnetID, nodeID), nil
}
func (s *state) PutPendingDelegator(staker *Staker) {
s.pendingStakers.PutDelegator(staker)
}
func (s *state) DeletePendingDelegator(staker *Staker) {
s.pendingStakers.DeleteDelegator(staker)
}
func (s *state) GetPendingStakerIterator() (StakerIterator, error) {
return s.pendingStakers.GetStakerIterator(), nil
}
func (s *state) shouldInit() (bool, error) {
has, err := s.singletonDB.Has(InitializedKey)
return !has, err
}
func (s *state) doneInit() error {
return s.singletonDB.Put(InitializedKey, nil)
}
func (s *state) GetSubnetIDs() ([]ids.ID, error) {
if s.cachedSubnetIDs != nil {
return s.cachedSubnetIDs, nil
}
subnetDBIt := s.subnetDB.NewIterator()
defer subnetDBIt.Release()
subnetIDs := []ids.ID{}
for subnetDBIt.Next() {
subnetIDBytes := subnetDBIt.Key()
subnetID, err := ids.ToID(subnetIDBytes)
if err != nil {
return nil, err
}
subnetIDs = append(subnetIDs, subnetID)
}
if err := subnetDBIt.Error(); err != nil {
return nil, err
}
subnetIDs = append(subnetIDs, s.addedSubnetIDs...)
s.cachedSubnetIDs = subnetIDs
return subnetIDs, nil
}
func (s *state) AddSubnet(subnetID ids.ID) {
s.addedSubnetIDs = append(s.addedSubnetIDs, subnetID)
if s.cachedSubnetIDs != nil {
s.cachedSubnetIDs = append(s.cachedSubnetIDs, subnetID)
}
}
func (s *state) GetSubnetOwner(subnetID ids.ID) (fx.Owner, error) {
if owner, exists := s.subnetOwners[subnetID]; exists {
return owner, nil
}
if ownerAndSize, cached := s.subnetOwnerCache.Get(subnetID); cached {
if ownerAndSize.owner == nil {
return nil, database.ErrNotFound
}
return ownerAndSize.owner, nil
}
ownerBytes, err := s.subnetOwnerDB.Get(subnetID[:])
if err == nil {
var owner fx.Owner
if _, err := block.GenesisCodec.Unmarshal(ownerBytes, &owner); err != nil {
return nil, err
}
s.subnetOwnerCache.Put(subnetID, fxOwnerAndSize{
owner: owner,
size: len(ownerBytes),
})
return owner, nil
}
if err != database.ErrNotFound {
return nil, err
}
subnetIntf, _, err := s.GetTx(subnetID)
if err != nil {
if err == database.ErrNotFound {
s.subnetOwnerCache.Put(subnetID, fxOwnerAndSize{})
}
return nil, err
}
subnet, ok := subnetIntf.Unsigned.(*txs.CreateSubnetTx)
if !ok {
return nil, fmt.Errorf("%q %w", subnetID, errIsNotSubnet)
}
s.SetSubnetOwner(subnetID, subnet.Owner)
return subnet.Owner, nil
}
func (s *state) SetSubnetOwner(subnetID ids.ID, owner fx.Owner) {
s.subnetOwners[subnetID] = owner
}
func (s *state) GetSubnetTransformation(subnetID ids.ID) (*txs.Tx, error) {
if tx, exists := s.transformedSubnets[subnetID]; exists {
return tx, nil
}
if tx, cached := s.transformedSubnetCache.Get(subnetID); cached {
if tx == nil {
return nil, database.ErrNotFound
}
return tx, nil
}
transformSubnetTxID, err := database.GetID(s.transformedSubnetDB, subnetID[:])
if err == database.ErrNotFound {
s.transformedSubnetCache.Put(subnetID, nil)
return nil, database.ErrNotFound
}
if err != nil {
return nil, err
}
transformSubnetTx, _, err := s.GetTx(transformSubnetTxID)
if err != nil {
return nil, err
}
s.transformedSubnetCache.Put(subnetID, transformSubnetTx)
return transformSubnetTx, nil
}
func (s *state) AddSubnetTransformation(transformSubnetTxIntf *txs.Tx) {
transformSubnetTx := transformSubnetTxIntf.Unsigned.(*txs.TransformSubnetTx)
s.transformedSubnets[transformSubnetTx.Subnet] = transformSubnetTxIntf
}
func (s *state) GetChains(subnetID ids.ID) ([]*txs.Tx, error) {
if chains, cached := s.chainCache.Get(subnetID); cached {
return chains, nil
}
chainDB := s.getChainDB(subnetID)
chainDBIt := chainDB.NewIterator()
defer chainDBIt.Release()
txs := []*txs.Tx(nil)
for chainDBIt.Next() {
chainIDBytes := chainDBIt.Key()
chainID, err := ids.ToID(chainIDBytes)
if err != nil {
return nil, err
}
chainTx, _, err := s.GetTx(chainID)
if err != nil {
return nil, err
}
txs = append(txs, chainTx)
}
if err := chainDBIt.Error(); err != nil {
return nil, err
}
txs = append(txs, s.addedChains[subnetID]...)
s.chainCache.Put(subnetID, txs)
return txs, nil
}
func (s *state) AddChain(createChainTxIntf *txs.Tx) {
createChainTx := createChainTxIntf.Unsigned.(*txs.CreateChainTx)
subnetID := createChainTx.SubnetID
s.addedChains[subnetID] = append(s.addedChains[subnetID], createChainTxIntf)
if chains, cached := s.chainCache.Get(subnetID); cached {
chains = append(chains, createChainTxIntf)
s.chainCache.Put(subnetID, chains)
}
}
func (s *state) getChainDB(subnetID ids.ID) linkeddb.LinkedDB {
if chainDB, cached := s.chainDBCache.Get(subnetID); cached {
return chainDB
}
rawChainDB := prefixdb.New(subnetID[:], s.chainDB)
chainDB := linkeddb.NewDefault(rawChainDB)
s.chainDBCache.Put(subnetID, chainDB)
return chainDB
}
func (s *state) GetTx(txID ids.ID) (*txs.Tx, status.Status, error) {
if tx, exists := s.addedTxs[txID]; exists {
return tx.tx, tx.status, nil
}
if tx, cached := s.txCache.Get(txID); cached {
if tx == nil {
return nil, status.Unknown, database.ErrNotFound
}
return tx.tx, tx.status, nil
}
txBytes, err := s.txDB.Get(txID[:])
if err == database.ErrNotFound {
s.txCache.Put(txID, nil)
return nil, status.Unknown, database.ErrNotFound
} else if err != nil {
return nil, status.Unknown, err
}
stx := txBytesAndStatus{}
if _, err := txs.GenesisCodec.Unmarshal(txBytes, &stx); err != nil {
return nil, status.Unknown, err
}
tx, err := txs.Parse(txs.GenesisCodec, stx.Tx)
if err != nil {
return nil, status.Unknown, err
}
ptx := &txAndStatus{
tx: tx,
status: stx.Status,
}
s.txCache.Put(txID, ptx)
return ptx.tx, ptx.status, nil
}
func (s *state) AddTx(tx *txs.Tx, status status.Status) {
s.addedTxs[tx.ID()] = &txAndStatus{
tx: tx,
status: status,
}
}
func (s *state) GetRewardUTXOs(txID ids.ID) ([]*avax.UTXO, error) {
if utxos, exists := s.addedRewardUTXOs[txID]; exists {
return utxos, nil
}
if utxos, exists := s.rewardUTXOsCache.Get(txID); exists {
return utxos, nil
}
rawTxDB := prefixdb.New(txID[:], s.rewardUTXODB)
txDB := linkeddb.NewDefault(rawTxDB)
it := txDB.NewIterator()
defer it.Release()
utxos := []*avax.UTXO(nil)
for it.Next() {
utxo := &avax.UTXO{}
if _, err := txs.Codec.Unmarshal(it.Value(), utxo); err != nil {
return nil, err
}
utxos = append(utxos, utxo)
}
if err := it.Error(); err != nil {
return nil, err
}
s.rewardUTXOsCache.Put(txID, utxos)
return utxos, nil
}
func (s *state) AddRewardUTXO(txID ids.ID, utxo *avax.UTXO) {
s.addedRewardUTXOs[txID] = append(s.addedRewardUTXOs[txID], utxo)
}
func (s *state) GetUTXO(utxoID ids.ID) (*avax.UTXO, error) {
if utxo, exists := s.modifiedUTXOs[utxoID]; exists {
if utxo == nil {
return nil, database.ErrNotFound
}
return utxo, nil
}
return s.utxoState.GetUTXO(utxoID)
}
func (s *state) UTXOIDs(addr []byte, start ids.ID, limit int) ([]ids.ID, error) {
return s.utxoState.UTXOIDs(addr, start, limit)
}
func (s *state) AddUTXO(utxo *avax.UTXO) {
s.modifiedUTXOs[utxo.InputID()] = utxo
}
func (s *state) DeleteUTXO(utxoID ids.ID) {
s.modifiedUTXOs[utxoID] = nil
}
func (s *state) GetStartTime(nodeID ids.NodeID, subnetID ids.ID) (time.Time, error) {
staker, err := s.currentStakers.GetValidator(subnetID, nodeID)
if err != nil {
return time.Time{}, err
}
return staker.StartTime, nil
}
func (s *state) GetTimestamp() time.Time {