THAMER
Sovereign Bitcoin Wallet

WALLET AI BITCOIN

Your Bitcoin Wallet. Your Keys. Your Engine.

Self-hosted Bitcoin software built for developers, applications, and AI agents.

CREATE WALLET

Testing Bitcoin Transaction Serialization and UTXO Accounting in Go

permalink THAMER
#bitcoin#bitcoin-script#golang#transactions#utxo

Regression tests should cover exact wire bytes, witness identity separation, weight rounding, missing prevouts, duplicate inputs and invalid monetary amounts. Passing these tests is not equivalent to consensus validation.

Go implementation

Go · 83 lines
51func (t Transaction) Serialize(witness bool) []byte {
52	var b bytes.Buffer
53	put := func(v any) { binary.Write(&b, binary.LittleEndian, v) }
54	put(t.Version)
55	has := false
56	for _, in := range t.Inputs {
57		if len(in.Witness) > 0 {
58			has = true
59		}
60	}
61	has = has && witness
62	if has {
63		b.Write([]byte{0, 1})
64	}
65	compact(&b, uint64(len(t.Inputs)))
66	for _, in := range t.Inputs {
67		b.Write(in.Previous.Hash[:])
68		put(in.Previous.Index)
69		blob(&b, in.Script)
70		put(in.Sequence)
71	}
72	compact(&b, uint64(len(t.Outputs)))
73	for _, out := range t.Outputs {
74		put(out.Value)
75		blob(&b, out.Script)
76	}
77	if has {
78		for _, in := range t.Inputs {
79			compact(&b, uint64(len(in.Witness)))
80			for _, item := range in.Witness {
81				blob(&b, item)
82			}
83		}
84	}
85	put(t.LockTime)
86	return b.Bytes()
87}
88
89func displayHash(data []byte) string {
90	h := sha256.Sum256(data)
91	h = sha256.Sum256(h[:])
92	for i := 0; i < 16; i++ {
93		h[i], h[31-i] = h[31-i], h[i]
94	}
95	return hex.EncodeToString(h[:])
96}
97func (t Transaction) TXID() string  { return displayHash(t.Serialize(false)) }
98func (t Transaction) WTXID() string { return displayHash(t.Serialize(true)) }
99func (t Transaction) Weight() int   { return 3*len(t.Serialize(false)) + len(t.Serialize(true)) }
100func (t Transaction) VSize() int    { return (t.Weight() + 3) / 4 }
101
102// Fee checks a supplied UTXO snapshot, not chain state or scripts.
103func (t Transaction) Fee(coins map[OutPoint]Output) (int64, error) {
104	if len(t.Inputs) == 0 || len(t.Outputs) == 0 {
105		return 0, errors.New("empty transaction")
106	}
107	var totalIn, totalOut int64
108	seen := make(map[OutPoint]bool)
109	for _, in := range t.Inputs {
110		if seen[in.Previous] {
111			return 0, errors.New("duplicate input")
112		}
113		seen[in.Previous] = true
114		coin, ok := coins[in.Previous]
115		if !ok {
116			return 0, errors.New("missing prevout")
117		}
118		if coin.Value < 0 || coin.Value > MaxMoney-totalIn {
119			return 0, errors.New("input amount out of range")
120		}
121		totalIn += coin.Value
122	}
123	for _, out := range t.Outputs {
124		if out.Value < 0 || out.Value > MaxMoney-totalOut {
125			return 0, errors.New("output amount out of range")
126		}
127		totalOut += out.Value
128	}
129	if totalOut > totalIn {
130		return 0, errors.New("insufficient input value")
131	}
132	return totalIn - totalOut, nil
133}

Practical exercise

Run go test -race -v ./... and go vet ./... before modifying the fixture.

Local verification

From the repository directory golang-bitcoin/006-transactions, run:

go test -race -v ./...
go vet ./...
Go · 57 lines
1package tx
2
3import (
4	"encoding/hex"
5	"strings"
6	"testing"
7)
8
9func fixture() Transaction {
10	return Transaction{Version: 2, Inputs: []Input{{Previous: OutPoint{Hash: [32]byte{1}, Index: 3}, Sequence: 0xfffffffd}}, Outputs: []Output{{Value: 9000, Script: []byte{0x51}}}}
11}
12func TestSerialization(t *testing.T) {
13	x := fixture()
14	want := "020000000101" + strings.Repeat("00", 31) + "0300000000fdffffff012823000000000000015100000000"
15	if got := hex.EncodeToString(x.Serialize(false)); got != want {
16		t.Fatal(got, want)
17	}
18	if x.TXID() != x.WTXID() {
19		t.Fatal("legacy hash mismatch")
20	}
21}
22func TestWitness(t *testing.T) {
23	x := fixture()
24	id := x.TXID()
25	x.Inputs[0].Witness = [][]byte{{1, 2}}
26	if x.TXID() != id || x.WTXID() == id {
27		t.Fatal("hash separation")
28	}
29	if x.Weight() != 250 || x.VSize() != 63 {
30		t.Fatal(x.Weight(), x.VSize())
31	}
32}
33func TestFee(t *testing.T) {
34	x := fixture()
35	coins := map[OutPoint]Output{x.Inputs[0].Previous: {Value: 10000}}
36	f, e := x.Fee(coins)
37	if e != nil || f != 1000 {
38		t.Fatal(f, e)
39	}
40	if _, e = x.Fee(nil); e == nil {
41		t.Fatal("missing coin")
42	}
43	x.Inputs = append(x.Inputs, x.Inputs[0])
44	if _, e = x.Fee(coins); e == nil {
45		t.Fatal("duplicate")
46	}
47}
48func TestAmounts(t *testing.T) {
49	x := fixture()
50	coins := map[OutPoint]Output{x.Inputs[0].Previous: {Value: 10000}}
51	for _, v := range []int64{-1, 10001, MaxMoney + 1} {
52		x.Outputs[0].Value = v
53		if _, e := x.Fee(coins); e == nil {
54			t.Fatal(v)
55		}
56	}
57}

Scope and security

This offline educational serializer uses synthetic data. It does not parse untrusted transactions, sign, broadcast, execute scripts, enforce locktimes, or validate consensus and mempool policy. The supplied UTXO map is not authenticated chain state. Do not use these examples to spend real funds.

References

https://developer.bitcoin.org/reference/transactions.html

https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki

https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki

https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki

https://github.com/btcsuite/btcd/tree/master/wire

Questions & Answers

Explore all questions →

Latest from the Lab

THAMER illustrated developer portrait and signature

ABOUT THE DEVELOPER

Independent Software Developer specializing in Bitcoin Script, Golang, and AI Agents.

Software engineering · Independent research · Open-source projects