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