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

Understanding Bitcoin secp256k1 in Go

permalink THAMER
#bitcoin#bitcoin-script#cryptography#golang

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

Go · 17 lines
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

Go · 20 lines
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

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