Skip to content

Commit 65ce550

Browse files
trie: extend range proofs with non-existence (#21000)
* trie: implement range proof with non-existent edge proof * trie: fix cornercase * trie: consider empty range * trie: add singleSide test * trie: support all-elements range proof * trie: fix typo * trie: tiny typos and formulations Co-authored-by: Péter Szilágyi <peterke@gmail.com>
1 parent 0a99efa commit 65ce550

3 files changed

Lines changed: 491 additions & 92 deletions

File tree

‎go.sum‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,8 @@ golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5h
202202
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
203203
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
204204
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
205+
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 h1:uYVVQ9WP/Ds2ROhcaGPeIdVq0RIXVLwsHlnvJ+cT1So=
206+
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
205207
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
206208
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
207209
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=

‎trie/proof.go‎

Lines changed: 174 additions & 39 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) (node, error) {
136+
func proofToPath(rootHash common.Hash, root node, key []byte, proofDb ethdb.KeyValueReader, allowNonExistent bool) (node, 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[:])
@@ -146,7 +146,8 @@ func proofToPath(rootHash common.Hash, root node, key []byte, proofDb ethdb.KeyV
146146
}
147147
return n, err
148148
}
149-
// If the root node is empty, resolve it first
149+
// If the root node is empty, resolve it first.
150+
// Root node must be included in the proof.
150151
if root == nil {
151152
n, err := resolveNode(rootHash)
152153
if err != nil {
@@ -165,7 +166,13 @@ func proofToPath(rootHash common.Hash, root node, key []byte, proofDb ethdb.KeyV
165166
keyrest, child = get(parent, key, false)
166167
switch cld := child.(type) {
167168
case nil:
168-
// The trie doesn't contain the key.
169+
// The trie doesn't contain the key. It's possible
170+
// the proof is a non-existing proof, but at least
171+
// we can prove all resolved nodes are correct, it's
172+
// enough for us to prove range.
173+
if allowNonExistent {
174+
return root, nil
175+
}
169176
return nil, errors.New("the node is not contained in trie")
170177
case *shortNode:
171178
key, parent = keyrest, child // Already resolved
@@ -205,7 +212,7 @@ func proofToPath(rootHash common.Hash, root node, key []byte, proofDb ethdb.KeyV
205212
// since the node content might be modified. Besides it can happen that some
206213
// fullnodes only have one child which is disallowed. But if the proof is valid,
207214
// the missing children will be filled, otherwise it will be thrown anyway.
208-
func unsetInternal(node node, left []byte, right []byte) error {
215+
func unsetInternal(n node, left []byte, right []byte) error {
209216
left, right = keybytesToHex(left), keybytesToHex(right)
210217

211218
// todo(rjl493456442) different length edge keys should be supported
@@ -214,25 +221,37 @@ func unsetInternal(node node, left []byte, right []byte) error {
214221
}
215222
// Step down to the fork point
216223
prefix, pos := prefixLen(left, right), 0
224+
var parent node
217225
for {
218226
if pos >= prefix {
219227
break
220228
}
221-
switch n := (node).(type) {
229+
switch rn := (n).(type) {
222230
case *shortNode:
223-
if len(left)-pos < len(n.Key) || !bytes.Equal(n.Key, left[pos:pos+len(n.Key)]) {
231+
if len(right)-pos < len(rn.Key) || !bytes.Equal(rn.Key, right[pos:pos+len(rn.Key)]) {
224232
return errors.New("invalid edge path")
225233
}
226-
n.flags = nodeFlag{dirty: true}
227-
node, pos = n.Val, pos+len(n.Key)
234+
// Special case, the non-existent proof points to the same path
235+
// as the existent proof, but the path of existent proof is longer.
236+
// In this case, truncate the extra path(it should be recovered
237+
// by node insertion).
238+
if len(left)-pos < len(rn.Key) || !bytes.Equal(rn.Key, left[pos:pos+len(rn.Key)]) {
239+
fn := parent.(*fullNode)
240+
fn.Children[left[pos-1]] = nil
241+
return nil
242+
}
243+
rn.flags = nodeFlag{dirty: true}
244+
parent = n
245+
n, pos = rn.Val, pos+len(rn.Key)
228246
case *fullNode:
229-
n.flags = nodeFlag{dirty: true}
230-
node, pos = n.Children[left[pos]], pos+1
247+
rn.flags = nodeFlag{dirty: true}
248+
parent = n
249+
n, pos = rn.Children[right[pos]], pos+1
231250
default:
232-
panic(fmt.Sprintf("%T: invalid node: %v", node, node))
251+
panic(fmt.Sprintf("%T: invalid node: %v", n, n))
233252
}
234253
}
235-
fn, ok := node.(*fullNode)
254+
fn, ok := n.(*fullNode)
236255
if !ok {
237256
return errors.New("the fork point must be a fullnode")
238257
}
@@ -241,50 +260,164 @@ func unsetInternal(node node, left []byte, right []byte) error {
241260
fn.Children[i] = nil
242261
}
243262
fn.flags = nodeFlag{dirty: true}
244-
unset(fn.Children[left[prefix]], left[prefix+1:], false)
245-
unset(fn.Children[right[prefix]], right[prefix+1:], true)
263+
if err := unset(fn, fn.Children[left[prefix]], left[prefix:], 1, false); err != nil {
264+
return err
265+
}
266+
if err := unset(fn, fn.Children[right[prefix]], right[prefix:], 1, true); err != nil {
267+
return err
268+
}
246269
return nil
247270
}
248271

249272
// unset removes all internal node references either the left most or right most.
250-
func unset(root node, rest []byte, removeLeft bool) {
251-
switch rn := root.(type) {
273+
// If we try to unset all right most references, it can meet these scenarios:
274+
//
275+
// - The given path is existent in the trie, unset the associated shortnode
276+
// - The given path is non-existent in the trie
277+
// - the fork point is a fullnode, the corresponding child pointed by path
278+
// is nil, return
279+
// - the fork point is a shortnode, the key of shortnode is less than path,
280+
// keep the entire branch and return.
281+
// - the fork point is a shortnode, the key of shortnode is greater than path,
282+
// unset the entire branch.
283+
//
284+
// If we try to unset all left most references, then the given path should
285+
// be existent.
286+
func unset(parent node, child node, key []byte, pos int, removeLeft bool) error {
287+
switch cld := child.(type) {
252288
case *fullNode:
253289
if removeLeft {
254-
for i := 0; i < int(rest[0]); i++ {
255-
rn.Children[i] = nil
290+
for i := 0; i < int(key[pos]); i++ {
291+
cld.Children[i] = nil
256292
}
257-
rn.flags = nodeFlag{dirty: true}
293+
cld.flags = nodeFlag{dirty: true}
258294
} else {
259-
for i := rest[0] + 1; i < 16; i++ {
260-
rn.Children[i] = nil
295+
for i := key[pos] + 1; i < 16; i++ {
296+
cld.Children[i] = nil
261297
}
262-
rn.flags = nodeFlag{dirty: true}
298+
cld.flags = nodeFlag{dirty: true}
263299
}
264-
unset(rn.Children[rest[0]], rest[1:], removeLeft)
300+
return unset(cld, cld.Children[key[pos]], key, pos+1, removeLeft)
265301
case *shortNode:
266-
rn.flags = nodeFlag{dirty: true}
267-
if _, ok := rn.Val.(valueNode); ok {
268-
rn.Val = nilValueNode
269-
return
302+
if len(key[pos:]) < len(cld.Key) || !bytes.Equal(cld.Key, key[pos:pos+len(cld.Key)]) {
303+
// Find the fork point, it's an non-existent branch.
304+
if removeLeft {
305+
return errors.New("invalid right edge proof")
306+
}
307+
if bytes.Compare(cld.Key, key[pos:]) > 0 {
308+
// The key of fork shortnode is greater than the
309+
// path(it belongs to the range), unset the entrie
310+
// branch. The parent must be a fullnode.
311+
fn := parent.(*fullNode)
312+
fn.Children[key[pos-1]] = nil
313+
} else {
314+
// The key of fork shortnode is less than the
315+
// path(it doesn't belong to the range), keep
316+
// it with the cached hash available.
317+
return nil
318+
}
319+
}
320+
if _, ok := cld.Val.(valueNode); ok {
321+
fn := parent.(*fullNode)
322+
fn.Children[key[pos-1]] = nil
323+
return nil
270324
}
271-
unset(rn.Val, rest[len(rn.Key):], removeLeft)
272-
case hashNode, nil, valueNode:
273-
panic("it shouldn't happen")
325+
cld.flags = nodeFlag{dirty: true}
326+
return unset(cld, cld.Val, key, pos+len(cld.Key), removeLeft)
327+
case nil:
328+
// If the node is nil, it's a child of the fork point
329+
// fullnode(it's an non-existent branch).
330+
if removeLeft {
331+
return errors.New("invalid right edge proof")
332+
}
333+
return nil
334+
default:
335+
panic("it shouldn't happen") // hashNode, valueNode
274336
}
275337
}
276338

277-
// VerifyRangeProof checks whether the given leave nodes and edge proofs
339+
// VerifyRangeProof checks whether the given leaf nodes and edge proofs
278340
// can prove the given trie leaves range is matched with given root hash
279341
// and the range is consecutive(no gap inside).
280-
func VerifyRangeProof(rootHash common.Hash, keys [][]byte, values [][]byte, firstProof ethdb.KeyValueReader, lastProof ethdb.KeyValueReader) error {
342+
//
343+
// Note the given first edge proof can be non-existing proof. For example
344+
// the first proof is for an non-existent values 0x03. The given batch
345+
// leaves are [0x04, 0x05, .. 0x09]. It's still feasible to prove. But the
346+
// last edge proof should always be an existent proof.
347+
//
348+
// The firstKey is paired with firstProof, not necessarily the same as keys[0]
349+
// (unless firstProof is an existent proof).
350+
//
351+
// Expect the normal case, this function can also be used to verify the following
352+
// range proofs:
353+
//
354+
// - All elements proof. In this case the left and right proof can be nil, but the
355+
// range should be all the leaves in the trie.
356+
//
357+
// - Zero element proof(left edge proof should be a non-existent proof). In this
358+
// case if there are still some other leaves available on the right side, then
359+
// an error will be returned.
360+
//
361+
// - One element proof. In this case no matter the left edge proof is a non-existent
362+
// proof or not, we can always verify the correctness of the proof.
363+
func VerifyRangeProof(rootHash common.Hash, firstKey []byte, keys [][]byte, values [][]byte, firstProof ethdb.KeyValueReader, lastProof ethdb.KeyValueReader) error {
281364
if len(keys) != len(values) {
282365
return fmt.Errorf("inconsistent proof data, keys: %d, values: %d", len(keys), len(values))
283366
}
367+
// Special case, there is no edge proof at all. The given range is expected
368+
// to be the whole leaf-set in the trie.
369+
if firstProof == nil && lastProof == nil {
370+
emptytrie, err := New(common.Hash{}, NewDatabase(memorydb.New()))
371+
if err != nil {
372+
return err
373+
}
374+
for index, key := range keys {
375+
emptytrie.TryUpdate(key, values[index])
376+
}
377+
if emptytrie.Hash() != rootHash {
378+
return fmt.Errorf("invalid proof, want hash %x, got %x", rootHash, emptytrie.Hash())
379+
}
380+
return nil
381+
}
382+
// Special case, there is a provided non-existence proof and zero key/value
383+
// pairs, meaning there are no more accounts / slots in the trie.
284384
if len(keys) == 0 {
285-
return fmt.Errorf("nothing to verify")
385+
// Recover the non-existent proof to a path, ensure there is nothing left
386+
root, err := proofToPath(rootHash, nil, firstKey, firstProof, true)
387+
if err != nil {
388+
return err
389+
}
390+
node, pos, firstKey := root, 0, keybytesToHex(firstKey)
391+
for node != nil {
392+
switch rn := node.(type) {
393+
case *fullNode:
394+
for i := firstKey[pos] + 1; i < 16; i++ {
395+
if rn.Children[i] != nil {
396+
return errors.New("more leaves available")
397+
}
398+
}
399+
node, pos = rn.Children[firstKey[pos]], pos+1
400+
case *shortNode:
401+
if len(firstKey)-pos < len(rn.Key) || !bytes.Equal(rn.Key, firstKey[pos:pos+len(rn.Key)]) {
402+
if bytes.Compare(rn.Key, firstKey[pos:]) < 0 {
403+
node = nil
404+
continue
405+
} else {
406+
return errors.New("more leaves available")
407+
}
408+
}
409+
node, pos = rn.Val, pos+len(rn.Key)
410+
case valueNode, hashNode:
411+
return errors.New("more leaves available")
412+
}
413+
}
414+
// Yeah, although we receive nothing, but we can prove
415+
// there is no more leaf in the trie, return nil.
416+
return nil
286417
}
287-
if len(keys) == 1 {
418+
// Special case, there is only one element and left edge
419+
// proof is an existent one.
420+
if len(keys) == 1 && bytes.Equal(keys[0], firstKey) {
288421
value, err := VerifyProof(rootHash, keys[0], firstProof)
289422
if err != nil {
290423
return err
@@ -296,19 +429,21 @@ func VerifyRangeProof(rootHash common.Hash, keys [][]byte, values [][]byte, firs
296429
}
297430
// Convert the edge proofs to edge trie paths. Then we can
298431
// have the same tree architecture with the original one.
299-
root, err := proofToPath(rootHash, nil, keys[0], firstProof)
432+
// For the first edge proof, non-existent proof is allowed.
433+
root, err := proofToPath(rootHash, nil, firstKey, firstProof, true)
300434
if err != nil {
301435
return err
302436
}
303437
// Pass the root node here, the second path will be merged
304-
// with the first one.
305-
root, err = proofToPath(rootHash, root, keys[len(keys)-1], lastProof)
438+
// with the first one. For the last edge proof, non-existent
439+
// proof is not allowed.
440+
root, err = proofToPath(rootHash, root, keys[len(keys)-1], lastProof, false)
306441
if err != nil {
307442
return err
308443
}
309444
// Remove all internal references. All the removed parts should
310445
// be re-filled(or re-constructed) by the given leaves range.
311-
if err := unsetInternal(root, keys[0], keys[len(keys)-1]); err != nil {
446+
if err := unsetInternal(root, firstKey, keys[len(keys)-1]); err != nil {
312447
return err
313448
}
314449
// Rebuild the trie with the leave stream, the shape of trie
@@ -318,7 +453,7 @@ func VerifyRangeProof(rootHash common.Hash, keys [][]byte, values [][]byte, firs
318453
newtrie.TryUpdate(key, values[index])
319454
}
320455
if newtrie.Hash() != rootHash {
321-
return fmt.Errorf("invalid proof, wanthash %x, got %x", rootHash, newtrie.Hash())
456+
return fmt.Errorf("invalid proof, want hash %x, got %x", rootHash, newtrie.Hash())
322457
}
323458
return nil
324459
}

0 commit comments

Comments
 (0)