This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
generated from mrz1836/go-template
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
beef_tx_bytes.go
85 lines (64 loc) · 1.78 KB
/
beef_tx_bytes.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
package bux
import (
"errors"
"github.com/libsv/go-bt/v2"
)
var (
hasBUMP = byte(0x01)
hasNoBUMP = byte(0x00)
)
func (beefTx *beefTx) toBeefBytes() ([]byte, error) {
if len(beefTx.bumps) == 0 || len(beefTx.transactions) < 2 { // valid BEEF contains at least two transactions (new transaction and one parent transaction)
return nil, errors.New("beef tx is incomplete")
}
// get beef bytes
beefSize := 0
ver := bt.LittleEndianBytes(beefTx.version, 4)
ver[2] = 0xBE
ver[3] = 0xEF
beefSize += len(ver)
nBUMPS := bt.VarInt(len(beefTx.bumps)).Bytes()
beefSize += len(nBUMPS)
bumps := beefTx.bumps.Bytes()
beefSize += len(bumps)
nTransactions := bt.VarInt(uint64(len(beefTx.transactions))).Bytes()
beefSize += len(nTransactions)
transactions := make([][]byte, 0, len(beefTx.transactions))
for _, t := range beefTx.transactions {
txBytes := toBeefBytes(t, beefTx.bumps)
transactions = append(transactions, txBytes)
beefSize += len(txBytes)
}
// compose beef
buffer := make([]byte, 0, beefSize)
buffer = append(buffer, ver...)
buffer = append(buffer, nBUMPS...)
buffer = append(buffer, bumps...)
buffer = append(buffer, nTransactions...)
for _, t := range transactions {
buffer = append(buffer, t...)
}
return buffer, nil
}
func toBeefBytes(tx *bt.Tx, bumps BUMPs) []byte {
txBeefBytes := tx.Bytes()
bumpIdx := getBumpPathIndex(tx, bumps)
if bumpIdx > -1 {
txBeefBytes = append(txBeefBytes, hasBUMP)
txBeefBytes = append(txBeefBytes, bt.VarInt(bumpIdx).Bytes()...)
} else {
txBeefBytes = append(txBeefBytes, hasNoBUMP)
}
return txBeefBytes
}
func getBumpPathIndex(tx *bt.Tx, bumps BUMPs) int {
bumpIndex := -1
for i, bump := range bumps {
for _, path := range bump.Path[0] {
if path.Hash == tx.TxID() {
bumpIndex = i
}
}
}
return bumpIndex
}