forked from libsv/go-bc
-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathblock.go
More file actions
96 lines (79 loc) · 2.57 KB
/
block.go
File metadata and controls
96 lines (79 loc) · 2.57 KB
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
// Package bc is a bitcoin blockchain library bc = block chain.
package bc
import (
"encoding/hex"
"github.com/bsv-blockchain/go-bt/v2"
)
/*
| Field | Purpose | Size (Bytes) |
|--------------|------------------------------------------------------------|--------------|
| block_header | Block Header | 80 |
| txn_count | Total number of txs in this block, including coinbase tx | VarInt |
| txs | 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 {
// Preallocate: 80 (header) + 9 (max varint) + estimated tx bytes
bytes := make([]byte, 0, 80+9+len(b.Txs)*250)
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, ErrBlockEmpty
}
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
// Safe conversion: txCount should never exceed reasonable transaction count
txCountInt := int(txCount) //nolint:gosec // G115: Safe conversion - txCount is bounded by block size limits
for i := 0; i < txCountInt; 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
}