forked from lightninglabs/lndclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tx_utils.go
70 lines (59 loc) · 1.45 KB
/
tx_utils.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
package lndclient
import (
"bytes"
"errors"
"fmt"
"strconv"
"strings"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
)
// encodeTx encodes a tx to raw bytes.
func encodeTx(tx *wire.MsgTx) ([]byte, error) {
var buffer bytes.Buffer
err := tx.BtcEncode(&buffer, 0, wire.WitnessEncoding)
if err != nil {
return nil, err
}
rawTx := buffer.Bytes()
return rawTx, nil
}
// decodeTx decodes raw tx bytes.
func decodeTx(rawTx []byte) (*wire.MsgTx, error) {
tx := wire.MsgTx{}
r := bytes.NewReader(rawTx)
err := tx.BtcDecode(r, 0, wire.WitnessEncoding)
if err != nil {
return nil, err
}
return &tx, nil
}
// decodeBlock decodes a raw block into a struct.
func decodeBlock(rawBlock []byte) (*wire.MsgBlock, error) {
var block wire.MsgBlock
err := block.Deserialize(bytes.NewReader(rawBlock))
if err != nil {
return nil, err
}
return &block, nil
}
// NewOutpointFromStr creates an outpoint from a string with the format
// txid:index.
func NewOutpointFromStr(outpoint string) (*wire.OutPoint, error) {
parts := strings.Split(outpoint, ":")
if len(parts) != 2 {
return nil, errors.New("outpoint should be of the form txid:index")
}
hash, err := chainhash.NewHashFromStr(parts[0])
if err != nil {
return nil, err
}
outputIndex, err := strconv.Atoi(parts[1])
if err != nil {
return nil, fmt.Errorf("invalid output index: %v", err)
}
return &wire.OutPoint{
Hash: *hash,
Index: uint32(outputIndex),
}, nil
}