github.com/chain5j/chain5j-pkg@v1.0.7/collection/trees/tree/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 tree 18 19 import ( 20 "bytes" 21 "fmt" 22 23 "github.com/chain5j/chain5j-pkg/codec/rlp" 24 "github.com/chain5j/chain5j-pkg/database/kvstore" 25 "github.com/chain5j/chain5j-pkg/types" 26 ) 27 28 // Prove constructs a merkle proof for key. The result contains all encoded nodes 29 // on the path to the value at key. The value itself is also included in the last 30 // node and can be retrieved by verifying the proof. 31 // 32 // If the trie does not contain a value for key, the returned proof contains all 33 // nodes of the longest existing prefix of the key (at least the root node), ending 34 // with the node that proves the absence of the key. 35 func (t *Trie) Prove(key []byte, fromLevel uint, proofDb kvstore.KeyValueWriter) error { 36 // Collect all nodes on the path to key. 37 key = keybytesToHex(key) 38 var nodes []node 39 tn := t.root 40 for len(key) > 0 && tn != nil { 41 switch n := tn.(type) { 42 case *shortNode: 43 if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) { 44 // The trie doesn't contain the key. 45 tn = nil 46 } else { 47 tn = n.Val 48 key = key[len(n.Key):] 49 } 50 nodes = append(nodes, n) 51 case *fullNode: 52 tn = n.Children[key[0]] 53 key = key[1:] 54 nodes = append(nodes, n) 55 case hashNode: 56 var err error 57 tn, err = t.resolveHash(n, nil) 58 if err != nil { 59 logger().Error(fmt.Sprintf("Unhandled trie error: %v", err)) 60 return err 61 } 62 default: 63 panic(fmt.Sprintf("%T: invalid node: %v", tn, tn)) 64 } 65 } 66 hasher := newHasher(nil) 67 defer returnHasherToPool(hasher) 68 69 for i, n := range nodes { 70 // Don't bother checking for errors here since hasher panics 71 // if encoding doesn't work and we're not writing to any database. 72 n, _, _ = hasher.hashChildren(n, nil) 73 hn, _ := hasher.store(n, nil, false) 74 if hash, ok := hn.(hashNode); ok || i == 0 { 75 // If the node's database encoding is a hash (or is the 76 // root node), it becomes a proof element. 77 if fromLevel > 0 { 78 fromLevel-- 79 } else { 80 enc, _ := rlp.EncodeToBytes(n) 81 if !ok { 82 hash = hasher.makeHashNode(enc) 83 } 84 proofDb.Put(hash, enc) 85 } 86 } 87 } 88 return nil 89 } 90 91 // Prove constructs a merkle proof for key. The result contains all encoded nodes 92 // on the path to the value at key. The value itself is also included in the last 93 // node and can be retrieved by verifying the proof. 94 // 95 // If the trie does not contain a value for key, the returned proof contains all 96 // nodes of the longest existing prefix of the key (at least the root node), ending 97 // with the node that proves the absence of the key. 98 func (t *SecureTrie) Prove(key []byte, fromLevel uint, proofDb kvstore.KeyValueWriter) error { 99 return t.trie.Prove(key, fromLevel, proofDb) 100 } 101 102 // VerifyProof checks merkle proofs. The given proof must contain the value for 103 // key in a trie with the given root hash. VerifyProof returns an error if the 104 // proof contains invalid trie nodes or the wrong value. 105 func VerifyProof(rootHash types.Hash, key []byte, proofDb kvstore.KeyValueReader) (value []byte, nodes int, err error) { 106 key = keybytesToHex(key) 107 wantHash := rootHash 108 for i := 0; ; i++ { 109 buf, _ := proofDb.Get(wantHash[:]) 110 if buf == nil { 111 return nil, i, fmt.Errorf("proof node %d (hash %064x) missing", i, wantHash) 112 } 113 n, err := decodeNode(wantHash[:], buf) 114 if err != nil { 115 return nil, i, fmt.Errorf("bad proof node %d: %v", i, err) 116 } 117 keyrest, cld := get(n, key) 118 switch cld := cld.(type) { 119 case nil: 120 // The trie doesn't contain the key. 121 return nil, i, nil 122 case hashNode: 123 key = keyrest 124 copy(wantHash[:], cld) 125 case valueNode: 126 return cld, i + 1, nil 127 } 128 } 129 } 130 131 func get(tn node, key []byte) ([]byte, node) { 132 for { 133 switch n := tn.(type) { 134 case *shortNode: 135 if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) { 136 return nil, nil 137 } 138 tn = n.Val 139 key = key[len(n.Key):] 140 case *fullNode: 141 tn = n.Children[key[0]] 142 key = key[1:] 143 case hashNode: 144 return key, n 145 case nil: 146 return key, nil 147 case valueNode: 148 return nil, n 149 default: 150 panic(fmt.Sprintf("%T: invalid node: %v", tn, tn)) 151 } 152 } 153 }