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

Bitcoin Schnorr Signatures with btcec in Go

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

GOLANG + BITCOIN SCRIPT — Stage 002, Lesson 09 of 14.

Engineering concept

BIP340 specifies 64-byte Schnorr signatures over secp256k1 with x-only public keys. The example signs a 32-byte demonstration digest using the library and verifies it. The test uses official vector zero with private scalar 3, zero message and zero auxiliary randomness. Fixed keys and auxiliary data are public test fixtures only.

Source example

Go · 24 lines
1package main
2
3import (
4	"crypto/sha256"
5	"fmt"
6	"github.com/btcsuite/btcd/btcec/v2"
7	"github.com/btcsuite/btcd/btcec/v2/schnorr"
8)
9
10func fixture() *btcec.PrivateKey {
11	b := make([]byte, 32)
12	b[31] = 3
13	k, _ := btcec.PrivKeyFromBytes(b)
14	return k
15}
16func main() {
17	k := fixture()
18	h := sha256.Sum256([]byte("educational message"))
19	s, e := schnorr.Sign(k, h[:])
20	if e != nil {
21		panic(e)
22	}
23	fmt.Printf("x-only: %x\nsignature: %x\nverified: %t\n", schnorr.SerializePubKey(k.PubKey()), s.Serialize(), s.Verify(h[:], k.PubKey()))
24}

Regression test

Go · 31 lines
1package main
2
3import (
4	"encoding/hex"
5	"github.com/btcsuite/btcd/btcec/v2/schnorr"
6	"testing"
7)
8
9func TestVector(t *testing.T) {
10	k := fixture()
11	h := make([]byte, 32)
12	s, e := schnorr.Sign(k, h, schnorr.CustomNonce([32]byte{}))
13	if e != nil {
14		t.Fatal(e)
15	}
16	want := "e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca821525f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0"
17	if hex.EncodeToString(s.Serialize()) != want {
18		t.Fatal("BIP340 vector 0 mismatch")
19	}
20	p, e := schnorr.ParsePubKey(schnorr.SerializePubKey(k.PubKey()))
21	if e != nil || !s.Verify(h, p) {
22		t.Fatal("verify failed")
23	}
24	h[0] = 1
25	if s.Verify(h, p) {
26		t.Fatal("tamper accepted")
27	}
28	if _, e := schnorr.ParseSignature([]byte{1}); e == nil {
29		t.Fatal("bad signature")
30	}
31}

Run locally

From the downloaded repository root, enter 002-cryptography/05-schnorr.

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://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki

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