github.com/daethereum/go-dae@v2.2.3+incompatible/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/daethereum/go-dae/common" 25 "github.com/daethereum/go-dae/ethdb" 26 "github.com/daethereum/go-dae/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 } 371 //else { 372 // The key of fork shortnode is greater than the 373 // path(it doesn't belong to the range), keep 374 // it with the cached hash available. 375 //} 376 } else { 377 if bytes.Compare(cld.Key, key[pos:]) > 0 { 378 // The key of fork shortnode is greater than the 379 // path(it belongs to the range), unset the entrie 380 // branch. The parent must be a fullnode. 381 fn := parent.(*fullNode) 382 fn.Children[key[pos-1]] = nil 383 } 384 //else { 385 // The key of fork shortnode is less than the 386 // path(it doesn't belong to the range), keep 387 // it with the cached hash available. 388 //} 389 } 390 return nil 391 } 392 if _, ok := cld.Val.(valueNode); ok { 393 fn := parent.(*fullNode) 394 fn.Children[key[pos-1]] = nil 395 return nil 396 } 397 cld.flags = nodeFlag{dirty: true} 398 return unset(cld, cld.Val, key, pos+len(cld.Key), removeLeft) 399 case nil: 400 // If the node is nil, then it's a child of the fork point 401 // fullnode(it's a non-existent branch). 402 return nil 403 default: 404 panic("it shouldn't happen") // hashNode, valueNode 405 } 406 } 407 408 // hasRightElement returns the indicator whether there exists more elements 409 // on the right side of the given path. The given path can point to an existent 410 // key or a non-existent one. This function has the assumption that the whole 411 // path should already be resolved. 412 func hasRightElement(node node, key []byte) bool { 413 pos, key := 0, keybytesToHex(key) 414 for node != nil { 415 switch rn := node.(type) { 416 case *fullNode: 417 for i := key[pos] + 1; i < 16; i++ { 418 if rn.Children[i] != nil { 419 return true 420 } 421 } 422 node, pos = rn.Children[key[pos]], pos+1 423 case *shortNode: 424 if len(key)-pos < len(rn.Key) || !bytes.Equal(rn.Key, key[pos:pos+len(rn.Key)]) { 425 return bytes.Compare(rn.Key, key[pos:]) > 0 426 } 427 node, pos = rn.Val, pos+len(rn.Key) 428 case valueNode: 429 return false // We have resolved the whole path 430 default: 431 panic(fmt.Sprintf("%T: invalid node: %v", node, node)) // hashnode 432 } 433 } 434 return false 435 } 436 437 // VerifyRangeProof checks whether the given leaf nodes and edge proof 438 // can prove the given trie leaves range is matched with the specific root. 439 // Besides, the range should be consecutive (no gap inside) and monotonic 440 // increasing. 441 // 442 // Note the given proof actually contains two edge proofs. Both of them can 443 // be non-existent proofs. For example the first proof is for a non-existent 444 // key 0x03, the last proof is for a non-existent key 0x10. The given batch 445 // leaves are [0x04, 0x05, .. 0x09]. It's still feasible to prove the given 446 // batch is valid. 447 // 448 // The firstKey is paired with firstProof, not necessarily the same as keys[0] 449 // (unless firstProof is an existent proof). Similarly, lastKey and lastProof 450 // are paired. 451 // 452 // Expect the normal case, this function can also be used to verify the following 453 // range proofs: 454 // 455 // - All elements proof. In this case the proof can be nil, but the range should 456 // be all the leaves in the trie. 457 // 458 // - One element proof. In this case no matter the edge proof is a non-existent 459 // proof or not, we can always verify the correctness of the proof. 460 // 461 // - Zero element proof. In this case a single non-existent proof is enough to prove. 462 // Besides, if there are still some other leaves available on the right side, then 463 // an error will be returned. 464 // 465 // Except returning the error to indicate the proof is valid or not, the function will 466 // also return a flag to indicate whether there exists more accounts/slots in the trie. 467 // 468 // Note: This method does not verify that the proof is of minimal form. If the input 469 // proofs are 'bloated' with neighbour leaves or random data, aside from the 'useful' 470 // data, then the proof will still be accepted. 471 func VerifyRangeProof(rootHash common.Hash, firstKey []byte, lastKey []byte, keys [][]byte, values [][]byte, proof ethdb.KeyValueReader) (bool, error) { 472 if len(keys) != len(values) { 473 return false, fmt.Errorf("inconsistent proof data, keys: %d, values: %d", len(keys), len(values)) 474 } 475 // Ensure the received batch is monotonic increasing and contains no deletions 476 for i := 0; i < len(keys)-1; i++ { 477 if bytes.Compare(keys[i], keys[i+1]) >= 0 { 478 return false, errors.New("range is not monotonically increasing") 479 } 480 } 481 for _, value := range values { 482 if len(value) == 0 { 483 return false, errors.New("range contains deletion") 484 } 485 } 486 // Special case, there is no edge proof at all. The given range is expected 487 // to be the whole leaf-set in the trie. 488 if proof == nil { 489 tr := NewStackTrie(nil) 490 for index, key := range keys { 491 tr.TryUpdate(key, values[index]) 492 } 493 if have, want := tr.Hash(), rootHash; have != want { 494 return false, fmt.Errorf("invalid proof, want hash %x, got %x", want, have) 495 } 496 return false, nil // No more elements 497 } 498 // Special case, there is a provided edge proof but zero key/value 499 // pairs, ensure there are no more accounts / slots in the trie. 500 if len(keys) == 0 { 501 root, val, err := proofToPath(rootHash, nil, firstKey, proof, true) 502 if err != nil { 503 return false, err 504 } 505 if val != nil || hasRightElement(root, firstKey) { 506 return false, errors.New("more entries available") 507 } 508 return false, nil 509 } 510 // Special case, there is only one element and two edge keys are same. 511 // In this case, we can't construct two edge paths. So handle it here. 512 if len(keys) == 1 && bytes.Equal(firstKey, lastKey) { 513 root, val, err := proofToPath(rootHash, nil, firstKey, proof, false) 514 if err != nil { 515 return false, err 516 } 517 if !bytes.Equal(firstKey, keys[0]) { 518 return false, errors.New("correct proof but invalid key") 519 } 520 if !bytes.Equal(val, values[0]) { 521 return false, errors.New("correct proof but invalid data") 522 } 523 return hasRightElement(root, firstKey), nil 524 } 525 // Ok, in all other cases, we require two edge paths available. 526 // First check the validity of edge keys. 527 if bytes.Compare(firstKey, lastKey) >= 0 { 528 return false, errors.New("invalid edge keys") 529 } 530 // todo(rjl493456442) different length edge keys should be supported 531 if len(firstKey) != len(lastKey) { 532 return false, errors.New("inconsistent edge keys") 533 } 534 // Convert the edge proofs to edge trie paths. Then we can 535 // have the same tree architecture with the original one. 536 // For the first edge proof, non-existent proof is allowed. 537 root, _, err := proofToPath(rootHash, nil, firstKey, proof, true) 538 if err != nil { 539 return false, err 540 } 541 // Pass the root node here, the second path will be merged 542 // with the first one. For the last edge proof, non-existent 543 // proof is also allowed. 544 root, _, err = proofToPath(rootHash, root, lastKey, proof, true) 545 if err != nil { 546 return false, err 547 } 548 // Remove all internal references. All the removed parts should 549 // be re-filled(or re-constructed) by the given leaves range. 550 empty, err := unsetInternal(root, firstKey, lastKey) 551 if err != nil { 552 return false, err 553 } 554 // Rebuild the trie with the leaf stream, the shape of trie 555 // should be same with the original one. 556 tr := newWithRootNode(root) 557 if empty { 558 tr.root = nil 559 } 560 for index, key := range keys { 561 tr.TryUpdate(key, values[index]) 562 } 563 if tr.Hash() != rootHash { 564 return false, fmt.Errorf("invalid proof, want hash %x, got %x", rootHash, tr.Hash()) 565 } 566 return hasRightElement(tr.root, keys[len(keys)-1]), nil 567 } 568 569 // get returns the child of the given node. Return nil if the 570 // node with specified key doesn't exist at all. 571 // 572 // There is an additional flag `skipResolved`. If it's set then 573 // all resolved nodes won't be returned. 574 func get(tn node, key []byte, skipResolved bool) ([]byte, node) { 575 for { 576 switch n := tn.(type) { 577 case *shortNode: 578 if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) { 579 return nil, nil 580 } 581 tn = n.Val 582 key = key[len(n.Key):] 583 if !skipResolved { 584 return key, tn 585 } 586 case *fullNode: 587 tn = n.Children[key[0]] 588 key = key[1:] 589 if !skipResolved { 590 return key, tn 591 } 592 case hashNode: 593 return key, n 594 case nil: 595 return key, nil 596 case valueNode: 597 return nil, n 598 default: 599 panic(fmt.Sprintf("%T: invalid node: %v", tn, tn)) 600 } 601 } 602 }