Skip to content

Commit 44ff3f3

Browse files
authored
trie: initial implementation for range proof (#20908)
* trie: initial implementation for range proof * trie: add benchmark * trie: fix lint * trie: fix minor issue * trie: unset the edge valuenode as well * trie: unset the edge valuenode as nilValuenode
1 parent 38aab0a commit 44ff3f3

3 files changed

Lines changed: 400 additions & 15 deletions

File tree

‎les/odr_requests.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ func (r *TrieRequest) Validate(db ethdb.Database, msg *Msg) error {
224224
// Verify the proof and store if checks out
225225
nodeSet := proofs.NodeSet()
226226
reads := &readTraceDB{db: nodeSet}
227-
if _, _, err := trie.VerifyProof(r.Id.Root, r.Key, reads); err != nil {
227+
if _, err := trie.VerifyProof(r.Id.Root, r.Key, reads); err != nil {
228228
return fmt.Errorf("merkle proof verification failed: %v", err)
229229
}
230230
// check if all nodes have been read by VerifyProof
@@ -378,7 +378,7 @@ func (r *ChtRequest) Validate(db ethdb.Database, msg *Msg) error {
378378
binary.BigEndian.PutUint64(encNumber[:], r.BlockNum)
379379

380380
reads := &readTraceDB{db: nodeSet}
381-
value, _, err := trie.VerifyProof(r.ChtRoot, encNumber[:], reads)
381+
value, err := trie.VerifyProof(r.ChtRoot, encNumber[:], reads)
382382
if err != nil {
383383
return fmt.Errorf("merkle proof verification failed: %v", err)
384384
}
@@ -470,7 +470,7 @@ func (r *BloomRequest) Validate(db ethdb.Database, msg *Msg) error {
470470

471471
for i, idx := range r.SectionIndexList {
472472
binary.BigEndian.PutUint64(encNumber[2:], idx)
473-
value, _, err := trie.VerifyProof(r.BloomTrieRoot, encNumber[:], reads)
473+
value, err := trie.VerifyProof(r.BloomTrieRoot, encNumber[:], reads)
474474
if err != nil {
475475
return err
476476
}

‎trie/proof.go‎

Lines changed: 214 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,12 @@ package trie
1818

1919
import (
2020
"bytes"
21+
"errors"
2122
"fmt"
2223

2324
"github.com/ethereum/go-ethereum/common"
2425
"github.com/ethereum/go-ethereum/ethdb"
26+
"github.com/ethereum/go-ethereum/ethdb/memorydb"
2527
"github.com/ethereum/go-ethereum/log"
2628
"github.com/ethereum/go-ethereum/rlp"
2729
)
@@ -101,33 +103,232 @@ func (t *SecureTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWri
101103
// VerifyProof checks merkle proofs. The given proof must contain the value for
102104
// key in a trie with the given root hash. VerifyProof returns an error if the
103105
// proof contains invalid trie nodes or the wrong value.
104-
func VerifyProof(rootHash common.Hash, key []byte, proofDb ethdb.KeyValueReader) (value []byte, nodes int, err error) {
106+
func VerifyProof(rootHash common.Hash, key []byte, proofDb ethdb.KeyValueReader) (value []byte, err error) {
105107
key = keybytesToHex(key)
106108
wantHash := rootHash
107109
for i := 0; ; i++ {
108110
buf, _ := proofDb.Get(wantHash[:])
109111
if buf == nil {
110-
return nil, i, fmt.Errorf("proof node %d (hash %064x) missing", i, wantHash)
112+
return nil, fmt.Errorf("proof node %d (hash %064x) missing", i, wantHash)
111113
}
112114
n, err := decodeNode(wantHash[:], buf)
113115
if err != nil {
114-
return nil, i, fmt.Errorf("bad proof node %d: %v", i, err)
116+
return nil, fmt.Errorf("bad proof node %d: %v", i, err)
115117
}
116-
keyrest, cld := get(n, key)
118+
keyrest, cld := get(n, key, true)
117119
switch cld := cld.(type) {
118120
case nil:
119121
// The trie doesn't contain the key.
120-
return nil, i, nil
122+
return nil, nil
121123
case hashNode:
122124
key = keyrest
123125
copy(wantHash[:], cld)
124126
case valueNode:
125-
return cld, i + 1, nil
127+
return cld, nil
126128
}
127129
}
128130
}
129131

130-
func get(tn node, key []byte) ([]byte, node) {
132+
// proofToPath converts a merkle proof to trie node path.
133+
// The main purpose of this function is recovering a node
134+
// path from the merkle proof stream. All necessary nodes
135+
// will be resolved and leave the remaining as hashnode.
136+
func proofToPath(rootHash common.Hash, root node, key []byte, proofDb ethdb.KeyValueReader) (node, error) {
137+
// resolveNode retrieves and resolves trie node from merkle proof stream
138+
resolveNode := func(hash common.Hash) (node, error) {
139+
buf, _ := proofDb.Get(hash[:])
140+
if buf == nil {
141+
return nil, fmt.Errorf("proof node (hash %064x) missing", hash)
142+
}
143+
n, err := decodeNode(hash[:], buf)
144+
if err != nil {
145+
return nil, fmt.Errorf("bad proof node %v", err)
146+
}
147+
return n, err
148+
}
149+
// If the root node is empty, resolve it first
150+
if root == nil {
151+
n, err := resolveNode(rootHash)
152+
if err != nil {
153+
return nil, err
154+
}
155+
root = n
156+
}
157+
var (
158+
err error
159+
child, parent node
160+
keyrest []byte
161+
terminate bool
162+
)
163+
key, parent = keybytesToHex(key), root
164+
for {
165+
keyrest, child = get(parent, key, false)
166+
switch cld := child.(type) {
167+
case nil:
168+
// The trie doesn't contain the key.
169+
return nil, errors.New("the node is not contained in trie")
170+
case *shortNode:
171+
key, parent = keyrest, child // Already resolved
172+
continue
173+
case *fullNode:
174+
key, parent = keyrest, child // Already resolved
175+
continue
176+
case hashNode:
177+
child, err = resolveNode(common.BytesToHash(cld))
178+
if err != nil {
179+
return nil, err
180+
}
181+
case valueNode:
182+
terminate = true
183+
}
184+
// Link the parent and child.
185+
switch pnode := parent.(type) {
186+
case *shortNode:
187+
pnode.Val = child
188+
case *fullNode:
189+
pnode.Children[key[0]] = child
190+
default:
191+
panic(fmt.Sprintf("%T: invalid node: %v", pnode, pnode))
192+
}
193+
if terminate {
194+
return root, nil // The whole path is resolved
195+
}
196+
key, parent = keyrest, child
197+
}
198+
}
199+
200+
// unsetInternal removes all internal node references(hashnode, embedded node).
201+
// It should be called after a trie is constructed with two edge proofs. Also
202+
// the given boundary keys must be the one used to construct the edge proofs.
203+
//
204+
// It's the key step for range proof. All visited nodes should be marked dirty
205+
// since the node content might be modified. Besides it can happen that some
206+
// fullnodes only have one child which is disallowed. But if the proof is valid,
207+
// the missing children will be filled, otherwise it will be thrown anyway.
208+
func unsetInternal(node node, left []byte, right []byte) error {
209+
left, right = keybytesToHex(left), keybytesToHex(right)
210+
211+
// todo(rjl493456442) different length edge keys should be supported
212+
if len(left) != len(right) {
213+
return errors.New("inconsistent edge path")
214+
}
215+
// Step down to the fork point
216+
prefix, pos := prefixLen(left, right), 0
217+
for {
218+
if pos >= prefix {
219+
break
220+
}
221+
switch n := (node).(type) {
222+
case *shortNode:
223+
if len(left)-pos < len(n.Key) || !bytes.Equal(n.Key, left[pos:pos+len(n.Key)]) {
224+
return errors.New("invalid edge path")
225+
}
226+
n.flags = nodeFlag{dirty: true}
227+
node, pos = n.Val, pos+len(n.Key)
228+
case *fullNode:
229+
n.flags = nodeFlag{dirty: true}
230+
node, pos = n.Children[left[pos]], pos+1
231+
default:
232+
panic(fmt.Sprintf("%T: invalid node: %v", node, node))
233+
}
234+
}
235+
fn, ok := node.(*fullNode)
236+
if !ok {
237+
return errors.New("the fork point must be a fullnode")
238+
}
239+
// Find the fork point! Unset all intermediate references
240+
for i := left[prefix] + 1; i < right[prefix]; i++ {
241+
fn.Children[i] = nil
242+
}
243+
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)
246+
return nil
247+
}
248+
249+
// 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) {
252+
case *fullNode:
253+
if removeLeft {
254+
for i := 0; i < int(rest[0]); i++ {
255+
rn.Children[i] = nil
256+
}
257+
rn.flags = nodeFlag{dirty: true}
258+
} else {
259+
for i := rest[0] + 1; i < 16; i++ {
260+
rn.Children[i] = nil
261+
}
262+
rn.flags = nodeFlag{dirty: true}
263+
}
264+
unset(rn.Children[rest[0]], rest[1:], removeLeft)
265+
case *shortNode:
266+
rn.flags = nodeFlag{dirty: true}
267+
if _, ok := rn.Val.(valueNode); ok {
268+
rn.Val = nilValueNode
269+
return
270+
}
271+
unset(rn.Val, rest[len(rn.Key):], removeLeft)
272+
case hashNode, nil, valueNode:
273+
panic("it shouldn't happen")
274+
}
275+
}
276+
277+
// VerifyRangeProof checks whether the given leave nodes and edge proofs
278+
// can prove the given trie leaves range is matched with given root hash
279+
// 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 {
281+
if len(keys) != len(values) {
282+
return fmt.Errorf("inconsistent proof data, keys: %d, values: %d", len(keys), len(values))
283+
}
284+
if len(keys) == 0 {
285+
return fmt.Errorf("nothing to verify")
286+
}
287+
if len(keys) == 1 {
288+
value, err := VerifyProof(rootHash, keys[0], firstProof)
289+
if err != nil {
290+
return err
291+
}
292+
if !bytes.Equal(value, values[0]) {
293+
return fmt.Errorf("correct proof but invalid data")
294+
}
295+
return nil
296+
}
297+
// Convert the edge proofs to edge trie paths. Then we can
298+
// have the same tree architecture with the original one.
299+
root, err := proofToPath(rootHash, nil, keys[0], firstProof)
300+
if err != nil {
301+
return err
302+
}
303+
// 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)
306+
if err != nil {
307+
return err
308+
}
309+
// Remove all internal references. All the removed parts should
310+
// be re-filled(or re-constructed) by the given leaves range.
311+
if err := unsetInternal(root, keys[0], keys[len(keys)-1]); err != nil {
312+
return err
313+
}
314+
// Rebuild the trie with the leave stream, the shape of trie
315+
// should be same with the original one.
316+
newtrie := &Trie{root: root, db: NewDatabase(memorydb.New())}
317+
for index, key := range keys {
318+
newtrie.TryUpdate(key, values[index])
319+
}
320+
if newtrie.Hash() != rootHash {
321+
return fmt.Errorf("invalid proof, wanthash %x, got %x", rootHash, newtrie.Hash())
322+
}
323+
return nil
324+
}
325+
326+
// get returns the child of the given node. Return nil if the
327+
// node with specified key doesn't exist at all.
328+
//
329+
// There is an additional flag `skipResolved`. If it's set then
330+
// all resolved nodes won't be returned.
331+
func get(tn node, key []byte, skipResolved bool) ([]byte, node) {
131332
for {
132333
switch n := tn.(type) {
133334
case *shortNode:
@@ -136,9 +337,15 @@ func get(tn node, key []byte) ([]byte, node) {
136337
}
137338
tn = n.Val
138339
key = key[len(n.Key):]
340+
if !skipResolved {
341+
return key, tn
342+
}
139343
case *fullNode:
140344
tn = n.Children[key[0]]
141345
key = key[1:]
346+
if !skipResolved {
347+
return key, tn
348+
}
142349
case hashNode:
143350
return key, n
144351
case nil:

0 commit comments

Comments
 (0)