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