forked from BuxOrg/bux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel_bump.go
344 lines (287 loc) · 7.49 KB
/
model_bump.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package bux
import (
"bytes"
"database/sql/driver"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"reflect"
"sort"
"github.com/libsv/go-bc"
"github.com/libsv/go-bt/v2"
)
const maxBumpHeight = 64
// BUMPs represents a slice of BUMPs - BSV Unified Merkle Paths
type BUMPs []*BUMP
// BUMP represents BUMP (BSV Unified Merkle Path) format
type BUMP struct {
BlockHeight uint64 `json:"blockHeight,string"`
Path [][]BUMPLeaf `json:"path"`
// private field for storing already used offsets to avoid duplicate nodes
allNodes []map[uint64]bool
}
// BUMPLeaf represents each BUMP path element
type BUMPLeaf struct {
Offset uint64 `json:"offset,string"`
Hash string `json:"hash,omitempty"`
TxID bool `json:"txid,omitempty"`
Duplicate bool `json:"duplicate,omitempty"`
}
// CalculateMergedBUMP calculates Merged BUMP from a slice of Merkle Proofs
func CalculateMergedBUMP(bumps []BUMP) (*BUMP, error) {
if len(bumps) == 0 || bumps == nil {
return nil, nil
}
blockHeight := bumps[0].BlockHeight
bumpHeight := len(bumps[0].Path)
if bumpHeight > maxBumpHeight {
return nil,
fmt.Errorf("BUMP cannot be higher than %d", maxBumpHeight)
}
for _, b := range bumps {
if bumpHeight != len(b.Path) {
return nil,
errors.New("Merged BUMP cannot be obtained from Merkle Proofs of different heights")
}
if b.BlockHeight != blockHeight {
return nil,
errors.New("BUMPs have different block heights. Cannot merge BUMPs from different blocks")
}
if len(b.Path) == 0 {
return nil,
errors.New("Empty BUMP given")
}
}
bump := BUMP{BlockHeight: blockHeight}
bump.Path = make([][]BUMPLeaf, bumpHeight)
bump.allNodes = make([]map[uint64]bool, bumpHeight)
for i := range bump.allNodes {
bump.allNodes[i] = make(map[uint64]bool, 0)
}
merkleRoot, err := bumps[0].calculateMerkleRoot()
if err != nil {
return nil, err
}
for _, b := range bumps {
mr, err := b.calculateMerkleRoot()
if err != nil {
return nil, err
}
if merkleRoot != mr {
return nil, errors.New("BUMPs have different merkle roots")
}
err = bump.add(b)
if err != nil {
return nil, err
}
}
for _, p := range bump.Path {
sort.Slice(p, func(i, j int) bool {
return p[i].Offset < p[j].Offset
})
}
return &bump, nil
}
func (bump *BUMP) add(b BUMP) error {
if len(bump.Path) != len(b.Path) {
return errors.New("BUMPs with different heights cannot be merged")
}
for i := range b.Path {
for _, v := range b.Path[i] {
_, value := bump.allNodes[i][v.Offset]
if !value {
bump.Path[i] = append(bump.Path[i], v)
bump.allNodes[i][v.Offset] = true
continue
}
if i == 0 && value && v.TxID {
for j := range bump.Path[i] {
if bump.Path[i][j].Offset == v.Offset {
bump.Path[i][j] = v
}
}
}
}
}
return nil
}
func (b *BUMP) calculateMerkleRoot() (string, error) {
merkleRoot := ""
for _, bumpPathElement := range b.Path[0] {
if bumpPathElement.TxID {
calcMerkleRoot, err := calculateMerkleRoot(bumpPathElement, b)
if err != nil {
return "", err
}
if merkleRoot == "" {
merkleRoot = calcMerkleRoot
continue
}
if calcMerkleRoot != merkleRoot {
return "", errors.New("different merkle roots for the same block")
}
}
}
return merkleRoot, nil
}
// calculateMerkleRoots will calculate one merkle root for tx in the BUMPLeaf
func calculateMerkleRoot(baseLeaf BUMPLeaf, bump *BUMP) (string, error) {
calculatedHash := baseLeaf.Hash
offset := baseLeaf.Offset
for _, bLevel := range bump.Path {
newOffset := getOffsetPair(offset)
leafInPair := findLeafByOffset(newOffset, bLevel)
if leafInPair == nil {
return "", errors.New("could not find pair")
}
leftNode, rightNode := prepareNodes(baseLeaf, offset, *leafInPair, newOffset)
str, err := bc.MerkleTreeParentStr(leftNode, rightNode)
if err != nil {
return "", err
}
calculatedHash = str
offset = offset / 2
baseLeaf = BUMPLeaf{
Hash: calculatedHash,
Offset: offset,
}
}
return calculatedHash, nil
}
func findLeafByOffset(offset uint64, bumpLeaves []BUMPLeaf) *BUMPLeaf {
for _, bumpTx := range bumpLeaves {
if bumpTx.Offset == offset {
return &bumpTx
}
}
return nil
}
func getOffsetPair(offset uint64) uint64 {
if offset%2 == 0 {
return offset + 1
}
return offset - 1
}
func prepareNodes(baseLeaf BUMPLeaf, offset uint64, leafInPair BUMPLeaf, newOffset uint64) (string, string) {
var baseLeafHash, pairLeafHash string
if baseLeaf.Duplicate {
baseLeafHash = leafInPair.Hash
} else {
baseLeafHash = baseLeaf.Hash
}
if leafInPair.Duplicate {
pairLeafHash = baseLeaf.Hash
} else {
pairLeafHash = leafInPair.Hash
}
if newOffset > offset {
return baseLeafHash, pairLeafHash
}
return pairLeafHash, baseLeafHash
}
// Bytes returns BUMPs bytes
func (bumps *BUMPs) Bytes() []byte {
var buff bytes.Buffer
for _, bump := range *bumps {
bytes, _ := hex.DecodeString(bump.Hex())
buff.Write(bytes)
}
return buff.Bytes()
}
// Hex returns BUMP in hex format
func (bump *BUMP) Hex() string {
return bump.bytesBuffer().String()
}
func (bump *BUMP) bytesBuffer() *bytes.Buffer {
var buff bytes.Buffer
buff.WriteString(hex.EncodeToString(bt.VarInt(bump.BlockHeight).Bytes()))
height := len(bump.Path)
buff.WriteString(leadingZeroInt(height))
for i := 0; i < height; i++ {
nodes := bump.Path[i]
nLeafs := len(nodes)
buff.WriteString(hex.EncodeToString(bt.VarInt(nLeafs).Bytes()))
for _, n := range nodes {
buff.WriteString(hex.EncodeToString(bt.VarInt(n.Offset).Bytes()))
buff.WriteString(fmt.Sprintf("%02x", flags(n.TxID, n.Duplicate)))
decodedHex, _ := hex.DecodeString(n.Hash)
buff.WriteString(hex.EncodeToString(bt.ReverseBytes(decodedHex)))
}
}
return &buff
}
// In case the offset or height is less than 10, they must be written with a leading zero
func leadingZeroInt(i int) string {
return fmt.Sprintf("%02x", i)
}
func flags(txID, duplicate bool) byte {
var (
dataFlag byte = 0o0
duplicateFlag byte = 0o1
txIDFlag byte = 0o2
)
if duplicate {
return duplicateFlag
}
if txID {
return txIDFlag
}
return dataFlag
}
// Scan scan value into Json, implements sql.Scanner interface
func (bump *BUMP) Scan(value interface{}) error {
if value == nil {
return nil
}
xType := fmt.Sprintf("%T", value)
var byteValue []byte
if xType == ValueTypeString {
byteValue = []byte(value.(string))
} else {
byteValue = value.([]byte)
}
if bytes.Equal(byteValue, []byte("")) || bytes.Equal(byteValue, []byte("\"\"")) {
return nil
}
return json.Unmarshal(byteValue, &bump)
}
// Value return json value, implement driver.Valuer interface
func (bump BUMP) Value() (driver.Value, error) {
if reflect.DeepEqual(bump, BUMP{}) {
return nil, nil
}
marshal, err := json.Marshal(bump)
if err != nil {
return nil, err
}
return string(marshal), nil
}
// Scan scan value into Json, implements sql.Scanner interface
func (bumps *BUMPs) Scan(value interface{}) error {
if value == nil {
return nil
}
xType := fmt.Sprintf("%T", value)
var byteValue []byte
if xType == ValueTypeString {
byteValue = []byte(value.(string))
} else {
byteValue = value.([]byte)
}
if bytes.Equal(byteValue, []byte("")) || bytes.Equal(byteValue, []byte("\"\"")) {
return nil
}
return json.Unmarshal(byteValue, &bumps)
}
// Value return json value, implement driver.Valuer interface
func (bumps BUMPs) Value() (driver.Value, error) {
if reflect.DeepEqual(bumps, BUMPs{}) {
return nil, nil
}
marshal, err := json.Marshal(bumps)
if err != nil {
return nil, err
}
return string(marshal), nil
}