Compressed and Uncompressed Bitcoin Public Keys in Go
GOLANG + BITCOIN SCRIPT — Stage 002, Lesson 04 of 14.
Engineering concept
SEC compressed encoding uses a parity prefix 02 or 03 and 32 bytes of x; uncompressed encoding uses 04 and both 32-byte coordinates. These encodings identify the same point but produce different hashes. Parse public keys with the library rather than accepting arbitrary byte strings. The generator fixture is checked against its known compressed encoding.
Source example
1package main
2
3import (
4 "fmt"
5 "github.com/btcsuite/btcd/btcec/v2"
6)
7
8func fixture() *btcec.PrivateKey {
9 b := make([]byte, 32)
10 b[31] = 1
11 k, _ := btcec.PrivKeyFromBytes(b)
12 return k
13}
14func main() {
15 p := fixture().PubKey()
16 fmt.Printf("compressed: %x\nuncompressed: %x\n", p.SerializeCompressed(), p.SerializeUncompressed())
17}Regression test
1package main
2
3import (
4 "encoding/hex"
5 "github.com/btcsuite/btcd/btcec/v2"
6 "testing"
7)
8
9func TestGenerator(t *testing.T) {
10 b := fixture().PubKey().SerializeCompressed()
11 if hex.EncodeToString(b) != "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" {
12 t.Fatal("generator mismatch")
13 }
14 if _, e := btcec.ParsePubKey(b); e != nil {
15 t.Fatal(e)
16 }
17 if _, e := btcec.ParsePubKey([]byte{2}); e == nil {
18 t.Fatal("bad key accepted")
19 }
20}Run locally
From the downloaded repository root, enter 002-cryptography/03-public-keys.
The external dependency is pinned but could not be downloaded in the authoring environment; run the commands below before relying on the example.
go mod tidy
go test -race ./...
go run .
All examples are educational and local. Never fund the published fixture keys. No network transaction is created.
Reference
https://pkg.go.dev/github.com/btcsuite/btcd/btcec/v2
Previous stage
https://thamer.org/learn/bitcoin-development-libraries-go
