forked from omni-network/omni
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merkle.go
98 lines (81 loc) · 2.36 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
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
package xchain
import (
"github.com/omni-network/omni/lib/errors"
"github.com/omni-network/omni/lib/merkle"
)
// BlockTree is a merkle tree of a cross chain block.
// It is attested to by the consensus chain validators.
// It's proofs are used to submit messages to destination chains.
type BlockTree [][32]byte
func (t BlockTree) Root() [32]byte {
return t[0]
}
// Proof returns the merkle multi proof for the provided header and messages.
func (t BlockTree) Proof(header BlockHeader, msgs []Msg) (merkle.MultiProof, error) {
// Get the indices to prove
indices := make([]int, 0, len(msgs)+1)
headerLeaf, err := blockHeaderLeaf(header)
if err != nil {
return merkle.MultiProof{}, err
}
headerIndex, err := t.leafIndex(headerLeaf)
if err != nil {
return merkle.MultiProof{}, errors.Wrap(err, "header index")
}
indices = append(indices, headerIndex)
for _, msg := range msgs {
msgLeaf, err := msgLeaf(msg)
if err != nil {
return merkle.MultiProof{}, err
}
msgIndex, err := t.leafIndex(msgLeaf)
if err != nil {
return merkle.MultiProof{}, errors.Wrap(err, "msg index")
}
indices = append(indices, msgIndex)
}
return merkle.GetMultiProof(t, indices...)
}
func (t BlockTree) leafIndex(leaf [32]byte) (int, error) {
// Linear search for the leaf (probably ok since trees are small; < 1000)
for i, l := range t {
if l == leaf {
return i, nil
}
}
return 0, errors.New("leaf not in tree")
}
// NewBlockTree returns the merkle root of the provided block
// to be attested to.
func NewBlockTree(block Block) (BlockTree, error) {
leafs := make([][32]byte, 0, 1+len(block.Msgs))
// First leaf is the block header
headerLeaf, err := blockHeaderLeaf(block.BlockHeader)
if err != nil {
return BlockTree{}, err
}
leafs = append(leafs, headerLeaf)
// Next leafs are the messages
for _, msg := range block.Msgs {
msgLeaf, err := msgLeaf(msg)
if err != nil {
return BlockTree{}, err
}
leafs = append(leafs, msgLeaf)
}
return merkle.MakeTree(leafs)
}
func msgLeaf(msg Msg) ([32]byte, error) {
bz, err := encodeMsg(msg)
if err != nil {
return [32]byte{}, errors.Wrap(err, "encode message")
}
return merkle.StdLeafHash(bz), nil
}
func blockHeaderLeaf(header BlockHeader) ([32]byte, error) {
bz, err := encodeHeader(header)
if err != nil {
return [32]byte{}, errors.Wrap(err, "encode block header")
}
return merkle.StdLeafHash(bz), nil
}