Generating Bitcoin Private Scalars with Go Crypto Rand
GOLANG + BITCOIN SCRIPT — Stage 002, Lesson 03 of 14.
Engineering concept
Use crypto/rand rather than math/rand or timestamps. Sampling uniformly below n−1 and adding one produces the valid scalar interval without modulo bias. The example exposes a generator function but prints only a validation result for a public fixture. The test checks range, not entropy quality. Production wallet generation also needs secure storage and recovery design.
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/crypto/rand
Previous stage
https://thamer.org/learn/bitcoin-development-libraries-go
