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

Deterministic ECDSA and Nonce Safety in Go

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

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

Engineering concept

Reusing an ECDSA nonce across distinct message digests can reveal the private key. Deterministic signing derives the nonce from the key and digest using a defined algorithm rather than a caller-supplied random integer. The test compares repeated signatures for the same fixture and digest. This does not prove side-channel resistance or safe key storage. Never implement nonce arithmetic for production signing.

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://www.rfc-editor.org/rfc/rfc6979

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