ECDSA vs Schnorr in Bitcoin: A Go Developer Guide
GOLANG + BITCOIN SCRIPT — Stage 002, Lesson 13 of 14.
Engineering concept
Legacy and SegWit v0 signature checks use ECDSA; Taproot uses BIP340 Schnorr for its defined signature checks. ECDSA DER signatures vary in length, whereas BIP340 signatures are 64 bytes before any transaction-specific sighash byte. Neither signature format is interchangeable. Compare the ECDSA example with the separate Schnorr module; both sign demonstration digests, not transactions.
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/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
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-0340.mediawiki
Previous stage
https://thamer.org/learn/bitcoin-development-libraries-go
