-
Notifications
You must be signed in to change notification settings - Fork 2
/
tx_pack.go
99 lines (81 loc) · 1.91 KB
/
tx_pack.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
package mscutil
import (
"bytes"
"encoding/binary"
"github.com/conformal/btcutil"
)
type TxPack struct {
Time int64
Height int64
Txs []*btcutil.Tx
}
//|time|height |len(txs)|len(tx)|tx bytes|len(tx)|tx bytes|
func (pack *TxPack) Deserialize(data []byte) error {
buff := bytes.NewBuffer(data)
var err error
err = binary.Read(buff, binary.LittleEndian, &pack.Time)
if err != nil {
return err
}
err = binary.Read(buff, binary.LittleEndian, &pack.Height)
if err != nil {
return err
}
var txSize uint32
err = binary.Read(buff, binary.LittleEndian, &txSize)
if err != nil {
return err
}
pack.Txs = make([]*btcutil.Tx, txSize)
// Loop for each transaction
for i := uint32(0); i < txSize; i++ {
// Get the length of the transaction in bytes
var byteLength uint32
err = binary.Read(buff, binary.LittleEndian, &byteLength)
if err != nil {
return err
}
// Make the buffer equal to the amount written (= len(tx)
txBuff := make([]byte, byteLength)
// Read the tx
err = binary.Read(buff, binary.LittleEndian, &txBuff)
if err != nil {
return err
}
// Create a new transaction
pack.Txs[i], err = btcutil.NewTxFromBytes(txBuff)
if err != nil {
return err
}
}
return nil
}
func (pack *TxPack) Serialize() ([]byte, error) {
var buff bytes.Buffer
var err error
err = binary.Write(&buff, binary.LittleEndian, pack.Time)
if err != nil {
return nil, err
}
err = binary.Write(&buff, binary.LittleEndian, pack.Height)
if err != nil {
return nil, err
}
err = binary.Write(&buff, binary.LittleEndian, uint32(len(pack.Txs)))
if err != nil {
return nil, err
}
for _, tx := range pack.Txs {
var b bytes.Buffer
tx.MsgTx().Serialize(&b)
err = binary.Write(&buff, binary.LittleEndian, uint32(b.Len()))
if err != nil {
return nil, err
}
err = binary.Write(&buff, binary.LittleEndian, b.Bytes())
if err != nil {
return nil, err
}
}
return buff.Bytes(), nil
}