-
Notifications
You must be signed in to change notification settings - Fork 107
/
proof.go
259 lines (225 loc) · 6.34 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
package syncer
import (
"context"
"errors"
"fmt"
"github.com/oasisprotocol/oasis-core/go/common/crypto/hash"
"github.com/oasisprotocol/oasis-core/go/storage/mkvs/node"
)
const (
// proofEntryFull is the proof entry type for full nodes.
proofEntryFull byte = 0x01
// proofEntryHash is the proof entry type for subtree hashes.
proofEntryHash byte = 0x02
)
// Proof is a Merkle proof for a subtree.
type Proof struct {
// UntrustedRoot is the root hash this proof is for. This should only be
// used as a quick sanity check and proof verification MUST use an
// independently obtained root hash as the prover can provide any root.
UntrustedRoot hash.Hash `json:"untrusted_root"`
// Entries are the proof entries in pre-order traversal.
Entries [][]byte `json:"entries"`
}
type proofNode struct {
serialized []byte
children []hash.Hash
}
// ProofBuilder is a Merkle proof builder.
type ProofBuilder struct {
root hash.Hash
subtree hash.Hash
included map[hash.Hash]*proofNode
size uint64
}
// NewProofBuilder creates a new Merkle proof builder for the given root.
func NewProofBuilder(root, subtree hash.Hash) *ProofBuilder {
return &ProofBuilder{
root: root,
subtree: subtree,
included: make(map[hash.Hash]*proofNode),
}
}
// Include adds a node to the set of included nodes.
//
// The node must be clean.
func (b *ProofBuilder) Include(n node.Node) {
if n == nil {
return
}
if !n.IsClean() {
panic("proof: attempted to add a dirty node")
}
// If node is already included, skip it.
nh := n.GetHash()
if _, ok := b.included[nh]; ok {
return
}
// Node is available, serialize it.
var err error
var pn proofNode
pn.serialized, err = n.CompactMarshalBinary()
if err != nil {
panic(err)
}
// For internal nodes, also add any children.
if nd, ok := n.(*node.InternalNode); ok {
// Add leaf, left and right.
for _, child := range []*node.Pointer{
// NOTE: LeafNode is always included with the internal node.
nd.Left,
nd.Right,
} {
var childHash hash.Hash
if child == nil {
childHash.Empty()
} else {
childHash = child.Hash
}
pn.children = append(pn.children, childHash)
}
}
b.included[nh] = &pn
b.size += 1 + uint64(len(pn.serialized))
}
// HasSubtree returns true if the subtree root node has already been included.
func (b *ProofBuilder) HasSubtreeRoot() bool {
return b.included[b.subtree] != nil
}
// GetSubtree returns the subtree root hash for this proof.
func (b *ProofBuilder) GetSubtreeRoot() hash.Hash {
return b.subtree
}
// Size returns the current size of this proof.
func (b *ProofBuilder) Size() uint64 {
return b.size
}
// Build tries to build the proof.
func (b *ProofBuilder) Build(ctx context.Context) (*Proof, error) {
var proof Proof
switch b.HasSubtreeRoot() {
case true:
// A partial proof for the subtree is available, include that.
proof.UntrustedRoot = b.subtree
case false:
// No partial proof available, we need to use the tree root.
proof.UntrustedRoot = b.root
}
if err := b.build(ctx, &proof, proof.UntrustedRoot); err != nil {
return nil, err
}
return &proof, nil
}
func (b *ProofBuilder) build(ctx context.Context, proof *Proof, h hash.Hash) error {
if ctx.Err() != nil {
return ctx.Err()
}
if h.IsEmpty() {
// Append nil for empty nodes.
proof.Entries = append(proof.Entries, nil)
return nil
}
n := b.included[h]
if n == nil {
// Node is not included in this proof, just add hash of subtree.
data, err := h.MarshalBinary()
if err != nil {
return err
}
proof.Entries = append(proof.Entries, append([]byte{proofEntryHash}, data...))
return nil
}
// Pre-order traversal, add visited node.
proof.Entries = append(proof.Entries, append([]byte{proofEntryFull}, n.serialized...))
// And then add any children.
for _, childHash := range n.children {
if err := b.build(ctx, proof, childHash); err != nil {
return err
}
}
return nil
}
// ProofVerifier enables verifying proofs returned by the ReadSyncer API.
type ProofVerifier struct {
}
// VerifyProof verifies a proof and generates an in-memory subtree representing
// the nodes which are included in the proof.
func (pv *ProofVerifier) VerifyProof(ctx context.Context, root hash.Hash, proof *Proof) (*node.Pointer, error) {
// Sanity check that the proof is for the correct root (as otherwise it
// makes no sense to verify the proof).
if !proof.UntrustedRoot.Equal(&root) {
return nil, fmt.Errorf("verifier: got proof for unexpected root (expected: %s got: %s)",
root,
proof.UntrustedRoot,
)
}
if len(proof.Entries) == 0 {
return nil, errors.New("verifier: empty proof")
}
_, rootNode, err := pv.verifyProof(ctx, proof, 0)
if err != nil {
return nil, err
}
rootNodeHash := rootNode.GetHash()
if rootNodeHash.IsEmpty() {
// Make sure that in case the root node is empty we always return nil
// and not a pointer that represents nil.
rootNode = nil
}
if !rootNodeHash.Equal(&root) {
return nil, fmt.Errorf("verifier: bad root (expected: %s got: %s)",
root,
rootNodeHash,
)
}
return rootNode, nil
}
func (pv *ProofVerifier) verifyProof(ctx context.Context, proof *Proof, idx int) (int, *node.Pointer, error) {
if ctx.Err() != nil {
return -1, nil, ctx.Err()
}
if idx >= len(proof.Entries) {
return -1, nil, errors.New("verifier: malformed proof")
}
entry := proof.Entries[idx]
if entry == nil {
return idx + 1, nil, nil
}
if len(entry) == 0 {
return -1, nil, errors.New("verifier: malformed proof")
}
switch entry[0] {
case proofEntryFull:
// Full node.
n, err := node.UnmarshalBinary(entry[1:])
if err != nil {
return -1, nil, err
}
// For internal nodes, also decode children.
pos := idx + 1
if nd, ok := n.(*node.InternalNode); ok {
// Left.
pos, nd.Left, err = pv.verifyProof(ctx, proof, pos)
if err != nil {
return -1, nil, err
}
// Right.
pos, nd.Right, err = pv.verifyProof(ctx, proof, pos)
if err != nil {
return -1, nil, err
}
// Recompute hash as hashes were not recomputed for compact encoding.
nd.UpdateHash()
}
return pos, &node.Pointer{Clean: true, Hash: n.GetHash(), Node: n}, nil
case proofEntryHash:
// Hash of a node.
var h hash.Hash
if err := h.UnmarshalBinary(entry[1:]); err != nil {
return -1, nil, err
}
return idx + 1, &node.Pointer{Clean: true, Hash: h}, nil
default:
return -1, nil, fmt.Errorf("verifier: unexpected entry in proof (%x)", entry[0])
}
}