-
Notifications
You must be signed in to change notification settings - Fork 133
/
Copy pathiterator.go
655 lines (596 loc) · 15.4 KB
/
iterator.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
// Copyright 2024 ChainSafe Systems (ON)
// SPDX-License-Identifier: LGPL-3.0-only
package triedb
import (
"bytes"
"fmt"
"iter"
"github.com/ChainSafe/gossamer/pkg/trie/triedb/codec"
"github.com/ChainSafe/gossamer/pkg/trie/triedb/hash"
"github.com/ChainSafe/gossamer/pkg/trie/triedb/nibbles"
)
type (
status interface {
isStatus()
}
statusEntering struct{}
statusAt struct{}
statusAtChild uint
statusExiting struct{}
statusAftExiting struct{}
)
func (statusEntering) isStatus() {}
func (statusAt) isStatus() {}
func (statusAtChild) isStatus() {}
func (statusExiting) isStatus() {}
func (statusAftExiting) isStatus() {}
type crumb[H hash.Hash] struct {
hash *H
node codec.EncodedNode
status
}
func (c *crumb[H]) step(fwd bool) {
switch status := c.status.(type) {
case statusEntering:
switch c.node.(type) {
case codec.Branch:
c.status = statusAt{}
default:
c.status = statusExiting{}
}
case statusAt:
switch c.node.(type) {
case codec.Branch:
if fwd {
c.status = statusAtChild(0)
} else {
c.status = statusAtChild(15)
}
default:
c.status = statusExiting{}
}
case statusAtChild:
switch c.node.(type) {
case codec.Branch:
if fwd && status < 15 {
c.status = status + 1
} else if !fwd && status > 15 {
c.status = status - 1
} else {
c.status = statusExiting{}
}
}
case statusExiting:
c.status = statusAftExiting{}
default:
c.status = statusExiting{}
}
}
type extractedKey struct {
Key []byte
Padding *byte
Value codec.EncodedValue
}
type rawItem[H hash.Hash] struct {
nibbles.NibbleSlice
hash *H
codec.EncodedNode
}
// Extracts the key from the result of a raw item retrieval.
//
// Given a raw item, it extracts the key information, including the key bytes, an optional
// extra nibble (prefix padding), and the node value.
func (ri rawItem[H]) extractKey() *extractedKey {
prefix := ri.NibbleSlice
node := ri.EncodedNode
var value codec.EncodedValue
switch node := node.(type) {
case codec.Leaf:
prefix.AppendPartial(node.PartialKey.RightPartial())
value = node.Value
case codec.Branch:
prefix.AppendPartial(node.PartialKey.RightPartial())
if node.Value == nil {
return nil
}
value = node.Value
default:
return nil
}
p := prefix.Prefix()
return &extractedKey{
Key: p.Key,
Padding: p.Padded,
Value: value,
}
}
type TrieDBRawIterator[H hash.Hash, Hasher hash.Hasher[H]] struct {
// Forward trail of nodes to visit.
trail []crumb[H]
// Forward iteration key nibbles of the current node.
keyNibbles nibbles.NibbleSlice
db *TrieDB[H, Hasher]
}
// Create a new iterator.
func NewTrieDBRawIterator[H hash.Hash, Hasher hash.Hasher[H]](
db *TrieDB[H, Hasher],
) (*TrieDBRawIterator[H, Hasher], error) {
rootNode, rootHash, err := db.getNodeOrLookup(
codec.HashedNode[H]{Hash: db.rootHash},
nibbles.Prefix{},
true,
)
if err != nil {
return nil, err
}
r := TrieDBRawIterator[H, Hasher]{
db: db,
}
r.descend(rootNode, rootHash)
return &r, nil
}
// Create a new iterator, but limited to a given prefix.
func NewPrefixedTrieDBRawIterator[H hash.Hash, Hasher hash.Hasher[H]](
db *TrieDB[H, Hasher], prefix []byte,
) (*TrieDBRawIterator[H, Hasher], error) {
iter, err := NewTrieDBRawIterator(db)
if err != nil {
return nil, err
}
err = iter.prefix(prefix, true)
if err != nil {
return nil, err
}
return iter, nil
}
// Create a new iterator, but limited to a given prefix.
// It then do a seek operation from prefixed context (using seek lose
// prefix context by default).
func NewPrefixedTrieDBRawIteratorThenSeek[H hash.Hash, Hasher hash.Hasher[H]](
db *TrieDB[H, Hasher], prefix []byte, seek []byte,
) (*TrieDBRawIterator[H, Hasher], error) {
iter, err := NewTrieDBRawIterator(db)
if err != nil {
return nil, err
}
err = iter.prefixThenSeek(prefix, seek)
if err != nil {
return nil, err
}
return iter, nil
}
// Descend into a node.
func (ri *TrieDBRawIterator[H, Hasher]) descend(node codec.EncodedNode, nodeHash *H) {
ri.trail = append(ri.trail, crumb[H]{
hash: nodeHash,
status: statusEntering{},
node: node,
})
}
// Seek a node position at key for iterator.
// Returns true if the cursor is at or after the key, but still shares
// a common prefix with the key, return false if the key do not
// share its prefix with the node.
// This indicates if there is still nodes to iterate over in the case
// where we limit iteration to key as a prefix.
func (ri *TrieDBRawIterator[H, Hasher]) seek(keyBytes []byte, fwd bool) (bool, error) {
ri.trail = nil
ri.keyNibbles.Clear()
key := nibbles.NewNibbles(keyBytes)
node, nodeHash, err := ri.db.getNodeOrLookup(
codec.HashedNode[H]{Hash: ri.db.rootHash}, nibbles.Prefix{}, true,
)
if err != nil {
return false, err
}
partial := key
var fullKeyNibbles uint
for {
var (
nextNode codec.EncodedNode
nextNodeHash *H
)
ri.descend(node, nodeHash)
crumb := &ri.trail[len(ri.trail)-1]
switch node := crumb.node.(type) {
case codec.Leaf:
if (fwd && node.PartialKey.Compare(partial) == -1) ||
(!fwd && node.PartialKey.Compare(partial) == 1) {
crumb.status = statusAftExiting{}
return false, nil
}
return node.PartialKey.StartsWith(partial), nil
case codec.Branch:
pk := node.PartialKey
if !partial.StartsWith(pk) {
if (fwd && pk.Compare(partial) == -1) ||
(!fwd && pk.Compare(partial) == 1) {
crumb.status = statusAftExiting{}
return false, nil
}
return pk.StartsWith(partial), nil
}
fullKeyNibbles += pk.Len()
partial = partial.Mid(pk.Len())
if partial.Len() == 0 {
return true, nil
}
i := partial.At(0)
crumb.status = statusAtChild(i)
ri.keyNibbles.AppendPartial(pk.RightPartial())
ri.keyNibbles.Push(i)
if child := node.Children[i]; child != nil {
fullKeyNibbles += 1
partial = partial.Mid(1)
prefix := key.Back(fullKeyNibbles)
var err error
nextNode, nextNodeHash, err = ri.db.getNodeOrLookup(child, prefix.Left(), true)
if err != nil {
return false, err
}
} else {
return false, nil
}
case codec.Empty:
if !(partial.Len() == 0) {
crumb.status = statusExiting{}
return false, nil
}
return true, nil
}
node = nextNode
nodeHash = nextNodeHash
}
}
// Advance the iterator into a prefix, no value out of the prefix will be accessed
// or returned after this operation.
func (ri *TrieDBRawIterator[H, Hasher]) prefix(prefix []byte, fwd bool) error {
found, err := ri.seek(prefix, fwd)
if err != nil {
return err
}
if found {
if len(ri.trail) > 0 {
popped := ri.trail[len(ri.trail)-1]
ri.trail = nil
ri.trail = append(ri.trail, popped)
}
} else {
ri.trail = nil
}
return nil
}
// Advance the iterator into a prefix, no value out of the prefix will be accessed
// or returned after this operation.
func (ri *TrieDBRawIterator[H, Hasher]) prefixThenSeek(prefix []byte, seek []byte) error {
if len(prefix) == 0 {
// Theres no prefix, so just seek.
_, err := ri.seek(seek, true)
if err != nil {
return err
}
}
if len(seek) == 0 || bytes.Compare(seek, prefix) <= 0 {
// Either were not supposed to seek anywhere,
// or were supposed to seek *before* the prefix,
// so just directly go to the prefix.
return ri.prefix(prefix, true)
}
if !bytes.HasPrefix(seek, prefix) {
// Were supposed to seek *after* the prefix,
// so just return an empty iterator.
ri.trail = nil
return nil
}
found, err := ri.seek(prefix, true)
if err != nil {
return err
}
if !found {
// The database doesnt have a key with such a prefix.
ri.trail = nil
return nil
}
// Now seek forward again
_, err = ri.seek(seek, true)
if err != nil {
return err
}
prefixLen := uint(len(prefix)) * nibbles.NibblesPerByte
var length uint
// look first prefix in trail
for i := 0; i < len(ri.trail); i++ {
switch node := ri.trail[i].node.(type) {
case codec.Empty:
case codec.Leaf:
length += node.PartialKey.Len()
case codec.Branch:
length++
length += node.PartialKey.Len()
}
if length > prefixLen {
ri.trail = ri.trail[i:]
return nil
}
}
ri.trail = nil
return nil
}
// Fetches the next raw item.
//
// Must be called with the same db as when the iterator was created.
//
// Specify fwd to indicate the direction of the iteration (true for forward).
func (ri *TrieDBRawIterator[H, Hasher]) nextRawItem(fwd bool) (*rawItem[H], error) {
for {
if len(ri.trail) == 0 {
return nil, nil
}
crumb := &ri.trail[len(ri.trail)-1]
switch status := crumb.status.(type) {
case statusEntering:
crumb.step(fwd)
if fwd {
return &rawItem[H]{ri.keyNibbles, crumb.hash, crumb.node}, nil
}
case statusAftExiting:
ri.trail = ri.trail[:len(ri.trail)-1]
if len(ri.trail) > 0 {
crumb := &ri.trail[len(ri.trail)-1]
crumb.step(fwd)
}
case statusExiting:
switch node := crumb.node.(type) {
case codec.Empty, codec.Leaf:
case codec.Branch:
ri.keyNibbles.DropLasts(node.PartialKey.Len() + 1)
default:
panic("unreachable")
}
crumb := &ri.trail[len(ri.trail)-1]
crumb.step(fwd)
if !fwd {
return &rawItem[H]{ri.keyNibbles, crumb.hash, crumb.node}, nil
}
case statusAt:
branch, ok := crumb.node.(codec.Branch)
if !ok {
panic("unsupported")
}
partial := branch.PartialKey
ri.keyNibbles.AppendPartial(partial.RightPartial())
if fwd {
ri.keyNibbles.Push(0)
} else {
ri.keyNibbles.Push(15)
}
crumb.step(fwd)
case statusAtChild:
i := status
branch, ok := crumb.node.(codec.Branch)
if !ok {
panic("unsupported")
}
children := branch.Children
child := children[i]
if child != nil {
ri.keyNibbles.Pop()
ri.keyNibbles.Push(uint8(i))
node, nodeHash, err := ri.db.getNodeOrLookup(children[i], ri.keyNibbles.Prefix(), true)
if err != nil {
crumb.step(fwd)
return nil, err
}
ri.descend(node, nodeHash)
} else {
crumb.step(fwd)
}
default:
panic(fmt.Errorf("unreachable: %T", status))
}
}
}
// Fetches the next trie item.
//
// Must be called with the same db as when the iterator was created.
func (ri *TrieDBRawIterator[H, Hasher]) NextItem() (*TrieItem, error) {
for {
rawItem, err := ri.nextRawItem(true)
if err != nil {
return nil, err
}
if rawItem == nil {
return nil, nil
}
extracted := rawItem.extractKey()
if extracted == nil {
continue
}
key := extracted.Key
maybeExtraNibble := extracted.Padding
value := extracted.Value
if maybeExtraNibble != nil {
return nil, fmt.Errorf("ValueAtIncompleteKey: %v %v", key, *maybeExtraNibble)
}
switch value := value.(type) {
case codec.HashedValue[H]:
val, err := ri.db.fetchValue(value.Hash, nibbles.Prefix{Key: key})
if err != nil {
return nil, err
}
return &TrieItem{key, val}, nil
case codec.InlineValue:
return &TrieItem{key, value}, nil
default:
panic("unreachable")
}
}
}
// Fetches the next key.
//
// Must be called with the same `db` as when the iterator was created.
func (ri *TrieDBRawIterator[H, Hasher]) NextKey() ([]byte, error) {
for {
rawItem, err := ri.nextRawItem(true)
if err != nil {
return nil, err
}
if rawItem == nil {
return nil, nil
}
extracted := rawItem.extractKey()
if extracted == nil {
continue
}
key := extracted.Key
maybeExtraNibble := extracted.Padding
if maybeExtraNibble != nil {
return nil, fmt.Errorf("ValueAtIncompleteKey: %v %v", key, *maybeExtraNibble)
}
return key, nil
}
}
type TrieItem struct {
Key []byte
Value []byte
}
// A trie iterator that also supports random access (`seek()`).
type TrieIterator[H hash.Hash, Item any] interface {
Seek(key []byte) error
Next() (Item, error)
// Items() iter.Seq2[Item, error]
}
// Iterator for going through all values in the trie in pre-order traversal order.
type TrieDBIterator[H hash.Hash, Hasher hash.Hasher[H]] struct {
db *TrieDB[H, Hasher]
rawIter TrieDBRawIterator[H, Hasher]
}
// Create a new iterator.
func NewTrieDBIterator[H hash.Hash, Hasher hash.Hasher[H]](
db *TrieDB[H, Hasher],
) (*TrieDBIterator[H, Hasher], error) {
rawIter, err := NewTrieDBRawIterator(db)
if err != nil {
return nil, err
}
return &TrieDBIterator[H, Hasher]{
db: db,
rawIter: *rawIter,
}, nil
}
// Create a new iterator, but limited to a given prefix.
func NewPrefixedTrieDBIterator[H hash.Hash, Hasher hash.Hasher[H]](
db *TrieDB[H, Hasher], prefix []byte,
) (*TrieDBIterator[H, Hasher], error) {
rawIter, err := NewPrefixedTrieDBRawIterator(db, prefix)
if err != nil {
return nil, err
}
return &TrieDBIterator[H, Hasher]{
db: db,
rawIter: *rawIter,
}, nil
}
// Create a new iterator, but limited to a given prefix.
// It then do a seek operation from prefixed context (using `seek` lose
// prefix context by default).
func NewPrefixedTrieDBIteratorThenSeek[H hash.Hash, Hasher hash.Hasher[H]](
db *TrieDB[H, Hasher], prefix []byte, startAt []byte,
) (*TrieDBIterator[H, Hasher], error) {
rawIter, err := NewPrefixedTrieDBRawIteratorThenSeek(db, prefix, startAt)
if err != nil {
return nil, err
}
return &TrieDBIterator[H, Hasher]{
db: db,
rawIter: *rawIter,
}, nil
}
func (tdbi *TrieDBIterator[H, Hasher]) Seek(key []byte) error {
_, err := tdbi.rawIter.seek(key, true)
return err
}
func (tdbi *TrieDBIterator[H, Hasher]) Next() (*TrieItem, error) {
return tdbi.rawIter.NextItem()
}
func (tdbi *TrieDBIterator[H, Hasher]) Items() iter.Seq2[TrieItem, error] {
return func(yield func(TrieItem, error) bool) {
for {
item, err := tdbi.Next()
if err != nil {
return
}
if item == nil {
return
}
if !yield(*item, err) {
return
}
}
}
}
// Iterator for going through all of key with values in the trie in pre-order traversal order.
type TrieDBKeyIterator[H hash.Hash, Hasher hash.Hasher[H]] struct {
rawIter TrieDBRawIterator[H, Hasher]
}
// Create a new iterator.
func NewTrieDBKeyIterator[H hash.Hash, Hasher hash.Hasher[H]](
db *TrieDB[H, Hasher],
) (*TrieDBKeyIterator[H, Hasher], error) {
rawIter, err := NewTrieDBRawIterator(db)
if err != nil {
return nil, err
}
return &TrieDBKeyIterator[H, Hasher]{
rawIter: *rawIter,
}, nil
}
// Create a new iterator, but limited to a given prefix.
func NewPrefixedTrieDBKeyIterator[H hash.Hash, Hasher hash.Hasher[H]](
db *TrieDB[H, Hasher], prefix []byte,
) (*TrieDBKeyIterator[H, Hasher], error) {
rawIter, err := NewPrefixedTrieDBRawIterator(db, prefix)
if err != nil {
return nil, err
}
return &TrieDBKeyIterator[H, Hasher]{
rawIter: *rawIter,
}, nil
}
// Create a new iterator, but limited to a given prefix.
// It then do a seek operation from prefixed context (using `seek` lose
// prefix context by default).
func NewPrefixedTrieDBKeyIteratorThenSeek[H hash.Hash, Hasher hash.Hasher[H]](
db *TrieDB[H, Hasher], prefix []byte, startAt []byte,
) (*TrieDBKeyIterator[H, Hasher], error) {
rawIter, err := NewPrefixedTrieDBRawIteratorThenSeek(db, prefix, startAt)
if err != nil {
return nil, err
}
return &TrieDBKeyIterator[H, Hasher]{
rawIter: *rawIter,
}, nil
}
func (tdbki *TrieDBKeyIterator[H, Hasher]) Seek(key []byte) error {
_, err := tdbki.rawIter.seek(key, true)
return err
}
func (tdbki *TrieDBKeyIterator[H, Hasher]) Next() ([]byte, error) {
return tdbki.rawIter.NextKey()
}
func (tdbki *TrieDBKeyIterator[H, Hasher]) Items() iter.Seq2[[]byte, error] {
return func(yield func([]byte, error) bool) {
for {
key, err := tdbki.Next()
if err != nil {
return
}
if key == nil {
return
}
if !yield(key, err) {
return
}
}
}
}