Understanding Bitcoin secp256k1 in Go
GOLANG + BITCOIN SCRIPT — Stage 002, Lesson 01 of 14.
Engineering concept
Bitcoin uses the curve y² = x³ + 7 over the prime field p = 2²⁵⁶ − 2³² − 977. The group order n is distinct from p. A private scalar d maps to the public point dG. The example uses d=1, so its public point must equal the published generator. Never use this public fixture for funds. Go crypto/elliptic P256 is a different curve; use a dedicated secp256k1 library.
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
