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