/
db.go
1399 lines (1194 loc) · 37.6 KB
/
db.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 merkledb
import (
"bytes"
"context"
"errors"
"fmt"
"runtime"
"slices"
"sync"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel/attribute"
"golang.org/x/exp/maps"
"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/trace"
"github.com/ava-labs/avalanchego/utils"
"github.com/ava-labs/avalanchego/utils/maybe"
"github.com/ava-labs/avalanchego/utils/set"
"github.com/ava-labs/avalanchego/utils/units"
oteltrace "go.opentelemetry.io/otel/trace"
)
const (
// TODO: name better
rebuildViewSizeFractionOfCacheSize = 50
minRebuildViewSizePerCommit = 1000
clearBatchSize = units.MiB
rebuildIntermediateDeletionWriteSize = units.MiB
valueNodePrefixLen = 1
cacheEntryOverHead = 8
)
var (
_ MerkleDB = (*merkleDB)(nil)
metadataPrefix = []byte{0}
valueNodePrefix = []byte{1}
intermediateNodePrefix = []byte{2}
// cleanShutdownKey is used to flag that the database did (or did not)
// previously shutdown correctly.
//
// If this key has value [hadCleanShutdown] it must be true that all
// intermediate nodes of the trie are correctly populated on disk and that
// the [rootDBKey] has the correct key for the root node.
//
// If this key has value [didNotHaveCleanShutdown] the intermediate nodes of
// the trie may not be correct and the [rootDBKey] may not exist or point to
// a node that node longer exists.
//
// Regardless of the value of [cleanShutdownKey], the value nodes must
// always be persisted correctly.
cleanShutdownKey = []byte(string(metadataPrefix) + "cleanShutdown")
rootDBKey = []byte(string(metadataPrefix) + "root")
hadCleanShutdown = []byte{1}
didNotHaveCleanShutdown = []byte{0}
errSameRoot = errors.New("start and end root are the same")
)
type ChangeProofer interface {
// GetChangeProof returns a proof for a subset of the key/value changes in key range
// [start, end] that occurred between [startRootID] and [endRootID].
// Returns at most [maxLength] key/value pairs.
// Returns [ErrInsufficientHistory] if this node has insufficient history
// to generate the proof.
// Returns ErrEmptyProof if [endRootID] is ids.Empty.
// Note that [endRootID] == ids.Empty means the trie is empty
// (i.e. we don't need a change proof.)
// Returns [ErrNoEndRoot], which wraps [ErrInsufficientHistory], if the
// history doesn't contain the [endRootID].
GetChangeProof(
ctx context.Context,
startRootID ids.ID,
endRootID ids.ID,
start maybe.Maybe[[]byte],
end maybe.Maybe[[]byte],
maxLength int,
) (*ChangeProof, error)
// Returns nil iff all the following hold:
// - [start] <= [end].
// - [proof] is non-empty.
// - All keys in [proof.KeyValues] and [proof.DeletedKeys] are in [start, end].
// If [start] is nothing, all keys are considered > [start].
// If [end] is nothing, all keys are considered < [end].
// - [proof.KeyValues] and [proof.DeletedKeys] are sorted in order of increasing key.
// - [proof.StartProof] and [proof.EndProof] are well-formed.
// - When the changes in [proof.KeyChanes] are applied,
// the root ID of the database is [expectedEndRootID].
VerifyChangeProof(
ctx context.Context,
proof *ChangeProof,
start maybe.Maybe[[]byte],
end maybe.Maybe[[]byte],
expectedEndRootID ids.ID,
) error
// CommitChangeProof commits the key/value pairs within the [proof] to the db.
CommitChangeProof(ctx context.Context, proof *ChangeProof) error
}
type RangeProofer interface {
// GetRangeProofAtRoot returns a proof for the key/value pairs in this trie within the range
// [start, end] when the root of the trie was [rootID].
// If [start] is Nothing, there's no lower bound on the range.
// If [end] is Nothing, there's no upper bound on the range.
// Returns ErrEmptyProof if [rootID] is ids.Empty.
// Note that [rootID] == ids.Empty means the trie is empty
// (i.e. we don't need a range proof.)
GetRangeProofAtRoot(
ctx context.Context,
rootID ids.ID,
start maybe.Maybe[[]byte],
end maybe.Maybe[[]byte],
maxLength int,
) (*RangeProof, error)
// CommitRangeProof commits the key/value pairs within the [proof] to the db.
// [start] is the smallest possible key in the range this [proof] covers.
// [end] is the largest possible key in the range this [proof] covers.
CommitRangeProof(ctx context.Context, start, end maybe.Maybe[[]byte], proof *RangeProof) error
}
type Clearer interface {
// Deletes all key/value pairs from the database
// and clears the change history.
Clear() error
}
type Prefetcher interface {
// PrefetchPath attempts to load all trie nodes on the path of [key]
// into the cache.
PrefetchPath(key []byte) error
// PrefetchPaths attempts to load all trie nodes on the paths of [keys]
// into the cache.
//
// Using PrefetchPaths can be more efficient than PrefetchPath because
// the underlying view used to compute each path can be reused.
PrefetchPaths(keys [][]byte) error
}
type MerkleDB interface {
database.Database
Clearer
Trie
MerkleRootGetter
ProofGetter
ChangeProofer
RangeProofer
Prefetcher
}
type Config struct {
// BranchFactor determines the number of children each node can have.
BranchFactor BranchFactor
// Hasher defines the hash function to use when hashing the trie.
//
// If not specified, [DefaultHasher] will be used.
Hasher Hasher
// RootGenConcurrency is the number of goroutines to use when
// generating a new state root.
//
// If 0 is specified, [runtime.NumCPU] will be used.
RootGenConcurrency uint
// The number of changes to the database that we store in memory in order to
// serve change proofs.
HistoryLength uint
// The number of bytes used to cache nodes with values.
ValueNodeCacheSize uint
// The number of bytes used to cache nodes without values.
IntermediateNodeCacheSize uint
// The number of bytes used to store nodes without values in memory before forcing them onto disk.
IntermediateWriteBufferSize uint
// The number of bytes to write to disk when intermediate nodes are evicted
// from the write buffer and written to disk.
IntermediateWriteBatchSize uint
// If [Reg] is nil, metrics are collected locally but not exported through
// Prometheus.
// This may be useful for testing.
Reg prometheus.Registerer
TraceLevel TraceLevel
Tracer trace.Tracer
}
// merkleDB can only be edited by committing changes from a view.
type merkleDB struct {
// Must be held when reading/writing fields.
lock sync.RWMutex
// Must be held when preparing work to be committed to the DB.
// Used to prevent editing of the trie without restricting read access
// until the full set of changes is ready to be written.
// Should be held before taking [db.lock]
commitLock sync.RWMutex
// Contains all the key-value pairs stored by this database,
// including metadata, intermediate nodes and value nodes.
baseDB database.Database
valueNodeDB *valueNodeDB
intermediateNodeDB *intermediateNodeDB
// Stores change lists. Used to serve change proofs and construct
// historical views of the trie.
history *trieHistory
// True iff the db has been closed.
closed bool
metrics metrics
debugTracer trace.Tracer
infoTracer trace.Tracer
// The root of this trie.
// Nothing if the trie is empty.
root maybe.Maybe[*node]
rootID ids.ID
// Valid children of this trie.
childViews []*view
// hashNodesKeyPool controls the number of goroutines that are created
// inside [hashChangedNode] at any given time and provides slices for the
// keys needed while hashing.
hashNodesKeyPool *bytesPool
tokenSize int
hasher Hasher
}
// New returns a new merkle database.
func New(ctx context.Context, db database.Database, config Config) (MerkleDB, error) {
metrics, err := newMetrics("merkledb", config.Reg)
if err != nil {
return nil, err
}
return newDatabase(ctx, db, config, metrics)
}
func newDatabase(
ctx context.Context,
db database.Database,
config Config,
metrics metrics,
) (*merkleDB, error) {
if err := config.BranchFactor.Valid(); err != nil {
return nil, err
}
hasher := config.Hasher
if hasher == nil {
hasher = DefaultHasher
}
rootGenConcurrency := runtime.NumCPU()
if config.RootGenConcurrency != 0 {
rootGenConcurrency = int(config.RootGenConcurrency)
}
// Share a bytes pool between the intermediateNodeDB and valueNodeDB to
// reduce memory allocations.
bufferPool := utils.NewBytesPool()
trieDB := &merkleDB{
metrics: metrics,
baseDB: db,
intermediateNodeDB: newIntermediateNodeDB(
db,
bufferPool,
metrics,
int(config.IntermediateNodeCacheSize),
int(config.IntermediateWriteBufferSize),
int(config.IntermediateWriteBatchSize),
BranchFactorToTokenSize[config.BranchFactor],
hasher,
),
valueNodeDB: newValueNodeDB(
db,
bufferPool,
metrics,
int(config.ValueNodeCacheSize),
hasher,
),
history: newTrieHistory(int(config.HistoryLength)),
debugTracer: getTracerIfEnabled(config.TraceLevel, DebugTrace, config.Tracer),
infoTracer: getTracerIfEnabled(config.TraceLevel, InfoTrace, config.Tracer),
childViews: make([]*view, 0, defaultPreallocationSize),
hashNodesKeyPool: newBytesPool(rootGenConcurrency),
tokenSize: BranchFactorToTokenSize[config.BranchFactor],
hasher: hasher,
}
shutdownType, err := trieDB.baseDB.Get(cleanShutdownKey)
switch err {
case nil:
case database.ErrNotFound:
// If the marker wasn't found then the DB is being created for the first
// time and there is nothing to do.
shutdownType = hadCleanShutdown
default:
return nil, err
}
if bytes.Equal(shutdownType, didNotHaveCleanShutdown) {
if err := trieDB.rebuild(ctx, int(config.ValueNodeCacheSize)); err != nil {
return nil, err
}
} else {
if err := trieDB.initializeRoot(); err != nil {
return nil, err
}
}
// add current root to history (has no changes)
trieDB.history.record(&changeSummary{
rootID: trieDB.rootID,
rootChange: change[maybe.Maybe[*node]]{
after: trieDB.root,
},
values: map[Key]*change[maybe.Maybe[[]byte]]{},
nodes: map[Key]*change[*node]{},
})
// mark that the db has not yet been cleanly closed
err = trieDB.baseDB.Put(cleanShutdownKey, didNotHaveCleanShutdown)
return trieDB, err
}
// Deletes every intermediate node and rebuilds them by re-adding every key/value.
// TODO: make this more efficient by only clearing out the stale portions of the trie.
func (db *merkleDB) rebuild(ctx context.Context, cacheSize int) error {
db.root = maybe.Nothing[*node]()
db.rootID = ids.Empty
// Delete intermediate nodes.
if err := database.ClearPrefix(db.baseDB, intermediateNodePrefix, rebuildIntermediateDeletionWriteSize); err != nil {
return err
}
// Add all key-value pairs back into the database.
opsSizeLimit := max(
cacheSize/rebuildViewSizeFractionOfCacheSize,
minRebuildViewSizePerCommit,
)
currentOps := make([]database.BatchOp, 0, opsSizeLimit)
valueIt := db.NewIterator()
// ensure valueIt is captured and release gets called on the latest copy of valueIt
defer func() { valueIt.Release() }()
for valueIt.Next() {
if len(currentOps) >= opsSizeLimit {
view, err := newView(db, db, ViewChanges{BatchOps: currentOps, ConsumeBytes: true})
if err != nil {
return err
}
if err := view.commitToDB(ctx); err != nil {
return err
}
currentOps = make([]database.BatchOp, 0, opsSizeLimit)
// reset the iterator to prevent memory bloat
nextValue := valueIt.Key()
valueIt.Release()
valueIt = db.NewIteratorWithStart(nextValue)
continue
}
currentOps = append(currentOps, database.BatchOp{
Key: valueIt.Key(),
Value: valueIt.Value(),
})
}
if err := valueIt.Error(); err != nil {
return err
}
view, err := newView(db, db, ViewChanges{BatchOps: currentOps, ConsumeBytes: true})
if err != nil {
return err
}
if err := view.commitToDB(ctx); err != nil {
return err
}
return db.Compact(nil, nil)
}
func (db *merkleDB) CommitChangeProof(ctx context.Context, proof *ChangeProof) error {
db.commitLock.Lock()
defer db.commitLock.Unlock()
if db.closed {
return database.ErrClosed
}
ops := make([]database.BatchOp, len(proof.KeyChanges))
for i, kv := range proof.KeyChanges {
ops[i] = database.BatchOp{
Key: kv.Key,
Value: kv.Value.Value(),
Delete: kv.Value.IsNothing(),
}
}
view, err := newView(db, db, ViewChanges{BatchOps: ops})
if err != nil {
return err
}
return view.commitToDB(ctx)
}
func (db *merkleDB) CommitRangeProof(ctx context.Context, start, end maybe.Maybe[[]byte], proof *RangeProof) error {
db.commitLock.Lock()
defer db.commitLock.Unlock()
if db.closed {
return database.ErrClosed
}
ops := make([]database.BatchOp, len(proof.KeyValues))
keys := set.NewSet[string](len(proof.KeyValues))
for i, kv := range proof.KeyValues {
keys.Add(string(kv.Key))
ops[i] = database.BatchOp{
Key: kv.Key,
Value: kv.Value,
}
}
largestKey := end
if len(proof.KeyValues) > 0 {
largestKey = maybe.Some(proof.KeyValues[len(proof.KeyValues)-1].Key)
}
keysToDelete, err := db.getKeysNotInSet(start, largestKey, keys)
if err != nil {
return err
}
for _, keyToDelete := range keysToDelete {
ops = append(ops, database.BatchOp{
Key: keyToDelete,
Delete: true,
})
}
// Don't need to lock [view] because nobody else has a reference to it.
view, err := newView(db, db, ViewChanges{BatchOps: ops})
if err != nil {
return err
}
return view.commitToDB(ctx)
}
func (db *merkleDB) Compact(start []byte, limit []byte) error {
if db.closed {
return database.ErrClosed
}
return db.baseDB.Compact(start, limit)
}
func (db *merkleDB) Close() error {
db.commitLock.Lock()
defer db.commitLock.Unlock()
db.lock.Lock()
defer db.lock.Unlock()
if db.closed {
return database.ErrClosed
}
// mark all children as no longer valid because the db has closed
db.invalidateChildrenExcept(nil)
db.closed = true
db.valueNodeDB.Close()
// Flush intermediary nodes to disk.
if err := db.intermediateNodeDB.Flush(); err != nil {
return err
}
var (
batch = db.baseDB.NewBatch()
err error
)
// Write the root key
if db.root.IsNothing() {
err = batch.Delete(rootDBKey)
} else {
rootKey := encodeKey(db.root.Value().key)
err = batch.Put(rootDBKey, rootKey)
}
if err != nil {
return err
}
// Write the clean shutdown marker
if err := batch.Put(cleanShutdownKey, hadCleanShutdown); err != nil {
return err
}
return batch.Write()
}
func (db *merkleDB) PrefetchPaths(keys [][]byte) error {
db.commitLock.RLock()
defer db.commitLock.RUnlock()
if db.closed {
return database.ErrClosed
}
for _, key := range keys {
if err := db.prefetchPath(key); err != nil {
return err
}
}
return nil
}
func (db *merkleDB) PrefetchPath(key []byte) error {
db.commitLock.RLock()
defer db.commitLock.RUnlock()
if db.closed {
return database.ErrClosed
}
return db.prefetchPath(key)
}
func (db *merkleDB) prefetchPath(keyBytes []byte) error {
return visitPathToKey(db, ToKey(keyBytes), func(n *node) error {
if n.hasValue() {
db.valueNodeDB.nodeCache.Put(n.key, n)
} else {
db.intermediateNodeDB.nodeCache.Put(n.key, n)
}
return nil
})
}
func (db *merkleDB) Get(key []byte) ([]byte, error) {
// this is a duplicate because the database interface doesn't support
// contexts, which are used for tracing
return db.GetValue(context.Background(), key)
}
func (db *merkleDB) GetValues(ctx context.Context, keys [][]byte) ([][]byte, []error) {
_, span := db.debugTracer.Start(ctx, "MerkleDB.GetValues", oteltrace.WithAttributes(
attribute.Int("keyCount", len(keys)),
))
defer span.End()
// Lock to ensure no commit happens during the reads.
db.lock.RLock()
defer db.lock.RUnlock()
values := make([][]byte, len(keys))
getErrors := make([]error, len(keys))
for i, key := range keys {
values[i], getErrors[i] = db.getValueCopy(ToKey(key))
}
return values, getErrors
}
// GetValue returns the value associated with [key].
// Returns database.ErrNotFound if it doesn't exist.
func (db *merkleDB) GetValue(ctx context.Context, key []byte) ([]byte, error) {
_, span := db.debugTracer.Start(ctx, "MerkleDB.GetValue")
defer span.End()
db.lock.RLock()
defer db.lock.RUnlock()
return db.getValueCopy(ToKey(key))
}
// getValueCopy returns a copy of the value for the given [key].
// Returns database.ErrNotFound if it doesn't exist.
// Assumes [db.lock] is read locked.
func (db *merkleDB) getValueCopy(key Key) ([]byte, error) {
val, err := db.getValueWithoutLock(key)
if err != nil {
return nil, err
}
return slices.Clone(val), nil
}
// getValue returns the value for the given [key].
// Returns database.ErrNotFound if it doesn't exist.
// Assumes [db.lock] isn't held.
func (db *merkleDB) getValue(key Key) ([]byte, error) {
db.lock.RLock()
defer db.lock.RUnlock()
return db.getValueWithoutLock(key)
}
// getValueWithoutLock returns the value for the given [key].
// Returns database.ErrNotFound if it doesn't exist.
// Assumes [db.lock] is read locked.
func (db *merkleDB) getValueWithoutLock(key Key) ([]byte, error) {
if db.closed {
return nil, database.ErrClosed
}
n, err := db.getNode(key, true /* hasValue */)
if err != nil {
return nil, err
}
if n.value.IsNothing() {
return nil, database.ErrNotFound
}
return n.value.Value(), nil
}
func (db *merkleDB) GetMerkleRoot(ctx context.Context) (ids.ID, error) {
_, span := db.infoTracer.Start(ctx, "MerkleDB.GetMerkleRoot")
defer span.End()
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return ids.Empty, database.ErrClosed
}
return db.getMerkleRoot(), nil
}
// Assumes [db.lock] or [db.commitLock] is read locked.
func (db *merkleDB) getMerkleRoot() ids.ID {
return db.rootID
}
func (db *merkleDB) GetProof(ctx context.Context, key []byte) (*Proof, error) {
db.commitLock.RLock()
defer db.commitLock.RUnlock()
_, span := db.infoTracer.Start(ctx, "MerkleDB.GetProof")
defer span.End()
if db.closed {
return nil, database.ErrClosed
}
return getProof(db, key)
}
func (db *merkleDB) GetRangeProof(
ctx context.Context,
start maybe.Maybe[[]byte],
end maybe.Maybe[[]byte],
maxLength int,
) (*RangeProof, error) {
db.commitLock.RLock()
defer db.commitLock.RUnlock()
_, span := db.infoTracer.Start(ctx, "MerkleDB.GetRangeProof")
defer span.End()
if db.closed {
return nil, database.ErrClosed
}
return getRangeProof(db, start, end, maxLength)
}
func (db *merkleDB) GetRangeProofAtRoot(
ctx context.Context,
rootID ids.ID,
start maybe.Maybe[[]byte],
end maybe.Maybe[[]byte],
maxLength int,
) (*RangeProof, error) {
db.commitLock.RLock()
defer db.commitLock.RUnlock()
_, span := db.infoTracer.Start(ctx, "MerkleDB.GetRangeProofAtRoot")
defer span.End()
switch {
case db.closed:
return nil, database.ErrClosed
case maxLength <= 0:
return nil, fmt.Errorf("%w but was %d", ErrInvalidMaxLength, maxLength)
case rootID == ids.Empty:
return nil, ErrEmptyProof
}
historicalTrie, err := db.getTrieAtRootForRange(rootID, start, end)
if err != nil {
return nil, err
}
return getRangeProof(historicalTrie, start, end, maxLength)
}
func (db *merkleDB) GetChangeProof(
ctx context.Context,
startRootID ids.ID,
endRootID ids.ID,
start maybe.Maybe[[]byte],
end maybe.Maybe[[]byte],
maxLength int,
) (*ChangeProof, error) {
_, span := db.infoTracer.Start(ctx, "MerkleDB.GetChangeProof")
defer span.End()
switch {
case start.HasValue() && end.HasValue() && bytes.Compare(start.Value(), end.Value()) == 1:
return nil, ErrStartAfterEnd
case startRootID == endRootID:
return nil, errSameRoot
case endRootID == ids.Empty:
return nil, ErrEmptyProof
}
db.commitLock.RLock()
defer db.commitLock.RUnlock()
if db.closed {
return nil, database.ErrClosed
}
changes, err := db.history.getValueChanges(startRootID, endRootID, start, end, maxLength)
if err != nil {
return nil, err
}
// [changedKeys] are a subset of the keys that were added or had their
// values modified between [startRootID] to [endRootID] sorted in increasing
// order.
changedKeys := maps.Keys(changes.values)
utils.Sort(changedKeys)
result := &ChangeProof{
KeyChanges: make([]KeyChange, 0, len(changedKeys)),
}
for _, key := range changedKeys {
change := changes.values[key]
result.KeyChanges = append(result.KeyChanges, KeyChange{
Key: key.Bytes(),
// create a copy so edits of the []byte don't affect the db
Value: maybe.Bind(change.after, slices.Clone[[]byte]),
})
}
largestKey := end
if len(result.KeyChanges) > 0 {
largestKey = maybe.Some(result.KeyChanges[len(result.KeyChanges)-1].Key)
}
// Since we hold [db.commitlock] we must still have sufficient
// history to recreate the trie at [endRootID].
historicalTrie, err := db.getTrieAtRootForRange(endRootID, start, largestKey)
if err != nil {
return nil, err
}
if largestKey.HasValue() {
endProof, err := getProof(historicalTrie, largestKey.Value())
if err != nil {
return nil, err
}
result.EndProof = endProof.Path
}
if start.HasValue() {
startProof, err := getProof(historicalTrie, start.Value())
if err != nil {
return nil, err
}
result.StartProof = startProof.Path
// strip out any common nodes to reduce proof size
commonNodeIndex := 0
for ; commonNodeIndex < len(result.StartProof) &&
commonNodeIndex < len(result.EndProof) &&
result.StartProof[commonNodeIndex].Key == result.EndProof[commonNodeIndex].Key; commonNodeIndex++ {
}
result.StartProof = result.StartProof[commonNodeIndex:]
}
// Note that one of the following must be true:
// - [result.StartProof] is non-empty.
// - [result.EndProof] is non-empty.
// - [result.KeyValues] is non-empty.
// - [result.DeletedKeys] is non-empty.
// If all of these were false, it would mean that no
// [start] and [end] were given, and no diff between
// the trie at [startRootID] and [endRootID] was found.
// Since [startRootID] != [endRootID], this is impossible.
return result, nil
}
// NewView returns a new view on top of this Trie where the passed changes
// have been applied.
//
// Changes made to the view will only be reflected in the original trie if
// Commit is called.
//
// Assumes [db.commitLock] and [db.lock] aren't held.
func (db *merkleDB) NewView(
_ context.Context,
changes ViewChanges,
) (View, error) {
// ensure the db doesn't change while creating the new view
db.commitLock.RLock()
defer db.commitLock.RUnlock()
if db.closed {
return nil, database.ErrClosed
}
view, err := newView(db, db, changes)
if err != nil {
return nil, err
}
// ensure access to childViews is protected
db.lock.Lock()
defer db.lock.Unlock()
db.childViews = append(db.childViews, view)
return view, nil
}
func (db *merkleDB) Has(k []byte) (bool, error) {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return false, database.ErrClosed
}
_, err := db.getValueWithoutLock(ToKey(k))
if errors.Is(err, database.ErrNotFound) {
return false, nil
}
return err == nil, err
}
func (db *merkleDB) HealthCheck(ctx context.Context) (interface{}, error) {
db.lock.RLock()
defer db.lock.RUnlock()
if db.closed {
return nil, database.ErrClosed
}
return db.baseDB.HealthCheck(ctx)
}
func (db *merkleDB) NewBatch() database.Batch {
return &batch{
db: db,
}
}
func (db *merkleDB) NewIterator() database.Iterator {
return db.NewIteratorWithStartAndPrefix(nil, nil)
}
func (db *merkleDB) NewIteratorWithStart(start []byte) database.Iterator {
return db.NewIteratorWithStartAndPrefix(start, nil)
}
func (db *merkleDB) NewIteratorWithPrefix(prefix []byte) database.Iterator {
return db.NewIteratorWithStartAndPrefix(nil, prefix)
}
func (db *merkleDB) NewIteratorWithStartAndPrefix(start, prefix []byte) database.Iterator {
return db.valueNodeDB.newIteratorWithStartAndPrefix(start, prefix)
}
func (db *merkleDB) Put(k, v []byte) error {
return db.PutContext(context.Background(), k, v)
}
// Same as [Put] but takes in a context used for tracing.
func (db *merkleDB) PutContext(ctx context.Context, k, v []byte) error {
db.commitLock.Lock()
defer db.commitLock.Unlock()
if db.closed {
return database.ErrClosed
}
view, err := newView(db, db, ViewChanges{BatchOps: []database.BatchOp{{Key: k, Value: v}}})
if err != nil {
return err
}
return view.commitToDB(ctx)
}
func (db *merkleDB) Delete(key []byte) error {
return db.DeleteContext(context.Background(), key)
}
func (db *merkleDB) DeleteContext(ctx context.Context, key []byte) error {
db.commitLock.Lock()
defer db.commitLock.Unlock()
if db.closed {
return database.ErrClosed
}
view, err := newView(db, db,
ViewChanges{
BatchOps: []database.BatchOp{{
Key: key,
Delete: true,
}},
ConsumeBytes: true,
})
if err != nil {
return err
}
return view.commitToDB(ctx)
}
// Assumes values inside [ops] are safe to reference after the function
// returns. Assumes [db.lock] isn't held.
func (db *merkleDB) commitBatch(ops []database.BatchOp) error {
db.commitLock.Lock()
defer db.commitLock.Unlock()
if db.closed {
return database.ErrClosed
}
view, err := newView(db, db, ViewChanges{BatchOps: ops, ConsumeBytes: true})
if err != nil {
return err
}
return view.commitToDB(context.Background())
}
// commitView commits the changes in [trieToCommit] to [db].
// Assumes [trieToCommit]'s node IDs have been calculated.
// Assumes [db.commitLock] is held.
func (db *merkleDB) commitView(ctx context.Context, trieToCommit *view) error {
db.lock.Lock()
defer db.lock.Unlock()
switch {
case db.closed:
return database.ErrClosed
case trieToCommit == nil:
return nil
case trieToCommit.isInvalid():
return ErrInvalid
case trieToCommit.committed:
return ErrCommitted
case trieToCommit.db != trieToCommit.getParentTrie():
return ErrParentNotDatabase
}
changes := trieToCommit.changes
_, span := db.infoTracer.Start(ctx, "MerkleDB.commitView", oteltrace.WithAttributes(
attribute.Int("nodesChanged", len(changes.nodes)),
attribute.Int("valuesChanged", len(changes.values)),
))
defer span.End()
// invalidate all child views except for the view being committed
db.invalidateChildrenExcept(trieToCommit)
// move any child views of the committed trie onto the db
db.moveChildViewsToDB(trieToCommit)
if len(changes.nodes) == 0 {
return nil
}
valueNodeBatch := db.baseDB.NewBatch()
if err := db.applyChanges(ctx, valueNodeBatch, changes); err != nil {
return err
}
if err := db.commitValueChanges(ctx, valueNodeBatch); err != nil {
return err
}
db.history.record(changes)
// Update root in database.
db.root = changes.rootChange.after
db.rootID = changes.rootID
return nil