Validating Bitcoin Private Keys in Go
GOLANG + BITCOIN SCRIPT — Stage 002, Lesson 02 of 14.
Engineering concept
A serialized private scalar must contain exactly 32 bytes and represent an integer from 1 through n−1. Reject zero, n, oversized and truncated inputs before passing them to a library that may reduce scalars modulo n. The test checks both invalid boundaries and a valid scalar. This big.Int example is for input validation, not secret-dependent elliptic curve arithmetic.
Source example
1package main
2
3import (
4 "crypto/rand"
5 "encoding/hex"
6 "fmt"
7 "math/big"
8)
9
10var order, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16)
11
12func valid(b []byte) bool {
13 return len(b) == 32 && new(big.Int).SetBytes(b).Sign() > 0 && new(big.Int).SetBytes(b).Cmp(order) < 0
14}
15func generate() ([]byte, error) {
16 n, e := rand.Int(rand.Reader, new(big.Int).Sub(order, big.NewInt(1)))
17 if e != nil {
18 return nil, e
19 }
20 return n.Add(n, big.NewInt(1)).FillBytes(make([]byte, 32)), nil
21}
22func main() {
23 b, _ := hex.DecodeString("0000000000000000000000000000000000000000000000000000000000000001")
24 fmt.Println(valid(b))
25}Regression test
1package main
2
3import (
4 "math/big"
5 "testing"
6)
7
8func TestBounds(t *testing.T) {
9 for _, n := range []*big.Int{big.NewInt(0), order} {
10 if valid(n.FillBytes(make([]byte, 32))) {
11 t.Fatal("invalid scalar accepted")
12 }
13 }
14 if !valid(big.NewInt(1).FillBytes(make([]byte, 32))) || valid([]byte{1}) {
15 t.Fatal("bounds")
16 }
17}
18func TestGenerate(t *testing.T) {
19 b, e := generate()
20 if e != nil || !valid(b) {
21 t.Fatal("generation failed")
22 }
23}Run locally
From the downloaded repository root, enter 002-cryptography/01-scalars.
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
