Testing Bitcoin Signature Verification and Tampering in Go
GOLANG + BITCOIN SCRIPT — Stage 002, Lesson 11 of 14.
Engineering concept
A valid signature must verify against the intended message and public key. The test modifies the message after signing and checks rejection, and rejects malformed signature length. A successful cryptographic verification alone does not prove a transaction is spendable: script rules, UTXO context and consensus conditions also apply.
Source example
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
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
