aboutsummaryrefslogtreecommitdiffstats
path: root/merkle.go
blob: 06e48556a0cb8a4db1b8530eee2b70bb0f24b649 (plain)
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
package main

import (
	"encoding/binary"
	"os"

	"golang.org/x/crypto/sha3"
)

const hashSize int64 = 32

type Merkle interface {
	Build() []byte
	Put(id int64, data []byte)
	Read(buf []byte, id int64)
	Size() int64
	Proof(id int64) [][]byte
}

func NewMerkle(mtype string, height int64, fname string) Merkle {
	var m Merkle
	switch mtype {
	case "bfs":
		m = NewBFSMerkle(height, fname)
	case "post":
		m = NewPostMerkle(height, fname)
	}
	return m
}
func ChildrenId(m Merkle, id int64) (id1, id2 int64) {
	id2 = (id + 1) * 2
	id1 = id2 - 1
	return id1, id2
}

func Children(child1, child2 []byte, id int64, m Merkle) {
	id1, id2 := ChildrenId(m, id)
	m.Read(child1, id1)
	m.Read(child2, id2)
}

func Init(m Merkle) {
	h := sha3.New256()
	hsize := h.Size()
	buf := make([]byte, hsize)

	for id := m.Size() / 2; id <= m.Size(); id++ {
		h.Reset()
		binary.Write(h, binary.LittleEndian, id)
		buf = h.Sum(buf[:0])
		m.Put(id, buf)
	}
}

// nodes are stored in BFS order, root node first
type BFSMerkle struct {
	height int64
	file   *os.File
	size   int64
}

func NewBFSMerkle(height int64, fname string) *BFSMerkle {
	file, err := os.Create(fname)
	if err != nil {
		panic(err)
	}
	size := int64(1)<<uint64(height) - 2
	return &BFSMerkle{height: height, file: file, size: size}
}

func (m *BFSMerkle) Size() int64 {
	return m.size
}

func (m *BFSMerkle) Put(id int64, data []byte) {
	m.file.WriteAt(data, id*hashSize)
}

func (m *BFSMerkle) Read(buf []byte, id int64) {
	m.file.ReadAt(buf, id*hashSize)
}

// disk access is sequential and mostly backward
func (m *BFSMerkle) Build() []byte {
	Init(m)
	size := m.Size()
	h := sha3.New256()
	hsize := h.Size()
	child1 := make([]byte, hsize)
	child2 := make([]byte, hsize)
	buf := make([]byte, hsize)
	for id := size/2 - 1; id >= 0; id-- {
		Children(child1, child2, id, m)
		h.Reset()
		h.Write(child1)
		h.Write(child2)
		buf = h.Sum(buf[:0])
		m.Put(id, buf)
	}
	return buf
}

func (m *BFSMerkle) Proof(id int64) [][]byte {
	proof := make([][]byte, m.height)
	proof[0] = make([]byte, hashSize)
	m.Read(proof[0], id)
	for i := 1; id > 0; i++ {
		proof[i] = make([]byte, hashSize)
		if id&1 == 0 {
			m.Read(proof[i], id-1)
		} else {
			m.Read(proof[i], id+1)
		}
		id = (id - 1) >> 1
	}
	return proof
}

// nodes are stored in depth-first post order
type PostMerkle struct {
	height int64
	file   *os.File
	size   int64
}

func NewPostMerkle(height int64, fname string) *PostMerkle {
	file, err := os.Create(fname)
	if err != nil {
		panic(err)
	}
	size := int64(1)<<uint64(height) - 2
	return &PostMerkle{height: height, file: file, size: size}
}

func (m *PostMerkle) Size() int64 {
	return m.size
}

func (m *PostMerkle) Put(id int64, data []byte) {
	pos := Post(m.size, m.height, id)
	m.file.WriteAt(data, pos*hashSize)
}

func (m *PostMerkle) Read(buf []byte, id int64) {
	pos := Post(m.size, m.height, id)
	m.file.ReadAt(buf, pos*hashSize)
}

// Iterative post-order depth-first construction of the Merkle tree
// disk access is optimal and forward
func (m *PostMerkle) Build() []byte {
	size := m.Size()
	h := sha3.New256()
	hsize := int64(h.Size())

	// pre-allocating the hash stack
	stack := make([][]byte, m.height)
	for i := 0; i < len(stack); i++ {
		stack[i] = make([]byte, hsize)
	}

	var cur int64 = size / 2 // current node (bfs id)
	var count int64 = 0      // post-order id of current node
	var l = 0                // length of the stack

	for count < size {
		if cur >= size/2 { // leaf node
			l++
			h.Reset()
			binary.Write(h, binary.LittleEndian, cur)
			h.Sum(stack[l-1][:0])
			m.file.WriteAt(stack[l-1], count*hsize)

			for cur&1 == 0 && count < size {
				// we just completed a right node, moving up to the parent
				cur = (cur - 1) >> 1
				count++
				h.Reset()
				h.Write(stack[l-2])
				h.Write(stack[l-1])
				l-- // pop two items, add one item
				h.Sum(stack[l-1][:0])
				m.file.WriteAt(stack[l-1], count*hsize)
			}
			// we just completed a left node, moving to its sibling
			cur++
			count++
		} else {
			cur = (cur << 1) + 1 // moving to the left child
		}
	}
	return stack[0]
}

func (m *PostMerkle) Proof(id int64) [][]byte {
	// traversing the tree from the root to the leaf reading the siblings along
	// the path and filling the proof from right to left
	proof := make([][]byte, m.height)
	cur := int64(1)<<uint64(m.height) - 2  // post-order id of the current node along the path, starting from the root
	size := int64(1) << uint64(m.height-1) // size of a subtree of the current node
	mask := size >> 1
	id += 1
	for i := len(proof) - 1; mask > 0; i-- {
		proof[i] = make([]byte, hashSize)
		if mask&id > 0 { // leaf is in the right subtree of current node
			m.file.ReadAt(proof[i], (cur-size)*hashSize) // reading the left child
			cur -= 1                                     // moving to the right subtree
		} else { // left is in the left subtree of current node
			m.file.ReadAt(proof[i], (cur-1)*hashSize) // reading the right child
			cur -= size                               // moving the left subtree
		}
		size = mask
		mask >>= 1
	}
	proof[0] = make([]byte, hashSize)
	m.file.ReadAt(proof[0], cur*hashSize)
	return proof
}