-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproof.go
151 lines (130 loc) · 2.35 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
package urkel
import (
"bytes"
)
type ProofType uint8
const (
DEADEND ProofType = iota
COLLISION
EXISTS
UNKNOWN // Used?
)
type ProofCode uint8
const (
OK ProofCode = iota
HASH_MISMATCH
SAME_KEY
UNKNOWN_ERROR
)
type ProofResult struct {
Code ProofCode
Value []byte
}
func NewProofResult(t ProofCode, v []byte) *ProofResult {
return &ProofResult{
Code: t,
Value: v,
}
}
type Proof struct {
Type ProofType
NodeHashes [][]byte
Key []byte
Hash []byte
Value []byte
}
func NewProof() *Proof {
return &Proof{
Type: DEADEND,
NodeHashes: make([][]byte, 0),
Key: nil, // being explicit
Hash: nil,
Value: nil,
}
}
func (p *Proof) Depth() int {
return len(p.NodeHashes)
}
func (p *Proof) Push(n []byte) {
p.NodeHashes = append(p.NodeHashes, n)
}
func (p *Proof) IsSane(hasher Hasher, bits int) bool {
// TODO: Need other sanity checks
if p.Depth() > bits {
return false
}
switch p.Type {
case DEADEND:
if p.Key != nil || p.Hash != nil || p.Value != nil {
return false
}
break
case COLLISION:
if p.Key == nil {
return false
}
if p.Hash == nil {
return false
}
if p.Value != nil {
return false
}
if len(p.Key) != (bits >> 3) {
return false
}
if len(p.Hash) != int(hasher.GetSize()) {
return false
}
break
case EXISTS:
if p.Key != nil {
return false
}
if p.Hash != nil {
return false
}
if p.Value == nil {
return false
}
if len(p.Value) > 0xffff {
return false
}
break
default:
return false
}
return true
}
func (p *Proof) Verify(root, key []byte, hasher Hasher, bits int) *ProofResult {
if !p.IsSane(hasher, bits) {
return NewProofResult(UNKNOWN_ERROR, nil)
}
leaf := hasher.ZeroHash()
switch p.Type {
case DEADEND:
//leaf = hasher.ZeroHash()
break
case COLLISION:
if bytes.Compare(p.Key, key) == 0 {
return NewProofResult(SAME_KEY, nil)
}
leaf = hasher.Hash(leafPrefix, p.Key, p.Hash)
break
case EXISTS:
leaf = leafHashValue(hasher, key, p.Value)
break
}
next := leaf
for i := p.Depth() - 1; i >= 0; i-- {
n := p.NodeHashes[i]
if HasBit(key, uint(i)) {
next = hasher.Hash(internalPrefix, n, next)
} else {
next = hasher.Hash(internalPrefix, next, n)
}
}
if bytes.Compare(next, root) != 0 {
return NewProofResult(HASH_MISMATCH, nil)
}
return NewProofResult(OK, p.Value)
}