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

Building P2WPKH Outputs in Go

permalink THAMER
#bip141#bitcoin#golang#segwit

GOLANG + BITCOIN SCRIPT — Stage 009, Lesson 03 of 12.

Engineering concept

P2WPKH commits to HASH160 of a public key. The output script is 00 14 followed by 20 bytes. The spending witness contains a signature and public key; native scriptSig must be empty. The example accepts an already computed hash, not a public key.

Source example

Inspect P2WPKH in the educational package below. Inputs are public fixtures; never treat this package as a wallet or consensus validator.

Go · 105 lines
1package segwit
2
3import (
4	"bytes"
5	"crypto/sha256"
6	"encoding/binary"
7	"errors"
8)
9
10func Hash256(b []byte) [32]byte { h := sha256.Sum256(b); return sha256.Sum256(h[:]) }
11func P2WPKH(hash []byte) ([]byte, error) {
12	if len(hash) != 20 {
13		return nil, errors.New("expected 20-byte hash")
14	}
15	return append([]byte{0, 20}, hash...), nil
16}
17func P2WSH(script []byte) []byte                       { h := sha256.Sum256(script); return append([]byte{0, 32}, h[:]...) }
18func MatchesWitnessScript(program, script []byte) bool { return bytes.Equal(program, P2WSH(script)) }
19func P2WPKHScriptCode(hash []byte) ([]byte, error) {
20	if len(hash) != 20 {
21		return nil, errors.New("expected 20-byte hash")
22	}
23	b := append([]byte{0x76, 0xa9, 20}, hash...)
24	return append(b, 0x88, 0xac), nil
25}
26func compact(b *bytes.Buffer, n uint64) {
27	switch {
28	case n < 253:
29		b.WriteByte(byte(n))
30	case n <= 65535:
31		b.WriteByte(253)
32		binary.Write(b, binary.LittleEndian, uint16(n))
33	case n <= 0xffffffff:
34		b.WriteByte(254)
35		binary.Write(b, binary.LittleEndian, uint32(n))
36	default:
37		b.WriteByte(255)
38		binary.Write(b, binary.LittleEndian, n)
39	}
40}
41func SerializeWitness(items [][]byte) []byte {
42	var b bytes.Buffer
43	compact(&b, uint64(len(items)))
44	for _, v := range items {
45		compact(&b, uint64(len(v)))
46		b.Write(v)
47	}
48	return b.Bytes()
49}
50
51type Outpoint struct {
52	Hash  [32]byte
53	Index uint32
54}
55type Input struct {
56	Previous Outpoint
57	Sequence uint32
58}
59type Output struct {
60	Value  int64
61	Script []byte
62}
63type Tx struct {
64	Version  int32
65	Inputs   []Input
66	Outputs  []Output
67	Locktime uint32
68}
69
70func put(b *bytes.Buffer, v any)           { binary.Write(b, binary.LittleEndian, v) }
71func outpoint(b *bytes.Buffer, o Outpoint) { b.Write(o.Hash[:]); put(b, o.Index) }
72
73// SighashAll implements BIP143 SIGHASH_ALL only, with caller-supplied scriptCode.
74// Outpoint hashes must be in wire byte order. This is not a transaction validator.
75func SighashAll(t Tx, index int, scriptCode []byte, amount int64) ([32]byte, error) {
76	if index < 0 || index >= len(t.Inputs) || amount < 0 || amount > 2100000000000000 {
77		return [32]byte{}, errors.New("invalid input or amount")
78	}
79	var p, s, o, b bytes.Buffer
80	for _, in := range t.Inputs {
81		outpoint(&p, in.Previous)
82		put(&s, in.Sequence)
83	}
84	for _, v := range t.Outputs {
85		if v.Value < 0 || v.Value > 2100000000000000 {
86			return [32]byte{}, errors.New("invalid output")
87		}
88		put(&o, v.Value)
89		compact(&o, uint64(len(v.Script)))
90		o.Write(v.Script)
91	}
92	hp, hs, ho := Hash256(p.Bytes()), Hash256(s.Bytes()), Hash256(o.Bytes())
93	put(&b, t.Version)
94	b.Write(hp[:])
95	b.Write(hs[:])
96	outpoint(&b, t.Inputs[index].Previous)
97	compact(&b, uint64(len(scriptCode)))
98	b.Write(scriptCode)
99	put(&b, amount)
100	put(&b, t.Inputs[index].Sequence)
101	b.Write(ho[:])
102	put(&b, t.Locktime)
103	put(&b, uint32(1))
104	return Hash256(b.Bytes()), nil
105}
Source: /repo/golang-bitcoin/009-segwit/segwit.go · Raw file · Read-only excerpt

Regression tests

Go · 50 lines
1package segwit
2
3import (
4	"bytes"
5	"encoding/hex"
6	"testing"
7)
8
9func TestPrograms(t *testing.T) {
10	h, _ := hex.DecodeString("751e76e8199196d454941c45d1b3a323f1433bd6")
11	p, e := P2WPKH(h)
12	if e != nil || hex.EncodeToString(p) != "0014751e76e8199196d454941c45d1b3a323f1433bd6" {
13		t.Fatal(p, e)
14	}
15	c, _ := P2WPKHScriptCode(h)
16	if hex.EncodeToString(c) != "76a914751e76e8199196d454941c45d1b3a323f1433bd688ac" {
17		t.Fatal(c)
18	}
19	if _, e = P2WPKH(nil); e == nil {
20		t.Fatal("length")
21	}
22	s := []byte{0x51}
23	if !MatchesWitnessScript(P2WSH(s), s) || MatchesWitnessScript(P2WSH(s), []byte{0x52}) {
24		t.Fatal("commitment")
25	}
26}
27func TestWitness(t *testing.T) {
28	if !bytes.Equal(SerializeWitness([][]byte{nil, {1, 2}}), []byte{2, 0, 2, 1, 2}) {
29		t.Fatal("encoding")
30	}
31}
32func TestDigest(t *testing.T) {
33	tx := Tx{Version: 2, Inputs: []Input{{Sequence: 0xfffffffd}}, Outputs: []Output{{Value: 100, Script: []byte{0x51}}}}
34	a, e := SighashAll(tx, 0, []byte{0x51}, 200)
35	if e != nil {
36		t.Fatal(e)
37	}
38	b, _ := SighashAll(tx, 0, []byte{0x51}, 201)
39	if a == b {
40		t.Fatal("amount not committed")
41	}
42	tx.Outputs[0].Value++
43	b, _ = SighashAll(tx, 0, []byte{0x51}, 200)
44	if a == b {
45		t.Fatal("output not committed")
46	}
47	if _, e = SighashAll(tx, 1, nil, 200); e == nil {
48		t.Fatal("index")
49	}
50}

Run locally

cd repo/golang-bitcoin/009-segwit/
go test -race -v ./...
go vet ./...

Practical exercise

Run the tests, then change a fixture relevant to P2WPKH and predict whether the serialized bytes, commitment or digest should change. Add an assertion before running the test again. Keep raw wire bytes separate from display hexadecimal.

Primary reference

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

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