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.go
89 lines (70 loc) · 1.9 KB
/
beef_tx.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
package bux
import (
"context"
"encoding/hex"
"fmt"
"github.com/libsv/go-bt/v2"
)
const maxBeefVer = uint32(0xFFFF) // value from BRC-62
type beefTx struct {
version uint32
bumps BUMPs
transactions []*bt.Tx
}
// ToBeef generates BEEF Hex for transaction
func ToBeef(ctx context.Context, tx *Transaction, store TransactionGetter) (string, error) {
if err := hydrateTransaction(ctx, tx); err != nil {
return "", err
}
bumpBtFactors, bumpFactors, err := prepareBEEFFactors(ctx, tx, store)
if err != nil {
return "", fmt.Errorf("prepareBUMPFactors() error: %w", err)
}
bumps, err := calculateMergedBUMP(bumpFactors)
if err != nil {
return "", err
}
sortedTxs := kahnTopologicalSortTransactions(bumpBtFactors)
beefHex, err := toBeefHex(bumps, sortedTxs)
if err != nil {
return "", fmt.Errorf("ToBeef() error: %w", err)
}
return beefHex, nil
}
func toBeefHex(bumps BUMPs, parentTxs []*bt.Tx) (string, error) {
beef, err := newBeefTx(1, bumps, parentTxs)
if err != nil {
return "", fmt.Errorf("ToBeefHex() error: %w", err)
}
beefBytes, err := beef.toBeefBytes()
if err != nil {
return "", fmt.Errorf("ToBeefHex() error: %w", err)
}
return hex.EncodeToString(beefBytes), nil
}
func newBeefTx(version uint32, bumps BUMPs, parentTxs []*bt.Tx) (*beefTx, error) {
if version > maxBeefVer {
return nil, fmt.Errorf("version above 0x%X", maxBeefVer)
}
if err := validateBumps(bumps); err != nil {
return nil, err
}
beef := &beefTx{
version: version,
bumps: bumps,
transactions: parentTxs,
}
return beef, nil
}
func hydrateTransaction(ctx context.Context, tx *Transaction) error {
if tx.draftTransaction == nil {
dTx, err := getDraftTransactionID(
ctx, tx.XPubID, tx.DraftID, tx.GetOptions(false)...,
)
if err != nil || dTx == nil {
return fmt.Errorf("retrieve DraftTransaction failed: %w", err)
}
tx.draftTransaction = dTx
}
return nil
}