-
Notifications
You must be signed in to change notification settings - Fork 10
/
proof.go
288 lines (248 loc) · 7.05 KB
/
proof.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package iavl
import (
"bytes"
"crypto/sha256"
"fmt"
"math"
"sync"
"github.com/pkg/errors"
hexbytes "github.com/cosmos/iavl/internal/bytes"
"github.com/cosmos/iavl/internal/encoding"
iavlproto "github.com/cosmos/iavl/proto"
)
var bufPool = &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
var (
// ErrInvalidProof is returned by Verify when a proof cannot be validated.
ErrInvalidProof = fmt.Errorf("invalid proof")
// ErrInvalidInputs is returned when the inputs passed to the function are invalid.
ErrInvalidInputs = fmt.Errorf("invalid inputs")
// ErrInvalidRoot is returned when the root passed in does not match the proof's.
ErrInvalidRoot = fmt.Errorf("invalid root")
)
//----------------------------------------
// ProofInnerNode
// Contract: Left and Right can never both be set. Will result in a empty `[]` roothash
type ProofInnerNode struct {
Height int8 `json:"height"`
Size int64 `json:"size"`
Version int64 `json:"version"`
Left []byte `json:"left"`
Right []byte `json:"right"`
}
func (pin ProofInnerNode) String() string {
return pin.stringIndented("")
}
func (pin ProofInnerNode) stringIndented(indent string) string {
return fmt.Sprintf(`ProofInnerNode{
%s Height: %v
%s Size: %v
%s Version: %v
%s Left: %X
%s Right: %X
%s}`,
indent, pin.Height,
indent, pin.Size,
indent, pin.Version,
indent, pin.Left,
indent, pin.Right,
indent)
}
func (pin ProofInnerNode) Hash(childHash []byte) ([]byte, error) {
hasher := sha256.New()
buf := bufPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufPool.Put(buf)
err := encoding.EncodeVarint(buf, int64(pin.Height))
if err == nil {
err = encoding.EncodeVarint(buf, pin.Size)
}
if err == nil {
err = encoding.EncodeVarint(buf, pin.Version)
}
if len(pin.Left) > 0 && len(pin.Right) > 0 {
return nil, errors.New("both left and right child hashes are set")
}
if len(pin.Left) == 0 {
if err == nil {
err = encoding.EncodeBytes(buf, childHash)
}
if err == nil {
err = encoding.EncodeBytes(buf, pin.Right)
}
} else {
if err == nil {
err = encoding.EncodeBytes(buf, pin.Left)
}
if err == nil {
err = encoding.EncodeBytes(buf, childHash)
}
}
if err != nil {
return nil, fmt.Errorf("failed to hash ProofInnerNode: %v", err)
}
_, err = hasher.Write(buf.Bytes())
if err != nil {
return nil, err
}
return hasher.Sum(nil), nil
}
// toProto converts the inner node proof to Protobuf, for use in ProofOps.
func (pin ProofInnerNode) toProto() *iavlproto.ProofInnerNode {
return &iavlproto.ProofInnerNode{
Height: int32(pin.Height),
Size_: pin.Size,
Version: pin.Version,
Left: pin.Left,
Right: pin.Right,
}
}
// proofInnerNodeFromProto converts a Protobuf ProofInnerNode to a ProofInnerNode.
func proofInnerNodeFromProto(pbInner *iavlproto.ProofInnerNode) (ProofInnerNode, error) {
if pbInner == nil {
return ProofInnerNode{}, errors.New("inner node cannot be nil")
}
if pbInner.Height > math.MaxInt8 || pbInner.Height < math.MinInt8 {
return ProofInnerNode{}, fmt.Errorf("height must fit inside an int8, got %v", pbInner.Height)
}
return ProofInnerNode{
Height: int8(pbInner.Height),
Size: pbInner.Size_,
Version: pbInner.Version,
Left: pbInner.Left,
Right: pbInner.Right,
}, nil
}
//----------------------------------------
type ProofLeafNode struct {
Key hexbytes.HexBytes `json:"key"`
ValueHash hexbytes.HexBytes `json:"value"`
Version int64 `json:"version"`
}
func (pln ProofLeafNode) String() string {
return pln.stringIndented("")
}
func (pln ProofLeafNode) stringIndented(indent string) string {
return fmt.Sprintf(`ProofLeafNode{
%s Key: %v
%s ValueHash: %X
%s Version: %v
%s}`,
indent, pln.Key,
indent, pln.ValueHash,
indent, pln.Version,
indent)
}
func (pln ProofLeafNode) Hash() ([]byte, error) {
hasher := sha256.New()
buf := bufPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufPool.Put(buf)
err := encoding.EncodeVarint(buf, 0)
if err == nil {
err = encoding.EncodeVarint(buf, 1)
}
if err == nil {
err = encoding.EncodeVarint(buf, pln.Version)
}
if err == nil {
err = encoding.EncodeBytes(buf, pln.Key)
}
if err == nil {
err = encoding.EncodeBytes(buf, pln.ValueHash)
}
if err != nil {
return nil, fmt.Errorf("failed to hash ProofLeafNode: %v", err)
}
_, err = hasher.Write(buf.Bytes())
if err != nil {
return nil, err
}
return hasher.Sum(nil), nil
}
// toProto converts the leaf node proof to Protobuf, for use in ProofOps.
func (pln ProofLeafNode) toProto() *iavlproto.ProofLeafNode {
return &iavlproto.ProofLeafNode{
Key: pln.Key,
ValueHash: pln.ValueHash,
Version: pln.Version,
}
}
// proofLeafNodeFromProto converts a Protobuf ProofLeadNode to a ProofLeafNode.
func proofLeafNodeFromProto(pbLeaf *iavlproto.ProofLeafNode) (ProofLeafNode, error) {
if pbLeaf == nil {
return ProofLeafNode{}, errors.New("leaf node cannot be nil")
}
return ProofLeafNode{
Key: pbLeaf.Key,
ValueHash: pbLeaf.ValueHash,
Version: pbLeaf.Version,
}, nil
}
//----------------------------------------
// If the key does not exist, returns the path to the next leaf left of key (w/
// path), except when key is less than the least item, in which case it returns
// a path to the least item.
func (node *Node) PathToLeaf(t *ImmutableTree, key []byte) (PathToLeaf, *Node, error) {
path := new(PathToLeaf)
val, err := node.pathToLeaf(t, key, path)
return *path, val, err
}
// pathToLeaf is a helper which recursively constructs the PathToLeaf.
// As an optimization the already constructed path is passed in as an argument
// and is shared among recursive calls.
func (node *Node) pathToLeaf(t *ImmutableTree, key []byte, path *PathToLeaf) (*Node, error) {
if node.GetHeight() == 0 {
if bytes.Equal(node.GetNodeKey(), key) {
return node, nil
}
return node, errors.New("key does not exist")
}
// Note that we do not store the left child in the ProofInnerNode when we're going to add the
// left node as part of the path, similarly we don't store the right child info when going down
// the right child node. This is done as an optimization since the child info is going to be
// already stored in the next ProofInnerNode in PathToLeaf.
if bytes.Compare(key, node.GetNodeKey()) < 0 {
// left side
rightNode, err := node.getRightNode(t)
if err != nil {
return nil, err
}
pin := ProofInnerNode{
Height: node.GetHeight(),
Size: node.GetSize(),
Version: node.GetVersion(),
Left: nil,
Right: rightNode.GetHash(),
}
*path = append(*path, pin)
leftNode, err := node.getLeftNode(t)
if err != nil {
return nil, err
}
n, err := leftNode.pathToLeaf(t, key, path)
return n, err
}
// right side
leftNode, err := node.getLeftNode(t)
if err != nil {
return nil, err
}
pin := ProofInnerNode{
Height: node.GetHeight(),
Size: node.GetSize(),
Version: node.GetVersion(),
Left: leftNode.GetHash(),
Right: nil,
}
*path = append(*path, pin)
rightNode, err := node.getRightNode(t)
if err != nil {
return nil, err
}
n, err := rightNode.pathToLeaf(t, key, path)
return n, err
}