Skip to content

Commit 389da6a

Browse files
trie: enforce monotonic range in prover and return end marker (#21130)
* trie: add hasRightElement indicator * trie: ensure the range is monotonic increasing * trie: address comment and fix lint * trie: address comment * trie: make linter happy Co-authored-by: Péter Szilágyi <peterke@gmail.com>
1 parent b2c59e2 commit 389da6a

2 files changed

Lines changed: 142 additions & 113 deletions

File tree

‎trie/proof.go‎

Lines changed: 69 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ func VerifyProof(rootHash common.Hash, key []byte, proofDb ethdb.KeyValueReader)
133133
// The main purpose of this function is recovering a node
134134
// path from the merkle proof stream. All necessary nodes
135135
// will be resolved and leave the remaining as hashnode.
136-
func proofToPath(rootHash common.Hash, root node, key []byte, proofDb ethdb.KeyValueReader, allowNonExistent bool) (node, error) {
136+
func proofToPath(rootHash common.Hash, root node, key []byte, proofDb ethdb.KeyValueReader, allowNonExistent bool) (node, []byte, error) {
137137
// resolveNode retrieves and resolves trie node from merkle proof stream
138138
resolveNode := func(hash common.Hash) (node, error) {
139139
buf, _ := proofDb.Get(hash[:])
@@ -151,15 +151,15 @@ func proofToPath(rootHash common.Hash, root node, key []byte, proofDb ethdb.KeyV
151151
if root == nil {
152152
n, err := resolveNode(rootHash)
153153
if err != nil {
154-
return nil, err
154+
return nil, nil, err
155155
}
156156
root = n
157157
}
158158
var (
159159
err error
160160
child, parent node
161161
keyrest []byte
162-
terminate bool
162+
valnode []byte
163163
)
164164
key, parent = keybytesToHex(key), root
165165
for {
@@ -171,9 +171,9 @@ func proofToPath(rootHash common.Hash, root node, key []byte, proofDb ethdb.KeyV
171171
// we can prove all resolved nodes are correct, it's
172172
// enough for us to prove range.
173173
if allowNonExistent {
174-
return root, nil
174+
return root, nil, nil
175175
}
176-
return nil, errors.New("the node is not contained in trie")
176+
return nil, nil, errors.New("the node is not contained in trie")
177177
case *shortNode:
178178
key, parent = keyrest, child // Already resolved
179179
continue
@@ -183,10 +183,10 @@ func proofToPath(rootHash common.Hash, root node, key []byte, proofDb ethdb.KeyV
183183
case hashNode:
184184
child, err = resolveNode(common.BytesToHash(cld))
185185
if err != nil {
186-
return nil, err
186+
return nil, nil, err
187187
}
188188
case valueNode:
189-
terminate = true
189+
valnode = cld
190190
}
191191
// Link the parent and child.
192192
switch pnode := parent.(type) {
@@ -197,8 +197,8 @@ func proofToPath(rootHash common.Hash, root node, key []byte, proofDb ethdb.KeyV
197197
default:
198198
panic(fmt.Sprintf("%T: invalid node: %v", pnode, pnode))
199199
}
200-
if terminate {
201-
return root, nil // The whole path is resolved
200+
if len(valnode) > 0 {
201+
return root, valnode, nil // The whole path is resolved
202202
}
203203
key, parent = keyrest, child
204204
}
@@ -351,9 +351,38 @@ func unset(parent node, child node, key []byte, pos int, removeLeft bool) error
351351
}
352352
}
353353

354+
// hasRightElement returns the indicator whether there exists more elements
355+
// in the right side of the given path. The given path can point to an existent
356+
// key or a non-existent one. This function has the assumption that the whole
357+
// path should already be resolved.
358+
func hasRightElement(node node, key []byte) bool {
359+
pos, key := 0, keybytesToHex(key)
360+
for node != nil {
361+
switch rn := node.(type) {
362+
case *fullNode:
363+
for i := key[pos] + 1; i < 16; i++ {
364+
if rn.Children[i] != nil {
365+
return true
366+
}
367+
}
368+
node, pos = rn.Children[key[pos]], pos+1
369+
case *shortNode:
370+
if len(key)-pos < len(rn.Key) || !bytes.Equal(rn.Key, key[pos:pos+len(rn.Key)]) {
371+
return bytes.Compare(rn.Key, key[pos:]) > 0
372+
}
373+
node, pos = rn.Val, pos+len(rn.Key)
374+
case valueNode:
375+
return false // We have resolved the whole path
376+
default:
377+
panic(fmt.Sprintf("%T: invalid node: %v", node, node)) // hashnode
378+
}
379+
}
380+
return false
381+
}
382+
354383
// VerifyRangeProof checks whether the given leaf nodes and edge proofs
355384
// can prove the given trie leaves range is matched with given root hash
356-
// and the range is consecutive(no gap inside).
385+
// and the range is consecutive(no gap inside) and monotonic increasing.
357386
//
358387
// Note the given first edge proof can be non-existing proof. For example
359388
// the first proof is for an non-existent values 0x03. The given batch
@@ -364,102 +393,74 @@ func unset(parent node, child node, key []byte, pos int, removeLeft bool) error
364393
// (unless firstProof is an existent proof).
365394
//
366395
// Expect the normal case, this function can also be used to verify the following
367-
// range proofs:
396+
// range proofs(note this function doesn't accept zero element proof):
368397
//
369398
// - All elements proof. In this case the left and right proof can be nil, but the
370399
// range should be all the leaves in the trie.
371400
//
372-
// - Zero element proof(left edge proof should be a non-existent proof). In this
373-
// case if there are still some other leaves available on the right side, then
374-
// an error will be returned.
375-
//
376401
// - One element proof. In this case no matter the left edge proof is a non-existent
377402
// proof or not, we can always verify the correctness of the proof.
378-
func VerifyRangeProof(rootHash common.Hash, firstKey []byte, keys [][]byte, values [][]byte, firstProof ethdb.KeyValueReader, lastProof ethdb.KeyValueReader) error {
403+
//
404+
// Except returning the error to indicate the proof is valid or not, the function will
405+
// also return a flag to indicate whether there exists more accounts/slots in the trie.
406+
func VerifyRangeProof(rootHash common.Hash, firstKey []byte, keys [][]byte, values [][]byte, firstProof ethdb.KeyValueReader, lastProof ethdb.KeyValueReader) (error, bool) {
379407
if len(keys) != len(values) {
380-
return fmt.Errorf("inconsistent proof data, keys: %d, values: %d", len(keys), len(values))
408+
return fmt.Errorf("inconsistent proof data, keys: %d, values: %d", len(keys), len(values)), false
409+
}
410+
if len(keys) == 0 {
411+
return errors.New("empty proof"), false
412+
}
413+
// Ensure the received batch is monotonic increasing.
414+
for i := 0; i < len(keys)-1; i++ {
415+
if bytes.Compare(keys[i], keys[i+1]) >= 0 {
416+
return errors.New("range is not monotonically increasing"), false
417+
}
381418
}
382419
// Special case, there is no edge proof at all. The given range is expected
383420
// to be the whole leaf-set in the trie.
384421
if firstProof == nil && lastProof == nil {
385422
emptytrie, err := New(common.Hash{}, NewDatabase(memorydb.New()))
386423
if err != nil {
387-
return err
424+
return err, false
388425
}
389426
for index, key := range keys {
390427
emptytrie.TryUpdate(key, values[index])
391428
}
392429
if emptytrie.Hash() != rootHash {
393-
return fmt.Errorf("invalid proof, want hash %x, got %x", rootHash, emptytrie.Hash())
394-
}
395-
return nil
396-
}
397-
// Special case, there is a provided non-existence proof and zero key/value
398-
// pairs, meaning there are no more accounts / slots in the trie.
399-
if len(keys) == 0 {
400-
// Recover the non-existent proof to a path, ensure there is nothing left
401-
root, err := proofToPath(rootHash, nil, firstKey, firstProof, true)
402-
if err != nil {
403-
return err
430+
return fmt.Errorf("invalid proof, want hash %x, got %x", rootHash, emptytrie.Hash()), false
404431
}
405-
node, pos, firstKey := root, 0, keybytesToHex(firstKey)
406-
for node != nil {
407-
switch rn := node.(type) {
408-
case *fullNode:
409-
for i := firstKey[pos] + 1; i < 16; i++ {
410-
if rn.Children[i] != nil {
411-
return errors.New("more leaves available")
412-
}
413-
}
414-
node, pos = rn.Children[firstKey[pos]], pos+1
415-
case *shortNode:
416-
if len(firstKey)-pos < len(rn.Key) || !bytes.Equal(rn.Key, firstKey[pos:pos+len(rn.Key)]) {
417-
if bytes.Compare(rn.Key, firstKey[pos:]) < 0 {
418-
node = nil
419-
continue
420-
} else {
421-
return errors.New("more leaves available")
422-
}
423-
}
424-
node, pos = rn.Val, pos+len(rn.Key)
425-
case valueNode, hashNode:
426-
return errors.New("more leaves available")
427-
}
428-
}
429-
// Yeah, although we receive nothing, but we can prove
430-
// there is no more leaf in the trie, return nil.
431-
return nil
432+
return nil, false // no more element.
432433
}
433434
// Special case, there is only one element and left edge
434435
// proof is an existent one.
435436
if len(keys) == 1 && bytes.Equal(keys[0], firstKey) {
436-
value, err := VerifyProof(rootHash, keys[0], firstProof)
437+
root, val, err := proofToPath(rootHash, nil, firstKey, firstProof, false)
437438
if err != nil {
438-
return err
439+
return err, false
439440
}
440-
if !bytes.Equal(value, values[0]) {
441-
return fmt.Errorf("correct proof but invalid data")
441+
if !bytes.Equal(val, values[0]) {
442+
return fmt.Errorf("correct proof but invalid data"), false
442443
}
443-
return nil
444+
return nil, hasRightElement(root, keys[0])
444445
}
445446
// Convert the edge proofs to edge trie paths. Then we can
446447
// have the same tree architecture with the original one.
447448
// For the first edge proof, non-existent proof is allowed.
448-
root, err := proofToPath(rootHash, nil, firstKey, firstProof, true)
449+
root, _, err := proofToPath(rootHash, nil, firstKey, firstProof, true)
449450
if err != nil {
450-
return err
451+
return err, false
451452
}
452453
// Pass the root node here, the second path will be merged
453454
// with the first one. For the last edge proof, non-existent
454455
// proof is not allowed.
455-
root, err = proofToPath(rootHash, root, keys[len(keys)-1], lastProof, false)
456+
root, _, err = proofToPath(rootHash, root, keys[len(keys)-1], lastProof, false)
456457
if err != nil {
457-
return err
458+
return err, false
458459
}
459460
// Remove all internal references. All the removed parts should
460461
// be re-filled(or re-constructed) by the given leaves range.
461462
if err := unsetInternal(root, firstKey, keys[len(keys)-1]); err != nil {
462-
return err
463+
return err, false
463464
}
464465
// Rebuild the trie with the leave stream, the shape of trie
465466
// should be same with the original one.
@@ -468,9 +469,9 @@ func VerifyRangeProof(rootHash common.Hash, firstKey []byte, keys [][]byte, valu
468469
newtrie.TryUpdate(key, values[index])
469470
}
470471
if newtrie.Hash() != rootHash {
471-
return fmt.Errorf("invalid proof, want hash %x, got %x", rootHash, newtrie.Hash())
472+
return fmt.Errorf("invalid proof, want hash %x, got %x", rootHash, newtrie.Hash()), false
472473
}
473-
return nil
474+
return nil, hasRightElement(root, keys[len(keys)-1])
474475
}
475476

476477
// get returns the child of the given node. Return nil if the

0 commit comments

Comments
 (0)