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