github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/trie/proof.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package trie 18 19 import ( 20 "bytes" 21 "errors" 22 "fmt" 23 24 "github.com/ethereum/go-ethereum/common" 25 "github.com/ethereum/go-ethereum/ethdb" 26 "github.com/ethereum/go-ethereum/log" 27 ) 28 29 // Prove constructs a merkle proof for key. The result contains all encoded nodes 30 // on the path to the value at key. The value itself is also included in the last 31 // node and can be retrieved by verifying the proof. 32 // 33 // If the trie does not contain a value for key, the returned proof contains all 34 // nodes of the longest existing prefix of the key (at least the root node), ending 35 // with the node that proves the absence of the key. 36 func (t *Trie) Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error { 37 // Collect all nodes on the path to key. 38 key = keybytesToHex(key) 39 var nodes []node 40 tn := t.root 41 for len(key) > 0 && tn != nil { 42 switch n := tn.(type) { 43 case *shortNode: 44 if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) { 45 // The trie doesn't contain the key. 46 tn = nil 47 } else { 48 tn = n.Val 49 key = key[len(n.Key):] 50 } 51 nodes = append(nodes, n) 52 case *fullNode: 53 tn = n.Children[key[0]] 54 key = key[1:] 55 nodes = append(nodes, n) 56 case hashNode: 57 var err error 58 tn, err = t.resolveHash(n, nil) 59 if err != nil { 60 log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) 61 return err 62 } 63 default: 64 panic(fmt.Sprintf("%T: invalid node: %v", tn, tn)) 65 } 66 } 67 hasher := newHasher(false) 68 defer returnHasherToPool(hasher) 69 70 for i, n := range nodes { 71 if fromLevel > 0 { 72 fromLevel-- 73 continue 74 } 75 var hn node 76 n, hn = hasher.proofHash(n) 77 if hash, ok := hn.(hashNode); ok || i == 0 { 78 // If the node's database encoding is a hash (or is the 79 // root node), it becomes a proof element. 80 enc := nodeToBytes(n) 81 if !ok { 82 hash = hasher.hashData(enc) 83 } 84 proofDb.Put(hash, enc) 85 } 86 } 87 return nil 88 } 89 90 // Prove constructs a merkle proof for key. The result contains all encoded nodes 91 // on the path to the value at key. The value itself is also included in the last 92 // node and can be retrieved by verifying the proof. 93 // 94 // If the trie does not contain a value for key, the returned proof contains all 95 // nodes of the longest existing prefix of the key (at least the root node), ending 96 // with the node that proves the absence of the key. 97 func (t *SecureTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error { 98 return t.trie.Prove(key, fromLevel, proofDb) 99 } 100 101 // VerifyProof checks merkle proofs. The given proof must contain the value for 102 // key in a trie with the given root hash. VerifyProof returns an error if the 103 // proof contains invalid trie nodes or the wrong value. 104 func VerifyProof(rootHash common.Hash, key []byte, proofDb ethdb.KeyValueReader) (value []byte, err error) { 105 key = keybytesToHex(key) 106 wantHash := rootHash 107 for i := 0; ; i++ { 108 buf, _ := proofDb.Get(wantHash[:]) 109 if buf == nil { 110 return nil, fmt.Errorf("proof node %d (hash %064x) missing", i, wantHash) 111 } 112 n, err := decodeNode(wantHash[:], buf) 113 if err != nil { 114 return nil, fmt.Errorf("bad proof node %d: %v", i, err) 115 } 116 keyrest, cld := get(n, key, true) 117 switch cld := cld.(type) { 118 case nil: 119 // The trie doesn't contain the key. 120 return nil, nil 121 case hashNode: 122 key = keyrest 123 copy(wantHash[:], cld) 124 case valueNode: 125 return cld, nil 126 } 127 } 128 } 129 130 // proofToPath converts a merkle proof to trie node path. The main purpose of 131 // this function is recovering a node path from the merkle proof stream. All 132 // necessary nodes will be resolved and leave the remaining as hashnode. 133 // 134 // The given edge proof is allowed to be an existent or non-existent proof. 135 func proofToPath(rootHash common.Hash, root node, key []byte, proofDb ethdb.KeyValueReader, allowNonExistent bool) (node, []byte, error) { 136 // resolveNode retrieves and resolves trie node from merkle proof stream 137 resolveNode := func(hash common.Hash) (node, error) { 138 buf, _ := proofDb.Get(hash[:]) 139 if buf == nil { 140 return nil, fmt.Errorf("proof node (hash %064x) missing", hash) 141 } 142 n, err := decodeNode(hash[:], buf) 143 if err != nil { 144 return nil, fmt.Errorf("bad proof node %v", err) 145 } 146 return n, err 147 } 148 // If the root node is empty, resolve it first. 149 // Root node must be included in the proof. 150 if root == nil { 151 n, err := resolveNode(rootHash) 152 if err != nil { 153 return nil, nil, err 154 } 155 root = n 156 } 157 var ( 158 err error 159 child, parent node 160 keyrest []byte 161 valnode []byte 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. It's possible 169 // the proof is a non-existing proof, but at least 170 // we can prove all resolved nodes are correct, it's 171 // enough for us to prove range. 172 if allowNonExistent { 173 return root, nil, nil 174 } 175 return nil, nil, errors.New("the node is not contained in trie") 176 case *shortNode: 177 key, parent = keyrest, child // Already resolved 178 continue 179 case *fullNode: 180 key, parent = keyrest, child // Already resolved 181 continue 182 case hashNode: 183 child, err = resolveNode(common.BytesToHash(cld)) 184 if err != nil { 185 return nil, nil, err 186 } 187 case valueNode: 188 valnode = cld 189 } 190 // Link the parent and child. 191 switch pnode := parent.(type) { 192 case *shortNode: 193 pnode.Val = child 194 case *fullNode: 195 pnode.Children[key[0]] = child 196 default: 197 panic(fmt.Sprintf("%T: invalid node: %v", pnode, pnode)) 198 } 199 if len(valnode) > 0 { 200 return root, valnode, nil // The whole path is resolved 201 } 202 key, parent = keyrest, child 203 } 204 } 205 206 // unsetInternal removes all internal node references(hashnode, embedded node). 207 // It should be called after a trie is constructed with two edge paths. Also 208 // the given boundary keys must be the one used to construct the edge paths. 209 // 210 // It's the key step for range proof. All visited nodes should be marked dirty 211 // since the node content might be modified. Besides it can happen that some 212 // fullnodes only have one child which is disallowed. But if the proof is valid, 213 // the missing children will be filled, otherwise it will be thrown anyway. 214 // 215 // Note we have the assumption here the given boundary keys are different 216 // and right is larger than left. 217 func unsetInternal(n node, left []byte, right []byte) (bool, error) { 218 left, right = keybytesToHex(left), keybytesToHex(right) 219 220 // Step down to the fork point. There are two scenarios can happen: 221 // - the fork point is a shortnode: either the key of left proof or 222 // right proof doesn't match with shortnode's key. 223 // - the fork point is a fullnode: both two edge proofs are allowed 224 // to point to a non-existent key. 225 var ( 226 pos = 0 227 parent node 228 229 // fork indicator, 0 means no fork, -1 means proof is less, 1 means proof is greater 230 shortForkLeft, shortForkRight int 231 ) 232 findFork: 233 for { 234 switch rn := (n).(type) { 235 case *shortNode: 236 rn.flags = nodeFlag{dirty: true} 237 238 // If either the key of left proof or right proof doesn't match with 239 // shortnode, stop here and the forkpoint is the shortnode. 240 if len(left)-pos < len(rn.Key) { 241 shortForkLeft = bytes.Compare(left[pos:], rn.Key) 242 } else { 243 shortForkLeft = bytes.Compare(left[pos:pos+len(rn.Key)], rn.Key) 244 } 245 if len(right)-pos < len(rn.Key) { 246 shortForkRight = bytes.Compare(right[pos:], rn.Key) 247 } else { 248 shortForkRight = bytes.Compare(right[pos:pos+len(rn.Key)], rn.Key) 249 } 250 if shortForkLeft != 0 || shortForkRight != 0 { 251 break findFork 252 } 253 parent = n 254 n, pos = rn.Val, pos+len(rn.Key) 255 case *fullNode: 256 rn.flags = nodeFlag{dirty: true} 257 258 // If either the node pointed by left proof or right proof is nil, 259 // stop here and the forkpoint is the fullnode. 260 leftnode, rightnode := rn.Children[left[pos]], rn.Children[right[pos]] 261 if leftnode == nil || rightnode == nil || leftnode != rightnode { 262 break findFork 263 } 264 parent = n 265 n, pos = rn.Children[left[pos]], pos+1 266 default: 267 panic(fmt.Sprintf("%T: invalid node: %v", n, n)) 268 } 269 } 270 switch rn := n.(type) { 271 case *shortNode: 272 // There can have these five scenarios: 273 // - both proofs are less than the trie path => no valid range 274 // - both proofs are greater than the trie path => no valid range 275 // - left proof is less and right proof is greater => valid range, unset the shortnode entirely 276 // - left proof points to the shortnode, but right proof is greater 277 // - right proof points to the shortnode, but left proof is less 278 if shortForkLeft == -1 && shortForkRight == -1 { 279 return false, errors.New("empty range") 280 } 281 if shortForkLeft == 1 && shortForkRight == 1 { 282 return false, errors.New("empty range") 283 } 284 if shortForkLeft != 0 && shortForkRight != 0 { 285 // The fork point is root node, unset the entire trie 286 if parent == nil { 287 return true, nil 288 } 289 parent.(*fullNode).Children[left[pos-1]] = nil 290 return false, nil 291 } 292 // Only one proof points to non-existent key. 293 if shortForkRight != 0 { 294 if _, ok := rn.Val.(valueNode); ok { 295 // The fork point is root node, unset the entire trie 296 if parent == nil { 297 return true, nil 298 } 299 parent.(*fullNode).Children[left[pos-1]] = nil 300 return false, nil 301 } 302 return false, unset(rn, rn.Val, left[pos:], len(rn.Key), false) 303 } 304 if shortForkLeft != 0 { 305 if _, ok := rn.Val.(valueNode); ok { 306 // The fork point is root node, unset the entire trie 307 if parent == nil { 308 return true, nil 309 } 310 parent.(*fullNode).Children[right[pos-1]] = nil 311 return false, nil 312 } 313 return false, unset(rn, rn.Val, right[pos:], len(rn.Key), true) 314 } 315 return false, nil 316 case *fullNode: 317 // unset all internal nodes in the forkpoint 318 for i := left[pos] + 1; i < right[pos]; i++ { 319 rn.Children[i] = nil 320 } 321 if err := unset(rn, rn.Children[left[pos]], left[pos:], 1, false); err != nil { 322 return false, err 323 } 324 if err := unset(rn, rn.Children[right[pos]], right[pos:], 1, true); err != nil { 325 return false, err 326 } 327 return false, nil 328 default: 329 panic(fmt.Sprintf("%T: invalid node: %v", n, n)) 330 } 331 } 332 333 // unset removes all internal node references either the left most or right most. 334 // It can meet these scenarios: 335 // 336 // - The given path is existent in the trie, unset the associated nodes with the 337 // specific direction 338 // - The given path is non-existent in the trie 339 // - the fork point is a fullnode, the corresponding child pointed by path 340 // is nil, return 341 // - the fork point is a shortnode, the shortnode is included in the range, 342 // keep the entire branch and return. 343 // - the fork point is a shortnode, the shortnode is excluded in the range, 344 // unset the entire branch. 345 func unset(parent node, child node, key []byte, pos int, removeLeft bool) error { 346 switch cld := child.(type) { 347 case *fullNode: 348 if removeLeft { 349 for i := 0; i < int(key[pos]); i++ { 350 cld.Children[i] = nil 351 } 352 cld.flags = nodeFlag{dirty: true} 353 } else { 354 for i := key[pos] + 1; i < 16; i++ { 355 cld.Children[i] = nil 356 } 357 cld.flags = nodeFlag{dirty: true} 358 } 359 return unset(cld, cld.Children[key[pos]], key, pos+1, removeLeft) 360 case *shortNode: 361 if len(key[pos:]) < len(cld.Key) || !bytes.Equal(cld.Key, key[pos:pos+len(cld.Key)]) { 362 // Find the fork point, it's an non-existent branch. 363 if removeLeft { 364 if bytes.Compare(cld.Key, key[pos:]) < 0 { 365 // The key of fork shortnode is less than the path 366 // (it belongs to the range), unset the entrie 367 // branch. The parent must be a fullnode. 368 fn := parent.(*fullNode) 369 fn.Children[key[pos-1]] = nil 370 } else { 371 // The key of fork shortnode is greater than the 372 // path(it doesn't belong to the range), keep 373 // it with the cached hash available. 374 } 375 } else { 376 if bytes.Compare(cld.Key, key[pos:]) > 0 { 377 // The key of fork shortnode is greater than the 378 // path(it belongs to the range), unset the entrie 379 // branch. The parent must be a fullnode. 380 fn := parent.(*fullNode) 381 fn.Children[key[pos-1]] = nil 382 } else { 383 // The key of fork shortnode is less than the 384 // path(it doesn't belong to the range), keep 385 // it with the cached hash available. 386 } 387 } 388 return nil 389 } 390 if _, ok := cld.Val.(valueNode); ok { 391 fn := parent.(*fullNode) 392 fn.Children[key[pos-1]] = nil 393 return nil 394 } 395 cld.flags = nodeFlag{dirty: true} 396 return unset(cld, cld.Val, key, pos+len(cld.Key), removeLeft) 397 case nil: 398 // If the node is nil, then it's a child of the fork point 399 // fullnode(it's a non-existent branch). 400 return nil 401 default: 402 panic("it shouldn't happen") // hashNode, valueNode 403 } 404 } 405 406 // hasRightElement returns the indicator whether there exists more elements 407 // on the right side of the given path. The given path can point to an existent 408 // key or a non-existent one. This function has the assumption that the whole 409 // path should already be resolved. 410 func hasRightElement(node node, key []byte) bool { 411 pos, key := 0, keybytesToHex(key) 412 for node != nil { 413 switch rn := node.(type) { 414 case *fullNode: 415 for i := key[pos] + 1; i < 16; i++ { 416 if rn.Children[i] != nil { 417 return true 418 } 419 } 420 node, pos = rn.Children[key[pos]], pos+1 421 case *shortNode: 422 if len(key)-pos < len(rn.Key) || !bytes.Equal(rn.Key, key[pos:pos+len(rn.Key)]) { 423 return bytes.Compare(rn.Key, key[pos:]) > 0 424 } 425 node, pos = rn.Val, pos+len(rn.Key) 426 case valueNode: 427 return false // We have resolved the whole path 428 default: 429 panic(fmt.Sprintf("%T: invalid node: %v", node, node)) // hashnode 430 } 431 } 432 return false 433 } 434 435 // VerifyRangeProof checks whether the given leaf nodes and edge proof 436 // can prove the given trie leaves range is matched with the specific root. 437 // Besides, the range should be consecutive (no gap inside) and monotonic 438 // increasing. 439 // 440 // Note the given proof actually contains two edge proofs. Both of them can 441 // be non-existent proofs. For example the first proof is for a non-existent 442 // key 0x03, the last proof is for a non-existent key 0x10. The given batch 443 // leaves are [0x04, 0x05, .. 0x09]. It's still feasible to prove the given 444 // batch is valid. 445 // 446 // The firstKey is paired with firstProof, not necessarily the same as keys[0] 447 // (unless firstProof is an existent proof). Similarly, lastKey and lastProof 448 // are paired. 449 // 450 // Expect the normal case, this function can also be used to verify the following 451 // range proofs: 452 // 453 // - All elements proof. In this case the proof can be nil, but the range should 454 // be all the leaves in the trie. 455 // 456 // - One element proof. In this case no matter the edge proof is a non-existent 457 // proof or not, we can always verify the correctness of the proof. 458 // 459 // - Zero element proof. In this case a single non-existent proof is enough to prove. 460 // Besides, if there are still some other leaves available on the right side, then 461 // an error will be returned. 462 // 463 // Except returning the error to indicate the proof is valid or not, the function will 464 // also return a flag to indicate whether there exists more accounts/slots in the trie. 465 // 466 // Note: This method does not verify that the proof is of minimal form. If the input 467 // proofs are 'bloated' with neighbour leaves or random data, aside from the 'useful' 468 // data, then the proof will still be accepted. 469 func VerifyRangeProof(rootHash common.Hash, firstKey []byte, lastKey []byte, keys [][]byte, values [][]byte, proof ethdb.KeyValueReader) (bool, error) { 470 if len(keys) != len(values) { 471 return false, fmt.Errorf("inconsistent proof data, keys: %d, values: %d", len(keys), len(values)) 472 } 473 // Ensure the received batch is monotonic increasing and contains no deletions 474 for i := 0; i < len(keys)-1; i++ { 475 if bytes.Compare(keys[i], keys[i+1]) >= 0 { 476 return false, errors.New("range is not monotonically increasing") 477 } 478 } 479 for _, value := range values { 480 if len(value) == 0 { 481 return false, errors.New("range contains deletion") 482 } 483 } 484 // Special case, there is no edge proof at all. The given range is expected 485 // to be the whole leaf-set in the trie. 486 if proof == nil { 487 tr := NewStackTrie(nil) 488 for index, key := range keys { 489 tr.TryUpdate(key, values[index]) 490 } 491 if have, want := tr.Hash(), rootHash; have != want { 492 return false, fmt.Errorf("invalid proof, want hash %x, got %x", want, have) 493 } 494 return false, nil // No more elements 495 } 496 // Special case, there is a provided edge proof but zero key/value 497 // pairs, ensure there are no more accounts / slots in the trie. 498 if len(keys) == 0 { 499 root, val, err := proofToPath(rootHash, nil, firstKey, proof, true) 500 if err != nil { 501 return false, err 502 } 503 if val != nil || hasRightElement(root, firstKey) { 504 return false, errors.New("more entries available") 505 } 506 return false, nil 507 } 508 // Special case, there is only one element and two edge keys are same. 509 // In this case, we can't construct two edge paths. So handle it here. 510 if len(keys) == 1 && bytes.Equal(firstKey, lastKey) { 511 root, val, err := proofToPath(rootHash, nil, firstKey, proof, false) 512 if err != nil { 513 return false, err 514 } 515 if !bytes.Equal(firstKey, keys[0]) { 516 return false, errors.New("correct proof but invalid key") 517 } 518 if !bytes.Equal(val, values[0]) { 519 return false, errors.New("correct proof but invalid data") 520 } 521 return hasRightElement(root, firstKey), nil 522 } 523 // Ok, in all other cases, we require two edge paths available. 524 // First check the validity of edge keys. 525 if bytes.Compare(firstKey, lastKey) >= 0 { 526 return false, errors.New("invalid edge keys") 527 } 528 // todo(rjl493456442) different length edge keys should be supported 529 if len(firstKey) != len(lastKey) { 530 return false, errors.New("inconsistent edge keys") 531 } 532 // Convert the edge proofs to edge trie paths. Then we can 533 // have the same tree architecture with the original one. 534 // For the first edge proof, non-existent proof is allowed. 535 root, _, err := proofToPath(rootHash, nil, firstKey, proof, true) 536 if err != nil { 537 return false, err 538 } 539 // Pass the root node here, the second path will be merged 540 // with the first one. For the last edge proof, non-existent 541 // proof is also allowed. 542 root, _, err = proofToPath(rootHash, root, lastKey, proof, true) 543 if err != nil { 544 return false, err 545 } 546 // Remove all internal references. All the removed parts should 547 // be re-filled(or re-constructed) by the given leaves range. 548 empty, err := unsetInternal(root, firstKey, lastKey) 549 if err != nil { 550 return false, err 551 } 552 // Rebuild the trie with the leaf stream, the shape of trie 553 // should be same with the original one. 554 tr := newWithRootNode(root) 555 if empty { 556 tr.root = nil 557 } 558 for index, key := range keys { 559 tr.TryUpdate(key, values[index]) 560 } 561 if tr.Hash() != rootHash { 562 return false, fmt.Errorf("invalid proof, want hash %x, got %x", rootHash, tr.Hash()) 563 } 564 return hasRightElement(tr.root, keys[len(keys)-1]), nil 565 } 566 567 // get returns the child of the given node. Return nil if the 568 // node with specified key doesn't exist at all. 569 // 570 // There is an additional flag `skipResolved`. If it's set then 571 // all resolved nodes won't be returned. 572 func get(tn node, key []byte, skipResolved bool) ([]byte, node) { 573 for { 574 switch n := tn.(type) { 575 case *shortNode: 576 if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) { 577 return nil, nil 578 } 579 tn = n.Val 580 key = key[len(n.Key):] 581 if !skipResolved { 582 return key, tn 583 } 584 case *fullNode: 585 tn = n.Children[key[0]] 586 key = key[1:] 587 if !skipResolved { 588 return key, tn 589 } 590 case hashNode: 591 return key, n 592 case nil: 593 return key, nil 594 case valueNode: 595 return nil, n 596 default: 597 panic(fmt.Sprintf("%T: invalid node: %v", tn, tn)) 598 } 599 } 600 }