-
Notifications
You must be signed in to change notification settings - Fork 649
/
state.go
2626 lines (2249 loc) · 73.5 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"
"go.uber.org/zap"
"github.com/prometheus/client_golang/prometheus"
"github.com/ava-labs/avalanchego/cache"
"github.com/ava-labs/avalanchego/cache/metercacher"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/database/linkeddb"
"github.com/ava-labs/avalanchego/database/prefixdb"
"github.com/ava-labs/avalanchego/database/versiondb"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow"
"github.com/ava-labs/avalanchego/snow/choices"
"github.com/ava-labs/avalanchego/snow/uptime"
"github.com/ava-labs/avalanchego/snow/validators"
"github.com/ava-labs/avalanchego/utils"
"github.com/ava-labs/avalanchego/utils/constants"
"github.com/ava-labs/avalanchego/utils/crypto/bls"
"github.com/ava-labs/avalanchego/utils/hashing"
"github.com/ava-labs/avalanchego/utils/logging"
"github.com/ava-labs/avalanchego/utils/timer"
"github.com/ava-labs/avalanchego/utils/wrappers"
"github.com/ava-labs/avalanchego/vms/components/avax"
"github.com/ava-labs/avalanchego/vms/platformvm/block"
"github.com/ava-labs/avalanchego/vms/platformvm/config"
"github.com/ava-labs/avalanchego/vms/platformvm/fx"
"github.com/ava-labs/avalanchego/vms/platformvm/genesis"
"github.com/ava-labs/avalanchego/vms/platformvm/metrics"
"github.com/ava-labs/avalanchego/vms/platformvm/reward"
"github.com/ava-labs/avalanchego/vms/platformvm/status"
"github.com/ava-labs/avalanchego/vms/platformvm/txs"
safemath "github.com/ava-labs/avalanchego/utils/math"
)
const (
pruneCommitLimit = 1024
pruneCommitSleepMultiplier = 5
pruneCommitSleepCap = 10 * time.Second
pruneUpdateFrequency = 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")
nestedValidatorWeightDiffsPrefix = []byte("validatorDiffs")
nestedValidatorPublicKeyDiffsPrefix = []byte("publicKeyDiffs")
flatValidatorWeightDiffsPrefix = []byte("flatValidatorDiffs")
flatValidatorPublicKeyDiffsPrefix = []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")
prunedKey = []byte("pruned")
)
// 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(createSubnetTx *txs.Tx)
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)
GetSubnets() ([]*txs.Tx, 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()
// Returns if the state should be pruned and indexed to remove rejected
// blocks and generate the block height index.
//
// TODO: Remove after v1.11.x is activated
ShouldPrune() (bool, error)
// Removes rejected blocks from disk and indexes accepted blocks by height. This
// function supports being (and is recommended to be) called asynchronously.
//
// TODO: Remove after v1.11.x is activated
PruneAndIndex(sync.Locker, 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
}
// TODO: Remove after v1.11.x is activated
type stateBlk struct {
Blk block.Block
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
* | |-. nested weight diffs TODO: Remove once only the flat db is needed
* | | '-. height+subnet
* | | '-. list
* | | '-- nodeID -> weightChange
* | |-. nested pub key diffs TODO: Remove once only the flat db is needed
* | | '-. height
* | | '-. list
* | | '-- nodeID -> compressed public key
* | |-. flat weight diffs
* | | '-- subnet+height+nodeID -> weightChange
* | '-. flat 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
* |-- prunedKey -> 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
nestedValidatorWeightDiffsDB database.Database
nestedValidatorPublicKeyDiffsDB database.Database
flatValidatorWeightDiffsDB database.Database
flatValidatorPublicKeyDiffsDB 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 isn't 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
cachedSubnets []*txs.Tx // nil if the subnets haven't been loaded
addedSubnets []*txs.Tx
subnetBaseDB database.Database
subnetDB linkeddb.LinkedDB
// Subnet ID --> Owner of the subnet
subnetOwners map[ids.ID]fx.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
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 heightWithSubnet struct {
Height uint64 `serialize:"true"`
SubnetID ids.ID `serialize:"true"`
}
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
}
// Before we start accepting new blocks, we check if the pruning process needs
// to be run.
//
// TODO: Cleanup after v1.11.x is activated
shouldPrune, err := s.ShouldPrune()
if err != nil {
return nil, err
}
if shouldPrune {
// If the pruned key is on disk, we must delete it to ensure our disk
// can't get into a partially pruned state if the node restarts mid-way
// through pruning.
if err := s.singletonDB.Delete(prunedKey); err != nil {
return nil, fmt.Errorf("failed to remove prunedKey from singletonDB: %w", err)
}
if err := s.Commit(); err != nil {
return nil, fmt.Errorf("failed to commit to baseDB: %w", 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)
nestedValidatorWeightDiffsDB := prefixdb.New(nestedValidatorWeightDiffsPrefix, validatorsDB)
nestedValidatorPublicKeyDiffsDB := prefixdb.New(nestedValidatorPublicKeyDiffsPrefix, validatorsDB)
flatValidatorWeightDiffsDB := prefixdb.New(flatValidatorWeightDiffsPrefix, validatorsDB)
flatValidatorPublicKeyDiffsDB := prefixdb.New(flatValidatorPublicKeyDiffsPrefix, 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),
nestedValidatorWeightDiffsDB: nestedValidatorWeightDiffsDB,
nestedValidatorPublicKeyDiffsDB: nestedValidatorPublicKeyDiffsDB,
flatValidatorWeightDiffsDB: flatValidatorWeightDiffsDB,
flatValidatorPublicKeyDiffsDB: flatValidatorPublicKeyDiffsDB,
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) ShouldPrune() (bool, error) {
has, err := s.singletonDB.Has(prunedKey)
if err != nil {
return true, err
}
// If [prunedKey] is not in [singletonDB], [PruneAndIndex()] did not finish
// execution.
if !has {
return true, nil
}
// To ensure the db was not modified since we last ran [PruneAndIndex()], we
// must verify that [s.lastAccepted] is height indexed.
blk, err := s.GetStatelessBlock(s.lastAccepted)
if err != nil {
return true, err
}
_, err = s.GetBlockIDAtHeight(blk.Height())
if err == database.ErrNotFound {
return true, nil
}
return false, err
}
func (s *state) donePrune() error {
return s.singletonDB.Put(prunedKey, nil)
}
func (s *state) GetSubnets() ([]*txs.Tx, error) {
if s.cachedSubnets != nil {
return s.cachedSubnets, nil
}
subnetDBIt := s.subnetDB.NewIterator()
defer subnetDBIt.Release()
txs := []*txs.Tx(nil)
for subnetDBIt.Next() {
subnetIDBytes := subnetDBIt.Key()
subnetID, err := ids.ToID(subnetIDBytes)
if err != nil {
return nil, err
}
subnetTx, _, err := s.GetTx(subnetID)
if err != nil {
return nil, err
}
txs = append(txs, subnetTx)
}
if err := subnetDBIt.Error(); err != nil {
return nil, err
}
txs = append(txs, s.addedSubnets...)
s.cachedSubnets = txs
return txs, nil
}
func (s *state) AddSubnet(createSubnetTx *txs.Tx) {
s.addedSubnets = append(s.addedSubnets, createSubnetTx)
if s.cachedSubnets != nil {
s.cachedSubnets = append(s.cachedSubnets, createSubnetTx)
}
}
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
}