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