-
Notifications
You must be signed in to change notification settings - Fork 0
/
merkle.go
67 lines (57 loc) · 1.21 KB
/
merkle.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
package main
import (
"crypto/sha256"
)
type MerkleTree interface {
Digest() []byte
Proof(footer []Op, proofs chan Proof, target_leaf_hash [32]byte) error
}
type Proof struct {
Leaf *Leaf
Proof []Op
}
type Op struct {
Tag byte
Arg []byte
}
type Fork struct {
digest []byte
Left MerkleTree
Right MerkleTree
}
func (f *Fork) Proof(footer []Op, proofs chan Proof, target_leaf_hash [32]byte) error {
il := []Op{{0xf0, f.Right.Digest()}, {0x08, f.Digest()}}
ir := []Op{{0xf1, f.Left.Digest()}, {0x08, f.Digest()}}
il = append(il, footer...)
ir = append(ir, footer...)
if e := f.Left.Proof(il, proofs, target_leaf_hash); e != nil {
return e
}
if e := f.Right.Proof(ir, proofs, target_leaf_hash); e != nil {
return e
}
return nil
}
func (f *Fork) Digest() []byte {
if len(f.digest) == 32 {
return f.digest
}
h := sha256.New()
h.Write(f.Left.Digest())
h.Write(f.Right.Digest())
f.digest = h.Sum(nil)
return f.digest
}
type Leaf struct {
digest [32]byte
}
func (v *Leaf) Proof(footer []Op, proofs chan Proof, target_leaf_hash [32]byte) error {
if v.digest == target_leaf_hash {
proofs <- Proof{v, footer}
close(proofs)
}
return nil
}
func (v *Leaf) Digest() []byte {
return v.digest[:]
}