-
Notifications
You must be signed in to change notification settings - Fork 10
/
block.go
94 lines (77 loc) · 2.25 KB
/
block.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
// Package bc is a bitcoin blockchain library bc = block chain.
package bc
import (
"encoding/hex"
"errors"
"github.com/libsv/go-bt/v2"
)
/*
Field Purpose Size (Bytes)
----------------------------------------------------------------------------------------------------
block_header Block Header 80
txn_count Total number of txs in this block, including the coinbase tx VarInt
txns Every tx in this block, one after another, in raw tx format -
*/
// A Block in the Bitcoin blockchain.
type Block struct {
BlockHeader *BlockHeader
Txs []*bt.Tx
}
// String returns the Block Header encoded as hex string.
func (b *Block) String() string {
return hex.EncodeToString(b.Bytes())
}
// Bytes will decode a bitcoin block struct into a byte slice.
//
// See https://btcinformation.org/en/developer-reference#serialized-blocks
func (b *Block) Bytes() []byte {
bytes := []byte{}
bytes = append(bytes, b.BlockHeader.Bytes()...)
txCount := uint64(len(b.Txs))
bytes = append(bytes, bt.VarInt(txCount).Bytes()...)
for _, tx := range b.Txs {
bytes = append(bytes, tx.Bytes()...)
}
return bytes
}
// NewBlockFromStr will encode a block header hash
// into the bitcoin block header structure.
//
// See https://btcinformation.org/en/developer-reference#serialized-blocks
func NewBlockFromStr(blockStr string) (*Block, error) {
blockBytes, err := hex.DecodeString(blockStr)
if err != nil {
return nil, err
}
return NewBlockFromBytes(blockBytes)
}
// NewBlockFromBytes will encode a block header byte slice
// into the bitcoin block header structure.
//
// See https://btcinformation.org/en/developer-reference#serialized-blocks
func NewBlockFromBytes(b []byte) (*Block, error) {
if len(b) == 0 {
return nil, errors.New("block cannot be empty")
}
var offset int
bh, err := NewBlockHeaderFromBytes(b[:80])
if err != nil {
return nil, err
}
offset += 80
txCount, size := bt.NewVarIntFromBytes(b[offset:])
offset += size
var txs []*bt.Tx
for i := 0; i < int(txCount); i++ {
tx, size, err := bt.NewTxFromStream(b[offset:])
if err != nil {
return nil, err
}
txs = append(txs, tx)
offset += size
}
return &Block{
BlockHeader: bh,
Txs: txs,
}, nil
}