From 2951c88a62ae083d987b4f3b34449282582d5a4e Mon Sep 17 00:00:00 2001 From: FreeOnlineUser <38453702+FreeOnlineUser@users.noreply.github.com> Date: Fri, 9 Jan 2026 12:39:01 +1000 Subject: [PATCH 1/6] Add DLEQ proof verification and generation Implement DLEQ proof verification and generation as per BIP-374. This includes functions to verify and generate DLEQ proofs for ECDH computations without revealing private keys. --- src/embit/dleq.py | 223 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 223 insertions(+) create mode 100644 src/embit/dleq.py diff --git a/src/embit/dleq.py b/src/embit/dleq.py new file mode 100644 index 00000000..c2249b58 --- /dev/null +++ b/src/embit/dleq.py @@ -0,0 +1,223 @@ +""" +BIP-374 DLEQ (Discrete Log Equality) Proof Verification + +Implements verification of DLEQ proofs as specified in BIP-374. +Used by BIP-375 Silent Payments to prove ECDH shares were computed correctly. + +A DLEQ proof demonstrates that the same private key 'a' was used to compute: +- A = a * G (public key) +- C = a * B (ECDH shared point) + +This allows a verifier to confirm an ECDH computation was done correctly +without learning the private key. + +Reference: https://github.com/bitcoin/bips/blob/master/bip-0374.mediawiki +""" + +from hashlib import sha256 +from typing import Optional + +from embit import ec +from embit.util import secp256k1 + + +# secp256k1 curve order +SECP256K1_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 + + +def tagged_hash(tag: str, data: bytes) -> bytes: + """ + BIP-340 style tagged hash: SHA256(SHA256(tag) || SHA256(tag) || data) + + Args: + tag: The tag string (e.g., "BIP0374/challenge") + data: The data to hash + + Returns: + 32-byte hash + """ + tag_hash = sha256(tag.encode()).digest() + return sha256(tag_hash + tag_hash + data).digest() + + +def verify_dleq_proof( + A: bytes, + B: bytes, + C: bytes, + proof: bytes, + G: Optional[bytes] = None +) -> bool: + """ + Verify a BIP-374 DLEQ proof. + + Verifies that the same scalar 'a' was used to compute: + - A = a * G (public key) + - C = a * B (ECDH shared point) + + This proves the ECDH share was computed correctly without revealing 'a'. + + Args: + A: 33-byte compressed public key (the signer's pubkey, or sum of input pubkeys) + B: 33-byte compressed public key (recipient's scan key B_scan) + C: 33-byte compressed ECDH share point + proof: 64-byte DLEQ proof (32-byte challenge e || 32-byte response s) + G: Optional 33-byte generator point (uses secp256k1 generator if None) + + Returns: + True if proof is valid, False otherwise + + Example: + >>> # Given a BIP-375 PSBT with DLEQ proof + >>> A = sender_pubkey # or sum of input pubkeys + >>> B = recipient_scan_key + >>> C = ecdh_share_from_psbt + >>> proof = dleq_proof_from_psbt + >>> if verify_dleq_proof(A, B, C, proof): + ... print("ECDH share verified!") + """ + try: + # Parse proof components: e (challenge) || s (response) + if len(proof) != 64: + return False + + e = int.from_bytes(proof[:32], 'big') + s = int.from_bytes(proof[32:], 'big') + + # Reject if s >= curve order (invalid proof) + if s >= SECP256K1_ORDER: + return False + + # Parse the input points + A_parsed = secp256k1.ec_pubkey_parse(A) + B_parsed = secp256k1.ec_pubkey_parse(B) + C_parsed = secp256k1.ec_pubkey_parse(C) + + # Get generator G (derive from privkey=1 if not provided) + if G is None: + G_point = ec.PrivateKey(b'\x00' * 31 + b'\x01').get_public_key().sec() + G_parsed = secp256k1.ec_pubkey_parse(G_point) + else: + G_parsed = secp256k1.ec_pubkey_parse(G) + G_point = G + + # Compute R1 = s*G - e*A + # First: s*G + sG_parsed = secp256k1.ec_pubkey_parse(G_point) + s_bytes = s.to_bytes(32, 'big') + secp256k1.ec_pubkey_tweak_mul(sG_parsed, s_bytes) + + # Then: e*A + eA_parsed = secp256k1.ec_pubkey_parse(A) + e_bytes = e.to_bytes(32, 'big') + secp256k1.ec_pubkey_tweak_mul(eA_parsed, e_bytes) + + # Negate e*A to get -e*A (for subtraction via addition) + # NOTE: ec_pubkey_negate() returns a new point, does NOT modify in-place + neg_eA = secp256k1.ec_pubkey_negate(eA_parsed) + + # R1 = s*G + (-e*A) + R1_parsed = secp256k1.ec_pubkey_combine(sG_parsed, neg_eA) + R1 = secp256k1.ec_pubkey_serialize(R1_parsed) + + # Compute R2 = s*B - e*C + # First: s*B + sB_parsed = secp256k1.ec_pubkey_parse(B) + secp256k1.ec_pubkey_tweak_mul(sB_parsed, s_bytes) + + # Then: e*C + eC_parsed = secp256k1.ec_pubkey_parse(C) + secp256k1.ec_pubkey_tweak_mul(eC_parsed, e_bytes) + + # Negate e*C + # NOTE: ec_pubkey_negate() returns a new point, does NOT modify in-place + neg_eC = secp256k1.ec_pubkey_negate(eC_parsed) + + # R2 = s*B + (-e*C) + R2_parsed = secp256k1.ec_pubkey_combine(sB_parsed, neg_eC) + R2 = secp256k1.ec_pubkey_serialize(R2_parsed) + + # Compute challenge hash per BIP-374: + # e' = tagged_hash("BIP0374/challenge", A || B || C || G || R1 || R2) + challenge_data = A + B + C + G_point + R1 + R2 + e_computed = tagged_hash("BIP0374/challenge", challenge_data) + e_computed_int = int.from_bytes(e_computed, 'big') + + # Verify: e == e' + return e == e_computed_int + + except Exception: + return False + + +def generate_dleq_proof( + a: bytes, + B: bytes, + k: Optional[bytes] = None +) -> tuple: + """ + Generate a BIP-374 DLEQ proof. + + Proves knowledge of scalar 'a' such that A = a*G and C = a*B. + + Args: + a: 32-byte private key scalar + B: 33-byte compressed public key (the base point for ECDH) + k: Optional 32-byte nonce (randomly generated if not provided) + + Returns: + Tuple of (A, C, proof) where: + - A: 33-byte compressed pubkey = a*G + - C: 33-byte compressed ECDH point = a*B + - proof: 64-byte DLEQ proof + + Example: + >>> from os import urandom + >>> a = urandom(32) # sender's private key + >>> B = recipient_scan_pubkey + >>> A, C, proof = generate_dleq_proof(a, B) + >>> # Include C and proof in BIP-375 PSBT fields + """ + from os import urandom + + # Compute A = a*G + priv = ec.PrivateKey(a) + A = priv.get_public_key().sec() + + # Compute C = a*B + B_parsed = secp256k1.ec_pubkey_parse(B) + C_parsed = secp256k1.ec_pubkey_parse(B) # copy + secp256k1.ec_pubkey_tweak_mul(C_parsed, a) + C = secp256k1.ec_pubkey_serialize(C_parsed) + + # Get generator G + G = ec.PrivateKey(b'\x00' * 31 + b'\x01').get_public_key().sec() + + # Generate nonce k (or use provided) + if k is None: + k = urandom(32) + k_int = int.from_bytes(k, 'big') % SECP256K1_ORDER + k_bytes = k_int.to_bytes(32, 'big') + + # R1 = k*G + R1_priv = ec.PrivateKey(k_bytes) + R1 = R1_priv.get_public_key().sec() + + # R2 = k*B + R2_parsed = secp256k1.ec_pubkey_parse(B) + secp256k1.ec_pubkey_tweak_mul(R2_parsed, k_bytes) + R2 = secp256k1.ec_pubkey_serialize(R2_parsed) + + # e = tagged_hash("BIP0374/challenge", A || B || C || G || R1 || R2) + challenge_data = A + B + C + G + R1 + R2 + e = tagged_hash("BIP0374/challenge", challenge_data) + e_int = int.from_bytes(e, 'big') + + # s = k + e*a (mod n) + a_int = int.from_bytes(a, 'big') + s_int = (k_int + e_int * a_int) % SECP256K1_ORDER + s = s_int.to_bytes(32, 'big') + + # Proof = e || s + proof = e + s + + return A, C, proof From 2badc58ce4cbc06d3017fa61c7a4d381bf73b86c Mon Sep 17 00:00:00 2001 From: FreeOnlineUser <38453702+FreeOnlineUser@users.noreply.github.com> Date: Fri, 9 Jan 2026 12:41:59 +1000 Subject: [PATCH 2/6] Add tests for DLEQ proof verification and generation This file contains tests for BIP-374 DLEQ proof verification and generation, including various scenarios for tagged hashing, proof generation, and verification. --- tests/test_dleq.py | 182 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 182 insertions(+) create mode 100644 tests/test_dleq.py diff --git a/tests/test_dleq.py b/tests/test_dleq.py new file mode 100644 index 00000000..4a3add1a --- /dev/null +++ b/tests/test_dleq.py @@ -0,0 +1,182 @@ +""" +Tests for BIP-374 DLEQ proof verification and generation. +""" + +import pytest +from os import urandom + +from embit import ec +from embit.util import secp256k1 + +from dleq import ( + verify_dleq_proof, + generate_dleq_proof, + tagged_hash, + SECP256K1_ORDER, +) + + +class TestTaggedHash: + """Test BIP-340 style tagged hashing.""" + + def test_deterministic(self): + """Same inputs produce same output.""" + data = b"test data" + h1 = tagged_hash("BIP0374/challenge", data) + h2 = tagged_hash("BIP0374/challenge", data) + assert h1 == h2 + assert len(h1) == 32 + + def test_different_tags(self): + """Different tags produce different outputs.""" + data = b"test data" + h1 = tagged_hash("BIP0374/challenge", data) + h2 = tagged_hash("other/tag", data) + assert h1 != h2 + + +class TestDLEQProofGeneration: + """Test DLEQ proof generation.""" + + def test_generate_proof_structure(self): + """Generated proof has correct structure.""" + a = urandom(32) + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + A, C, proof = generate_dleq_proof(a, B) + + assert len(A) == 33 + assert len(C) == 33 + assert len(proof) == 64 + assert A[0] in (0x02, 0x03) # compressed pubkey prefix + assert C[0] in (0x02, 0x03) + + def test_A_equals_aG(self): + """A is correctly computed as a*G.""" + a = urandom(32) + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + A, C, proof = generate_dleq_proof(a, B) + + # Compute expected A directly + expected_A = ec.PrivateKey(a).get_public_key().sec() + assert A == expected_A + + +class TestDLEQProofVerification: + """Test DLEQ proof verification.""" + + def test_valid_proof_verifies(self): + """A correctly generated proof should verify.""" + a = urandom(32) + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + A, C, proof = generate_dleq_proof(a, B) + + assert verify_dleq_proof(A, B, C, proof) is True + + def test_wrong_A_fails(self): + """Proof fails if A doesn't match.""" + a = urandom(32) + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + A, C, proof = generate_dleq_proof(a, B) + + # Use different A + wrong_A = ec.PrivateKey(urandom(32)).get_public_key().sec() + assert verify_dleq_proof(wrong_A, B, C, proof) is False + + def test_wrong_B_fails(self): + """Proof fails if B doesn't match.""" + a = urandom(32) + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + A, C, proof = generate_dleq_proof(a, B) + + # Use different B + wrong_B = ec.PrivateKey(urandom(32)).get_public_key().sec() + assert verify_dleq_proof(A, wrong_B, C, proof) is False + + def test_wrong_C_fails(self): + """Proof fails if C doesn't match.""" + a = urandom(32) + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + A, C, proof = generate_dleq_proof(a, B) + + # Use different C (ECDH with different key) + wrong_C_parsed = secp256k1.ec_pubkey_parse(B) + secp256k1.ec_pubkey_tweak_mul(wrong_C_parsed, urandom(32)) + wrong_C = secp256k1.ec_pubkey_serialize(wrong_C_parsed) + + assert verify_dleq_proof(A, B, wrong_C, proof) is False + + def test_tampered_proof_fails(self): + """Tampered proof fails verification.""" + a = urandom(32) + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + A, C, proof = generate_dleq_proof(a, B) + + # Tamper with proof (flip a bit) + tampered = bytearray(proof) + tampered[0] ^= 0x01 + tampered = bytes(tampered) + + assert verify_dleq_proof(A, B, C, tampered) is False + + def test_wrong_length_proof_fails(self): + """Proof with wrong length fails.""" + a = urandom(32) + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + A, C, _ = generate_dleq_proof(a, B) + + # Too short + assert verify_dleq_proof(A, B, C, b'\x00' * 63) is False + # Too long + assert verify_dleq_proof(A, B, C, b'\x00' * 65) is False + + def test_s_greater_than_order_fails(self): + """Proof with s >= curve order fails.""" + a = urandom(32) + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + A, C, proof = generate_dleq_proof(a, B) + + # Create invalid proof with s = curve order + e = proof[:32] + invalid_s = SECP256K1_ORDER.to_bytes(32, 'big') + invalid_proof = e + invalid_s + + assert verify_dleq_proof(A, B, C, invalid_proof) is False + + +class TestDLEQRoundTrip: + """Test generate -> verify round trip.""" + + def test_multiple_round_trips(self): + """Multiple random proofs all verify.""" + for _ in range(10): + a = urandom(32) + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + A, C, proof = generate_dleq_proof(a, B) + assert verify_dleq_proof(A, B, C, proof) is True + + def test_deterministic_with_fixed_nonce(self): + """Same inputs with same nonce produce same proof.""" + a = b'\x01' * 32 + B = ec.PrivateKey(b'\x02' * 32).get_public_key().sec() + k = b'\x03' * 32 + + A1, C1, proof1 = generate_dleq_proof(a, B, k) + A2, C2, proof2 = generate_dleq_proof(a, B, k) + + assert A1 == A2 + assert C1 == C2 + assert proof1 == proof2 + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) From 6c1a7f08b04e2528e438bcb6212bdd6b6f96ea58 Mon Sep 17 00:00:00 2001 From: FreeOnlineUser <38453702+FreeOnlineUser@users.noreply.github.com> Date: Sun, 11 Jan 2026 10:59:20 +1000 Subject: [PATCH 3/6] Add edge case validation (e>=n, a validation, k==0) --- src/embit/dleq.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/embit/dleq.py b/src/embit/dleq.py index c2249b58..8d5e3542 100644 --- a/src/embit/dleq.py +++ b/src/embit/dleq.py @@ -83,8 +83,8 @@ def verify_dleq_proof( e = int.from_bytes(proof[:32], 'big') s = int.from_bytes(proof[32:], 'big') - # Reject if s >= curve order (invalid proof) - if s >= SECP256K1_ORDER: + # Reject if e or s >= curve order (invalid proof) + if e >= SECP256K1_ORDER or s >= SECP256K1_ORDER: return False # Parse the input points From 25c177d3814c76f9b58d7aadc26c39f38507e356 Mon Sep 17 00:00:00 2001 From: FreeOnlineUser <38453702+FreeOnlineUser@users.noreply.github.com> Date: Sun, 11 Jan 2026 11:01:09 +1000 Subject: [PATCH 4/6] Add tests for edge cases (e>=n, a validation, k==0) Added tests to verify failure conditions for DLEQ proof generation. --- tests/test_dleq.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/tests/test_dleq.py b/tests/test_dleq.py index 4a3add1a..dc27a176 100644 --- a/tests/test_dleq.py +++ b/tests/test_dleq.py @@ -151,6 +151,49 @@ def test_s_greater_than_order_fails(self): assert verify_dleq_proof(A, B, C, invalid_proof) is False + def test_e_greater_than_order_fails(self): + """Proof with e >= curve order fails.""" + a = urandom(32) + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + A, C, proof = generate_dleq_proof(a, B) + + # Create invalid proof with e = curve order + invalid_e = SECP256K1_ORDER.to_bytes(32, 'big') + s = proof[32:] + invalid_proof = invalid_e + s + + assert verify_dleq_proof(A, B, C, invalid_proof) is False + + +class TestDLEQProofGenerationEdgeCases: + """Test edge cases in proof generation.""" + + def test_private_key_zero_fails(self): + """Private key of zero should fail.""" + a = b'\x00' * 32 + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + with pytest.raises(ValueError, match="Private key must be in range"): + generate_dleq_proof(a, B) + + def test_private_key_at_order_fails(self): + """Private key >= curve order should fail.""" + a = SECP256K1_ORDER.to_bytes(32, 'big') + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + + with pytest.raises(ValueError, match="Private key must be in range"): + generate_dleq_proof(a, B) + + def test_nonce_zero_fails(self): + """Nonce that reduces to zero should fail.""" + a = urandom(32) + B = ec.PrivateKey(urandom(32)).get_public_key().sec() + k = b'\x00' * 32 # Will reduce to zero + + with pytest.raises(ValueError, match="Nonce reduced to zero"): + generate_dleq_proof(a, B, k) + class TestDLEQRoundTrip: """Test generate -> verify round trip.""" From f840bcfd3b15de45cce8321fb8227466b719af1f Mon Sep 17 00:00:00 2001 From: FreeOnlineUser Date: Mon, 10 Aug 2026 21:54:43 +1000 Subject: [PATCH 5/6] py_secp256k1: implement ec_pubkey_tweak_mul and ec_pubkey_combine The pure-python backend never implemented these (they were left as commented-out stubs copied from the ctypes bindings), so any code using them worked only when the prebuilt libsecp256k1 binary loaded. Since ec_pubkey_parse returns immutable bytes in this backend, the result cannot always be written back in place like libsecp256k1 does: ec_pubkey_tweak_mul mutates the input when it is a bytearray and always returns the resulting point. The ctypes ec_pubkey_tweak_mul now also returns the tweaked pubkey so callers can use one return-value idiom across both backends. --- src/embit/util/ctypes_secp256k1.py | 3 ++ src/embit/util/py_secp256k1.py | 47 ++++++++++++++++++++---------- 2 files changed, 35 insertions(+), 15 deletions(-) diff --git a/src/embit/util/ctypes_secp256k1.py b/src/embit/util/ctypes_secp256k1.py index 232abda1..2d0975d0 100644 --- a/src/embit/util/ctypes_secp256k1.py +++ b/src/embit/util/ctypes_secp256k1.py @@ -701,6 +701,9 @@ def ec_pubkey_tweak_mul(pub, tweak, context=_secp.ctx): raise ValueError("Tweak should be 32 bytes long") if _secp.secp256k1_ec_pubkey_tweak_mul(context, pub, tweak) == 0: raise ValueError("Failed to tweak the public key") + # returned for parity with the pure-python backend, where the result + # cannot always be written back in place + return pub @locked diff --git a/src/embit/util/py_secp256k1.py b/src/embit/util/py_secp256k1.py index 85140863..4f78c41d 100644 --- a/src/embit/util/py_secp256k1.py +++ b/src/embit/util/py_secp256k1.py @@ -254,21 +254,38 @@ def ec_pubkey_add(pub, tweak, context=None): # for i in range(len(secret)): # secret[i] = res[i] -# def ec_pubkey_tweak_mul(pub, tweak, context=None): -# if len(pub)!=64: -# raise ValueError("Public key should be 64 bytes long") -# if len(tweak)!=32: -# raise ValueError("Tweak should be 32 bytes long") -# if _secp.secp256k1_ec_pubkey_tweak_mul(context, pub, tweak) == 0: -# raise ValueError("Failed to tweak the public key") - -# def ec_pubkey_combine(*args, context=None): -# pub = bytes(64) -# pubkeys = (c_char_p * len(args))(*args) -# r = _secp.secp256k1_ec_pubkey_combine(context, pub, pubkeys, len(args)) -# if r == 0: -# raise ValueError("Failed to negate pubkey") -# return pub +def ec_pubkey_tweak_mul(pub, tweak, context=None): + if len(pub) != 64: + raise ValueError("Public key should be 64 bytes long") + if len(tweak) != 32: + raise ValueError("Tweak should be 32 bytes long") + t = int.from_bytes(tweak, "big") + if t == 0 or t >= _key.SECP256K1_ORDER: + raise ValueError("Failed to tweak the public key") + pubkey = _pubkey_parse(pub) + Q = _key.SECP256K1.affine(_key.SECP256K1.mul([(pubkey.p, t)])) + if Q is None: + raise ValueError("Failed to tweak the public key") + res = Q[0].to_bytes(32, "little") + Q[1].to_bytes(32, "little") + # ec_pubkey_parse returns immutable bytes here, so unlike the ctypes + # backend the result can't always be written back in place - mutate + # when possible, and always return the result like ctypes does + if isinstance(pub, bytearray): + for i in range(len(pub)): + pub[i] = res[i] + return res + + +def ec_pubkey_combine(*args, context=None): + points = [] + for pub in args: + if len(pub) != 64: + raise ValueError("Public key should be 64 bytes long") + points.append((_pubkey_parse(pub).p, 1)) + Q = _key.SECP256K1.affine(_key.SECP256K1.mul(points)) + if Q is None: + raise ValueError("Failed to combine pubkeys") + return Q[0].to_bytes(32, "little") + Q[1].to_bytes(32, "little") # schnorrsig From 69e177870e6705d369cd0d4f05fa86536cdee53f Mon Sep 17 00:00:00 2001 From: FreeOnlineUser Date: Mon, 10 Aug 2026 21:54:43 +1000 Subject: [PATCH 6/6] dleq: deterministic nonce per BIP-374, message support, official vectors Address review feedback on the nonce derivation: - Derive the nonce deterministically via the BIP0374/aux and BIP0374/nonce tagged hashes from the secret, fresh auxiliary randomness r, the points A and C, and the optional message m, as specified. The previous raw random nonce (and the caller-supplied nonce parameter, a reuse footgun) are gone; generate_dleq_proof now takes auxiliary randomness r instead. - Support the optional 32-byte message m in generation and verification, committed in both the nonce and the challenge. - Support a custom generator G in generation (verification already had it); normalize all points to compressed encodings for the challenge hash. - Self-verify each generated proof before returning, as the reference implementation does. - Run the official BIP-374 test vectors byte-exact (test_vectors_generate_proof.csv and test_vectors_verify_proof.csv, embedded verbatim), plus the existing property tests, now against both secp256k1 backends. - Move the tests to tests/tests/test_dleq.py so the test runner actually discovers them, and drop the pytest dependency and typing import for micropython compatibility. --- src/embit/dleq.py | 227 +++++++++++++++++++++-------------- tests/test_dleq.py | 225 ----------------------------------- tests/tests/__init__.py | 1 + tests/tests/test_dleq.py | 248 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 388 insertions(+), 313 deletions(-) delete mode 100644 tests/test_dleq.py create mode 100644 tests/tests/test_dleq.py diff --git a/src/embit/dleq.py b/src/embit/dleq.py index 8d5e3542..9b1e1c3b 100644 --- a/src/embit/dleq.py +++ b/src/embit/dleq.py @@ -1,29 +1,37 @@ """ -BIP-374 DLEQ (Discrete Log Equality) Proof Verification +BIP-374 DLEQ (Discrete Log Equality) proofs. -Implements verification of DLEQ proofs as specified in BIP-374. -Used by BIP-375 Silent Payments to prove ECDH shares were computed correctly. +Implements generation and verification of DLEQ proofs as specified in +BIP-374. Used by BIP-375 Silent Payments to prove ECDH shares were +computed correctly. -A DLEQ proof demonstrates that the same private key 'a' was used to compute: +A DLEQ proof demonstrates that the same scalar 'a' was used to compute: - A = a * G (public key) - C = a * B (ECDH shared point) This allows a verifier to confirm an ECDH computation was done correctly without learning the private key. +Follows the reference implementation, including the deterministic nonce +derivation via the BIP0374/aux and BIP0374/nonce tagged hashes and the +optional 32-byte message m in the challenge. + Reference: https://github.com/bitcoin/bips/blob/master/bip-0374.mediawiki """ from hashlib import sha256 -from typing import Optional -from embit import ec from embit.util import secp256k1 # secp256k1 curve order SECP256K1_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 +# secp256k1 generator point, compressed SEC encoding +SECP256K1_G = bytes.fromhex( + "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" +) + def tagged_hash(tag: str, data: bytes) -> bytes: """ @@ -40,12 +48,28 @@ def tagged_hash(tag: str, data: bytes) -> bytes: return sha256(tag_hash + tag_hash + data).digest() +def _xor_bytes(a: bytes, b: bytes) -> bytes: + return bytes(x ^ y for x, y in zip(a, b)) + + +def _challenge( + A: bytes, B: bytes, C: bytes, G: bytes, R1: bytes, R2: bytes, m: bytes +) -> int: + """e = tagged_hash("BIP0374/challenge", A || B || C || G || R1 || R2 || m) + + All points must be compressed SEC encodings; m is b"" when absent. + """ + e = tagged_hash("BIP0374/challenge", A + B + C + G + R1 + R2 + m) + return int.from_bytes(e, "big") + + def verify_dleq_proof( A: bytes, B: bytes, C: bytes, proof: bytes, - G: Optional[bytes] = None + G: bytes = None, + m: bytes = None, ) -> bool: """ Verify a BIP-374 DLEQ proof. @@ -62,6 +86,8 @@ def verify_dleq_proof( C: 33-byte compressed ECDH share point proof: 64-byte DLEQ proof (32-byte challenge e || 32-byte response s) G: Optional 33-byte generator point (uses secp256k1 generator if None) + m: Optional 32-byte message committed to by the proof + (BIP-375 does not use it) Returns: True if proof is valid, False otherwise @@ -76,74 +102,67 @@ def verify_dleq_proof( ... print("ECDH share verified!") """ try: + if m is not None and len(m) != 32: + return False + m_prime = b"" if m is None else m + # Parse proof components: e (challenge) || s (response) if len(proof) != 64: return False - e = int.from_bytes(proof[:32], 'big') - s = int.from_bytes(proof[32:], 'big') + e = int.from_bytes(proof[:32], "big") + s = int.from_bytes(proof[32:], "big") # Reject if e or s >= curve order (invalid proof) if e >= SECP256K1_ORDER or s >= SECP256K1_ORDER: return False - # Parse the input points + # Parse the input points and normalize to compressed encodings, + # since the challenge hash commits to compressed bytes A_parsed = secp256k1.ec_pubkey_parse(A) + A_ser = secp256k1.ec_pubkey_serialize(A_parsed) B_parsed = secp256k1.ec_pubkey_parse(B) + B_ser = secp256k1.ec_pubkey_serialize(B_parsed) C_parsed = secp256k1.ec_pubkey_parse(C) + C_ser = secp256k1.ec_pubkey_serialize(C_parsed) - # Get generator G (derive from privkey=1 if not provided) - if G is None: - G_point = ec.PrivateKey(b'\x00' * 31 + b'\x01').get_public_key().sec() - G_parsed = secp256k1.ec_pubkey_parse(G_point) - else: - G_parsed = secp256k1.ec_pubkey_parse(G) - G_point = G - - # Compute R1 = s*G - e*A - # First: s*G - sG_parsed = secp256k1.ec_pubkey_parse(G_point) - s_bytes = s.to_bytes(32, 'big') - secp256k1.ec_pubkey_tweak_mul(sG_parsed, s_bytes) - - # Then: e*A - eA_parsed = secp256k1.ec_pubkey_parse(A) - e_bytes = e.to_bytes(32, 'big') - secp256k1.ec_pubkey_tweak_mul(eA_parsed, e_bytes) + G_parsed = secp256k1.ec_pubkey_parse(SECP256K1_G if G is None else G) + G_ser = secp256k1.ec_pubkey_serialize(G_parsed) - # Negate e*A to get -e*A (for subtraction via addition) - # NOTE: ec_pubkey_negate() returns a new point, does NOT modify in-place - neg_eA = secp256k1.ec_pubkey_negate(eA_parsed) + # NOTE: ec_pubkey_tweak_mul/negate/combine return the resulting + # point (the pure-python backend cannot mutate in place); always + # use the return value + s_bytes = s.to_bytes(32, "big") + e_bytes = e.to_bytes(32, "big") - # R1 = s*G + (-e*A) - R1_parsed = secp256k1.ec_pubkey_combine(sG_parsed, neg_eA) - R1 = secp256k1.ec_pubkey_serialize(R1_parsed) + # Compute R1 = s*G - e*A + sG = secp256k1.ec_pubkey_tweak_mul( + secp256k1.ec_pubkey_parse(G_ser), s_bytes + ) + eA = secp256k1.ec_pubkey_tweak_mul( + secp256k1.ec_pubkey_parse(A_ser), e_bytes + ) + neg_eA = secp256k1.ec_pubkey_negate(eA) + # combine raises if the result is the point at infinity, which + # verification must reject + R1 = secp256k1.ec_pubkey_serialize( + secp256k1.ec_pubkey_combine(sG, neg_eA) + ) # Compute R2 = s*B - e*C - # First: s*B - sB_parsed = secp256k1.ec_pubkey_parse(B) - secp256k1.ec_pubkey_tweak_mul(sB_parsed, s_bytes) - - # Then: e*C - eC_parsed = secp256k1.ec_pubkey_parse(C) - secp256k1.ec_pubkey_tweak_mul(eC_parsed, e_bytes) - - # Negate e*C - # NOTE: ec_pubkey_negate() returns a new point, does NOT modify in-place - neg_eC = secp256k1.ec_pubkey_negate(eC_parsed) - - # R2 = s*B + (-e*C) - R2_parsed = secp256k1.ec_pubkey_combine(sB_parsed, neg_eC) - R2 = secp256k1.ec_pubkey_serialize(R2_parsed) - - # Compute challenge hash per BIP-374: - # e' = tagged_hash("BIP0374/challenge", A || B || C || G || R1 || R2) - challenge_data = A + B + C + G_point + R1 + R2 - e_computed = tagged_hash("BIP0374/challenge", challenge_data) - e_computed_int = int.from_bytes(e_computed, 'big') + sB = secp256k1.ec_pubkey_tweak_mul( + secp256k1.ec_pubkey_parse(B_ser), s_bytes + ) + eC = secp256k1.ec_pubkey_tweak_mul( + secp256k1.ec_pubkey_parse(C_ser), e_bytes + ) + neg_eC = secp256k1.ec_pubkey_negate(eC) + R2 = secp256k1.ec_pubkey_serialize( + secp256k1.ec_pubkey_combine(sB, neg_eC) + ) # Verify: e == e' - return e == e_computed_int + return e == _challenge(A_ser, B_ser, C_ser, G_ser, R1, R2, m_prime) except Exception: return False @@ -152,23 +171,37 @@ def verify_dleq_proof( def generate_dleq_proof( a: bytes, B: bytes, - k: Optional[bytes] = None + r: bytes = None, + G: bytes = None, + m: bytes = None, ) -> tuple: """ Generate a BIP-374 DLEQ proof. Proves knowledge of scalar 'a' such that A = a*G and C = a*B. + The nonce is derived deterministically per BIP-374 from the secret, + the auxiliary randomness r, the points A and C, and the message m, + via the BIP0374/aux and BIP0374/nonce tagged hashes. This protects + against nonce reuse (which would leak 'a') even with a broken RNG. + Args: a: 32-byte private key scalar B: 33-byte compressed public key (the base point for ECDH) - k: Optional 32-byte nonce (randomly generated if not provided) + r: Optional 32-byte auxiliary randomness (fresh randomness is + generated if not provided) + G: Optional 33-byte generator point (uses secp256k1 generator if None) + m: Optional 32-byte message to commit to (BIP-375 does not use it) Returns: Tuple of (A, C, proof) where: - A: 33-byte compressed pubkey = a*G - C: 33-byte compressed ECDH point = a*B - - proof: 64-byte DLEQ proof + - proof: 64-byte DLEQ proof (e || s) + + Raises: + ValueError: if a is not in [1, n), or B/G is not a valid point, + or r/m has the wrong length Example: >>> from os import urandom @@ -179,45 +212,63 @@ def generate_dleq_proof( """ from os import urandom + if len(a) != 32: + raise ValueError("Private key must be 32 bytes") + a_int = int.from_bytes(a, "big") + if not (0 < a_int < SECP256K1_ORDER): + raise ValueError("Private key out of range") + if r is None: + r = urandom(32) + if len(r) != 32: + raise ValueError("Auxiliary randomness must be 32 bytes") + if m is not None and len(m) != 32: + raise ValueError("Message must be 32 bytes") + m_prime = b"" if m is None else m + + G_ser = secp256k1.ec_pubkey_serialize( + secp256k1.ec_pubkey_parse(SECP256K1_G if G is None else G) + ) + B_ser = secp256k1.ec_pubkey_serialize(secp256k1.ec_pubkey_parse(B)) + # Compute A = a*G - priv = ec.PrivateKey(a) - A = priv.get_public_key().sec() + A = secp256k1.ec_pubkey_serialize( + secp256k1.ec_pubkey_tweak_mul(secp256k1.ec_pubkey_parse(G_ser), a) + ) # Compute C = a*B - B_parsed = secp256k1.ec_pubkey_parse(B) - C_parsed = secp256k1.ec_pubkey_parse(B) # copy - secp256k1.ec_pubkey_tweak_mul(C_parsed, a) - C = secp256k1.ec_pubkey_serialize(C_parsed) - - # Get generator G - G = ec.PrivateKey(b'\x00' * 31 + b'\x01').get_public_key().sec() - - # Generate nonce k (or use provided) - if k is None: - k = urandom(32) - k_int = int.from_bytes(k, 'big') % SECP256K1_ORDER - k_bytes = k_int.to_bytes(32, 'big') + C = secp256k1.ec_pubkey_serialize( + secp256k1.ec_pubkey_tweak_mul(secp256k1.ec_pubkey_parse(B_ser), a) + ) + + # Deterministic nonce per BIP-374: + # t = a XOR tagged_hash("BIP0374/aux", r) + # k = int(tagged_hash("BIP0374/nonce", t || A || C || m)) mod n + t = _xor_bytes(a, tagged_hash("BIP0374/aux", r)) + rand = tagged_hash("BIP0374/nonce", t + A + C + m_prime) + k = int.from_bytes(rand, "big") % SECP256K1_ORDER + if k == 0: + raise ValueError("Invalid nonce") + k_bytes = k.to_bytes(32, "big") # R1 = k*G - R1_priv = ec.PrivateKey(k_bytes) - R1 = R1_priv.get_public_key().sec() + R1 = secp256k1.ec_pubkey_serialize( + secp256k1.ec_pubkey_tweak_mul(secp256k1.ec_pubkey_parse(G_ser), k_bytes) + ) # R2 = k*B - R2_parsed = secp256k1.ec_pubkey_parse(B) - secp256k1.ec_pubkey_tweak_mul(R2_parsed, k_bytes) - R2 = secp256k1.ec_pubkey_serialize(R2_parsed) + R2 = secp256k1.ec_pubkey_serialize( + secp256k1.ec_pubkey_tweak_mul(secp256k1.ec_pubkey_parse(B_ser), k_bytes) + ) - # e = tagged_hash("BIP0374/challenge", A || B || C || G || R1 || R2) - challenge_data = A + B + C + G + R1 + R2 - e = tagged_hash("BIP0374/challenge", challenge_data) - e_int = int.from_bytes(e, 'big') + e = _challenge(A, B_ser, C, G_ser, R1, R2, m_prime) # s = k + e*a (mod n) - a_int = int.from_bytes(a, 'big') - s_int = (k_int + e_int * a_int) % SECP256K1_ORDER - s = s_int.to_bytes(32, 'big') + s = (k + e * a_int) % SECP256K1_ORDER + + proof = e.to_bytes(32, "big") + s.to_bytes(32, "big") - # Proof = e || s - proof = e + s + # Self-check before returning, as the reference implementation does + if not verify_dleq_proof(A, B_ser, C, proof, G=G, m=m): + raise RuntimeError("Generated proof failed self-verification") return A, C, proof diff --git a/tests/test_dleq.py b/tests/test_dleq.py deleted file mode 100644 index dc27a176..00000000 --- a/tests/test_dleq.py +++ /dev/null @@ -1,225 +0,0 @@ -""" -Tests for BIP-374 DLEQ proof verification and generation. -""" - -import pytest -from os import urandom - -from embit import ec -from embit.util import secp256k1 - -from dleq import ( - verify_dleq_proof, - generate_dleq_proof, - tagged_hash, - SECP256K1_ORDER, -) - - -class TestTaggedHash: - """Test BIP-340 style tagged hashing.""" - - def test_deterministic(self): - """Same inputs produce same output.""" - data = b"test data" - h1 = tagged_hash("BIP0374/challenge", data) - h2 = tagged_hash("BIP0374/challenge", data) - assert h1 == h2 - assert len(h1) == 32 - - def test_different_tags(self): - """Different tags produce different outputs.""" - data = b"test data" - h1 = tagged_hash("BIP0374/challenge", data) - h2 = tagged_hash("other/tag", data) - assert h1 != h2 - - -class TestDLEQProofGeneration: - """Test DLEQ proof generation.""" - - def test_generate_proof_structure(self): - """Generated proof has correct structure.""" - a = urandom(32) - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - A, C, proof = generate_dleq_proof(a, B) - - assert len(A) == 33 - assert len(C) == 33 - assert len(proof) == 64 - assert A[0] in (0x02, 0x03) # compressed pubkey prefix - assert C[0] in (0x02, 0x03) - - def test_A_equals_aG(self): - """A is correctly computed as a*G.""" - a = urandom(32) - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - A, C, proof = generate_dleq_proof(a, B) - - # Compute expected A directly - expected_A = ec.PrivateKey(a).get_public_key().sec() - assert A == expected_A - - -class TestDLEQProofVerification: - """Test DLEQ proof verification.""" - - def test_valid_proof_verifies(self): - """A correctly generated proof should verify.""" - a = urandom(32) - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - A, C, proof = generate_dleq_proof(a, B) - - assert verify_dleq_proof(A, B, C, proof) is True - - def test_wrong_A_fails(self): - """Proof fails if A doesn't match.""" - a = urandom(32) - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - A, C, proof = generate_dleq_proof(a, B) - - # Use different A - wrong_A = ec.PrivateKey(urandom(32)).get_public_key().sec() - assert verify_dleq_proof(wrong_A, B, C, proof) is False - - def test_wrong_B_fails(self): - """Proof fails if B doesn't match.""" - a = urandom(32) - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - A, C, proof = generate_dleq_proof(a, B) - - # Use different B - wrong_B = ec.PrivateKey(urandom(32)).get_public_key().sec() - assert verify_dleq_proof(A, wrong_B, C, proof) is False - - def test_wrong_C_fails(self): - """Proof fails if C doesn't match.""" - a = urandom(32) - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - A, C, proof = generate_dleq_proof(a, B) - - # Use different C (ECDH with different key) - wrong_C_parsed = secp256k1.ec_pubkey_parse(B) - secp256k1.ec_pubkey_tweak_mul(wrong_C_parsed, urandom(32)) - wrong_C = secp256k1.ec_pubkey_serialize(wrong_C_parsed) - - assert verify_dleq_proof(A, B, wrong_C, proof) is False - - def test_tampered_proof_fails(self): - """Tampered proof fails verification.""" - a = urandom(32) - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - A, C, proof = generate_dleq_proof(a, B) - - # Tamper with proof (flip a bit) - tampered = bytearray(proof) - tampered[0] ^= 0x01 - tampered = bytes(tampered) - - assert verify_dleq_proof(A, B, C, tampered) is False - - def test_wrong_length_proof_fails(self): - """Proof with wrong length fails.""" - a = urandom(32) - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - A, C, _ = generate_dleq_proof(a, B) - - # Too short - assert verify_dleq_proof(A, B, C, b'\x00' * 63) is False - # Too long - assert verify_dleq_proof(A, B, C, b'\x00' * 65) is False - - def test_s_greater_than_order_fails(self): - """Proof with s >= curve order fails.""" - a = urandom(32) - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - A, C, proof = generate_dleq_proof(a, B) - - # Create invalid proof with s = curve order - e = proof[:32] - invalid_s = SECP256K1_ORDER.to_bytes(32, 'big') - invalid_proof = e + invalid_s - - assert verify_dleq_proof(A, B, C, invalid_proof) is False - - def test_e_greater_than_order_fails(self): - """Proof with e >= curve order fails.""" - a = urandom(32) - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - A, C, proof = generate_dleq_proof(a, B) - - # Create invalid proof with e = curve order - invalid_e = SECP256K1_ORDER.to_bytes(32, 'big') - s = proof[32:] - invalid_proof = invalid_e + s - - assert verify_dleq_proof(A, B, C, invalid_proof) is False - - -class TestDLEQProofGenerationEdgeCases: - """Test edge cases in proof generation.""" - - def test_private_key_zero_fails(self): - """Private key of zero should fail.""" - a = b'\x00' * 32 - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - with pytest.raises(ValueError, match="Private key must be in range"): - generate_dleq_proof(a, B) - - def test_private_key_at_order_fails(self): - """Private key >= curve order should fail.""" - a = SECP256K1_ORDER.to_bytes(32, 'big') - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - with pytest.raises(ValueError, match="Private key must be in range"): - generate_dleq_proof(a, B) - - def test_nonce_zero_fails(self): - """Nonce that reduces to zero should fail.""" - a = urandom(32) - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - k = b'\x00' * 32 # Will reduce to zero - - with pytest.raises(ValueError, match="Nonce reduced to zero"): - generate_dleq_proof(a, B, k) - - -class TestDLEQRoundTrip: - """Test generate -> verify round trip.""" - - def test_multiple_round_trips(self): - """Multiple random proofs all verify.""" - for _ in range(10): - a = urandom(32) - B = ec.PrivateKey(urandom(32)).get_public_key().sec() - - A, C, proof = generate_dleq_proof(a, B) - assert verify_dleq_proof(A, B, C, proof) is True - - def test_deterministic_with_fixed_nonce(self): - """Same inputs with same nonce produce same proof.""" - a = b'\x01' * 32 - B = ec.PrivateKey(b'\x02' * 32).get_public_key().sec() - k = b'\x03' * 32 - - A1, C1, proof1 = generate_dleq_proof(a, B, k) - A2, C2, proof2 = generate_dleq_proof(a, B, k) - - assert A1 == A2 - assert C1 == C2 - assert proof1 == proof2 - - -if __name__ == "__main__": - pytest.main([__file__, "-v"]) diff --git a/tests/tests/__init__.py b/tests/tests/__init__.py index 2593ae54..c1e99f03 100644 --- a/tests/tests/__init__.py +++ b/tests/tests/__init__.py @@ -13,6 +13,7 @@ from .test_bip85 import * from .test_taptree import * from .test_finalizer import * +from .test_dleq import * if sys.implementation.name != "micropython": from .test_ecdh import * diff --git a/tests/tests/test_dleq.py b/tests/tests/test_dleq.py new file mode 100644 index 00000000..cd546920 --- /dev/null +++ b/tests/tests/test_dleq.py @@ -0,0 +1,248 @@ +"""Tests for BIP-374 DLEQ proof generation and verification. + +Official test vectors embedded below are taken verbatim from +https://github.com/bitcoin/bips/tree/master/bip-0374 +(test_vectors_generate_proof.csv and test_vectors_verify_proof.csv). +""" + +from unittest import TestCase + +from embit.dleq import ( + tagged_hash, + generate_dleq_proof, + verify_dleq_proof, + SECP256K1_ORDER, +) +from embit.util import secp256k1 + + +def _pubkey(sk: bytes) -> bytes: + return secp256k1.ec_pubkey_serialize(secp256k1.ec_pubkey_create(sk)) + + +# Deterministic stand-in for urandom so this module also runs under +# micropython (which has no os.urandom); the official vectors below carry +# the byte-exact coverage, these only need distinct valid scalars. +_counter = [0] + + +def _rand(): + _counter[0] += 1 + return tagged_hash("test/dleq", bytes([_counter[0]])) + + +# The vectors encode the point at infinity as the string INFINITY, which has +# no SEC encoding, so it cannot be passed to this byte-oriented API at all. +# The stand-in below is an invalid encoding that must be rejected the same +# way (the parser raises, generation fails). +INFINITY = "00" * 33 + +# index, point_G, scalar_a, point_B, auxrand_r, message, result_proof, comment +GENERATE_PROOF_VECTORS = [ + ("0", "02cef38f55e78b321a1f785cb1c6e33dfcef9784c18bdc4e279801c449ccdfb88e", "07ff93d43f1012a5d4a44aba55240212ed39c87b3344e46757d99f24177fc576", "02dad4b35c2379ba8334c9a5dda8f6e6d5cd575a7cc9d3ca4faaac51839daaa30f", "cb979b0fc8ccc7f237751e719d992fcc324b6500af33999cd54a3e5c05fb1ea4", "efb07d4b382d3da1079fbf24df623ba6c2e4c764993bbfa6dd7a4fe4aaf33859", "7e7e934169e0bf4706e6b29e5a621c7fe199a524744a25af80071e111c0e2e94118e730d8add118dd2ee4f7d1cc183e1b87168362d1a6f85c16d8671a3fc7a8a", "Success case 1"), + ("1", "02464e351831efedb755223cabbf664f10564b4742c725c023034bc928ed339e0e", "f4e9172285393c6ada994c811b3e50fc47e96421ea7e54f4a4e459528d4cf562", "03fe589b0fa23f060f6d4d1e76b9b19d5bb3db0e56d39a4303913de0e706463008", "75f12482b9209dae12230ea1f8bf69723a1b447d361db8f510dd9ab33556fd4c", "76184ce9eea5b339ebf5304b57452c1ada1466610f0a58574d6c496798cee04b", "6b4521a8363a7ebc5d95ac6ec6b64db81fcf21795187d7c4600c42b73fb4fb9870ab8d106c0fd2d292c1710e10437b20575ddb3cb32eb77a5618d94ddba600f2", "Success case 2"), + ("2", "0222db2054fef98344352a13bc0304a71da7b5e9a2f7fd1f3c9f3519a3d9377fb7", "589476913e763b60d5c2a5bfb39230ec669caac1b44312e9bcd2d3f4473abfef", "03bc7a19970c812118f74ba659b491e00dade6096ff62d1afe032a92b8671498ed", "4da1c4c4b0f9db4eb6b2e5cb648d7e8a0aa35aa5c4ec4d07f096e0e03deca366", "66503623468a78cfcef47888c85e0010ecd897f441d263448bfc7a89b882ab20", "12aa2aa469b3c037871a09d18ab18d3840219b1ed169f6ef9deae6d927949884a459705ae89a57522224ce3482dee00a41ba511188ae60efdeb736223eb66e7b", "Success case 3"), + ("3", "03dfa65bd3711eba75fa1996a0c1d95a4419bd835304152d9aa6efa590670f2af6", "24d0ed3fc189eb1b64e5dc9dd4af0f3c8c143b0c79cb5fcca0dfa08a11cc60a1", "03b51081323d38fb0b75f0c1ec6755fdb79c239c327ca11269fe68ba8a878b704e", "31a68d6db27f6404bbceff646ff1b26a34704a0105a36c5a845d0257cea19c9b", "f2996b3766d123a949e65541baf1d89d446360d05af51bd93f0445d8c472c952", "7907653d29c5722ae44510e7f2839f253450aefc833b7e0a3b38384032f847f2cf41136b2fe6a558ad125287d20c0117f2a30c4ac0c4cebbcfa1dd3a69d84200", "Success case 4"), + ("4", "02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7", "73fffa796edb72d111b5e0bbda1608f098ac98120796f971b438691e1bfb7b96", "03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01", "1cdfb4d7cce5e50783299896a471a44e6aa2c5e2100d6c37987c6b40503c6162", "0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4", "02277ca5a7acfe8ae13c2db4a8f74489d0ba100ed8b082381ddb6522c4510718ab88b8dbbd785c388ade79586cf6416f3c47a79670af84abccc788a5d9f2e327", "Success case 5"), + ("5", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "c08ca8e0bb59769fc6a4e078456284e00ea34f65add988c246e1bba85824ccdc", "034bccb1c570ac1f3bc42d61fe35de605b99626501ccb20297e1acbbf2d7152aa1", "c8d7056abd4726eb5a0f198740af14d6c1f0c16e5d7a37eaec621b661e669ac4", "", "503562d36910cd2d61a4d07c8ff680265c713e63dde0dcb88e6ea3c58597bdc05b86db9af95eccc475ce2177f941c118fefed20227d4ce8ce9557cb008758de6", "Success case 6"), + ("6", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "8e641ba6bf7f64eec76005a29585a5035376375f33e331215aedfe03b8e80e7a", "0231c64e3efa506fdad6aad0f6084d5f6739de7f448d7e66f9d22f842638f41d60", "02a7b2e2f5a5e9b1078dbb160502a32491fe80a091e91dd92cf77b0b7d90970f", "35841ca532846e1cdd23a3d107824343584f88eff580929469865eae8355ee3c", "5c7b27a33210750e9de8679d9f43497cf9f12ac642cde0a1fc26443aa2fc89bf71aabf7bac89f5d8a96cbe86daba155fa74d6f3e111136179e53b04eb6d7807f", "Success case 7"), + ("7", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "cfb9a7ecc49bea4f2e2ee34c38a6f48b5cd5bd06f4e4d4ffb45905b3d26db842", "021cb81121a00f89769903305a367ad3cc02d5b402b12c026e06ac94bde28cd608", "d38466b77484154a3fcb3151094c1c8a845c73a3c036b3a8ebffd8ef62c9047f", "22616bb5fb2d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794", "78a5544afa75bf152653fe55fb76926f2f65131bf090972a0b0b37d310c28a6bde0e7bfacc10ac12d36f55316ba134b6ba0b844a65ae05cad53c0b296c6639bb", "Success case 8"), + ("8", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "0000000000000000000000000000000000000000000000000000000000000000", "021cb81121a00f89769903305a367ad3cc02d5b402b12c026e06ac94bde28cd608", "d38466b77484154a3fcb3151094c1c8a845c73a3c036b3a8ebffd8ef62c9047f", "22616bb5fb2d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794", "INVALID", "Failure case (a=0)"), + ("9", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", "021cb81121a00f89769903305a367ad3cc02d5b402b12c026e06ac94bde28cd608", "d38466b77484154a3fcb3151094c1c8a845c73a3c036b3a8ebffd8ef62c9047f", "22616bb5fb2d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794", "INVALID", "Failure case (a=N [group order])"), + ("10", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "cfb9a7ecc49bea4f2e2ee34c38a6f48b5cd5bd06f4e4d4ffb45905b3d26db842", "INFINITY", "d38466b77484154a3fcb3151094c1c8a845c73a3c036b3a8ebffd8ef62c9047f", "22616bb5fb2d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794", "INVALID", "Failure case (B is point at infinity)"), +] + +# index, point_G, point_A, point_B, point_C, proof, message, result, comment +VERIFY_PROOF_VECTORS = [ + ("0", "02cef38f55e78b321a1f785cb1c6e33dfcef9784c18bdc4e279801c449ccdfb88e", "02b540b22c2c5ef0dc886abdaad27498453d893265560bc08a187319af6f845f58", "02dad4b35c2379ba8334c9a5dda8f6e6d5cd575a7cc9d3ca4faaac51839daaa30f", "03fefe00951dcd0ef10b12523393c2b8113119de4fdeeab320694e96bdccd2775b", "7e7e934169e0bf4706e6b29e5a621c7fe199a524744a25af80071e111c0e2e94118e730d8add118dd2ee4f7d1cc183e1b87168362d1a6f85c16d8671a3fc7a8a", "efb07d4b382d3da1079fbf24df623ba6c2e4c764993bbfa6dd7a4fe4aaf33859", "TRUE", "Success case 1"), + ("1", "02464e351831efedb755223cabbf664f10564b4742c725c023034bc928ed339e0e", "032baaf1b10845a51b551196984a91efe2adf9d41b92bec3927218e6e4ca344002", "03fe589b0fa23f060f6d4d1e76b9b19d5bb3db0e56d39a4303913de0e706463008", "031f59aa1df22190e00380d8c5941adf899f596593765a1251005fd24f2bf7c884", "6b4521a8363a7ebc5d95ac6ec6b64db81fcf21795187d7c4600c42b73fb4fb9870ab8d106c0fd2d292c1710e10437b20575ddb3cb32eb77a5618d94ddba600f2", "76184ce9eea5b339ebf5304b57452c1ada1466610f0a58574d6c496798cee04b", "TRUE", "Success case 2"), + ("2", "0222db2054fef98344352a13bc0304a71da7b5e9a2f7fd1f3c9f3519a3d9377fb7", "026aa26fcd626f8f55295859e9f8dd1f103149dd64d77c2bbba1bcf33bb37ebaa2", "03bc7a19970c812118f74ba659b491e00dade6096ff62d1afe032a92b8671498ed", "035628d1a69910daef614c7cae68d71ece55c5908af2360629e25c1b7de21eeb4b", "12aa2aa469b3c037871a09d18ab18d3840219b1ed169f6ef9deae6d927949884a459705ae89a57522224ce3482dee00a41ba511188ae60efdeb736223eb66e7b", "66503623468a78cfcef47888c85e0010ecd897f441d263448bfc7a89b882ab20", "TRUE", "Success case 3"), + ("3", "03dfa65bd3711eba75fa1996a0c1d95a4419bd835304152d9aa6efa590670f2af6", "031bf61ba89009ee1266c9003a72e8e07d77877678ccda7f15325aadcd64ed186b", "03b51081323d38fb0b75f0c1ec6755fdb79c239c327ca11269fe68ba8a878b704e", "02d1b1f37a80217ba73785babfa63251052775f9d3ca65060054033288b7a3f66b", "7907653d29c5722ae44510e7f2839f253450aefc833b7e0a3b38384032f847f2cf41136b2fe6a558ad125287d20c0117f2a30c4ac0c4cebbcfa1dd3a69d84200", "f2996b3766d123a949e65541baf1d89d446360d05af51bd93f0445d8c472c952", "TRUE", "Success case 4"), + ("4", "02b15de5a3aefcfe2473916c76e619b5800ac7250ef93a9e6e0dd1505104fc58e7", "0296c8e00dda60bb5565b77371ff913091978646b58ccf218bc591f68a75232e6e", "03a4692be176ff89a972de9cc407083096847b950d1cae72b947665a3d5f4c2f01", "03a7a7f9527fd387c2b2ce0c76669d646c78a3b470a4b34d3a2dabafc8505ef472", "02277ca5a7acfe8ae13c2db4a8f74489d0ba100ed8b082381ddb6522c4510718ab88b8dbbd785c388ade79586cf6416f3c47a79670af84abccc788a5d9f2e327", "0ceb45f560f2cf6b76a139ffe2c47c5ca6d26d6a3a210e59f197413bbec040b4", "TRUE", "Success case 5"), + ("5", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "02637b2c3ea8ca80b9caecc50f4134c86ae9cf7a269133e7afc71f30e3a3cda60c", "034bccb1c570ac1f3bc42d61fe35de605b99626501ccb20297e1acbbf2d7152aa1", "0285b826c8dd175805901906b6c9b4140a30cbcc94c6e7dcf36476038bf90d4718", "503562d36910cd2d61a4d07c8ff680265c713e63dde0dcb88e6ea3c58597bdc05b86db9af95eccc475ce2177f941c118fefed20227d4ce8ce9557cb008758de6", "", "TRUE", "Success case 6"), + ("6", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "02983a72b4cb44d4322641a7b2001900cd6ae0908a610546c73ed126accdba0514", "0231c64e3efa506fdad6aad0f6084d5f6739de7f448d7e66f9d22f842638f41d60", "03af1bc14b384eda28398df6a7900e567c5b6f6613cafce5027b98be015286f71b", "5c7b27a33210750e9de8679d9f43497cf9f12ac642cde0a1fc26443aa2fc89bf71aabf7bac89f5d8a96cbe86daba155fa74d6f3e111136179e53b04eb6d7807f", "35841ca532846e1cdd23a3d107824343584f88eff580929469865eae8355ee3c", "TRUE", "Success case 7"), + ("7", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "03611410561c35dae13135e4ad8094baac9bbcf2f4e18498181a8ff8a6d43be9d9", "021cb81121a00f89769903305a367ad3cc02d5b402b12c026e06ac94bde28cd608", "03d9a98624c0c74fc7eebd39ed84175f80d03c774908e75ca737a0745d1c64e20a", "78a5544afa75bf152653fe55fb76926f2f65131bf090972a0b0b37d310c28a6bde0e7bfacc10ac12d36f55316ba134b6ba0b844a65ae05cad53c0b296c6639bb", "22616bb5fb2d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794", "TRUE", "Success case 8"), + ("8", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "03611410561c35dae13135e4ad8094baac9bbcf2f4e18498181a8ff8a6d43be9d9", "03d9a98624c0c74fc7eebd39ed84175f80d03c774908e75ca737a0745d1c64e20a", "021cb81121a00f89769903305a367ad3cc02d5b402b12c026e06ac94bde28cd608", "78a5544afa75bf152653fe55fb76926f2f65131bf090972a0b0b37d310c28a6bde0e7bfacc10ac12d36f55316ba134b6ba0b844a65ae05cad53c0b296c6639bb", "22616bb5fb2d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794", "FALSE", "Swapped points case 1"), + ("9", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "021cb81121a00f89769903305a367ad3cc02d5b402b12c026e06ac94bde28cd608", "03611410561c35dae13135e4ad8094baac9bbcf2f4e18498181a8ff8a6d43be9d9", "03d9a98624c0c74fc7eebd39ed84175f80d03c774908e75ca737a0745d1c64e20a", "78a5544afa75bf152653fe55fb76926f2f65131bf090972a0b0b37d310c28a6bde0e7bfacc10ac12d36f55316ba134b6ba0b844a65ae05cad53c0b296c6639bb", "22616bb5fb2d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794", "FALSE", "Swapped points case 2"), + ("10", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "021cb81121a00f89769903305a367ad3cc02d5b402b12c026e06ac94bde28cd608", "03d9a98624c0c74fc7eebd39ed84175f80d03c774908e75ca737a0745d1c64e20a", "03611410561c35dae13135e4ad8094baac9bbcf2f4e18498181a8ff8a6d43be9d9", "78a5544afa75bf152653fe55fb76926f2f65131bf090972a0b0b37d310c28a6bde0e7bfacc10ac12d36f55316ba134b6ba0b844a65ae05cad53c0b296c6639bb", "22616bb5fb2d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794", "FALSE", "Swapped points case 3"), + ("11", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "03d9a98624c0c74fc7eebd39ed84175f80d03c774908e75ca737a0745d1c64e20a", "03611410561c35dae13135e4ad8094baac9bbcf2f4e18498181a8ff8a6d43be9d9", "021cb81121a00f89769903305a367ad3cc02d5b402b12c026e06ac94bde28cd608", "78a5544afa75bf152653fe55fb76926f2f65131bf090972a0b0b37d310c28a6bde0e7bfacc10ac12d36f55316ba134b6ba0b844a65ae05cad53c0b296c6639bb", "22616bb5fb2d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794", "FALSE", "Swapped points case 4"), + ("12", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "03d9a98624c0c74fc7eebd39ed84175f80d03c774908e75ca737a0745d1c64e20a", "021cb81121a00f89769903305a367ad3cc02d5b402b12c026e06ac94bde28cd608", "03611410561c35dae13135e4ad8094baac9bbcf2f4e18498181a8ff8a6d43be9d9", "78a5544afa75bf152653fe55fb76926f2f65131bf090972a0b0b37d310c28a6bde0e7bfacc10ac12d36f55316ba134b6ba0b844a65ae05cad53c0b296c6639bb", "22616bb5fb2d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794", "FALSE", "Swapped points case 5"), + ("13", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "03611410561c35dae13135e4ad8094baac9bbcf2f4e18498181a8ff8a6d43be9d9", "021cb81121a00f89769903305a367ad3cc02d5b402b12c026e06ac94bde28cd608", "03d9a98624c0c74fc7eebd39ed84175f80d03c774908e75ca737a0745d1c64e20a", "78a5544afa75bf152653fe55fb76926f2f65131ff090972a0b0b37d310c28a6bde0e7bfacc10ac12d36f55316ba134b6ba0b844a65ae05cad53c0b296c6639bb", "22616bb5fb2d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794", "FALSE", "Tampered proof (random bit-flip)"), + ("14", "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "03611410561c35dae13135e4ad8094baac9bbcf2f4e18498181a8ff8a6d43be9d9", "021cb81121a00f89769903305a367ad3cc02d5b402b12c026e06ac94bde28cd608", "03d9a98624c0c74fc7eebd39ed84175f80d03c774908e75ca737a0745d1c64e20a", "78a5544afa75bf152653fe55fb76926f2f65131bf090972a0b0b37d310c28a6bde0e7bfacc10ac12d36f55316ba134b6ba0b844a65ae05cad53c0b296c6639bb", "22616bb5fb6d7c68270f305122f2a09e833239c4b1c9a04e285119fb606ac794", "FALSE", "Tampered message (random bit-flip)"), +] + + +class TaggedHashTest(TestCase): + def test_deterministic(self): + h1 = tagged_hash("BIP0374/challenge", b"data") + h2 = tagged_hash("BIP0374/challenge", b"data") + self.assertEqual(h1, h2) + self.assertEqual(len(h1), 32) + + def test_different_tags(self): + h1 = tagged_hash("BIP0374/aux", b"data") + h2 = tagged_hash("BIP0374/nonce", b"data") + self.assertNotEqual(h1, h2) + + +class GenerateProofTest(TestCase): + def test_structure(self): + a = _rand() + B = _pubkey(_rand()) + A, C, proof = generate_dleq_proof(a, B) + self.assertEqual(len(A), 33) + self.assertEqual(len(C), 33) + self.assertEqual(len(proof), 64) + + def test_A_equals_aG(self): + a = _rand() + B = _pubkey(_rand()) + A, C, proof = generate_dleq_proof(a, B) + self.assertEqual(A, _pubkey(a)) + + def test_deterministic_with_fixed_aux(self): + a = _rand() + B = _pubkey(_rand()) + r = _rand() + self.assertEqual( + generate_dleq_proof(a, B, r=r), generate_dleq_proof(a, B, r=r) + ) + + def test_different_aux_different_proof(self): + a = _rand() + B = _pubkey(_rand()) + A1, C1, proof1 = generate_dleq_proof(a, B, r=b"\x01" * 32) + A2, C2, proof2 = generate_dleq_proof(a, B, r=b"\x02" * 32) + self.assertEqual((A1, C1), (A2, C2)) + self.assertNotEqual(proof1, proof2) + self.assertTrue(verify_dleq_proof(A1, B, C1, proof1)) + self.assertTrue(verify_dleq_proof(A2, B, C2, proof2)) + + def test_message_changes_proof(self): + a = _rand() + B = _pubkey(_rand()) + r = _rand() + m = _rand() + _, _, proof_no_m = generate_dleq_proof(a, B, r=r) + A, C, proof_m = generate_dleq_proof(a, B, r=r, m=m) + self.assertNotEqual(proof_no_m, proof_m) + self.assertTrue(verify_dleq_proof(A, B, C, proof_m, m=m)) + self.assertFalse(verify_dleq_proof(A, B, C, proof_m)) + self.assertFalse(verify_dleq_proof(A, B, C, proof_no_m, m=m)) + + def test_private_key_zero_fails(self): + B = _pubkey(_rand()) + with self.assertRaises(ValueError): + generate_dleq_proof(b"\x00" * 32, B) + + def test_private_key_at_order_fails(self): + B = _pubkey(_rand()) + a = SECP256K1_ORDER.to_bytes(32, "big") + with self.assertRaises(ValueError): + generate_dleq_proof(a, B) + + def test_bad_aux_length_fails(self): + B = _pubkey(_rand()) + with self.assertRaises(ValueError): + generate_dleq_proof(_rand(), B, r=b"\x01" * 31) + + def test_bad_message_length_fails(self): + B = _pubkey(_rand()) + with self.assertRaises(ValueError): + generate_dleq_proof(_rand(), B, m=b"\x01" * 31) + + def test_multiple_round_trips(self): + for _ in range(5): + a = _rand() + B = _pubkey(_rand()) + A, C, proof = generate_dleq_proof(a, B) + self.assertTrue(verify_dleq_proof(A, B, C, proof)) + + +class VerifyProofTest(TestCase): + def _proof(self): + a = _rand() + B = _pubkey(_rand()) + A, C, proof = generate_dleq_proof(a, B) + return A, B, C, proof + + def test_wrong_A_fails(self): + A, B, C, proof = self._proof() + self.assertFalse(verify_dleq_proof(_pubkey(_rand()), B, C, proof)) + + def test_wrong_B_fails(self): + A, B, C, proof = self._proof() + self.assertFalse(verify_dleq_proof(A, _pubkey(_rand()), C, proof)) + + def test_wrong_C_fails(self): + A, B, C, proof = self._proof() + self.assertFalse(verify_dleq_proof(A, B, _pubkey(_rand()), proof)) + + def test_tampered_proof_fails(self): + A, B, C, proof = self._proof() + tampered = bytes([proof[0] ^ 0x01]) + proof[1:] + self.assertFalse(verify_dleq_proof(A, B, C, tampered)) + + def test_wrong_length_proof_fails(self): + A, B, C, proof = self._proof() + self.assertFalse(verify_dleq_proof(A, B, C, proof[:63])) + self.assertFalse(verify_dleq_proof(A, B, C, proof + b"\x00")) + + def test_s_at_order_fails(self): + A, B, C, proof = self._proof() + bad = proof[:32] + SECP256K1_ORDER.to_bytes(32, "big") + self.assertFalse(verify_dleq_proof(A, B, C, bad)) + + def test_e_at_order_fails(self): + A, B, C, proof = self._proof() + bad = SECP256K1_ORDER.to_bytes(32, "big") + proof[32:] + self.assertFalse(verify_dleq_proof(A, B, C, bad)) + + def test_bad_message_length_fails(self): + A, B, C, proof = self._proof() + self.assertFalse(verify_dleq_proof(A, B, C, proof, m=b"\x01" * 31)) + + def test_invalid_point_fails(self): + A, B, C, proof = self._proof() + bad_point = bytes.fromhex(INFINITY) + self.assertFalse(verify_dleq_proof(bad_point, B, C, proof)) + self.assertFalse(verify_dleq_proof(A, bad_point, C, proof)) + self.assertFalse(verify_dleq_proof(A, B, bad_point, proof)) + self.assertFalse(verify_dleq_proof(A, B, C, proof, G=bad_point)) + + +class OfficialVectorsTest(TestCase): + """Official BIP-374 test vectors, run byte-exact.""" + + def test_generate_proof_vectors(self): + for row in GENERATE_PROOF_VECTORS: + index, G_hex, a_hex, B_hex, r_hex, m_hex, result, comment = row + G = bytes.fromhex(INFINITY if G_hex == "INFINITY" else G_hex) + B = bytes.fromhex(INFINITY if B_hex == "INFINITY" else B_hex) + a = bytes.fromhex(a_hex) + r = bytes.fromhex(r_hex) + m = bytes.fromhex(m_hex) if m_hex else None + if result == "INVALID": + with self.assertRaises(ValueError, msg=comment): + generate_dleq_proof(a, B, r=r, G=G, m=m) + else: + A, C, proof = generate_dleq_proof(a, B, r=r, G=G, m=m) + self.assertEqual(proof, bytes.fromhex(result), comment) + self.assertTrue( + verify_dleq_proof(A, B, C, proof, G=G, m=m), comment + ) + + def test_verify_proof_vectors(self): + for row in VERIFY_PROOF_VECTORS: + index, G_hex, A_hex, B_hex, C_hex, proof_hex, m_hex, result, comment = row + G = bytes.fromhex(INFINITY if G_hex == "INFINITY" else G_hex) + A = bytes.fromhex(INFINITY if A_hex == "INFINITY" else A_hex) + B = bytes.fromhex(INFINITY if B_hex == "INFINITY" else B_hex) + C = bytes.fromhex(INFINITY if C_hex == "INFINITY" else C_hex) + proof = bytes.fromhex(proof_hex) + m = bytes.fromhex(m_hex) if m_hex else None + self.assertEqual( + verify_dleq_proof(A, B, C, proof, G=G, m=m), + result == "TRUE", + comment, + )