-
Notifications
You must be signed in to change notification settings - Fork 661
/
state.go
537 lines (446 loc) · 12.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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package state
import (
"fmt"
"time"
"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/prefixdb"
"github.com/ava-labs/avalanchego/database/versiondb"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils"
"github.com/ava-labs/avalanchego/vms/avm/block"
"github.com/ava-labs/avalanchego/vms/avm/txs"
"github.com/ava-labs/avalanchego/vms/components/avax"
)
const (
txCacheSize = 8192
blockIDCacheSize = 8192
blockCacheSize = 2048
)
var (
utxoPrefix = []byte("utxo")
txPrefix = []byte("tx")
blockIDPrefix = []byte("blockID")
blockPrefix = []byte("block")
singletonPrefix = []byte("singleton")
isInitializedKey = []byte{0x00}
timestampKey = []byte{0x01}
lastAcceptedKey = []byte{0x02}
_ State = (*state)(nil)
)
type ReadOnlyChain interface {
avax.UTXOGetter
GetTx(txID ids.ID) (*txs.Tx, error)
GetBlockIDAtHeight(height uint64) (ids.ID, error)
GetBlock(blkID ids.ID) (block.Block, error)
GetLastAccepted() ids.ID
GetTimestamp() time.Time
}
type Chain interface {
ReadOnlyChain
avax.UTXOAdder
avax.UTXODeleter
AddTx(tx *txs.Tx)
AddBlock(block block.Block)
SetLastAccepted(blkID ids.ID)
SetTimestamp(t time.Time)
}
// State persistently maintains a set of UTXOs, transaction, statuses, and
// singletons.
type State interface {
Chain
avax.UTXOReader
IsInitialized() (bool, error)
SetInitialized() error
// InitializeChainState is called after the VM has been linearized. Calling
// [GetLastAccepted] or [GetTimestamp] before calling this function will
// return uninitialized data.
//
// Invariant: After the chain is linearized, this function is expected to be
// called during startup.
InitializeChainState(stopVertexID ids.ID, genesisTimestamp time.Time) error
// Discard uncommitted changes to the database.
Abort()
// 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)
// Checksums returns the current TxChecksum and UTXOChecksum.
Checksums() (txChecksum ids.ID, utxoChecksum ids.ID)
Close() error
}
/*
* VMDB
* |- utxos
* | '-- utxoDB
* |-. txs
* | '-- txID -> tx bytes
* |-. blockIDs
* | '-- height -> blockID
* |-. blocks
* | '-- blockID -> block bytes
* '-. singletons
* |-- initializedKey -> nil
* |-- timestampKey -> timestamp
* '-- lastAcceptedKey -> lastAccepted
*/
type state struct {
parser block.Parser
db *versiondb.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
addedTxs map[ids.ID]*txs.Tx // map of txID -> *txs.Tx
txCache cache.Cacher[ids.ID, *txs.Tx] // cache of txID -> *txs.Tx. If the entry is nil, it is not in the database
txDB database.Database
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
// [lastAccepted] is the most recently accepted block.
lastAccepted, persistedLastAccepted ids.ID
timestamp, persistedTimestamp time.Time
singletonDB database.Database
trackChecksum bool
txChecksum ids.ID
}
func New(
db *versiondb.Database,
parser block.Parser,
metrics prometheus.Registerer,
trackChecksums bool,
) (State, error) {
utxoDB := prefixdb.New(utxoPrefix, db)
txDB := prefixdb.New(txPrefix, db)
blockIDDB := prefixdb.New(blockIDPrefix, db)
blockDB := prefixdb.New(blockPrefix, db)
singletonDB := prefixdb.New(singletonPrefix, db)
txCache, err := metercacher.New[ids.ID, *txs.Tx](
"tx_cache",
metrics,
&cache.LRU[ids.ID, *txs.Tx]{Size: txCacheSize},
)
if err != nil {
return nil, err
}
blockIDCache, err := metercacher.New[uint64, ids.ID](
"block_id_cache",
metrics,
&cache.LRU[uint64, ids.ID]{Size: blockIDCacheSize},
)
if err != nil {
return nil, err
}
blockCache, err := metercacher.New[ids.ID, block.Block](
"block_cache",
metrics,
&cache.LRU[ids.ID, block.Block]{Size: blockCacheSize},
)
if err != nil {
return nil, err
}
utxoState, err := avax.NewMeteredUTXOState(utxoDB, parser.Codec(), metrics, trackChecksums)
if err != nil {
return nil, err
}
s := &state{
parser: parser,
db: db,
modifiedUTXOs: make(map[ids.ID]*avax.UTXO),
utxoDB: utxoDB,
utxoState: utxoState,
addedTxs: make(map[ids.ID]*txs.Tx),
txCache: txCache,
txDB: txDB,
addedBlockIDs: make(map[uint64]ids.ID),
blockIDCache: blockIDCache,
blockIDDB: blockIDDB,
addedBlocks: make(map[ids.ID]block.Block),
blockCache: blockCache,
blockDB: blockDB,
singletonDB: singletonDB,
trackChecksum: trackChecksums,
}
return s, s.initTxChecksum()
}
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) GetTx(txID ids.ID) (*txs.Tx, error) {
if tx, exists := s.addedTxs[txID]; exists {
return tx, nil
}
if tx, exists := s.txCache.Get(txID); exists {
if tx == nil {
return nil, database.ErrNotFound
}
return tx, nil
}
txBytes, err := s.txDB.Get(txID[:])
if err == database.ErrNotFound {
s.txCache.Put(txID, nil)
return nil, database.ErrNotFound
}
if err != nil {
return nil, err
}
// The key was in the database
tx, err := s.parser.ParseGenesisTx(txBytes)
if err != nil {
return nil, err
}
s.txCache.Put(txID, tx)
return tx, nil
}
func (s *state) AddTx(tx *txs.Tx) {
txID := tx.ID()
s.updateTxChecksum(txID)
s.addedTxs[txID] = tx
}
func (s *state) GetBlockIDAtHeight(height uint64) (ids.ID, error) {
if blkID, exists := s.addedBlockIDs[height]; exists {
return blkID, nil
}
if blkID, cached := s.blockIDCache.Get(height); cached {
if blkID == ids.Empty {
return ids.Empty, database.ErrNotFound
}
return blkID, nil
}
heightKey := database.PackUInt64(height)
blkID, err := database.GetID(s.blockIDDB, heightKey)
if err == database.ErrNotFound {
s.blockIDCache.Put(height, ids.Empty)
return ids.Empty, database.ErrNotFound
}
if err != nil {
return ids.Empty, err
}
s.blockIDCache.Put(height, blkID)
return blkID, nil
}
func (s *state) GetBlock(blkID ids.ID) (block.Block, error) {
if blk, exists := s.addedBlocks[blkID]; exists {
return blk, nil
}
if blk, cached := s.blockCache.Get(blkID); cached {
if blk == nil {
return nil, database.ErrNotFound
}
return blk, nil
}
blkBytes, err := s.blockDB.Get(blkID[:])
if err == database.ErrNotFound {
s.blockCache.Put(blkID, nil)
return nil, database.ErrNotFound
}
if err != nil {
return nil, err
}
blk, err := s.parser.ParseBlock(blkBytes)
if err != nil {
return nil, err
}
s.blockCache.Put(blkID, blk)
return blk, nil
}
func (s *state) AddBlock(block block.Block) {
blkID := block.ID()
s.addedBlockIDs[block.Height()] = blkID
s.addedBlocks[blkID] = block
}
func (s *state) InitializeChainState(stopVertexID ids.ID, genesisTimestamp time.Time) error {
lastAccepted, err := database.GetID(s.singletonDB, lastAcceptedKey)
if err == database.ErrNotFound {
return s.initializeChainState(stopVertexID, genesisTimestamp)
} else if err != nil {
return err
}
s.lastAccepted = lastAccepted
s.persistedLastAccepted = lastAccepted
s.timestamp, err = database.GetTimestamp(s.singletonDB, timestampKey)
s.persistedTimestamp = s.timestamp
return err
}
func (s *state) initializeChainState(stopVertexID ids.ID, genesisTimestamp time.Time) error {
genesis, err := block.NewStandardBlock(
stopVertexID,
0,
genesisTimestamp,
nil,
s.parser.Codec(),
)
if err != nil {
return err
}
s.SetLastAccepted(genesis.ID())
s.SetTimestamp(genesis.Timestamp())
s.AddBlock(genesis)
return s.Commit()
}
func (s *state) IsInitialized() (bool, error) {
return s.singletonDB.Has(isInitializedKey)
}
func (s *state) SetInitialized() error {
return s.singletonDB.Put(isInitializedKey, nil)
}
func (s *state) GetLastAccepted() ids.ID {
return s.lastAccepted
}
func (s *state) SetLastAccepted(lastAccepted ids.ID) {
s.lastAccepted = lastAccepted
}
func (s *state) GetTimestamp() time.Time {
return s.timestamp
}
func (s *state) SetTimestamp(t time.Time) {
s.timestamp = t
}
func (s *state) Commit() error {
defer s.Abort()
batch, err := s.CommitBatch()
if err != nil {
return err
}
return batch.Write()
}
func (s *state) Abort() {
s.db.Abort()
}
func (s *state) CommitBatch() (database.Batch, error) {
if err := s.write(); err != nil {
return nil, err
}
return s.db.CommitBatch()
}
func (s *state) Close() error {
return utils.Err(
s.utxoDB.Close(),
s.txDB.Close(),
s.blockIDDB.Close(),
s.blockDB.Close(),
s.singletonDB.Close(),
s.db.Close(),
)
}
func (s *state) write() error {
return utils.Err(
s.writeUTXOs(),
s.writeTxs(),
s.writeBlockIDs(),
s.writeBlocks(),
s.writeMetadata(),
)
}
func (s *state) writeUTXOs() error {
for utxoID, utxo := range s.modifiedUTXOs {
delete(s.modifiedUTXOs, utxoID)
if utxo != nil {
if err := s.utxoState.PutUTXO(utxo); err != nil {
return fmt.Errorf("failed to add utxo: %w", err)
}
} else {
if err := s.utxoState.DeleteUTXO(utxoID); err != nil {
return fmt.Errorf("failed to remove utxo: %w", err)
}
}
}
return nil
}
func (s *state) writeTxs() error {
for txID, tx := range s.addedTxs {
txID := txID
txBytes := tx.Bytes()
delete(s.addedTxs, txID)
s.txCache.Put(txID, tx)
if err := s.txDB.Put(txID[:], txBytes); err != nil {
return fmt.Errorf("failed to add tx: %w", err)
}
}
return nil
}
func (s *state) writeBlockIDs() error {
for height, blkID := range s.addedBlockIDs {
heightKey := database.PackUInt64(height)
delete(s.addedBlockIDs, height)
s.blockIDCache.Put(height, blkID)
if err := database.PutID(s.blockIDDB, heightKey, blkID); err != nil {
return fmt.Errorf("failed to add blockID: %w", err)
}
}
return nil
}
func (s *state) writeBlocks() error {
for blkID, blk := range s.addedBlocks {
blkID := blkID
blkBytes := blk.Bytes()
delete(s.addedBlocks, blkID)
s.blockCache.Put(blkID, blk)
if err := s.blockDB.Put(blkID[:], blkBytes); err != nil {
return fmt.Errorf("failed to add block: %w", err)
}
}
return nil
}
func (s *state) writeMetadata() error {
if !s.persistedTimestamp.Equal(s.timestamp) {
if err := database.PutTimestamp(s.singletonDB, timestampKey, s.timestamp); err != nil {
return fmt.Errorf("failed to write timestamp: %w", err)
}
s.persistedTimestamp = s.timestamp
}
if s.persistedLastAccepted != s.lastAccepted {
if err := database.PutID(s.singletonDB, lastAcceptedKey, s.lastAccepted); err != nil {
return fmt.Errorf("failed to write last accepted: %w", err)
}
s.persistedLastAccepted = s.lastAccepted
}
return nil
}
func (s *state) Checksums() (ids.ID, ids.ID) {
return s.txChecksum, s.utxoState.Checksum()
}
func (s *state) initTxChecksum() error {
if !s.trackChecksum {
return nil
}
txIt := s.txDB.NewIterator()
defer txIt.Release()
for txIt.Next() {
txIDBytes := txIt.Key()
txID, err := ids.ToID(txIDBytes)
if err != nil {
return err
}
s.updateTxChecksum(txID)
}
return txIt.Error()
}
func (s *state) updateTxChecksum(modifiedID ids.ID) {
if !s.trackChecksum {
return
}
s.txChecksum = s.txChecksum.XOR(modifiedID)
}