Digital Signatures
ECDSA, EdDSA, Schnorr signatures, multi-signature schemes, threshold signatures, key recovery, and signature aggregation.
Overview
Digital signatures provide authentication, integrity, and non-repudiation in blockchain transactions. They prove ownership of private keys without revealing them.
Elliptic Curve Digital Signature Algorithm (ECDSA)
ECDSA is the signature scheme used in Bitcoin and many other cryptocurrencies.
Mathematical Foundation
Given elliptic curve over finite field with generator point of order :
Key Generation:
- Private key:
- Public key:
Signature Generation:
- Choose random
- Compute , let
- Compute
- Signature:
Verification:
- Compute
- Compute
- Compute
- Valid if
ECDSA Implementation
from hashlib import sha256
from secrets import randbelow
class ECDSASignature:
"""Simplified ECDSA implementation for educational purposes."""
def __init__(self, curve_params):
self.p = curve_params['p']
self.a = curve_params['a']
self.b = curve_params['b']
self.G = curve_params['G']
self.n = curve_params['n']
def point_add(self, P, Q):
"""Add two points on the elliptic curve."""
if P is None:
return Q
if Q is None:
return P
x1, y1 = P
x2, y2 = Q
if x1 == x2 and y1 != y2:
return None # Point at infinity
if x1 == x2:
lam = (3 * x1 * x1 + self.a) * pow(2 * y1, -1, self.p) % self.p
else:
lam = (y2 - y1) * pow(x2 - x1, -1, self.p) % self.p
x3 = (lam * lam - x1 - x2) % self.p
y3 = (lam * (x1 - x3) - y1) % self.p
return (x3, y3)
def scalar_mult(self, k, P):
"""Scalar multiplication using double-and-add."""
result = None
addend = P
while k:
if k & 1:
result = self.point_add(result, addend)
addend = self.point_add(addend, addend)
k >>= 1
return result
def keygen(self):
"""Generate ECDSA key pair."""
private_key = randbelow(self.n - 1) + 1
public_key = self.scalar_mult(private_key, self.G)
return private_key, public_key
def sign(self, private_key, message: bytes):
"""Sign a message."""
z = int.from_bytes(sha256(message).digest(), 'big') % self.n
while True:
k = randbelow(self.n - 1) + 1
R = self.scalar_mult(k, self.G)
r = R[0] % self.n
if r == 0:
continue
s = (pow(k, -1, self.n) * (z + r * private_key)) % self.n
if s == 0:
continue
return (r, s)
def verify(self, public_key, message: bytes, signature):
"""Verify ECDSA signature."""
r, s = signature
z = int.from_bytes(sha256(message).digest(), 'big') % self.n
if not (1 <= r < self.n and 1 <= s < self.n):
return False
w = pow(s, -1, self.n)
u1 = (z * w) % self.n
u2 = (r * w) % self.n
P = self.point_add(
self.scalar_mult(u1, self.G),
self.scalar_mult(u2, public_key)
)
if P is None:
return False
return P[0] % self.n == r
# secp256k1 parameters (simplified)
secp256k1 = {
'p': 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F,
'a': 0,
'b': 7,
'G': (
0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
),
'n': 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
}
ecdsa = ECDSASignature(secp256k1)
priv_key, pub_key = ecdsa.keygen()
message = b"Transfer 1 BTC"
signature = ecdsa.sign(priv_key, message)
print(f"Signature valid: {ecdsa.verify(pub_key, message, signature)}")
ECDSA Security Considerations
| Issue | Description | Mitigation |
|---|---|---|
| Nonce reuse | Same leaks private key | RFC 6979 deterministic nonces |
| Weak randomness | Predictable enables attack | Use CSPRNG |
| Malleability | is also valid | BIP-62, SegWit |
| Side-channel attacks | Timing, power analysis | Constant-time implementations |
EdDSA (Ed25519)
Edwards-curve Digital Signature Algorithm offers better performance and security than ECDSA.
Ed25519 Properties
- Curve: Twisted Edwards curve over
- Signature size: 64 bytes
- Public key size: 32 bytes
- Deterministic nonces (no random number generation needed for signing)
Ed25519 Implementation
from hashlib import sha512
from secrets import randbits
# Ed25519 constants
q = 2**255 - 19
d = -121665 * pow(121666, -1, q) % q
I = pow(2, (q - 1) // 4, q) # Square root of -1
class Ed25519:
"""Simplified Ed25519 implementation."""
def point_add(self, P, Q):
"""Add points on Ed25519 curve."""
if P is None:
return Q
if Q is None:
return P
x1, y1 = P
x2, y2 = Q
x3 = (x1 * y2 + y1 * x2) * pow(1 + d * x1 * x2 * y1 * y2, -1, q) % q
y3 = (y1 * y2 - d * x1 * x2 * y1 * y2 * x1 * x2) * pow(1 - d * x1 * x2 * y1 * y2, -1, q) % q
return (x3, y3)
def scalar_mult(self, k, P):
"""Scalar multiplication."""
result = None
addend = P
while k:
if k & 1:
result = self.point_add(result, addend)
addend = self.point_add(addend, addend)
k >>= 1
return result
def encode_point(self, P):
"""Encode point to bytes."""
x, y = P
return (y | ((x & 1) << 255)).to_bytes(32, 'little')
def keygen(self, seed: bytes = None):
"""Generate Ed25519 key pair."""
if seed is None:
seed = randbits(256).to_bytes(32, 'big')
# Hash seed to get private scalar
h = sha512(seed).digest()
a = int.from_bytes(h[:32], 'little')
a = a & ((1 << 254) - 8) | (1 << 254) # Cofactor clearing
# Clamp
a = a & ((1 << 254) - 8) | (1 << 254)
A = self.scalar_mult(a, (self.Bx, self.By))
return seed, a, A
def sign(self, secret_key: bytes, message: bytes):
"""Sign message with Ed25519."""
h = sha512(secret_key).digest()
a = int.from_bytes(h[:32], 'little') & ((1 << 254) - 8) | (1 << 254)
A = self.scalar_mult(a, (self.Bx, self.By))
# Deterministic nonce
r = int.from_bytes(sha512(h[32:] + message).digest(), 'little') % self.l
R = self.scalar_mult(r, (self.Bx, self.By))
k = int.from_bytes(
sha512(self.encode_point(R) + self.encode_point(A) + message).digest(),
'little'
) % self.l
S = (r + k * a) % self.l
return self.encode_point(R) + S.to_bytes(32, 'little')
def verify(self, public_key: bytes, message: bytes, signature: bytes):
"""Verify Ed25519 signature."""
if len(signature) != 64:
return False
A = self.decode_point(public_key)
R = self.decode_point(signature[:32])
S = int.from_bytes(signature[32:], 'little')
h = int.from_bytes(
sha512(signature[:32] + public_key + message).digest(),
'little'
) % self.l
P = self.point_add(
self.scalar_mult(S, (self.Bx, self.By)),
self.scalar_mult(h, self.point_neg(A))
)
return R == P
# Curve base point
ed25519 = Ed25519()
ed25519.Bx = 151122213495298422797791939744103834178482059765688096625737925335456694727480896
ed25519.By = 46316835694926478169428394956744886179139155277889686556834773011299949577687882
ed25519.l = 2**252 + 27742317777372353535851937790883648493
seed, priv, pub = ed25519.keygen()
message = b"Hello, Ed25519!"
sig = ed25519.sign(seed, message)
print(f"Ed25519 signature valid: {ed25519.verify(pub, message, sig)}")
Ed25519 vs ECDSA Comparison
| Feature | ECDSA (secp256k1) | Ed25519 |
|---|---|---|
| Curve | Weierstrass | Twisted Edwards |
| Signature size | 64 bytes | 64 bytes |
| Public key size | 33/65 bytes | 32 bytes |
| Deterministic | Optional (RFC 6979) | Mandatory |
| Speed | 2-3x slower | Faster |
| Side-channel resistance | Requires care | Built-in |
| Adoption | Bitcoin, Ethereum | Solana, Cardano |
Schnorr Signatures
Schnorr signatures enable signature aggregation and are used in Bitcoin's Taproot upgrade.
Schnorr Protocol
Key Generation:
- Private key:
- Public key:
Signature:
- Choose random
- Compute
- Compute
- Compute
- Signature:
Verification:
- Compute
- Check
Schnorr Implementation
from hashlib import sha256
class SchnorrSignature:
"""Simplified Schnorr signature scheme."""
def __init__(self, G, n):
self.G = G
self.n = n
def hash_point(self, *points):
"""Hash multiple points together."""
data = b""
for p in points:
if p is not None:
data += p[0].to_bytes(32, 'big') + p[1].to_bytes(32, 'big')
return int.from_bytes(sha256(data).digest(), 'big') % self.n
def sign(self, private_key, message: bytes):
"""Generate Schnorr signature."""
x = private_key
X = self.point_mult(x, self.G)
k = randbelow(self.n - 1) + 1
R = self.point_mult(k, self.G)
e = self.hash_point(R, X, message)
s = (k + e * x) % self.n
return (R, s)
def verify(self, public_key, message: bytes, signature):
"""Verify Schnorr signature."""
R, s = signature
X = public_key
e = self.hash_point(R, X, message)
lhs = self.point_mult(s, self.G)
rhs = self.point_add(R, self.point_mult(e, X))
return lhs == rhs
def aggregate_signatures(self, signatures, messages, public_keys):
"""Aggregate multiple Schnorr signatures."""
if len(signatures) != len(messages) != len(public_keys):
raise ValueError("Input lengths must match")
R_agg = None
s_agg = 0
for i, (R, s) in enumerate(signatures):
e = self.hash_point(R, public_keys[i], messages[i])
if R_agg is None:
R_agg = R
else:
R_agg = self.point_add(R_agg, R)
s_agg = (s_agg + s) % self.n
# Compute aggregated challenge
e_agg = self.hash_point(R_agg, *public_keys)
# Adjust s_agg
for i, (R, s) in enumerate(signatures):
e_i = self.hash_point(R, public_keys[i], messages[i])
# Subtract individual challenges
s_agg = (s_agg - e_i * (e_agg - e_i)) % self.n
return (R_agg, s_agg)
Schnorr Multi-Signature (MuSig)
MuSig allows multiple signers to produce a single signature that verifies against the aggregated public key.
Signers: Alice (x₁, X₁), Bob (x₂, X₂)
1. Aggregate public key: X = H(X₁, X₂) · X₁ + H(X₂, X₁) · X₂
2. Each signer i:
- Choose kᵢ, compute Rᵢ = kᵢ · G
- Broadcast Rᵢ
3. Compute R = R₁ + R₂
e = H(R, X, m)
4. Each signer computes:
sᵢ = kᵢ + e · (H(Xᵢ, X) · xᵢ)
5. Aggregate: s = s₁ + s₂
Signature: (R, s)
Multi-Signature Schemes
Bitcoin Script-based Multisig
class MultisigWallet:
"""Bitcoin-style m-of-n multisig."""
def __init__(self, public_keys: list, m: int):
"""
Args:
public_keys: List of participant public keys
m: Number of required signatures
"""
self.public_keys = public_keys
self.n = len(public_keys)
self.m = m
if m > self.n:
raise ValueError("m cannot exceed n")
def create_script(self) -> str:
"""Create redeem script (P2SH)."""
script = f"OP_{self.m} "
for pk in self.public_keys:
script += f"{pk.hex()} "
script += f"OP_{self.n} OP_CHECKMULTISIG"
return script
def sign(self, private_keys: dict, message: bytes) -> list:
"""Sign with required number of keys."""
signatures = []
for pk_index, priv_key in private_keys.items():
if pk_index >= self.n:
raise ValueError(f"Invalid key index: {pk_index}")
# Simplified signing
sig = self._sign_with_key(priv_key, message)
signatures.append({
'index': pk_index,
'signature': sig
})
return signatures
def verify(self, signatures: list, message: bytes) -> bool:
"""Verify m-of-n signatures."""
if len(signatures) < self.m:
return False
valid_count = 0
seen_indices = set()
for sig_info in signatures:
idx = sig_info['index']
if idx in seen_indices:
return False
seen_indices.add(idx)
if self._verify_signature(
self.public_keys[idx],
message,
sig_info['signature']
):
valid_count += 1
return valid_count >= self.m
# Create 2-of-3 multisig
multisig = MultisigWallet(
public_keys=[b"pk1", b"pk2", b"pk3"],
m=2
)
print(multisig.create_script())
Multisig Comparison
| Scheme | Type | Use Case | Flexibility |
|---|---|---|---|
| P2SH Multisig | On-chain | Bitcoin, legacy | Low |
| P2WSH Multisig | On-chain | Bitcoin, SegWit | Medium |
| Safe (Gnosis) | Smart contract | Ethereum | High |
| MuSig2 | Off-chain | Taproot | High |
Threshold Signatures
Threshold signatures distribute signing power among out of parties without revealing individual key shares.
Shamir's Secret Sharing
Where (private key)
from secrets import randbelow
from functools import reduce
class ShamirSecretSharing:
"""Shamir's Secret Sharing for threshold signatures."""
def __init__(self, prime: int):
self.p = prime
def split(self, secret: int, n: int, t: int) -> list:
"""Split secret into n shares with threshold t."""
coefficients = [secret]
for _ in range(t - 1):
coefficients.append(randbelow(self.p - 1))
shares = []
for x in range(1, n + 1):
y = sum(
coeff * pow(x, exp, self.p)
for exp, coeff in enumerate(coefficients)
) % self.p
shares.append((x, y))
return shares
def reconstruct(self, shares: list) -> int:
"""Reconstruct secret from t shares using Lagrange interpolation."""
secret = 0
for i, (xi, yi) in enumerate(shares):
numerator = 1
denominator = 1
for j, (xj, _) in enumerate(shares):
if i != j:
numerator = (numerator * (-xj)) % self.p
denominator = (denominator * (xi - xj)) % self.p
lagrange = (numerator * pow(denominator, -1, self.p)) % self.p
secret = (secret + yi * lagrange) % self.p
return secret
# Example: Split secret 42 into 5 shares, need 3 to reconstruct
sss = ShamirSecretSharing(prime=2**255 - 19)
shares = sss.split(42, n=5, t=3)
print(f"Shares: {shares}")
# Reconstruct with 3 shares
reconstructed = sss.reconstruct(shares[:3])
print(f"Reconstructed secret: {reconstructed}")
Threshold Signature Protocol
Setup:
1. Generate polynomial f(x) with f(0) = private_key
2. Distribute f(i) to party i (secret share)
Signing (t-of-n):
1. Each party i computes partial signature σᵢ = f(i) · H(m)
2. Combine using Lagrange coefficients:
σ = Σᵢ λᵢ · σᵢ
Where λᵢ = Πⱼ≠ᵢ (j / (j - i)) mod n
Key Recovery
ECDSA Key Recovery from Signature
Given ECDSA signature and message hash , we can recover the public key.
class ECDSAKeyRecovery:
"""Recover ECDSA public key from signature."""
def __init__(self, curve_params):
self.p = curve_params['p']
self.a = curve_params['a']
self.b = curve_params['b']
self.G = curve_params['G']
self.n = curve_params['n']
def recover_public_key(self, z, signature, recovery_id):
"""Recover public key from signature."""
r, s = signature
# Calculate curve point R
x = r + recovery_id * self.n
# Solve for y: y² = x³ + ax + b (mod p)
y_sq = (pow(x, 3, self.p) + self.a * x + self.b) % self.p
y = pow(y_sq, (self.p + 1) // 4, self.p)
if (y + recovery_id) % 2 != 0:
y = self.p - y
R = (x, y)
# Recover public key
u1 = (-r * pow(s, -1, self.n)) % self.n
u2 = (z * pow(s, -1, self.n)) % self.n
Q = self.point_add(
self.point_mult(u1, self.G),
self.point_mult(u2, R)
)
return Q
Recovery ID
The recovery ID (v in Ethereum) indicates which of the two possible public keys is the correct one:
- : coordinate of is even
- : coordinate of is odd
Signature Aggregation
BLS Signatures
BLS (Boneh-Lynn-Shacham) signatures enable simple signature aggregation.
Properties:
- Signature: (point on curve)
- Verification:
- Aggregation:
class BLSSignature:
"""Simplified BLS signature scheme (conceptual)."""
def __init__(self, G1, G2, pairing):
self.G1 = G1 # Generator in G1
self.G2 = G2 # Generator in G2
self.pairing = pairing
def keygen(self):
"""Generate BLS key pair."""
x = randbelow(self.curve_order - 1) + 1
X = self.point_mult(x, self.G2)
return x, X
def sign(self, private_key, message: bytes):
"""Sign message."""
H_m = self.hash_to_point(message)
return self.point_mult(private_key, H_m)
def verify(self, public_key, message: bytes, signature):
"""Verify BLS signature."""
H_m = self.hash_to_point(message)
lhs = self.pairing(signature, self.G1)
rhs = self.pairing(H_m, public_key)
return lhs == rhs
def aggregate(self, signatures: list):
"""Aggregate multiple signatures."""
agg = signatures[0]
for sig in signatures[1:]:
agg = self.point_add(agg, sig)
return agg
def verify_aggregate(self, public_keys: list, messages: list, agg_sig):
"""Verify aggregated signature."""
agg_pk = public_keys[0]
for pk in public_keys[1:]:
agg_pk = self.point_add(agg_pk, pk)
agg_msg = self.hash_to_point(messages[0])
for msg in messages[1:]:
agg_msg = self.point_add(agg_msg, self.hash_to_point(msg))
lhs = self.pairing(agg_sig, self.G1)
rhs = self.pairing(agg_msg, agg_pk)
return lhs == rhs
Signature Scheme Comparison
| Scheme | Size | Aggregation | Use Cases |
|---|---|---|---|
| ECDSA | 64 bytes | No | Bitcoin, Ethereum |
| EdDSA | 64 bytes | Limited | Solana, Cardano |
| Schnorr | 64 bytes | Yes (MuSig) | Bitcoin Taproot |
| BLS | 96 bytes | Yes (simple) | Ethereum 2.0, Filecoin |
Real-World Examples
Bitcoin Transaction Signing
def sign_bitcoin_transaction(private_key, tx_data):
"""Sign a Bitcoin transaction."""
# Create sighash
sighash = sha256(tx_data).digest()
# Sign with ECDSA
r, s = ecdsa_sign(private_key, sighash)
# Normalize s (BIP-62)
if s > secp256k1_order // 2:
s = secp256k1_order - s
# Add to script
signature = r.to_bytes(32, 'big') + s.to_bytes(32, 'big')
pubkey = get_public_key(private_key)
return signature + b'\x01' + pubkey # SIGHASH_ALL
Ethereum Signature (EIP-191)
def sign_ethereum_message(private_key, message):
"""Sign message per EIP-191."""
prefix = "\x19Ethereum Signed Message:\n" + str(len(message))
data = prefix.encode() + message
hash_result = keccak256(data)
v, r, s = ecdsa_sign_raw(private_key, hash_result)
# Adjust v for Ethereum
v = v + 27
return r + s + v.to_bytes(1, 'big')
Trade-offs
| Trade-off | ECDSA | EdDSA | Schnorr | BLS |
|---|---|---|---|---|
| Compatibility | High | Medium | Medium | Low |
| Speed | Slow | Fast | Fast | Slow (pairing) |
| Aggregation | No | Limited | Yes | Yes |
| Standardization | Mature | Modern | Emerging | Emerging |
| Privacy | Basic | Basic | Better (MuSig) | Basic |
Interview Questions
Q1: Why does Bitcoin prefer ECDSA over RSA for digital signatures?
Answer: ECDSA is preferred because:
- Key size: 256-bit EC key ≈ 3072-bit RSA key security
- Signature size: ECDSA signatures are ~64 bytes vs 256+ bytes for RSA
- Verification speed: ECDSA verification is faster
- Bandwidth: Smaller signatures save block space
- Quantum resistance: While neither is quantum-resistant, ECDSA's smaller key sizes make post-quantum migration easier
Q2: What problem does MuSig2 solve that basic multi-signature doesn't?
Answer: MuSig2 addresses several issues:
- Key aggregation: Produces a single signature instead of multiple
- Privacy: External observers can't tell how many signers participated
- Efficiency: Single signature verification instead of multiple
- Blockchain savings: Smaller transaction size (one sig vs many)
- No malleability: Aggregated signature is unique
Q3: How do threshold signatures differ from multisig?
Answer: Threshold signatures offer advantages over traditional multisig:
- Single signature: Appears as regular signature on-chain
- No cooperation: Signers can compute signature independently
- Privacy: No indication of threshold scheme
- Flexibility: Can change threshold without changing address
- Efficiency: Lower transaction fees (one signature vs m)
Quiz Questions
Q1: What vulnerability does RFC 6979 (deterministic nonces) address in ECDSA?
A) Key reuse B) Nonce reuse C) Signature malleability D) Side-channel attacks
Answer: B) Nonce reuse
Q2: Which signature scheme is used in Ethereum 2.0 for validator attestations?
A) ECDSA B) EdDSA C) Schnorr D) BLS
Answer: D) BLS
Q3: In Shamir's Secret Sharing with threshold t=3, what is the minimum number of shares needed to reconstruct the secret?
A) 1 B) 2 C) 3 D) All shares
Answer: C) 3
Practice
- Implement ECDSA signing and verification from scratch
- Build a simple multi-signature wallet
- Create a threshold signature scheme using Shamir's Secret Sharing
- Compare signature sizes across different schemes