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 ECDSA DER Signature Encoding in Go

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

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

Engineering concept

DER represents ECDSA r and s as ASN.1 integers inside a sequence. Integer sign padding and minimal encoding matter. BIP66 specifies strict DER rules for applicable Bitcoin script signatures. A transaction signature also carries a sighash type byte outside the DER object. The example round-trips DER and rejects truncated data; it is not a complete script-policy validator.

Source example

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

Regression test

Go · 29 lines
1package main
2
3import (
4	"bytes"
5	"crypto/sha256"
6	"github.com/btcsuite/btcd/btcec/v2/ecdsa"
7	"testing"
8)
9
10func TestSignature(t *testing.T) {
11	k := fixture()
12	h := sha256.Sum256([]byte("demo"))
13	s := ecdsa.Sign(k, h[:])
14	b := s.Serialize()
15	if !bytes.Equal(b, ecdsa.Sign(k, h[:]).Serialize()) {
16		t.Fatal("not deterministic")
17	}
18	p, e := ecdsa.ParseDERSignature(b)
19	if e != nil || !p.Verify(h[:], k.PubKey()) {
20		t.Fatal("verify failed")
21	}
22	h[0] ^= 1
23	if p.Verify(h[:], k.PubKey()) {
24		t.Fatal("tamper accepted")
25	}
26	if _, e := ecdsa.ParseDERSignature([]byte{0x30}); e == nil {
27		t.Fatal("bad DER")
28	}
29}

Run locally

From the downloaded repository root, enter 002-cryptography/04-ecdsa.

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-0066.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