From 398acb891940a05d1445e9ef6b240a15642bc999 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 12:37:16 -0300 Subject: [PATCH 01/54] crypto: secp256k1's ECDH returns secret<32>, and gives the raw x coordinate and the shared point --- doc/changelog.adoc | 2 +- doc/generated/backends-keypair.adoc | 2 +- doc/generated/matrix.adoc | 2 +- doc/generated/namespace-curves.adoc | 4 +- doc/generated/use-cases.adoc | 9 +- doc/llms.txt | 10 +- doc/memory.adoc | 2 +- doc/p2p.adoc | 6 +- doc/secp256k1.adoc | 81 +++- doc/tables/crypto.json | 13 +- example/Jamfile | 3 + example/ecdh_session.cpp | 19 +- example/ecdh_x_coordinate.cpp | 121 ++++++ example/ecdh_x_coordinate.expected | 3 + include/webcpp/crypto/curves/secp256k1.hpp | 120 +++++- test/Jamfile | 4 + test/secp256k1_allocation_test.cpp | 11 +- test/secp256k1_ecdh_test.cpp | 406 +++++++++++++++++++++ test/secp256k1_test.cpp | 7 +- test/secp256k1_wycheproof_test.cpp | 198 +--------- test/support/secp256k1_checks.hpp | 5 +- 21 files changed, 771 insertions(+), 257 deletions(-) create mode 100644 example/ecdh_x_coordinate.cpp create mode 100644 example/ecdh_x_coordinate.expected create mode 100644 test/secp256k1_ecdh_test.cpp diff --git a/doc/changelog.adoc b/doc/changelog.adoc index feedffbe..a1fe634c 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -20,7 +20,7 @@ of every version are on webcpp's index page. * Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default, one default per family and target, and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). -* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. +* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH in three forms (ecdh, ecdh_x, ecdh_point) returned as self-wiping secrets, strict DER, low-S and the x-only tweak. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. * Added ciphers::secretbox and secretbox_xchacha20poly1305, without additional data, hybrid::box, box_xchacha20poly1305 and sealed_box (failed seals and opens zeroing data), and curves::x25519::kx_keypair (crypto_kx) on libsodium, refusing peer keys of small order. diff --git a/doc/generated/backends-keypair.adoc b/doc/generated/backends-keypair.adoc index 1ca69118..da9cd9b3 100644 --- a/doc/generated/backends-keypair.adoc +++ b/doc/generated/backends-keypair.adoc @@ -16,7 +16,7 @@ The backends of `+curves::secp256k1::keypair+`, from the test programs that run |libsecp256k1 |`+/third_party//secp256k1+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+secp256k1+`, `+secp256k1_bip340+`, `+secp256k1_xonly_tweak+`) +|native, wasip2, wasip3, emscripten (tested by `+secp256k1+`, `+secp256k1_bip340+`, `+secp256k1_xonly_tweak+`, `+secp256k1_ecdh+`) |=== A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index b63d68eb..621ac0d2 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -59,7 +59,7 @@ |`+curves::secp256k1::keypair+` |libsecp256k1 |native, wasip2, wasip3, emscripten -|`+secp256k1+`, `+secp256k1_bip340+`, `+secp256k1_xonly_tweak+` +|`+secp256k1+`, `+secp256k1_bip340+`, `+secp256k1_xonly_tweak+`, `+secp256k1_ecdh+` |`+curves::secp256k1::verify_schnorr+`, `+verify_ecdsa+` |libsecp256k1 diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index 4bafb223..2dc4d342 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -12,7 +12,7 @@ |Curve |`secp256k1` |`ed25519` |`x25519` |What it does -|BIP 340 Schnorr and ECDSA signatures, ECDH, the x-only tweak +|BIP 340 Schnorr and ECDSA signatures, ECDH in three forms, the x-only tweak |Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair |Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction @@ -57,7 +57,7 @@ |yes: X25519 (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) |Choose it for compatibility with -|Bitcoin's keys and signatures; Nostr's event signatures (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]); Ethereum's ECDSA verification with a known key. Not in this version: Ethereum's recoverable signatures and its addresses from the uncompressed key; ECDH in the raw x-coordinate form of Nostr's encrypted messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]); BIP 32's derivation (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32, hierarchical deterministic wallets]) +|Bitcoin's keys and signatures; Nostr's event signatures (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]). Not in this version: Ethereum's recoverable signatures and its addresses from the uncompressed key; BIP 32's derivation (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32, hierarchical deterministic wallets]) |SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's |TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` (link:https://doc.libsodium.org/key_exchange[libsodium's documentation, key exchange]). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested (link:https://github.com/C2SP/wycheproof[Project Wycheproof, test vectors for cryptographic libraries]) |=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index a214f60a..7f109fab 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -71,13 +71,20 @@ |<> |Agree on a key with a peer through a relay that sees everything -|In `+curves::secp256k1+`: `+keypair::ecdh+` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `+aes256_gcm+` +|In `+curves::secp256k1+`: `+keypair::ecdh+` (SHA-256 of the shared point), then HKDF on Boost.Hash2 and `+aes256_gcm+` |libsecp256k1, and AES-GCM's default |`+/webcpp/crypto//crypto+` + `+/third_party//secp256k1+` + `+/webcpp/crypto//gcm-default+` |<> +|Derive a Nostr direct message's conversation key (NIP-44; the format is a domain library's) +|In `+curves::secp256k1+`: `+keypair::ecdh_x+`, then HKDF on Boost.Hash2 +|libsecp256k1 +|`+/webcpp/crypto//crypto+` + +`+/third_party//secp256k1+` +|<> + |Make and keep a wallet's key |In `+curves::secp256k1+`: `+keypair::make+`, `+xonly_public_key+`, `+public_key+`; `+aes256_gcm+` at rest |libsecp256k1, and AES-GCM's default diff --git a/doc/llms.txt b/doc/llms.txt index 22af6385..d4547678 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -62,13 +62,15 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp ## webcpp::crypto::curves -- [curves::secp256k1::keypair](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): A secp256k1 key pair: BIP 340 Schnorr and ECDSA signatures, ECDH and the x-only tweak. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. +- [curves::secp256k1::keypair](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): A secp256k1 key pair: BIP 340 Schnorr and ECDSA signatures, ECDH in three forms and the x-only tweak. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. - make: Makes a key pair from a secret key. - xonly_public_key: The BIP340 x-only public key. - public_key: The public key, SEC1 compressed. - sign_schnorr: A BIP340 signature of a message of any length. - sign_ecdsa: An ECDSA signature of a 32-byte hash: RFC 6979's nonce, low-S, compact form. - ecdh: The SHA-256 of the compressed shared point with a peer's public key, libsecp256k1's default. + - ecdh_x: The shared point's x coordinate, unhashed: what Wycheproof's ECDH vectors, Nostr's NIP-44 and other protocols that hash it themselves take. + - ecdh_point: The shared point itself, SEC1 uncompressed (0x04, x, y). - tweak_xonly: Tweaks this key pair in place by a 32-byte tweak t: its x-only public key P becomes P + t*G, and its secret key follows (`secp256k1_keypair_xonly_tweak_add`). - [curves::secp256k1::verify_schnorr, verify_ecdsa](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): Verifies a BIP 340 or an ECDSA signature with a public key alone. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. - verify_schnorr: Verifies a BIP340 signature with libsecp256k1's static context, which allocates nothing, after its self-test. @@ -174,7 +176,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [The usage limit](https://webcpporg.github.io/libs/crypto/#crypto-gcm-rules): with random IVs, at most 2^32 messages under one key ([NIST SP 800-38D, GCM and GMAC](https://csrc.nist.gov/pubs/sp/800/38/d/final), section 8.3); rotate the key before. - [A failed open zeroes data](https://webcpporg.github.io/libs/crypto/#crypto-gcm-rules): when the tag does not match, `open` returns `authentication_failed` and zeroes the whole of `data`; keep a copy of the ciphertext if it is needed after a failure. There is no incremental open: a large message is split into records. - [Records: each stream its own key](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): records numbered from 0 with the number as IV are safe only under a key used for that one stream: derive a key per stream (HKDF of the storage key with a random salt) or draw one; never number two streams' records under one key. -- [ECDH's form](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): `keypair::ecdh` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point; it does not interoperate with protocols that take the raw x coordinate, such as Nostr's NIP-44 ([Nostr NIP-44, encrypted payloads](https://github.com/nostr-protocol/nips/blob/master/44.md)). Derive keys from it with HKDF, never use it directly. +- [ECDH's form](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ecdh): `keypair::ecdh` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point; protocols that take the raw x coordinate, such as Nostr's NIP-44 ([Nostr NIP-44, encrypted payloads](https://github.com/nostr-protocol/nips/blob/master/44.md)), need `ecdh_x`. Both sides must use the same form, or they derive different keys. Derive keys with a KDF, never use a shared secret directly. - [The x-only tweak is not BIP 32](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly` is BIP 341's even-y arithmetic ([BIP 341, Taproot](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki)); BIP 32's child derivation needs a tweak of the full key, which this version does not offer ([BIP 32, hierarchical deterministic wallets](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)). - [Ethereum](https://webcpporg.github.io/libs/crypto/#crypto-curves): this version verifies Ethereum's ECDSA signatures with a known key but has no recoverable signature (no recovery id `v`, no public key recovery) and no uncompressed public key output, so it cannot sign Ethereum transactions or derive addresses. - [Compare secrets in constant time](https://webcpporg.github.io/libs/crypto/#crypto-equal): compare a tag, a MAC or a token with `equal`, never `==` or `memcmp` ([CWE-208, observable timing discrepancy](https://cwe.mitre.org/data/definitions/208.html)). @@ -194,7 +196,8 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Turn a sequential id into an opaque reference](https://webcpporg.github.io/libs/crypto/#crypto-block): `aes256` (webcpp::crypto::ciphers); backend ctaes, or OpenSSL natively and on WASI; Jamfile /webcpp/crypto//crypto /third_party//ctaes. Example: example/order_reference.cpp. - [Prove who wrote a message posted to a relay](https://webcpporg.github.io/libs/crypto/#crypto-p2p-signed): `keypair::sign_schnorr`, `verify_schnorr` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/signed_message.cpp. - [Check a software update or a licence file](https://webcpporg.github.io/libs/crypto/#crypto-everyday-update): `keypair::sign_ecdsa`, `verify_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/signed_update.cpp. -- [Agree on a key with a peer through a relay that sees everything](https://webcpporg.github.io/libs/crypto/#crypto-p2p-session): `keypair::ecdh` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `aes256_gcm` (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/ecdh_session.cpp. +- [Agree on a key with a peer through a relay that sees everything](https://webcpporg.github.io/libs/crypto/#crypto-p2p-session): `keypair::ecdh` (SHA-256 of the shared point), then HKDF on Boost.Hash2 and `aes256_gcm` (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/ecdh_session.cpp. +- [Derive a Nostr direct message's conversation key (NIP-44; the format is a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ecdh): `keypair::ecdh_x`, then HKDF on Boost.Hash2 (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdh_x_coordinate.cpp. - [Make and keep a wallet's key](https://webcpporg.github.io/libs/crypto/#crypto-wallets-key): `keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/wallet_key.cpp. - [Sign a Bitcoin SegWit v0 input (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-der): `sign_ecdsa`, `to_der`, `normalize_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdsa_der.cpp. - [Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly`, `keypair::tweak_xonly` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/taproot_tweak.cpp. @@ -220,6 +223,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/bearssl_prng.cpp: Seeds BearSSL's own HMAC-DRBG from webcpp::crypto::random_device and draws bytes from it. A generator is only as good as its seed: the seed must come from the system's entropy, never from the clock or a counter. - example/box_messages.cpp: Two people who know each other's X25519 public keys exchange messages in libsodium's box: each makes a box from the own secret key and the other's public key, agreeing one key for the pair, then seals each message with a nonce drawn at random. What one seals the other opens; a stranger's box, from another key pair, does not. Prints what each reads. - example/ecdh_session.cpp: Two peers agree on a shared secret with ECDH, derive a session key from it with HKDF-SHA-256 and talk over AES-256-GCM. The raw ECDH output is not a key: HKDF turns it into one and ties it to this application with a context string. +- example/ecdh_x_coordinate.cpp: Two key pairs agree on the shared point's raw x coordinate with ecdh_x, the form Nostr's encrypted messages (NIP-44) take, then derive from it what a NIP-44 library would: the conversation key, HKDF-extract with the salt "nip44-v2". The x coordinate is not a key; the derivation that makes one is the protocol's, and belongs to a domain library. - example/ecdsa_der.cpp: Signs with ECDSA the way a domain library does: a sighash computed by the library, a 64-byte signature, its strict DER form for the wire, and the low-S rule. The same signature has a twin with S replaced by n - S; accepting both makes transaction ids malleable, so verifiers refuse the high-S twin. - example/ed25519_sign.cpp: Signs RFC 8032's second Ed25519 test with a key pair made from its seed and verifies the signature with the public key alone; then signs the message "abc" given in two pieces with Ed25519ph, as RFC 8032's Ed25519ph test does, and verifies it. Prints each key and signature in hex. - example/equal_hmac.cpp: Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::crypto::equal, the constant-time comparison. Comparing tags with == or memcmp stops at the first difference, and that timing lets an attacker guess a valid tag one byte at a time. diff --git a/doc/memory.adoc b/doc/memory.adoc index 9986b01d..6942a853 100644 --- a/doc/memory.adoc +++ b/doc/memory.adoc @@ -15,7 +15,7 @@ key pair. Every buffer is the caller's. * *Nothing allocates per message, on any backend:* `seal`, `open`, `begin_seal`, `update`, `result`, `encrypt`, `decrypt`, `fill`, the signatures, -`ecdh` and the verifications. The counting tests of `test/` prove it, every +`ecdh`, `ecdh_x`, `ecdh_point` and the verifications. The counting tests of `test/` prove it, every `operator new` and the C library's allocator counted. * *BearSSL and ctaes allocate nothing,* `make` included: the key schedule lives inside the object. diff --git a/doc/p2p.adoc b/doc/p2p.adoc index 54bd16f8..fed02fce 100644 --- a/doc/p2p.adoc +++ b/doc/p2p.adoc @@ -151,6 +151,6 @@ a secret key computes every past session's secret from the recorded public keys, while fresh pairs wiped after the session give *forward secrecy* (link:https://en.wikipedia.org/wiki/Forward_secrecy[Wikipedia]); a long-lived key signs the fresh public keys instead. `ecdh` returns libsecp256k1's hashed -form, the SHA-256 of the compressed shared point: both sides must use it, and -it does not interoperate with protocols that take the raw x coordinate, such -as Nostr's NIP-44 (<>). +form, the SHA-256 of the compressed shared point, as a `secret<32>` that wipes +itself: both sides must use the same form, and a protocol that takes the raw x +coordinate, such as Nostr's NIP-44, needs `ecdh_x` (<>). diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index acd87098..413ce948 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -25,20 +25,20 @@ Each signature's nonce is RFC 6979's, derived from the key and the hash, so that no weak generator can leak the key (link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979]), and each is in low-S form; -* *ECDH*, a 32-byte shared secret: libsecp256k1's hashed form, the SHA-256 of -the shared point in its 33-byte compressed encoding. It interoperates only with -peers that hash the same way, such as another program on libsecp256k1's -default. It does not interoperate with Nostr's encrypted messages -(link:https://github.com/nostr-protocol/nips/blob/master/44.md[NIP-44]) or -other protocols that take the shared point's raw x coordinate, which this -version does not give. +* *ECDH*, a shared secret: `ecdh` gives libsecp256k1's hashed form, the +SHA-256 of the shared point in its 33-byte compressed encoding, one of three +forms (<>). It interoperates only with peers that hash +the same way, such as another program on libsecp256k1's default; `ecdh_x` +gives the raw x coordinate that Nostr's encrypted messages +(link:https://github.com/nostr-protocol/nips/blob/master/44.md[NIP-44]) take. A `keypair` is made from a 32-byte secret key with `make(secret)`, which allocates its signing context in the `std::pmr::memory_resource` it is given, and randomises it from `random_device`; crypto's own code allocates nothing else (<>). A key pair gives its x-only public key (`xonly_public_key`) and its compressed one (`public_key`), signs -(`sign_schnorr`, `sign_ecdsa`), derives an ECDH secret (`ecdh`), and is tweaked +(`sign_schnorr`, `sign_ecdsa`), derives an ECDH secret (`ecdh`, `ecdh_x`, +`ecdh_point`), and is tweaked in place (`tweak_xonly`). `verify_schnorr` and `verify_ecdsa` check signatures with a public key alone; `to_der`, `from_der` (strict DER) and `normalize_ecdsa` convert ECDSA's DER and low-S forms; and `tweak_xonly` tweaks @@ -87,3 +87,68 @@ examples use zeros only to print fixed signatures. not enforce it. A verifier that normalizes before verifying accepts both forms of a signature, so it must not rely on the signature's bytes being unique (link:https://github.com/bitcoin/bips/blob/master/bip-0146.mediawiki[BIP 146]). + +[#crypto-secp256k1-ecdh] +==== Three forms of ECDH + +Two users of a chat app who have never met want to talk without the server +reading along. Each publishes a public key; with elliptic-curve Diffie-Hellman +(ECDH) each combines its own secret key with the other's public key and both +arrive at the same shared secret, which nobody who sees only the public keys +can compute +(link:https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman[Wikipedia]). +The shared secret is a point on the curve, the secret key of one side times the +public key of the other; what a program takes of that point is a choice of the +protocol, and a key pair gives the three that protocols use: + +* `ecdh`: the SHA-256 of the point's compressed encoding, 32 bytes, +libsecp256k1's default +(link:https://github.com/bitcoin-core/secp256k1#readme[libsecp256k1]). Two +programs on webcpp, or one on libsecp256k1's default, agree on it; it is the +form of the chat session of <>. +* `ecdh_x`: the point's x coordinate, 32 bytes, unhashed. Nostr's encrypted +messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[NIP-44]) +and Wycheproof's ECDH test vectors +(link:https://github.com/C2SP/wycheproof[Wycheproof]) take this form; the +protocol then hashes it its own way. +* `ecdh_point`: the point itself, SEC1 uncompressed (0x04, x, y), 65 bytes, for +a protocol that hashes both coordinates +(link:https://www.secg.org/sec2-v2.pdf[SEC 2]). + +Each is returned as a `secret`, which wipes its bytes when it is destroyed +or moved from: a program reads it with `bytes()` and makes no copy of its own +to forget. Each refuses a moved-from key pair with `invalid_state`, and a peer +key that is not a point of the curve, or not 33 bytes compressed or 65 bytes +uncompressed with the prefix 04, with `invalid_public_key`. They are members +of the key pair, whose backends are listed above. + +*Example.* Two key pairs agree on the x coordinate, and a Nostr library's +first step follows: NIP-44's conversation key, HKDF-extract +(link:https://www.rfc-editor.org/rfc/rfc5869[RFC 5869]) of the x coordinate +with the salt `nip44-v2`. The rest of NIP-44 (message keys, padding, the +payload) is a domain library's, not crypto's: + +[source,cpp] +---- +include::{examples}/ecdh_x_coordinate.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/ecdh_x_coordinate.expected[] +---- + +*Pitfalls.* + +* The raw x coordinate is not a key: a Diffie-Hellman value is not uniformly +random (link:https://www.rfc-editor.org/rfc/rfc5869#section-3.3[RFC 5869, +section 3.3]), and only about half of all 32-byte values are the x of a point. +A protocol's key derivation function (HKDF in NIP-44) turns it into keys; used +directly as an AES key it is weaker than it looks. +* Two programs must agree on the form. One that takes `ecdh` and one that +takes `ecdh_x` derive different keys from the same key pairs, and fail +silently: every message is refused as forged, with nothing pointing at the +cause. Read the protocol's specification for the form it names. +* Never use one shared secret as two keys, one per direction or one for +encryption and one for authentication: derive one key per purpose with the +KDF, each with its own label (<>). diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index f8f43b63..b106dc66 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -273,13 +273,13 @@ { "id": "keypair", "family": "secp256k1", - "functions": ["make", "xonly_public_key", "public_key", "sign_schnorr", "sign_ecdsa", "ecdh", "tweak_xonly"], + "functions": ["make", "xonly_public_key", "public_key", "sign_schnorr", "sign_ecdsa", "ecdh", "ecdh_x", "ecdh_point", "tweak_xonly"], "namespace": "curves", "api": "curves::secp256k1::keypair", "header": "", - "what": "A secp256k1 key pair: BIP 340 Schnorr and ECDSA signatures, ECDH and the x-only tweak.", + "what": "A secp256k1 key pair: BIP 340 Schnorr and ECDSA signatures, ECDH in three forms and the x-only tweak.", "section": "crypto-secp256k1", - "backends": {"secp256k1": {"tests": ["secp256k1", "secp256k1_bip340", "secp256k1_xonly_tweak"]}} + "backends": {"secp256k1": {"tests": ["secp256k1", "secp256k1_bip340", "secp256k1_xonly_tweak", "secp256k1_ecdh"]}} }, { "id": "verify", @@ -829,7 +829,7 @@ {"title": "The usage limit", "section": "crypto-gcm-rules", "text": "with random IVs, at most 2^32 messages under one key ({sp800-38d}, section 8.3); rotate the key before."}, {"title": "A failed open zeroes data", "section": "crypto-gcm-rules", "text": "when the tag does not match, `open` returns `authentication_failed` and zeroes the whole of `data`; keep a copy of the ciphertext if it is needed after a failure. There is no incremental open: a large message is split into records."}, {"title": "Records: each stream its own key", "section": "crypto-gcm-incremental", "text": "records numbered from 0 with the number as IV are safe only under a key used for that one stream: derive a key per stream (HKDF of the storage key with a random salt) or draw one; never number two streams' records under one key."}, - {"title": "ECDH's form", "section": "crypto-secp256k1", "text": "`keypair::ecdh` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point; it does not interoperate with protocols that take the raw x coordinate, such as Nostr's NIP-44 ({nip44}). Derive keys from it with HKDF, never use it directly."}, + {"title": "ECDH's form", "section": "crypto-secp256k1-ecdh", "text": "`keypair::ecdh` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point; protocols that take the raw x coordinate, such as Nostr's NIP-44 ({nip44}), need `ecdh_x`. Both sides must use the same form, or they derive different keys. Derive keys with a KDF, never use a shared secret directly."}, {"title": "The x-only tweak is not BIP 32", "section": "crypto-wallets-taproot", "text": "`tweak_xonly` is BIP 341's even-y arithmetic ({bip341}); BIP 32's child derivation needs a tweak of the full key, which this version does not offer ({bip32})."}, {"title": "Ethereum", "section": "crypto-curves", "text": "this version verifies Ethereum's ECDSA signatures with a known key but has no recoverable signature (no recovery id `v`, no public key recovery) and no uncompressed public key output, so it cannot sign Ethereum transactions or derive addresses."}, {"title": "Compare secrets in constant time", "section": "crypto-equal", "text": "compare a tag, a MAC or a token with `equal`, never `==` or `memcmp` ({cwe208})."}, @@ -887,7 +887,7 @@ "columns": ["Curve", "What it does", "Security level", "Key sizes", "Signature sizes", "Speed", "Constant time, measured", "Standards", "Ecosystems that require it", "Browsers' WebCrypto", "Choose it for compatibility with"], "cited": ["Standards", "Ecosystems that require it", "Browsers' WebCrypto"], "rows": [ - ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, ECDH, the x-only tweak", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 32 bytes x-only", "64 bytes; ECDSA in DER up to 72", "{speed:secp256k1}", "{constant_time:secp256k1}", "{sec2}, {bip340}, {rfc6979}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key. Not in this version: Ethereum's recoverable signatures and its addresses from the uncompressed key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}); BIP 32's derivation ({bip32})"], + ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, ECDH in three forms, the x-only tweak", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 32 bytes x-only", "64 bytes; ECDSA in DER up to 72", "{speed:secp256k1}", "{constant_time:secp256k1}", "{sec2}, {bip340}, {rfc6979}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}). Not in this version: Ethereum's recoverable signatures and its addresses from the uncompressed key; BIP 32's derivation ({bip32})"], ["`ed25519`", "Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair", "about 128 bits ({rfc8032})", "secret 32 bytes (the seed); public 32 bytes", "64 bytes", "{speed:ed25519}", "{constant_time:ed25519}", "{rfc8032}, {fips186-5}", "SSH keys ({rfc8709}), Signal's signatures on its Curve25519 keys ({signal-xeddsa}), Tor's identity keys ({tor-cert-spec}), Solana's accounts ({solana-accounts})", "yes: Ed25519 ({webcrypto})", "SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"], ["`x25519`", "Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction", "about 128 bits ({rfc7748})", "secret 32 bytes; public 32 bytes", "none: no signatures", "{speed:x25519}", "{constant_time:x25519}", "{rfc7748}", "TLS 1.3 ({rfc8446-groups}), SSH ({rfc8731}), WireGuard ({wireguard}), Signal ({x3dh})", "yes: X25519 ({webcrypto})", "TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` ({libsodium-kx}). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested ({wycheproof})"] ] @@ -913,7 +913,8 @@ {"need": "Turn a sequential id into an opaque reference", "namespace": "webcpp::crypto::ciphers", "api": "`aes256`", "backend": "ctaes, or OpenSSL natively and on WASI", "jamfile": "/webcpp/crypto//crypto /third_party//ctaes", "example": "order_reference", "section": "crypto-block"}, {"need": "Prove who wrote a message posted to a relay", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_schnorr`, `verify_schnorr`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "signed_message", "section": "crypto-p2p-signed"}, {"need": "Check a software update or a licence file", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_ecdsa`, `verify_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "signed_update", "section": "crypto-everyday-update"}, - {"need": "Agree on a key with a peer through a relay that sees everything", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::ecdh` (SHA-256 of the shared point: not NIP-44's raw x coordinate), then HKDF on Boost.Hash2 and `aes256_gcm`", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "ecdh_session", "section": "crypto-p2p-session"}, + {"need": "Agree on a key with a peer through a relay that sees everything", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::ecdh` (SHA-256 of the shared point), then HKDF on Boost.Hash2 and `aes256_gcm`", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "ecdh_session", "section": "crypto-p2p-session"}, + {"need": "Derive a Nostr direct message's conversation key (NIP-44; the format is a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::ecdh_x`, then HKDF on Boost.Hash2", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdh_x_coordinate", "section": "crypto-secp256k1-ecdh"}, {"need": "Make and keep a wallet's key", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "wallet_key", "section": "crypto-wallets-key"}, {"need": "Sign a Bitcoin SegWit v0 input (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`sign_ecdsa`, `to_der`, `normalize_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdsa_der", "section": "crypto-wallets-der"}, {"need": "Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`tweak_xonly`, `keypair::tweak_xonly`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "taproot_tweak", "section": "crypto-wallets-taproot"}, diff --git a/example/Jamfile b/example/Jamfile index 0695d5b3..b817fc26 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -49,6 +49,9 @@ webcpp.example signed_update.cpp : /third_party//secp256k1 ; # ECDH, HKDF-SHA-256 and AES-256-GCM between two peers. webcpp.example ecdh_session.cpp : /third_party//secp256k1 /webcpp/crypto//gcm-default ; +# ECDH's raw x coordinate, and the NIP-44 conversation key a domain library derives from it. +webcpp.example ecdh_x_coordinate.cpp : /third_party//secp256k1 ; + # A wallet's key pair, its secret sealed at rest and restored. webcpp.example wallet_key.cpp : /third_party//secp256k1 /webcpp/crypto//gcm-default ; diff --git a/example/ecdh_session.cpp b/example/ecdh_session.cpp index be3f3304..5864a5db 100644 --- a/example/ecdh_session.cpp +++ b/example/ecdh_session.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -126,10 +127,11 @@ boost::system::result generate_key() { } } -// Both sides derive their session key the same way. +// Both sides derive their session key the same way. The shared secret wipes itself when it +// goes out of scope; the key derived from it is the program's to wipe. boost::system::result session_cipher( - std::array const& shared) { - auto key = hkdf_sha256<32>(shared, {}, bytes_of("example chat v1 session key")); + crypto::secret<32> const& shared) { + auto key = hkdf_sha256<32>(shared.bytes(), {}, bytes_of("example chat v1 session key")); auto cipher = crypto::ciphers::aes256_gcm::make(key); // The cipher keeps its own copy of the key, which it wipes; this one goes now. wipe(std::as_writable_bytes(std::span(key))); @@ -167,19 +169,18 @@ int main() { if (!alice_public || !bob_public) { return 1; } - auto alice_shared = alice->ecdh(*bob_public); - auto bob_shared = bob->ecdh(*alice_public); - if (!alice_shared || !bob_shared || !crypto::equal(*alice_shared, *bob_shared)) { + auto const alice_shared = alice->ecdh(*bob_public); + auto const bob_shared = bob->ecdh(*alice_public); + if (!alice_shared || !bob_shared || + !crypto::equal(alice_shared->bytes(), bob_shared->bytes())) { return 1; } std::printf("shared secrets match\n"); // end::agree[] + // The shared secrets are secret<32>, which wipe themselves when they go out of scope. auto alice_cipher = session_cipher(*alice_shared); auto bob_cipher = session_cipher(*bob_shared); - // The shared secrets have given their keys: wipe them. - wipe(std::as_writable_bytes(std::span(*alice_shared))); - wipe(std::as_writable_bytes(std::span(*bob_shared))); if (!alice_cipher || !bob_cipher) { return 1; } diff --git a/example/ecdh_x_coordinate.cpp b/example/ecdh_x_coordinate.cpp new file mode 100644 index 00000000..3af5f27a --- /dev/null +++ b/example/ecdh_x_coordinate.cpp @@ -0,0 +1,121 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Two key pairs agree on the shared point's raw x coordinate with ecdh_x, the form Nostr's +// encrypted messages (NIP-44) take, then derive from it what a NIP-44 library would: the +// conversation key, HKDF-extract with the salt "nip44-v2". The x coordinate is not a key; the +// derivation that makes one is the protocol's, and belongs to a domain library. +// tag::program[] +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace secp256k1 = webcpp::crypto::curves::secp256k1; +namespace hash2 = boost::hash2; + +namespace { + +// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead +// store: crypto wipes its own copies of keys this way, and the program wipes its own. +void wipe(std::span secret) { + std::byte volatile* const bytes = secret.data(); + for (std::size_t i = 0; i < secret.size(); ++i) { + bytes[i] = std::byte{0}; + } +} + +// Wipes an object of key-derived state, such as an HMAC whose inner and outer states hold the +// key: its bytes are all it is, so overwriting them leaves nothing of the key. +template +void wipe_object(T& object) { + static_assert(std::is_trivially_copyable_v); + wipe(std::as_writable_bytes(std::span(&object, 1))); +} + +std::span bytes_of(std::string_view text) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + return {reinterpret_cast(text.data()), text.size()}; +} + +void print_hex(char const* label, std::span bytes) { + std::printf("%s", label); + for (std::uint8_t const octet : bytes) { + std::printf("%02x", static_cast(octet)); + } + std::printf("\n"); +} + +// NIP-44's conversation key: HKDF-extract (RFC 5869), an HMAC-SHA-256 keyed with the salt +// "nip44-v2" over the shared x coordinate. A NIP-44 library computes it; the message keys, +// the padding and the payload's format that follow are the protocol's too. +std::array conversation_key(crypto::secret<32> const& shared_x) { + auto const salt = bytes_of("nip44-v2"); + hash2::hmac_sha2_256 extract(salt.data(), salt.size()); + extract.update(shared_x.bytes().data(), shared_x.size()); + auto digest = extract.result(); + wipe_object(extract); + std::array key{}; + std::span const digest_bytes(digest.data(), digest.size()); + std::ranges::copy(digest_bytes, key.begin()); + wipe(std::as_writable_bytes(std::span(digest.data(), digest.size()))); + return key; +} + +boost::system::result from_secret(std::uint8_t fill) { + std::array secret{}; + secret.fill(fill); + auto made = secp256k1::keypair::make(secret); + // The key pair keeps its own copy, which it wipes; this one goes now. + wipe(std::as_writable_bytes(std::span(secret))); + return made; +} + +} // namespace + +int main() { + // Fixed secrets, so that the output is fixed. A real program draws its secret keys from + // random_device, as wallet_key.cpp does. + auto const alice = from_secret(0x11); + auto const bob = from_secret(0x22); + if (!alice || !bob) { + return 1; + } + auto const alice_public = alice->public_key(); + auto const bob_public = bob->public_key(); + if (!alice_public || !bob_public) { + return 1; + } + // Each side combines its secret key with the other's public key: the same x coordinate, + // a secret<32> that wipes itself. + auto const alice_x = alice->ecdh_x(*bob_public); + auto const bob_x = bob->ecdh_x(*alice_public); + if (!alice_x || !bob_x || !crypto::equal(alice_x->bytes(), bob_x->bytes())) { + return 1; + } + std::printf("shared x coordinates match\n"); + + // A real program never prints a shared secret; this one does to show the fixed value. + print_hex("x: ", alice_x->bytes()); + auto key = conversation_key(*alice_x); + print_hex("conversation key (what a NIP-44 library derives): ", key); + wipe(std::as_writable_bytes(std::span(key))); + return 0; +} + +// end::program[] diff --git a/example/ecdh_x_coordinate.expected b/example/ecdh_x_coordinate.expected new file mode 100644 index 00000000..66d192eb --- /dev/null +++ b/example/ecdh_x_coordinate.expected @@ -0,0 +1,3 @@ +shared x coordinates match +x: 77e0510d5042e2f5e9e59c977b81eeed590cf7d20c1c51da451a8eaa9fdc45ff +conversation key (what a NIP-44 library derives): 2cbdf074f601178c24da3f829b504507a1f550f97d472af0f3f2cc59ab7757d1 diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index bd674187..a0657b12 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -6,7 +6,8 @@ /** secp256k1 on libsecp256k1: BIP340 Schnorr and ECDSA signatures, their verification, and - ECDH; ECDSA's DER and low-S forms, and the tweak of an x-only key. + ECDH in three forms, each a secret; ECDSA's DER and low-S forms, and the tweak of an x-only + key. @see "secp256k1", in the guide. */ @@ -21,6 +22,7 @@ #include #include #include // lint-world: the context's randomisation, its purpose +#include #include @@ -28,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -135,6 +138,41 @@ struct secp256k1_secret { secp256k1_nonzero(std::span(output_bytes).last<32>()); } +extern "C" { + +/** + * libsecp256k1's ECDH hash function that hashes nothing: the shared point's x coordinate, + * 32 bytes, as Wycheproof's and NIP-44's ECDH give it. C linkage, as libsecp256k1's function + * pointer type has. + * + * @return 1, always. + */ +inline int webcpp_crypto_detail_secp256k1_copy_x(unsigned char* output_bytes, + unsigned char const* x_coordinate, + unsigned char const* /*y_coordinate*/, + void* /*user_data*/) noexcept { + std::memcpy(output_bytes, x_coordinate, 32); + return 1; +} + +/** + * libsecp256k1's ECDH hash function that writes the shared point, SEC1 uncompressed: + * 0x04, x, y, 65 bytes. + * + * @return 1, always. + */ +inline int webcpp_crypto_detail_secp256k1_copy_point(unsigned char* output_bytes, + unsigned char const* x_coordinate, + unsigned char const* y_coordinate, + void* /*user_data*/) noexcept { + output_bytes[0] = 0x04; + std::memcpy(output_bytes + 1, x_coordinate, 32); + std::memcpy(output_bytes + 33, y_coordinate, 32); + return 1; +} + +} // extern "C" + /** * Whether `Backend` is libsecp256k1, the one backend of `curves::secp256k1`. * @@ -357,26 +395,39 @@ class basic_keypair { * default. * * @param public_key_bytes The peer's key, SEC1: 33 bytes, prefix 02 or 03, or 65, prefix 04. - * @return 32 bytes; `invalid_state`; `invalid_public_key`; `backend_failure`. + * @return 32 secret bytes; `invalid_state`; `invalid_public_key`; `backend_failure`. */ - [[nodiscard]] boost::system::result> ecdh( + [[nodiscard]] boost::system::result> ecdh( std::span public_key_bytes) const noexcept { - if (!keyed_) { - return error::invalid_state; - } - secp256k1_pubkey parsed_value{}; - if (!webcpp::crypto::detail::secp256k1_parse_public_key(public_key_bytes, parsed_value)) { - return error::invalid_public_key; - } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - webcpp::crypto::detail::secp256k1_secret secret_bytes; - secp256k1_keypair_sec(context_, secret_bytes.bytes.data(), &keypair_); - std::array output_bytes{}; - if (secp256k1_ecdh(context_, output_bytes.data(), &parsed_value, secret_bytes.bytes.data(), - nullptr, nullptr) == 0) { - return error::backend_failure; - } - return output_bytes; + return agree<32>(public_key_bytes, nullptr); + } + + /** + * The shared point's x coordinate, unhashed: what Wycheproof's ECDH vectors, Nostr's NIP-44 + * and other protocols that hash it themselves take. + * + * Tip: the x coordinate is not a key; a protocol derives its keys from it (NIP-44 with + * HKDF), and that derivation is the protocol's. + * + * @param public_key_bytes The peer's key, SEC1, as `ecdh` takes it. + * @return 32 secret bytes; `invalid_state`; `invalid_public_key`; `backend_failure`. + */ + [[nodiscard]] boost::system::result> ecdh_x( + std::span public_key_bytes) const noexcept { + return agree<32>(public_key_bytes, + webcpp::crypto::detail::webcpp_crypto_detail_secp256k1_copy_x); + } + + /** + * The shared point itself, SEC1 uncompressed (0x04, x, y). + * + * @param public_key_bytes The peer's key, SEC1, as `ecdh` takes it. + * @return 65 secret bytes; `invalid_state`; `invalid_public_key`; `backend_failure`. + */ + [[nodiscard]] boost::system::result> ecdh_point( + std::span public_key_bytes) const noexcept { + return agree<65>(public_key_bytes, + webcpp::crypto::detail::webcpp_crypto_detail_secp256k1_copy_point); } /** @@ -409,6 +460,37 @@ class basic_keypair { private: basic_keypair() noexcept = default; + /** + * ECDH with a peer's public key, its output written by `hash_function` into the secret: + * libsecp256k1's SHA-256 when it is null. + * + * @tparam N The output's size, which `hash_function` writes. + * @param public_key_bytes The peer's key, SEC1, as `ecdh` takes it. + * @param hash_function libsecp256k1's hash function, or null for its default. + * @return `N` secret bytes; `invalid_state`; `invalid_public_key`; `backend_failure`. + */ + template + [[nodiscard]] boost::system::result> agree( + std::span public_key_bytes, + secp256k1_ecdh_hash_function hash_function) const noexcept { + if (!keyed_) { + return error::invalid_state; + } + secp256k1_pubkey parsed_value{}; + if (!webcpp::crypto::detail::secp256k1_parse_public_key(public_key_bytes, parsed_value)) { + return error::invalid_public_key; + } + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + webcpp::crypto::detail::secp256k1_secret secret_bytes; + secp256k1_keypair_sec(context_, secret_bytes.bytes.data(), &keypair_); + secret shared_secret; + if (secp256k1_ecdh(context_, shared_secret.writable().data(), &parsed_value, + secret_bytes.bytes.data(), hash_function, nullptr) == 0) { + return error::backend_failure; + } + return shared_secret; + } + static std::size_t context_size() noexcept { return secp256k1_context_preallocated_size(webcpp::crypto::detail::secp256k1_context_flags); } diff --git a/test/Jamfile b/test/Jamfile index 57c3f702..c21e0fd0 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -206,6 +206,10 @@ crypto-run secp256k1_bip340 : secp256k1_bip340_test.cpp crypto-run secp256k1_wycheproof : secp256k1_wycheproof_test.cpp : /third_party//secp256k1 /third_party//wycheproof /webcpp//boost_json ; +# The three forms of ECDH, each a secret, and Wycheproof's ECDH vectors. +crypto-run secp256k1_ecdh : secp256k1_ecdh_test.cpp + : /third_party//secp256k1 /third_party//wycheproof + /webcpp//boost_json ; # libsecp256k1's recovery and ElligatorSwift modules, which webcpp does not # wrap, called through the C API and linked. crypto-run secp256k1_c_api : secp256k1_c_api_test.cpp : /third_party//secp256k1 ; diff --git a/test/secp256k1_allocation_test.cpp b/test/secp256k1_allocation_test.cpp index 9a760e48..34ca2f6d 100644 --- a/test/secp256k1_allocation_test.cpp +++ b/test/secp256k1_allocation_test.cpp @@ -7,9 +7,10 @@ // secp256k1's one allocation (spec section 8.5): make allocates the signing context once, in // the resource it is given, of libsecp256k1's preallocated size and aligned to max_align_t, // and never through operator new nor the C library's allocator where the target lets a -// program count it; the signatures, ECDH, the public keys, both verifications, the DER and -// low-S functions and the x-only tweak allocate nothing, each counted alone; the destructor -// gives the block back; a refused make allocates nothing. A control proves the counter moves. +// program count it; the signatures, the three forms of ECDH, the public keys, both +// verifications, the DER and low-S functions and the x-only tweak allocate nothing, each +// counted alone; the destructor gives the block back; a refused make allocates nothing. A +// control proves the counter moves. #include #include @@ -101,7 +102,9 @@ int main() { auto const xonly = key.xonly_public_key(); auto const public_key = key.public_key(); auto const shared = key.ecdh(*public_key); - BOOST_TEST(schnorr && ecdsa && xonly && public_key && shared); + auto const shared_x = key.ecdh_x(*public_key); + auto const shared_point = key.ecdh_point(*public_key); + BOOST_TEST(schnorr && ecdsa && xonly && public_key && shared && shared_x && shared_point); BOOST_TEST(secp::verify_schnorr(*schnorr, message, *xonly).has_value()); BOOST_TEST(secp::verify_ecdsa(*ecdsa, message, *public_key).has_value()); BOOST_TEST_EQ(webcpp::test::allocations(), before); diff --git a/test/secp256k1_ecdh_test.cpp b/test/secp256k1_ecdh_test.cpp new file mode 100644 index 00000000..58851fdf --- /dev/null +++ b/test/secp256k1_ecdh_test.cpp @@ -0,0 +1,406 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// secp256k1's three forms of ECDH, each a secret: ecdh (libsecp256k1's SHA-256 of the +// compressed shared point), ecdh_x (the point's raw x coordinate) and ecdh_point (the point, +// SEC1 uncompressed). Two sides agree in every form; a known answer computed apart from +// libsecp256k1; ecdh keeps version 0.1's value; Wycheproof's ECDH vectors, in ASN.1 and JWK +// form, against ecdh_x; the refusals of a moved-from key pair and of every malformed key. + +#include +#include +#include +#include + +#include "support/hex.hpp" +#include "support/secp256k1_data.hpp" + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace secp = webcpp::crypto::curves::secp256k1; +namespace test = webcpp::test; +namespace json = boost::json; + +namespace { + +using bytes = std::vector; + +void fail(std::string const& message) { + BOOST_ERROR(message.c_str()); +} + +secp::keypair from_byte(std::uint8_t b) { + std::array secret{}; + secret.fill(b); + return *secp::keypair::make(secret); +} + +// A key pair from the generator: a secret make refuses (zero, or not below the group order) +// is drawn again. +secp::keypair draw(std::mt19937_64& generator) { + for (;;) { + std::array secret{}; + for (auto& octet : secret) { + octet = static_cast(generator()); + } + auto made = secp::keypair::make(secret); + if (made) { + return std::move(*made); + } + BOOST_TEST(made.error() == crypto::error::invalid_secret_key); + } +} + +// The uncompressed SEC1 form, 04 || x || y, of a key pair's public key, through libsecp256k1. +std::array uncompressed(secp::keypair const& key) { + auto const compressed = *key.public_key(); + secp256k1_pubkey parsed{}; + BOOST_TEST(secp256k1_ec_pubkey_parse(secp256k1_context_static, &parsed, compressed.data(), + compressed.size()) == 1); + std::array out{}; + std::size_t size = out.size(); + // NOLINTNEXTLINE(bugprone-signed-bitwise): libsecp256k1's macro shifts a signed constant + unsigned const flags = SECP256K1_EC_UNCOMPRESSED; + BOOST_TEST(secp256k1_ec_pubkey_serialize(secp256k1_context_static, out.data(), &size, &parsed, + flags) == 1); + return out; +} + +// The SHA-256 of the compressed form of an uncompressed point, which the point must be: what +// libsecp256k1's default ECDH hash computes. +bool hashes_to(std::span point, std::span hashed) { + secp256k1_pubkey parsed{}; + if (secp256k1_ec_pubkey_parse(secp256k1_context_static, &parsed, point.data(), point.size()) != + 1) { + return false; + } + std::array compressed{}; + std::size_t size = compressed.size(); + // NOLINTNEXTLINE(bugprone-signed-bitwise): libsecp256k1's macro shifts a signed constant + unsigned const flags = SECP256K1_EC_COMPRESSED; + secp256k1_ec_pubkey_serialize(secp256k1_context_static, compressed.data(), &size, &parsed, + flags); + boost::hash2::sha2_256 hasher; + hasher.update(compressed.data(), compressed.size()); + auto const digest = hasher.result(); + return std::ranges::equal(digest, hashed); +} + +void types() { + auto const key = from_byte(0x11); + auto const peer = *key.public_key(); + static_assert(std::is_same_v>>); + static_assert(std::is_same_v>>); + static_assert(std::is_same_v>>); +} + +// 32 pairs of key pairs from a seeded generator: both sides of each agree in every form, the +// point's x is ecdh_x, the point is on the curve, and ecdh is the SHA-256 of its compressed +// form, as version 0.1's ecdh was. +void agreement() { + std::mt19937_64 generator(0x5ec9256b1ecdULL); + for (int round = 0; round < 32; ++round) { + auto const a = draw(generator); + auto const b = draw(generator); + auto const a_public = *a.public_key(); + auto const b_public = *b.public_key(); + auto const x_a = a.ecdh_x(b_public); + auto const x_b = b.ecdh_x(a_public); + auto const point_a = a.ecdh_point(b_public); + auto const point_b = b.ecdh_point(a_public); + auto const hashed_a = a.ecdh(b_public); + auto const hashed_b = b.ecdh(a_public); + if (!BOOST_TEST(x_a && x_b && point_a && point_b && hashed_a && hashed_b)) { + continue; + } + BOOST_TEST(std::ranges::equal(x_a->bytes(), x_b->bytes())); + BOOST_TEST(std::ranges::equal(point_a->bytes(), point_b->bytes())); + BOOST_TEST(std::ranges::equal(hashed_a->bytes(), hashed_b->bytes())); + BOOST_TEST_EQ(point_a->bytes()[0], 0x04U); + BOOST_TEST(std::ranges::equal(point_a->bytes().subspan<1, 32>(), x_a->bytes())); + secp256k1_pubkey parsed{}; + BOOST_TEST(secp256k1_ec_pubkey_parse(secp256k1_context_static, &parsed, + point_a->bytes().data(), 65) == 1); + BOOST_TEST(hashes_to(point_a->bytes(), hashed_a->bytes())); + // The peer's key, uncompressed, gives the same x. + auto const x_full = a.ecdh_x(uncompressed(b)); + BOOST_TEST(x_full && std::ranges::equal(x_full->bytes(), x_a->bytes())); + } +} + +// The secrets 0x11 and 0x22 repeated 32 times, whose shared x and first public key were +// computed apart from libsecp256k1, in affine arithmetic over the curve's field. +void known_answer() { + auto const a = from_byte(0x11); + auto const b = from_byte(0x22); + auto const a_public = a.public_key(); + BOOST_TEST(a_public && + test::to_hex(*a_public) == + "034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa"); + auto const x_a = a.ecdh_x(*b.public_key()); + auto const x_b = b.ecdh_x(*a_public); + std::string const expected = "77e0510d5042e2f5e9e59c977b81eeed590cf7d20c1c51da451a8eaa9fdc45ff"; + BOOST_TEST(x_a && test::to_hex(x_a->bytes()) == expected); + BOOST_TEST(x_b && test::to_hex(x_b->bytes()) == expected); +} + +// A moved-from key pair answers invalid_state; a key of the wrong size, an x that is no point's +// and X9.62's hybrid prefixes, 06 and 07, are invalid_public_key, in every form. +// NOLINTBEGIN(bugprone-use-after-move) +void guards() { + auto key = from_byte(0x42); + secp::keypair moved = std::move(key); + auto const peer = *moved.public_key(); + BOOST_TEST(key.ecdh(peer).error() == crypto::error::invalid_state); + BOOST_TEST(key.ecdh_x(peer).error() == crypto::error::invalid_state); + BOOST_TEST(key.ecdh_point(peer).error() == crypto::error::invalid_state); + + auto const a = from_byte(0x11); + std::array off_curve{}; + off_curve[0] = 0x02; // x = 0: no point + auto first_hybrid = uncompressed(from_byte(0x22)); + auto second_hybrid = first_hybrid; + first_hybrid[0] = 0x06; + second_hybrid[0] = 0x07; + std::vector const refused{ + bytes(32), + bytes(34), + bytes(66), + bytes(off_curve.begin(), off_curve.end()), + bytes(first_hybrid.begin(), first_hybrid.end()), + bytes(second_hybrid.begin(), second_hybrid.end()), + }; + for (auto const& peer_key : refused) { + BOOST_TEST(a.ecdh(peer_key).error() == crypto::error::invalid_public_key); + BOOST_TEST(a.ecdh_x(peer_key).error() == crypto::error::invalid_public_key); + BOOST_TEST(a.ecdh_point(peer_key).error() == crypto::error::invalid_public_key); + } +} + +// NOLINTEND(bugprone-use-after-move) + +json::value load(std::string const& name) { + auto const text = test::read_file(WEBCPP_TEST_WYCHEPROOF "/testvectors_v1/" + name + ".json"); + boost::system::error_code ec; + auto value = json::parse(text, ec); + BOOST_TEST(!ec); + return value; +} + +std::string str(json::value const& v) { + return std::string(std::string_view(v.as_string())); +} + +struct counts { + int taken = 0; + int skipped = 0; + int valid = 0; + int invalid = 0; + int acceptable = 0; + int acceptable_taken = 0; + int acceptable_refused = 0; + int compressed = 0; + int uncompressed = 0; + int refused = 0; + int bad_scalar = 0; + int agreed_x = 0; + int agreed_default = 0; +}; + +// The three forms of a key pair whose secret make accepted, on one taken case: a point +// libsecp256k1 cannot parse is refused in every form; otherwise ecdh_point's x is ecdh_x and +// ecdh equals the C API's default hash. +bool forms(std::string const& label, secp::keypair const& key, bytes const& point, + std::array const& scalar, bytes const& shared, counts& c) { + secp256k1_pubkey parsed{}; + bool const parses = secp256k1_ec_pubkey_parse(secp256k1_context_static, &parsed, point.data(), + point.size()) == 1; + auto const x = key.ecdh_x(point); + auto const whole = key.ecdh_point(point); + auto const hashed = key.ecdh(point); + if (!x.has_value()) { + BOOST_TEST(x.error() == crypto::error::invalid_public_key); + BOOST_TEST(whole.has_error() && whole.error() == crypto::error::invalid_public_key); + BOOST_TEST(hashed.has_error() && hashed.error() == crypto::error::invalid_public_key); + return false; + } + BOOST_TEST(parses); + if (!BOOST_TEST(whole && hashed)) { + return true; + } + BOOST_TEST(std::ranges::equal(whole->bytes().subspan<1, 32>(), x->bytes())); + std::array reference{}; + if (BOOST_TEST(secp256k1_ecdh(secp256k1_context_static, reference.data(), &parsed, + scalar.data(), nullptr, nullptr) == 1) && + std::ranges::equal(hashed->bytes(), reference)) { + ++c.agreed_default; + } else { + fail(label + ": ecdh differs from the C API's default"); + } + if (std::ranges::equal(x->bytes(), shared)) { + ++c.agreed_x; + } + return true; +} + +// One taken case: the point as SEC1 bytes and the private key as 32 bytes. A valid case's +// shared secret is ecdh_x; an invalid one is refused, by make for its scalar or by ecdh_x for +// its point; an acceptable one is counted by what webcpp does. +void ecdh_case(std::string const& label, std::string const& verdict, bytes const& point, + std::array const& scalar, bytes const& shared, counts& c) { + ++c.taken; + auto const key = secp::keypair::make(scalar); + bool computes = false; + if (!key.has_value()) { + // A scalar libsecp256k1 refuses (zero or not below the order) gives no shared secret. + ++c.bad_scalar; + BOOST_TEST(key.error() == crypto::error::invalid_secret_key); + } else { + int const agreed = c.agreed_x; + computes = forms(label, *key, point, scalar, shared, c); + if (verdict == "valid" && c.agreed_x == agreed) { + fail(label + ": shared secret differs from ecdh_x"); + } + } + if (!computes) { + ++c.refused; + } + if (verdict == "valid") { + ++c.valid; + BOOST_TEST(computes); + } else if (verdict == "invalid") { + ++c.invalid; + if (computes) { + fail(label + ": invalid case taken"); + } + } else { + ++c.acceptable; + ++(computes ? c.acceptable_taken : c.acceptable_refused); + } +} + +void print(char const* name, counts const& c) { + std::cout << name << ": taken=" << c.taken << " skipped=" << c.skipped + << " uncompressed=" << c.uncompressed << " compressed=" << c.compressed + << " valid=" << c.valid << " invalid=" << c.invalid << " acceptable=" << c.acceptable + << " acceptable_taken=" << c.acceptable_taken + << " acceptable_refused=" << c.acceptable_refused << " refused=" << c.refused + << " bad_scalar=" << c.bad_scalar << " agreed_with_shared=" << c.agreed_x + << " agreed_with_default_hash=" << c.agreed_default << '\n'; +} + +void ecdh_asn() { + constexpr std::string_view uncompressed_prefix = + "3056301006072a8648ce3d020106052b8104000a034200"; + constexpr std::string_view compressed_prefix = "3036301006072a8648ce3d020106052b8104000a032200"; + auto const doc = load("ecdh_secp256k1_test"); + counts c; + int total = 0; + for (auto const& group : doc.at("testGroups").as_array()) { + for (auto const& t : group.at("tests").as_array()) { + ++total; + auto const label = + "ecdh asn tcId " + std::to_string(t.at("tcId").to_number()); + auto const pub = str(t.at("public")); + std::string_view tail; + if (pub.size() == 2 * ((uncompressed_prefix.size() / 2) + 65) && + std::string_view(pub).starts_with(uncompressed_prefix)) { + tail = std::string_view(pub).substr(uncompressed_prefix.size()); + ++c.uncompressed; + } else if (pub.size() == 2 * ((compressed_prefix.size() / 2) + 33) && + std::string_view(pub).starts_with(compressed_prefix)) { + tail = std::string_view(pub).substr(compressed_prefix.size()); + ++c.compressed; + } else { + ++c.skipped; + continue; + } + auto const priv = test::from_hex(str(t.at("private"))); + ecdh_case(label, str(t.at("result")), test::from_hex(tail), test::scalar32(priv), + test::from_hex(str(t.at("shared"))), c); + } + } + print("ecdh asn", c); + BOOST_TEST_EQ(total, 752); + BOOST_TEST_EQ(c.taken, 496); + BOOST_TEST_EQ(c.uncompressed, 492); + BOOST_TEST_EQ(c.compressed, 4); + BOOST_TEST_EQ(c.skipped, 256); + BOOST_TEST_EQ(c.valid, 473); + BOOST_TEST_EQ(c.invalid, 21); + BOOST_TEST_EQ(c.acceptable, 2); + BOOST_TEST_EQ(c.acceptable_taken, 1); + BOOST_TEST_EQ(c.acceptable_refused, 1); + BOOST_TEST_EQ(c.agreed_default, c.valid + c.acceptable_taken); +} + +void ecdh_jwk() { + auto const doc = load("ecdh_secp256k1_webcrypto_test"); + counts c; + int total = 0; + for (auto const& group : doc.at("testGroups").as_array()) { + for (auto const& t : group.at("tests").as_array()) { + ++total; + auto const label = + "ecdh jwk tcId " + std::to_string(t.at("tcId").to_number()); + auto const& pub = t.at("public").as_object(); + if (str(pub.at("crv")) != "P-256K") { + ++c.skipped; + continue; + } + bytes point{0x04}; + for (char const* coordinate : {"x", "y"}) { + auto const part = test::from_base64url(str(pub.at(coordinate))); + point.insert(point.end(), part.begin(), part.end()); + } + auto const d = test::from_base64url(str(t.at("private").at("d"))); + ecdh_case(label, str(t.at("result")), point, test::scalar32(d), + test::from_hex(str(t.at("shared"))), c); + } + } + print("ecdh jwk", c); + BOOST_TEST_EQ(total, 496); + BOOST_TEST_EQ(c.taken, 491); + BOOST_TEST_EQ(c.valid, 473); + BOOST_TEST_EQ(c.invalid, 18); + BOOST_TEST_EQ(c.skipped, 5); + BOOST_TEST_EQ(c.agreed_default, c.valid); +} + +} // namespace + +int main() { + types(); + agreement(); + known_answer(); + guards(); + ecdh_asn(); + ecdh_jwk(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/secp256k1_test.cpp b/test/secp256k1_test.cpp index 35c5d257..036cbdc2 100644 --- a/test/secp256k1_test.cpp +++ b/test/secp256k1_test.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -119,7 +120,7 @@ void ecdh() { auto const b = from_byte(0x22); auto const shared_a = a.ecdh(*b.public_key()); auto const shared_b = b.ecdh(*a.public_key()); - BOOST_TEST(shared_a && shared_b && *shared_a == *shared_b); + BOOST_TEST(shared_a && shared_b && std::ranges::equal(shared_a->bytes(), shared_b->bytes())); std::array off_curve{}; off_curve[0] = 0x02; // x = 0: no point BOOST_TEST(a.ecdh(off_curve).error() == crypto::error::invalid_public_key); @@ -128,7 +129,9 @@ void ecdh() { BOOST_TEST(a.ecdh(std::array{}).error() == crypto::error::invalid_public_key); // The uncompressed form agrees; the hybrid forms, 06 and 07, are refused. auto const full = uncompressed(b); - BOOST_TEST(a.ecdh(full).has_value() && *a.ecdh(full) == *shared_a); + auto const shared_full = a.ecdh(full); + BOOST_TEST(shared_full && shared_a && + std::ranges::equal(shared_full->bytes(), shared_a->bytes())); BOOST_TEST(a.ecdh(hybrid(full)).error() == crypto::error::invalid_public_key); } diff --git a/test/secp256k1_wycheproof_test.cpp b/test/secp256k1_wycheproof_test.cpp index aa0a43ad..12b363d1 100644 --- a/test/secp256k1_wycheproof_test.cpp +++ b/test/secp256k1_wycheproof_test.cpp @@ -4,32 +4,26 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// secp256k1 against Wycheproof (spec 8.1): the Bitcoin ECDSA vectors through verify_ecdsa, -// and the ECDH vectors, in ASN.1 and JWK form, through libsecp256k1's C API and webcpp's -// keypair::ecdh, which must agree with it. +// secp256k1 against Wycheproof (spec 8.1): the Bitcoin ECDSA vectors through verify_ecdsa. +// The ECDH vectors are secp256k1_ecdh_test.cpp's. #include #include #include #include "support/hex.hpp" -#include "support/secp256k1_data.hpp" +#include "support/test_data.hpp" #include #include #include #include -#include #include #include -#include #include -#include #include -#include -#include #include #include #include @@ -41,8 +35,6 @@ namespace json = boost::json; namespace { -using bytes = std::vector; - void fail(std::string const& message) { BOOST_ERROR(message.c_str()); } @@ -114,193 +106,9 @@ void ecdsa_bitcoin() { BOOST_TEST_EQ(invalid, 112); } -// The ECDH hash function of the test: the x coordinate, as Wycheproof's shared secret. -int copy_x(unsigned char* output, unsigned char const* x32, unsigned char const* /*y32*/, - void* /*data*/) { - std::memcpy(output, x32, 32); - return 1; -} - -struct counts { - int taken = 0; - int skipped = 0; - int valid = 0; - int invalid = 0; - int acceptable = 0; - int acceptable_taken = 0; - int acceptable_refused = 0; - int compressed = 0; - int uncompressed = 0; - int refused = 0; - int bad_scalar = 0; - int agreed_default = 0; -}; - -// What libsecp256k1's C API makes of a taken case: the point parsed, and the shared x. -struct c_api_result { - secp256k1_pubkey parsed{}; - bool parses = false; - bool computes = false; -}; - -// The C API on one taken case, against its verdict: a valid case agrees with the expected x, -// an invalid one is refused, an acceptable one is counted by what the C API does. -c_api_result c_api_case(std::string const& label, std::string const& verdict, bytes const& point, - std::array const& scalar, bytes const& shared, - counts& c) { - c_api_result r; - r.parses = secp256k1_ec_pubkey_parse(secp256k1_context_static, &r.parsed, point.data(), - point.size()) == 1; - std::array x{}; - r.computes = r.parses && secp256k1_ecdh(secp256k1_context_static, x.data(), &r.parsed, - scalar.data(), copy_x, nullptr) == 1; - if (!r.computes) { - ++c.refused; - } - if (verdict == "valid") { - ++c.valid; - BOOST_TEST(r.computes); - if (r.computes && !std::ranges::equal(x, shared)) { - fail(label + ": shared secret differs"); - } - } else if (verdict == "invalid") { - ++c.invalid; - if (r.computes) { - fail(label + ": invalid case taken by the C API"); - } - } else { - ++c.acceptable; - ++(r.computes ? c.acceptable_taken : c.acceptable_refused); - } - return r; -} - -// One taken case: the point as SEC1 bytes and the private key as 32 bytes, through the C API, -// then through keypair::ecdh, which refuses what the C API cannot parse and otherwise equals -// the C API's default hash. -void ecdh_case(std::string const& label, std::string const& verdict, bytes const& point, - std::array const& scalar, bytes const& shared, counts& c) { - ++c.taken; - auto const r = c_api_case(label, verdict, point, scalar, shared, c); - auto const key = secp::keypair::make(scalar); - if (!key.has_value()) { - // A scalar libsecp256k1 refuses (zero or not below the order) gives no shared secret. - ++c.bad_scalar; - BOOST_TEST(!r.computes); - return; - } - auto const mine = key->ecdh(point); - if (!r.parses) { - BOOST_TEST(mine.has_error() && mine.error() == crypto::error::invalid_public_key); - return; - } - std::array reference{}; - bool const reference_ok = secp256k1_ecdh(secp256k1_context_static, reference.data(), &r.parsed, - scalar.data(), nullptr, nullptr) == 1; - BOOST_TEST_EQ(reference_ok, r.computes); - if (!reference_ok) { - return; - } - if (mine.has_value() && *mine == reference) { - ++c.agreed_default; - } else { - fail(label + ": ecdh differs from the C API's default"); - } -} - -void print(char const* name, counts const& c) { - std::cout << name << ": taken=" << c.taken << " skipped=" << c.skipped - << " uncompressed=" << c.uncompressed << " compressed=" << c.compressed - << " valid=" << c.valid << " invalid=" << c.invalid << " acceptable=" << c.acceptable - << " acceptable_taken=" << c.acceptable_taken - << " acceptable_refused=" << c.acceptable_refused << " refused_by_c_api=" << c.refused - << " bad_scalar=" << c.bad_scalar << " agreed_with_default_hash=" << c.agreed_default - << '\n'; -} - -void ecdh_asn() { - constexpr std::string_view uncompressed_prefix = - "3056301006072a8648ce3d020106052b8104000a034200"; - constexpr std::string_view compressed_prefix = "3036301006072a8648ce3d020106052b8104000a032200"; - auto const doc = load("ecdh_secp256k1_test"); - counts c; - int total = 0; - for (auto const& group : doc.at("testGroups").as_array()) { - for (auto const& t : group.at("tests").as_array()) { - ++total; - auto const label = - "ecdh asn tcId " + std::to_string(t.at("tcId").to_number()); - auto const pub = str(t.at("public")); - std::string_view tail; - if (pub.size() == 2 * ((uncompressed_prefix.size() / 2) + 65) && - std::string_view(pub).starts_with(uncompressed_prefix)) { - tail = std::string_view(pub).substr(uncompressed_prefix.size()); - ++c.uncompressed; - } else if (pub.size() == 2 * ((compressed_prefix.size() / 2) + 33) && - std::string_view(pub).starts_with(compressed_prefix)) { - tail = std::string_view(pub).substr(compressed_prefix.size()); - ++c.compressed; - } else { - ++c.skipped; - continue; - } - auto const priv = test::from_hex(str(t.at("private"))); - ecdh_case(label, str(t.at("result")), test::from_hex(tail), test::scalar32(priv), - test::from_hex(str(t.at("shared"))), c); - } - } - print("ecdh asn", c); - BOOST_TEST_EQ(total, 752); - BOOST_TEST_EQ(c.taken, 496); - BOOST_TEST_EQ(c.uncompressed, 492); - BOOST_TEST_EQ(c.compressed, 4); - BOOST_TEST_EQ(c.skipped, 256); - BOOST_TEST_EQ(c.valid, 473); - BOOST_TEST_EQ(c.invalid, 21); - BOOST_TEST_EQ(c.acceptable, 2); - BOOST_TEST_EQ(c.acceptable_taken, 1); - BOOST_TEST_EQ(c.acceptable_refused, 1); - BOOST_TEST_EQ(c.agreed_default, c.valid + c.acceptable_taken); -} - -void ecdh_jwk() { - auto const doc = load("ecdh_secp256k1_webcrypto_test"); - counts c; - int total = 0; - for (auto const& group : doc.at("testGroups").as_array()) { - for (auto const& t : group.at("tests").as_array()) { - ++total; - auto const label = - "ecdh jwk tcId " + std::to_string(t.at("tcId").to_number()); - auto const& pub = t.at("public").as_object(); - if (str(pub.at("crv")) != "P-256K") { - ++c.skipped; - continue; - } - bytes point{0x04}; - for (char const* coordinate : {"x", "y"}) { - auto const part = test::from_base64url(str(pub.at(coordinate))); - point.insert(point.end(), part.begin(), part.end()); - } - auto const d = test::from_base64url(str(t.at("private").at("d"))); - ecdh_case(label, str(t.at("result")), point, test::scalar32(d), - test::from_hex(str(t.at("shared"))), c); - } - } - print("ecdh jwk", c); - BOOST_TEST_EQ(total, 496); - BOOST_TEST_EQ(c.taken, 491); - BOOST_TEST_EQ(c.valid, 473); - BOOST_TEST_EQ(c.invalid, 18); - BOOST_TEST_EQ(c.skipped, 5); - BOOST_TEST_EQ(c.agreed_default, c.valid); -} - } // namespace int main() { ecdsa_bitcoin(); - ecdh_asn(); - ecdh_jwk(); return webcpp::test::exit_status(boost::report_errors()); } diff --git a/test/support/secp256k1_checks.hpp b/test/support/secp256k1_checks.hpp index f46c4967..8f3dc61c 100644 --- a/test/support/secp256k1_checks.hpp +++ b/test/support/secp256k1_checks.hpp @@ -40,7 +40,10 @@ inline void expect_empty_keypair(webcpp::crypto::curves::secp256k1::keypair& key BOOST_TEST(key.sign_ecdsa(message).error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.tweak_xonly(tweak).error() == webcpp::crypto::error::invalid_state); if (BOOST_TEST(live.has_value())) { - BOOST_TEST(key.ecdh(*live->public_key()).error() == webcpp::crypto::error::invalid_state); + auto const peer = *live->public_key(); + BOOST_TEST(key.ecdh(peer).error() == webcpp::crypto::error::invalid_state); + BOOST_TEST(key.ecdh_x(peer).error() == webcpp::crypto::error::invalid_state); + BOOST_TEST(key.ecdh_point(peer).error() == webcpp::crypto::error::invalid_state); } } From 1e447a9a1603522bb54d6c9393968b3b9c7722b1 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 12:51:48 -0300 Subject: [PATCH 02/54] crypto: ECDH's page cites SEC 1 and Wycheproof as sources, its pitfall says what a raw x costs; the session example wipes its shared secrets once the ciphers are made Task 2.1's review, Minors 2 to 7: crypto.json gains the sources sec1 and wycheproof; the uncompressed encoding is cited to SEC 1, not SEC 2; the raw x coordinate's pitfall cites SEC 1 for the points' x and names the cost; the ECDH test returns when libsecp256k1 refuses a point webcpp took, instead of reaching its illegal callback; ecdh_session scopes its shared secrets; the memory page's edited line is rewrapped. --- doc/memory.adoc | 4 ++-- doc/secp256k1.adoc | 21 +++++++++++++-------- doc/tables/crypto.json | 3 ++- example/ecdh_session.cpp | 33 +++++++++++++++++++++------------ test/secp256k1_ecdh_test.cpp | 7 ++++++- 5 files changed, 44 insertions(+), 24 deletions(-) diff --git a/doc/memory.adoc b/doc/memory.adoc index 6942a853..3951c365 100644 --- a/doc/memory.adoc +++ b/doc/memory.adoc @@ -15,8 +15,8 @@ key pair. Every buffer is the caller's. * *Nothing allocates per message, on any backend:* `seal`, `open`, `begin_seal`, `update`, `result`, `encrypt`, `decrypt`, `fill`, the signatures, -`ecdh`, `ecdh_x`, `ecdh_point` and the verifications. The counting tests of `test/` prove it, every -`operator new` and the C library's allocator counted. +`ecdh`, `ecdh_x`, `ecdh_point` and the verifications. The counting tests of +`test/` prove it, every `operator new` and the C library's allocator counted. * *BearSSL and ctaes allocate nothing,* `make` included: the key schedule lives inside the object. * *OpenSSL's `make` allocates its cipher context through OpenSSL's own diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index 413ce948..96139d68 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -109,11 +109,12 @@ form of the chat session of <>. * `ecdh_x`: the point's x coordinate, 32 bytes, unhashed. Nostr's encrypted messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[NIP-44]) and Wycheproof's ECDH test vectors -(link:https://github.com/C2SP/wycheproof[Wycheproof]) take this form; the -protocol then hashes it its own way. -* `ecdh_point`: the point itself, SEC1 uncompressed (0x04, x, y), 65 bytes, for -a protocol that hashes both coordinates -(link:https://www.secg.org/sec2-v2.pdf[SEC 2]). +(link:https://github.com/C2SP/wycheproof[Project Wycheproof, test vectors for +cryptographic libraries]) take this form; the protocol then hashes it its own +way. +* `ecdh_point`: the point itself, 65 bytes in SEC1's uncompressed encoding +(0x04, x, y; link:https://www.secg.org/sec1-v2.pdf[SEC 1, sections 2.3.3 and +2.3.4]): both coordinates, of which the other two forms keep x alone. Each is returned as a `secret`, which wipes its bytes when it is destroyed or moved from: a program reads it with `bytes()` and makes no copy of its own @@ -142,9 +143,13 @@ include::{examples}/ecdh_x_coordinate.expected[] * The raw x coordinate is not a key: a Diffie-Hellman value is not uniformly random (link:https://www.rfc-editor.org/rfc/rfc5869#section-3.3[RFC 5869, -section 3.3]), and only about half of all 32-byte values are the x of a point. -A protocol's key derivation function (HKDF in NIP-44) turns it into keys; used -directly as an AES key it is weaker than it looks. +section 3.3]). It is always below the field's prime and always the x of a +point, which not every 32-byte value is +(link:https://www.secg.org/sec1-v2.pdf[SEC 1, sections 2.3.3 and 2.3.4]), so +its 256 bits hold less than 256 bits of entropy. A protocol's key derivation +function (HKDF in NIP-44) turns it into keys. Used directly as an AES key, it +is the same key in every protocol that uses the same two key pairs that way: +a key that leaks from one leaks from all of them. * Two programs must agree on the form. One that takes `ecdh` and one that takes `ecdh_x` derive different keys from the same key pairs, and fail silently: every message is refused as forged, with nothing pointing at the diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index b106dc66..abd1ed4f 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -104,7 +104,8 @@ "xchacha-draft": ["draft-irtf-cfrg-xchacha, XChaCha20-Poly1305", "https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha"], "libsodium-secretstream": ["libsodium's documentation, encrypted streams (secretstream, on XChaCha20-Poly1305)", "https://doc.libsodium.org/secret-key_cryptography/secretstream"], "rfc7748-kdf": ["RFC 7748, section 6.1: a KDF over the shared secret and both public keys", "https://www.rfc-editor.org/rfc/rfc7748#section-6.1"], - "libsodium-doc-licence": ["libsodium's documentation, jedisct1/libsodium-doc at 6d1ea27, ISC", "https://github.com/jedisct1/libsodium-doc/tree/6d1ea27b79b853b2a04f09ae9e1a8231c90e3b56"] + "libsodium-doc-licence": ["libsodium's documentation, jedisct1/libsodium-doc at 6d1ea27, ISC", "https://github.com/jedisct1/libsodium-doc/tree/6d1ea27b79b853b2a04f09ae9e1a8231c90e3b56"], + "sec1": ["SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings", "https://www.secg.org/sec1-v2.pdf"] }, "backends": { "bearssl": { diff --git a/example/ecdh_session.cpp b/example/ecdh_session.cpp index 5864a5db..83c9565d 100644 --- a/example/ecdh_session.cpp +++ b/example/ecdh_session.cpp @@ -23,9 +23,11 @@ #include #include #include +#include #include #include #include +#include namespace crypto = webcpp::crypto; namespace secp256k1 = webcpp::crypto::curves::secp256k1; @@ -169,21 +171,28 @@ int main() { if (!alice_public || !bob_public) { return 1; } - auto const alice_shared = alice->ecdh(*bob_public); - auto const bob_shared = bob->ecdh(*alice_public); - if (!alice_shared || !bob_shared || - !crypto::equal(alice_shared->bytes(), bob_shared->bytes())) { - return 1; + // The shared secrets live only in this block: each is a secret<32>, which wipes itself at + // the block's end, as soon as the session ciphers are made from it. + std::optional alice_cipher; + std::optional bob_cipher; + { + auto const alice_shared = alice->ecdh(*bob_public); + auto const bob_shared = bob->ecdh(*alice_public); + if (!alice_shared || !bob_shared || + !crypto::equal(alice_shared->bytes(), bob_shared->bytes())) { + return 1; + } + std::printf("shared secrets match\n"); + auto alice_made = session_cipher(*alice_shared); + auto bob_made = session_cipher(*bob_shared); + if (!alice_made || !bob_made) { + return 1; + } + alice_cipher.emplace(std::move(*alice_made)); + bob_cipher.emplace(std::move(*bob_made)); } - std::printf("shared secrets match\n"); // end::agree[] - // The shared secrets are secret<32>, which wipe themselves when they go out of scope. - auto alice_cipher = session_cipher(*alice_shared); - auto bob_cipher = session_cipher(*bob_shared); - if (!alice_cipher || !bob_cipher) { - return 1; - } std::array iv{}; if (!crypto::random_device().fill(iv)) { return 1; diff --git a/test/secp256k1_ecdh_test.cpp b/test/secp256k1_ecdh_test.cpp index 58851fdf..8eb4988e 100644 --- a/test/secp256k1_ecdh_test.cpp +++ b/test/secp256k1_ecdh_test.cpp @@ -250,7 +250,12 @@ bool forms(std::string const& label, secp::keypair const& key, bytes const& poin BOOST_TEST(hashed.has_error() && hashed.error() == crypto::error::invalid_public_key); return false; } - BOOST_TEST(parses); + // A point webcpp took and libsecp256k1's parser refuses is reported here: the C call below + // would reach libsecp256k1's illegal callback with the unparsed point, and abort. + if (!BOOST_TEST(parses)) { + fail(label + ": a point libsecp256k1 refuses was taken"); + return true; + } if (!BOOST_TEST(whole && hashed)) { return true; } From a89b2cde2413f6a18731abaee8233f3be5ecfe92 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 12:54:53 -0300 Subject: [PATCH 03/54] crypto: the ECDH example's Jam comment wraps at 80 columns, as the lint's jam-comments rule asks --- example/Jamfile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/example/Jamfile b/example/Jamfile index b817fc26..7df164e7 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -49,7 +49,8 @@ webcpp.example signed_update.cpp : /third_party//secp256k1 ; # ECDH, HKDF-SHA-256 and AES-256-GCM between two peers. webcpp.example ecdh_session.cpp : /third_party//secp256k1 /webcpp/crypto//gcm-default ; -# ECDH's raw x coordinate, and the NIP-44 conversation key a domain library derives from it. +# ECDH's raw x coordinate, and the NIP-44 conversation key a domain library +# derives from it. webcpp.example ecdh_x_coordinate.cpp : /third_party//secp256k1 ; # A wallet's key pair, its secret sealed at rest and restored. From 730f3fc3323105ae2dd6d57415d08fb1c387d3c9 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 14:02:17 -0300 Subject: [PATCH 04/54] crypto: secp256k1's recoverable signatures, hedged ECDSA and the parsed public key in both forms --- doc/changelog.adoc | 2 +- doc/generated/backends-keypair.adoc | 2 +- doc/generated/backends-public_key.adoc | 30 ++ doc/generated/backends-recovery.adoc | 30 ++ doc/generated/matrix.adoc | 24 +- doc/generated/namespace-curves.adoc | 8 +- doc/generated/use-cases.adoc | 7 + doc/llms.txt | 11 +- doc/memory.adoc | 5 +- doc/secp256k1.adoc | 127 +++++- doc/tables/crypto.json | 36 +- doc/testing.adoc | 13 +- example/Jamfile | 4 + example/recover_signer.cpp | 107 +++++ example/recover_signer.expected | 2 + include/webcpp/crypto/backends/secp256k1.hpp | 5 +- include/webcpp/crypto/curves/secp256k1.hpp | 400 ++++++++++++++++++- test/Jamfile | 8 +- test/secp256k1_allocation_test.cpp | 20 +- test/secp256k1_c_api_test.cpp | 30 +- test/secp256k1_keys_test.cpp | 255 ++++++++++++ test/secp256k1_recovery_test.cpp | 276 +++++++++++++ test/support/secp256k1_checks.hpp | 3 + 23 files changed, 1342 insertions(+), 63 deletions(-) create mode 100644 doc/generated/backends-public_key.adoc create mode 100644 doc/generated/backends-recovery.adoc create mode 100644 example/recover_signer.cpp create mode 100644 example/recover_signer.expected create mode 100644 test/secp256k1_keys_test.cpp create mode 100644 test/secp256k1_recovery_test.cpp diff --git a/doc/changelog.adoc b/doc/changelog.adoc index a1fe634c..68b0593e 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -20,7 +20,7 @@ of every version are on webcpp's index page. * Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default, one default per family and target, and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). -* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH in three forms (ecdh, ecdh_x, ecdh_point) returned as self-wiping secrets, strict DER, low-S and the x-only tweak. +* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, hedged and recoverable, recover, public_key in both forms, ECDH in three forms as self-wiping secrets, strict DER, low-S, x-only tweaks. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. * Added ciphers::secretbox and secretbox_xchacha20poly1305, without additional data, hybrid::box, box_xchacha20poly1305 and sealed_box (failed seals and opens zeroing data), and curves::x25519::kx_keypair (crypto_kx) on libsodium, refusing peer keys of small order. diff --git a/doc/generated/backends-keypair.adoc b/doc/generated/backends-keypair.adoc index da9cd9b3..ee9a4a77 100644 --- a/doc/generated/backends-keypair.adoc +++ b/doc/generated/backends-keypair.adoc @@ -16,7 +16,7 @@ The backends of `+curves::secp256k1::keypair+`, from the test programs that run |libsecp256k1 |`+/third_party//secp256k1+` |`++` -|native, wasip2, wasip3, emscripten (tested by `+secp256k1+`, `+secp256k1_bip340+`, `+secp256k1_xonly_tweak+`, `+secp256k1_ecdh+`) +|native, wasip2, wasip3, emscripten (tested by `+secp256k1+`, `+secp256k1_bip340+`, `+secp256k1_xonly_tweak+`, `+secp256k1_ecdh+`, `+secp256k1_recovery+`) |=== A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: diff --git a/doc/generated/backends-public_key.adoc b/doc/generated/backends-public_key.adoc new file mode 100644 index 00000000..f69b6ece --- /dev/null +++ b/doc/generated/backends-public_key.adoc @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+curves::secp256k1::public_key+`, `+parse_public_key+`, `+serialize_public_key+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsecp256k1 +|`+/third_party//secp256k1+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+secp256k1_keys+`) +|=== + +A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsecp256k1 +|=== diff --git a/doc/generated/backends-recovery.adoc b/doc/generated/backends-recovery.adoc new file mode 100644 index 00000000..8bc5ba1e --- /dev/null +++ b/doc/generated/backends-recovery.adoc @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+curves::secp256k1::recover+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsecp256k1 +|`+/third_party//secp256k1+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+secp256k1_recovery+`) +|=== + +A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsecp256k1 +|=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 621ac0d2..8f21420d 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -59,7 +59,7 @@ |`+curves::secp256k1::keypair+` |libsecp256k1 |native, wasip2, wasip3, emscripten -|`+secp256k1+`, `+secp256k1_bip340+`, `+secp256k1_xonly_tweak+`, `+secp256k1_ecdh+` +|`+secp256k1+`, `+secp256k1_bip340+`, `+secp256k1_xonly_tweak+`, `+secp256k1_ecdh+`, `+secp256k1_recovery+` |`+curves::secp256k1::verify_schnorr+`, `+verify_ecdsa+` |libsecp256k1 @@ -190,6 +190,16 @@ |libsodium |native, wasip2, wasip3, emscripten |`+box_sodium+`, `+allocation_sodium+` + +|`+curves::secp256k1::recover+` +|libsecp256k1 +|native, wasip2, wasip3, emscripten +|`+secp256k1_recovery+` + +|`+curves::secp256k1::public_key+`, `+parse_public_key+`, `+serialize_public_key+` +|libsecp256k1 +|native, wasip2, wasip3, emscripten +|`+secp256k1_keys+` |=== The same, by target: the backends each operation runs on. @@ -365,4 +375,16 @@ The same, by target: the backends each operation runs on. |libsodium |libsodium |libsodium + +|`+curves::secp256k1::recover+` +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 + +|`+curves::secp256k1::public_key+`, `+parse_public_key+`, `+serialize_public_key+` +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 |=== diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index 2dc4d342..50190144 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -12,7 +12,7 @@ |Curve |`secp256k1` |`ed25519` |`x25519` |What it does -|BIP 340 Schnorr and ECDSA signatures, ECDH in three forms, the x-only tweak +|BIP 340 Schnorr and ECDSA signatures, hedged and recoverable ECDSA, the recovery of a signer's key, ECDH in three forms, public keys in both forms, the x-only tweak |Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair |Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction @@ -22,12 +22,12 @@ |about 128 bits (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)]) |Key sizes -|secret 32 bytes; public 33 bytes compressed, 32 bytes x-only +|secret 32 bytes; public 33 bytes compressed, 65 bytes uncompressed (link:https://www.secg.org/sec1-v2.pdf[SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings]), 32 bytes x-only |secret 32 bytes (the seed); public 32 bytes |secret 32 bytes; public 32 bytes |Signature sizes -|64 bytes; ECDSA in DER up to 72 +|64 bytes; 65 bytes recoverable; ECDSA in DER up to 72 |64 bytes |none: no signatures @@ -57,7 +57,7 @@ |yes: X25519 (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) |Choose it for compatibility with -|Bitcoin's keys and signatures; Nostr's event signatures (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]). Not in this version: Ethereum's recoverable signatures and its addresses from the uncompressed key; BIP 32's derivation (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32, hierarchical deterministic wallets]) +|Bitcoin's keys and signatures; Nostr's event signatures (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]); Ethereum's recoverable signatures and uncompressed keys (link:https://ethereum.github.io/yellowpaper/paper.pdf[The Ethereum yellow paper, appendix F: ECDSA on secp256k1]), the address hashing being a domain library's. Not in this version: BIP 32's derivation (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32, hierarchical deterministic wallets]) |SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's |TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` (link:https://doc.libsodium.org/key_exchange[libsodium's documentation, key exchange]). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested (link:https://github.com/C2SP/wycheproof[Project Wycheproof, test vectors for cryptographic libraries]) |=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 7f109fab..24a9d168 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -85,6 +85,13 @@ `+/third_party//secp256k1+` |<> +|Find who signed a message or a transaction without being sent their key (Ethereum's signatures) +|In `+curves::secp256k1+`: `+keypair::sign_recoverable+`, `+recover+` +|libsecp256k1 +|`+/webcpp/crypto//crypto+` + +`+/third_party//secp256k1+` +|<> + |Make and keep a wallet's key |In `+curves::secp256k1+`: `+keypair::make+`, `+xonly_public_key+`, `+public_key+`; `+aes256_gcm+` at rest |libsecp256k1, and AES-GCM's default diff --git a/doc/llms.txt b/doc/llms.txt index d4547678..39eae8b8 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -62,12 +62,14 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp ## webcpp::crypto::curves -- [curves::secp256k1::keypair](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): A secp256k1 key pair: BIP 340 Schnorr and ECDSA signatures, ECDH in three forms and the x-only tweak. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. +- [curves::secp256k1::keypair](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1): A secp256k1 key pair: BIP 340 Schnorr and ECDSA signatures, hedged and recoverable too, ECDH in three forms and the x-only tweak. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. - make: Makes a key pair from a secret key. - xonly_public_key: The BIP340 x-only public key. - public_key: The public key, SEC1 compressed. + - public_key_uncompressed: The public key, SEC1 uncompressed. - sign_schnorr: A BIP340 signature of a message of any length. - sign_ecdsa: An ECDSA signature of a 32-byte hash: RFC 6979's nonce, low-S, compact form. + - sign_recoverable: An ECDSA signature of a 32-byte hash with its recovery id: RFC 6979's nonce, low-S, as `sign_ecdsa` (the same r and s), then the id from which `recover` finds the key. - ecdh: The SHA-256 of the compressed shared point with a peer's public key, libsecp256k1's default. - ecdh_x: The shared point's x coordinate, unhashed: what Wycheproof's ECDH vectors, Nostr's NIP-44 and other protocols that hash it themselves take. - ecdh_point: The shared point itself, SEC1 uncompressed (0x04, x, y). @@ -116,6 +118,11 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - public_key: The public key, which the peer needs. - client_session_keys: The client's keys, from the server's public key, `crypto_kx_client_session_keys`. - server_session_keys: The server's keys, from the client's public key, `crypto_kx_server_session_keys`. +- [curves::secp256k1::recover](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-recovery): The public key that made a recoverable ECDSA signature of a hash. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: find who signed a message or a transaction without being sent their key (Ethereum's signatures). + - recover: The public key that made a recoverable signature of a 32-byte hash (`secp256k1_ecdsa_recover`), as Ethereum identifies a transaction's signer. +- [curves::secp256k1::public_key, parse_public_key, serialize_public_key](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-keys): A parsed public key, read from and written to its compressed or uncompressed form. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. + - parse_public_key: Parses a public key: 33 bytes with prefix 02 or 03, or 65 with prefix 04 (X9.62's hybrid prefixes 06 and 07 are refused, as everywhere in crypto). + - serialize_public_key: Serialises a public key in `Form`. ## webcpp::crypto::hybrid @@ -198,6 +205,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Check a software update or a licence file](https://webcpporg.github.io/libs/crypto/#crypto-everyday-update): `keypair::sign_ecdsa`, `verify_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/signed_update.cpp. - [Agree on a key with a peer through a relay that sees everything](https://webcpporg.github.io/libs/crypto/#crypto-p2p-session): `keypair::ecdh` (SHA-256 of the shared point), then HKDF on Boost.Hash2 and `aes256_gcm` (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/ecdh_session.cpp. - [Derive a Nostr direct message's conversation key (NIP-44; the format is a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ecdh): `keypair::ecdh_x`, then HKDF on Boost.Hash2 (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdh_x_coordinate.cpp. +- [Find who signed a message or a transaction without being sent their key (Ethereum's signatures)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-recovery): `keypair::sign_recoverable`, `recover` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/recover_signer.cpp. - [Make and keep a wallet's key](https://webcpporg.github.io/libs/crypto/#crypto-wallets-key): `keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/wallet_key.cpp. - [Sign a Bitcoin SegWit v0 input (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-der): `sign_ecdsa`, `to_der`, `normalize_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdsa_der.cpp. - [Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly`, `keypair::tweak_xonly` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/taproot_tweak.cpp. @@ -233,6 +241,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/kx_session.cpp: A chat app's client and server, each with a crypto_kx key pair made from libsodium's kx test's seeds, exchange public keys and compute their session keys; the client seals a message with its transmit key and the server opens it with its receive key, on ChaCha20-Poly1305; a peer key of low order is refused. Prints the public keys and the client's session keys in hex. - example/openssl_memory.cpp: Sends every allocation of OpenSSL's to the program's own memory resource, natively, then seals and opens one block with AES-256-GCM on OpenSSL, on a worker thread as an audio engine's or a server's would. Built with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, /webcpp/crypto//openssl and threads (example/Jamfile). - example/order_reference.cpp: Turns a sequential order id into an opaque 16-byte reference with the raw AES block cipher, and back. Customers then cannot guess other orders' numbers. This is NOT authenticated encryption: a forged reference still decrypts, to garbage, so the program checks the padding. +- example/recover_signer.cpp: Finds who signed a message without being sent their key, as Ethereum finds a transaction's signer: a wallet signs a message's hash with a recoverable signature, and a reader that holds no key recovers the signer's public key from the signature and the hash, then compares it with the key the wallet published. Recovery always finds some key, so the comparison is the check: a changed message recovers another key. - example/reset_token.cpp: Draws a 32-byte password-reset token and a six-digit one-time code from the system's random generator. Tokens that can be guessed or repeated let an attacker take over accounts, so both come from random_device, never from rand() or the clock. - example/schnorr_sign.cpp: Signs BIP340's first test vector with secp256k1 and verifies it, then tweaks the key pair by a 32-byte tweak, as a domain library derives one, and signs and verifies under the tweaked key. Prints each key and signature in hex. - example/sealed_records.cpp: Seals data in pieces two ways: one message in chunks with the incremental seal, and a stream as separate records, each bound to its position and to whether it is the last. The number in the additional data stops records from being reordered or replayed at another position, and the last-record flag stops a stream from being cut short without being noticed. Each stream has a key of its own, drawn when the stream starts: the counter IVs 0, 1, 2 of one stream are safe only because no other stream seals under its key. diff --git a/doc/memory.adoc b/doc/memory.adoc index 3951c365..7e62d784 100644 --- a/doc/memory.adoc +++ b/doc/memory.adoc @@ -14,8 +14,9 @@ from the `std::pmr::memory_resource` the program passes, which must outlive the key pair. Every buffer is the caller's. * *Nothing allocates per message, on any backend:* `seal`, `open`, -`begin_seal`, `update`, `result`, `encrypt`, `decrypt`, `fill`, the signatures, -`ecdh`, `ecdh_x`, `ecdh_point` and the verifications. The counting tests of +`begin_seal`, `update`, `result`, `encrypt`, `decrypt`, `fill`, the signatures +(hedged and recoverable too), `ecdh`, `ecdh_x`, `ecdh_point`, the verifications, +`recover`, `parse_public_key` and `serialize_public_key`. The counting tests of `test/` prove it, every `operator new` and the C library's allocator counted. * *BearSSL and ctaes allocate nothing,* `make` included: the key schedule lives inside the object. diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index 96139d68..c798729d 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -24,7 +24,9 @@ link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow paper]). Each signature's nonce is RFC 6979's, derived from the key and the hash, so that no weak generator can leak the key (link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979]), and each is in low-S -form; +form. A signature is also made hedged, with the caller's fresh randomness +mixed into the nonce, or recoverable, with the id from which a reader finds +the signer's key (<>); * *ECDH*, a shared secret: `ecdh` gives libsecp256k1's hashed form, the SHA-256 of the shared point in its 33-byte compressed encoding, one of three forms (<>). It interoperates only with peers that hash @@ -36,14 +38,17 @@ A `keypair` is made from a 32-byte secret key with `make(secret)`, which allocates its signing context in the `std::pmr::memory_resource` it is given, and randomises it from `random_device`; crypto's own code allocates nothing else (<>). A key pair gives its x-only public key -(`xonly_public_key`) and its compressed one (`public_key`), signs -(`sign_schnorr`, `sign_ecdsa`), derives an ECDH secret (`ecdh`, `ecdh_x`, -`ecdh_point`), and is tweaked -in place (`tweak_xonly`). `verify_schnorr` and `verify_ecdsa` check signatures -with a public key alone; `to_der`, `from_der` (strict DER) and -`normalize_ecdsa` convert ECDSA's DER and low-S forms; and `tweak_xonly` tweaks -an x-only public key. Every function reads libsecp256k1's canary, so that a -program linked with another build of the library does not link. +(`xonly_public_key`), its compressed and uncompressed ones (`public_key`, +`public_key_uncompressed`), signs (`sign_schnorr`, `sign_ecdsa`, +`sign_recoverable`), derives an ECDH secret (`ecdh`, `ecdh_x`, `ecdh_point`), +and is tweaked in place (`tweak_xonly`). `verify_schnorr` and `verify_ecdsa` +check signatures with a public key alone, and `recover` finds the key from a +recoverable signature; `parse_public_key` and `serialize_public_key` read and +write a `public_key` (<>); `to_der`, `from_der` (strict +DER) and `normalize_ecdsa` convert ECDSA's DER and low-S forms; and +`tweak_xonly` tweaks an x-only public key. Every function reads libsecp256k1's +canary, so that a program linked with another build of the library does not +link. include::generated/backends-keypair.adoc[] @@ -157,3 +162,107 @@ cause. Read the protocol's specification for the form it names. * Never use one shared secret as two keys, one per direction or one for encryption and one for authentication: derive one key per purpose with the KDF, each with its own label (<>). + +[#crypto-secp256k1-keys] +==== Public keys and their two forms + +A public key arrives as bytes: from a peer, from a file, from a transaction. A +program that checks many signatures with one key, or compares keys, parses it +once into a `public_key`, a point of the curve that the type guarantees, and +uses that from then on. The check matters: a peer's key that is not on the +curve is how invalid-curve attacks begin, in which a key off the curve, +combined with a secret key, leaks that secret bit by bit, which is why the +holder of a long-lived secret key validates the other side's public key +(link:https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman[Wikipedia]). +`parse_public_key` makes the only `public_key` there is, so a program that +holds one holds a valid point. + +A point is written in one of two forms +(link:https://www.secg.org/sec1-v2.pdf[SEC 1, sections 2.3.3 and 2.3.4]): + +* *compressed*, 33 bytes: 02 or 03 by the parity of y, then x. Bitcoin writes +keys this way, and its SegWit outputs take no other form by default +(link:https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki[BIP 143]); +* *uncompressed*, 65 bytes: 04, x, y. Ethereum's keys are x and y, 64 bytes, +the uncompressed form without its prefix +(link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow paper]). + +`serialize_public_key` writes either (`point_form::compressed`, the default, +or `point_form::uncompressed`); a key pair gives its own key in both forms, +`public_key` and `public_key_uncompressed`. Two `public_key` values compare +with `==`, and order with `+<=>+` as their compressed encodings do, the order +MuSig2's key sorting uses +(link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327]). A `public_key` holds nothing secret and is copied +freely. + +include::generated/backends-public_key.adoc[] + +*Pitfalls.* + +* X9.62's hybrid form, prefix 06 or 07 then x and y, is refused with +`invalid_public_key`, though libsecp256k1 reads it: SEC 1 defines only the two +forms above and refuses every other prefix +(link:https://www.secg.org/sec1-v2.pdf[SEC 1, section 2.3.4]), so a key webcpp +takes is one every SEC 1 parser takes, and one key has one encoding of each +form. +* A key compared as bytes, rather than parsed, differs between its two forms: +the same key compressed and uncompressed are different bytes. Parse both and +compare the `public_key` values. +* Ethereum's 64-byte key is the uncompressed form without its 04: add the +prefix before `parse_public_key`, and drop it after `serialize_public_key`. + +[#crypto-secp256k1-recovery] +==== Recoverable signatures + +Ethereum names an account by the hash of its public key, and a transaction +carries no key: only the signature, from which a node recovers the key that +made it +(link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow +paper, appendix F]). An ECDSA signature fits up to four keys, and the +recovery id, 0 to 3, names the one that made it +(link:https://www.secg.org/sec1-v2.pdf[SEC 1, section 4.1.6]). `sign_recoverable` +writes 65 bytes, r, s and the id, with the same r and s as `sign_ecdsa`, and +`recover` returns the `public_key` from those 65 bytes and the hash. It +refuses with `invalid_signature` an id above 3, an r or an s not below the +group order, and a signature from which no key is recovered. + +include::generated/backends-recovery.adoc[] + +*Example.* A wallet signs a message's hash; a reader that holds no key of the +wallet's recovers the signer's key and compares it with the key the wallet +published; a changed message recovers a different key: + +[source,cpp] +---- +include::{examples}/recover_signer.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/recover_signer.expected[] +---- + +`sign_ecdsa` also has a hedged form, which takes 32 more bytes, drawn from +`random_device` and new for each signature, and mixes them into RFC 6979's +nonce, as the RFC's variant with additional data allows +(link:https://www.rfc-editor.org/rfc/rfc6979#section-3.6[RFC 6979, section +3.6]) and libsecp256k1's `ndata` takes +(link:https://github.com/bitcoin-core/secp256k1#readme[libsecp256k1]). The +signature verifies as any other. + +*Pitfalls.* + +* Recovery always yields some key for almost every signature and hash, a +forged one included: a program that trusts the recovered key alone accepts +anything. Compare it with the key expected, as the example does, or with the +account the key's hash must name. +* Ethereum's `v` is the recovery id plus 27, or plus an offset of the chain's +(link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow +paper, appendix F]): passing `v` as the id makes `recover` refuse it. That +encoding, and the message hash Ethereum signs, are a domain library's. +* The hedged form gives a different signature each time, so a test that +compares signatures with fixed bytes uses the unhedged form. Use the hedged +form where the signer runs on hardware an attacker can fault or observe: the +nonce then no longer depends on the key and the hash alone, so two signings of +one hash do not repeat the same computation. Never reuse the 32 bytes: fixed +extra data leaves the signature deterministic, as plain RFC 6979. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index abd1ed4f..0f4fc2a4 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -105,7 +105,8 @@ "libsodium-secretstream": ["libsodium's documentation, encrypted streams (secretstream, on XChaCha20-Poly1305)", "https://doc.libsodium.org/secret-key_cryptography/secretstream"], "rfc7748-kdf": ["RFC 7748, section 6.1: a KDF over the shared secret and both public keys", "https://www.rfc-editor.org/rfc/rfc7748#section-6.1"], "libsodium-doc-licence": ["libsodium's documentation, jedisct1/libsodium-doc at 6d1ea27, ISC", "https://github.com/jedisct1/libsodium-doc/tree/6d1ea27b79b853b2a04f09ae9e1a8231c90e3b56"], - "sec1": ["SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings", "https://www.secg.org/sec1-v2.pdf"] + "sec1": ["SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings", "https://www.secg.org/sec1-v2.pdf"], + "bip327": ["BIP 327, MuSig2, its key sorting", "https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki"] }, "backends": { "bearssl": { @@ -274,13 +275,13 @@ { "id": "keypair", "family": "secp256k1", - "functions": ["make", "xonly_public_key", "public_key", "sign_schnorr", "sign_ecdsa", "ecdh", "ecdh_x", "ecdh_point", "tweak_xonly"], + "functions": ["make", "xonly_public_key", "public_key", "public_key_uncompressed", "sign_schnorr", "sign_ecdsa", "sign_recoverable", "ecdh", "ecdh_x", "ecdh_point", "tweak_xonly"], "namespace": "curves", "api": "curves::secp256k1::keypair", "header": "", - "what": "A secp256k1 key pair: BIP 340 Schnorr and ECDSA signatures, ECDH in three forms and the x-only tweak.", + "what": "A secp256k1 key pair: BIP 340 Schnorr and ECDSA signatures, hedged and recoverable too, ECDH in three forms and the x-only tweak.", "section": "crypto-secp256k1", - "backends": {"secp256k1": {"tests": ["secp256k1", "secp256k1_bip340", "secp256k1_xonly_tweak", "secp256k1_ecdh"]}} + "backends": {"secp256k1": {"tests": ["secp256k1", "secp256k1_bip340", "secp256k1_xonly_tweak", "secp256k1_ecdh", "secp256k1_recovery"]}} }, { "id": "verify", @@ -550,6 +551,30 @@ "section": "crypto-sealed-box", "default": "`sealed_box` names the default backend.", "backends": {"sodium": {"tests": ["box_sodium", "allocation_sodium"]}} + }, + { + "id": "recovery", + "family": "secp256k1", + "free": true, + "functions": ["recover"], + "namespace": "curves", + "api": "curves::secp256k1::recover", + "header": "", + "what": "The public key that made a recoverable ECDSA signature of a hash.", + "section": "crypto-secp256k1-recovery", + "backends": {"secp256k1": {"tests": ["secp256k1_recovery"]}} + }, + { + "id": "public_key", + "family": "secp256k1", + "free": true, + "functions": ["parse_public_key", "serialize_public_key"], + "namespace": "curves", + "api": "curves::secp256k1::public_key, parse_public_key, serialize_public_key", + "header": "", + "what": "A parsed public key, read from and written to its compressed or uncompressed form.", + "section": "crypto-secp256k1-keys", + "backends": {"secp256k1": {"tests": ["secp256k1_keys"]}} } ], "families": [ @@ -888,7 +913,7 @@ "columns": ["Curve", "What it does", "Security level", "Key sizes", "Signature sizes", "Speed", "Constant time, measured", "Standards", "Ecosystems that require it", "Browsers' WebCrypto", "Choose it for compatibility with"], "cited": ["Standards", "Ecosystems that require it", "Browsers' WebCrypto"], "rows": [ - ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, ECDH in three forms, the x-only tweak", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 32 bytes x-only", "64 bytes; ECDSA in DER up to 72", "{speed:secp256k1}", "{constant_time:secp256k1}", "{sec2}, {bip340}, {rfc6979}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}). Not in this version: Ethereum's recoverable signatures and its addresses from the uncompressed key; BIP 32's derivation ({bip32})"], + ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, hedged and recoverable ECDSA, the recovery of a signer's key, ECDH in three forms, public keys in both forms, the x-only tweak", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 65 bytes uncompressed ({sec1}), 32 bytes x-only", "64 bytes; 65 bytes recoverable; ECDSA in DER up to 72", "{speed:secp256k1}", "{constant_time:secp256k1}", "{sec2}, {bip340}, {rfc6979}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}); Ethereum's recoverable signatures and uncompressed keys ({ethereum}), the address hashing being a domain library's. Not in this version: BIP 32's derivation ({bip32})"], ["`ed25519`", "Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair", "about 128 bits ({rfc8032})", "secret 32 bytes (the seed); public 32 bytes", "64 bytes", "{speed:ed25519}", "{constant_time:ed25519}", "{rfc8032}, {fips186-5}", "SSH keys ({rfc8709}), Signal's signatures on its Curve25519 keys ({signal-xeddsa}), Tor's identity keys ({tor-cert-spec}), Solana's accounts ({solana-accounts})", "yes: Ed25519 ({webcrypto})", "SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"], ["`x25519`", "Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction", "about 128 bits ({rfc7748})", "secret 32 bytes; public 32 bytes", "none: no signatures", "{speed:x25519}", "{constant_time:x25519}", "{rfc7748}", "TLS 1.3 ({rfc8446-groups}), SSH ({rfc8731}), WireGuard ({wireguard}), Signal ({x3dh})", "yes: X25519 ({webcrypto})", "TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` ({libsodium-kx}). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested ({wycheproof})"] ] @@ -916,6 +941,7 @@ {"need": "Check a software update or a licence file", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_ecdsa`, `verify_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "signed_update", "section": "crypto-everyday-update"}, {"need": "Agree on a key with a peer through a relay that sees everything", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::ecdh` (SHA-256 of the shared point), then HKDF on Boost.Hash2 and `aes256_gcm`", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "ecdh_session", "section": "crypto-p2p-session"}, {"need": "Derive a Nostr direct message's conversation key (NIP-44; the format is a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::ecdh_x`, then HKDF on Boost.Hash2", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdh_x_coordinate", "section": "crypto-secp256k1-ecdh"}, + {"need": "Find who signed a message or a transaction without being sent their key (Ethereum's signatures)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_recoverable`, `recover`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "recover_signer", "section": "crypto-secp256k1-recovery"}, {"need": "Make and keep a wallet's key", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "wallet_key", "section": "crypto-wallets-key"}, {"need": "Sign a Bitcoin SegWit v0 input (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`sign_ecdsa`, `to_der`, `normalize_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdsa_der", "section": "crypto-wallets-der"}, {"need": "Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`tweak_xonly`, `keypair::tweak_xonly`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "taproot_tweak", "section": "crypto-wallets-taproot"}, diff --git a/doc/testing.adoc b/doc/testing.adoc index 94cc0be6..9173a112 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -52,12 +52,13 @@ What the tests check: * *The vectors.* AES-GCM against the GCM specification's cases and Project Wycheproof's vectors, on BearSSL and on OpenSSL; AES against FIPS 197 on ctaes -and OpenSSL; secp256k1 against BIP 340's vectors and Wycheproof's ECDSA and DER -vectors, and the x-only tweak against BIP 341's. Ed25519 against RFC 8032's -tests, Wycheproof's EdDSA vectors and the twelve edge cases of "Taming the -many EdDSAs"; X25519 against RFC 7748's and Wycheproof's; ChaCha20-Poly1305 -and XChaCha20-Poly1305 against RFC 8439's and the XChaCha20 draft's examples -and Wycheproof's vectors, on every backend that has them. +and OpenSSL; secp256k1 against BIP 340's vectors, Wycheproof's ECDSA, ECDH and +DER vectors and libsecp256k1's own recovery edge cases, and the x-only tweak +against BIP 341's. Ed25519 against RFC 8032's tests, Wycheproof's EdDSA vectors +and the twelve edge cases of "Taming the many EdDSAs"; X25519 against RFC 7748's +and Wycheproof's; ChaCha20-Poly1305 and XChaCha20-Poly1305 against RFC 8439's +and the XChaCha20 draft's examples and Wycheproof's vectors, on every backend +that has them. * *node's WebCrypto as an outside oracle,* on Emscripten: 200 Ed25519 key pairs, messages and signatures from a fixed seed, each verified and signed again by `crypto.subtle`, which must give the same public key and signature, diff --git a/example/Jamfile b/example/Jamfile index 7df164e7..b46cdb29 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -53,6 +53,10 @@ webcpp.example ecdh_session.cpp : /third_party//secp256k1 /web # derives from it. webcpp.example ecdh_x_coordinate.cpp : /third_party//secp256k1 ; +# A recoverable signature: a reader finds the signer's key from the signature +# and the hash. +webcpp.example recover_signer.cpp : /third_party//secp256k1 ; + # A wallet's key pair, its secret sealed at rest and restored. webcpp.example wallet_key.cpp : /third_party//secp256k1 /webcpp/crypto//gcm-default ; diff --git a/example/recover_signer.cpp b/example/recover_signer.cpp new file mode 100644 index 00000000..feef1cd6 --- /dev/null +++ b/example/recover_signer.cpp @@ -0,0 +1,107 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Finds who signed a message without being sent their key, as Ethereum finds a transaction's +// signer: a wallet signs a message's hash with a recoverable signature, and a reader that holds +// no key recovers the signer's public key from the signature and the hash, then compares it +// with the key the wallet published. Recovery always finds some key, so the comparison is the +// check: a changed message recovers another key. +// tag::program[] +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace secp256k1 = webcpp::crypto::curves::secp256k1; + +namespace { + +// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead +// store: crypto wipes its own copies of keys this way, and the program wipes its own. +void wipe(std::span secret) { + std::byte volatile* const bytes = secret.data(); + for (std::size_t i = 0; i < secret.size(); ++i) { + bytes[i] = std::byte{0}; + } +} + +// The message's SHA-256. Ethereum's own message hash is EIP-191's (a prefix, then Keccak-256), +// which a domain library computes; crypto signs and recovers whatever 32-byte hash it is given. +std::array sha256(std::string_view text) { + boost::hash2::sha2_256 hash; + hash.update(text.data(), text.size()); + auto const digest = hash.result(); + std::array out{}; + std::copy_n(digest.data(), out.size(), out.begin()); + return out; +} + +boost::system::result generate_key() { + crypto::random_device device; + std::array secret{}; + for (;;) { + auto const filled = device.fill(secret); + if (!filled) { + return filled.error(); + } + auto key = secp256k1::keypair::make(secret); + if (key || key.error() != crypto::error::invalid_secret_key) { + // The key pair keeps its own copy, which it wipes; this one goes now. + wipe(std::as_writable_bytes(std::span(secret))); + return key; + } + } +} + +} // namespace + +int main() { + // The wallet publishes its key once, uncompressed as Ethereum writes it, and signs. + auto wallet = generate_key(); + if (!wallet) { + return 1; + } + auto const published = wallet->public_key_uncompressed(); + std::string message = "pay 10 to bob"; + auto const signature = wallet->sign_recoverable(sha256(message)); + if (!published || !signature) { + return 1; + } + + // tag::recover[] + // The reader holds no key of the wallet's: it parses the published key once, recovers the + // signer's key from the 65-byte signature and the hash, and compares the two. + auto const expected = secp256k1::parse_public_key(*published); + auto const signer = secp256k1::recover(*signature, sha256(message)); + if (!expected || !signer || *signer != *expected) { + return 1; + } + std::printf("recovered the wallet's key\n"); + + // A changed message still recovers a key, but not the wallet's. + message = "pay 99 to bob"; + auto const other = secp256k1::recover(*signature, sha256(message)); + if (other && *other == *expected) { + return 1; + } + std::printf("a changed message names another signer\n"); + // end::recover[] + return 0; +} + +// end::program[] diff --git a/example/recover_signer.expected b/example/recover_signer.expected new file mode 100644 index 00000000..550a2027 --- /dev/null +++ b/example/recover_signer.expected @@ -0,0 +1,2 @@ +recovered the wallet's key +a changed message names another signer diff --git a/include/webcpp/crypto/backends/secp256k1.hpp b/include/webcpp/crypto/backends/secp256k1.hpp index 28d71f32..f6219fde 100644 --- a/include/webcpp/crypto/backends/secp256k1.hpp +++ b/include/webcpp/crypto/backends/secp256k1.hpp @@ -7,8 +7,8 @@ /** The backend libsecp256k1: its v0.8.0, built from its sources by `/third_party//secp256k1`, every module on. It serves `curves::secp256k1::keypair`, `verify_schnorr`, `verify_ecdsa`, - the DER and low-S functions and the x-only tweak, and its whole C API stays reachable - through ``. + `recover`, the parsed `public_key`, the DER and low-S functions and the x-only tweak, and its + whole C API stays reachable through ``. @see "secp256k1", in the guide. */ @@ -29,6 +29,7 @@ #include #include #include +#include #include #include diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index a0657b12..bc6a40af 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -5,9 +5,10 @@ // https://www.boost.org/LICENSE_1_0.txt) /** - secp256k1 on libsecp256k1: BIP340 Schnorr and ECDSA signatures, their verification, and - ECDH in three forms, each a secret; ECDSA's DER and low-S forms, and the tweak of an x-only - key. + secp256k1 on libsecp256k1: BIP340 Schnorr and ECDSA signatures, hedged and recoverable, their + verification and the recovery of a signer's key, and ECDH in three forms, each a secret; the + parsed public key in its two SEC1 forms; ECDSA's DER and low-S forms, and the tweak of an + x-only key. @see "secp256k1", in the guide. */ @@ -28,6 +29,7 @@ #include #include +#include #include #include #include @@ -41,14 +43,88 @@ #define WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY "webcpp::crypto: curves::secp256k1 runs on libsecp256k1 alone. Name backends::secp256k1, or leave the backend out, as in curves::secp256k1::keypair." // clang-format on +namespace webcpp::crypto::curves::secp256k1 { + +template +class basic_keypair; + +class public_key; + +} // namespace webcpp::crypto::curves::secp256k1 + namespace webcpp::crypto::detail { +/** + * The one door of the module headers (those under `curves/secp256k1/`) into a key pair and a public + * key: the key pair's context and `secp256k1_keypair`, whether it is keyed, and a public key's + * point. It hands out nothing a caller of crypto could not already do through the key pair. + */ +struct secp256k1_access { + /** + * Whether a key pair holds a key: false moved from, or after a refused tweak. + * + * @param key_pair The key pair. + * @return Whether it is keyed. + */ + template + [[nodiscard]] static bool keyed( + curves::secp256k1::basic_keypair const& key_pair) noexcept; + + /** + * A key pair's randomised signing context, for the functions that multiply the generator. + * + * @param key_pair The key pair, keyed. + * @return Its context; null moved from. + */ + template + [[nodiscard]] static secp256k1_context const* context( + curves::secp256k1::basic_keypair const& key_pair) noexcept; + + /** + * A key pair's `secp256k1_keypair`, its secret and public key. + * + * @param key_pair The key pair, keyed. + * @return Its `secp256k1_keypair`, wiped moved from. + */ + template + [[nodiscard]] static secp256k1_keypair const& pair( + curves::secp256k1::basic_keypair const& key_pair) noexcept; + + /** + * A public key's point. + * + * @param key The public key. + * @return Its `secp256k1_pubkey`. + */ + [[nodiscard]] static secp256k1_pubkey const& point( + curves::secp256k1::public_key const& key) noexcept; + + /** + * A public key's point, to be written by the function that makes the key. + * + * @param key The public key. + * @return Its `secp256k1_pubkey`. + */ + [[nodiscard]] static secp256k1_pubkey& point(curves::secp256k1::public_key& key) noexcept; + + /** + * A public key whose point is zero, not yet a key: the function that returns it writes its + * point first, and returns an error instead where libsecp256k1 writes none. + * + * @return The unwritten key. + */ + [[nodiscard]] static curves::secp256k1::public_key make_public_key() noexcept; +}; + // NOLINTBEGIN(bugprone-signed-bitwise): libsecp256k1's macros shift a signed constant /** The flags of a context that signs and verifies: none. */ inline constexpr unsigned secp256k1_context_flags = SECP256K1_CONTEXT_NONE; /** The flag of the SEC1 compressed form. */ inline constexpr unsigned secp256k1_compressed = SECP256K1_EC_COMPRESSED; + +/** The flag of the SEC1 uncompressed form. */ +inline constexpr unsigned secp256k1_uncompressed = SECP256K1_EC_UNCOMPRESSED; // NOLINTEND(bugprone-signed-bitwise) /** @@ -188,6 +264,80 @@ namespace webcpp::crypto::curves::secp256k1 { /** The longest strict DER encoding of a secp256k1 ECDSA signature, in bytes. */ inline constexpr std::size_t max_der_size = 72; +/** The two SEC1 encodings of a point. */ +enum class point_form { + /** 33 bytes: 02 or 03 by the parity of y, then x; Bitcoin's form. */ + compressed, + /** 65 bytes: 04, x, y; Ethereum's form, and OpenSSL's default. */ + uncompressed, +}; + +/** + * The size of a point in `Form`: 33 or 65. + * + * @tparam Form The SEC1 form. + */ +template +inline constexpr std::size_t point_size = Form == point_form::compressed ? 33 : 65; + +/** The size of a recoverable signature: r, s, then the recovery id. */ +inline constexpr std::size_t recoverable_signature_size = 65; + +/** + * A secp256k1 public key, parsed: a point on the curve, never the identity + * (libsecp256k1's `secp256k1_pubkey`). + * + * It holds nothing secret and is copied freely; it is made only by the functions that return + * one, so that it is always valid. + */ +class public_key { +public: + /** + * Equal when the points are equal. + * + * @param left_key A key. + * @param right_key Another key. + * @return Whether they are the same point. + */ + [[nodiscard]] friend bool operator==(public_key const& left_key, + public_key const& right_key) noexcept { + return compare(left_key, right_key) == 0; + } + + /** + * Ordered as their compressed encodings, BIP 327's KeySort (`secp256k1_ec_pubkey_cmp`). + * + * @param left_key A key. + * @param right_key Another key. + * @return The order of their compressed encodings, byte by byte. + */ + [[nodiscard]] friend std::strong_ordering operator<=>(public_key const& left_key, + public_key const& right_key) noexcept { + return compare(left_key, right_key) <=> 0; + } + +private: + friend struct webcpp::crypto::detail::secp256k1_access; + + public_key() noexcept = default; + + /** + * libsecp256k1's comparison of two keys with the static context, which reads both as + * compressed encodings. Both are valid points: no key is made otherwise, so the illegal + * callback is never reached. + * + * @return Negative, zero or positive, as `memcmp`. + */ + [[nodiscard]] static int compare(public_key const& left_key, + public_key const& right_key) noexcept { + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + return secp256k1_ec_pubkey_cmp(secp256k1_context_static, &left_key.point_value_, + &right_key.point_value_); + } + + secp256k1_pubkey point_value_{}; +}; + /** A tweaked x-only key: the key and the parity of its point's y. */ struct tweaked_xonly_key { /** The 32-byte x-only key. */ @@ -325,17 +475,17 @@ class basic_keypair { * @return 33 bytes; `invalid_state` moved from. */ [[nodiscard]] boost::system::result> public_key() const noexcept { - if (!keyed_) { - return error::invalid_state; - } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - secp256k1_pubkey public_point{}; - std::array output_bytes{}; - std::size_t written_size = output_bytes.size(); - secp256k1_keypair_pub(context_, &public_point, &keypair_); - secp256k1_ec_pubkey_serialize(context_, output_bytes.data(), &written_size, &public_point, - webcpp::crypto::detail::secp256k1_compressed); - return output_bytes; + return encoded_public_key<33>(webcpp::crypto::detail::secp256k1_compressed); + } + + /** + * The public key, SEC1 uncompressed. + * + * @return 65 bytes; `invalid_state` moved from. + */ + [[nodiscard]] boost::system::result> public_key_uncompressed() + const noexcept { + return encoded_public_key<65>(webcpp::crypto::detail::secp256k1_uncompressed); } /** @@ -373,20 +523,51 @@ class basic_keypair { */ [[nodiscard]] boost::system::result> sign_ecdsa( std::span message_hash) const noexcept { + return signed_ecdsa(message_hash, nullptr); + } + + /** + * A hedged ECDSA signature: RFC 6979's nonce with 32 bytes of the caller's fresh + * randomness mixed in (libsecp256k1's `ndata`), so that a fault or a side channel on one + * signing does not repeat on the next. + * + * @param message_hash The 32-byte hash signed. + * @param extra_entropy 32 bytes from `random_device`, new for each signature. + * @return 64 bytes, r then s, low-S; `invalid_state`; `backend_failure`. + */ + [[nodiscard]] boost::system::result> sign_ecdsa( + std::span message_hash, + std::span extra_entropy) const noexcept { + webcpp::crypto::detail::secp256k1_secret nonce_data; + std::ranges::copy(extra_entropy, nonce_data.bytes.begin()); + return signed_ecdsa(message_hash, nonce_data.bytes.data()); + } + + /** + * An ECDSA signature of a 32-byte hash with its recovery id: RFC 6979's nonce, low-S, as + * `sign_ecdsa` (the same r and s), then the id from which `recover` finds the key. + * + * @param message_hash The 32-byte hash signed. + * @return 65 bytes, r, s and the id 0 to 3; `invalid_state`; `backend_failure`. + */ + [[nodiscard]] boost::system::result> + sign_recoverable(std::span message_hash) const noexcept { if (!keyed_) { return error::invalid_state; } webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); webcpp::crypto::detail::secp256k1_secret secret_bytes; secp256k1_keypair_sec(context_, secret_bytes.bytes.data(), &keypair_); - secp256k1_ecdsa_signature signature_bytes{}; - std::array output_bytes{}; - if (secp256k1_ecdsa_sign(context_, &signature_bytes, message_hash.data(), - secret_bytes.bytes.data(), nullptr, nullptr) == 0) { + secp256k1_ecdsa_recoverable_signature signature_value{}; + if (secp256k1_ecdsa_sign_recoverable(context_, &signature_value, message_hash.data(), + secret_bytes.bytes.data(), nullptr, nullptr) == 0) { return error::backend_failure; } - secp256k1_ecdsa_signature_serialize_compact(context_, output_bytes.data(), - &signature_bytes); + std::array output_bytes{}; + int recovery_id = 0; + secp256k1_ecdsa_recoverable_signature_serialize_compact(context_, output_bytes.data(), + &recovery_id, &signature_value); + output_bytes[64] = static_cast(recovery_id); return output_bytes; } @@ -458,8 +639,60 @@ class basic_keypair { } private: + friend struct webcpp::crypto::detail::secp256k1_access; + basic_keypair() noexcept = default; + /** + * The public key in the SEC1 form `flags` names. + * + * @tparam N The form's size, 33 or 65. + * @param flags libsecp256k1's flag of the form. + * @return `N` bytes; `invalid_state` moved from. + */ + template + [[nodiscard]] boost::system::result> encoded_public_key( + unsigned flags) const noexcept { + if (!keyed_) { + return error::invalid_state; + } + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_pubkey public_point{}; + std::array output_bytes{}; + std::size_t written_size = output_bytes.size(); + secp256k1_keypair_pub(context_, &public_point, &keypair_); + secp256k1_ec_pubkey_serialize(context_, output_bytes.data(), &written_size, &public_point, + flags); + return output_bytes; + } + + /** + * An ECDSA signature with RFC 6979's nonce, `nonce_data` mixed in when it is not null. + * + * @param message_hash The 32-byte hash signed. + * @param nonce_data 32 bytes of extra entropy, libsecp256k1's `ndata`, or null. + * @return 64 bytes, r then s, low-S; `invalid_state`; `backend_failure`. + */ + [[nodiscard]] boost::system::result> signed_ecdsa( + std::span message_hash, + unsigned char const* nonce_data) const noexcept { + if (!keyed_) { + return error::invalid_state; + } + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + webcpp::crypto::detail::secp256k1_secret secret_bytes; + secp256k1_keypair_sec(context_, secret_bytes.bytes.data(), &keypair_); + secp256k1_ecdsa_signature signature_bytes{}; + std::array output_bytes{}; + if (secp256k1_ecdsa_sign(context_, &signature_bytes, message_hash.data(), + secret_bytes.bytes.data(), nullptr, nonce_data) == 0) { + return error::backend_failure; + } + secp256k1_ecdsa_signature_serialize_compact(context_, output_bytes.data(), + &signature_bytes); + return output_bytes; + } + /** * ECDH with a peer's public key, its output written by `hash_function` into the secret: * libsecp256k1's SHA-256 when it is null. @@ -514,6 +747,133 @@ class basic_keypair { /** A key pair on libsecp256k1. */ using keypair = basic_keypair<>; +} // namespace webcpp::crypto::curves::secp256k1 + +namespace webcpp::crypto::detail { + +template +inline bool secp256k1_access::keyed( + curves::secp256k1::basic_keypair const& key_pair) noexcept { + return key_pair.keyed_; +} + +template +inline secp256k1_context const* secp256k1_access::context( + curves::secp256k1::basic_keypair const& key_pair) noexcept { + return key_pair.context_; +} + +template +inline secp256k1_keypair const& secp256k1_access::pair( + curves::secp256k1::basic_keypair const& key_pair) noexcept { + return key_pair.keypair_; +} + +inline secp256k1_pubkey const& secp256k1_access::point( + curves::secp256k1::public_key const& key) noexcept { + return key.point_value_; +} + +inline secp256k1_pubkey& secp256k1_access::point(curves::secp256k1::public_key& key) noexcept { + return key.point_value_; +} + +inline curves::secp256k1::public_key secp256k1_access::make_public_key() noexcept { + return curves::secp256k1::public_key(); +} + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::curves::secp256k1 { + +/** + * Parses a public key: 33 bytes with prefix 02 or 03, or 65 with prefix 04 (X9.62's hybrid + * prefixes 06 and 07 are refused, as everywhere in crypto). + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param encoded_key The key, SEC1. + * @return The key; `invalid_public_key` for any other length or prefix, or a point off the curve. + */ +template +[[nodiscard]] boost::system::result parse_public_key( + std::span encoded_key) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + public_key parsed_key = access::make_public_key(); + if (!webcpp::crypto::detail::secp256k1_parse_public_key(encoded_key, + access::point(parsed_key))) { + return error::invalid_public_key; + } + return parsed_key; +} + +/** + * Serialises a public key in `Form`. + * + * @tparam Form The SEC1 form, `compressed` by default. + * @tparam Backend The backend, `backends::secp256k1`. + * @param parsed_key The key. + * @return 33 bytes (`compressed`, the default) or 65 (`uncompressed`). + */ +template +[[nodiscard]] std::array> serialize_public_key( + public_key const& parsed_key) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + std::array> output_bytes{}; + std::size_t written_size = output_bytes.size(); + secp256k1_ec_pubkey_serialize(secp256k1_context_static, output_bytes.data(), &written_size, + &webcpp::crypto::detail::secp256k1_access::point(parsed_key), + Form == point_form::compressed + ? webcpp::crypto::detail::secp256k1_compressed + : webcpp::crypto::detail::secp256k1_uncompressed); + return output_bytes; +} + +/** + * The public key that made a recoverable signature of a 32-byte hash + * (`secp256k1_ecdsa_recover`), as Ethereum identifies a transaction's signer. + * + * Tip: recovery finds some key for almost any signature; the signature is the expected + * signer's only when the key recovered is the one expected. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param recoverable_signature 65 bytes: r, s, then the recovery id, 0 to 3. + * @param message_hash The 32-byte hash signed. + * @return The key; `invalid_signature` for a recovery id above 3, an r or an s not below the + * group order, or a signature from which no key is recovered. + */ +template +[[nodiscard]] boost::system::result recover( + std::span recoverable_signature, + std::span message_hash) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + // libsecp256k1 checks the id with ARG_CHECK, whose callback aborts: refused first here. + int const recovery_id = recoverable_signature[64]; + if (recovery_id > 3) { + return error::invalid_signature; + } + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + secp256k1_ecdsa_recoverable_signature parsed_value{}; + public_key recovered_key = access::make_public_key(); + if (secp256k1_ecdsa_recoverable_signature_parse_compact(secp256k1_context_static, &parsed_value, + recoverable_signature.data(), + recovery_id) == 0 || + secp256k1_ecdsa_recover(secp256k1_context_static, &access::point(recovered_key), + &parsed_value, message_hash.data()) == 0) { + return error::invalid_signature; + } + return recovered_key; +} + /** * Verifies a BIP340 signature with libsecp256k1's static context, which allocates nothing, * after its self-test (`include/secp256k1.h:235-247`). diff --git a/test/Jamfile b/test/Jamfile index c21e0fd0..2977de00 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -210,8 +210,12 @@ crypto-run secp256k1_wycheproof : secp256k1_wycheproof_test.cpp crypto-run secp256k1_ecdh : secp256k1_ecdh_test.cpp : /third_party//secp256k1 /third_party//wycheproof /webcpp//boost_json ; -# libsecp256k1's recovery and ElligatorSwift modules, which webcpp does not -# wrap, called through the C API and linked. +# The parsed public key in both SEC1 forms, and its refusals. +crypto-run secp256k1_keys : secp256k1_keys_test.cpp : /third_party//secp256k1 ; +# Recoverable ECDSA signatures, libsecp256k1's edge cases, and hedged ECDSA. +crypto-run secp256k1_recovery : secp256k1_recovery_test.cpp : /third_party//secp256k1 ; +# libsecp256k1's recovery and ElligatorSwift modules called through its C API, +# which stays reachable beside the wrappers, and compared with them. crypto-run secp256k1_c_api : secp256k1_c_api_test.cpp : /third_party//secp256k1 ; crypto-run secp256k1_der : secp256k1_der_test.cpp : /third_party//secp256k1 /third_party//wycheproof diff --git a/test/secp256k1_allocation_test.cpp b/test/secp256k1_allocation_test.cpp index 34ca2f6d..3294a8e1 100644 --- a/test/secp256k1_allocation_test.cpp +++ b/test/secp256k1_allocation_test.cpp @@ -7,10 +7,10 @@ // secp256k1's one allocation (spec section 8.5): make allocates the signing context once, in // the resource it is given, of libsecp256k1's preallocated size and aligned to max_align_t, // and never through operator new nor the C library's allocator where the target lets a -// program count it; the signatures, the three forms of ECDH, the public keys, both -// verifications, the DER and low-S functions and the x-only tweak allocate nothing, each -// counted alone; the destructor gives the block back; a refused make allocates nothing. A -// control proves the counter moves. +// program count it; the signatures (hedged and recoverable too), the three forms of ECDH, the +// public keys in both forms, both verifications, the parsed public key, recovery, the DER and +// low-S functions and the x-only tweak allocate nothing, each counted alone; the destructor gives +// the block back; a refused make allocates nothing. A control proves the counter moves. #include #include @@ -104,7 +104,11 @@ int main() { auto const shared = key.ecdh(*public_key); auto const shared_x = key.ecdh_x(*public_key); auto const shared_point = key.ecdh_point(*public_key); + auto const hedged = key.sign_ecdsa(message, aux); + auto const recoverable = key.sign_recoverable(message); + auto const uncompressed = key.public_key_uncompressed(); BOOST_TEST(schnorr && ecdsa && xonly && public_key && shared && shared_x && shared_point); + BOOST_TEST(hedged && recoverable && uncompressed); BOOST_TEST(secp::verify_schnorr(*schnorr, message, *xonly).has_value()); BOOST_TEST(secp::verify_ecdsa(*ecdsa, message, *public_key).has_value()); BOOST_TEST_EQ(webcpp::test::allocations(), before); @@ -128,6 +132,14 @@ int main() { none("from_der", [&] { return secp::from_der(encoded); }); none("normalize_ecdsa", [&] { return secp::normalize_ecdsa(*ecdsa); }); none("tweak_xonly", [&] { return secp::tweak_xonly(*xonly, message); }); + auto const parsed = secp::parse_public_key(*uncompressed); + none("parse_public_key", [&] { return secp::parse_public_key(*public_key); }); + none("serialize_public_key", [&] { + return secp::serialize_public_key(*parsed) == + *uncompressed; + }); + none("recover", [&] { return secp::recover(*recoverable, message); }); + none("public_key <=>", [&] { return (*parsed <=> *parsed) == 0; }); none("keypair::tweak_xonly", [&] { return key.tweak_xonly(message); }); BOOST_TEST_EQ(resource.allocated, 1U); BOOST_TEST_EQ(resource.deallocated, 0U); diff --git a/test/secp256k1_c_api_test.cpp b/test/secp256k1_c_api_test.cpp index 9b081da9..a4a9d92c 100644 --- a/test/secp256k1_c_api_test.cpp +++ b/test/secp256k1_c_api_test.cpp @@ -4,11 +4,12 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// A C module webcpp does not wrap, called and linked (spec section 2.8, "A C module not -// wrapped"): the recovery module's `secp256k1_ecdsa_sign_recoverable` and -// `secp256k1_ecdsa_recover`, and the ElligatorSwift module's `secp256k1_ellswift_create` and -// `secp256k1_ellswift_decode`, against `/third_party//secp256k1` and nothing else of webcpp's -// but the key pair, which names the public key they must agree with. +// libsecp256k1's C API stays reachable beside crypto's wrappers: the recovery module's +// `secp256k1_ecdsa_sign_recoverable` and `secp256k1_ecdsa_recover`, and the ElligatorSwift +// module's `secp256k1_ellswift_create` and `secp256k1_ellswift_decode`, called and linked +// against `/third_party//secp256k1`. What the C calls give is compared with the wrappers: the +// key the C API recovers with `recover`'s, and the key ElligatorSwift decodes with +// `parse_public_key`'s; both with the key pair's. #include #include @@ -19,6 +20,7 @@ #include #include +#include #include #include #include @@ -69,6 +71,17 @@ void recovery(secp256k1_context const* context, secret_key const& secret, BOOST_TEST_EQ(secp256k1_ecdsa_recover(context, &again, &parsed, hash.data()), 1); BOOST_TEST(serialised(context, again) == expected); + // The wrapper recovers the same key from the same 65 bytes, r, s and the id. + std::array with_id{}; + std::ranges::copy(compact, with_id.begin()); + with_id[64] = static_cast(id); + auto const wrapped = secp::recover(with_id, hash); + auto const expected_key = secp::parse_public_key(expected); + if (BOOST_TEST(wrapped && expected_key)) { + BOOST_TEST(*wrapped == *expected_key); + BOOST_TEST(secp::serialize_public_key(*wrapped) == serialised(context, again)); + } + hash.fill(0xa5); secp256k1_pubkey other; if (BOOST_TEST_EQ(secp256k1_ecdsa_recover(context, &other, &parsed, hash.data()), 1)) { @@ -87,6 +100,13 @@ void ellswift(secp256k1_context const* context, secret_key const& secret, secp256k1_pubkey decoded; BOOST_TEST_EQ(secp256k1_ellswift_decode(context, &decoded, encoded.data()), 1); BOOST_TEST(serialised(context, decoded) == expected); + + // The decoded point, serialised by the C API, parses with the wrapper to the key pair's key. + auto const wrapped = secp::parse_public_key(serialised(context, decoded)); + auto const expected_key = secp::parse_public_key(expected); + if (BOOST_TEST(wrapped && expected_key)) { + BOOST_TEST(*wrapped == *expected_key); + } } } // namespace diff --git a/test/secp256k1_keys_test.cpp b/test/secp256k1_keys_test.cpp new file mode 100644 index 00000000..ec418d17 --- /dev/null +++ b/test/secp256k1_keys_test.cpp @@ -0,0 +1,255 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// secp256k1's parsed public key in both SEC1 forms: the generator's first multiples parse and +// serialise, compressed and uncompressed, and a key pair's two forms parse to one key; every +// length but 33 and 65, every prefix but 02, 03 and 04 (X9.62's hybrid 06 and 07 with a valid +// point, which libsecp256k1 alone takes, among them), an x not below the field's prime and an +// x with no y are invalid_public_key; keys order as their compressed bytes. + +#include +#include +#include + +#include "support/hex.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace secp = webcpp::crypto::curves::secp256k1; +namespace test = webcpp::test; + +namespace { + +static_assert(!std::is_default_constructible_v); +static_assert(std::is_trivially_copyable_v); +static_assert(secp::point_size == 33); +static_assert(secp::point_size == 65); +static_assert( + std::is_same_v())), + std::array>); +static_assert(std::is_same_v( + std::declval())), + std::array>); + +// The compressed keys of 1G, 2G and 3G: the public keys of the secrets 1, 2 and 3. +constexpr std::array multiples = { + "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5", + "02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", +}; + +// The secret key k, 32 bytes big-endian. +std::array small_secret(std::uint8_t k) { + std::array secret{}; + secret.back() = k; + return secret; +} + +void refused(std::string const& label, std::span encoded) { + auto const parsed = secp::parse_public_key(encoded); + if (!BOOST_TEST(parsed.has_error()) || + !BOOST_TEST(parsed.error() == crypto::error::invalid_public_key)) { + BOOST_ERROR(label.c_str()); + } +} + +// 1G, 2G and 3G: each is the key pair's of its secret, parses, serialises to its bytes, and +// comes back to them through the uncompressed form. +void generator_multiples() { + for (std::size_t i = 0; i < multiples.size(); ++i) { + auto const expected = test::from_hex(multiples[i]); + auto const key = secp::keypair::make(small_secret(static_cast(i + 1))); + if (!BOOST_TEST(key.has_value())) { + continue; + } + auto const from_pair = key->public_key(); + BOOST_TEST(from_pair && std::ranges::equal(*from_pair, expected)); + auto const parsed = secp::parse_public_key(expected); + if (!BOOST_TEST(parsed.has_value())) { + continue; + } + auto const compressed = secp::serialize_public_key(*parsed); + BOOST_TEST(std::ranges::equal(compressed, expected)); + auto const uncompressed = + secp::serialize_public_key(*parsed); + BOOST_TEST_EQ(uncompressed[0], 0x04); + BOOST_TEST(std::ranges::equal(std::span(uncompressed).subspan(1, 32), + std::span(expected).subspan(1, 32))); + auto const again = secp::parse_public_key(uncompressed); + if (BOOST_TEST(again.has_value())) { + BOOST_TEST(*again == *parsed); + BOOST_TEST(std::ranges::equal(secp::serialize_public_key(*again), expected)); + BOOST_TEST(std::ranges::equal( + secp::serialize_public_key(*again), uncompressed)); + } + } +} + +// A key pair's uncompressed key parses to the same key as its compressed one. +void keypair_forms() { + for (std::uint8_t k = 1; k <= 16; ++k) { + auto const key = secp::keypair::make(small_secret(k)); + if (!BOOST_TEST(key.has_value())) { + continue; + } + auto const compressed = key->public_key(); + auto const uncompressed = key->public_key_uncompressed(); + if (!BOOST_TEST(compressed && uncompressed)) { + continue; + } + BOOST_TEST_EQ((*uncompressed)[0], 0x04); + auto const from_compressed = secp::parse_public_key(*compressed); + auto const from_uncompressed = secp::parse_public_key(*uncompressed); + if (BOOST_TEST(from_compressed && from_uncompressed)) { + BOOST_TEST(*from_compressed == *from_uncompressed); + BOOST_TEST(std::ranges::equal( + secp::serialize_public_key(*from_compressed), + *uncompressed)); + } + } +} + +// The SEC1 uncompressed form of a compressed key, through libsecp256k1. +std::array uncompressed_of(std::span compressed) { + secp256k1_pubkey point{}; + BOOST_TEST_EQ(secp256k1_ec_pubkey_parse(secp256k1_context_static, &point, compressed.data(), + compressed.size()), + 1); + std::array out{}; + std::size_t size = out.size(); + // NOLINTNEXTLINE(bugprone-signed-bitwise): libsecp256k1's macro shifts a signed constant + unsigned const flags = SECP256K1_EC_UNCOMPRESSED; + BOOST_TEST_EQ( + secp256k1_ec_pubkey_serialize(secp256k1_context_static, out.data(), &size, &point, flags), + 1); + return out; +} + +// Whether libsecp256k1's own parser takes the bytes. +bool libsecp256k1_takes(std::span encoded) { + secp256k1_pubkey point{}; + return secp256k1_ec_pubkey_parse(secp256k1_context_static, &point, encoded.data(), + encoded.size()) == 1; +} + +void refusals() { + auto const one_g = test::from_hex(multiples[0]); + auto const one_g_long = uncompressed_of(one_g); + + // Every length but 33 and 65. + for (std::size_t const size : {0U, 1U, 32U, 34U, 64U, 66U}) { + std::vector encoded(one_g_long.begin(), one_g_long.end()); + encoded.resize(size, 0x01); + refused("length " + std::to_string(size), encoded); + } + + // Every prefix but 02, 03 and 04, on 33 and on 65 bytes. + for (std::uint8_t const prefix : {0x00, 0x01, 0x05, 0x06, 0x07, 0x08, 0xff}) { + auto short_form = one_g; + short_form[0] = prefix; + refused("prefix " + std::to_string(prefix) + ", 33 bytes", short_form); + auto long_form = one_g_long; + long_form[0] = prefix; + refused("prefix " + std::to_string(prefix) + ", 65 bytes", long_form); + } + + // X9.62's hybrid forms of valid points, 06 for an even y (1G) and 07 for an odd one (6G), + // which libsecp256k1 alone takes. + auto hybrid_even = one_g_long; + hybrid_even[0] = 0x06; + BOOST_TEST(libsecp256k1_takes(hybrid_even)); + refused("hybrid 06, a valid point", hybrid_even); + auto const six_g = + test::from_hex("03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556"); + auto hybrid_odd = uncompressed_of(six_g); + hybrid_odd[0] = 0x07; + BOOST_TEST(libsecp256k1_takes(hybrid_odd)); + refused("hybrid 07, a valid point", hybrid_odd); + + // An x not below the field's prime p, and p itself. + auto const p_itself = + test::from_hex("02fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); + refused("x = p", p_itself); + auto const all_ones = + test::from_hex("03ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + refused("x = 2^256 - 1", all_ones); + auto p_long = one_g_long; + std::ranges::copy(std::span(p_itself).subspan(1), p_long.begin() + 1); + refused("x = p, 65 bytes", p_long); + + // x = 5: x^3 + 7 is not a square modulo p, so no point has this x. x = 0 neither. + for (std::uint8_t const x : {0x00, 0x05}) { + std::array no_y{}; + no_y[0] = 0x02; + no_y.back() = x; + BOOST_TEST(!libsecp256k1_takes(no_y)); + refused("x = " + std::to_string(x) + ", no y", no_y); + } + + // A point whose y is not the curve's for its x. + auto off_curve = one_g_long; + off_curve.back() ^= 0x01; + refused("y off the curve", off_curve); +} + +// Keys order as their compressed encodings: 1G, 2G, 3G; a key equals its re-parsed copy. +void ordering() { + std::vector keys; + for (auto const hex : multiples) { + auto const parsed = secp::parse_public_key(test::from_hex(hex)); + if (!BOOST_TEST(parsed.has_value())) { + return; + } + keys.push_back(*parsed); + } + BOOST_TEST(keys[0] < keys[1]); + BOOST_TEST(keys[1] < keys[2]); + BOOST_TEST(keys[0] < keys[2]); + BOOST_TEST(keys[2] > keys[0]); + BOOST_TEST((keys[1] <=> keys[1]) == std::strong_ordering::equal); + BOOST_TEST(keys[0] != keys[1]); + std::vector reversed(keys.rbegin(), keys.rend()); + std::ranges::sort(reversed); + BOOST_TEST(reversed == keys); + for (auto const& key : keys) { + auto const copy = secp::parse_public_key(secp::serialize_public_key(key)); + if (BOOST_TEST(copy.has_value())) { + BOOST_TEST(*copy == key); + BOOST_TEST((*copy <=> key) == std::strong_ordering::equal); + } + } + // A key's two forms order alike: the order reads the point, not the bytes it came from. + auto const long_one = + secp::parse_public_key(secp::serialize_public_key(keys[0])); + if (BOOST_TEST(long_one.has_value())) { + BOOST_TEST(*long_one < keys[1]); + BOOST_TEST(*long_one == keys[0]); + } +} + +} // namespace + +int main() { + generator_multiples(); + keypair_forms(); + refusals(); + ordering(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/secp256k1_recovery_test.cpp b/test/secp256k1_recovery_test.cpp new file mode 100644 index 00000000..a0b92bdd --- /dev/null +++ b/test/secp256k1_recovery_test.cpp @@ -0,0 +1,276 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// secp256k1's recoverable ECDSA signatures and hedged ECDSA: 64 seeded key pairs and hashes, +// each recovered to its key; libsecp256k1's own recovery edge cases; the refusals of an id +// above 3, of an r or an s out of range, and of a moved-from key pair; the hedged signature, +// equal to libsecp256k1's own with the same extra entropy and different from the unhedged one. + +#include +#include +#include + +#include "support/hex.hpp" +#include "support/secp256k1_checks.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace secp = webcpp::crypto::curves::secp256k1; +namespace test = webcpp::test; + +namespace { + +using hash_bytes = std::array; +using recoverable = std::array; + +static_assert(secp::recoverable_signature_size == 65); +static_assert(std::is_same_v(), + std::declval())), + boost::system::result>); + +// A key pair from the generator: a secret make refuses is drawn again. +secp::keypair draw(std::mt19937_64& generator, hash_bytes& secret) { + for (;;) { + for (auto& octet : secret) { + octet = static_cast(generator()); + } + auto made = secp::keypair::make(secret); + if (made) { + return std::move(*made); + } + BOOST_TEST(made.error() == crypto::error::invalid_secret_key); + } +} + +hash_bytes draw_hash(std::mt19937_64& generator) { + hash_bytes hash{}; + for (auto& octet : hash) { + octet = static_cast(generator()); + } + return hash; +} + +// The key pair's public key, parsed. +secp::public_key key_of(secp::keypair const& key) { + return *secp::parse_public_key(*key.public_key()); +} + +bool refused_as_signature(boost::system::result const& recovered) { + return recovered.has_error() && recovered.error() == crypto::error::invalid_signature; +} + +// 64 key pairs and hashes: recover finds the key pair's key from the signature and the hash; +// the id is 0 to 3; the first 64 bytes are sign_ecdsa's; another hash finds another key or +// none; an id of 4 or 255 is refused without reaching libsecp256k1's illegal callback. +void round_trips() { + std::mt19937_64 generator(0x2ec0e7ab1eULL); + int other_keys = 0; + for (int round = 0; round < 64; ++round) { + hash_bytes secret{}; + auto const key = draw(generator, secret); + auto const hash = draw_hash(generator); + auto const signature = key.sign_recoverable(hash); + auto const plain = key.sign_ecdsa(hash); + if (!BOOST_TEST(signature && plain)) { + continue; + } + BOOST_TEST((*signature)[64] <= 3); + BOOST_TEST(std::ranges::equal(std::span(*signature).first(64), *plain)); + auto const recovered = secp::recover(*signature, hash); + if (BOOST_TEST(recovered.has_value())) { + BOOST_TEST(*recovered == key_of(key)); + } + + auto other_hash = hash; + other_hash[0] ^= 0x80; + auto const other = secp::recover(*signature, other_hash); + if (other) { + BOOST_TEST(*other != key_of(key)); + ++other_keys; + } else { + BOOST_TEST(other.error() == crypto::error::invalid_signature); + } + + for (std::uint8_t const id : {4, 5, 255}) { + auto bad_id = *signature; + bad_id[64] = id; + BOOST_TEST(refused_as_signature(secp::recover(bad_id, hash))); + } + } + BOOST_TEST(other_keys > 0); +} + +// From libsecp256k1's src/modules/recovery/tests_impl.h, test_ecdsa_recovery_edge_cases +// (v0.8.0, MIT; Copyright (c) 2013-2015 Pieter Wuille): its message, and a signature made with +// the secret key 0 and a fixed nonce, which recovers a key with id 1 alone. +constexpr hash_bytes edge_message = {'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 'v', + 'e', 'r', 'y', ' ', 's', 'e', 'c', 'r', 'e', 't', ' ', + 'm', 'e', 's', 's', 'a', 'g', 'e', '.', '.', '.'}; +constexpr std::array edge_signature = { + 0x67, 0xCB, 0x28, 0x5F, 0x9C, 0xD1, 0x94, 0xE8, 0x40, 0xD6, 0x29, 0x39, 0x7A, 0xF5, 0x56, 0x96, + 0x62, 0xFD, 0xE4, 0x46, 0x49, 0x99, 0x59, 0x63, 0x17, 0x9A, 0x7D, 0xD1, 0x7B, 0xD2, 0x35, 0x32, + 0x4B, 0x1B, 0x7D, 0xF3, 0x4C, 0xE1, 0xF6, 0x8E, 0x69, 0x4F, 0xF6, 0xF1, 0x1A, 0xC7, 0x51, 0xDD, + 0x7D, 0xD7, 0x3E, 0x38, 0x7E, 0xE4, 0xFC, 0x86, 0x6E, 0x1B, 0xE8, 0xEC, 0xC7, 0xDD, 0x95, 0x57, +}; + +// (r, s) as two small numbers, then the id. +recoverable small_signature(std::uint8_t r, std::uint8_t s, std::uint8_t id) { + recoverable signature{}; + signature[31] = r; + signature[63] = s; + signature[64] = id; + return signature; +} + +void edge_cases() { + for (std::uint8_t id = 0; id < 4; ++id) { + recoverable signature{}; + std::ranges::copy(edge_signature, signature.begin()); + signature[64] = id; + auto const recovered = secp::recover(signature, edge_message); + if (id == 1) { + BOOST_TEST(recovered.has_value()); + } else { + BOOST_TEST(refused_as_signature(recovered)); + } + } + + // (r, s) = (4, 4) recovers a key with each id, and verifies under each. + for (std::uint8_t id = 0; id < 4; ++id) { + auto const signature = small_signature(4, 4, id); + auto const recovered = secp::recover(signature, edge_message); + if (!BOOST_TEST(recovered.has_value())) { + continue; + } + auto const encoded = secp::serialize_public_key(*recovered); + BOOST_TEST(secp::verify_ecdsa(std::span(signature).first<64>(), edge_message, encoded) + .has_value()); + } + + // (1, 1) recovers with id 0, and verifies. + auto const one_one = small_signature(1, 1, 0); + auto const recovered = secp::recover(one_one, edge_message); + if (BOOST_TEST(recovered.has_value())) { + BOOST_TEST(secp::verify_ecdsa(std::span(one_one).first<64>(), edge_message, + secp::serialize_public_key(*recovered)) + .has_value()); + } + + // r = 0 or s = 0: no key. + BOOST_TEST(refused_as_signature(secp::recover(small_signature(0, 1, 0), edge_message))); + BOOST_TEST(refused_as_signature(secp::recover(small_signature(1, 0, 0), edge_message))); + BOOST_TEST(refused_as_signature(secp::recover(small_signature(0, 0, 0), edge_message))); + + // r or s equal to the group order n, or above it: refused by the parser. + auto const order = + test::from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); + auto r_is_n = small_signature(0, 4, 0); + std::ranges::copy(order, r_is_n.begin()); + BOOST_TEST(refused_as_signature(secp::recover(r_is_n, edge_message))); + auto s_is_n = small_signature(4, 0, 0); + std::ranges::copy(order, s_is_n.begin() + 32); + BOOST_TEST(refused_as_signature(secp::recover(s_is_n, edge_message))); + recoverable all_ones{}; + all_ones.fill(0xff); + all_ones[64] = 0; + BOOST_TEST(refused_as_signature(secp::recover(all_ones, edge_message))); +} + +// libsecp256k1's own ECDSA signature with RFC 6979's nonce and the given ndata, through its C +// API, on a context of its own. +std::array reference_signature(secp256k1_context const* context, + hash_bytes const& secret, hash_bytes const& hash, + hash_bytes const* extra) { + secp256k1_ecdsa_signature signature{}; + BOOST_TEST_EQ(secp256k1_ecdsa_sign(context, &signature, hash.data(), secret.data(), nullptr, + extra == nullptr ? nullptr : extra->data()), + 1); + std::array compact{}; + secp256k1_ecdsa_signature_serialize_compact(context, compact.data(), &signature); + return compact; +} + +// The hedged form: different entropy gives different signatures, both valid, each libsecp256k1's +// own for that entropy; 32 zero bytes are mixed in too. +void hedged() { + // NOLINTNEXTLINE(bugprone-signed-bitwise): libsecp256k1's macro shifts a signed constant + secp256k1_context* const context = secp256k1_context_create(SECP256K1_CONTEXT_NONE); + if (!BOOST_TEST(context != nullptr)) { + return; + } + std::mt19937_64 generator(0x4ed6edULL); + for (int round = 0; round < 16; ++round) { + hash_bytes secret{}; + auto const key = draw(generator, secret); + auto const hash = draw_hash(generator); + auto const first_entropy = draw_hash(generator); + auto second_entropy = first_entropy; + second_entropy[31] ^= 0x01; + hash_bytes const zero{}; + + auto const first = key.sign_ecdsa(hash, first_entropy); + auto const second = key.sign_ecdsa(hash, second_entropy); + auto const zeroed = key.sign_ecdsa(hash, zero); + auto const plain = key.sign_ecdsa(hash); + if (!BOOST_TEST(first && second && zeroed && plain)) { + continue; + } + BOOST_TEST(*first != *second); + BOOST_TEST(*zeroed != *plain); + BOOST_TEST(*first != *plain); + auto const public_key = *key.public_key(); + BOOST_TEST(secp::verify_ecdsa(*first, hash, public_key).has_value()); + BOOST_TEST(secp::verify_ecdsa(*second, hash, public_key).has_value()); + BOOST_TEST(secp::verify_ecdsa(*zeroed, hash, public_key).has_value()); + BOOST_TEST(*first == reference_signature(context, secret, hash, &first_entropy)); + BOOST_TEST(*second == reference_signature(context, secret, hash, &second_entropy)); + BOOST_TEST(*zeroed == reference_signature(context, secret, hash, &zero)); + BOOST_TEST(*plain == reference_signature(context, secret, hash, nullptr)); + // Hedged twice with the same entropy, the signature is the same: the hedging is + // deterministic given its input. + BOOST_TEST(key.sign_ecdsa(hash, first_entropy).value() == *first); + } + secp256k1_context_destroy(context); +} + +// A moved-from key pair answers invalid_state from the new members, as from every other. +void moved_from() { + auto made = secp::keypair::make(std::array{7}); + if (!BOOST_TEST(made.has_value())) { + return; + } + secp::keypair source = std::move(*made); + secp::keypair const target = std::move(source); + hash_bytes const hash{}; + BOOST_TEST(source.sign_recoverable(hash).error() == crypto::error::invalid_state); + BOOST_TEST(source.sign_ecdsa(hash, hash).error() == crypto::error::invalid_state); + BOOST_TEST(source.public_key_uncompressed().error() == crypto::error::invalid_state); + test::expect_empty_keypair(source); + BOOST_TEST(target.sign_recoverable(hash).has_value()); +} + +} // namespace + +int main() { + round_trips(); + edge_cases(); + hedged(); + moved_from(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/support/secp256k1_checks.hpp b/test/support/secp256k1_checks.hpp index 8f3dc61c..cffa0bf3 100644 --- a/test/support/secp256k1_checks.hpp +++ b/test/support/secp256k1_checks.hpp @@ -37,7 +37,10 @@ inline void expect_empty_keypair(webcpp::crypto::curves::secp256k1::keypair& key BOOST_TEST(key.xonly_public_key().error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.public_key().error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.sign_schnorr(message, aux).error() == webcpp::crypto::error::invalid_state); + BOOST_TEST(key.public_key_uncompressed().error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.sign_ecdsa(message).error() == webcpp::crypto::error::invalid_state); + BOOST_TEST(key.sign_ecdsa(message, aux).error() == webcpp::crypto::error::invalid_state); + BOOST_TEST(key.sign_recoverable(message).error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.tweak_xonly(tweak).error() == webcpp::crypto::error::invalid_state); if (BOOST_TEST(live.has_value())) { auto const peer = *live->public_key(); From 294bd2b4190bb3cfc0cf89875e3fc11e39f4414b Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 14:32:55 -0300 Subject: [PATCH 05/54] crypto: the curves page and its Ethereum rule say what Tasks 2.1 and 2.2 added; recover reads the canary before the id's check; the changelog's secp256k1 line reads plainly --- doc/changelog.adoc | 2 +- doc/curves.adoc | 11 ++++++----- doc/llms.txt | 2 +- doc/tables/crypto.json | 2 +- include/webcpp/crypto/curves/secp256k1.hpp | 2 +- 5 files changed, 10 insertions(+), 9 deletions(-) diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 68b0593e..654d1b2d 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -20,7 +20,7 @@ of every version are on webcpp's index page. * Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default, one default per family and target, and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). -* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, hedged and recoverable, recover, public_key in both forms, ECDH in three forms as self-wiping secrets, strict DER, low-S, x-only tweaks. +* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDSA also hedged or recoverable, keys recovered from signatures, public_key in both forms, three self-wiping ECDH forms, strict DER, low-S, x-only tweaks. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. * Added ciphers::secretbox and secretbox_xchacha20poly1305, without additional data, hybrid::box, box_xchacha20poly1305 and sealed_box (failed seals and opens zeroing data), and curves::x25519::kx_keypair (crypto_kx) on libsodium, refusing peer keys of small order. diff --git a/doc/curves.adoc b/doc/curves.adoc index b2ff026a..489dafe8 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -19,11 +19,12 @@ The namespace `webcpp::crypto::curves` holds three curves in this version, the three columns of the table below. The first is secp256k1 (link:https://www.secg.org/sec2-v2.pdf[SEC 2]; link:https://en.bitcoin.it/wiki/Secp256k1[Bitcoin Wiki]), the curve of Bitcoin, Ethereum and Nostr. This version covers Bitcoin's keys and signatures, -Nostr's event signatures (NIP-01) and the verification of Ethereum's ECDSA -signatures with a known key. It does not cover Ethereum's recoverable -signatures (the recovery id `v`, and the recovery of a public key from a -signature), nor ECDH in the raw x-coordinate form that Nostr's encrypted -messages (NIP-44) use. The second is Ed25519, RFC 8032's signatures on +Nostr's event signatures (NIP-01) and the raw x-coordinate ECDH of its +encrypted messages (NIP-44, <>), and Ethereum's ECDSA: +recoverable signatures, the recovery of a signer's public key from a +signature, and the uncompressed key (<>). +Ethereum's `v` encoding of the recovery id, the hash it signs, its +transactions and its addresses are a domain library's. The second is Ed25519, RFC 8032's signatures on edwards25519, with Ed25519ph for a message given in pieces (link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032]; <>). The third is X25519, RFC 7748's key agreement on Curve25519, the same curve in diff --git a/doc/llms.txt b/doc/llms.txt index 39eae8b8..0f388361 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -185,7 +185,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Records: each stream its own key](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): records numbered from 0 with the number as IV are safe only under a key used for that one stream: derive a key per stream (HKDF of the storage key with a random salt) or draw one; never number two streams' records under one key. - [ECDH's form](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ecdh): `keypair::ecdh` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point; protocols that take the raw x coordinate, such as Nostr's NIP-44 ([Nostr NIP-44, encrypted payloads](https://github.com/nostr-protocol/nips/blob/master/44.md)), need `ecdh_x`. Both sides must use the same form, or they derive different keys. Derive keys with a KDF, never use a shared secret directly. - [The x-only tweak is not BIP 32](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly` is BIP 341's even-y arithmetic ([BIP 341, Taproot](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki)); BIP 32's child derivation needs a tweak of the full key, which this version does not offer ([BIP 32, hierarchical deterministic wallets](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)). -- [Ethereum](https://webcpporg.github.io/libs/crypto/#crypto-curves): this version verifies Ethereum's ECDSA signatures with a known key but has no recoverable signature (no recovery id `v`, no public key recovery) and no uncompressed public key output, so it cannot sign Ethereum transactions or derive addresses. +- [Ethereum](https://webcpporg.github.io/libs/crypto/#crypto-curves): this version signs and verifies Ethereum's ECDSA, recoverable signatures included (`keypair::sign_recoverable`), recovers a signer's public key from a signature and a hash (`recover`), and writes the uncompressed key ([The Ethereum yellow paper, appendix F: ECDSA on secp256k1](https://ethereum.github.io/yellowpaper/paper.pdf)); the recovery id's `v` encoding, the hash Ethereum signs, transactions and addresses are a domain library's. - [Compare secrets in constant time](https://webcpporg.github.io/libs/crypto/#crypto-equal): compare a tag, a MAC or a token with `equal`, never `==` or `memcmp` ([CWE-208, observable timing discrepancy](https://cwe.mitre.org/data/definitions/208.html)). - [Secrets come from random_device](https://webcpporg.github.io/libs/crypto/#crypto-entropy): keys, IVs and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ([CWE-338, a weak generator used for security](https://cwe.mitre.org/data/definitions/338.html)). - [Never reuse a nonce under one ChaCha20-Poly1305 key](https://webcpporg.github.io/libs/crypto/#crypto-chacha): two messages under one key and one nonce reveal the XOR of their plaintexts and let an attacker forge tags ([RFC 8439, section 4: a nonce is never repeated under one key](https://www.rfc-editor.org/rfc/rfc8439#section-4)). `xchacha20_poly1305` and the secret boxes: draw 24 bytes at random per message. `chacha20_poly1305`: number the 12-byte nonces with a counter that never repeats, a restart included, or draw them at random for at most 2^32 messages per key, AES-GCM's bound for random 12-byte IVs ([NIST SP 800-38D, GCM and GMAC](https://csrc.nist.gov/pubs/sp/800/38/d/final)). `chacha20_poly1305_original`: a counter only, its 8 bytes are too short to draw. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 0f4fc2a4..b3ddf5f2 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -857,7 +857,7 @@ {"title": "Records: each stream its own key", "section": "crypto-gcm-incremental", "text": "records numbered from 0 with the number as IV are safe only under a key used for that one stream: derive a key per stream (HKDF of the storage key with a random salt) or draw one; never number two streams' records under one key."}, {"title": "ECDH's form", "section": "crypto-secp256k1-ecdh", "text": "`keypair::ecdh` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point; protocols that take the raw x coordinate, such as Nostr's NIP-44 ({nip44}), need `ecdh_x`. Both sides must use the same form, or they derive different keys. Derive keys with a KDF, never use a shared secret directly."}, {"title": "The x-only tweak is not BIP 32", "section": "crypto-wallets-taproot", "text": "`tweak_xonly` is BIP 341's even-y arithmetic ({bip341}); BIP 32's child derivation needs a tweak of the full key, which this version does not offer ({bip32})."}, - {"title": "Ethereum", "section": "crypto-curves", "text": "this version verifies Ethereum's ECDSA signatures with a known key but has no recoverable signature (no recovery id `v`, no public key recovery) and no uncompressed public key output, so it cannot sign Ethereum transactions or derive addresses."}, + {"title": "Ethereum", "section": "crypto-curves", "text": "this version signs and verifies Ethereum's ECDSA, recoverable signatures included (`keypair::sign_recoverable`), recovers a signer's public key from a signature and a hash (`recover`), and writes the uncompressed key ({ethereum}); the recovery id's `v` encoding, the hash Ethereum signs, transactions and addresses are a domain library's."}, {"title": "Compare secrets in constant time", "section": "crypto-equal", "text": "compare a tag, a MAC or a token with `equal`, never `==` or `memcmp` ({cwe208})."}, {"title": "Secrets come from random_device", "section": "crypto-entropy", "text": "keys, IVs and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ({cwe338})."}, {"title": "Never reuse a nonce under one ChaCha20-Poly1305 key", "section": "crypto-chacha", "text": "two messages under one key and one nonce reveal the XOR of their plaintexts and let an attacker forge tags ({rfc8439-nonce}). `xchacha20_poly1305` and the secret boxes: draw 24 bytes at random per message. `chacha20_poly1305`: number the 12-byte nonces with a counter that never repeats, a restart included, or draw them at random for at most 2^32 messages per key, AES-GCM's bound for random 12-byte IVs ({sp800-38d}). `chacha20_poly1305_original`: a counter only, its 8 bytes are too short to draw."}, diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index bc6a40af..2cd9e01f 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -854,12 +854,12 @@ template std::span message_hash) noexcept { static_assert(webcpp::crypto::detail::secp256k1_backend, WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); // libsecp256k1 checks the id with ARG_CHECK, whose callback aborts: refused first here. int const recovery_id = recoverable_signature[64]; if (recovery_id > 3) { return error::invalid_signature; } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; secp256k1_ecdsa_recoverable_signature parsed_value{}; From b3dce1c02c43468a2561d9a6b2073657078b44b7 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 16:29:33 -0300 Subject: [PATCH 06/54] crypto: the curves page's paragraph on Ethereum wraps at 80 columns, as the rest of it does --- doc/curves.adoc | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/doc/curves.adoc b/doc/curves.adoc index 489dafe8..fe5d0d05 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -24,17 +24,17 @@ encrypted messages (NIP-44, <>), and Ethereum's ECDSA: recoverable signatures, the recovery of a signer's public key from a signature, and the uncompressed key (<>). Ethereum's `v` encoding of the recovery id, the hash it signs, its -transactions and its addresses are a domain library's. The second is Ed25519, RFC 8032's signatures on -edwards25519, with Ed25519ph for a message given in pieces -(link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032]; <>). The -third is X25519, RFC 7748's key agreement on Curve25519, the same curve in -another form, with the conversion of an Ed25519 key to it -(link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748]; <>), and -libsodium's key exchange on it, `crypto_kx` (<>). A -program chooses a curve for compatibility: a signature on one curve is checked -only with that curve, and the curve of passkeys and TLS certificates, P-256, is -another, which this version does not offer. Ed25519's and X25519's keys leave a -program, and enter it, in the standard forms OpenSSL and WebCrypto use, SPKI -and PKCS#8, as DER or PEM text (<>). +transactions and its addresses are a domain library's. The second is Ed25519, +RFC 8032's signatures on edwards25519, with Ed25519ph for a message given in +pieces (link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032]; +<>). The third is X25519, RFC 7748's key agreement on +Curve25519, the same curve in another form, with the conversion of an Ed25519 +key to it (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748]; +<>), and libsodium's key exchange on it, `crypto_kx` +(<>). A program chooses a curve for compatibility: a signature on one +curve is checked only with that curve, and the curve of passkeys and TLS +certificates, P-256, is another, which this version does not offer. Ed25519's +and X25519's keys leave a program, and enter it, in the standard forms OpenSSL +and WebCrypto use, SPKI and PKCS#8, as DER or PEM text (<>). include::generated/namespace-curves.adoc[] From 9bbad30cf7312ea35e06646eb10b50be722cc2ca Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 16:59:43 -0300 Subject: [PATCH 07/54] crypto: secp256k1's tweaks, negation and combination, and its SPKI and PKCS#8 --- doc/changelog.adoc | 2 +- doc/generated/backends-key_formats.adoc | 30 + doc/generated/backends-key_tweaks.adoc | 30 + doc/generated/matrix.adoc | 22 + doc/generated/namespace-curves.adoc | 6 +- doc/generated/use-cases.adoc | 7 + doc/llms.txt | 17 +- doc/memory.adoc | 7 +- doc/secp256k1.adoc | 150 +++- doc/tables/crypto.json | 34 +- doc/testing.adoc | 14 +- doc/wallets.adoc | 5 +- example/Jamfile | 4 + example/key_tweak.cpp | 132 ++++ example/key_tweak.expected | 2 + include/webcpp/crypto.hpp | 2 + include/webcpp/crypto/backends/secp256k1.hpp | 5 +- include/webcpp/crypto/curves/secp256k1.hpp | 76 +- .../crypto/curves/secp256k1/formats.hpp | 245 +++++++ .../webcpp/crypto/curves/secp256k1/tweak.hpp | 271 +++++++ test/Jamfile | 14 + test/crypto_secp256k1_test.cpp | 8 +- test/secp256k1_allocation_test.cpp | 39 +- test/secp256k1_formats_test.cpp | 689 ++++++++++++++++++ test/secp256k1_tweak_test.cpp | 345 +++++++++ test/support/secp256k1_checks.hpp | 4 + test/windows_h_after_test.cpp | 2 + test/windows_h_before_test.cpp | 2 + 28 files changed, 2128 insertions(+), 36 deletions(-) create mode 100644 doc/generated/backends-key_formats.adoc create mode 100644 doc/generated/backends-key_tweaks.adoc create mode 100644 example/key_tweak.cpp create mode 100644 example/key_tweak.expected create mode 100644 include/webcpp/crypto/curves/secp256k1/formats.hpp create mode 100644 include/webcpp/crypto/curves/secp256k1/tweak.hpp create mode 100644 test/secp256k1_formats_test.cpp create mode 100644 test/secp256k1_tweak_test.cpp diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 654d1b2d..4207bcef 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -20,7 +20,7 @@ of every version are on webcpp's index page. * Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default, one default per family and target, and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). -* Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDSA also hedged or recoverable, keys recovered from signatures, public_key in both forms, three self-wiping ECDH forms, strict DER, low-S, x-only tweaks. +* Added curves::secp256k1: key pairs, BIP340, hedged and recoverable ECDSA, keys recovered from signatures, three self-wiping ECDH forms, strict DER, low-S, tweaks, negation, combination, SPKI and PKCS#8. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. * Added ciphers::secretbox and secretbox_xchacha20poly1305, without additional data, hybrid::box, box_xchacha20poly1305 and sealed_box (failed seals and opens zeroing data), and curves::x25519::kx_keypair (crypto_kx) on libsodium, refusing peer keys of small order. diff --git a/doc/generated/backends-key_formats.adoc b/doc/generated/backends-key_formats.adoc new file mode 100644 index 00000000..895543f6 --- /dev/null +++ b/doc/generated/backends-key_formats.adoc @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+curves::secp256k1::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsecp256k1 +|`+/third_party//secp256k1+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+secp256k1_formats+`, `+secp256k1_formats_openssl+`) +|=== + +A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsecp256k1 +|=== diff --git a/doc/generated/backends-key_tweaks.adoc b/doc/generated/backends-key_tweaks.adoc new file mode 100644 index 00000000..d47d8092 --- /dev/null +++ b/doc/generated/backends-key_tweaks.adoc @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+curves::secp256k1::seckey_tweak_add+`, `+seckey_tweak_mul+`, `+seckey_negate+`, `+pubkey_tweak_add+`, `+pubkey_tweak_mul+`, `+pubkey_negate+`, `+pubkey_combine+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsecp256k1 +|`+/third_party//secp256k1+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+secp256k1_tweak+`) +|=== + +A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsecp256k1 +|=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 8f21420d..43bc324e 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -200,6 +200,16 @@ |libsecp256k1 |native, wasip2, wasip3, emscripten |`+secp256k1_keys+` + +|`+curves::secp256k1::seckey_tweak_add+`, `+seckey_tweak_mul+`, `+seckey_negate+`, `+pubkey_tweak_add+`, `+pubkey_tweak_mul+`, `+pubkey_negate+`, `+pubkey_combine+` +|libsecp256k1 +|native, wasip2, wasip3, emscripten +|`+secp256k1_tweak+` + +|`+curves::secp256k1::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|libsecp256k1 +|native, wasip2, wasip3, emscripten +|`+secp256k1_formats+`, `+secp256k1_formats_openssl+` |=== The same, by target: the backends each operation runs on. @@ -387,4 +397,16 @@ The same, by target: the backends each operation runs on. |libsecp256k1 |libsecp256k1 |libsecp256k1 + +|`+curves::secp256k1::seckey_tweak_add+`, `+seckey_tweak_mul+`, `+seckey_negate+`, `+pubkey_tweak_add+`, `+pubkey_tweak_mul+`, `+pubkey_negate+`, `+pubkey_combine+` +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 + +|`+curves::secp256k1::encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+` +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 |=== diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index 50190144..0ceb7a6a 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -12,7 +12,7 @@ |Curve |`secp256k1` |`ed25519` |`x25519` |What it does -|BIP 340 Schnorr and ECDSA signatures, hedged and recoverable ECDSA, the recovery of a signer's key, ECDH in three forms, public keys in both forms, the x-only tweak +|BIP 340 Schnorr and ECDSA signatures, hedged and recoverable ECDSA, the recovery of a signer's key, ECDH in three forms, public keys in both forms, the x-only tweak, the tweaks, negation and combination of keys, SPKI and PKCS#8 |Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair |Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction @@ -22,7 +22,7 @@ |about 128 bits (link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)]) |Key sizes -|secret 32 bytes; public 33 bytes compressed, 65 bytes uncompressed (link:https://www.secg.org/sec1-v2.pdf[SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings]), 32 bytes x-only +|secret 32 bytes; public 33 bytes compressed, 65 bytes uncompressed (link:https://www.secg.org/sec1-v2.pdf[SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings]), 32 bytes x-only; SPKI 56 or 88 bytes (link:https://www.rfc-editor.org/rfc/rfc5480[RFC 5480, Elliptic Curve Cryptography Subject Public Key Information]), PKCS#8 135 bytes (link:https://www.rfc-editor.org/rfc/rfc5208[RFC 5208, PKCS #8: Private-Key Information Syntax], link:https://www.rfc-editor.org/rfc/rfc5915[RFC 5915, Elliptic Curve Private Key Structure]) |secret 32 bytes (the seed); public 32 bytes |secret 32 bytes; public 32 bytes @@ -57,7 +57,7 @@ |yes: X25519 (link:https://www.w3.org/TR/WebCryptoAPI/[W3C Web Cryptography API]) |Choose it for compatibility with -|Bitcoin's keys and signatures; Nostr's event signatures (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]); Ethereum's recoverable signatures and uncompressed keys (link:https://ethereum.github.io/yellowpaper/paper.pdf[The Ethereum yellow paper, appendix F: ECDSA on secp256k1]), the address hashing being a domain library's. Not in this version: BIP 32's derivation (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32, hierarchical deterministic wallets]) +|Bitcoin's keys and signatures; Nostr's event signatures (link:https://github.com/nostr-protocol/nips/blob/master/01.md[Nostr NIP-01, events signed with BIP 340 on secp256k1]); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages (link:https://github.com/nostr-protocol/nips/blob/master/44.md[Nostr NIP-44, encrypted payloads]); Ethereum's recoverable signatures and uncompressed keys (link:https://ethereum.github.io/yellowpaper/paper.pdf[The Ethereum yellow paper, appendix F: ECDSA on secp256k1]), the address hashing being a domain library's; BIP 32's tweaks of the full key, its derivation of the tweak being a domain library's (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32, hierarchical deterministic wallets]); keys exchanged with OpenSSL as SPKI or PKCS#8 (link:https://www.rfc-editor.org/rfc/rfc5480[RFC 5480, Elliptic Curve Cryptography Subject Public Key Information], link:https://www.rfc-editor.org/rfc/rfc5915[RFC 5915, Elliptic Curve Private Key Structure]) |SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's |TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` (link:https://doc.libsodium.org/key_exchange[libsodium's documentation, key exchange]). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested (link:https://github.com/C2SP/wycheproof[Project Wycheproof, test vectors for cryptographic libraries]) |=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 24a9d168..109651f8 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -92,6 +92,13 @@ `+/third_party//secp256k1+` |<> +|Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's) +|In `+curves::secp256k1+`: `+seckey_tweak_add+`, `+pubkey_tweak_add+` +|libsecp256k1 +|`+/webcpp/crypto//crypto+` + +`+/third_party//secp256k1+` +|<> + |Make and keep a wallet's key |In `+curves::secp256k1+`: `+keypair::make+`, `+xonly_public_key+`, `+public_key+`; `+aes256_gcm+` at rest |libsecp256k1, and AES-GCM's default diff --git a/doc/llms.txt b/doc/llms.txt index 0f388361..82699a6f 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -123,6 +123,19 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [curves::secp256k1::public_key, parse_public_key, serialize_public_key](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-keys): A parsed public key, read from and written to its compressed or uncompressed form. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. - parse_public_key: Parses a public key: 33 bytes with prefix 02 or 03, or 65 with prefix 04 (X9.62's hybrid prefixes 06 and 07 are refused, as everywhere in crypto). - serialize_public_key: Serialises a public key in `Form`. +- [curves::secp256k1::seckey_tweak_add, seckey_tweak_mul, seckey_negate, pubkey_tweak_add, pubkey_tweak_mul, pubkey_negate, pubkey_combine](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-tweaks): A secret or public key plus or times a tweak, its negation, and the sum of public keys. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's). + - seckey_tweak_add: A secret key plus a tweak modulo the group order (`secp256k1_ec_seckey_tweak_add`). + - seckey_tweak_mul: A secret key times a tweak modulo the group order (`secp256k1_ec_seckey_tweak_mul`). + - seckey_negate: The group order minus a secret key (`secp256k1_ec_seckey_negate`). + - pubkey_tweak_add: A public key P plus t times the generator (`secp256k1_ec_pubkey_tweak_add`). + - pubkey_tweak_mul: A public key P times t (`secp256k1_ec_pubkey_tweak_mul`). + - pubkey_negate: The negation -P of a public key (`secp256k1_ec_pubkey_negate`), which never fails. + - pubkey_combine: The sum of public keys (`secp256k1_ec_pubkey_combine`), in a workspace the caller lends for libsecp256k1's array of pointers. +- [curves::secp256k1::encode_spki, decode_spki, encode_pkcs8, decode_pkcs8](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-formats): A public key's SPKI and a key pair's PKCS#8, in OpenSSL's forms, decoded strictly. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. + - encode_spki: Writes a public key's SPKI (RFC 5480, the secp256k1 OID) into `output_bytes`. + - decode_spki: The public key of an SPKI in exactly one of the two forms `encode_spki` writes. + - encode_pkcs8: Writes a key pair's PKCS#8 into `output_bytes`, in OpenSSL's form: version 0, and RFC 5915's ECPrivateKey of version 1 with the uncompressed public key and no parameters inside. + - decode_pkcs8: The key pair of a PKCS#8 that is exactly what `encode_pkcs8` writes for its secret, made as `basic_keypair::make` makes it. ## webcpp::crypto::hybrid @@ -184,7 +197,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [A failed open zeroes data](https://webcpporg.github.io/libs/crypto/#crypto-gcm-rules): when the tag does not match, `open` returns `authentication_failed` and zeroes the whole of `data`; keep a copy of the ciphertext if it is needed after a failure. There is no incremental open: a large message is split into records. - [Records: each stream its own key](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): records numbered from 0 with the number as IV are safe only under a key used for that one stream: derive a key per stream (HKDF of the storage key with a random salt) or draw one; never number two streams' records under one key. - [ECDH's form](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ecdh): `keypair::ecdh` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point; protocols that take the raw x coordinate, such as Nostr's NIP-44 ([Nostr NIP-44, encrypted payloads](https://github.com/nostr-protocol/nips/blob/master/44.md)), need `ecdh_x`. Both sides must use the same form, or they derive different keys. Derive keys with a KDF, never use a shared secret directly. -- [The x-only tweak is not BIP 32](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly` is BIP 341's even-y arithmetic ([BIP 341, Taproot](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki)); BIP 32's child derivation needs a tweak of the full key, which this version does not offer ([BIP 32, hierarchical deterministic wallets](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)). +- [The x-only tweak is not BIP 32](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly` is BIP 341's even-y arithmetic ([BIP 341, Taproot](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki)); BIP 32's child derivation tweaks the full key, with `seckey_tweak_add` and `pubkey_tweak_add`, and computes the tweak with HMAC-SHA-512, a domain library's ([BIP 32, hierarchical deterministic wallets](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)). - [Ethereum](https://webcpporg.github.io/libs/crypto/#crypto-curves): this version signs and verifies Ethereum's ECDSA, recoverable signatures included (`keypair::sign_recoverable`), recovers a signer's public key from a signature and a hash (`recover`), and writes the uncompressed key ([The Ethereum yellow paper, appendix F: ECDSA on secp256k1](https://ethereum.github.io/yellowpaper/paper.pdf)); the recovery id's `v` encoding, the hash Ethereum signs, transactions and addresses are a domain library's. - [Compare secrets in constant time](https://webcpporg.github.io/libs/crypto/#crypto-equal): compare a tag, a MAC or a token with `equal`, never `==` or `memcmp` ([CWE-208, observable timing discrepancy](https://cwe.mitre.org/data/definitions/208.html)). - [Secrets come from random_device](https://webcpporg.github.io/libs/crypto/#crypto-entropy): keys, IVs and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ([CWE-338, a weak generator used for security](https://cwe.mitre.org/data/definitions/338.html)). @@ -206,6 +219,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Agree on a key with a peer through a relay that sees everything](https://webcpporg.github.io/libs/crypto/#crypto-p2p-session): `keypair::ecdh` (SHA-256 of the shared point), then HKDF on Boost.Hash2 and `aes256_gcm` (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/ecdh_session.cpp. - [Derive a Nostr direct message's conversation key (NIP-44; the format is a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ecdh): `keypair::ecdh_x`, then HKDF on Boost.Hash2 (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdh_x_coordinate.cpp. - [Find who signed a message or a transaction without being sent their key (Ethereum's signatures)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-recovery): `keypair::sign_recoverable`, `recover` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/recover_signer.cpp. +- [Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-tweaks): `seckey_tweak_add`, `pubkey_tweak_add` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/key_tweak.cpp. - [Make and keep a wallet's key](https://webcpporg.github.io/libs/crypto/#crypto-wallets-key): `keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/wallet_key.cpp. - [Sign a Bitcoin SegWit v0 input (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-der): `sign_ecdsa`, `to_der`, `normalize_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdsa_der.cpp. - [Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly`, `keypair::tweak_xonly` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/taproot_tweak.cpp. @@ -238,6 +252,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/failure_reasons.cpp: Shows the three ways AES-GCM can refuse a message: a tampered ciphertext, an IV of the wrong size and a tag of the wrong size. A program must tell the first from the others: only authentication_failed means someone changed the data, and open then wipes the plaintext so that no unauthenticated bytes are ever used. - example/file_share.cpp: A file-sharing app shares a file with a recipient it knows only by an X25519 public key: the file is sealed once in a secret box under a key drawn for this file, and that file key is sealed to the recipient's public key in a sealed box. The upload holds both; only the recipient's secret key opens the file key, and the file key opens the file. Prints what the recipient reads, the sizes on the wire, and the refusals of a changed upload and of another key pair. - example/key_formats.cpp: Reads RFC 8410's Ed25519 private key in PEM (section 10.3), as OpenSSL or WebCrypto export it, writes its public key as PEM, which is the RFC's section 10.1 to the character, and signs with it; writes an X25519 key pair's public key the same way; and refuses the RFC's version 2 of the private key, which carries the public key too. Prints the PEM texts and each verdict. +- example/key_tweak.cpp: A watch-only wallet: a server that holds the wallet's public key and no secret gives each payment a fresh key, and the signing device, which holds the secret, derives the same keys' secrets. Both add the same tweak, one to the public key and one to the secret key; the device's tweaked key pair signs (BIP 340), and the signature verifies under the server's tweaked public key. The tweak here is an HMAC-SHA-256 of the public key and the payment's number under a chain code both sides share and no one else sees; BIP 32 derives such tweaks its own way, with HMAC-SHA-512, and is a domain library's. - example/kx_session.cpp: A chat app's client and server, each with a crypto_kx key pair made from libsodium's kx test's seeds, exchange public keys and compute their session keys; the client seals a message with its transmit key and the server opens it with its receive key, on ChaCha20-Poly1305; a peer key of low order is refused. Prints the public keys and the client's session keys in hex. - example/openssl_memory.cpp: Sends every allocation of OpenSSL's to the program's own memory resource, natively, then seals and opens one block with AES-256-GCM on OpenSSL, on a worker thread as an audio engine's or a server's would. Built with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, /webcpp/crypto//openssl and threads (example/Jamfile). - example/order_reference.cpp: Turns a sequential order id into an opaque 16-byte reference with the raw AES block cipher, and back. Customers then cannot guess other orders' numbers. This is NOT authenticated encryption: a forged reference still decrypts, to garbage, so the program checks the padding. diff --git a/doc/memory.adoc b/doc/memory.adoc index 7e62d784..c53a90d5 100644 --- a/doc/memory.adoc +++ b/doc/memory.adoc @@ -16,8 +16,11 @@ key pair. Every buffer is the caller's. * *Nothing allocates per message, on any backend:* `seal`, `open`, `begin_seal`, `update`, `result`, `encrypt`, `decrypt`, `fill`, the signatures (hedged and recoverable too), `ecdh`, `ecdh_x`, `ecdh_point`, the verifications, -`recover`, `parse_public_key` and `serialize_public_key`. The counting tests of -`test/` prove it, every `operator new` and the C library's allocator counted. +`recover`, `parse_public_key`, `serialize_public_key`, the tweaks and negations, +`pubkey_combine` (in a `workspace` the caller lends), and the SPKI and PKCS#8 +encoders and decoders (`decode_pkcs8` makes a key pair, whose context is the one +allocation above). The counting tests of `test/` prove it, every `operator new` +and the C library's allocator counted. * *BearSSL and ctaes allocate nothing,* `make` included: the key schedule lives inside the object. * *OpenSSL's `make` allocates its cipher context through OpenSSL's own diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index c798729d..278ef752 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -46,9 +46,12 @@ check signatures with a public key alone, and `recover` finds the key from a recoverable signature; `parse_public_key` and `serialize_public_key` read and write a `public_key` (<>); `to_der`, `from_der` (strict DER) and `normalize_ecdsa` convert ECDSA's DER and low-S forms; and -`tweak_xonly` tweaks an x-only public key. Every function reads libsecp256k1's -canary, so that a program linked with another build of the library does not -link. +`tweak_xonly` tweaks an x-only public key. Two more headers hold the tweaks, +negation and combination of whole keys +(``, <>) +and the keys' SPKI and PKCS#8 (``, +<>). Every function reads libsecp256k1's canary, so +that a program linked with another build of the library does not link. include::generated/backends-keypair.adoc[] @@ -192,8 +195,8 @@ or `point_form::uncompressed`); a key pair gives its own key in both forms, `public_key` and `public_key_uncompressed`. Two `public_key` values compare with `==`, and order with `+<=>+` as their compressed encodings do, the order MuSig2's key sorting uses -(link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327]). A `public_key` holds nothing secret and is copied -freely. +(link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327]). +A `public_key` holds nothing secret and is copied freely. include::generated/backends-public_key.adoc[] @@ -220,11 +223,11 @@ made it (link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow paper, appendix F]). An ECDSA signature fits up to four keys, and the recovery id, 0 to 3, names the one that made it -(link:https://www.secg.org/sec1-v2.pdf[SEC 1, section 4.1.6]). `sign_recoverable` -writes 65 bytes, r, s and the id, with the same r and s as `sign_ecdsa`, and -`recover` returns the `public_key` from those 65 bytes and the hash. It -refuses with `invalid_signature` an id above 3, an r or an s not below the -group order, and a signature from which no key is recovered. +(link:https://www.secg.org/sec1-v2.pdf[SEC 1, section 4.1.6]). +`sign_recoverable` writes 65 bytes, r, s and the id, with the same r and s as +`sign_ecdsa`, and `recover` returns the `public_key` from those 65 bytes and +the hash. It refuses with `invalid_signature` an id above 3, an r or an s not +below the group order, and a signature from which no key is recovered. include::generated/backends-recovery.adoc[] @@ -266,3 +269,130 @@ form where the signer runs on hardware an attacker can fault or observe: the nonce then no longer depends on the key and the hash alone, so two signings of one hash do not repeat the same computation. Never reuse the 32 bytes: fixed extra data leaves the signature deterministic, as plain RFC 6979. + +[#crypto-secp256k1-tweaks] +==== Tweaks, negation and combination + +A wallet app gives every payment a new address, so that strangers cannot +link the payments to one person, yet keeps a single backup. A shop's web +server that hands out those addresses holds no secret key at all: if it is +broken into, the thief sees payments but cannot spend them +(link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32]). +Both rest on one property of the curve: adding a number t, the tweak, to a +secret key d adds t times the generator G to its public key, so that the public +key of d + t is P + tG. The server computes P + tG from the public key P alone; +the signing device computes d + t from the secret; and both arrive at the same +key pair without the server ever holding a secret. + +`` offers that arithmetic on whole +keys, each function a call of libsecp256k1: + +* `seckey_tweak_add` and `seckey_tweak_mul`: a secret key plus or times a +32-byte tweak, modulo the group order, returned as a `secret<32>`; +`pubkey_tweak_add` and `pubkey_tweak_mul`: P + tG and tP, the public keys of +those two secrets; +* `seckey_negate` and `pubkey_negate`: the negation of either, n - d and -P; +* `pubkey_combine`: the sum of public keys, the public key of the sum of their +secrets. libsecp256k1 takes an array of pointers to the keys, which crypto +builds in a `workspace` the caller lends, of `combine_workspace_size(n)` bytes, +so that nothing is allocated; the workspace is wiped before the call returns. + +A secret key that is zero or not below the group order is refused with +`invalid_secret_key` before the tweak runs; so are a tweak not below the +order, a zero multiplier, and a result that is no key (a zero secret, the +point at infinity). `pubkey_combine` refuses no keys and a short workspace +with `invalid_input_size`, and a sum at infinity with `invalid_public_key`. + +include::generated/backends-key_tweaks.adoc[] + +*Example.* A watch-only wallet: the server adds a payment's tweak to the +wallet's public key, the device adds the same tweak to the secret key, and a +signature of the device's tweaked key pair verifies under the server's key. The +tweak is an HMAC of the public key and the payment's number under a chain code +both sides share, as BIP 32 extends each key with a chain code so that child +keys do not depend on the key alone; BIP 32's own derivation, with HMAC-SHA-512, +is a domain library's +(link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32]): + +[source,cpp] +---- +include::{examples}/key_tweak.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/key_tweak.expected[] +---- + +*Pitfalls.* + +* A tweak computed from public data alone (the public key and a counter) +links every derived key to the wallet: anyone who sees the public key computes +the same tweaks and recognises each payment. Mix in a value only the two sides +hold, as BIP 32's chain code is +(link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32]). +* A tweaked secret is a secret, which is why it is returned as a `secret<32>`: +whoever knows the tweak and the tweaked secret key computes the original. With +BIP 32's public derivation, one leaked child secret key and the parent's +extended public key give away the parent's secret key, and with it every key +of the wallet +(link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32]). +* The sum of keys others choose is not a multisignature. A participant who +picks its key after seeing yours can choose its own key minus yours, and the +sum is then its key alone, which it signs for without you. MuSig2 weighs each +key with a coefficient hashed from all the keys, so that no participant can +cancel another's +(link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327]). + +[#crypto-secp256k1-formats] +==== Keys in files: SPKI and PKCS#8 + +A server's key lives in a configuration file, a peer's public key arrives in a +certificate or a handshake, and other tools, OpenSSL among them, must read +both. Two DER structures carry them. SPKI, SubjectPublicKeyInfo, is a public +key with the name of its algorithm and curve +(link:https://www.rfc-editor.org/rfc/rfc5480[RFC 5480]); PKCS#8 is a private +key with the same name +(link:https://www.rfc-editor.org/rfc/rfc5208[RFC 5208]), which for an elliptic +curve holds RFC 5915's ECPrivateKey: the secret, and optionally the curve and +the public key (link:https://www.rfc-editor.org/rfc/rfc5915[RFC 5915]). + +`` writes and reads them: + +* `encode_spki` writes the SPKI of a `public_key` with the secp256k1 OID, its +point compressed, 56 bytes (the default), or uncompressed, 88 bytes, into a +buffer of at least `max_spki_size` bytes; `decode_spki` reads either back; +* `encode_pkcs8` writes a key pair's PKCS#8, 135 bytes, into a buffer of at +least `max_pkcs8_size`: version 0, and an ECPrivateKey of version 1 with the +uncompressed public key and no curve inside it, which is the form OpenSSL +writes for a key in its default uncompressed form; `decode_pkcs8` reads it into +a key pair, made as `keypair::make` makes one. + +The decoders are strict: they accept exactly the bytes the encoders write, and +refuse anything else with `invalid_encoding`. The point must be on the curve, +the secret below the group order, and the public key inside a PKCS#8 the +secret's own: `decode_pkcs8` makes the key pair, encodes it again and compares +the whole input. The encoders refuse a short buffer with `invalid_input_size` +and a moved-from key pair with `invalid_state`, and write nothing then. The +tests read OpenSSL's keys and give OpenSSL webcpp's, natively and on WASI, and +under Emscripten round-trip every encoding through node's `crypto` module. + +include::generated/backends-key_formats.adoc[] + +*Pitfalls.* + +* A lenient parser gives one key many encodings, and lets a file say two +things at once. RFC 5915 makes the curve and the public key optional inside +ECPrivateKey (link:https://www.rfc-editor.org/rfc/rfc5915[RFC 5915]), so a +PKCS#8 can carry a public key that is not its secret's; a program that shows or +checks that key, rather than the one the secret gives, trusts the wrong key. +`decode_pkcs8` refuses such a file. +* X9.62's hybrid point form, prefix 06 or 07, is refused: RFC 5480 forbids it +in an SPKI (link:https://www.rfc-editor.org/rfc/rfc5480[RFC 5480]). +* OpenSSL writes a key set to the compressed form with its compressed point +inside the PKCS#8 too, 102 bytes, which `decode_pkcs8` refuses: export the key +in OpenSSL's default uncompressed form, and choose the SPKI's form when writing +it. +* The PKCS#8 these functions write holds the secret key in clear. Keep it +where only the program reads it, out of source control, or seal it at rest +(<>). diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index b3ddf5f2..da9be994 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -106,7 +106,10 @@ "rfc7748-kdf": ["RFC 7748, section 6.1: a KDF over the shared secret and both public keys", "https://www.rfc-editor.org/rfc/rfc7748#section-6.1"], "libsodium-doc-licence": ["libsodium's documentation, jedisct1/libsodium-doc at 6d1ea27, ISC", "https://github.com/jedisct1/libsodium-doc/tree/6d1ea27b79b853b2a04f09ae9e1a8231c90e3b56"], "sec1": ["SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings", "https://www.secg.org/sec1-v2.pdf"], - "bip327": ["BIP 327, MuSig2, its key sorting", "https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki"] + "bip327": ["BIP 327, MuSig2, its key sorting", "https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki"], + "rfc5480": ["RFC 5480, Elliptic Curve Cryptography Subject Public Key Information", "https://www.rfc-editor.org/rfc/rfc5480"], + "rfc5915": ["RFC 5915, Elliptic Curve Private Key Structure", "https://www.rfc-editor.org/rfc/rfc5915"], + "rfc5208": ["RFC 5208, PKCS #8: Private-Key Information Syntax", "https://www.rfc-editor.org/rfc/rfc5208"] }, "backends": { "bearssl": { @@ -575,6 +578,30 @@ "what": "A parsed public key, read from and written to its compressed or uncompressed form.", "section": "crypto-secp256k1-keys", "backends": {"secp256k1": {"tests": ["secp256k1_keys"]}} + }, + { + "id": "key_tweaks", + "family": "secp256k1", + "free": true, + "functions": ["seckey_tweak_add", "seckey_tweak_mul", "seckey_negate", "pubkey_tweak_add", "pubkey_tweak_mul", "pubkey_negate", "pubkey_combine"], + "namespace": "curves", + "api": "curves::secp256k1::seckey_tweak_add, seckey_tweak_mul, seckey_negate, pubkey_tweak_add, pubkey_tweak_mul, pubkey_negate, pubkey_combine", + "header": "", + "what": "A secret or public key plus or times a tweak, its negation, and the sum of public keys.", + "section": "crypto-secp256k1-tweaks", + "backends": {"secp256k1": {"tests": ["secp256k1_tweak"]}} + }, + { + "id": "key_formats", + "family": "secp256k1", + "free": true, + "functions": ["encode_spki", "decode_spki", "encode_pkcs8", "decode_pkcs8"], + "namespace": "curves", + "api": "curves::secp256k1::encode_spki, decode_spki, encode_pkcs8, decode_pkcs8", + "header": "", + "what": "A public key's SPKI and a key pair's PKCS#8, in OpenSSL's forms, decoded strictly.", + "section": "crypto-secp256k1-formats", + "backends": {"secp256k1": {"tests": ["secp256k1_formats", "secp256k1_formats_openssl"]}} } ], "families": [ @@ -856,7 +883,7 @@ {"title": "A failed open zeroes data", "section": "crypto-gcm-rules", "text": "when the tag does not match, `open` returns `authentication_failed` and zeroes the whole of `data`; keep a copy of the ciphertext if it is needed after a failure. There is no incremental open: a large message is split into records."}, {"title": "Records: each stream its own key", "section": "crypto-gcm-incremental", "text": "records numbered from 0 with the number as IV are safe only under a key used for that one stream: derive a key per stream (HKDF of the storage key with a random salt) or draw one; never number two streams' records under one key."}, {"title": "ECDH's form", "section": "crypto-secp256k1-ecdh", "text": "`keypair::ecdh` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point; protocols that take the raw x coordinate, such as Nostr's NIP-44 ({nip44}), need `ecdh_x`. Both sides must use the same form, or they derive different keys. Derive keys with a KDF, never use a shared secret directly."}, - {"title": "The x-only tweak is not BIP 32", "section": "crypto-wallets-taproot", "text": "`tweak_xonly` is BIP 341's even-y arithmetic ({bip341}); BIP 32's child derivation needs a tweak of the full key, which this version does not offer ({bip32})."}, + {"title": "The x-only tweak is not BIP 32", "section": "crypto-wallets-taproot", "text": "`tweak_xonly` is BIP 341's even-y arithmetic ({bip341}); BIP 32's child derivation tweaks the full key, with `seckey_tweak_add` and `pubkey_tweak_add`, and computes the tweak with HMAC-SHA-512, a domain library's ({bip32})."}, {"title": "Ethereum", "section": "crypto-curves", "text": "this version signs and verifies Ethereum's ECDSA, recoverable signatures included (`keypair::sign_recoverable`), recovers a signer's public key from a signature and a hash (`recover`), and writes the uncompressed key ({ethereum}); the recovery id's `v` encoding, the hash Ethereum signs, transactions and addresses are a domain library's."}, {"title": "Compare secrets in constant time", "section": "crypto-equal", "text": "compare a tag, a MAC or a token with `equal`, never `==` or `memcmp` ({cwe208})."}, {"title": "Secrets come from random_device", "section": "crypto-entropy", "text": "keys, IVs and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ({cwe338})."}, @@ -913,7 +940,7 @@ "columns": ["Curve", "What it does", "Security level", "Key sizes", "Signature sizes", "Speed", "Constant time, measured", "Standards", "Ecosystems that require it", "Browsers' WebCrypto", "Choose it for compatibility with"], "cited": ["Standards", "Ecosystems that require it", "Browsers' WebCrypto"], "rows": [ - ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, hedged and recoverable ECDSA, the recovery of a signer's key, ECDH in three forms, public keys in both forms, the x-only tweak", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 65 bytes uncompressed ({sec1}), 32 bytes x-only", "64 bytes; 65 bytes recoverable; ECDSA in DER up to 72", "{speed:secp256k1}", "{constant_time:secp256k1}", "{sec2}, {bip340}, {rfc6979}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}); Ethereum's recoverable signatures and uncompressed keys ({ethereum}), the address hashing being a domain library's. Not in this version: BIP 32's derivation ({bip32})"], + ["`secp256k1`", "BIP 340 Schnorr and ECDSA signatures, hedged and recoverable ECDSA, the recovery of a signer's key, ECDH in three forms, public keys in both forms, the x-only tweak, the tweaks, negation and combination of keys, SPKI and PKCS#8", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 65 bytes uncompressed ({sec1}), 32 bytes x-only; SPKI 56 or 88 bytes ({rfc5480}), PKCS#8 135 bytes ({rfc5208}, {rfc5915})", "64 bytes; 65 bytes recoverable; ECDSA in DER up to 72", "{speed:secp256k1}", "{constant_time:secp256k1}", "{sec2}, {bip340}, {rfc6979}", "Bitcoin ({bip340}), Ethereum ({ethereum}), Nostr ({nip01})", "no: WebCrypto offers P-256, P-384, P-521, Ed25519 and X25519, not secp256k1 ({webcrypto})", "Bitcoin's keys and signatures; Nostr's event signatures ({nip01}); Ethereum's ECDSA verification with a known key; ECDH in the raw x-coordinate form of Nostr's encrypted messages ({nip44}); Ethereum's recoverable signatures and uncompressed keys ({ethereum}), the address hashing being a domain library's; BIP 32's tweaks of the full key, its derivation of the tweak being a domain library's ({bip32}); keys exchanged with OpenSSL as SPKI or PKCS#8 ({rfc5480}, {rfc5915})"], ["`ed25519`", "Ed25519 signatures, and Ed25519ph over SHA-512 for a message given in pieces; the X25519 secret key of a key pair", "about 128 bits ({rfc8032})", "secret 32 bytes (the seed); public 32 bytes", "64 bytes", "{speed:ed25519}", "{constant_time:ed25519}", "{rfc8032}, {fips186-5}", "SSH keys ({rfc8709}), Signal's signatures on its Curve25519 keys ({signal-xeddsa}), Tor's identity keys ({tor-cert-spec}), Solana's accounts ({solana-accounts})", "yes: Ed25519 ({webcrypto})", "SSH, Tor and Solana keys and signatures, and any protocol that names RFC 8032's Ed25519 or Ed25519ph; verification is strict (libsodium's rules), which some lenient verifiers are not. Not Bitcoin, Ethereum or Nostr, whose keys are secp256k1's"], ["`x25519`", "Key agreement (Diffie-Hellman on Curve25519): two parties who exchanged public keys share a 32-byte secret; `kx_keypair`, libsodium's `crypto_kx`, gives a client and a server a session key for each direction", "about 128 bits ({rfc7748})", "secret 32 bytes; public 32 bytes", "none: no signatures", "{speed:x25519}", "{constant_time:x25519}", "{rfc7748}", "TLS 1.3 ({rfc8446-groups}), SSH ({rfc8731}), WireGuard ({wireguard}), Signal ({x3dh})", "yes: X25519 ({webcrypto})", "TLS 1.3's and SSH's key exchange, WireGuard, Signal; libsodium's `crypto_box` keys, and the session keys of `crypto_kx` with `kx_keypair` ({libsodium-kx}). The Ed25519 public key of a peer converts with `curves::ed25519::to_x25519_public`. A shared secret goes through a KDF before it keys a cipher. Every case of Wycheproof's X25519 file is tested ({wycheproof})"] ] @@ -942,6 +969,7 @@ {"need": "Agree on a key with a peer through a relay that sees everything", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::ecdh` (SHA-256 of the shared point), then HKDF on Boost.Hash2 and `aes256_gcm`", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "ecdh_session", "section": "crypto-p2p-session"}, {"need": "Derive a Nostr direct message's conversation key (NIP-44; the format is a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::ecdh_x`, then HKDF on Boost.Hash2", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdh_x_coordinate", "section": "crypto-secp256k1-ecdh"}, {"need": "Find who signed a message or a transaction without being sent their key (Ethereum's signatures)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_recoverable`, `recover`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "recover_signer", "section": "crypto-secp256k1-recovery"}, + {"need": "Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`seckey_tweak_add`, `pubkey_tweak_add`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "key_tweak", "section": "crypto-secp256k1-tweaks"}, {"need": "Make and keep a wallet's key", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "wallet_key", "section": "crypto-wallets-key"}, {"need": "Sign a Bitcoin SegWit v0 input (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`sign_ecdsa`, `to_der`, `normalize_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdsa_der", "section": "crypto-wallets-der"}, {"need": "Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`tweak_xonly`, `keypair::tweak_xonly`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "taproot_tweak", "section": "crypto-wallets-taproot"}, diff --git a/doc/testing.adoc b/doc/testing.adoc index 9173a112..1be35eda 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -53,12 +53,14 @@ What the tests check: * *The vectors.* AES-GCM against the GCM specification's cases and Project Wycheproof's vectors, on BearSSL and on OpenSSL; AES against FIPS 197 on ctaes and OpenSSL; secp256k1 against BIP 340's vectors, Wycheproof's ECDSA, ECDH and -DER vectors and libsecp256k1's own recovery edge cases, and the x-only tweak -against BIP 341's. Ed25519 against RFC 8032's tests, Wycheproof's EdDSA vectors -and the twelve edge cases of "Taming the many EdDSAs"; X25519 against RFC 7748's -and Wycheproof's; ChaCha20-Poly1305 and XChaCha20-Poly1305 against RFC 8439's -and the XChaCha20 draft's examples and Wycheproof's vectors, on every backend -that has them. +DER vectors and libsecp256k1's own recovery edge cases, the x-only tweak against +BIP 341's, the tweaks, negations and sums of keys against libsecp256k1's C API, +and the SPKI and PKCS#8 encodings against Wycheproof's SPKIs, OpenSSL (natively +and on WASI) and node's `crypto` module (under Emscripten). Ed25519 against RFC +8032's tests, Wycheproof's EdDSA vectors and the twelve edge cases of "Taming +the many EdDSAs"; X25519 against RFC 7748's and Wycheproof's; ChaCha20-Poly1305 +and XChaCha20-Poly1305 against RFC 8439's and the XChaCha20 draft's examples and +Wycheproof's vectors, on every backend that has them. * *node's WebCrypto as an outside oracle,* on Emscripten: 200 Ed25519 key pairs, messages and signatures from a fixed seed, each verified and signed again by `crypto.subtle`, which must give the same public key and signature, diff --git a/doc/wallets.adoc b/doc/wallets.adoc index 93fb1e3f..9e5226d9 100644 --- a/doc/wallets.adoc +++ b/doc/wallets.adoc @@ -131,8 +131,9 @@ output key or a pay-to-contract commitment to an x-only key. It is not BIP 32's child derivation, which adds to the parent's full point and secret key without that negation: for the half of the parents whose public key has an odd y, an x-only tweak derives another child than every BIP 32 wallet, whose addresses a -wallet restored from the same seed never finds. BIP 32 needs a tweak of the -full key, which this version does not offer +wallet restored from the same seed never finds. BIP 32 tweaks the full key, +with `seckey_tweak_add` and `pubkey_tweak_add` (<>), +and computes its tweak with HMAC-SHA-512, which is a domain library's (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32]). *Mistakes to avoid.* A Taproot tweak is computed from public data (the internal diff --git a/example/Jamfile b/example/Jamfile index b46cdb29..fb72c9db 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -57,6 +57,10 @@ webcpp.example ecdh_x_coordinate.cpp : /third_party//secp256k1 ; # and the hash. webcpp.example recover_signer.cpp : /third_party//secp256k1 ; +# A watch-only wallet: the same tweak on the public key and on the secret key, +# and a signature of the tweaked key pair verified under the tweaked public key. +webcpp.example key_tweak.cpp : /third_party//secp256k1 ; + # A wallet's key pair, its secret sealed at rest and restored. webcpp.example wallet_key.cpp : /third_party//secp256k1 /webcpp/crypto//gcm-default ; diff --git a/example/key_tweak.cpp b/example/key_tweak.cpp new file mode 100644 index 00000000..7389d6d0 --- /dev/null +++ b/example/key_tweak.cpp @@ -0,0 +1,132 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A watch-only wallet: a server that holds the wallet's public key and no secret gives each +// payment a fresh key, and the signing device, which holds the secret, derives the same keys' +// secrets. Both add the same tweak, one to the public key and one to the secret key; the +// device's tweaked key pair signs (BIP 340), and the signature verifies under the server's +// tweaked public key. The tweak here is an HMAC-SHA-256 of the public key and the payment's +// number under a chain code both sides share and no one else sees; BIP 32 derives such tweaks +// its own way, with HMAC-SHA-512, and is a domain library's. +// tag::program[] +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace secp256k1 = webcpp::crypto::curves::secp256k1; +namespace hash2 = boost::hash2; + +namespace { + +// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead +// store: crypto wipes its own copies of keys this way, and the program wipes its own. +void wipe(std::span secret) { + std::byte volatile* const bytes = secret.data(); + for (std::size_t i = 0; i < secret.size(); ++i) { + bytes[i] = std::byte{0}; + } +} + +// The tweak of payment `number`: HMAC-SHA-256 under the chain code of the compressed public key +// and the number. Both sides compute it; an outsider without the chain code cannot, and so +// cannot tell that two payment keys belong to one wallet. +std::array payment_tweak(std::span chain_code, + std::span public_key, + std::uint32_t number) { + hash2::hmac_sha2_256 mac(chain_code.data(), chain_code.size()); + mac.update(public_key.data(), public_key.size()); + std::array const index{ + static_cast(number >> 24U), + static_cast(number >> 16U), + static_cast(number >> 8U), + static_cast(number), + }; + mac.update(index.data(), index.size()); + auto const digest = mac.result(); + std::array tweak{}; + std::copy_n(digest.data(), tweak.size(), tweak.begin()); + return tweak; +} + +} // namespace + +int main() { + // The device's secret and the chain code, drawn once; the device keeps both, the server + // gets the chain code and the public key. + crypto::random_device device; + std::array secret{}; + std::array chain_code{}; + if (!device.fill(secret) || !device.fill(chain_code)) { + return 1; + } + auto const wallet = secp256k1::keypair::make(secret); + if (!wallet) { + // A secret not below the group order: negligible, and a real wallet draws again. + return 1; + } + auto const wallet_public = wallet->public_key(); + if (!wallet_public) { + return 1; + } + auto const tweak = payment_tweak(chain_code, *wallet_public, 7); + + // tag::tweak[] + // The server: the wallet's public key plus the tweak, with no secret anywhere. + auto const parsed = secp256k1::parse_public_key(*wallet_public); + if (!parsed) { + return 1; + } + auto const watched = secp256k1::pubkey_tweak_add(*parsed, tweak); + + // The device: the secret key plus the same tweak, a secret<32> it makes a key pair of. + auto const tweaked_secret = secp256k1::seckey_tweak_add(secret, tweak); + wipe(std::as_writable_bytes(std::span(secret))); + if (!watched || !tweaked_secret) { + return 1; + } + auto const payment_key = secp256k1::keypair::make(tweaked_secret->bytes()); + if (!payment_key) { + return 1; + } + auto const payment_public = payment_key->public_key(); + if (!payment_public || secp256k1::serialize_public_key(*watched) != *payment_public) { + return 1; + } + std::printf("tweaked keys match\n"); + // end::tweak[] + + // tag::sign[] + // The device signs a spend with the payment's key pair; the server verifies under the + // x-only form of the key it derived alone (the compressed key without its prefix byte). + std::array const message{}; + std::array aux{}; + if (!device.fill(aux)) { + return 1; + } + auto const signature = payment_key->sign_schnorr(message, aux); + auto const watched_bytes = secp256k1::serialize_public_key(*watched); + std::array xonly{}; + std::copy_n(watched_bytes.begin() + 1, xonly.size(), xonly.begin()); + if (!signature || !secp256k1::verify_schnorr(*signature, message, xonly)) { + return 1; + } + std::printf("signature verifies under the tweaked public key\n"); + // end::sign[] + return 0; +} + +// end::program[] diff --git a/example/key_tweak.expected b/example/key_tweak.expected new file mode 100644 index 00000000..5ad513e9 --- /dev/null +++ b/example/key_tweak.expected @@ -0,0 +1,2 @@ +tweaked keys match +signature verifies under the tweaked public key diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index b54685fb..395a2efb 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -57,6 +57,8 @@ #ifdef WEBCPP_CRYPTO_HAS_SECP256K1 #include +#include +#include #endif #endif // WEBCPP_CRYPTO_HPP diff --git a/include/webcpp/crypto/backends/secp256k1.hpp b/include/webcpp/crypto/backends/secp256k1.hpp index f6219fde..5b7652c8 100644 --- a/include/webcpp/crypto/backends/secp256k1.hpp +++ b/include/webcpp/crypto/backends/secp256k1.hpp @@ -7,8 +7,9 @@ /** The backend libsecp256k1: its v0.8.0, built from its sources by `/third_party//secp256k1`, every module on. It serves `curves::secp256k1::keypair`, `verify_schnorr`, `verify_ecdsa`, - `recover`, the parsed `public_key`, the DER and low-S functions and the x-only tweak, and its - whole C API stays reachable through ``. + `recover`, the parsed `public_key`, the DER and low-S functions, the x-only tweak, the tweaks + and combination of `curves/secp256k1/tweak.hpp` and the SPKI and PKCS#8 of + `curves/secp256k1/formats.hpp`, and its whole C API stays reachable through ``. @see "secp256k1", in the guide. */ diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index 2cd9e01f..8245d6f8 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -7,8 +7,8 @@ /** secp256k1 on libsecp256k1: BIP340 Schnorr and ECDSA signatures, hedged and recoverable, their verification and the recovery of a signer's key, and ECDH in three forms, each a secret; the - parsed public key in its two SEC1 forms; ECDSA's DER and low-S forms, and the tweak of an - x-only key. + parsed public key in its two SEC1 forms; ECDSA's DER and low-S forms, the tweak of an x-only + key, and the workspace a function over many keys borrows. @see "secp256k1", in the guide. */ @@ -33,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -151,6 +152,65 @@ struct secp256k1_secret { ~secp256k1_secret() { wipe(bytes.data(), bytes.size()); } }; +/** + * The carver of a caller's workspace into the arrays of pointers libsecp256k1 takes, which + * wipes every byte it handed out when it is destroyed. + * + * Each array is aligned to `alignof(std::max_align_t)`, in the order the function's size + * function lists them; an array of no elements takes no bytes and is `nullptr`. + */ +class secp256k1_workspace { +public: + /** + * Carves `lent_bytes`, from its first byte on. + * + * @param lent_bytes The caller's workspace. + */ + explicit secp256k1_workspace(std::span lent_bytes) noexcept + : lent_bytes_(lent_bytes) {} + + /** Not copyable: one carver wipes what it handed out. */ + secp256k1_workspace(secp256k1_workspace const&) = delete; + /** Not copyable: one carver wipes what it handed out. */ + secp256k1_workspace& operator=(secp256k1_workspace const&) = delete; + + /** Wipes every byte handed out, and the padding between them. */ + ~secp256k1_workspace() { wipe(lent_bytes_.data(), used_size_); } + + /** + * The next array of `element_count` elements of `T`, aligned to `alignof(std::max_align_t)`. + * + * @tparam T The element, a type with no constructor to run (a pointer). + * @param element_count The number of elements. + * @return The array; `nullptr` for no elements, or when the rest of the workspace is short. + */ + template + [[nodiscard]] T* take(std::size_t element_count) noexcept { + static_assert( + std::is_trivially_default_constructible_v && std::is_trivially_destructible_v, + "the workspace holds arrays of pointers"); + if (element_count == 0) { + return nullptr; + } + std::size_t const array_size = element_count * sizeof(T); + void* array_start = lent_bytes_.data() + used_size_; + std::size_t free_size = lent_bytes_.size() - used_size_; + if (std::align(alignof(std::max_align_t), array_size, array_start, free_size) == nullptr) { + return nullptr; + } + used_size_ = + static_cast(static_cast(array_start) - lent_bytes_.data()) + + array_size; + // Bytes the caller lent give their storage to an array of pointers, an implicit-lifetime + // type ([intro.object]): the array exists once it is written. + return static_cast(array_start); + } + +private: + std::span lent_bytes_; + std::size_t used_size_ = 0; +}; + /** * Parses a public key of 33 bytes, compressed, or 65, uncompressed. libsecp256k1 also * accepts X9.62's hybrid forms, prefix 06 or 07, of 65 bytes; they are refused here, as every @@ -264,6 +324,18 @@ namespace webcpp::crypto::curves::secp256k1 { /** The longest strict DER encoding of a secp256k1 ECDSA signature, in bytes. */ inline constexpr std::size_t max_der_size = 72; +/** + * Memory a caller lends to a function over many keys, nonces or outputs, for libsecp256k1's + * arrays of pointers, which crypto builds there and allocates nowhere. + * + * Each such function has a `*_workspace_size` that says how many bytes it needs, and wipes the + * bytes before it returns; a short workspace is `invalid_input_size`, never an allocation. + * + * Tip: `alignas(std::max_align_t) std::array` on the stack, or a vector the + * program owns. + */ +using workspace = std::span; + /** The two SEC1 encodings of a point. */ enum class point_form { /** 33 bytes: 02 or 03 by the parity of y, then x; Bitcoin's form. */ diff --git a/include/webcpp/crypto/curves/secp256k1/formats.hpp b/include/webcpp/crypto/curves/secp256k1/formats.hpp new file mode 100644 index 00000000..652020fa --- /dev/null +++ b/include/webcpp/crypto/curves/secp256k1/formats.hpp @@ -0,0 +1,245 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + secp256k1's keys in the standard formats on libsecp256k1: a public key's SPKI (RFC 5480, the + secp256k1 OID, either point form) and a key pair's PKCS#8 (RFC 5208 around RFC 5915's + ECPrivateKey), each decoded only when it is exactly what the encoder writes. + + @see "Keys in files: SPKI and PKCS#8", in the guide's secp256k1 chapter. +*/ +#ifndef WEBCPP_CRYPTO_CURVES_SECP256K1_FORMATS_HPP +#define WEBCPP_CRYPTO_CURVES_SECP256K1_FORMATS_HPP + +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** + * RFC 5480's SPKI before an uncompressed secp256k1 point: the SEQUENCE, the AlgorithmIdentifier + * (id-ecPublicKey, secp256k1), then a BIT STRING of 66 bytes. + */ +inline constexpr std::array secp256k1_spki_uncompressed_prefix{ + 0x30, 0x56, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, + 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x0a, 0x03, 0x42, 0x00, +}; + +/** RFC 5480's SPKI before a compressed secp256k1 point, whose BIT STRING has 34 bytes. */ +inline constexpr std::array secp256k1_spki_compressed_prefix{ + 0x30, 0x36, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, + 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x0a, 0x03, 0x22, 0x00, +}; + +/** + * PKCS#8 before the secret, in OpenSSL's form: version 0, the AlgorithmIdentifier, and an + * OCTET STRING holding RFC 5915's ECPrivateKey (version 1, then its 32-byte OCTET STRING), with + * no [0] parameters. + */ +inline constexpr std::array secp256k1_pkcs8_prefix{ + 0x30, 0x81, 0x84, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x07, 0x2a, + 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, + 0x00, 0x0a, 0x04, 0x6d, 0x30, 0x6b, 0x02, 0x01, 0x01, 0x04, 0x20, +}; + +/** PKCS#8 between the secret and the uncompressed public point: ECPrivateKey's [1] BIT STRING. */ +inline constexpr std::array secp256k1_pkcs8_infix{0xa1, 0x44, 0x03, 0x42, 0x00}; + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::curves::secp256k1 { + +/** The size of an SPKI with a compressed point, 56 bytes. */ +inline constexpr std::size_t spki_compressed_size = 56; + +/** The size of an SPKI with an uncompressed point, 88 bytes. */ +inline constexpr std::size_t spki_uncompressed_size = 88; + +/** The size of the longest SPKI, 88 bytes. */ +inline constexpr std::size_t max_spki_size = spki_uncompressed_size; + +/** The size of a PKCS#8, 135 bytes: the secret and the uncompressed public point. */ +inline constexpr std::size_t max_pkcs8_size = 135; + +/** + * Writes a public key's SPKI (RFC 5480, the secp256k1 OID) into `output_bytes`. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param parsed_key The key. + * @param output_bytes At least `max_spki_size` bytes, whatever the form; nothing is written on + * an error. + * @param encoded_form The point's SEC1 form, `compressed` by default. + * @return The number of bytes written, `spki_compressed_size` or `spki_uncompressed_size`; + * `invalid_input_size` when `output_bytes` is shorter than `max_spki_size`. + */ +template +[[nodiscard]] boost::system::result encode_spki( + public_key const& parsed_key, std::span output_bytes, + point_form encoded_form = point_form::compressed) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + if (output_bytes.size() < max_spki_size) { + return error::invalid_input_size; + } + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + bool const is_compressed = encoded_form == point_form::compressed; + std::array point_bytes{}; + std::size_t point_length = is_compressed ? 33 : 65; + secp256k1_ec_pubkey_serialize(secp256k1_context_static, point_bytes.data(), &point_length, + &webcpp::crypto::detail::secp256k1_access::point(parsed_key), + is_compressed ? webcpp::crypto::detail::secp256k1_compressed + : webcpp::crypto::detail::secp256k1_uncompressed); + auto const cursor = + std::ranges::copy(is_compressed + ? webcpp::crypto::detail::secp256k1_spki_compressed_prefix + : webcpp::crypto::detail::secp256k1_spki_uncompressed_prefix, + output_bytes.begin()) + .out; + std::ranges::copy(std::span(point_bytes).first(point_length), cursor); + return is_compressed ? spki_compressed_size : spki_uncompressed_size; +} + +/** + * The public key of an SPKI in exactly one of the two forms `encode_spki` writes. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param spki_bytes The SPKI, exactly: nothing may follow it. + * @return The key; `invalid_encoding` for any other bytes, a point off the curve and X9.62's + * hybrid form included. + */ +template +[[nodiscard]] boost::system::result decode_spki( + std::span spki_bytes) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + std::span const prefix = + spki_bytes.size() == spki_compressed_size + ? std::span( + webcpp::crypto::detail::secp256k1_spki_compressed_prefix) + : std::span( + webcpp::crypto::detail::secp256k1_spki_uncompressed_prefix); + if ((spki_bytes.size() != spki_compressed_size && + spki_bytes.size() != spki_uncompressed_size) || + !equal(spki_bytes.first(prefix.size()), prefix)) { + return error::invalid_encoding; + } + using access = webcpp::crypto::detail::secp256k1_access; + public_key decoded_key = access::make_public_key(); + // 33 bytes parse only with the prefix 02 or 03, and 65 only with 04. + if (!webcpp::crypto::detail::secp256k1_parse_public_key(spki_bytes.subspan(prefix.size()), + access::point(decoded_key))) { + return error::invalid_encoding; + } + return decoded_key; +} + +/** + * Writes a key pair's PKCS#8 into `output_bytes`, in OpenSSL's form: version 0, and RFC 5915's + * ECPrivateKey of version 1 with the uncompressed public key and no parameters inside. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param key_pair The key pair. + * @param output_bytes At least `max_pkcs8_size` bytes; nothing is written on an error. + * @return The number of bytes written, `max_pkcs8_size`; `invalid_state` moved from; + * `invalid_input_size` when `output_bytes` is shorter than `max_pkcs8_size`. + */ +template +[[nodiscard]] boost::system::result encode_pkcs8( + basic_keypair const& key_pair, std::span output_bytes) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + using access = webcpp::crypto::detail::secp256k1_access; + if (!access::keyed(key_pair)) { + return error::invalid_state; + } + if (output_bytes.size() < max_pkcs8_size) { + return error::invalid_input_size; + } + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + webcpp::crypto::detail::secp256k1_secret secret_bytes; + secp256k1_keypair_sec(secp256k1_context_static, secret_bytes.bytes.data(), + &access::pair(key_pair)); + secp256k1_pubkey public_point{}; + secp256k1_keypair_pub(secp256k1_context_static, &public_point, &access::pair(key_pair)); + std::array point_bytes{}; + std::size_t point_length = point_bytes.size(); + secp256k1_ec_pubkey_serialize(secp256k1_context_static, point_bytes.data(), &point_length, + &public_point, webcpp::crypto::detail::secp256k1_uncompressed); + auto cursor = + std::ranges::copy(webcpp::crypto::detail::secp256k1_pkcs8_prefix, output_bytes.begin()).out; + cursor = std::ranges::copy(secret_bytes.bytes, cursor).out; + cursor = std::ranges::copy(webcpp::crypto::detail::secp256k1_pkcs8_infix, cursor).out; + std::ranges::copy(point_bytes, cursor); + return max_pkcs8_size; +} + +/** + * The key pair of a PKCS#8 that is exactly what `encode_pkcs8` writes for its secret, made as + * `basic_keypair::make` makes it. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param pkcs8_bytes The PKCS#8, exactly: nothing may follow it. + * @param memory_resource The resource of the key pair's signing context, as `make` takes it. + * @return The key pair; `invalid_encoding` for any other bytes, a secret zero or not below the + * group order and a public key not the secret's included; `entropy_unavailable` and + * `backend_failure` as `make` reports them. + */ +template +[[nodiscard]] boost::system::result> decode_pkcs8( + std::span pkcs8_bytes, + std::pmr::memory_resource* memory_resource = std::pmr::get_default_resource()) { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + constexpr std::size_t prefix_size = webcpp::crypto::detail::secp256k1_pkcs8_prefix.size(); + if (pkcs8_bytes.size() != max_pkcs8_size || + !equal(pkcs8_bytes.first(prefix_size), webcpp::crypto::detail::secp256k1_pkcs8_prefix)) { + return error::invalid_encoding; + } + webcpp::crypto::detail::secp256k1_secret secret_bytes; + std::ranges::copy(pkcs8_bytes.subspan(prefix_size, secret_bytes.bytes.size()), + secret_bytes.bytes.begin()); + auto made_pair = basic_keypair::make(secret_bytes.bytes, memory_resource); + if (!made_pair) { + if (made_pair.error() == error::invalid_secret_key) { + return error::invalid_encoding; + } + return made_pair.error(); + } + // The rest, the public key above all, is checked by encoding the key pair again: a PKCS#8 + // whose public key is not its secret's is refused. + std::array encoded_again{}; + bool const is_same = + encode_pkcs8(*made_pair, encoded_again).has_value() && equal(encoded_again, pkcs8_bytes); + webcpp::crypto::detail::wipe(encoded_again.data(), encoded_again.size()); + if (!is_same) { + return error::invalid_encoding; + } + return made_pair; +} + +} // namespace webcpp::crypto::curves::secp256k1 + +#endif // WEBCPP_CRYPTO_CURVES_SECP256K1_FORMATS_HPP diff --git a/include/webcpp/crypto/curves/secp256k1/tweak.hpp b/include/webcpp/crypto/curves/secp256k1/tweak.hpp new file mode 100644 index 00000000..db974478 --- /dev/null +++ b/include/webcpp/crypto/curves/secp256k1/tweak.hpp @@ -0,0 +1,271 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + secp256k1's tweaks, negation and combination of secret and public keys on libsecp256k1: a + secret key plus or times a tweak, the same on its public key, the negation of either, and the + sum of public keys. Each tweaked or negated secret key is a `secret<32>`. + + @see "Tweaks, negation and combination", in the guide's secp256k1 chapter. +*/ +#ifndef WEBCPP_CRYPTO_CURVES_SECP256K1_TWEAK_HPP +#define WEBCPP_CRYPTO_CURVES_SECP256K1_TWEAK_HPP + +#include + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** The function libsecp256k1 runs on a secret key and a tweak: `secp256k1_ec_seckey_tweak_*`. */ +using secp256k1_seckey_tweak = int (*)(secp256k1_context const*, unsigned char*, + unsigned char const*); + +/** The function libsecp256k1 runs on a public key and a tweak: `secp256k1_ec_pubkey_tweak_*`. */ +using secp256k1_pubkey_tweak = int (*)(secp256k1_context const*, secp256k1_pubkey*, + unsigned char const*); + +/** + * A secret key tweaked by libsecp256k1, computed in a wiped copy of the key and moved into the + * secret returned. + * + * @param secret_key The 32-byte secret key. + * @param tweak_bytes The 32-byte tweak, or null for a negation. + * @param tweak_function libsecp256k1's tweak, used when `tweak_bytes` is not null. + * @return The secret; `invalid_secret_key` for a secret key zero or not below the group order, + * then for a tweak not below it or a result of zero. + */ +[[nodiscard]] inline boost::system::result> secp256k1_tweaked_secret( + std::span secret_key, unsigned char const* tweak_bytes, + secp256k1_seckey_tweak tweak_function) noexcept { + // The key is checked first, so that a refusal names the input that was wrong. + if (secp256k1_ec_seckey_verify(secp256k1_context_static, secret_key.data()) == 0) { + return error::invalid_secret_key; + } + secp256k1_secret working_copy; + std::ranges::copy(secret_key, working_copy.bytes.begin()); + int const status = + tweak_bytes == nullptr + ? secp256k1_ec_seckey_negate(secp256k1_context_static, working_copy.bytes.data()) + : tweak_function(secp256k1_context_static, working_copy.bytes.data(), tweak_bytes); + if (status == 0) { + return error::invalid_secret_key; + } + secret<32> tweaked_secret; + std::ranges::copy(working_copy.bytes, tweaked_secret.writable().begin()); + return tweaked_secret; +} + +/** + * A public key tweaked by libsecp256k1 on the static context. + * + * @param parsed_key The key, valid. + * @param tweak_bytes The 32-byte tweak. + * @param tweak_function libsecp256k1's tweak. + * @return The key; `invalid_secret_key` for a tweak not below the group order, a zero + * multiplier, or a result at infinity. + */ +[[nodiscard]] inline boost::system::result secp256k1_tweaked_key( + curves::secp256k1::public_key const& parsed_key, std::span tweak_bytes, + secp256k1_pubkey_tweak tweak_function) noexcept { + curves::secp256k1::public_key tweaked_key = parsed_key; + if (tweak_function(secp256k1_context_static, &secp256k1_access::point(tweaked_key), + tweak_bytes.data()) == 0) { + return error::invalid_secret_key; + } + return tweaked_key; +} + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::curves::secp256k1 { + +/** + * The workspace `pubkey_combine` needs for `key_count` keys, in bytes. + * + * @param key_count The number of keys combined. + * @return One pointer per key and one `alignof(std::max_align_t)` of padding. + */ +[[nodiscard]] constexpr std::size_t combine_workspace_size(std::size_t key_count) noexcept { + return (key_count * sizeof(secp256k1_pubkey const*)) + alignof(std::max_align_t); +} + +/** + * A secret key plus a tweak modulo the group order (`secp256k1_ec_seckey_tweak_add`). + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param secret_key The 32-byte secret key. + * @param tweak_bytes The 32-byte tweak, a big-endian scalar. + * @return The tweaked secret key; `invalid_secret_key` for a secret key zero or not below the + * group order, a tweak not below it, or a sum of zero. + */ +template +[[nodiscard]] boost::system::result> seckey_tweak_add( + std::span secret_key, + std::span tweak_bytes) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + return webcpp::crypto::detail::secp256k1_tweaked_secret(secret_key, tweak_bytes.data(), + secp256k1_ec_seckey_tweak_add); +} + +/** + * A secret key times a tweak modulo the group order (`secp256k1_ec_seckey_tweak_mul`). + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param secret_key The 32-byte secret key. + * @param tweak_bytes The 32-byte tweak, a big-endian scalar. + * @return The tweaked secret key; `invalid_secret_key` for a secret key zero or not below the + * group order, or a tweak that is zero or not below it. + */ +template +[[nodiscard]] boost::system::result> seckey_tweak_mul( + std::span secret_key, + std::span tweak_bytes) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + return webcpp::crypto::detail::secp256k1_tweaked_secret(secret_key, tweak_bytes.data(), + secp256k1_ec_seckey_tweak_mul); +} + +/** + * The group order minus a secret key (`secp256k1_ec_seckey_negate`). + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param secret_key The 32-byte secret key. + * @return The negated secret key; `invalid_secret_key` for a secret key zero or not below the + * group order. + */ +template +[[nodiscard]] boost::system::result> seckey_negate( + std::span secret_key) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + return webcpp::crypto::detail::secp256k1_tweaked_secret(secret_key, nullptr, nullptr); +} + +/** + * A public key P plus t times the generator (`secp256k1_ec_pubkey_tweak_add`). + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param parsed_key The key P. + * @param tweak_bytes The 32-byte tweak t, a big-endian scalar. + * @return The tweaked key; `invalid_secret_key` for a tweak not below the group order, or a + * sum at infinity. + */ +template +[[nodiscard]] boost::system::result pubkey_tweak_add( + public_key const& parsed_key, std::span tweak_bytes) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + return webcpp::crypto::detail::secp256k1_tweaked_key(parsed_key, tweak_bytes, + secp256k1_ec_pubkey_tweak_add); +} + +/** + * A public key P times t (`secp256k1_ec_pubkey_tweak_mul`). + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param parsed_key The key P. + * @param tweak_bytes The 32-byte tweak t, a big-endian scalar. + * @return The tweaked key; `invalid_secret_key` for a tweak that is zero or not below the + * group order. + */ +template +[[nodiscard]] boost::system::result pubkey_tweak_mul( + public_key const& parsed_key, std::span tweak_bytes) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + return webcpp::crypto::detail::secp256k1_tweaked_key(parsed_key, tweak_bytes, + secp256k1_ec_pubkey_tweak_mul); +} + +/** + * The negation -P of a public key (`secp256k1_ec_pubkey_negate`), which never fails. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param parsed_key The key P. + * @return -P, the public key of the negated secret key. + */ +template +[[nodiscard]] public_key pubkey_negate(public_key const& parsed_key) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + public_key negated_key = parsed_key; + // A valid point always negates: libsecp256k1 returns 1. + static_cast(secp256k1_ec_pubkey_negate( + secp256k1_context_static, &webcpp::crypto::detail::secp256k1_access::point(negated_key))); + return negated_key; +} + +/** + * The sum of public keys (`secp256k1_ec_pubkey_combine`), in a workspace the caller lends for + * libsecp256k1's array of pointers. + * + * Tip: the sum of keys an attacker chooses is not a multisignature's key: the attacker picks + * its key as another's negation plus its own (a rogue key), and the sum is its alone. MuSig2 + * aggregates keys safely. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param parsed_keys The keys, at least one. + * @param pointer_space At least `combine_workspace_size(parsed_keys.size())` bytes; zero when + * the function returns. + * @return The sum; `invalid_input_size` for no keys or a short workspace; `invalid_public_key` + * for a sum at infinity. + */ +template +[[nodiscard]] boost::system::result pubkey_combine( + std::span parsed_keys, workspace pointer_space) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + // libsecp256k1 checks the count with ARG_CHECK, whose callback aborts: refused first here. + if (parsed_keys.empty() || pointer_space.size() < combine_workspace_size(parsed_keys.size())) { + return error::invalid_input_size; + } + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + webcpp::crypto::detail::secp256k1_workspace carver(pointer_space); + auto* const key_pointers = carver.take(parsed_keys.size()); + if (key_pointers == nullptr) { + return error::invalid_input_size; + } + for (std::size_t key_index = 0; key_index < parsed_keys.size(); ++key_index) { + key_pointers[key_index] = &access::point(parsed_keys[key_index]); + } + public_key combined_key = access::make_public_key(); + if (secp256k1_ec_pubkey_combine(secp256k1_context_static, &access::point(combined_key), + key_pointers, parsed_keys.size()) == 0) { + return error::invalid_public_key; + } + return combined_key; +} + +} // namespace webcpp::crypto::curves::secp256k1 + +#endif // WEBCPP_CRYPTO_CURVES_SECP256K1_TWEAK_HPP diff --git a/test/Jamfile b/test/Jamfile index 2977de00..228907a9 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -66,6 +66,7 @@ webcpp.headers-alone crypto : ../include # WEBCPP_CRYPTO_HAS_SECP256K1 (without it, each stops with its message). webcpp.headers-alone crypto : ../include : crypto/curves/secp256k1.hpp crypto/backends/secp256k1.hpp + crypto/curves/secp256k1/tweak.hpp crypto/curves/secp256k1/formats.hpp : /third_party//secp256k1 ; # config.hpp defines WEBCPP_CRYPTO_NO_EXCEPTIONS exactly when webcpp has no @@ -217,6 +218,19 @@ crypto-run secp256k1_recovery : secp256k1_recovery_test.cpp : /third_pa # libsecp256k1's recovery and ElligatorSwift modules called through its C API, # which stays reachable beside the wrappers, and compared with them. crypto-run secp256k1_c_api : secp256k1_c_api_test.cpp : /third_party//secp256k1 ; +# Tweaks, negation and combination of secret and public keys, against the +# C API, and their refusals. +crypto-run secp256k1_tweak : secp256k1_tweak_test.cpp : /third_party//secp256k1 ; +# SPKI and PKCS#8: round trips, Wycheproof's SPKIs, malformed inputs and, on +# Emscripten, node's crypto module as the outside oracle. +crypto-run secp256k1_formats : secp256k1_formats_test.cpp + : /third_party//secp256k1 /third_party//wycheproof + /webcpp//boost_json ; +# The same source with OpenSSL as the outside oracle: its keys and encodings. +crypto-run secp256k1_formats_openssl : secp256k1_formats_test.cpp + : /third_party//secp256k1 /webcpp/crypto//openssl + WEBCPP_TEST_OPENSSL_ORACLE + : native wasip2 wasip3 ; crypto-run secp256k1_der : secp256k1_der_test.cpp : /third_party//secp256k1 /third_party//wycheproof /webcpp//boost_json ; diff --git a/test/crypto_secp256k1_test.cpp b/test/crypto_secp256k1_test.cpp index 00620454..77aaed58 100644 --- a/test/crypto_secp256k1_test.cpp +++ b/test/crypto_secp256k1_test.cpp @@ -5,8 +5,8 @@ // https://www.boost.org/LICENSE_1_0.txt) // in a program that links libsecp256k1 brings secp256k1's header: its -// branch for WEBCPP_CRYPTO_HAS_SECP256K1 compiles, and the key pair and both verifications -// are declared through it alone. +// branch for WEBCPP_CRYPTO_HAS_SECP256K1 compiles, and the key pair, both verifications, the +// tweaks of tweak.hpp and the formats of formats.hpp are declared through it alone. #include @@ -21,6 +21,10 @@ namespace secp = webcpp::crypto::curves::secp256k1; static_assert(std::is_same_v); static_assert(std::is_function_v)>); static_assert(std::is_function_v)>); +static_assert(std::is_function_v)>); +static_assert(std::is_function_v)>); +static_assert(std::is_function_v)>); +static_assert(std::is_function_v)>); int main() { return 0; diff --git a/test/secp256k1_allocation_test.cpp b/test/secp256k1_allocation_test.cpp index 3294a8e1..1eff14c4 100644 --- a/test/secp256k1_allocation_test.cpp +++ b/test/secp256k1_allocation_test.cpp @@ -9,10 +9,14 @@ // and never through operator new nor the C library's allocator where the target lets a // program count it; the signatures (hedged and recoverable too), the three forms of ECDH, the // public keys in both forms, both verifications, the parsed public key, recovery, the DER and -// low-S functions and the x-only tweak allocate nothing, each counted alone; the destructor gives -// the block back; a refused make allocates nothing. A control proves the counter moves. +// low-S functions, the x-only tweak, the tweaks, negations and combination of tweak.hpp and the +// SPKI and PKCS#8 encoders and decoders of formats.hpp allocate nothing, each counted alone +// (decode_pkcs8's key pair takes its one block from the resource it is given); the destructor +// gives the block back; a refused make allocates nothing. A control proves the counter moves. #include +#include +#include #include #include "support/counting.hpp" @@ -141,8 +145,39 @@ int main() { none("recover", [&] { return secp::recover(*recoverable, message); }); none("public_key <=>", [&] { return (*parsed <=> *parsed) == 0; }); none("keypair::tweak_xonly", [&] { return key.tweak_xonly(message); }); + + // tweak.hpp: the tweaks, the negations and the combination, its workspace on the stack. + none("seckey_tweak_add", [&] { return secp::seckey_tweak_add(secret, message); }); + none("seckey_tweak_mul", [&] { return secp::seckey_tweak_mul(secret, message); }); + none("seckey_negate", [&] { return secp::seckey_negate(secret); }); + none("pubkey_tweak_add", [&] { return secp::pubkey_tweak_add(*parsed, message); }); + none("pubkey_tweak_mul", [&] { return secp::pubkey_tweak_mul(*parsed, message); }); + none("pubkey_negate", [&] { return secp::pubkey_negate(*parsed) != *parsed; }); + alignas(std::max_align_t) std::array space{}; + std::array const pair{*parsed, *parsed}; + none("pubkey_combine", [&] { return secp::pubkey_combine(pair, space); }); + + // formats.hpp: both SPKIs and the PKCS#8, written and read. + std::array encoding{}; + std::size_t spki_size = 0; + none("encode_spki", [&] { + auto const r = secp::encode_spki(*parsed, encoding, secp::point_form::uncompressed); + spki_size = r ? *r : 0; + return r; + }); + none("decode_spki", [&] { + return secp::decode_spki(std::span(encoding).first(spki_size)); + }); + none("encode_pkcs8", [&] { return secp::encode_pkcs8(key, encoding); }); BOOST_TEST_EQ(resource.allocated, 1U); BOOST_TEST_EQ(resource.deallocated, 0U); + + // decode_pkcs8 makes a key pair: its one block from the resource it is given, nothing + // else. + counting_resource decoded_resource; + none("decode_pkcs8", [&] { return secp::decode_pkcs8(encoding, &decoded_resource); }); + BOOST_TEST_EQ(decoded_resource.allocated, 1U); + BOOST_TEST_EQ(decoded_resource.deallocated, 1U); } // The destructor gave the block back, once. BOOST_TEST_EQ(resource.deallocated, 1U); diff --git a/test/secp256k1_formats_test.cpp b/test/secp256k1_formats_test.cpp new file mode 100644 index 00000000..3cf43bf1 --- /dev/null +++ b/test/secp256k1_formats_test.cpp @@ -0,0 +1,689 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// secp256k1's keys in files: RFC 5480's SPKI in both point forms and PKCS#8 with RFC 5915's +// ECPrivateKey, strict. The constants equal the DER a small builder writes here from the ASN.1; +// 64 seeded key pairs round-trip; Wycheproof's 752 SPKIs of its ECDH vectors decode exactly +// where version 0.1's parser takes their point (WEBCPP_TEST_WYCHEPROOF); every malformed input +// is invalid_encoding, and an encoder's refusal writes nothing. The outside oracles: OpenSSL's +// keys and encodings (WEBCPP_TEST_OPENSSL_ORACLE: natively and on WASI), and node's crypto +// module under Emscripten. + +#include +#include +#include +#include + +#include "support/hex.hpp" + +#include +#include + +#include + +#ifdef WEBCPP_TEST_WYCHEPROOF +#include "support/test_data.hpp" + +#include +#endif + +#ifdef WEBCPP_TEST_OPENSSL_ORACLE +#include +#include +#include +#include +#include +#include +#endif + +#ifdef __EMSCRIPTEN__ +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace secp = webcpp::crypto::curves::secp256k1; +namespace test = webcpp::test; + +namespace { + +using bytes = std::vector; + +static_assert(secp::spki_compressed_size == 56); +static_assert(secp::spki_uncompressed_size == 88); +static_assert(secp::max_spki_size == 88); +static_assert(secp::max_pkcs8_size == 135); +static_assert(crypto::detail::secp256k1_spki_compressed_prefix.size() + 33 == + secp::spki_compressed_size); +static_assert(crypto::detail::secp256k1_spki_uncompressed_prefix.size() + 65 == + secp::spki_uncompressed_size); +static_assert(crypto::detail::secp256k1_pkcs8_prefix.size() + 32 + + crypto::detail::secp256k1_pkcs8_infix.size() + 65 == + secp::max_pkcs8_size); +static_assert(std::is_same_v())), + boost::system::result>); + +// The ASN.1 of the formats, written by hand here so that the header's constants are checked +// against something they were not copied from. +bytes cat(std::initializer_list parts) { + bytes out; + for (auto const& part : parts) { + out.insert(out.end(), part.begin(), part.end()); + } + return out; +} + +// A DER element: the tag, the length in its shortest form, the content. +bytes der(std::uint8_t tag, bytes const& content) { + bytes out{tag}; + if (content.size() < 0x80) { + out.push_back(static_cast(content.size())); + } else { + out.push_back(0x81); + out.push_back(static_cast(content.size())); + } + out.insert(out.end(), content.begin(), content.end()); + return out; +} + +// The OIDs' contents: id-ecPublicKey (1.2.840.10045.2.1), secp256k1 (1.3.132.0.10) and P-256 +// (1.2.840.10045.3.1.7). +bytes ec_public_key_oid() { + return test::from_hex("2a8648ce3d0201"); +} + +bytes secp256k1_oid() { + return test::from_hex("2b8104000a"); +} + +bytes p256_oid() { + return test::from_hex("2a8648ce3d030107"); +} + +bytes algorithm(bytes const& curve) { + return der(0x30, cat({der(0x06, ec_public_key_oid()), der(0x06, curve)})); +} + +bytes bit_string(bytes const& point) { + return der(0x03, cat({{0x00}, point})); +} + +bytes spki_of(bytes const& curve, bytes const& point) { + return der(0x30, cat({algorithm(curve), bit_string(point)})); +} + +struct ec_private_key { + std::uint8_t version = 1; + bytes secret; + bool parameters = false; + bytes point; // none when empty +}; + +bytes encoded(ec_private_key const& key) { + bytes content = cat({der(0x02, {key.version}), der(0x04, key.secret)}); + if (key.parameters) { + content = cat({content, der(0xa0, der(0x06, secp256k1_oid()))}); + } + if (!key.point.empty()) { + content = cat({content, der(0xa1, bit_string(key.point))}); + } + return der(0x30, content); +} + +bytes pkcs8_of(std::uint8_t version, bytes const& curve, ec_private_key const& key) { + return der(0x30, cat({der(0x02, {version}), algorithm(curve), der(0x04, encoded(key))})); +} + +// A key pair from the generator: a secret make refuses is drawn again. +std::pair draw(std::mt19937_64& generator) { + for (;;) { + bytes secret(32); + for (auto& octet : secret) { + octet = static_cast(generator()); + } + auto made = secp::keypair::make(secret); + if (made) { + return {std::move(*made), secret}; + } + } +} + +secp::public_key public_of(secp::keypair const& key) { + auto const encoded_key = key.public_key(); + auto const parsed = secp::parse_public_key(*encoded_key); + if (!BOOST_TEST(parsed.has_value())) { + std::exit(boost::report_errors()); + } + return *parsed; +} + +bytes uncompressed_of(secp::keypair const& key) { + auto const point = key.public_key_uncompressed(); + return {point->begin(), point->end()}; +} + +bytes compressed_of(secp::keypair const& key) { + auto const point = key.public_key(); + return {point->begin(), point->end()}; +} + +bytes spki(secp::public_key const& key, secp::point_form form) { + std::array out{}; + auto const size = secp::encode_spki(key, out, form); + if (!BOOST_TEST(size.has_value())) { + return {}; + } + return {out.begin(), out.begin() + static_cast(*size)}; +} + +bytes pkcs8(secp::keypair const& key) { + std::array out{}; + auto const size = secp::encode_pkcs8(key, out); + if (!BOOST_TEST(size.has_value())) { + return {}; + } + return {out.begin(), out.begin() + static_cast(*size)}; +} + +// The constants are the DER the builder writes. +void constants() { + std::mt19937_64 generator(0xf0a3a75ULL); + auto const [key, secret] = draw(generator); + auto const compressed = compressed_of(key); + auto const uncompressed = uncompressed_of(key); + BOOST_TEST_EQ(test::to_hex(spki(public_of(key), secp::point_form::compressed)), + test::to_hex(spki_of(secp256k1_oid(), compressed))); + BOOST_TEST_EQ(test::to_hex(spki(public_of(key), secp::point_form::uncompressed)), + test::to_hex(spki_of(secp256k1_oid(), uncompressed))); + BOOST_TEST_EQ( + test::to_hex(pkcs8(key)), + test::to_hex(pkcs8_of( + 0, secp256k1_oid(), + {.version = 1, .secret = secret, .parameters = false, .point = uncompressed}))); + // The default form is compressed. + std::array out{}; + auto const size = secp::encode_spki(public_of(key), out); + BOOST_TEST(size && *size == secp::spki_compressed_size); +} + +// One key pair's SPKI in `form` decodes to its key and encodes again to the same bytes. +void spki_round_trip(secp::public_key const& expected, secp::point_form form) { + auto const encoding = spki(expected, form); + BOOST_TEST_EQ(encoding.size(), form == secp::point_form::compressed + ? secp::spki_compressed_size + : secp::spki_uncompressed_size); + auto const decoded = secp::decode_spki(encoding); + if (BOOST_TEST(decoded.has_value())) { + BOOST_TEST(*decoded == expected); + BOOST_TEST(spki(*decoded, form) == encoding); + } +} + +// One key pair's PKCS#8 holds its secret, decodes to a key pair of the same key that signs as +// the original does, and encodes again to the same bytes. +void pkcs8_round_trip(secp::keypair const& key, bytes const& secret) { + auto const private_encoding = pkcs8(key); + BOOST_TEST_EQ(private_encoding.size(), secp::max_pkcs8_size); + BOOST_TEST(std::ranges::equal(std::span(private_encoding).subspan(33, 32), secret)); + auto const decoded = secp::decode_pkcs8(private_encoding); + if (!BOOST_TEST(decoded.has_value())) { + return; + } + BOOST_TEST(public_of(*decoded) == public_of(key)); + BOOST_TEST(pkcs8(*decoded) == private_encoding); + std::array const hash{1, 2, 3}; + BOOST_TEST(decoded->sign_ecdsa(hash).value() == key.sign_ecdsa(hash).value()); +} + +// 64 seeded key pairs, each SPKI in both forms and each PKCS#8. +void round_trips() { + std::mt19937_64 generator(0x5b1c0de5ULL); + for (int round = 0; round < 64; ++round) { + auto const [key, secret] = draw(generator); + spki_round_trip(public_of(key), secp::point_form::compressed); + spki_round_trip(public_of(key), secp::point_form::uncompressed); + pkcs8_round_trip(key, secret); + } +} + +// An encoder that refuses writes nothing: a short buffer, a moved-from key pair. +// NOLINTBEGIN(bugprone-use-after-move) +void encoder_refusals() { + std::mt19937_64 generator(0xe2c0de2ULL); + auto [key, secret] = draw(generator); + auto const parsed = public_of(key); + std::array out{}; + out.fill(0xa5); + auto const untouched = [&out] { + return std::ranges::all_of(out, [](std::uint8_t b) { return b == 0xa5; }); + }; + for (auto const form : {secp::point_form::compressed, secp::point_form::uncompressed}) { + auto const refused = + secp::encode_spki(parsed, std::span(out).first(secp::max_spki_size - 1), form); + BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_input_size); + } + auto const short_pkcs8 = + secp::encode_pkcs8(key, std::span(out).first(secp::max_pkcs8_size - 1)); + BOOST_TEST(short_pkcs8.has_error() && short_pkcs8.error() == crypto::error::invalid_input_size); + BOOST_TEST(untouched()); + secp::keypair const moved = std::move(key); + auto const empty = secp::encode_pkcs8(key, out); + BOOST_TEST(empty.has_error() && empty.error() == crypto::error::invalid_state); + BOOST_TEST(untouched()); + BOOST_TEST(secp::encode_pkcs8(moved, out).has_value()); +} + +// NOLINTEND(bugprone-use-after-move) + +void refused_spki(std::string const& label, bytes const& encoding) { + auto const decoded = secp::decode_spki(encoding); + if (!BOOST_TEST(decoded.has_error()) || + !BOOST_TEST(decoded.error() == crypto::error::invalid_encoding)) { + BOOST_ERROR(label.c_str()); + } +} + +void refused_pkcs8(std::string const& label, bytes const& encoding) { + auto const decoded = secp::decode_pkcs8(encoding); + if (!BOOST_TEST(decoded.has_error()) || + !BOOST_TEST(decoded.error() == crypto::error::invalid_encoding)) { + BOOST_ERROR(label.c_str()); + } +} + +// The group order n. +bytes order() { + return test::from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +} + +// Every malformed input is invalid_encoding. +void malformed() { + std::mt19937_64 generator(0xbad0de5ULL); + auto const [key, secret] = draw(generator); + auto const [other, other_secret] = draw(generator); + auto const compressed = compressed_of(key); + auto const uncompressed = uncompressed_of(key); + auto const good_compressed = spki_of(secp256k1_oid(), compressed); + auto const good_uncompressed = spki_of(secp256k1_oid(), uncompressed); + auto const good_pkcs8 = + pkcs8_of(0, secp256k1_oid(), + {.version = 1, .secret = secret, .parameters = false, .point = uncompressed}); + BOOST_TEST(secp::decode_spki(good_compressed).has_value()); + BOOST_TEST(secp::decode_spki(good_uncompressed).has_value()); + BOOST_TEST(secp::decode_pkcs8(good_pkcs8).has_value()); + + refused_spki("empty", {}); + refused_spki("prefix alone", spki_of(secp256k1_oid(), {})); + refused_spki("P-256's OID, uncompressed", spki_of(p256_oid(), uncompressed)); + refused_spki("P-256's OID, compressed", spki_of(p256_oid(), compressed)); + refused_spki("trailing byte", cat({good_uncompressed, {0x00}})); + refused_spki("trailing byte, compressed", cat({good_compressed, {0x00}})); + refused_spki("truncated", bytes(good_uncompressed.begin(), good_uncompressed.end() - 1)); + // 30 81 56 ...: the outer length in long form, which DER forbids for a length below 128. + refused_spki( + "long-form length", + cat({{0x30, 0x81, 0x56}, bytes(good_uncompressed.begin() + 2, good_uncompressed.end())})); + // A point of the other form under each prefix, the lengths left as the prefix says. + refused_spki( + "compressed point, uncompressed prefix", + cat({bytes(good_uncompressed.begin(), good_uncompressed.begin() + 23), compressed})); + refused_spki("uncompressed point, compressed prefix", + cat({bytes(good_compressed.begin(), good_compressed.begin() + 23), uncompressed})); + // X9.62's hybrid prefixes, 06 and 07, with the point's own parity: a valid point. + auto hybrid = uncompressed; + hybrid[0] = static_cast(0x06U | (uncompressed[64] & 1U)); + refused_spki("hybrid prefix", spki_of(secp256k1_oid(), hybrid)); + hybrid[0] ^= 1U; + refused_spki("hybrid prefix, wrong parity", spki_of(secp256k1_oid(), hybrid)); + // A point off the curve, and an x with no y. + auto off_curve = uncompressed; + off_curve[64] ^= 1U; + refused_spki("off the curve", spki_of(secp256k1_oid(), off_curve)); + bytes no_y(33); + no_y[0] = 0x02; + no_y[32] = 0x05; // x = 5 is no point's x + refused_spki("x with no y", spki_of(secp256k1_oid(), no_y)); + // The BIT STRING's unused-bits byte not zero. + auto unused_bits = good_uncompressed; + unused_bits[22] = 0x01; + refused_spki("unused bits", unused_bits); + + refused_pkcs8("empty", {}); + refused_pkcs8( + "P-256's OID", + pkcs8_of(0, p256_oid(), + {.version = 1, .secret = secret, .parameters = false, .point = uncompressed})); + refused_pkcs8("trailing byte", cat({good_pkcs8, {0x00}})); + refused_pkcs8("truncated", bytes(good_pkcs8.begin(), good_pkcs8.end() - 1)); + // OpenSSL's -nopubkey form: no [1] publicKey. + refused_pkcs8("no public key", + pkcs8_of(0, secp256k1_oid(), + {.version = 1, .secret = secret, .parameters = false, .point = {}})); + // The curve's OID again in ECPrivateKey's [0] parameters. + refused_pkcs8( + "[0] parameters", + pkcs8_of(0, secp256k1_oid(), + {.version = 1, .secret = secret, .parameters = true, .point = uncompressed})); + // OneAsymmetricKey version 2 (the value 1). + refused_pkcs8( + "version 1", + pkcs8_of(1, secp256k1_oid(), + {.version = 1, .secret = secret, .parameters = false, .point = uncompressed})); + refused_pkcs8( + "ECPrivateKey version 0", + pkcs8_of(0, secp256k1_oid(), + {.version = 0, .secret = secret, .parameters = false, .point = uncompressed})); + // The public key of another secret. + refused_pkcs8("another key's public key", pkcs8_of(0, secp256k1_oid(), + { + .version = 1, + .secret = secret, + .parameters = false, + .point = uncompressed_of(other), + })); + // The secret's own public key, compressed: OpenSSL's form for a key set to compressed, 102 + // bytes, whose outer length fits the short form. + auto const compressed_inside = + pkcs8_of(0, secp256k1_oid(), + {.version = 1, .secret = secret, .parameters = false, .point = compressed}); + BOOST_TEST_EQ(compressed_inside.size(), 102U); + refused_pkcs8("compressed public key", compressed_inside); + // A public key off the curve. + refused_pkcs8( + "public key off the curve", + pkcs8_of(0, secp256k1_oid(), + {.version = 1, .secret = secret, .parameters = false, .point = off_curve})); + // A secret of zero, and one equal to the group order. + refused_pkcs8( + "zero secret", + pkcs8_of(0, secp256k1_oid(), + {.version = 1, .secret = bytes(32), .parameters = false, .point = uncompressed})); + refused_pkcs8( + "order-sized secret", + pkcs8_of(0, secp256k1_oid(), + {.version = 1, .secret = order(), .parameters = false, .point = uncompressed})); + // The outer length, 132, takes the long form 81 84; the longer 82 00 84 is not DER. + refused_pkcs8("non-minimal long form", + cat({{0x30, 0x82, 0x00, 0x84}, bytes(good_pkcs8.begin() + 3, good_pkcs8.end())})); +} + +#ifdef WEBCPP_TEST_WYCHEPROOF +struct wycheproof_counts { + int total = 0; + int taken = 0; + int other = 0; + int decoded = 0; + int refused = 0; +}; + +// One SPKI of the file: refused unless it is in one of the two forms and its point parses +// with version 0.1's parser; decoded, it encodes again to the same bytes. +void wycheproof_case(std::string const& label, std::string_view hex, wycheproof_counts& counts) { + constexpr std::string_view uncompressed_prefix = + "3056301006072a8648ce3d020106052b8104000a034200"; + constexpr std::string_view compressed_prefix = "3036301006072a8648ce3d020106052b8104000a032200"; + ++counts.total; + auto const encoding = test::from_hex(hex); + auto const result = secp::decode_spki(encoding); + bool const uncompressed = hex.size() == std::size_t{2} * secp::spki_uncompressed_size && + hex.starts_with(uncompressed_prefix); + bool const compressed = hex.size() == std::size_t{2} * secp::spki_compressed_size && + hex.starts_with(compressed_prefix); + secp256k1_pubkey point{}; + bool const parses = (uncompressed || compressed) && crypto::detail::secp256k1_parse_public_key( + std::span(encoding).subspan(23), point); + if (!uncompressed && !compressed) { + ++counts.other; + } else { + ++counts.taken; + ++(parses ? counts.decoded : counts.refused); + } + if (parses) { + auto const form = + compressed ? secp::point_form::compressed : secp::point_form::uncompressed; + if (!BOOST_TEST(result.has_value()) || !BOOST_TEST(spki(*result, form) == encoding)) { + BOOST_ERROR(label.c_str()); + } + } else if (!BOOST_TEST(result.has_error() && + result.error() == crypto::error::invalid_encoding)) { + BOOST_ERROR(label.c_str()); + } +} + +// Wycheproof's ECDH vectors carry each peer key as an SPKI: the 496 in either of the two forms +// version 0.1's test takes decode exactly where version 0.1's parser takes their point, and the +// other 256 (other curves' parameters, other encodings, the hybrid form) are refused. +void wycheproof() { + auto const text = + test::read_file(WEBCPP_TEST_WYCHEPROOF "/testvectors_v1/ecdh_secp256k1_test.json"); + boost::system::error_code ec; + auto const doc = boost::json::parse(text, ec); + if (!BOOST_TEST(!ec)) { + return; + } + wycheproof_counts counts; + for (auto const& group : doc.at("testGroups").as_array()) { + for (auto const& t : group.at("tests").as_array()) { + wycheproof_case("tcId " + std::to_string(t.at("tcId").to_number()), + std::string_view(t.at("public").as_string()), counts); + } + } + std::cout << "wycheproof spki: total=" << counts.total << " taken=" << counts.taken + << " decoded=" << counts.decoded << " refused_point=" << counts.refused + << " refused_other=" << counts.other << '\n'; + BOOST_TEST_EQ(counts.total, 752); + BOOST_TEST_EQ(counts.taken, 496); + BOOST_TEST_EQ(counts.other, 256); + BOOST_TEST_EQ(counts.decoded, 474); + BOOST_TEST_EQ(counts.refused, 22); +} +#endif + +#ifdef WEBCPP_TEST_OPENSSL_ORACLE +bytes openssl_pkcs8(EVP_PKEY const* key) { + // NOLINTNEXTLINE(bugprone-signed-bitwise): OpenSSL's macro ors signed constants + int const selection = EVP_PKEY_KEYPAIR; + OSSL_ENCODER_CTX* context = + OSSL_ENCODER_CTX_new_for_pkey(key, selection, "DER", "PrivateKeyInfo", nullptr); + unsigned char* data = nullptr; + std::size_t size = 0; + bytes out; + if (BOOST_TEST(context != nullptr) && + BOOST_TEST(OSSL_ENCODER_to_data(context, &data, &size) == 1)) { + out.assign(data, data + size); + } + OPENSSL_free(data); + OSSL_ENCODER_CTX_free(context); + return out; +} + +bytes openssl_spki(EVP_PKEY const* key) { + int const size = i2d_PUBKEY(key, nullptr); + if (!BOOST_TEST(size > 0)) { + return {}; + } + bytes out(static_cast(size)); + unsigned char* cursor = out.data(); + BOOST_TEST_EQ(i2d_PUBKEY(key, &cursor), size); + return out; +} + +// webcpp's SPKI read by OpenSSL is the key it came from. +void openssl_reads_spki(EVP_PKEY const* key, bytes const& encoding) { + unsigned char const* cursor = encoding.data(); + EVP_PKEY* read = d2i_PUBKEY(nullptr, &cursor, static_cast(encoding.size())); + BOOST_TEST(read != nullptr && EVP_PKEY_eq(read, key) == 1); + BOOST_TEST(cursor == encoding.data() + encoding.size()); + EVP_PKEY_free(read); +} + +// OpenSSL's key in its default uncompressed form: webcpp decodes its PKCS#8 and SPKI and encodes +// the same bytes, and OpenSSL reads webcpp's encodings back to the same key. +void openssl_default_form(EVP_PKEY const* key) { + auto const private_encoding = openssl_pkcs8(key); + auto const uncompressed = openssl_spki(key); + BOOST_TEST_EQ(private_encoding.size(), secp::max_pkcs8_size); + BOOST_TEST_EQ(uncompressed.size(), secp::spki_uncompressed_size); + auto const pair = secp::decode_pkcs8(private_encoding); + auto const from_uncompressed = secp::decode_spki(uncompressed); + if (!BOOST_TEST(pair.has_value()) || !BOOST_TEST(from_uncompressed.has_value())) { + return; + } + BOOST_TEST(pkcs8(*pair) == private_encoding); + BOOST_TEST(spki(*from_uncompressed, secp::point_form::uncompressed) == uncompressed); + BOOST_TEST(public_of(*pair) == *from_uncompressed); + auto const mine = pkcs8(*pair); + unsigned char const* cursor = mine.data(); + EVP_PKEY* read = d2i_AutoPrivateKey(nullptr, &cursor, static_cast(mine.size())); + BOOST_TEST(read != nullptr && EVP_PKEY_eq(read, key) == 1); + BOOST_TEST(read != nullptr && openssl_pkcs8(read) == private_encoding); + EVP_PKEY_free(read); + openssl_reads_spki(key, spki(*from_uncompressed, secp::point_form::uncompressed)); + openssl_reads_spki(key, spki(*from_uncompressed, secp::point_form::compressed)); +} + +// The same key set to the compressed form: webcpp decodes OpenSSL's compressed SPKI and encodes +// the same bytes; OpenSSL now writes the compressed point into ECPrivateKey's [1] too, 102 +// bytes, which webcpp refuses. +void openssl_compressed_form(EVP_PKEY* key) { + BOOST_TEST(EVP_PKEY_set_utf8_string_param(key, OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, + "compressed") == 1); + auto const compressed = openssl_spki(key); + BOOST_TEST_EQ(compressed.size(), secp::spki_compressed_size); + auto const from_compressed = secp::decode_spki(compressed); + if (BOOST_TEST(from_compressed.has_value())) { + BOOST_TEST(spki(*from_compressed, secp::point_form::compressed) == compressed); + openssl_reads_spki(key, spki(*from_compressed, secp::point_form::uncompressed)); + } + auto const compressed_private = openssl_pkcs8(key); + BOOST_TEST_EQ(compressed_private.size(), 102U); + auto const refused = secp::decode_pkcs8(compressed_private); + BOOST_TEST(refused.has_error() && refused.error() == crypto::error::invalid_encoding); +} + +// 64 keys OpenSSL makes, in both forms; OpenSSL's error queue is left empty. +void openssl_oracle() { + for (int round = 0; round < 64; ++round) { + EVP_PKEY* key = EVP_PKEY_Q_keygen(nullptr, nullptr, "EC", "secp256k1"); + if (!BOOST_TEST(key != nullptr)) { + break; + } + openssl_default_form(key); + openssl_compressed_form(key); + EVP_PKEY_free(key); + } + BOOST_TEST_EQ(ERR_peek_error(), 0UL); +} +#endif + +#ifdef __EMSCRIPTEN__ +// node's crypto module (synchronous: no JSPI): a PKCS#8 or an SPKI imported and exported again +// as DER. Each writes the bytes to `output` and returns their count, or -1 when node refused +// (the message goes to the console). +// clang-format off +EM_JS(int, node_pkcs8, (const std::uint8_t* input, std::size_t input_size, std::uint8_t* output), { + try { + const crypto = process.getBuiltinModule('node:crypto'); + const der = HEAPU8.slice(input, input + input_size); + const key = crypto.createPrivateKey({key: der, format: 'der', type: 'pkcs8'}); + const back = new Uint8Array(key.export({format: 'der', type: 'pkcs8'})); + HEAPU8.set(back, output); + return back.length; + } catch (e) { + console.error("node pkcs8: " + e); + return -1; + } +}); + +EM_JS(int, node_spki, (const std::uint8_t* input, std::size_t input_size, std::uint8_t* output), { + try { + const crypto = process.getBuiltinModule('node:crypto'); + const der = HEAPU8.slice(input, input + input_size); + const key = crypto.createPublicKey({key: der, format: 'der', type: 'spki'}); + const back = new Uint8Array(key.export({format: 'der', type: 'spki'})); + HEAPU8.set(back, output); + return back.length; + } catch (e) { + console.error("node spki: " + e); + return -1; + } +}); + +EM_JS(int, node_public_of, (const std::uint8_t* input, std::size_t input_size, + std::uint8_t* output), { + try { + const crypto = process.getBuiltinModule('node:crypto'); + const der = HEAPU8.slice(input, input + input_size); + const key = crypto.createPrivateKey({key: der, format: 'der', type: 'pkcs8'}); + const back = new Uint8Array( + crypto.createPublicKey(key).export({format: 'der', type: 'spki'})); + HEAPU8.set(back, output); + return back.length; + } catch (e) { + console.error("node public key: " + e); + return -1; + } +}); +// clang-format on + +template +bytes through_node(Call call, bytes const& input) { + std::array out{}; + int const size = call(input.data(), input.size(), out.data()); + if (!BOOST_TEST(size > 0)) { + return {}; + } + return {out.begin(), out.begin() + size}; +} + +// 64 seeded key pairs: node's crypto gives webcpp's PKCS#8 and both SPKIs back, and derives +// from the PKCS#8 the public key webcpp encodes. +void node_oracle() { + std::mt19937_64 generator(0x0de0de5ULL); + for (int round = 0; round < 64; ++round) { + auto const [key, secret] = draw(generator); + auto const private_encoding = pkcs8(key); + auto const uncompressed = spki(public_of(key), secp::point_form::uncompressed); + auto const compressed = spki(public_of(key), secp::point_form::compressed); + BOOST_TEST(through_node(node_pkcs8, private_encoding) == private_encoding); + BOOST_TEST(through_node(node_spki, uncompressed) == uncompressed); + BOOST_TEST(through_node(node_spki, compressed) == compressed); + BOOST_TEST(through_node(node_public_of, private_encoding) == uncompressed); + } +} +#endif + +} // namespace + +int main() { + constants(); + round_trips(); + encoder_refusals(); + malformed(); +#ifdef WEBCPP_TEST_WYCHEPROOF + wycheproof(); +#endif +#ifdef WEBCPP_TEST_OPENSSL_ORACLE + openssl_oracle(); +#endif +#ifdef __EMSCRIPTEN__ + node_oracle(); +#endif + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/secp256k1_tweak_test.cpp b/test/secp256k1_tweak_test.cpp new file mode 100644 index 00000000..84e12871 --- /dev/null +++ b/test/secp256k1_tweak_test.cpp @@ -0,0 +1,345 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// secp256k1's tweaks, negation and combination of secret and public keys. Over 64 seeded +// secrets d and tweaks t, with P(x) the public key of the secret x: P(d) + tG is +// P(d + t), tP(d) is P(dt), -P(d) is P(-d), -(-d) is d, P(d) + P(t) is P(d + t), and each +// result equals libsecp256k1's C API called directly. The known answer 1 + 1, whose public key +// is 2G. The refusals: a tweak equal to the group order, a sum or a product that is zero, a +// zero or order-sized secret, a sum of keys at infinity, no keys and a short workspace. The +// workspace is zero after every call. + +#include +#include +#include +#include +#include + +#include "support/hex.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace secp = webcpp::crypto::curves::secp256k1; +namespace test = webcpp::test; + +namespace { + +using scalar = std::array; + +constexpr std::string_view order_hex = + "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"; + +static_assert(std::is_same_v(), + std::declval())), + boost::system::result>>); +static_assert(std::is_same_v(), + std::declval())), + boost::system::result>>); +static_assert(std::is_same_v())), + boost::system::result>>); +static_assert( + std::is_same_v(), + std::declval())), + boost::system::result>); +static_assert( + std::is_same_v(), + std::declval())), + boost::system::result>); +static_assert(std::is_same_v())), + secp::public_key>); +static_assert(std::is_same_v>); +static_assert(secp::combine_workspace_size(2) == + (2 * sizeof(secp256k1_pubkey const*)) + alignof(std::max_align_t)); +static_assert(noexcept(secp::pubkey_negate(std::declval()))); + +scalar to_scalar(std::span bytes) { + scalar out{}; + std::ranges::copy(bytes.first(32), out.begin()); + return out; +} + +scalar order() { + return to_scalar(test::from_hex(order_hex)); +} + +scalar small(std::uint8_t k) { + scalar out{}; + out.back() = k; + return out; +} + +// n - x in unsigned arithmetic, for x below the group order n. +scalar order_minus(std::span x) { + auto const n = order(); + scalar out{}; + unsigned borrow = 0; + for (std::size_t i = 32; i-- > 0;) { + unsigned const d = unsigned{n[i]} - unsigned{x[i]} - borrow; + out[i] = static_cast(d & 0xffU); + borrow = (d >> 8U) & 1U; + } + return out; +} + +// A scalar from the generator that libsecp256k1 takes as a secret key: not zero, below n. +scalar draw(std::mt19937_64& generator) { + for (;;) { + scalar out{}; + for (auto& octet : out) { + octet = static_cast(generator()); + } + if (secp256k1_ec_seckey_verify(secp256k1_context_static, out.data()) == 1) { + return out; + } + } +} + +// P(x): the public key of the secret x, through a key pair. +secp::public_key public_of(std::span secret_bytes) { + auto const key = secp::keypair::make(secret_bytes); + if (!BOOST_TEST(key.has_value())) { + std::exit(boost::report_errors()); + } + auto const encoded = key->public_key(); + auto const parsed = secp::parse_public_key(*encoded); + if (!BOOST_TEST(parsed.has_value())) { + std::exit(boost::report_errors()); + } + return *parsed; +} + +// The compressed bytes of a key libsecp256k1's C API computed. +std::array c_bytes(secp256k1_pubkey const& point) { + std::array out{}; + std::size_t size = out.size(); + // NOLINTNEXTLINE(bugprone-signed-bitwise): libsecp256k1's macro shifts a signed constant + unsigned const flags = SECP256K1_EC_COMPRESSED; + secp256k1_ec_pubkey_serialize(secp256k1_context_static, out.data(), &size, &point, flags); + return out; +} + +secp256k1_pubkey c_point(secp::public_key const& key) { + auto const encoded = secp::serialize_public_key(key); + secp256k1_pubkey out{}; + BOOST_TEST(secp256k1_ec_pubkey_parse(secp256k1_context_static, &out, encoded.data(), + encoded.size()) == 1); + return out; +} + +bool all_zero(std::span bytes) { + return std::ranges::all_of(bytes, [](std::byte b) { return b == std::byte{0}; }); +} + +// The secret results of one round against libsecp256k1's C API, called directly on copies of d. +void secrets_against_c_api(scalar const& d, scalar const& t, crypto::secret<32> const& sum, + crypto::secret<32> const& product, crypto::secret<32> const& negated) { + scalar c_sum = d; + scalar c_product = d; + scalar c_negated = d; + BOOST_TEST(secp256k1_ec_seckey_tweak_add(secp256k1_context_static, c_sum.data(), t.data()) == + 1); + BOOST_TEST( + secp256k1_ec_seckey_tweak_mul(secp256k1_context_static, c_product.data(), t.data()) == 1); + BOOST_TEST(secp256k1_ec_seckey_negate(secp256k1_context_static, c_negated.data()) == 1); + BOOST_TEST(std::ranges::equal(sum.bytes(), c_sum)); + BOOST_TEST(std::ranges::equal(product.bytes(), c_product)); + BOOST_TEST(std::ranges::equal(negated.bytes(), c_negated)); +} + +// The public results of one round against the C API: P + tG, tP, -P and P + T. +void keys_against_c_api(secp::public_key const& p_d, secp::public_key const& p_t, scalar const& t, + std::array const& results) { + auto c_added = c_point(p_d); + auto c_multiplied = c_point(p_d); + auto c_minus = c_point(p_d); + BOOST_TEST(secp256k1_ec_pubkey_tweak_add(secp256k1_context_static, &c_added, t.data()) == 1); + BOOST_TEST(secp256k1_ec_pubkey_tweak_mul(secp256k1_context_static, &c_multiplied, t.data()) == + 1); + BOOST_TEST(secp256k1_ec_pubkey_negate(secp256k1_context_static, &c_minus) == 1); + std::array const c_pair{c_point(p_d), c_point(p_t)}; + std::array const c_pointers{c_pair.data(), c_pair.data() + 1}; + secp256k1_pubkey c_combined{}; + BOOST_TEST(secp256k1_ec_pubkey_combine(secp256k1_context_static, &c_combined, c_pointers.data(), + c_pointers.size()) == 1); + std::array const expected{ + &c_added, + &c_multiplied, + &c_minus, + &c_combined, + }; + for (std::size_t i = 0; i < results.size(); ++i) { + BOOST_TEST(std::ranges::equal(secp::serialize_public_key(results.at(i)), + c_bytes(*expected.at(i)))); + } +} + +// One round: the identities, then each result against the C API. +void identity_round(scalar const& d, scalar const& t, secp::workspace space) { + auto const p_d = public_of(d); + auto const p_t = public_of(t); + auto const sum = secp::seckey_tweak_add(d, t); + auto const product = secp::seckey_tweak_mul(d, t); + auto const negated = secp::seckey_negate(d); + auto const p_sum = secp::pubkey_tweak_add(p_d, t); + auto const p_product = secp::pubkey_tweak_mul(p_d, t); + auto const p_negated = secp::pubkey_negate(p_d); + std::array const pair{p_d, p_t}; + auto const combined = secp::pubkey_combine(pair, space); + BOOST_TEST(all_zero(space)); + if (!BOOST_TEST(sum && product && negated && p_sum && p_product && combined)) { + return; + } + BOOST_TEST(*p_sum == public_of(sum->bytes())); + BOOST_TEST(*p_product == public_of(product->bytes())); + BOOST_TEST(p_negated == public_of(negated->bytes())); + BOOST_TEST(p_negated != p_d); + BOOST_TEST(secp::pubkey_negate(p_negated) == p_d); + BOOST_TEST(*combined == *p_sum); + // -(-d) holds d's bytes; each step bound to a name (secret's views are lvalue-only). + auto const twice = secp::seckey_negate(negated->bytes()); + BOOST_TEST(twice && std::ranges::equal(twice->bytes(), d)); + + secrets_against_c_api(d, t, *sum, *product, *negated); + keys_against_c_api(p_d, p_t, t, {*p_sum, *p_product, p_negated, *combined}); +} + +void identities() { + std::mt19937_64 generator(0x7e3a6b1c0ffeeULL); + alignas(std::max_align_t) std::array space{}; + for (int round = 0; round < 64; ++round) { + auto const d = draw(generator); + auto const t = draw(generator); + identity_round(d, t, space); + } +} + +// More keys than two, and one key alone, against the sum of their secrets. +void combinations() { + std::mt19937_64 generator(0xc0b1e5ULL); + std::vector secrets; + std::vector keys; + for (int i = 0; i < 5; ++i) { + secrets.push_back(draw(generator)); + keys.push_back(public_of(secrets.back())); + } + scalar total = secrets[0]; + for (std::size_t i = 1; i < secrets.size(); ++i) { + BOOST_TEST(secp256k1_ec_seckey_tweak_add(secp256k1_context_static, total.data(), + secrets[i].data()) == 1); + } + std::vector space(secp::combine_workspace_size(keys.size())); + auto const combined = secp::pubkey_combine(keys, space); + BOOST_TEST(combined && *combined == public_of(total)); + BOOST_TEST(all_zero(space)); + + alignas(std::max_align_t) std::array one{}; + auto const alone = secp::pubkey_combine(std::span(keys).first(1), one); + BOOST_TEST(alone && *alone == keys[0]); + BOOST_TEST(all_zero(one)); +} + +// 1 + 1 is 2, whose public key is 2G. +void known_answer() { + auto const two = secp::seckey_tweak_add(small(1), small(1)); + if (!BOOST_TEST(two.has_value())) { + return; + } + BOOST_TEST(std::ranges::equal(two->bytes(), small(2))); + auto const key = public_of(two->bytes()); + BOOST_TEST_EQ(test::to_hex(secp::serialize_public_key(key)), + "02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"); + auto const added = secp::pubkey_tweak_add(public_of(small(1)), small(1)); + BOOST_TEST(added && *added == key); +} + +template +void refused(char const* name, Result const& result, crypto::error expected) { + if (!BOOST_TEST(result.has_error()) || !BOOST_TEST(result.error() == expected)) { + BOOST_ERROR(name); + } +} + +void refusals() { + std::mt19937_64 generator(0x5eedULL); + auto const d = draw(generator); + auto const p_d = public_of(d); + auto const n = order(); + scalar const zero{}; + auto const n_minus_d = order_minus(d); + + // A tweak equal to the group order. + refused("seckey_tweak_add(d, n)", secp::seckey_tweak_add(d, n), + crypto::error::invalid_secret_key); + refused("seckey_tweak_mul(d, n)", secp::seckey_tweak_mul(d, n), + crypto::error::invalid_secret_key); + refused("pubkey_tweak_add(P, n)", secp::pubkey_tweak_add(p_d, n), + crypto::error::invalid_secret_key); + refused("pubkey_tweak_mul(P, n)", secp::pubkey_tweak_mul(p_d, n), + crypto::error::invalid_secret_key); + // A sum that is zero, and a product by zero. + refused("seckey_tweak_add(d, n - d)", secp::seckey_tweak_add(d, n_minus_d), + crypto::error::invalid_secret_key); + refused("pubkey_tweak_add(P(d), n - d)", secp::pubkey_tweak_add(p_d, n_minus_d), + crypto::error::invalid_secret_key); + refused("seckey_tweak_mul(d, 0)", secp::seckey_tweak_mul(d, zero), + crypto::error::invalid_secret_key); + refused("pubkey_tweak_mul(P, 0)", secp::pubkey_tweak_mul(p_d, zero), + crypto::error::invalid_secret_key); + // A zero and an order-sized secret. + for (auto const& bad : {zero, n}) { + refused("seckey_tweak_add(bad, t)", secp::seckey_tweak_add(bad, small(1)), + crypto::error::invalid_secret_key); + refused("seckey_tweak_mul(bad, t)", secp::seckey_tweak_mul(bad, small(1)), + crypto::error::invalid_secret_key); + refused("seckey_negate(bad)", secp::seckey_negate(bad), crypto::error::invalid_secret_key); + } + // A zero tweak adds nothing: d + 0 is d. + auto const same = secp::seckey_tweak_add(d, zero); + BOOST_TEST(same && std::ranges::equal(same->bytes(), d)); + + // P + (-P) is the point at infinity. + alignas(std::max_align_t) std::array space{}; + std::array const opposite{p_d, secp::pubkey_negate(p_d)}; + refused("pubkey_combine(P, -P)", secp::pubkey_combine(opposite, space), + crypto::error::invalid_public_key); + BOOST_TEST(all_zero(space)); + // No keys, and a workspace one byte short; the workspace is not written. + refused("pubkey_combine({})", secp::pubkey_combine({}, space), + crypto::error::invalid_input_size); + std::array const pair{p_d, public_of(small(7))}; + refused("pubkey_combine(short)", + secp::pubkey_combine(pair, std::span(space).first(space.size() - 1)), + crypto::error::invalid_input_size); + refused("pubkey_combine(no workspace)", secp::pubkey_combine(pair, {}), + crypto::error::invalid_input_size); + BOOST_TEST(all_zero(space)); +} + +} // namespace + +int main() { + identities(); + combinations(); + known_answer(); + refusals(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/support/secp256k1_checks.hpp b/test/support/secp256k1_checks.hpp index cffa0bf3..a3212422 100644 --- a/test/support/secp256k1_checks.hpp +++ b/test/support/secp256k1_checks.hpp @@ -11,6 +11,7 @@ #define WEBCPP_TEST_CRYPTO_SUPPORT_SECP256K1_CHECKS_HPP #include +#include #include #include @@ -42,6 +43,9 @@ inline void expect_empty_keypair(webcpp::crypto::curves::secp256k1::keypair& key BOOST_TEST(key.sign_ecdsa(message, aux).error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.sign_recoverable(message).error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.tweak_xonly(tweak).error() == webcpp::crypto::error::invalid_state); + std::array encoding{}; + BOOST_TEST(webcpp::crypto::curves::secp256k1::encode_pkcs8(key, encoding).error() == + webcpp::crypto::error::invalid_state); if (BOOST_TEST(live.has_value())) { auto const peer = *live->public_key(); BOOST_TEST(key.ecdh(peer).error() == webcpp::crypto::error::invalid_state); diff --git a/test/windows_h_after_test.cpp b/test/windows_h_after_test.cpp index 682eab91..c09eac3e 100644 --- a/test/windows_h_after_test.cpp +++ b/test/windows_h_after_test.cpp @@ -25,6 +25,8 @@ #include #include #include +#include +#include #include #include #include diff --git a/test/windows_h_before_test.cpp b/test/windows_h_before_test.cpp index 718693e5..3a1da08e 100644 --- a/test/windows_h_before_test.cpp +++ b/test/windows_h_before_test.cpp @@ -40,6 +40,8 @@ #include #include #include +#include +#include #include #include #include From 8e3f54f6b3f0007775c056f576ec7e437373f124 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 17:09:55 -0300 Subject: [PATCH 08/54] crypto: the SPKI and PKCS#8 encoders and pubkey_combine read the canary first; a workspace is wiped whole, off-alignment ones tested; the tweak example wipes on every path; the pages cite OpenSSL and name tweaks and key files --- doc/curves.adoc | 5 ++- doc/secp256k1.adoc | 15 ++++--- doc/tables/crypto.json | 3 +- example/key_tweak.cpp | 41 ++++++++++++------- include/webcpp/crypto/curves/secp256k1.hpp | 10 +++-- .../crypto/curves/secp256k1/formats.hpp | 4 +- .../webcpp/crypto/curves/secp256k1/tweak.hpp | 2 +- test/secp256k1_tweak_test.cpp | 41 ++++++++++++++++++- 8 files changed, 92 insertions(+), 29 deletions(-) diff --git a/doc/curves.adoc b/doc/curves.adoc index fe5d0d05..4c5cb8a5 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -22,7 +22,10 @@ Bitcoin, Ethereum and Nostr. This version covers Bitcoin's keys and signatures, Nostr's event signatures (NIP-01) and the raw x-coordinate ECDH of its encrypted messages (NIP-44, <>), and Ethereum's ECDSA: recoverable signatures, the recovery of a signer's public key from a -signature, and the uncompressed key (<>). +signature, and the uncompressed key (<>). It adds +tweaks to whole keys, the arithmetic of BIP 32's derivation and of watch-only +wallets (<>), and writes and reads keys in the SPKI and +PKCS#8 files that OpenSSL exchanges (<>). Ethereum's `v` encoding of the recovery id, the hash it signs, its transactions and its addresses are a domain library's. The second is Ed25519, RFC 8032's signatures on edwards25519, with Ed25519ph for a message given in diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index 278ef752..7b665385 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -365,8 +365,11 @@ buffer of at least `max_spki_size` bytes; `decode_spki` reads either back; * `encode_pkcs8` writes a key pair's PKCS#8, 135 bytes, into a buffer of at least `max_pkcs8_size`: version 0, and an ECPrivateKey of version 1 with the uncompressed public key and no curve inside it, which is the form OpenSSL -writes for a key in its default uncompressed form; `decode_pkcs8` reads it into -a key pair, made as `keypair::make` makes one. +writes for a key in its default uncompressed form: OpenSSL's point form is +uncompressed unless a program sets it, and it includes the public key when it +encodes a private key unless told not to +(link:https://docs.openssl.org/master/man7/EVP_PKEY-EC/[OpenSSL's EVP_PKEY-EC]); +`decode_pkcs8` reads it into a key pair, made as `keypair::make` makes one. The decoders are strict: they accept exactly the bytes the encoders write, and refuse anything else with `invalid_encoding`. The point must be on the curve, @@ -389,9 +392,11 @@ checks that key, rather than the one the secret gives, trusts the wrong key. `decode_pkcs8` refuses such a file. * X9.62's hybrid point form, prefix 06 or 07, is refused: RFC 5480 forbids it in an SPKI (link:https://www.rfc-editor.org/rfc/rfc5480[RFC 5480]). -* OpenSSL writes a key set to the compressed form with its compressed point -inside the PKCS#8 too, 102 bytes, which `decode_pkcs8` refuses: export the key -in OpenSSL's default uncompressed form, and choose the SPKI's form when writing +* OpenSSL keeps a key's point form through its DER and PEM encodings +(link:https://docs.openssl.org/master/man7/EVP_PKEY-EC/[OpenSSL's EVP_PKEY-EC]), +so a key set to the compressed form carries its compressed point inside the +PKCS#8 too, 102 bytes, which `decode_pkcs8` refuses: export the key in +OpenSSL's default uncompressed form, and choose the SPKI's form when writing it. * The PKCS#8 these functions write holds the secret key in clear. Keep it where only the program reads it, out of source control, or seal it at rest diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index da9be994..0bacf028 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -109,7 +109,8 @@ "bip327": ["BIP 327, MuSig2, its key sorting", "https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki"], "rfc5480": ["RFC 5480, Elliptic Curve Cryptography Subject Public Key Information", "https://www.rfc-editor.org/rfc/rfc5480"], "rfc5915": ["RFC 5915, Elliptic Curve Private Key Structure", "https://www.rfc-editor.org/rfc/rfc5915"], - "rfc5208": ["RFC 5208, PKCS #8: Private-Key Information Syntax", "https://www.rfc-editor.org/rfc/rfc5208"] + "rfc5208": ["RFC 5208, PKCS #8: Private-Key Information Syntax", "https://www.rfc-editor.org/rfc/rfc5208"], + "openssl-evp-pkey-ec": ["OpenSSL's EVP_PKEY-EC: an EC key's point form and its encodings", "https://docs.openssl.org/master/man7/EVP_PKEY-EC/"] }, "backends": { "bearssl": { diff --git a/example/key_tweak.cpp b/example/key_tweak.cpp index 7389d6d0..9be7fc4f 100644 --- a/example/key_tweak.cpp +++ b/example/key_tweak.cpp @@ -32,14 +32,24 @@ namespace hash2 = boost::hash2; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; +// 32 secret bytes the program holds, overwritten when the scope ends, on every path, an early +// return's included. The bytes are written through a volatile pointer, which the optimiser +// cannot drop as a dead store: crypto wipes its own copies of keys this way, and the program +// wipes its own. +struct wiped_bytes { + std::array bytes{}; + + wiped_bytes() = default; + wiped_bytes(wiped_bytes const&) = delete; + wiped_bytes& operator=(wiped_bytes const&) = delete; + + ~wiped_bytes() { + std::uint8_t volatile* const data = bytes.data(); + for (std::size_t i = 0; i < bytes.size(); ++i) { + data[i] = 0; + } } -} +}; // The tweak of payment `number`: HMAC-SHA-256 under the chain code of the compressed public key // and the number. Both sides compute it; an outsider without the chain code cannot, and so @@ -68,12 +78,12 @@ int main() { // The device's secret and the chain code, drawn once; the device keeps both, the server // gets the chain code and the public key. crypto::random_device device; - std::array secret{}; - std::array chain_code{}; - if (!device.fill(secret) || !device.fill(chain_code)) { + wiped_bytes secret; + wiped_bytes chain_code; + if (!device.fill(secret.bytes) || !device.fill(chain_code.bytes)) { return 1; } - auto const wallet = secp256k1::keypair::make(secret); + auto const wallet = secp256k1::keypair::make(secret.bytes); if (!wallet) { // A secret not below the group order: negligible, and a real wallet draws again. return 1; @@ -82,7 +92,9 @@ int main() { if (!wallet_public) { return 1; } - auto const tweak = payment_tweak(chain_code, *wallet_public, 7); + // The tweak and the tweaked secret give back the secret: the tweak is wiped too. + wiped_bytes tweak; + tweak.bytes = payment_tweak(chain_code.bytes, *wallet_public, 7); // tag::tweak[] // The server: the wallet's public key plus the tweak, with no secret anywhere. @@ -90,11 +102,10 @@ int main() { if (!parsed) { return 1; } - auto const watched = secp256k1::pubkey_tweak_add(*parsed, tweak); + auto const watched = secp256k1::pubkey_tweak_add(*parsed, tweak.bytes); // The device: the secret key plus the same tweak, a secret<32> it makes a key pair of. - auto const tweaked_secret = secp256k1::seckey_tweak_add(secret, tweak); - wipe(std::as_writable_bytes(std::span(secret))); + auto const tweaked_secret = secp256k1::seckey_tweak_add(secret.bytes, tweak.bytes); if (!watched || !tweaked_secret) { return 1; } diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index 8245d6f8..74657601 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -154,7 +154,7 @@ struct secp256k1_secret { /** * The carver of a caller's workspace into the arrays of pointers libsecp256k1 takes, which - * wipes every byte it handed out when it is destroyed. + * wipes the whole workspace when it is destroyed. * * Each array is aligned to `alignof(std::max_align_t)`, in the order the function's size * function lists them; an array of no elements takes no bytes and is `nullptr`. @@ -174,8 +174,12 @@ class secp256k1_workspace { /** Not copyable: one carver wipes what it handed out. */ secp256k1_workspace& operator=(secp256k1_workspace const&) = delete; - /** Wipes every byte handed out, and the padding between them. */ - ~secp256k1_workspace() { wipe(lent_bytes_.data(), used_size_); } + /** + * Wipes the whole workspace: the arrays handed out, the padding before each, and the bytes + * after the last, so that the workspace is zero when the function returns, wherever it + * starts. + */ + ~secp256k1_workspace() { wipe(lent_bytes_.data(), lent_bytes_.size()); } /** * The next array of `element_count` elements of `T`, aligned to `alignof(std::max_align_t)`. diff --git a/include/webcpp/crypto/curves/secp256k1/formats.hpp b/include/webcpp/crypto/curves/secp256k1/formats.hpp index 652020fa..6efb1aa6 100644 --- a/include/webcpp/crypto/curves/secp256k1/formats.hpp +++ b/include/webcpp/crypto/curves/secp256k1/formats.hpp @@ -95,10 +95,10 @@ template point_form encoded_form = point_form::compressed) noexcept { static_assert(webcpp::crypto::detail::secp256k1_backend, WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); if (output_bytes.size() < max_spki_size) { return error::invalid_input_size; } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); bool const is_compressed = encoded_form == point_form::compressed; std::array point_bytes{}; @@ -168,6 +168,7 @@ template basic_keypair const& key_pair, std::span output_bytes) noexcept { static_assert(webcpp::crypto::detail::secp256k1_backend, WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); using access = webcpp::crypto::detail::secp256k1_access; if (!access::keyed(key_pair)) { return error::invalid_state; @@ -175,7 +176,6 @@ template if (output_bytes.size() < max_pkcs8_size) { return error::invalid_input_size; } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); webcpp::crypto::detail::secp256k1_secret secret_bytes; secp256k1_keypair_sec(secp256k1_context_static, secret_bytes.bytes.data(), diff --git a/include/webcpp/crypto/curves/secp256k1/tweak.hpp b/include/webcpp/crypto/curves/secp256k1/tweak.hpp index db974478..ead02e79 100644 --- a/include/webcpp/crypto/curves/secp256k1/tweak.hpp +++ b/include/webcpp/crypto/curves/secp256k1/tweak.hpp @@ -243,11 +243,11 @@ template std::span parsed_keys, workspace pointer_space) noexcept { static_assert(webcpp::crypto::detail::secp256k1_backend, WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); // libsecp256k1 checks the count with ARG_CHECK, whose callback aborts: refused first here. if (parsed_keys.empty() || pointer_space.size() < combine_workspace_size(parsed_keys.size())) { return error::invalid_input_size; } - webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; webcpp::crypto::detail::secp256k1_workspace carver(pointer_space); diff --git a/test/secp256k1_tweak_test.cpp b/test/secp256k1_tweak_test.cpp index 84e12871..dbe481e2 100644 --- a/test/secp256k1_tweak_test.cpp +++ b/test/secp256k1_tweak_test.cpp @@ -10,7 +10,7 @@ // result equals libsecp256k1's C API called directly. The known answer 1 + 1, whose public key // is 2G. The refusals: a tweak equal to the group order, a sum or a product that is zero, a // zero or order-sized secret, a sum of keys at infinity, no keys and a short workspace. The -// workspace is zero after every call. +// workspace is zero after every call, one that starts off the alignment included. #include #include @@ -257,6 +257,44 @@ void combinations() { BOOST_TEST(all_zero(one)); } +// A workspace that starts off the alignment, at every offset below alignof(std::max_align_t): +// the keys' pointers start at the next aligned byte, which combine_workspace_size's padding +// pays for. The workspace is filled with a guard byte before each call and is zero after it, +// the padding before the pointers and the bytes after them included; the bytes around it are +// not touched. +void off_alignment() { + std::mt19937_64 generator(0xa1196eULL); + std::array secrets{}; + for (auto& secret_bytes : secrets) { + secret_bytes = draw(generator); + } + std::array const keys{ + public_of(secrets[0]), + public_of(secrets[1]), + public_of(secrets[2]), + }; + scalar total = secrets[0]; + for (std::size_t i = 1; i < secrets.size(); ++i) { + BOOST_TEST(secp256k1_ec_seckey_tweak_add(secp256k1_context_static, total.data(), + secrets.at(i).data()) == 1); + } + auto const expected = public_of(total); + constexpr std::size_t space_size = secp::combine_workspace_size(3); + constexpr std::byte guard{0x5a}; + for (std::size_t offset = 1; offset < alignof(std::max_align_t); ++offset) { + alignas(std::max_align_t) std::array + buffer{}; + buffer.fill(guard); + auto const space = std::span(buffer).subspan(offset, space_size); + auto const combined = secp::pubkey_combine(keys, space); + BOOST_TEST(combined && *combined == expected); + BOOST_TEST(all_zero(space)); + auto const is_guard = [](std::byte b) { return b == guard; }; + BOOST_TEST(std::ranges::all_of(std::span(buffer).first(offset), is_guard)); + BOOST_TEST(std::ranges::all_of(std::span(buffer).subspan(offset + space_size), is_guard)); + } +} + // 1 + 1 is 2, whose public key is 2G. void known_answer() { auto const two = secp::seckey_tweak_add(small(1), small(1)); @@ -339,6 +377,7 @@ void refusals() { int main() { identities(); combinations(); + off_alignment(); known_answer(); refusals(); return webcpp::test::exit_status(boost::report_errors()); From 4573e957e2ddb4f394579eda8bf6fea59b0e1dfb Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 17:43:26 -0300 Subject: [PATCH 09/54] crypto: ElligatorSwift on libsecp256k1, against BIP 324's vectors --- doc/changelog.adoc | 2 +- doc/curves.adoc | 4 +- doc/generated/backends-ellswift.adoc | 30 ++ doc/generated/matrix.adoc | 11 + doc/generated/use-cases.adoc | 7 + doc/llms.txt | 7 + doc/secp256k1.adoc | 81 ++++- doc/tables/crypto.json | 15 + example/Jamfile | 4 + example/ellswift_handshake.cpp | 78 +++++ example/ellswift_handshake.expected | 2 + include/webcpp/crypto.hpp | 1 + include/webcpp/crypto/backends/secp256k1.hpp | 6 +- .../crypto/curves/secp256k1/ellswift.hpp | 169 ++++++++++ test/Jamfile | 5 + test/crypto_secp256k1_test.cpp | 5 +- test/secp256k1_allocation_test.cpp | 18 +- test/secp256k1_ellswift_test.cpp | 297 ++++++++++++++++++ test/support/secp256k1_checks.hpp | 7 + test/windows_h_after_test.cpp | 1 + test/windows_h_before_test.cpp | 1 + 21 files changed, 740 insertions(+), 11 deletions(-) create mode 100644 doc/generated/backends-ellswift.adoc create mode 100644 example/ellswift_handshake.cpp create mode 100644 example/ellswift_handshake.expected create mode 100644 include/webcpp/crypto/curves/secp256k1/ellswift.hpp create mode 100644 test/secp256k1_ellswift_test.cpp diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 4207bcef..5d26b9f2 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -20,7 +20,7 @@ of every version are on webcpp's index page. * Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default, one default per family and target, and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). -* Added curves::secp256k1: key pairs, BIP340, hedged and recoverable ECDSA, keys recovered from signatures, three self-wiping ECDH forms, strict DER, low-S, tweaks, negation, combination, SPKI and PKCS#8. +* Added curves::secp256k1: key pairs, BIP340, hedged and recoverable ECDSA, three self-wiping ECDH forms, strict DER, low-S, tweaks, negation, combination, SPKI, PKCS#8 and BIP 324's ElligatorSwift. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. * Added ciphers::secretbox and secretbox_xchacha20poly1305, without additional data, hybrid::box, box_xchacha20poly1305 and sealed_box (failed seals and opens zeroing data), and curves::x25519::kx_keypair (crypto_kx) on libsodium, refusing peer keys of small order. diff --git a/doc/curves.adoc b/doc/curves.adoc index 4c5cb8a5..cdeebc64 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -25,7 +25,9 @@ recoverable signatures, the recovery of a signer's public key from a signature, and the uncompressed key (<>). It adds tweaks to whole keys, the arithmetic of BIP 32's derivation and of watch-only wallets (<>), and writes and reads keys in the SPKI and -PKCS#8 files that OpenSSL exchanges (<>). +PKCS#8 files that OpenSSL exchanges (<>), and sends +keys as random-looking bytes, BIP 324's ElligatorSwift +(<>). Ethereum's `v` encoding of the recovery id, the hash it signs, its transactions and its addresses are a domain library's. The second is Ed25519, RFC 8032's signatures on edwards25519, with Ed25519ph for a message given in diff --git a/doc/generated/backends-ellswift.adoc b/doc/generated/backends-ellswift.adoc new file mode 100644 index 00000000..ac87298b --- /dev/null +++ b/doc/generated/backends-ellswift.adoc @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+curves::secp256k1::ellswift_encode+`, `+ellswift_decode+`, `+ellswift_create+`, `+ellswift_xdh+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsecp256k1 +|`+/third_party//secp256k1+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+secp256k1_ellswift+`) +|=== + +A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsecp256k1 +|=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 43bc324e..8334571b 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -210,6 +210,11 @@ |libsecp256k1 |native, wasip2, wasip3, emscripten |`+secp256k1_formats+`, `+secp256k1_formats_openssl+` + +|`+curves::secp256k1::ellswift_encode+`, `+ellswift_decode+`, `+ellswift_create+`, `+ellswift_xdh+` +|libsecp256k1 +|native, wasip2, wasip3, emscripten +|`+secp256k1_ellswift+` |=== The same, by target: the backends each operation runs on. @@ -409,4 +414,10 @@ The same, by target: the backends each operation runs on. |libsecp256k1 |libsecp256k1 |libsecp256k1 + +|`+curves::secp256k1::ellswift_encode+`, `+ellswift_decode+`, `+ellswift_create+`, `+ellswift_xdh+` +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 |=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 109651f8..dbcfbc35 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -99,6 +99,13 @@ `+/third_party//secp256k1+` |<> +|Make a peer-to-peer connection's key exchange look like random bytes (BIP 324's transport; its packets are a domain library's) +|In `+curves::secp256k1+`: `+ellswift_create+`, `+ellswift_decode+`, `+ellswift_xdh+` +|libsecp256k1 +|`+/webcpp/crypto//crypto+` + +`+/third_party//secp256k1+` +|<> + |Make and keep a wallet's key |In `+curves::secp256k1+`: `+keypair::make+`, `+xonly_public_key+`, `+public_key+`; `+aes256_gcm+` at rest |libsecp256k1, and AES-GCM's default diff --git a/doc/llms.txt b/doc/llms.txt index 82699a6f..3e39c250 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -136,6 +136,11 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - decode_spki: The public key of an SPKI in exactly one of the two forms `encode_spki` writes. - encode_pkcs8: Writes a key pair's PKCS#8 into `output_bytes`, in OpenSSL's form: version 0, and RFC 5915's ECPrivateKey of version 1 with the uncompressed public key and no parameters inside. - decode_pkcs8: The key pair of a PKCS#8 that is exactly what `encode_pkcs8` writes for its secret, made as `basic_keypair::make` makes it. +- [curves::secp256k1::ellswift_encode, ellswift_decode, ellswift_create, ellswift_xdh](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ellswift): A public key written as 64 bytes that look random, and BIP 324's key exchange of two such encodings. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: make a peer-to-peer connection's key exchange look like random bytes (BIP 324's transport; its packets are a domain library's). + - ellswift_encode: A public key's ElligatorSwift encoding (`secp256k1_ellswift_encode`): one of many, chosen by the randomness, each of which decodes to the key. + - ellswift_decode: The public key of any 64 bytes (`secp256k1_ellswift_decode`): every input decodes. + - ellswift_create: The encoding of a key pair's public key, made from its secret with the key pair's context (`secp256k1_ellswift_create`), so that the public key is never computed apart. + - ellswift_xdh: The shared secret of an ElligatorSwift key exchange, hashed as BIP 324 hashes it (`secp256k1_ellswift_xdh` with `secp256k1_ellswift_xdh_hash_function_bip324`): a tagged hash of both encodings and the shared point's x coordinate. ## webcpp::crypto::hybrid @@ -220,6 +225,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Derive a Nostr direct message's conversation key (NIP-44; the format is a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ecdh): `keypair::ecdh_x`, then HKDF on Boost.Hash2 (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdh_x_coordinate.cpp. - [Find who signed a message or a transaction without being sent their key (Ethereum's signatures)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-recovery): `keypair::sign_recoverable`, `recover` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/recover_signer.cpp. - [Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-tweaks): `seckey_tweak_add`, `pubkey_tweak_add` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/key_tweak.cpp. +- [Make a peer-to-peer connection's key exchange look like random bytes (BIP 324's transport; its packets are a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ellswift): `ellswift_create`, `ellswift_decode`, `ellswift_xdh` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ellswift_handshake.cpp. - [Make and keep a wallet's key](https://webcpporg.github.io/libs/crypto/#crypto-wallets-key): `keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/wallet_key.cpp. - [Sign a Bitcoin SegWit v0 input (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-der): `sign_ecdsa`, `to_der`, `normalize_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdsa_der.cpp. - [Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly`, `keypair::tweak_xonly` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/taproot_tweak.cpp. @@ -248,6 +254,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/ecdh_x_coordinate.cpp: Two key pairs agree on the shared point's raw x coordinate with ecdh_x, the form Nostr's encrypted messages (NIP-44) take, then derive from it what a NIP-44 library would: the conversation key, HKDF-extract with the salt "nip44-v2". The x coordinate is not a key; the derivation that makes one is the protocol's, and belongs to a domain library. - example/ecdsa_der.cpp: Signs with ECDSA the way a domain library does: a sighash computed by the library, a 64-byte signature, its strict DER form for the wire, and the low-S rule. The same signature has a twin with S replaced by n - S; accepting both makes transaction ids malleable, so verifiers refuse the high-S twin. - example/ed25519_sign.cpp: Signs RFC 8032's second Ed25519 test with a key pair made from its seed and verifies the signature with the public key alone; then signs the message "abc" given in two pieces with Ed25519ph, as RFC 8032's Ed25519ph test does, and verifies it. Prints each key and signature in hex. +- example/ellswift_handshake.cpp: The first messages of a peer-to-peer connection whose key exchange looks like random bytes, as BIP 324's transport starts: each peer sends its public key as an ElligatorSwift encoding, 64 bytes with no recognisable prefix, and both compute the same shared secret from the two encodings. The secrets and the randomness are fixed here, so that the program runs the same each time; a real program draws all four from random_device. Nothing random is printed. - example/equal_hmac.cpp: Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::crypto::equal, the constant-time comparison. Comparing tags with == or memcmp stops at the first difference, and that timing lets an attacker guess a valid tag one byte at a time. - example/failure_reasons.cpp: Shows the three ways AES-GCM can refuse a message: a tampered ciphertext, an IV of the wrong size and a tag of the wrong size. A program must tell the first from the others: only authentication_failed means someone changed the data, and open then wipes the plaintext so that no unauthenticated bytes are ever used. - example/file_share.cpp: A file-sharing app shares a file with a recipient it knows only by an X25519 public key: the file is sealed once in a secret box under a key drawn for this file, and that file key is sealed to the recipient's public key in a sealed box. The upload holds both; only the recipient's secret key opens the file key, and the file key opens the file. Prints what the recipient reads, the sizes on the wire, and the refusals of a changed upload and of another key pair. diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index 7b665385..3f5571e9 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -46,11 +46,13 @@ check signatures with a public key alone, and `recover` finds the key from a recoverable signature; `parse_public_key` and `serialize_public_key` read and write a `public_key` (<>); `to_der`, `from_der` (strict DER) and `normalize_ecdsa` convert ECDSA's DER and low-S forms; and -`tweak_xonly` tweaks an x-only public key. Two more headers hold the tweaks, +`tweak_xonly` tweaks an x-only public key. Three more headers hold the tweaks, negation and combination of whole keys -(``, <>) -and the keys' SPKI and PKCS#8 (``, -<>). Every function reads libsecp256k1's canary, so +(``, <>), +the keys' SPKI and PKCS#8 (``, +<>) and ElligatorSwift, keys sent as random-looking +bytes (``, +<>). Every function reads libsecp256k1's canary, so that a program linked with another build of the library does not link. include::generated/backends-keypair.adoc[] @@ -401,3 +403,74 @@ it. * The PKCS#8 these functions write holds the secret key in clear. Keep it where only the program reads it, out of source control, or seal it at rest (<>). + +[#crypto-secp256k1-ellswift] +==== ElligatorSwift: keys that look like noise + +A peer-to-peer program, a Bitcoin node or a messenger, opens connections that +a censor or a middlebox on the path may want to block or throttle. Such a box +recognises a protocol by its first bytes, and a handshake that starts with a +public key is easy to spot: a compressed key starts with 02 or 03, and the 32 +bytes after it are always the x coordinate of a point of the curve, which only +about half of all random strings are. BIP 324 sends each peer's key +instead as 64 bytes that cannot be told from random ones, so that the first +bytes of the connection look like noise +(link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324]). + +ElligatorSwift is the encoding that makes this work. It maps every string of +64 bytes to a point of the curve, and each point has many such strings; an +encoding drawn at random among those of a key is uniform among all 64-byte +strings, so a key sent this way looks like any other random bytes +(link:https://eprint.iacr.org/2022/759[Chavez-Saab, Rodríguez-Henríquez and +Tibouchi, SwiftEC, 2022]). +`` offers libsecp256k1's +functions: + +* `ellswift_create` makes the encoding of a key pair's own public key from its +secret and 32 bytes of fresh randomness, so that the key is never computed +apart; `ellswift_encode` encodes any `public_key`; +* `ellswift_decode` returns the `public_key` of any 64 bytes: it never fails; +* `ellswift_xdh` is the key exchange: the x coordinate of the shared point, +hashed with both encodings as BIP 324 hashes it, a tagged SHA-256, into a +`secret<32>`. It takes the initiator's encoding, then the responder's, and +which of the two the key pair is (`ellswift_party`). + +A moved-from key pair is refused with `invalid_state`. The tests check BIP +324's own vectors: every encoding of its decoding list, and the shared secret +of each of its packet vectors. + +include::generated/backends-ellswift.adoc[] + +*Example.* Two peers each send the 64 bytes `ellswift_create` makes; each +message decodes to its sender's key, and the two shared secrets agree: + +[source,cpp] +---- +include::{examples}/ellswift_handshake.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/ellswift_handshake.expected[] +---- + +The messages carry no recognisable prefix, unlike a compressed key's 02 or 03 +(link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324]). +That hides that a key exchange happens, not who takes part: the addresses of +both peers stay visible to whoever watches the connection. + +*Pitfalls.* + +* Draw fresh randomness for every encoding. The same key with the same +randomness gives the same 64 bytes, so two connections of one node, or one +key reused, are linked by anyone who sees both; with fresh randomness each +encoding is new. +* The hash binds both encodings in a fixed order, the initiator's first. A +side that passes them in its own order, ours then theirs, or names the wrong +party, computes a different secret, and the connection fails with nothing +pointing at the cause. +* The shared secret is the input of the protocol's key schedule, never a key +by itself: BIP 324 derives its session's keys from it with HKDF +(link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324]), +and that schedule, its packets and its garbage terminators are a domain +library's. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 0bacf028..14499755 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -110,6 +110,8 @@ "rfc5480": ["RFC 5480, Elliptic Curve Cryptography Subject Public Key Information", "https://www.rfc-editor.org/rfc/rfc5480"], "rfc5915": ["RFC 5915, Elliptic Curve Private Key Structure", "https://www.rfc-editor.org/rfc/rfc5915"], "rfc5208": ["RFC 5208, PKCS #8: Private-Key Information Syntax", "https://www.rfc-editor.org/rfc/rfc5208"], + "bip324": ["BIP 324, version 2 P2P encrypted transport protocol", "https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki"], + "elligatorswift": ["Chavez-Saab, Rodríguez-Henríquez and Tibouchi, SwiftEC: Shallue-van de Woestijne Indifferentiable Function to Elliptic Curves, 2022", "https://eprint.iacr.org/2022/759"], "openssl-evp-pkey-ec": ["OpenSSL's EVP_PKEY-EC: an EC key's point form and its encodings", "https://docs.openssl.org/master/man7/EVP_PKEY-EC/"] }, "backends": { @@ -603,6 +605,18 @@ "what": "A public key's SPKI and a key pair's PKCS#8, in OpenSSL's forms, decoded strictly.", "section": "crypto-secp256k1-formats", "backends": {"secp256k1": {"tests": ["secp256k1_formats", "secp256k1_formats_openssl"]}} + }, + { + "id": "ellswift", + "family": "secp256k1", + "free": true, + "functions": ["ellswift_encode", "ellswift_decode", "ellswift_create", "ellswift_xdh"], + "namespace": "curves", + "api": "curves::secp256k1::ellswift_encode, ellswift_decode, ellswift_create, ellswift_xdh", + "header": "", + "what": "A public key written as 64 bytes that look random, and BIP 324's key exchange of two such encodings.", + "section": "crypto-secp256k1-ellswift", + "backends": {"secp256k1": {"tests": ["secp256k1_ellswift"]}} } ], "families": [ @@ -971,6 +985,7 @@ {"need": "Derive a Nostr direct message's conversation key (NIP-44; the format is a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::ecdh_x`, then HKDF on Boost.Hash2", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdh_x_coordinate", "section": "crypto-secp256k1-ecdh"}, {"need": "Find who signed a message or a transaction without being sent their key (Ethereum's signatures)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_recoverable`, `recover`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "recover_signer", "section": "crypto-secp256k1-recovery"}, {"need": "Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`seckey_tweak_add`, `pubkey_tweak_add`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "key_tweak", "section": "crypto-secp256k1-tweaks"}, + {"need": "Make a peer-to-peer connection's key exchange look like random bytes (BIP 324's transport; its packets are a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`ellswift_create`, `ellswift_decode`, `ellswift_xdh`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ellswift_handshake", "section": "crypto-secp256k1-ellswift"}, {"need": "Make and keep a wallet's key", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "wallet_key", "section": "crypto-wallets-key"}, {"need": "Sign a Bitcoin SegWit v0 input (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`sign_ecdsa`, `to_der`, `normalize_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdsa_der", "section": "crypto-wallets-der"}, {"need": "Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`tweak_xonly`, `keypair::tweak_xonly`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "taproot_tweak", "section": "crypto-wallets-taproot"}, diff --git a/example/Jamfile b/example/Jamfile index fb72c9db..b59e3e53 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -61,6 +61,10 @@ webcpp.example recover_signer.cpp : /third_party//secp256k1 ; # and a signature of the tweaked key pair verified under the tweaked public key. webcpp.example key_tweak.cpp : /third_party//secp256k1 ; +# Two peers send their keys as ElligatorSwift encodings, 64 bytes that look +# random, and agree on BIP 324's shared secret. +webcpp.example ellswift_handshake.cpp : /third_party//secp256k1 ; + # A wallet's key pair, its secret sealed at rest and restored. webcpp.example wallet_key.cpp : /third_party//secp256k1 /webcpp/crypto//gcm-default ; diff --git a/example/ellswift_handshake.cpp b/example/ellswift_handshake.cpp new file mode 100644 index 00000000..f8da839d --- /dev/null +++ b/example/ellswift_handshake.cpp @@ -0,0 +1,78 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The first messages of a peer-to-peer connection whose key exchange looks like random bytes, +// as BIP 324's transport starts: each peer sends its public key as an ElligatorSwift encoding, +// 64 bytes with no recognisable prefix, and both compute the same shared secret from the two +// encodings. The secrets and the randomness are fixed here, so that the program runs the same +// each time; a real program draws all four from random_device. Nothing random is printed. +// tag::program[] +#include +#include +#include +#include + +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace secp256k1 = webcpp::crypto::curves::secp256k1; + +namespace { + +std::array repeated(std::uint8_t value) { + std::array bytes{}; + bytes.fill(value); + return bytes; +} + +} // namespace + +int main() { + // Each peer's key pair and the randomness of its encoding (random_device in a real program). + auto const initiator = secp256k1::keypair::make(repeated(0x11)); + auto const responder = secp256k1::keypair::make(repeated(0x22)); + if (!initiator || !responder) { + return 1; + } + + // tag::exchange[] + // Each peer sends the 64 bytes ellswift_create makes from its key pair. + auto const initiator_message = secp256k1::ellswift_create(*initiator, repeated(0x33)); + auto const responder_message = secp256k1::ellswift_create(*responder, repeated(0x44)); + if (!initiator_message || !responder_message) { + return 1; + } + + // Each message decodes to its sender's public key; any 64 bytes decode to some key. + auto const initiator_key = initiator->public_key(); + auto const responder_key = responder->public_key(); + if (!initiator_key || !responder_key || + secp256k1::serialize_public_key(secp256k1::ellswift_decode(*initiator_message)) != + *initiator_key || + secp256k1::serialize_public_key(secp256k1::ellswift_decode(*responder_message)) != + *responder_key) { + return 1; + } + std::printf("each 64-byte message decodes to its sender's key\n"); + + // Both pass the two messages in the same order, the initiator's first, and name their own + // side; the shared secret is the input of the protocol's key schedule, not a key itself. + auto const initiator_secret = secp256k1::ellswift_xdh( + *initiator, *initiator_message, *responder_message, secp256k1::ellswift_party::initiator); + auto const responder_secret = secp256k1::ellswift_xdh( + *responder, *initiator_message, *responder_message, secp256k1::ellswift_party::responder); + if (!initiator_secret || !responder_secret || + !crypto::equal(initiator_secret->bytes(), responder_secret->bytes())) { + return 1; + } + std::printf("initiator and responder agree\n"); + // end::exchange[] + return 0; +} + +// end::program[] diff --git a/example/ellswift_handshake.expected b/example/ellswift_handshake.expected new file mode 100644 index 00000000..aff69a54 --- /dev/null +++ b/example/ellswift_handshake.expected @@ -0,0 +1,2 @@ +each 64-byte message decodes to its sender's key +initiator and responder agree diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index 395a2efb..cad7719e 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -57,6 +57,7 @@ #ifdef WEBCPP_CRYPTO_HAS_SECP256K1 #include +#include #include #include #endif diff --git a/include/webcpp/crypto/backends/secp256k1.hpp b/include/webcpp/crypto/backends/secp256k1.hpp index 5b7652c8..08f3b0d2 100644 --- a/include/webcpp/crypto/backends/secp256k1.hpp +++ b/include/webcpp/crypto/backends/secp256k1.hpp @@ -8,8 +8,9 @@ The backend libsecp256k1: its v0.8.0, built from its sources by `/third_party//secp256k1`, every module on. It serves `curves::secp256k1::keypair`, `verify_schnorr`, `verify_ecdsa`, `recover`, the parsed `public_key`, the DER and low-S functions, the x-only tweak, the tweaks - and combination of `curves/secp256k1/tweak.hpp` and the SPKI and PKCS#8 of - `curves/secp256k1/formats.hpp`, and its whole C API stays reachable through ``. + and combination of `curves/secp256k1/tweak.hpp`, the SPKI and PKCS#8 of + `curves/secp256k1/formats.hpp` and the ElligatorSwift of `curves/secp256k1/ellswift.hpp`, and + its whole C API stays reachable through ``. @see "secp256k1", in the guide. */ @@ -28,6 +29,7 @@ #include #include +#include #include #include #include diff --git a/include/webcpp/crypto/curves/secp256k1/ellswift.hpp b/include/webcpp/crypto/curves/secp256k1/ellswift.hpp new file mode 100644 index 00000000..9ee4196d --- /dev/null +++ b/include/webcpp/crypto/curves/secp256k1/ellswift.hpp @@ -0,0 +1,169 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + secp256k1's ElligatorSwift on libsecp256k1: a public key written as 64 bytes that cannot be + told from random ones, read back from any 64 bytes, made from a key pair's secret, and the + x-only key exchange of two such encodings, hashed as BIP 324 hashes it into a `secret<32>`. + + @see "ElligatorSwift: keys that look like noise", in the guide's secp256k1 chapter. +*/ +#ifndef WEBCPP_CRYPTO_CURVES_SECP256K1_ELLSWIFT_HPP +#define WEBCPP_CRYPTO_CURVES_SECP256K1_ELLSWIFT_HPP + +#include + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace webcpp::crypto::curves::secp256k1 { + +/** The size of an ElligatorSwift encoding: 64 bytes, indistinguishable from random. */ +inline constexpr std::size_t ellswift_size = 64; + +/** The two sides of `ellswift_xdh` (BIP 324's initiator and responder). */ +enum class ellswift_party { + /** The side whose encoding comes first in the hash: BIP 324's initiator. */ + initiator = 0, + /** The other side. */ + responder = 1, +}; + +/** + * A public key's ElligatorSwift encoding (`secp256k1_ellswift_encode`): one of many, chosen by + * the randomness, each of which decodes to the key. + * + * Tip: `ellswift_create` makes the encoding of a key pair's own key from its secret, which + * libsecp256k1 recommends over this function. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param parsed_key The key. + * @param randomness 32 fresh bytes from `random_device`: the encoding is one of many. + * @return The 64 bytes. + */ +template +[[nodiscard]] std::array ellswift_encode( + public_key const& parsed_key, std::span randomness) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + std::array encoded_key{}; + // libsecp256k1 returns 1 always: every valid point has encodings. + static_cast(secp256k1_ellswift_encode( + secp256k1_context_static, encoded_key.data(), + &webcpp::crypto::detail::secp256k1_access::point(parsed_key), randomness.data())); + return encoded_key; +} + +/** + * The public key of any 64 bytes (`secp256k1_ellswift_decode`): every input decodes. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param encoded_key The 64 bytes, as received. + * @return The key. + */ +template +[[nodiscard]] public_key ellswift_decode( + std::span encoded_key) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + public_key decoded_key = access::make_public_key(); + // libsecp256k1 returns 1 always: ElligatorSwift maps every 64 bytes to a point. + static_cast(secp256k1_ellswift_decode(secp256k1_context_static, + &access::point(decoded_key), encoded_key.data())); + return decoded_key; +} + +/** + * The encoding of a key pair's public key, made from its secret with the key pair's context + * (`secp256k1_ellswift_create`), so that the public key is never computed apart. + * + * @tparam Backend The key pair's backend, `backends::secp256k1`. + * @param key_pair The key pair. + * @param randomness 32 fresh bytes from `random_device`, mixed with the secret into the choice + * of the encoding. + * @return 64 bytes; `invalid_state` moved from; `backend_failure`. + */ +template +[[nodiscard]] boost::system::result> ellswift_create( + basic_keypair const& key_pair, std::span randomness) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + using access = webcpp::crypto::detail::secp256k1_access; + if (!access::keyed(key_pair)) { + return error::invalid_state; + } + webcpp::crypto::detail::secp256k1_secret seckey32; + secp256k1_keypair_sec(access::context(key_pair), seckey32.bytes.data(), + &access::pair(key_pair)); + std::array encoded_key{}; + // The key pair's secret is valid: libsecp256k1 refuses only one that is not. + if (secp256k1_ellswift_create(access::context(key_pair), encoded_key.data(), + seckey32.bytes.data(), randomness.data()) == 0) { + return error::backend_failure; + } + return encoded_key; +} + +/** + * The shared secret of an ElligatorSwift key exchange, hashed as BIP 324 hashes it + * (`secp256k1_ellswift_xdh` with `secp256k1_ellswift_xdh_hash_function_bip324`): a tagged + * hash of both encodings and the shared point's x coordinate. + * + * Tip: both sides pass the two encodings in the same order, the initiator's first, and each + * names its own party; the secret is input to the protocol's key schedule, never a key itself. + * + * @tparam Backend The key pair's backend, `backends::secp256k1`. + * @param key_pair The key pair, whose encoding is `our_party`'s. + * @param initiator_encoding The initiator's 64 bytes, as sent. + * @param responder_encoding The responder's 64 bytes, as sent. + * @param our_party Which of the two this key pair is. + * @return 32 secret bytes; `invalid_state` moved from; `backend_failure`. + */ +template +[[nodiscard]] boost::system::result> ellswift_xdh( + basic_keypair const& key_pair, + std::span initiator_encoding, + std::span responder_encoding, + ellswift_party our_party) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + using access = webcpp::crypto::detail::secp256k1_access; + if (!access::keyed(key_pair)) { + return error::invalid_state; + } + webcpp::crypto::detail::secp256k1_secret seckey32; + secp256k1_keypair_sec(access::context(key_pair), seckey32.bytes.data(), + &access::pair(key_pair)); + secret<32> shared_secret; + // The secret is valid and BIP 324's hash never fails: libsecp256k1 returns 1. + if (secp256k1_ellswift_xdh(access::context(key_pair), shared_secret.writable().data(), + initiator_encoding.data(), responder_encoding.data(), + seckey32.bytes.data(), static_cast(our_party), + secp256k1_ellswift_xdh_hash_function_bip324, nullptr) == 0) { + return error::backend_failure; + } + return shared_secret; +} + +} // namespace webcpp::crypto::curves::secp256k1 + +#endif // WEBCPP_CRYPTO_CURVES_SECP256K1_ELLSWIFT_HPP diff --git a/test/Jamfile b/test/Jamfile index 228907a9..03327969 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -67,6 +67,7 @@ webcpp.headers-alone crypto : ../include webcpp.headers-alone crypto : ../include : crypto/curves/secp256k1.hpp crypto/backends/secp256k1.hpp crypto/curves/secp256k1/tweak.hpp crypto/curves/secp256k1/formats.hpp + crypto/curves/secp256k1/ellswift.hpp : /third_party//secp256k1 ; # config.hpp defines WEBCPP_CRYPTO_NO_EXCEPTIONS exactly when webcpp has no @@ -231,6 +232,10 @@ crypto-run secp256k1_formats_openssl : secp256k1_formats_test.cpp : /third_party//secp256k1 /webcpp/crypto//openssl WEBCPP_TEST_OPENSSL_ORACLE : native wasip2 wasip3 ; +# ElligatorSwift against BIP 324's decoding and packet vectors, round trips +# over seeded key pairs, and the key exchange from both sides. +crypto-run secp256k1_ellswift : secp256k1_ellswift_test.cpp + : /third_party//secp256k1 /third_party//bips ; crypto-run secp256k1_der : secp256k1_der_test.cpp : /third_party//secp256k1 /third_party//wycheproof /webcpp//boost_json ; diff --git a/test/crypto_secp256k1_test.cpp b/test/crypto_secp256k1_test.cpp index 77aaed58..0d698520 100644 --- a/test/crypto_secp256k1_test.cpp +++ b/test/crypto_secp256k1_test.cpp @@ -6,7 +6,8 @@ // in a program that links libsecp256k1 brings secp256k1's header: its // branch for WEBCPP_CRYPTO_HAS_SECP256K1 compiles, and the key pair, both verifications, the -// tweaks of tweak.hpp and the formats of formats.hpp are declared through it alone. +// tweaks of tweak.hpp, the formats of formats.hpp and the ElligatorSwift of ellswift.hpp are +// declared through it alone. #include @@ -25,6 +26,8 @@ static_assert(std::is_function_v)>); static_assert(std::is_function_v)>); static_assert(std::is_function_v)>); static_assert(std::is_function_v)>); +static_assert(std::is_function_v)>); +static_assert(std::is_function_v)>); int main() { return 0; diff --git a/test/secp256k1_allocation_test.cpp b/test/secp256k1_allocation_test.cpp index 1eff14c4..206c6868 100644 --- a/test/secp256k1_allocation_test.cpp +++ b/test/secp256k1_allocation_test.cpp @@ -9,12 +9,14 @@ // and never through operator new nor the C library's allocator where the target lets a // program count it; the signatures (hedged and recoverable too), the three forms of ECDH, the // public keys in both forms, both verifications, the parsed public key, recovery, the DER and -// low-S functions, the x-only tweak, the tweaks, negations and combination of tweak.hpp and the -// SPKI and PKCS#8 encoders and decoders of formats.hpp allocate nothing, each counted alone +// low-S functions, the x-only tweak, the tweaks, negations and combination of tweak.hpp, the +// SPKI and PKCS#8 encoders and decoders of formats.hpp and the ElligatorSwift functions of +// ellswift.hpp allocate nothing, each counted alone // (decode_pkcs8's key pair takes its one block from the resource it is given); the destructor // gives the block back; a refused make allocates nothing. A control proves the counter moves. #include +#include #include #include #include @@ -169,6 +171,18 @@ int main() { return secp::decode_spki(std::span(encoding).first(spki_size)); }); none("encode_pkcs8", [&] { return secp::encode_pkcs8(key, encoding); }); + + // ellswift.hpp: the encoding of a key and of a key pair, its decoding, and the exchange. + std::array noise{}; + none("ellswift_encode", [&] { + noise = secp::ellswift_encode(*parsed, aux); + return true; + }); + none("ellswift_decode", [&] { return secp::ellswift_decode(noise) == *parsed; }); + none("ellswift_create", [&] { return secp::ellswift_create(key, aux); }); + none("ellswift_xdh", [&] { + return secp::ellswift_xdh(key, noise, noise, secp::ellswift_party::initiator); + }); BOOST_TEST_EQ(resource.allocated, 1U); BOOST_TEST_EQ(resource.deallocated, 0U); diff --git a/test/secp256k1_ellswift_test.cpp b/test/secp256k1_ellswift_test.cpp new file mode 100644 index 00000000..27ee3d42 --- /dev/null +++ b/test/secp256k1_ellswift_test.cpp @@ -0,0 +1,297 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// secp256k1's ElligatorSwift against BIP 324's vectors. bip-0324/ellswift_decode_test_vectors.csv: +// each of its 76 encodings decodes to a key whose x is the row's. bip-0324/ +// packet_encoding_test_vectors.csv, 7 rows: both encodings decode to keys whose x are +// mid_x_ours and mid_x_theirs, in_priv_ours's key pair has our key, and ellswift_xdh with the two +// encodings in initiator-then-responder order and our party gives mid_shared_secret; the other +// columns (the session's keys, garbage terminators, ciphertexts) are BIP 324's protocol and are +// not read. xswiftec_inv_test_vectors.csv is not read: its inverse map is internal to +// libsecp256k1, whose own ElligatorSwift tests the c-suites lane runs. Over 64 seeded key pairs: +// ellswift_create and ellswift_encode decode to the key pair's key, two encodings of one key with +// different randomness differ, and the initiator's and the responder's ellswift_xdh agree while +// a swapped party does not. A moved-from key pair: invalid_state from ellswift_create and +// ellswift_xdh. + +#include +#include +#include +#include +#include +#include + +#include "support/hex.hpp" +#include "support/secp256k1_checks.hpp" +#include "support/test_data.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace secp = webcpp::crypto::curves::secp256k1; +namespace test = webcpp::test; + +namespace { + +using encoding = std::array; +using scalar = std::array; + +static_assert(secp::ellswift_size == 64); +static_assert(static_cast(secp::ellswift_party::initiator) == 0); +static_assert(static_cast(secp::ellswift_party::responder) == 1); +static_assert(std::is_same_v(), + std::declval())), + encoding>); +static_assert(std::is_same_v())), + secp::public_key>); +static_assert(std::is_same_v(), + std::declval())), + boost::system::result>); +static_assert( + std::is_same_v(), std::declval(), + std::declval(), secp::ellswift_party::initiator)), + boost::system::result>>); +static_assert(noexcept(secp::ellswift_decode(std::declval()))); + +std::vector split(std::string const& line) { + std::vector fields; + std::string field; + std::istringstream in(line); + while (std::getline(in, field, ',')) { + fields.push_back(field); + } + if (!line.empty() && line.back() == ',') { + fields.emplace_back(); + } + return fields; +} + +std::string without_cr(std::string line) { + if (!line.empty() && line.back() == '\r') { + line.pop_back(); + } + return line; +} + +// The rows of a CSV file of BIP 324's, each a map from the header's names to the fields. +std::vector> rows_of(std::string const& path) { + auto const text = test::read_file(path); + std::istringstream in(text); + std::string line; + std::getline(in, line); + auto const names = split(without_cr(line)); + std::vector> rows; + while (std::getline(in, line)) { + line = without_cr(line); + if (line.empty()) { + continue; + } + auto const fields = split(line); + if (fields.size() != names.size()) { + BOOST_ERROR(("malformed row: " + line).c_str()); + continue; + } + std::map row; + for (std::size_t i = 0; i < names.size(); ++i) { + row[names[i]] = fields[i]; + } + rows.push_back(std::move(row)); + } + return rows; +} + +template +std::array fixed(std::string const& hex) { + auto const bytes = test::from_hex(hex); + std::array out{}; + if (!BOOST_TEST_EQ(bytes.size(), N)) { + return out; + } + std::ranges::copy(bytes, out.begin()); + return out; +} + +// The x coordinate of a key, in hex: its compressed form without the prefix. +std::string x_of(secp::public_key const& key) { + auto const compressed = secp::serialize_public_key(key); + return test::to_hex(std::span(compressed).subspan(1)); +} + +secp::keypair keypair_of(std::span secret_bytes) { + auto made = secp::keypair::make(secret_bytes); + if (!BOOST_TEST(made.has_value())) { + std::exit(boost::report_errors()); + } + return std::move(*made); +} + +secp::public_key public_of(secp::keypair const& key) { + auto const encoded = key.public_key(); + auto const parsed = secp::parse_public_key(*encoded); + if (!BOOST_TEST(parsed.has_value())) { + std::exit(boost::report_errors()); + } + return *parsed; +} + +void decode_vectors() { + auto const rows = rows_of(WEBCPP_TEST_BIPS "/bip-0324/ellswift_decode_test_vectors.csv"); + int decoded = 0; + for (auto const& row : rows) { + auto const key = secp::ellswift_decode(fixed<64>(row.at("ellswift"))); + if (BOOST_TEST_EQ(x_of(key), row.at("x"))) { + ++decoded; + } else { + BOOST_ERROR(row.at("comment").c_str()); + } + } + std::cout << "ellswift_decode: rows=" << rows.size() << " decoded=" << decoded << '\n'; + BOOST_TEST_EQ(rows.size(), 76U); + BOOST_TEST_EQ(decoded, 76); +} + +void packet_vectors() { + auto const rows = rows_of(WEBCPP_TEST_BIPS "/bip-0324/packet_encoding_test_vectors.csv"); + int agreed = 0; + for (auto const& row : rows) { + auto const ours = fixed<64>(row.at("in_ellswift_ours")); + auto const theirs = fixed<64>(row.at("in_ellswift_theirs")); + bool const initiating = row.at("in_initiating") == "1"; + BOOST_TEST_EQ(x_of(secp::ellswift_decode(ours)), row.at("mid_x_ours")); + BOOST_TEST_EQ(x_of(secp::ellswift_decode(theirs)), row.at("mid_x_theirs")); + auto const key = keypair_of(fixed<32>(row.at("in_priv_ours"))); + BOOST_TEST_EQ(x_of(public_of(key)), row.at("mid_x_ours")); + auto const& initiator = initiating ? ours : theirs; + auto const& responder = initiating ? theirs : ours; + auto const shared = secp::ellswift_xdh( + key, initiator, responder, + initiating ? secp::ellswift_party::initiator : secp::ellswift_party::responder); + if (BOOST_TEST(shared.has_value()) && + BOOST_TEST_EQ(test::to_hex(shared->bytes()), row.at("mid_shared_secret"))) { + ++agreed; + } + } + std::cout << "packet_encoding: rows=" << rows.size() << " agreed=" << agreed << '\n'; + BOOST_TEST_EQ(rows.size(), 7U); + BOOST_TEST_EQ(agreed, 7); +} + +scalar draw(std::mt19937_64& generator) { + for (;;) { + scalar out{}; + for (auto& octet : out) { + octet = static_cast(generator()); + } + if (secp256k1_ec_seckey_verify(secp256k1_context_static, out.data()) == 1) { + return out; + } + } +} + +scalar random_bytes(std::mt19937_64& generator) { + scalar out{}; + for (auto& octet : out) { + octet = static_cast(generator()); + } + return out; +} + +// One round over two seeded key pairs: the round trips, the encodings' variety, and the +// exchange from both sides. +void seeded_round(std::mt19937_64& generator) { + auto const initiator_key = keypair_of(draw(generator)); + auto const responder_key = keypair_of(draw(generator)); + auto const initiator_public = public_of(initiator_key); + auto const first_randomness = random_bytes(generator); + auto const second_randomness = random_bytes(generator); + + auto const created = secp::ellswift_create(initiator_key, first_randomness); + auto const created_again = secp::ellswift_create(initiator_key, second_randomness); + auto const responder_created = secp::ellswift_create(responder_key, first_randomness); + if (!BOOST_TEST(created && created_again && responder_created)) { + return; + } + BOOST_TEST(secp::ellswift_decode(*created) == initiator_public); + BOOST_TEST(secp::ellswift_decode(*created_again) == initiator_public); + BOOST_TEST(*created != *created_again); + + auto const encoded = secp::ellswift_encode(initiator_public, first_randomness); + auto const encoded_again = secp::ellswift_encode(initiator_public, second_randomness); + BOOST_TEST(secp::ellswift_decode(encoded) == initiator_public); + BOOST_TEST(secp::ellswift_decode(encoded_again) == initiator_public); + BOOST_TEST(encoded != encoded_again); + + auto const initiator_secret = secp::ellswift_xdh(initiator_key, *created, *responder_created, + secp::ellswift_party::initiator); + auto const responder_secret = secp::ellswift_xdh(responder_key, *created, *responder_created, + secp::ellswift_party::responder); + auto const swapped = secp::ellswift_xdh(initiator_key, *created, *responder_created, + secp::ellswift_party::responder); + if (!BOOST_TEST(initiator_secret && responder_secret && swapped)) { + return; + } + BOOST_TEST(crypto::equal(initiator_secret->bytes(), responder_secret->bytes())); + BOOST_TEST(!crypto::equal(initiator_secret->bytes(), swapped->bytes())); + // Any encoding of the same key gives the same point, but the hash binds the bytes sent. + auto const other_encoding = secp::ellswift_xdh( + responder_key, *created_again, *responder_created, secp::ellswift_party::responder); + BOOST_TEST(other_encoding && + !crypto::equal(initiator_secret->bytes(), other_encoding->bytes())); +} + +void seeded() { + std::mt19937_64 generator(0xe115f17ULL); + for (int round = 0; round < 64; ++round) { + seeded_round(generator); + } +} + +void moved_from() { + scalar secret_bytes{}; + secret_bytes.fill(0x11); + auto source = keypair_of(secret_bytes); + auto const peer = secp::ellswift_create(source, scalar{}); + auto const target = std::move(source); + BOOST_TEST(target.public_key().has_value()); + // NOLINTBEGIN(bugprone-use-after-move): the moved-from pair is what is tested + BOOST_TEST(secp::ellswift_create(source, scalar{}).error() == crypto::error::invalid_state); + if (BOOST_TEST(peer.has_value())) { + BOOST_TEST( + secp::ellswift_xdh(source, *peer, *peer, secp::ellswift_party::initiator).error() == + crypto::error::invalid_state); + } + test::expect_empty_keypair(source); + // NOLINTEND(bugprone-use-after-move) +} + +} // namespace + +int main() { + decode_vectors(); + packet_vectors(); + seeded(); + moved_from(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/support/secp256k1_checks.hpp b/test/support/secp256k1_checks.hpp index a3212422..cd4dffd4 100644 --- a/test/support/secp256k1_checks.hpp +++ b/test/support/secp256k1_checks.hpp @@ -11,6 +11,7 @@ #define WEBCPP_TEST_CRYPTO_SUPPORT_SECP256K1_CHECKS_HPP #include +#include #include #include @@ -43,6 +44,12 @@ inline void expect_empty_keypair(webcpp::crypto::curves::secp256k1::keypair& key BOOST_TEST(key.sign_ecdsa(message, aux).error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.sign_recoverable(message).error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.tweak_xonly(tweak).error() == webcpp::crypto::error::invalid_state); + BOOST_TEST(webcpp::crypto::curves::secp256k1::ellswift_create(key, aux).error() == + webcpp::crypto::error::invalid_state); + std::array const noise{}; + BOOST_TEST(webcpp::crypto::curves::secp256k1::ellswift_xdh( + key, noise, noise, webcpp::crypto::curves::secp256k1::ellswift_party::initiator) + .error() == webcpp::crypto::error::invalid_state); std::array encoding{}; BOOST_TEST(webcpp::crypto::curves::secp256k1::encode_pkcs8(key, encoding).error() == webcpp::crypto::error::invalid_state); diff --git a/test/windows_h_after_test.cpp b/test/windows_h_after_test.cpp index c09eac3e..cd896ce9 100644 --- a/test/windows_h_after_test.cpp +++ b/test/windows_h_after_test.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include diff --git a/test/windows_h_before_test.cpp b/test/windows_h_before_test.cpp index 3a1da08e..b908a461 100644 --- a/test/windows_h_before_test.cpp +++ b/test/windows_h_before_test.cpp @@ -40,6 +40,7 @@ #include #include #include +#include #include #include #include From aa3cdd0f6f5239725b4a0c9f57b1f523342e451e Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 18:52:15 -0300 Subject: [PATCH 10/54] crypto: pubkey_combine wipes its workspace on every return, its refusals included --- include/webcpp/crypto/curves/secp256k1/tweak.hpp | 5 +++-- test/secp256k1_tweak_test.cpp | 8 ++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/include/webcpp/crypto/curves/secp256k1/tweak.hpp b/include/webcpp/crypto/curves/secp256k1/tweak.hpp index ead02e79..2f5a1b90 100644 --- a/include/webcpp/crypto/curves/secp256k1/tweak.hpp +++ b/include/webcpp/crypto/curves/secp256k1/tweak.hpp @@ -234,7 +234,7 @@ template * @tparam Backend The backend, `backends::secp256k1`. * @param parsed_keys The keys, at least one. * @param pointer_space At least `combine_workspace_size(parsed_keys.size())` bytes; zero when - * the function returns. + * the function returns, whatever it returns. * @return The sum; `invalid_input_size` for no keys or a short workspace; `invalid_public_key` * for a sum at infinity. */ @@ -244,13 +244,14 @@ template static_assert(webcpp::crypto::detail::secp256k1_backend, WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + // The carver first: it wipes the workspace on every return, a refusal's included. + webcpp::crypto::detail::secp256k1_workspace carver(pointer_space); // libsecp256k1 checks the count with ARG_CHECK, whose callback aborts: refused first here. if (parsed_keys.empty() || pointer_space.size() < combine_workspace_size(parsed_keys.size())) { return error::invalid_input_size; } secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; - webcpp::crypto::detail::secp256k1_workspace carver(pointer_space); auto* const key_pointers = carver.take(parsed_keys.size()); if (key_pointers == nullptr) { return error::invalid_input_size; diff --git a/test/secp256k1_tweak_test.cpp b/test/secp256k1_tweak_test.cpp index dbe481e2..a9771722 100644 --- a/test/secp256k1_tweak_test.cpp +++ b/test/secp256k1_tweak_test.cpp @@ -360,16 +360,20 @@ void refusals() { refused("pubkey_combine(P, -P)", secp::pubkey_combine(opposite, space), crypto::error::invalid_public_key); BOOST_TEST(all_zero(space)); - // No keys, and a workspace one byte short; the workspace is not written. + // No keys, and a workspace one byte short: refused, and the workspace, lent full of + // non-zero bytes, is zero afterwards all the same. + std::ranges::fill(space, std::byte{0xa5}); refused("pubkey_combine({})", secp::pubkey_combine({}, space), crypto::error::invalid_input_size); + BOOST_TEST(all_zero(space)); + std::ranges::fill(space, std::byte{0xa5}); std::array const pair{p_d, public_of(small(7))}; refused("pubkey_combine(short)", secp::pubkey_combine(pair, std::span(space).first(space.size() - 1)), crypto::error::invalid_input_size); + BOOST_TEST(all_zero(std::span(space).first(space.size() - 1))); refused("pubkey_combine(no workspace)", secp::pubkey_combine(pair, {}), crypto::error::invalid_input_size); - BOOST_TEST(all_zero(space)); } } // namespace From c7c8583db0092530b37e2bfb677b30d0ddf30d90 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 18:55:09 -0300 Subject: [PATCH 11/54] crypto: the tweak example wipes the HMAC's state, its digest and the tweak it computes --- example/key_tweak.cpp | 46 ++++++++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/example/key_tweak.cpp b/example/key_tweak.cpp index 9be7fc4f..7f0b2fc1 100644 --- a/example/key_tweak.cpp +++ b/example/key_tweak.cpp @@ -25,6 +25,7 @@ #include #include #include +#include namespace crypto = webcpp::crypto; namespace secp256k1 = webcpp::crypto::curves::secp256k1; @@ -32,10 +33,19 @@ namespace hash2 = boost::hash2; namespace { -// 32 secret bytes the program holds, overwritten when the scope ends, on every path, an early -// return's included. The bytes are written through a volatile pointer, which the optimiser -// cannot drop as a dead store: crypto wipes its own copies of keys this way, and the program -// wipes its own. +// Overwrites an object's bytes through a volatile pointer, which the optimiser cannot drop as a +// dead store: crypto wipes its own copies of keys this way, and the program wipes its own. +template +void wipe(T& object) { + static_assert(std::is_trivially_destructible_v, "an object whose bytes are all its state"); + auto* const data = reinterpret_cast(&object); + for (std::size_t i = 0; i < sizeof(T); ++i) { + data[i] = 0; + } +} + +// 32 secret bytes the program holds, wiped when the scope ends, on every path, an early return's +// included. struct wiped_bytes { std::array bytes{}; @@ -43,20 +53,16 @@ struct wiped_bytes { wiped_bytes(wiped_bytes const&) = delete; wiped_bytes& operator=(wiped_bytes const&) = delete; - ~wiped_bytes() { - std::uint8_t volatile* const data = bytes.data(); - for (std::size_t i = 0; i < bytes.size(); ++i) { - data[i] = 0; - } - } + ~wiped_bytes() { wipe(bytes); } }; // The tweak of payment `number`: HMAC-SHA-256 under the chain code of the compressed public key -// and the number. Both sides compute it; an outsider without the chain code cannot, and so -// cannot tell that two payment keys belong to one wallet. -std::array payment_tweak(std::span chain_code, - std::span public_key, - std::uint32_t number) { +// and the number, written into `tweak`. Both sides compute it; an outsider without the chain +// code cannot, and so cannot tell that two payment keys belong to one wallet. The HMAC's state, +// keyed by the chain code, and its digest, the tweak itself, are wiped before it returns. +void payment_tweak(std::span chain_code, + std::span public_key, std::uint32_t number, + wiped_bytes& tweak) { hash2::hmac_sha2_256 mac(chain_code.data(), chain_code.size()); mac.update(public_key.data(), public_key.size()); std::array const index{ @@ -66,10 +72,10 @@ std::array payment_tweak(std::span cha static_cast(number), }; mac.update(index.data(), index.size()); - auto const digest = mac.result(); - std::array tweak{}; - std::copy_n(digest.data(), tweak.size(), tweak.begin()); - return tweak; + auto digest = mac.result(); + std::copy_n(digest.data(), tweak.bytes.size(), tweak.bytes.begin()); + wipe(digest); + wipe(mac); } } // namespace @@ -94,7 +100,7 @@ int main() { } // The tweak and the tweaked secret give back the secret: the tweak is wiped too. wiped_bytes tweak; - tweak.bytes = payment_tweak(chain_code.bytes, *wallet_public, 7); + payment_tweak(chain_code.bytes, *wallet_public, 7, tweak); // tag::tweak[] // The server: the wallet's public key plus the tweak, with no secret anywhere. From ce84ca857141a8e8ddaee0f638626615e7fda130 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 18:55:16 -0300 Subject: [PATCH 12/54] crypto: the ElligatorSwift example drops its exchange tag, which no page includes --- example/ellswift_handshake.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/example/ellswift_handshake.cpp b/example/ellswift_handshake.cpp index f8da839d..e4da9ebf 100644 --- a/example/ellswift_handshake.cpp +++ b/example/ellswift_handshake.cpp @@ -40,7 +40,6 @@ int main() { return 1; } - // tag::exchange[] // Each peer sends the 64 bytes ellswift_create makes from its key pair. auto const initiator_message = secp256k1::ellswift_create(*initiator, repeated(0x33)); auto const responder_message = secp256k1::ellswift_create(*responder, repeated(0x44)); @@ -71,7 +70,6 @@ int main() { return 1; } std::printf("initiator and responder agree\n"); - // end::exchange[] return 0; } From 1bb9a70023d9df1a79d33ba73dfa7f7795e850f2 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 18:55:37 -0300 Subject: [PATCH 13/54] crypto: the curves page lists what secp256k1's three module headers add, one item each --- doc/curves.adoc | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/doc/curves.adoc b/doc/curves.adoc index cdeebc64..29556575 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -22,12 +22,16 @@ Bitcoin, Ethereum and Nostr. This version covers Bitcoin's keys and signatures, Nostr's event signatures (NIP-01) and the raw x-coordinate ECDH of its encrypted messages (NIP-44, <>), and Ethereum's ECDSA: recoverable signatures, the recovery of a signer's public key from a -signature, and the uncompressed key (<>). It adds -tweaks to whole keys, the arithmetic of BIP 32's derivation and of watch-only -wallets (<>), and writes and reads keys in the SPKI and -PKCS#8 files that OpenSSL exchanges (<>), and sends -keys as random-looking bytes, BIP 324's ElligatorSwift +signature, and the uncompressed key (<>). It also +offers: + +* tweaks of whole keys, the arithmetic of BIP 32's derivation and of +watch-only wallets (<>); +* keys written and read in the SPKI and PKCS#8 files that OpenSSL exchanges +(<>); +* keys sent as random-looking bytes, BIP 324's ElligatorSwift (<>). + Ethereum's `v` encoding of the recovery id, the hash it signs, its transactions and its addresses are a domain library's. The second is Ed25519, RFC 8032's signatures on edwards25519, with Ed25519ph for a message given in From 37cab1dc7acdc4eb9eb480a8f3f44ddf5e8f80df Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 19:02:26 -0300 Subject: [PATCH 14/54] crypto: secp256k1's Doc Comments name the random device in words, as the header lint's world rule asks --- include/webcpp/crypto/curves/secp256k1.hpp | 2 +- include/webcpp/crypto/curves/secp256k1/ellswift.hpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index 74657601..9d20ed61 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -608,7 +608,7 @@ class basic_keypair { * signing does not repeat on the next. * * @param message_hash The 32-byte hash signed. - * @param extra_entropy 32 bytes from `random_device`, new for each signature. + * @param extra_entropy 32 bytes from crypto's random device, new for each signature. * @return 64 bytes, r then s, low-S; `invalid_state`; `backend_failure`. */ [[nodiscard]] boost::system::result> sign_ecdsa( diff --git a/include/webcpp/crypto/curves/secp256k1/ellswift.hpp b/include/webcpp/crypto/curves/secp256k1/ellswift.hpp index 9ee4196d..2a4ca705 100644 --- a/include/webcpp/crypto/curves/secp256k1/ellswift.hpp +++ b/include/webcpp/crypto/curves/secp256k1/ellswift.hpp @@ -50,7 +50,7 @@ enum class ellswift_party { * * @tparam Backend The backend, `backends::secp256k1`. * @param parsed_key The key. - * @param randomness 32 fresh bytes from `random_device`: the encoding is one of many. + * @param randomness 32 fresh bytes from crypto's random device: the encoding is one of many. * @return The 64 bytes. */ template @@ -96,8 +96,8 @@ template * * @tparam Backend The key pair's backend, `backends::secp256k1`. * @param key_pair The key pair. - * @param randomness 32 fresh bytes from `random_device`, mixed with the secret into the choice - * of the encoding. + * @param randomness 32 fresh bytes from crypto's random device, mixed with the secret into the + * choice of the encoding. * @return 64 bytes; `invalid_state` moved from; `backend_failure`. */ template From 8d9272828e451f3728c40f90451b9c465c2b44aa Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 19:08:32 -0300 Subject: [PATCH 15/54] crypto: MuSig2 on libsecp256k1, against BIP 327's vectors, with a nonce its signature consumes --- doc/changelog.adoc | 2 +- doc/curves.adoc | 4 +- doc/generated/backends-musig.adoc | 30 + doc/generated/matrix.adoc | 11 + doc/generated/messages.adoc | 10 + doc/generated/use-cases.adoc | 7 + doc/llms.txt | 21 + doc/secp256k1.adoc | 96 ++- doc/tables/crypto.json | 18 +- example/Jamfile | 4 + example/musig_wallet.cpp | 110 +++ example/musig_wallet.expected | 3 + include/webcpp/crypto.hpp | 1 + include/webcpp/crypto/backends/secp256k1.hpp | 6 +- include/webcpp/crypto/curves/secp256k1.hpp | 26 + .../webcpp/crypto/curves/secp256k1/musig.hpp | 728 ++++++++++++++++ test/Jamfile | 11 +- test/crypto_secp256k1_test.cpp | 6 +- test/messages/Jamfile | 1 + test/messages/musig_nonce_copied/Jamfile | 12 + .../musig_nonce_copied/musig_nonce_copied.cpp | 40 + test/msvc/Jamfile | 1 + test/msvc/musig_nonce_copied/Jamfile | 10 + test/msvc/musig_nonce_copied/app.cpp | 35 + test/secp256k1_allocation_test.cpp | 90 +- test/secp256k1_musig_entropy_test.cpp | 90 ++ test/secp256k1_musig_test.cpp | 781 ++++++++++++++++++ test/support/secp256k1_checks.hpp | 45 + test/windows_h_after_test.cpp | 1 + test/windows_h_before_test.cpp | 1 + test/wipe_objects_test.cpp | 37 +- 31 files changed, 2217 insertions(+), 21 deletions(-) create mode 100644 doc/generated/backends-musig.adoc create mode 100644 example/musig_wallet.cpp create mode 100644 example/musig_wallet.expected create mode 100644 include/webcpp/crypto/curves/secp256k1/musig.hpp create mode 100644 test/messages/musig_nonce_copied/Jamfile create mode 100644 test/messages/musig_nonce_copied/musig_nonce_copied.cpp create mode 100644 test/msvc/musig_nonce_copied/Jamfile create mode 100644 test/msvc/musig_nonce_copied/app.cpp create mode 100644 test/secp256k1_musig_entropy_test.cpp create mode 100644 test/secp256k1_musig_test.cpp diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 5d26b9f2..dac4925a 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -20,7 +20,7 @@ of every version are on webcpp's index page. * Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default, one default per family and target, and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). -* Added curves::secp256k1: key pairs, BIP340, hedged and recoverable ECDSA, three self-wiping ECDH forms, strict DER, low-S, tweaks, negation, combination, SPKI, PKCS#8 and BIP 324's ElligatorSwift. +* Added curves::secp256k1: key pairs, BIP340, hedged and recoverable ECDSA, three self-wiping ECDH forms, strict DER, low-S, tweaks, negation, combination, SPKI, PKCS#8, BIP 324's ElligatorSwift and BIP 327's MuSig2. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. * Added ciphers::secretbox and secretbox_xchacha20poly1305, without additional data, hybrid::box, box_xchacha20poly1305 and sealed_box (failed seals and opens zeroing data), and curves::x25519::kx_keypair (crypto_kx) on libsodium, refusing peer keys of small order. diff --git a/doc/curves.adoc b/doc/curves.adoc index 29556575..428649c4 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -30,7 +30,9 @@ watch-only wallets (<>); * keys written and read in the SPKI and PKCS#8 files that OpenSSL exchanges (<>); * keys sent as random-looking bytes, BIP 324's ElligatorSwift -(<>). +(<>); +* many signers' keys and signatures aggregated into one, BIP 327's MuSig2 +(<>). Ethereum's `v` encoding of the recovery id, the hash it signs, its transactions and its addresses are a domain library's. The second is Ed25519, diff --git a/doc/generated/backends-musig.adoc b/doc/generated/backends-musig.adoc new file mode 100644 index 00000000..b1ff2f21 --- /dev/null +++ b/doc/generated/backends-musig.adoc @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+curves::secp256k1::musig::aggregate_key+`, `+key_aggregate+`, `+nonce_gen+`, `+nonce_aggregate+`, `+nonce_process+`, `+partial_sign+`, `+partial_signature_verify+`, `+partial_signature_aggregate+`, `+parse_public_nonce+`, `+serialize_public_nonce+`, `+parse_aggregate_nonce+`, `+serialize_aggregate_nonce+`, `+parse_partial_signature+`, `+serialize_partial_signature+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsecp256k1 +|`+/third_party//secp256k1+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+secp256k1_musig+`, `+secp256k1_musig_entropy+`) +|=== + +A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsecp256k1 +|=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index 8334571b..dcc67912 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -215,6 +215,11 @@ |libsecp256k1 |native, wasip2, wasip3, emscripten |`+secp256k1_ellswift+` + +|`+curves::secp256k1::musig::aggregate_key+`, `+key_aggregate+`, `+nonce_gen+`, `+nonce_aggregate+`, `+nonce_process+`, `+partial_sign+`, `+partial_signature_verify+`, `+partial_signature_aggregate+`, `+parse_public_nonce+`, `+serialize_public_nonce+`, `+parse_aggregate_nonce+`, `+serialize_aggregate_nonce+`, `+parse_partial_signature+`, `+serialize_partial_signature+` +|libsecp256k1 +|native, wasip2, wasip3, emscripten +|`+secp256k1_musig+`, `+secp256k1_musig_entropy+` |=== The same, by target: the backends each operation runs on. @@ -420,4 +425,10 @@ The same, by target: the backends each operation runs on. |libsecp256k1 |libsecp256k1 |libsecp256k1 + +|`+curves::secp256k1::musig::aggregate_key+`, `+key_aggregate+`, `+nonce_gen+`, `+nonce_aggregate+`, `+nonce_process+`, `+partial_sign+`, `+partial_signature_verify+`, `+partial_signature_aggregate+`, `+parse_public_nonce+`, `+serialize_public_nonce+`, `+parse_aggregate_nonce+`, `+serialize_aggregate_nonce+`, `+parse_partial_signature+`, `+serialize_partial_signature+` +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 |=== diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 58dd2f67..18b4ddb0 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -139,6 +139,12 @@ The fix: As `+heavy_without_threads+`. The fix: Add `+/webcpp/crypto//kx-default+`, which links `+/third_party//sodium+` on every target. +|`+musig_nonce_copied+` +|native, wasip2 +|`+call to deleted constructor of+` + +The fix: Pass the nonce with std::move, once: a secret nonce signs one message. + |`+no_backend_wasm+` |wasip2, wasip3 |`+webcpp::crypto: AES-GCM's default backend on this target is BearSSL, which is not linked. Add /webcpp/crypto//gcm-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//gcm-default ; or name another backend in the type, as in ciphers::gcm>. The backends that have it: bearssl (native, wasip2, wasip3, emscripten), openssl (native, wasip2, wasip3). (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` @@ -948,6 +954,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the link |Give the define in the requirements of the program's project, with OpenSSL beside it, `+project app : requirements WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE /webcpp/crypto//openssl ;+`, so that every target of the program gets both. +|`+musig_nonce_copied+` +|the compile +|Pass the nonce with std::move, once: a secret nonce signs one message. + |`+openssl_memory_not_linked+` |the compile |A target has the define and not OpenSSL: put `+/webcpp/crypto//openssl+` in the same project requirements as the define, or remove the define. diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index dbcfbc35..7b5cee53 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -106,6 +106,13 @@ `+/third_party//secp256k1+` |<> +|Require two devices to sign for a wallet, with one ordinary signature on the chain +|In `+curves::secp256k1::musig+`: `+key_aggregate+`, `+nonce_gen+`, `+partial_sign+`, `+partial_signature_aggregate+` +|libsecp256k1 +|`+/webcpp/crypto//crypto+` + +`+/third_party//secp256k1+` +|<> + |Make and keep a wallet's key |In `+curves::secp256k1+`: `+keypair::make+`, `+xonly_public_key+`, `+public_key+`; `+aes256_gcm+` at rest |libsecp256k1, and AES-GCM's default diff --git a/doc/llms.txt b/doc/llms.txt index 3e39c250..85c0a786 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -141,6 +141,25 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - ellswift_decode: The public key of any 64 bytes (`secp256k1_ellswift_decode`): every input decodes. - ellswift_create: The encoding of a key pair's public key, made from its secret with the key pair's context (`secp256k1_ellswift_create`), so that the public key is never computed apart. - ellswift_xdh: The shared secret of an ElligatorSwift key exchange, hashed as BIP 324 hashes it (`secp256k1_ellswift_xdh` with `secp256k1_ellswift_xdh_hash_function_bip324`): a tagged hash of both encodings and the shared point's x coordinate. +- [curves::secp256k1::musig::aggregate_key, key_aggregate, nonce_gen, nonce_aggregate, nonce_process, partial_sign, partial_signature_verify, partial_signature_aggregate, parse_public_nonce, serialize_public_nonce, parse_aggregate_nonce, serialize_aggregate_nonce, parse_partial_signature, serialize_partial_signature](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-musig): BIP 327's MuSig2: many signers' keys aggregated into one, and their two rounds into one BIP 340 signature, each secret nonce consumed by its partial signature. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: require two devices to sign for a wallet, with one ordinary signature on the chain. + - xonly_public_key: The BIP 340 x-only key the final signature verifies under. + - full_public_key: The aggregate as a full point (`secp256k1_musig_pubkey_get`), which a plain tweak acts on. + - tweak_add: Adds t times G as a plain tweak (BIP 327's ApplyTweak, is_xonly false, `secp256k1_musig_pubkey_ec_tweak_add`). + - tweak_xonly_add: Adds t times G as an x-only tweak (BIP 327's ApplyTweak, is_xonly true, `secp256k1_musig_pubkey_xonly_tweak_add`), as Taproot tweaks an output key. + - workspace_size: The workspace `key_aggregate`, `nonce_aggregate` and `partial_signature_aggregate` need for `count` items, in bytes. + - key_aggregate: Aggregates the signers' keys in the order given (`secp256k1_musig_pubkey_agg`). + - nonce_gen: A fresh nonce for one signature (`secp256k1_musig_nonce_gen`), its 32 bytes of session randomness drawn inside from crypto's random device, with the key pair's secret, its public key and the aggregate key. + - nonce_aggregate: Sums the signers' public nonces (`secp256k1_musig_nonce_agg`), as one of them or a coordinator does once every public nonce is in. + - nonce_process: The session of one message (`secp256k1_musig_nonce_process`): the final nonce and the challenge every signer signs. + - partial_sign: This signer's partial signature (`secp256k1_musig_partial_sign`), consuming the nonce: it is taken by value, wiped by the call and destroyed at its end. + - partial_signature_verify: Verifies one signer's partial signature (`secp256k1_musig_partial_sig_verify`), which tells a dishonest or faulty signer apart before the signature is aggregated. + - partial_signature_aggregate: The BIP 340 signature of the partial signatures (`secp256k1_musig_partial_sig_agg`), which `verify_schnorr` checks under `aggregate_key::xonly_public_key()`. + - parse_public_nonce: Parses a signer's public nonce (`secp256k1_musig_pubnonce_parse`): two compressed points. + - serialize_public_nonce: Serialises a signer's public nonce (`secp256k1_musig_pubnonce_serialize`). + - parse_aggregate_nonce: Parses an aggregate nonce (`secp256k1_musig_aggnonce_parse`): two compressed points, either of which may be the point at infinity, written as 33 zero bytes. + - serialize_aggregate_nonce: Serialises an aggregate nonce (`secp256k1_musig_aggnonce_serialize`). + - parse_partial_signature: Parses a partial signature (`secp256k1_musig_partial_sig_parse`). + - serialize_partial_signature: Serialises a partial signature (`secp256k1_musig_partial_sig_serialize`). ## webcpp::crypto::hybrid @@ -226,6 +245,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Find who signed a message or a transaction without being sent their key (Ethereum's signatures)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-recovery): `keypair::sign_recoverable`, `recover` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/recover_signer.cpp. - [Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-tweaks): `seckey_tweak_add`, `pubkey_tweak_add` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/key_tweak.cpp. - [Make a peer-to-peer connection's key exchange look like random bytes (BIP 324's transport; its packets are a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ellswift): `ellswift_create`, `ellswift_decode`, `ellswift_xdh` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ellswift_handshake.cpp. +- [Require two devices to sign for a wallet, with one ordinary signature on the chain](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-musig): `key_aggregate`, `nonce_gen`, `partial_sign`, `partial_signature_aggregate` (webcpp::crypto::curves::secp256k1::musig); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/musig_wallet.cpp. - [Make and keep a wallet's key](https://webcpporg.github.io/libs/crypto/#crypto-wallets-key): `keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/wallet_key.cpp. - [Sign a Bitcoin SegWit v0 input (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-der): `sign_ecdsa`, `to_der`, `normalize_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdsa_der.cpp. - [Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly`, `keypair::tweak_xonly` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/taproot_tweak.cpp. @@ -261,6 +281,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/key_formats.cpp: Reads RFC 8410's Ed25519 private key in PEM (section 10.3), as OpenSSL or WebCrypto export it, writes its public key as PEM, which is the RFC's section 10.1 to the character, and signs with it; writes an X25519 key pair's public key the same way; and refuses the RFC's version 2 of the private key, which carries the public key too. Prints the PEM texts and each verdict. - example/key_tweak.cpp: A watch-only wallet: a server that holds the wallet's public key and no secret gives each payment a fresh key, and the signing device, which holds the secret, derives the same keys' secrets. Both add the same tweak, one to the public key and one to the secret key; the device's tweaked key pair signs (BIP 340), and the signature verifies under the server's tweaked public key. The tweak here is an HMAC-SHA-256 of the public key and the payment's number under a chain code both sides share and no one else sees; BIP 32 derives such tweaks its own way, with HMAC-SHA-512, and is a domain library's. - example/kx_session.cpp: A chat app's client and server, each with a crypto_kx key pair made from libsodium's kx test's seeds, exchange public keys and compute their session keys; the client seals a message with its transmit key and the server opens it with its receive key, on ChaCha20-Poly1305; a peer key of low order is refused. Prints the public keys and the client's session keys in hex. +- example/musig_wallet.cpp: A wallet split across two devices, a phone and a laptop, whose coins move only when both sign (BIP 327's MuSig2): the two public keys are sorted and aggregated into one; each device makes a nonce and sends its public half; each signs its part once every public nonce is in; the parts add up to one BIP 340 signature under the one x-only key, which on the chain looks like any single signer's. The devices' secrets are fixed here, so that the program runs the same each time; a real wallet draws them from crypto's random device. The nonces are fresh in every run, drawn inside nonce_gen; nothing random is printed. - example/openssl_memory.cpp: Sends every allocation of OpenSSL's to the program's own memory resource, natively, then seals and opens one block with AES-256-GCM on OpenSSL, on a worker thread as an audio engine's or a server's would. Built with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, /webcpp/crypto//openssl and threads (example/Jamfile). - example/order_reference.cpp: Turns a sequential order id into an opaque 16-byte reference with the raw AES block cipher, and back. Customers then cannot guess other orders' numbers. This is NOT authenticated encryption: a forged reference still decrypts, to garbage, so the program checks the padding. - example/recover_signer.cpp: Finds who signed a message without being sent their key, as Ethereum finds a transaction's signer: a wallet signs a message's hash with a recoverable signature, and a reader that holds no key recovers the signer's public key from the signature and the hash, then compares it with the key the wallet published. Recovery always finds some key, so the comparison is the check: a changed message recovers another key. diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index 3f5571e9..5bfae59b 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -46,13 +46,15 @@ check signatures with a public key alone, and `recover` finds the key from a recoverable signature; `parse_public_key` and `serialize_public_key` read and write a `public_key` (<>); `to_der`, `from_der` (strict DER) and `normalize_ecdsa` convert ECDSA's DER and low-S forms; and -`tweak_xonly` tweaks an x-only public key. Three more headers hold the tweaks, +`tweak_xonly` tweaks an x-only public key. Four more headers hold the tweaks, negation and combination of whole keys (``, <>), the keys' SPKI and PKCS#8 (``, -<>) and ElligatorSwift, keys sent as random-looking +<>), ElligatorSwift, keys sent as random-looking bytes (``, -<>). Every function reads libsecp256k1's canary, so +<>), and MuSig2, many signers' one signature +(``, <>). +Every function reads libsecp256k1's canary, so that a program linked with another build of the library does not link. include::generated/backends-keypair.adoc[] @@ -474,3 +476,91 @@ by itself: BIP 324 derives its session's keys from it with HKDF (link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324]), and that schedule, its packets and its garbage terminators are a domain library's. + +[#crypto-secp256k1-musig] +==== MuSig2: many signers, one signature + +Some coins should move only when several parties agree: a company's treasury +that two officers approve, a Lightning channel whose two peers both sign each +update, a wallet split across a phone and a laptop so that a thief who takes +one device takes nothing. MuSig2 lets those signers aggregate their public +keys into one key and their signatures into one BIP 340 signature under it. +On the chain the key and the signature look like any single signer's: they +cost no more and tell no one that several parties hold the coins +(link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327]). + +It works in two rounds +(link:https://eprint.iacr.org/2020/1261[Nick, Ruffing and Seurin, MuSig2, +CRYPTO 2021]). First every signer makes a nonce and sends its public half to +the others, before the message need be known; then, with every public nonce +in, each signs its part of the message, and the parts add up to the +signature. ``, namespace +`curves::secp256k1::musig`, offers libsecp256k1's functions: + +* `key_aggregate` aggregates the signers' keys, in the order given, into an +`aggregate_key`; sort them first with `std::ranges::sort`, since the order of +`public_key` is BIP 327's KeySort. Its `xonly_public_key` is the key the +signature verifies under; `tweak_add` and `tweak_xonly_add` tweak it as a +protocol asks; +* `nonce_gen` makes one signer's nonce for one signature from its key pair, its +randomness drawn inside: a `secret_nonce` to keep and a `public_nonce` to send; +* `nonce_aggregate` sums the public nonces, and `nonce_process` makes the +`session` of the 32-byte message; +* `partial_sign` signs this signer's part, consuming its secret nonce; +`partial_signature_verify` checks one signer's part, and +`partial_signature_aggregate` adds the parts into 64 bytes that +`verify_schnorr` checks; +* `parse_public_nonce`, `parse_aggregate_nonce` and `parse_partial_signature` +read what the other signers send, and the `serialize_` functions write it. + +The functions over many keys, nonces or parts take a `workspace` of +`workspace_size(n)` bytes for libsecp256k1's array of pointers, so that nothing +is allocated, and wipe it before they return; no items or a short workspace is +`invalid_input_size`. A nonce or a partial signature that does not parse is +`invalid_point` or `invalid_signature`, a tweak out of range +`invalid_secret_key`, and a moved-from key pair or a used nonce +`invalid_state`. The tests check BIP 327's own vectors, those that need no +secret nonce of the vector's: a `secret_nonce` exists only from `nonce_gen`, +and libsecp256k1's own tests, run in the `c-suites` lane, check the rest. + +include::generated/backends-musig.adoc[] + +*Example.* A phone and a laptop hold the two halves of a wallet. They +aggregate their keys, exchange public nonces, each signs its part, and the +signature verifies as one BIP 340 signature under the wallet's one key: + +[source,cpp] +---- +include::{examples}/musig_wallet.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/musig_wallet.expected[] +---- + +*Pitfalls.* + +* A nonce used for two signatures gives away the secret key: from two partial +signatures with the same nonce, anyone solves for it +(link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327]). +This is why `partial_sign` takes the `secret_nonce` by value, so that passing +it needs a `std::move`, why its copy is deleted (the build stops), and why a +second move of the same object is refused with `invalid_state`. Never store a +secret nonce to sign later, after a restart: a nonce restored from a backup +signs a second time. +* Never sign before every public nonce is in. A signer who signs while others +can still choose their nonces lets them steer the final nonce, which the +two-round design exists to prevent +(link:https://eprint.iacr.org/2020/1261[MuSig2]). +* A key aggregated with an attacker's key that the attacker chose after seeing +yours is safe here: MuSig2 weighs each key with a coefficient hashed from all +of them, so that no signer can cancel another's. The plain sum of keys, +`pubkey_combine` (<>), has no such weight, and is +not a multisignature +(link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327]). +* The tweaks belong to a protocol. Taproot's output key is the aggregate key +tweaked by a tagged hash of it and a script tree's root +(link:https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki[BIP 341]); +that hash, and every other rule of the protocol, is a domain library's, which +passes the tweak to `tweak_xonly_add`. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 14499755..70b51fa1 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -106,13 +106,14 @@ "rfc7748-kdf": ["RFC 7748, section 6.1: a KDF over the shared secret and both public keys", "https://www.rfc-editor.org/rfc/rfc7748#section-6.1"], "libsodium-doc-licence": ["libsodium's documentation, jedisct1/libsodium-doc at 6d1ea27, ISC", "https://github.com/jedisct1/libsodium-doc/tree/6d1ea27b79b853b2a04f09ae9e1a8231c90e3b56"], "sec1": ["SEC 1 version 2, Elliptic Curve Cryptography, sections 2.3.3 and 2.3.4: a point's encodings", "https://www.secg.org/sec1-v2.pdf"], - "bip327": ["BIP 327, MuSig2, its key sorting", "https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki"], + "bip327": ["BIP 327, MuSig2 for BIP340-compatible multi-signatures", "https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki"], "rfc5480": ["RFC 5480, Elliptic Curve Cryptography Subject Public Key Information", "https://www.rfc-editor.org/rfc/rfc5480"], "rfc5915": ["RFC 5915, Elliptic Curve Private Key Structure", "https://www.rfc-editor.org/rfc/rfc5915"], "rfc5208": ["RFC 5208, PKCS #8: Private-Key Information Syntax", "https://www.rfc-editor.org/rfc/rfc5208"], "bip324": ["BIP 324, version 2 P2P encrypted transport protocol", "https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki"], "elligatorswift": ["Chavez-Saab, Rodríguez-Henríquez and Tibouchi, SwiftEC: Shallue-van de Woestijne Indifferentiable Function to Elliptic Curves, 2022", "https://eprint.iacr.org/2022/759"], - "openssl-evp-pkey-ec": ["OpenSSL's EVP_PKEY-EC: an EC key's point form and its encodings", "https://docs.openssl.org/master/man7/EVP_PKEY-EC/"] + "openssl-evp-pkey-ec": ["OpenSSL's EVP_PKEY-EC: an EC key's point form and its encodings", "https://docs.openssl.org/master/man7/EVP_PKEY-EC/"], + "musig2": ["Nick, Ruffing and Seurin, MuSig2: Simple Two-Round Schnorr Multi-Signatures, CRYPTO 2021", "https://eprint.iacr.org/2020/1261"] }, "backends": { "bearssl": { @@ -617,6 +618,17 @@ "what": "A public key written as 64 bytes that look random, and BIP 324's key exchange of two such encodings.", "section": "crypto-secp256k1-ellswift", "backends": {"secp256k1": {"tests": ["secp256k1_ellswift"]}} + }, + { + "id": "musig", + "family": "secp256k1", + "functions": ["xonly_public_key", "full_public_key", "tweak_add", "tweak_xonly_add", "workspace_size", "key_aggregate", "nonce_gen", "nonce_aggregate", "nonce_process", "partial_sign", "partial_signature_verify", "partial_signature_aggregate", "parse_public_nonce", "serialize_public_nonce", "parse_aggregate_nonce", "serialize_aggregate_nonce", "parse_partial_signature", "serialize_partial_signature"], + "namespace": "curves", + "api": "curves::secp256k1::musig::aggregate_key, key_aggregate, nonce_gen, nonce_aggregate, nonce_process, partial_sign, partial_signature_verify, partial_signature_aggregate, parse_public_nonce, serialize_public_nonce, parse_aggregate_nonce, serialize_aggregate_nonce, parse_partial_signature, serialize_partial_signature", + "header": "", + "what": "BIP 327's MuSig2: many signers' keys aggregated into one, and their two rounds into one BIP 340 signature, each secret nonce consumed by its partial signature.", + "section": "crypto-secp256k1-musig", + "backends": {"secp256k1": {"tests": ["secp256k1_musig", "secp256k1_musig_entropy"]}} } ], "families": [ @@ -986,6 +998,7 @@ {"need": "Find who signed a message or a transaction without being sent their key (Ethereum's signatures)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_recoverable`, `recover`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "recover_signer", "section": "crypto-secp256k1-recovery"}, {"need": "Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`seckey_tweak_add`, `pubkey_tweak_add`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "key_tweak", "section": "crypto-secp256k1-tweaks"}, {"need": "Make a peer-to-peer connection's key exchange look like random bytes (BIP 324's transport; its packets are a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`ellswift_create`, `ellswift_decode`, `ellswift_xdh`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ellswift_handshake", "section": "crypto-secp256k1-ellswift"}, + {"need": "Require two devices to sign for a wallet, with one ordinary signature on the chain", "namespace": "webcpp::crypto::curves::secp256k1::musig", "api": "`key_aggregate`, `nonce_gen`, `partial_sign`, `partial_signature_aggregate`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "musig_wallet", "section": "crypto-secp256k1-musig"}, {"need": "Make and keep a wallet's key", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "wallet_key", "section": "crypto-wallets-key"}, {"need": "Sign a Bitcoin SegWit v0 input (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`sign_ecdsa`, `to_der`, `normalize_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdsa_der", "section": "crypto-wallets-der"}, {"need": "Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`tweak_xonly`, `keypair::tweak_xonly`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "taproot_tweak", "section": "crypto-wallets-taproot"}, @@ -1085,6 +1098,7 @@ "secp256k1_not_linked": "Add `/third_party//secp256k1`.", "gcm_on_ctaes": "Name `gcm>` or `gcm>`, or use `aes256_gcm` with its default linked.", "secp256k1_other_backend": "Name `backends::secp256k1`, or leave the backend out: `curves::secp256k1::keypair`.", + "musig_nonce_copied": "Pass the nonce with std::move, once: a secret nonce signs one message.", "aes_on_bearssl": "Name `ciphers::aes256`, include `` and add `/third_party//ctaes`.", "default_selected": "Remove the define, and name `gcm>` where the program wants BearSSL.", "default_openssl_wasm": "Remove the define, and name `gcm>` where the program wants OpenSSL.", diff --git a/example/Jamfile b/example/Jamfile index b59e3e53..b978fd2a 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -65,6 +65,10 @@ webcpp.example key_tweak.cpp : /third_party//secp256k1 ; # random, and agree on BIP 324's shared secret. webcpp.example ellswift_handshake.cpp : /third_party//secp256k1 ; +# A wallet split across two devices: their keys aggregated with MuSig2, two +# rounds of nonces and partial signatures, one BIP 340 signature on the chain. +webcpp.example musig_wallet.cpp : /third_party//secp256k1 ; + # A wallet's key pair, its secret sealed at rest and restored. webcpp.example wallet_key.cpp : /third_party//secp256k1 /webcpp/crypto//gcm-default ; diff --git a/example/musig_wallet.cpp b/example/musig_wallet.cpp new file mode 100644 index 00000000..35e3fede --- /dev/null +++ b/example/musig_wallet.cpp @@ -0,0 +1,110 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A wallet split across two devices, a phone and a laptop, whose coins move only when both +// sign (BIP 327's MuSig2): the two public keys are sorted and aggregated into one; each device +// makes a nonce and sends its public half; each signs its part once every public nonce is in; +// the parts add up to one BIP 340 signature under the one x-only key, which on the chain looks +// like any single signer's. The devices' secrets are fixed here, so that the program runs the +// same each time; a real wallet draws them from crypto's random device. The nonces are fresh +// in every run, drawn inside nonce_gen; nothing random is printed. +// tag::program[] +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace secp256k1 = webcpp::crypto::curves::secp256k1; +namespace musig = webcpp::crypto::curves::secp256k1::musig; + +namespace { + +std::array repeated(std::uint8_t value) { + std::array bytes{}; + bytes.fill(value); + return bytes; +} + +} // namespace + +int main() { + // Each device's key pair; each sends the other its public key. + auto const phone = secp256k1::keypair::make(repeated(0x11)); + auto const laptop = secp256k1::keypair::make(repeated(0x22)); + if (!phone || !laptop) { + return 1; + } + auto const phone_key = secp256k1::parse_public_key(*phone->public_key()); + auto const laptop_key = secp256k1::parse_public_key(*laptop->public_key()); + if (!phone_key || !laptop_key) { + return 1; + } + + // Both sort the keys (BIP 327's KeySort) and aggregate them: the same key on both devices. + // The workspace holds libsecp256k1's array of pointers; nothing is allocated. + std::array keys{*phone_key, *laptop_key}; + std::ranges::sort(keys); + alignas(std::max_align_t) std::array space{}; + auto const wallet_key = musig::key_aggregate(keys, space); + if (!wallet_key) { + return 1; + } + std::printf("aggregate key made from %zu signers\n", keys.size()); + + // The spend both approve: the transaction's 32-byte hash, as a domain library computes it. + auto const message = repeated(0x5a); + + // Round one: each device makes a nonce for this signature and sends its public half. + auto phone_nonce = musig::nonce_gen(*phone, *wallet_key, message); + auto laptop_nonce = musig::nonce_gen(*laptop, *wallet_key, message); + if (!phone_nonce || !laptop_nonce) { + return 1; + } + + // Once both public nonces are in, each device computes the same session. + std::array const nonces{phone_nonce->public_part, + laptop_nonce->public_part}; + auto const nonce_sum = musig::nonce_aggregate(nonces, space); + if (!nonce_sum) { + return 1; + } + auto const signing_session = musig::nonce_process(*nonce_sum, message, *wallet_key); + if (!signing_session) { + return 1; + } + + // Round two: each signs its part, which consumes its secret nonce; the other checks it. + auto const phone_part = musig::partial_sign(*phone, std::move(phone_nonce->secret_part), + *wallet_key, *signing_session); + auto const laptop_part = musig::partial_sign(*laptop, std::move(laptop_nonce->secret_part), + *wallet_key, *signing_session); + if (!phone_part || !laptop_part || + !musig::partial_signature_verify(*phone_part, nonces[0], *phone_key, *wallet_key, + *signing_session) || + !musig::partial_signature_verify(*laptop_part, nonces[1], *laptop_key, *wallet_key, + *signing_session)) { + return 1; + } + std::printf("both partial signatures verify\n"); + + // The parts add up to one BIP 340 signature under the wallet's one x-only key. + std::array const parts{*phone_part, *laptop_part}; + auto const signature = musig::partial_signature_aggregate(*signing_session, parts, space); + if (!signature || + !secp256k1::verify_schnorr(*signature, message, wallet_key->xonly_public_key())) { + return 1; + } + std::printf("the aggregate signature verifies as one BIP 340 signature\n"); + return 0; +} + +// end::program[] diff --git a/example/musig_wallet.expected b/example/musig_wallet.expected new file mode 100644 index 00000000..df8d1456 --- /dev/null +++ b/example/musig_wallet.expected @@ -0,0 +1,3 @@ +aggregate key made from 2 signers +both partial signatures verify +the aggregate signature verifies as one BIP 340 signature diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index cad7719e..4c8de8c7 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -59,6 +59,7 @@ #include #include #include +#include #include #endif diff --git a/include/webcpp/crypto/backends/secp256k1.hpp b/include/webcpp/crypto/backends/secp256k1.hpp index 08f3b0d2..e2d053de 100644 --- a/include/webcpp/crypto/backends/secp256k1.hpp +++ b/include/webcpp/crypto/backends/secp256k1.hpp @@ -9,8 +9,9 @@ every module on. It serves `curves::secp256k1::keypair`, `verify_schnorr`, `verify_ecdsa`, `recover`, the parsed `public_key`, the DER and low-S functions, the x-only tweak, the tweaks and combination of `curves/secp256k1/tweak.hpp`, the SPKI and PKCS#8 of - `curves/secp256k1/formats.hpp` and the ElligatorSwift of `curves/secp256k1/ellswift.hpp`, and - its whole C API stays reachable through ``. + `curves/secp256k1/formats.hpp`, the ElligatorSwift of `curves/secp256k1/ellswift.hpp` and the + MuSig2 of `curves/secp256k1/musig.hpp`, and its whole C API stays reachable through + ``. @see "secp256k1", in the guide. */ @@ -31,6 +32,7 @@ #include #include #include +#include #include #include #include diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index 9d20ed61..e342f7e9 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -115,6 +115,32 @@ struct secp256k1_access { * @return The unwritten key. */ [[nodiscard]] static curves::secp256k1::public_key make_public_key() noexcept; + + /** + * An object of a module header's opaque type (MuSig2's aggregate key, nonces, session and + * partial signature), not yet written: the function that returns it writes its + * libsecp256k1 struct first, and returns an error instead where libsecp256k1 writes none. + * + * @tparam Opaque The type, whose default constructor is private. + * @return The unwritten object. + */ + template + [[nodiscard]] static Opaque make_opaque() noexcept { + return Opaque(); + } + + /** + * What a module header's opaque type wraps, its private member `native_value_`: the + * libsecp256k1 struct, or for a secret nonce the struct and what crypto keeps beside it. + * + * @tparam Opaque The type, `const` for a read. + * @param object The object. + * @return Its member, `const` when the object is. + */ + template + [[nodiscard]] static auto& native(Opaque& object) noexcept { + return object.native_value_; + } }; // NOLINTBEGIN(bugprone-signed-bitwise): libsecp256k1's macros shift a signed constant diff --git a/include/webcpp/crypto/curves/secp256k1/musig.hpp b/include/webcpp/crypto/curves/secp256k1/musig.hpp new file mode 100644 index 00000000..ea54c052 --- /dev/null +++ b/include/webcpp/crypto/curves/secp256k1/musig.hpp @@ -0,0 +1,728 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + secp256k1's MuSig2 on libsecp256k1 (BIP 327): many signers' keys aggregated into one x-only + key, and their two rounds, nonces then partial signatures, into one BIP 340 signature under it. + A secret nonce is consumed by the partial signature it makes. + + @see "MuSig2: many signers, one signature", in the guide's secp256k1 chapter. +*/ +#ifndef WEBCPP_CRYPTO_CURVES_SECP256K1_MUSIG_HPP +#define WEBCPP_CRYPTO_CURVES_SECP256K1_MUSIG_HPP + +#include + +#include +#include +#include +#include +#include // lint-world: the nonce's session randomness + +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** + * What a MuSig2 secret nonce holds: libsecp256k1's secret nonce first, then the compressed key + * of the key pair it was made for, and whether it may still sign. + */ +struct secp256k1_nonce_state { + /** libsecp256k1's secret nonce: its magic, two secret scalars and the signer's point. */ + secp256k1_musig_secnonce nonce_value{}; + /** The signer's public key, SEC1 compressed, public. */ + std::array signer_key{}; + /** True from `nonce_gen` until a partial signature, a move or the destructor uses it. */ + bool fresh = false; +}; + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::curves::secp256k1::musig { + +/** The size of a signer's public nonce: two compressed points. */ +inline constexpr std::size_t public_nonce_size = 66; + +/** The size of an aggregate nonce: two compressed points, each 33 zero bytes at infinity. */ +inline constexpr std::size_t aggregate_nonce_size = 66; + +/** The size of a partial signature: a scalar below the group order. */ +inline constexpr std::size_t partial_signature_size = 32; + +/** + * The signers' aggregate key and what signing needs of it (libsecp256k1's keyagg cache), with + * the tweaks a protocol applies to it: public data, copied freely, made only by + * `key_aggregate`. + */ +class aggregate_key { +public: + /** + * The BIP 340 x-only key the final signature verifies under. + * + * @return 32 bytes, the tweaks included. + */ + [[nodiscard]] std::array xonly_public_key() const noexcept { + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + public_key full_key = full_public_key(); + secp256k1_xonly_pubkey xonly_key{}; + std::array output_bytes{}; + // A valid point always has an x-only form: libsecp256k1 returns 1. + static_cast(secp256k1_xonly_pubkey_from_pubkey( + secp256k1_context_static, &xonly_key, nullptr, + &webcpp::crypto::detail::secp256k1_access::point(full_key))); + static_cast(secp256k1_xonly_pubkey_serialize(secp256k1_context_static, + output_bytes.data(), &xonly_key)); + return output_bytes; + } + + /** + * The aggregate as a full point (`secp256k1_musig_pubkey_get`), which a plain tweak acts on. + * + * @return The key, the tweaks included. + */ + [[nodiscard]] public_key full_public_key() const noexcept { + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + public_key full_key = access::make_public_key(); + // The cache is valid, made by key_aggregate: libsecp256k1 returns 1. The status is named + // and dropped, since GCC's warn_unused_result does not yield to a cast to void. + int const get_status = secp256k1_musig_pubkey_get(secp256k1_context_static, + &access::point(full_key), &native_value_); + static_cast(get_status); + return full_key; + } + + /** + * Adds t times G as a plain tweak (BIP 327's ApplyTweak, is_xonly false, + * `secp256k1_musig_pubkey_ec_tweak_add`). + * + * @param tweak_bytes The 32-byte tweak t, a big-endian scalar. + * @return Nothing; `invalid_secret_key` for a tweak not below the group order or a result + * at infinity, after which the key is unchanged. + */ + [[nodiscard]] boost::system::result tweak_add( + std::span tweak_bytes) noexcept { + return tweaked(tweak_bytes, secp256k1_musig_pubkey_ec_tweak_add); + } + + /** + * Adds t times G as an x-only tweak (BIP 327's ApplyTweak, is_xonly true, + * `secp256k1_musig_pubkey_xonly_tweak_add`), as Taproot tweaks an output key. + * + * @param tweak_bytes The 32-byte tweak t, a big-endian scalar. + * @return Nothing; `invalid_secret_key` for a tweak not below the group order or a result + * at infinity, after which the key is unchanged. + */ + [[nodiscard]] boost::system::result tweak_xonly_add( + std::span tweak_bytes) noexcept { + return tweaked(tweak_bytes, secp256k1_musig_pubkey_xonly_tweak_add); + } + +private: + friend struct webcpp::crypto::detail::secp256k1_access; + + aggregate_key() noexcept = default; + + /** + * The cache tweaked by libsecp256k1, which leaves it as it was when it refuses. + * + * @param tweak_bytes The 32-byte tweak. + * @param tweak_function libsecp256k1's plain or x-only tweak. + * @return Nothing; `invalid_secret_key`. + */ + [[nodiscard]] boost::system::result tweaked( + std::span tweak_bytes, + int (*tweak_function)(secp256k1_context const*, secp256k1_pubkey*, + secp256k1_musig_keyagg_cache*, unsigned char const*)) noexcept { + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + if (tweak_function(secp256k1_context_static, nullptr, &native_value_, tweak_bytes.data()) == + 0) { + return error::invalid_secret_key; + } + return {}; + } + + secp256k1_musig_keyagg_cache native_value_{}; +}; + +/** + * A signer's public nonce, parsed (libsecp256k1's pubnonce): public, copied freely, made only + * by `nonce_gen` and `parse_public_nonce`. + */ +class public_nonce { +private: + friend struct webcpp::crypto::detail::secp256k1_access; + + public_nonce() noexcept = default; + + secp256k1_musig_pubnonce native_value_{}; +}; + +/** + * The sum of the signers' public nonces, parsed (libsecp256k1's aggnonce): public, copied + * freely, made only by `nonce_aggregate` and `parse_aggregate_nonce`. + */ +class aggregate_nonce { +private: + friend struct webcpp::crypto::detail::secp256k1_access; + + aggregate_nonce() noexcept = default; + + secp256k1_musig_aggnonce native_value_{}; +}; + +/** + * The session of one message (libsecp256k1's session): the final nonce and the challenge, public, + * copied freely, made only by `nonce_process`. + */ +class session { +private: + friend struct webcpp::crypto::detail::secp256k1_access; + + session() noexcept = default; + + secp256k1_musig_session native_value_{}; +}; + +/** + * One signer's partial signature, parsed (libsecp256k1's partial_sig): public, copied freely, + * made only by `partial_sign` and `parse_partial_signature`. + */ +class partial_signature { +private: + friend struct webcpp::crypto::detail::secp256k1_access; + + partial_signature() noexcept = default; + + secp256k1_musig_partial_sig native_value_{}; +}; + +/** + * A signer's secret nonce: move-only, wiped on move and destruction, made only by `nonce_gen`. + * + * It is consumed by `partial_sign`, which takes it by value, so that a nonce cannot be passed to a + * second signature without an explicit `std::move` of an object already moved from (which + * `partial_sign` refuses with `invalid_state`). Reusing a nonce in two signatures reveals the + * secret key. + */ +class secret_nonce { +public: + /** + * Moves the nonce; the source is wiped and signs nothing. + * + * @param moved_source The source, empty afterwards. + */ + secret_nonce(secret_nonce&& moved_source) noexcept : native_value_(moved_source.native_value_) { + moved_source.release(); + } + + /** + * Moves over this nonce, which is wiped first. + * + * @param moved_source The source, empty afterwards. + * @return This nonce. + */ + secret_nonce& operator=(secret_nonce&& moved_source) noexcept { + if (this != &moved_source) { + release(); + native_value_ = moved_source.native_value_; + moved_source.release(); + } + return *this; + } + + /** Not copyable: a copy could sign a second message, which reveals the secret key. */ + secret_nonce(secret_nonce const&) = delete; + /** Not copyable: a copy could sign a second message, which reveals the secret key. */ + secret_nonce& operator=(secret_nonce const&) = delete; + + /** Wipes the nonce. */ + ~secret_nonce() { release(); } + +private: + friend struct webcpp::crypto::detail::secp256k1_access; + + secret_nonce() noexcept = default; + + void release() noexcept { webcpp::crypto::detail::wipe_object(native_value_); } + + webcpp::crypto::detail::secp256k1_nonce_state native_value_{}; +}; + +/** What `nonce_gen` returns: the secret nonce to keep, the public nonce to send. */ +struct nonce_pair { + /** The secret nonce, which this signer's `partial_sign` consumes. */ + secret_nonce secret_part; + /** The public nonce, sent to every other signer. */ + public_nonce public_part; +}; + +/** + * The workspace `key_aggregate`, `nonce_aggregate` and `partial_signature_aggregate` need for + * `count` items, in bytes. + * + * @param count The number of keys, nonces or partial signatures. + * @return One array of `count` pointers and one `alignof(std::max_align_t)` of padding. + */ +[[nodiscard]] constexpr std::size_t workspace_size(std::size_t count) noexcept { + return (count * sizeof(void const*)) + alignof(std::max_align_t); +} + +/** + * Aggregates the signers' keys in the order given (`secp256k1_musig_pubkey_agg`). + * + * Tip: sort the keys first (`std::ranges::sort`: `public_key`'s order is BIP 327's KeySort) + * where the protocol does, so that every signer computes the same key. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param signer_keys The signers' keys, at least one. + * @param pointer_space At least `workspace_size(signer_keys.size())` bytes; zero when the + * function returns, whatever it returns. + * @return The aggregate key; `invalid_input_size` for no keys or a short workspace; + * `backend_failure`. + */ +template +[[nodiscard]] boost::system::result key_aggregate( + std::span signer_keys, workspace pointer_space) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + // The carver first: it wipes the workspace on every return, a refusal's included. + webcpp::crypto::detail::secp256k1_workspace carver(pointer_space); + // libsecp256k1 checks the count with ARG_CHECK, whose callback aborts: refused first here. + if (signer_keys.empty() || pointer_space.size() < workspace_size(signer_keys.size())) { + return error::invalid_input_size; + } + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + auto* const key_pointers = carver.take(signer_keys.size()); + if (key_pointers == nullptr) { + return error::invalid_input_size; + } + for (std::size_t key_index = 0; key_index < signer_keys.size(); ++key_index) { + key_pointers[key_index] = &access::point(signer_keys[key_index]); + } + auto aggregated_key = access::make_opaque(); + if (secp256k1_musig_pubkey_agg(secp256k1_context_static, nullptr, + &access::native(aggregated_key), key_pointers, + signer_keys.size()) == 0) { + return error::backend_failure; + } + return aggregated_key; +} + +/** + * A fresh nonce for one signature (`secp256k1_musig_nonce_gen`), its 32 bytes of session + * randomness drawn inside from crypto's random device, with the key pair's secret, its public + * key and the aggregate key. + * + * Tip: make the nonce when the signature is to be made, and keep it nowhere else: a nonce + * survives no restart of the program, which is what keeps it from being used twice. + * + * @tparam Backend The key pair's backend, `backends::secp256k1`. + * @param signer The signer's key pair, whose context makes the nonce. + * @param signers_key The aggregate key, with its tweaks. + * @param message_hash The 32-byte message, when it is known already, or empty. + * @param extra_input 32 bytes more to mix in, or empty. + * @return The pair; `invalid_state` moved from; `invalid_input_size` for a message or an + * extra input that is neither empty nor 32 bytes; `entropy_unavailable`; `backend_failure`. + */ +template +[[nodiscard]] boost::system::result nonce_gen( + basic_keypair const& signer, aggregate_key const& signers_key, + std::span message_hash = {}, + std::span extra_input = {}) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + using access = webcpp::crypto::detail::secp256k1_access; + if (!access::keyed(signer)) { + return error::invalid_state; + } + if ((!message_hash.empty() && message_hash.size() != 32) || + (!extra_input.empty() && extra_input.size() != 32)) { + return error::invalid_input_size; + } + // libsecp256k1 zeroes the randomness itself once it is used; the secret wipes it again. + webcpp::crypto::detail::secp256k1_secret session_randomness; + auto const drawn = + random_device().fill(session_randomness.bytes); // lint-world: the nonce's randomness + if (!drawn) { + return webcpp::crypto::detail::secp256k1_seed_error(drawn.error()); + } + webcpp::crypto::detail::secp256k1_secret secret_bytes; + secp256k1_keypair_sec(access::context(signer), secret_bytes.bytes.data(), + &access::pair(signer)); + secp256k1_pubkey signer_point{}; + secp256k1_keypair_pub(access::context(signer), &signer_point, &access::pair(signer)); + auto made_secret = access::make_opaque(); + auto made_public = access::make_opaque(); + auto& state = access::native(made_secret); + if (secp256k1_musig_nonce_gen( + access::context(signer), &state.nonce_value, &access::native(made_public), + session_randomness.bytes.data(), secret_bytes.bytes.data(), &signer_point, + message_hash.empty() ? nullptr : message_hash.data(), &access::native(signers_key), + extra_input.empty() ? nullptr : extra_input.data()) == 0) { + return error::backend_failure; + } + std::size_t written_size = state.signer_key.size(); + secp256k1_ec_pubkey_serialize(secp256k1_context_static, state.signer_key.data(), &written_size, + &signer_point, webcpp::crypto::detail::secp256k1_compressed); + state.fresh = true; + return nonce_pair{.secret_part = std::move(made_secret), .public_part = made_public}; +} + +/** + * Sums the signers' public nonces (`secp256k1_musig_nonce_agg`), as one of them or a + * coordinator does once every public nonce is in. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param signer_nonces Every signer's public nonce, at least one. + * @param pointer_space At least `workspace_size(signer_nonces.size())` bytes; zero when the + * function returns, whatever it returns. + * @return The aggregate nonce; `invalid_input_size` for no nonces or a short workspace; + * `backend_failure`. + */ +template +[[nodiscard]] boost::system::result nonce_aggregate( + std::span signer_nonces, workspace pointer_space) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + // The carver first: it wipes the workspace on every return, a refusal's included. + webcpp::crypto::detail::secp256k1_workspace carver(pointer_space); + // libsecp256k1 checks the count with ARG_CHECK, whose callback aborts: refused first here. + if (signer_nonces.empty() || pointer_space.size() < workspace_size(signer_nonces.size())) { + return error::invalid_input_size; + } + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + auto* const nonce_pointers = carver.take(signer_nonces.size()); + if (nonce_pointers == nullptr) { + return error::invalid_input_size; + } + for (std::size_t nonce_index = 0; nonce_index < signer_nonces.size(); ++nonce_index) { + nonce_pointers[nonce_index] = &access::native(signer_nonces[nonce_index]); + } + auto nonce_sum = access::make_opaque(); + if (secp256k1_musig_nonce_agg(secp256k1_context_static, &access::native(nonce_sum), + nonce_pointers, signer_nonces.size()) == 0) { + return error::backend_failure; + } + return nonce_sum; +} + +/** + * The session of one message (`secp256k1_musig_nonce_process`): the final nonce and the + * challenge every signer signs. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param nonce_sum The aggregate nonce. + * @param message_bytes The 32-byte message, as libsecp256k1 signs. + * @param signers_key The aggregate key, with its tweaks. + * @return The session; `backend_failure`. + */ +template +[[nodiscard]] boost::system::result nonce_process( + aggregate_nonce const& nonce_sum, std::span message_bytes, + aggregate_key const& signers_key) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + auto signing_session = access::make_opaque(); + if (secp256k1_musig_nonce_process(secp256k1_context_static, &access::native(signing_session), + &access::native(nonce_sum), message_bytes.data(), + &access::native(signers_key)) == 0) { + return error::backend_failure; + } + return signing_session; +} + +/** + * This signer's partial signature (`secp256k1_musig_partial_sign`), consuming the nonce: it is + * taken by value, wiped by the call and destroyed at its end. + * + * @tparam Backend The key pair's backend, `backends::secp256k1`. + * @param signer The signer's key pair. + * @param signer_nonce The nonce `nonce_gen` made for this key pair, moved in. + * @param signers_key The aggregate key, with its tweaks. + * @param signing_session The session of the message. + * @return The partial signature; `invalid_state` for a moved-from key pair or nonce, a nonce + * already used, or a nonce made for another key pair; `backend_failure`. + */ +template +[[nodiscard]] boost::system::result partial_sign( + basic_keypair const& signer, secret_nonce signer_nonce, + aggregate_key const& signers_key, session const& signing_session) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + using access = webcpp::crypto::detail::secp256k1_access; + auto& state = access::native(signer_nonce); + // libsecp256k1 checks a used nonce and the signer's key with ARG_CHECK, whose callback + // aborts: refused first here. + if (!access::keyed(signer) || !state.fresh) { + return error::invalid_state; + } + secp256k1_pubkey signer_point{}; + secp256k1_keypair_pub(access::context(signer), &signer_point, &access::pair(signer)); + std::array signer_key{}; + std::size_t written_size = signer_key.size(); + secp256k1_ec_pubkey_serialize(secp256k1_context_static, signer_key.data(), &written_size, + &signer_point, webcpp::crypto::detail::secp256k1_compressed); + if (signer_key != state.signer_key) { + return error::invalid_state; + } + state.fresh = false; + auto signature_part = access::make_opaque(); + if (secp256k1_musig_partial_sign(access::context(signer), &access::native(signature_part), + &state.nonce_value, &access::pair(signer), + &access::native(signers_key), + &access::native(signing_session)) == 0) { + return error::backend_failure; + } + return signature_part; +} + +/** + * Verifies one signer's partial signature (`secp256k1_musig_partial_sig_verify`), which tells + * a dishonest or faulty signer apart before the signature is aggregated. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param signature_part The signer's partial signature. + * @param signer_nonce The signer's public nonce. + * @param signer_key The signer's public key. + * @param signers_key The aggregate key, with its tweaks. + * @param signing_session The session of the message. + * @return Nothing; `invalid_signature` when it does not verify. + */ +template +[[nodiscard]] boost::system::result partial_signature_verify( + partial_signature const& signature_part, public_nonce const& signer_nonce, + public_key const& signer_key, aggregate_key const& signers_key, + session const& signing_session) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + if (secp256k1_musig_partial_sig_verify( + secp256k1_context_static, &access::native(signature_part), + &access::native(signer_nonce), &access::point(signer_key), &access::native(signers_key), + &access::native(signing_session)) == 0) { + return error::invalid_signature; + } + return {}; +} + +/** + * The BIP 340 signature of the partial signatures (`secp256k1_musig_partial_sig_agg`), which + * `verify_schnorr` checks under `aggregate_key::xonly_public_key()`. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param signing_session The session of the message. + * @param signature_parts Every signer's partial signature, at least one. + * @param pointer_space At least `workspace_size(signature_parts.size())` bytes; zero when the + * function returns, whatever it returns. + * @return 64 bytes; `invalid_input_size` for no partial signatures or a short workspace; + * `backend_failure`. + */ +template +[[nodiscard]] boost::system::result> partial_signature_aggregate( + session const& signing_session, std::span signature_parts, + workspace pointer_space) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + // The carver first: it wipes the workspace on every return, a refusal's included. + webcpp::crypto::detail::secp256k1_workspace carver(pointer_space); + // libsecp256k1 checks the count with ARG_CHECK, whose callback aborts: refused first here. + if (signature_parts.empty() || pointer_space.size() < workspace_size(signature_parts.size())) { + return error::invalid_input_size; + } + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + auto* const part_pointers = + carver.take(signature_parts.size()); + if (part_pointers == nullptr) { + return error::invalid_input_size; + } + for (std::size_t part_index = 0; part_index < signature_parts.size(); ++part_index) { + part_pointers[part_index] = &access::native(signature_parts[part_index]); + } + std::array output_bytes{}; + if (secp256k1_musig_partial_sig_agg(secp256k1_context_static, output_bytes.data(), + &access::native(signing_session), part_pointers, + signature_parts.size()) == 0) { + return error::backend_failure; + } + return output_bytes; +} + +/** + * Parses a signer's public nonce (`secp256k1_musig_pubnonce_parse`): two compressed points. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param encoded_nonce The 66 bytes. + * @return The nonce; `invalid_input_size` for another length; `invalid_point` for a half that + * is not a point. + */ +template +[[nodiscard]] boost::system::result parse_public_nonce( + std::span encoded_nonce) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + if (encoded_nonce.size() != public_nonce_size) { + return error::invalid_input_size; + } + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + auto parsed_nonce = access::make_opaque(); + if (secp256k1_musig_pubnonce_parse(secp256k1_context_static, &access::native(parsed_nonce), + encoded_nonce.data()) == 0) { + return error::invalid_point; + } + return parsed_nonce; +} + +/** + * Serialises a signer's public nonce (`secp256k1_musig_pubnonce_serialize`). + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param parsed_nonce The nonce. + * @return The 66 bytes, two compressed points. + */ +template +[[nodiscard]] std::array serialize_public_nonce( + public_nonce const& parsed_nonce) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + std::array output_bytes{}; + // A parsed or made nonce always serialises: libsecp256k1 returns 1. + static_cast(secp256k1_musig_pubnonce_serialize( + secp256k1_context_static, output_bytes.data(), + &webcpp::crypto::detail::secp256k1_access::native(parsed_nonce))); + return output_bytes; +} + +/** + * Parses an aggregate nonce (`secp256k1_musig_aggnonce_parse`): two compressed points, either + * of which may be the point at infinity, written as 33 zero bytes. + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param encoded_nonce The 66 bytes. + * @return The nonce; `invalid_input_size` for another length; `invalid_point` for a half that + * is neither a point nor 33 zero bytes. + */ +template +[[nodiscard]] boost::system::result parse_aggregate_nonce( + std::span encoded_nonce) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + if (encoded_nonce.size() != aggregate_nonce_size) { + return error::invalid_input_size; + } + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + auto parsed_nonce = access::make_opaque(); + if (secp256k1_musig_aggnonce_parse(secp256k1_context_static, &access::native(parsed_nonce), + encoded_nonce.data()) == 0) { + return error::invalid_point; + } + return parsed_nonce; +} + +/** + * Serialises an aggregate nonce (`secp256k1_musig_aggnonce_serialize`). + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param parsed_nonce The nonce. + * @return The 66 bytes, a point at infinity as 33 zero bytes. + */ +template +[[nodiscard]] std::array serialize_aggregate_nonce( + aggregate_nonce const& parsed_nonce) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + std::array output_bytes{}; + // A parsed or summed nonce always serialises: libsecp256k1 returns 1. + static_cast(secp256k1_musig_aggnonce_serialize( + secp256k1_context_static, output_bytes.data(), + &webcpp::crypto::detail::secp256k1_access::native(parsed_nonce))); + return output_bytes; +} + +/** + * Parses a partial signature (`secp256k1_musig_partial_sig_parse`). + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param encoded_signature The 32 bytes. + * @return The partial signature; `invalid_input_size` for another length; `invalid_signature` + * for a scalar not below the group order. + */ +template +[[nodiscard]] boost::system::result parse_partial_signature( + std::span encoded_signature) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + if (encoded_signature.size() != partial_signature_size) { + return error::invalid_input_size; + } + secp256k1_selftest(); + using access = webcpp::crypto::detail::secp256k1_access; + auto parsed_signature = access::make_opaque(); + if (secp256k1_musig_partial_sig_parse(secp256k1_context_static, + &access::native(parsed_signature), + encoded_signature.data()) == 0) { + return error::invalid_signature; + } + return parsed_signature; +} + +/** + * Serialises a partial signature (`secp256k1_musig_partial_sig_serialize`). + * + * @tparam Backend The backend, `backends::secp256k1`. + * @param parsed_signature The partial signature. + * @return The 32 bytes. + */ +template +[[nodiscard]] std::array serialize_partial_signature( + partial_signature const& parsed_signature) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + secp256k1_selftest(); + std::array output_bytes{}; + // A parsed or made partial signature always serialises: libsecp256k1 returns 1. + static_cast(secp256k1_musig_partial_sig_serialize( + secp256k1_context_static, output_bytes.data(), + &webcpp::crypto::detail::secp256k1_access::native(parsed_signature))); + return output_bytes; +} + +} // namespace webcpp::crypto::curves::secp256k1::musig + +#endif // WEBCPP_CRYPTO_CURVES_SECP256K1_MUSIG_HPP diff --git a/test/Jamfile b/test/Jamfile index 03327969..da674f64 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -67,7 +67,7 @@ webcpp.headers-alone crypto : ../include webcpp.headers-alone crypto : ../include : crypto/curves/secp256k1.hpp crypto/backends/secp256k1.hpp crypto/curves/secp256k1/tweak.hpp crypto/curves/secp256k1/formats.hpp - crypto/curves/secp256k1/ellswift.hpp + crypto/curves/secp256k1/ellswift.hpp crypto/curves/secp256k1/musig.hpp : /third_party//secp256k1 ; # config.hpp defines WEBCPP_CRYPTO_NO_EXCEPTIONS exactly when webcpp has no @@ -236,6 +236,15 @@ crypto-run secp256k1_formats_openssl : secp256k1_formats_test.cpp # over seeded key pairs, and the key exchange from both sides. crypto-run secp256k1_ellswift : secp256k1_ellswift_test.cpp : /third_party//secp256k1 /third_party//bips ; +# MuSig2 against BIP 327's vectors, 2-of-2 and 3-of-3 round trips, and a +# secret nonce that signs once. +crypto-run secp256k1_musig : secp256k1_musig_test.cpp + : /third_party//secp256k1 /third_party//bips + /webcpp//boost_json ; +# MuSig2's nonce with the system's source failing: a program of its own, since +# the test seam is a whole-program define. +crypto-run secp256k1_musig_entropy : secp256k1_musig_entropy_test.cpp + : /third_party//secp256k1 WEBCPP_CRYPTO_DETAIL_TEST_ENTROPY ; crypto-run secp256k1_der : secp256k1_der_test.cpp : /third_party//secp256k1 /third_party//wycheproof /webcpp//boost_json ; diff --git a/test/crypto_secp256k1_test.cpp b/test/crypto_secp256k1_test.cpp index 0d698520..7cba0720 100644 --- a/test/crypto_secp256k1_test.cpp +++ b/test/crypto_secp256k1_test.cpp @@ -6,8 +6,8 @@ // in a program that links libsecp256k1 brings secp256k1's header: its // branch for WEBCPP_CRYPTO_HAS_SECP256K1 compiles, and the key pair, both verifications, the -// tweaks of tweak.hpp, the formats of formats.hpp and the ElligatorSwift of ellswift.hpp are -// declared through it alone. +// tweaks of tweak.hpp, the formats of formats.hpp, the ElligatorSwift of ellswift.hpp and the +// MuSig2 of musig.hpp are declared through it alone. #include @@ -28,6 +28,8 @@ static_assert(std::is_function_v)>); static_assert(std::is_function_v)>); static_assert(std::is_function_v)>); static_assert(std::is_function_v)>); +static_assert(std::is_function_v)>); +static_assert(std::is_function_v)>); int main() { return 0; diff --git a/test/messages/Jamfile b/test/messages/Jamfile index bac047be..5aea7dda 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -42,3 +42,4 @@ build-project chacha_header_not_included ; build-project chacha_unknown_backend ; build-project ed25519_unknown_policy ; build-project secret_of_no_bytes ; +build-project musig_nonce_copied ; diff --git a/test/messages/musig_nonce_copied/Jamfile b/test/messages/musig_nonce_copied/Jamfile new file mode 100644 index 00000000..85350ce5 --- /dev/null +++ b/test/messages/musig_nonce_copied/Jamfile @@ -0,0 +1,12 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +webcpp.compile-diagnostic musig_nonce_copied : musig_nonce_copied.cpp + : /third_party//secp256k1 : native wasip2 ; diff --git a/test/messages/musig_nonce_copied/musig_nonce_copied.cpp b/test/messages/musig_nonce_copied/musig_nonce_copied.cpp new file mode 100644 index 00000000..5bd6da55 --- /dev/null +++ b/test/messages/musig_nonce_copied/musig_nonce_copied.cpp @@ -0,0 +1,40 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A MuSig2 secret nonce passed to partial_sign without std::move: its copy constructor is +// deleted, so a nonce cannot be kept and signed with a second time. A second std::move of the +// same object compiles; partial_sign refuses that one at run time with invalid_state. + +#include +#include + +#include +#include +#include +#include + +int main() { + namespace secp = webcpp::crypto::curves::secp256k1; + namespace musig = webcpp::crypto::curves::secp256k1::musig; + std::array secret_bytes{}; + secret_bytes.fill(0x11); + auto const signer = secp::keypair::make(secret_bytes); + auto const signer_key = secp::parse_public_key(*signer->public_key()); + std::array const keys{*signer_key}; + std::vector space(musig::workspace_size(keys.size())); + auto const key = musig::key_aggregate(keys, space); + auto made = musig::nonce_gen(*signer, *key); + std::array const nonces{made->public_part}; + auto const sum = musig::nonce_aggregate(nonces, space); + auto const signing_session = musig::nonce_process(*sum, secret_bytes, *key); + musig::secret_nonce& kept = made->secret_part; + // expected-error@+1 {{call to deleted constructor of}} + auto const part = musig::partial_sign(*signer, kept, *key, *signing_session); + // clang-format off + // expected-note@webcpp/crypto/curves/secp256k1/musig.hpp:* {{'secret_nonce' has been explicitly marked deleted here}} + // clang-format on + return part ? 0 : 1; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index 8616808b..30f0b1da 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -60,3 +60,4 @@ build-project chacha_header_not_included ; build-project chacha_unknown_backend ; build-project ed25519_unknown_policy ; build-project secret_of_no_bytes ; +build-project musig_nonce_copied ; diff --git a/test/msvc/musig_nonce_copied/Jamfile b/test/msvc/musig_nonce_copied/Jamfile new file mode 100644 index 00000000..f2457992 --- /dev/null +++ b/test/msvc/musig_nonce_copied/Jamfile @@ -0,0 +1,10 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail musig_nonce_copied : app.cpp + : /webcpp/crypto//crypto /third_party//secp256k1 : native ; diff --git a/test/msvc/musig_nonce_copied/app.cpp b/test/msvc/musig_nonce_copied/app.cpp new file mode 100644 index 00000000..b7262cd7 --- /dev/null +++ b/test/msvc/musig_nonce_copied/app.cpp @@ -0,0 +1,35 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A MuSig2 secret nonce passed to partial_sign without std::move: its copy constructor is +// deleted, so on MSVC the compile fails. The text is checked on clang, in +// test/messages/musig_nonce_copied. +#include +#include + +#include +#include +#include +#include + +int main() { + namespace secp = webcpp::crypto::curves::secp256k1; + namespace musig = webcpp::crypto::curves::secp256k1::musig; + std::array secret_bytes{}; + secret_bytes.fill(0x11); + auto const signer = secp::keypair::make(secret_bytes); + auto const signer_key = secp::parse_public_key(*signer->public_key()); + std::array const keys{*signer_key}; + std::vector space(musig::workspace_size(keys.size())); + auto const key = musig::key_aggregate(keys, space); + auto made = musig::nonce_gen(*signer, *key); + std::array const nonces{made->public_part}; + auto const sum = musig::nonce_aggregate(nonces, space); + auto const signing_session = musig::nonce_process(*sum, secret_bytes, *key); + musig::secret_nonce& kept = made->secret_part; + auto const part = musig::partial_sign(*signer, kept, *key, *signing_session); + return part ? 0 : 1; +} diff --git a/test/secp256k1_allocation_test.cpp b/test/secp256k1_allocation_test.cpp index 206c6868..1542e80c 100644 --- a/test/secp256k1_allocation_test.cpp +++ b/test/secp256k1_allocation_test.cpp @@ -10,14 +10,15 @@ // program count it; the signatures (hedged and recoverable too), the three forms of ECDH, the // public keys in both forms, both verifications, the parsed public key, recovery, the DER and // low-S functions, the x-only tweak, the tweaks, negations and combination of tweak.hpp, the -// SPKI and PKCS#8 encoders and decoders of formats.hpp and the ElligatorSwift functions of -// ellswift.hpp allocate nothing, each counted alone +// SPKI and PKCS#8 encoders and decoders of formats.hpp, the ElligatorSwift functions of +// ellswift.hpp and the MuSig2 functions of musig.hpp allocate nothing, each counted alone // (decode_pkcs8's key pair takes its one block from the resource it is given); the destructor // gives the block back; a refused make allocates nothing. A control proves the counter moves. #include #include #include +#include #include #include @@ -30,6 +31,7 @@ #include #include #include +#include #include #include @@ -183,6 +185,90 @@ int main() { none("ellswift_xdh", [&] { return secp::ellswift_xdh(key, noise, noise, secp::ellswift_party::initiator); }); + + // musig.hpp: one signer's two rounds, its workspace on the stack, each step alone. + namespace musig = secp::musig; + // The key pair was tweaked above: its key now, not the one parsed before. + auto const signer_key = secp::parse_public_key(*key.public_key()); + if (!BOOST_TEST(signer_key.has_value())) { + return webcpp::test::exit_status(boost::report_errors()); + } + std::array const signer_keys{*signer_key}; + alignas(std::max_align_t) std::array musig_space{}; + std::optional signers_key; + none("key_aggregate", [&] { + auto r = musig::key_aggregate(signer_keys, musig_space); + if (r) { + signers_key.emplace(*r); + } + return r; + }); + if (!BOOST_TEST(signers_key.has_value())) { + return webcpp::test::exit_status(boost::report_errors()); + } + none("aggregate_key::xonly_public_key", + [&] { return signers_key->xonly_public_key() != std::array{}; }); + none("aggregate_key::full_public_key", + [&] { return signers_key->full_public_key() == signers_key->full_public_key(); }); + none("aggregate_key::tweak_add", [&] { return signers_key->tweak_add(message); }); + none("aggregate_key::tweak_xonly_add", + [&] { return signers_key->tweak_xonly_add(message); }); + // The tweaks stay in the aggregate key, whose cache the session reads; the signer's key + // pair signs as it is. + std::optional nonces; + none("nonce_gen", [&] { + auto r = musig::nonce_gen(key, *signers_key, message); + if (r) { + nonces.emplace(std::move(*r)); + } + return r.has_value(); + }); + if (!BOOST_TEST(nonces.has_value())) { + return webcpp::test::exit_status(boost::report_errors()); + } + std::array const public_nonces{nonces->public_part}; + std::optional nonce_sum; + none("nonce_aggregate", [&] { + auto r = musig::nonce_aggregate(public_nonces, musig_space); + if (r) { + nonce_sum.emplace(*r); + } + return r; + }); + std::optional signing_session; + none("nonce_process", [&] { + auto r = musig::nonce_process(*nonce_sum, message, *signers_key); + if (r) { + signing_session.emplace(*r); + } + return r; + }); + std::optional part; + none("partial_sign", [&] { + auto r = musig::partial_sign(key, std::move(nonces->secret_part), *signers_key, + *signing_session); + if (r) { + part.emplace(*r); + } + return r; + }); + none("partial_signature_verify", [&] { + return musig::partial_signature_verify(*part, public_nonces[0], *signer_key, + *signers_key, *signing_session); + }); + std::array const parts{*part}; + none("partial_signature_aggregate", [&] { + return musig::partial_signature_aggregate(*signing_session, parts, musig_space); + }); + none("serialize_public_nonce, parse_public_nonce", [&] { + return musig::parse_public_nonce(musig::serialize_public_nonce(public_nonces[0])); + }); + none("serialize_aggregate_nonce, parse_aggregate_nonce", [&] { + return musig::parse_aggregate_nonce(musig::serialize_aggregate_nonce(*nonce_sum)); + }); + none("serialize_partial_signature, parse_partial_signature", [&] { + return musig::parse_partial_signature(musig::serialize_partial_signature(*part)); + }); BOOST_TEST_EQ(resource.allocated, 1U); BOOST_TEST_EQ(resource.deallocated, 0U); diff --git a/test/secp256k1_musig_entropy_test.cpp b/test/secp256k1_musig_entropy_test.cpp new file mode 100644 index 00000000..00bbcb0f --- /dev/null +++ b/test/secp256k1_musig_entropy_test.cpp @@ -0,0 +1,90 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// MuSig2's nonce with the system's source failing (the test seam +// WEBCPP_CRYPTO_DETAIL_TEST_ENTROPY, a whole-program define, hence a program of its own): the +// planted source answers the key pairs' context seeds, which keypair::make draws from the same +// source, then fails; nonce_gen returns entropy_unavailable, without aborting, after drawing +// exactly once and calling nothing after the failure. That the buffer the draw wrote is zero +// on that failure is random_device::fill's contract, tested by random_device_failing; the wipe +// after a successful draw is detail::secp256k1_secret's destructor's. + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the planted source's script +int answer_after = 0; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the planted source's tally +std::size_t calls = 0; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the source's next answers +std::uint8_t next_byte = 1; + +} // namespace + +extern "C" int webcpp_test_entropy(void* output_bytes, std::size_t byte_count) { + ++calls; + // As getentropy does: 0 when it fills, -1 with errno set when it fails. + if (answer_after == 0) { + errno = EIO; + return -1; + } + --answer_after; + std::memset(output_bytes, next_byte++, byte_count); + return 0; +} + +int main() { + namespace crypto = webcpp::crypto; + namespace secp = webcpp::crypto::curves::secp256k1; + namespace musig = webcpp::crypto::curves::secp256k1::musig; + + // The two key pairs' context seeds, then the aggregate key, which draws nothing. + answer_after = 2; + std::array first_secret{}; + first_secret.fill(0x11); + std::array second_secret{}; + second_secret.fill(0x22); + auto const first = secp::keypair::make(first_secret); + auto const second = secp::keypair::make(second_secret); + if (!BOOST_TEST(first && second)) { + return webcpp::test::exit_status(boost::report_errors()); + } + BOOST_TEST_EQ(calls, 2U); + auto const first_key = secp::parse_public_key(*first->public_key()); + auto const second_key = secp::parse_public_key(*second->public_key()); + std::array const keys{*first_key, *second_key}; + std::vector space(musig::workspace_size(keys.size())); + auto const key = musig::key_aggregate(keys, space); + if (!BOOST_TEST(key.has_value())) { + return webcpp::test::exit_status(boost::report_errors()); + } + BOOST_TEST_EQ(calls, 2U); + + // The source fails now: the nonce's session randomness is not drawn, and nothing is made. + auto const refused = musig::nonce_gen(*first, *key); + BOOST_TEST(!refused && refused.error() == crypto::error::entropy_unavailable); + BOOST_TEST_EQ(calls, 3U); + + // With the source answering again, the nonce is drawn once. + answer_after = 1; + auto const made = musig::nonce_gen(*second, *key); + BOOST_TEST(made.has_value()); + BOOST_TEST_EQ(calls, 4U); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/secp256k1_musig_test.cpp b/test/secp256k1_musig_test.cpp new file mode 100644 index 00000000..795b0712 --- /dev/null +++ b/test/secp256k1_musig_test.cpp @@ -0,0 +1,781 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// secp256k1's MuSig2 against BIP 327's vectors (bip-0327/vectors/*.json). key_sort: sorting the +// six parsed keys with public_key's order gives sorted_pubkeys. key_agg: the 4 valid cases' +// x-only keys; its error cases, three keys parse_public_key refuses and two tweaks the aggregate +// key refuses, after which the key is unchanged. nonce_agg: the 2 valid sums (the second at +// infinity, written as 33 zero bytes) and 3 nonces parse_public_nonce refuses. sign_verify: the +// 4 valid cases whose message is 32 bytes verify their partial signature (the empty and the +// 38-byte message are counted as skipped: libsecp256k1 signs 32-byte messages); the 3 +// verify_fail cases, over the aggregate of their nonces, do not; the verify_error and sign_error +// cases that need no secret nonce of the vector's are refused at parsing (a sign_error case that +// needs one is counted as skipped). tweak: the 5 valid cases verify after their tweaks, the +// error case's tweak is refused. sig_agg: the 4 valid cases give the vector's signature, which +// verify_schnorr accepts under the aggregate key, and a partial signature not below the group +// order is refused. The vectors' secret nonces (sign_verify's and tweak's secnonces, +// det_sign_vectors.json, nonce_gen_vectors.json) are not reachable through crypto's interface +// by design: a secret_nonce exists only from nonce_gen, with fresh randomness; libsecp256k1's +// own tests run them in the c-suites lane. Round trips: 2-of-2 and 3-of-3 over seeded key pairs +// and messages, plain and with an x-only tweak, each partial signature verified, the aggregate +// verified with verify_schnorr, and a partial signature changed in one bit refused. The nonce: +// consumed by partial_sign, refused when used again or given to another key pair. The refusals +// of a moved-from key pair, of sizes and of workspaces; every workspace is zero afterwards. + +#include +#include +#include +#include + +#include "support/hex.hpp" +#include "support/secp256k1_checks.hpp" +#include "support/test_data.hpp" + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace secp = webcpp::crypto::curves::secp256k1; +namespace musig = webcpp::crypto::curves::secp256k1::musig; +namespace test = webcpp::test; +namespace json = boost::json; + +namespace { + +using bytes = std::vector; +using scalar = std::array; + +// Each type libsecp256k1 checks the magic of is made only by the functions that return one. +static_assert(!std::is_default_constructible_v); +static_assert(!std::is_default_constructible_v); +static_assert(!std::is_default_constructible_v); +static_assert(!std::is_default_constructible_v); +static_assert(!std::is_default_constructible_v); +static_assert(!std::is_default_constructible_v); +// The public forms are copied freely; the secret nonce is moved, never copied. +static_assert(std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(musig::public_nonce_size == 66); +static_assert(musig::aggregate_nonce_size == 66); +static_assert(musig::partial_signature_size == 32); +static_assert(musig::workspace_size(3) == (3 * sizeof(void const*)) + alignof(std::max_align_t)); + +std::string str(json::value const& v) { + return std::string(std::string_view(v.as_string())); +} + +bytes hex(json::value const& v) { + return test::from_hex(str(v)); +} + +template +std::array fixed(json::value const& v) { + auto const b = hex(v); + std::array out{}; + if (BOOST_TEST_EQ(b.size(), N)) { + std::ranges::copy(b, out.begin()); + } + return out; +} + +json::value document(char const* name) { + auto const text = test::read_file(std::string(WEBCPP_TEST_BIPS "/bip-0327/vectors/") + name); + boost::system::error_code ec; + auto doc = json::parse(text, ec); + if (ec) { + BOOST_ERROR(name); + std::exit(boost::report_errors()); + } + return doc; +} + +std::size_t index_at(json::array const& indices, std::size_t at) { + return static_cast(indices.at(at).as_int64()); +} + +// A workspace on the heap, filled with non-zero bytes, so that its wipe is seen. +std::vector lent(std::size_t count) { + return std::vector(musig::workspace_size(count), std::byte{0xa5}); +} + +bool all_zero(std::span space) { + return std::ranges::all_of(space, [](std::byte b) { return b == std::byte{0}; }); +} + +secp::public_key parsed_key(json::value const& v) { + auto const parsed = secp::parse_public_key(hex(v)); + if (!BOOST_TEST(parsed.has_value())) { + std::exit(boost::report_errors()); + } + return *parsed; +} + +// The keys at `indices` of `keys`, parsed. +std::vector keys_at(json::array const& keys, json::array const& indices) { + std::vector out; + for (auto const& i : indices) { + out.push_back(parsed_key(keys.at(static_cast(i.as_int64())))); + } + return out; +} + +musig::aggregate_key aggregated(std::span keys) { + auto space = lent(keys.size()); + auto made = musig::key_aggregate(keys, space); + BOOST_TEST(all_zero(space)); + if (!BOOST_TEST(made.has_value())) { + std::exit(boost::report_errors()); + } + return *made; +} + +musig::public_nonce parsed_nonce(json::value const& v) { + auto const parsed = musig::parse_public_nonce(hex(v)); + if (!BOOST_TEST(parsed.has_value())) { + std::exit(boost::report_errors()); + } + return *parsed; +} + +musig::aggregate_nonce parsed_aggregate(json::value const& v) { + auto const parsed = musig::parse_aggregate_nonce(hex(v)); + if (!BOOST_TEST(parsed.has_value())) { + std::exit(boost::report_errors()); + } + return *parsed; +} + +musig::partial_signature parsed_signature(json::value const& v) { + auto const parsed = musig::parse_partial_signature(hex(v)); + if (!BOOST_TEST(parsed.has_value())) { + std::exit(boost::report_errors()); + } + return *parsed; +} + +musig::session session_of(musig::aggregate_nonce const& nonce_sum, scalar const& message, + musig::aggregate_key const& key) { + auto made = musig::nonce_process(nonce_sum, message, key); + if (!BOOST_TEST(made.has_value())) { + std::exit(boost::report_errors()); + } + return *made; +} + +// Applies a case's tweaks to `key` in order: x-only or plain, as `is_xonly` says. +boost::system::result tweaked(musig::aggregate_key& key, json::array const& tweaks, + json::array const& tweak_indices, json::array const& is_xonly) { + for (std::size_t i = 0; i < tweak_indices.size(); ++i) { + auto const tweak = fixed<32>(tweaks.at(index_at(tweak_indices, i))); + auto const done = + is_xonly.at(i).as_bool() ? key.tweak_xonly_add(tweak) : key.tweak_add(tweak); + if (!done) { + return done; + } + } + return {}; +} + +void key_sort() { + auto const doc = document("key_sort_vectors.json"); + std::vector keys; + for (auto const& k : doc.at("pubkeys").as_array()) { + keys.push_back(parsed_key(k)); + } + std::ranges::sort(keys); + auto const& sorted = doc.at("sorted_pubkeys").as_array(); + if (!BOOST_TEST_EQ(keys.size(), sorted.size())) { + return; + } + for (std::size_t i = 0; i < keys.size(); ++i) { + BOOST_TEST(std::ranges::equal(secp::serialize_public_key(keys[i]), hex(sorted.at(i)))); + } + std::cout << "key_sort: keys=" << keys.size() << '\n'; +} + +void key_agg() { + auto const doc = document("key_agg_vectors.json"); + auto const& keys = doc.at("pubkeys").as_array(); + auto const& tweaks = doc.at("tweaks").as_array(); + int valid = 0; + for (auto const& c : doc.at("valid_test_cases").as_array()) { + auto const signers = keys_at(keys, c.at("key_indices").as_array()); + auto const key = aggregated(signers); + valid += static_cast( + BOOST_TEST(std::ranges::equal(key.xonly_public_key(), hex(c.at("expected"))))); + } + int refused = 0; + for (auto const& c : doc.at("error_test_cases").as_array()) { + auto const& indices = c.at("key_indices").as_array(); + auto const& error = c.at("error").as_object(); + if (error.at("type").as_string() == "invalid_contribution") { + // The signer's key does not parse. + auto const bad = + index_at(indices, static_cast(error.at("signer").as_int64())); + refused += + static_cast(BOOST_TEST(secp::parse_public_key(hex(keys.at(bad))).error() == + crypto::error::invalid_public_key)); + continue; + } + // A tweak not below the group order, or one that gives the point at infinity: refused, + // and the key is as it was. + auto key = aggregated(keys_at(keys, indices)); + auto const& tweak_indices = c.at("tweak_indices").as_array(); + auto const& is_xonly = c.at("is_xonly").as_array(); + auto const before = key.xonly_public_key(); + auto const done = tweaked(key, tweaks, tweak_indices, is_xonly); + refused += static_cast(BOOST_TEST(done.error() == crypto::error::invalid_secret_key)); + BOOST_TEST(key.xonly_public_key() == before); + } + std::cout << "key_agg: valid=" << valid << " refused=" << refused << '\n'; + BOOST_TEST_EQ(valid, 4); + BOOST_TEST_EQ(refused, 5); +} + +void nonce_agg() { + auto const doc = document("nonce_agg_vectors.json"); + auto const& nonces = doc.at("pnonces").as_array(); + int valid = 0; + for (auto const& c : doc.at("valid_test_cases").as_array()) { + std::vector signer_nonces; + for (auto const& i : c.at("pnonce_indices").as_array()) { + signer_nonces.push_back( + parsed_nonce(nonces.at(static_cast(i.as_int64())))); + // Each nonce is written back as it was read. + BOOST_TEST(std::ranges::equal(musig::serialize_public_nonce(signer_nonces.back()), + hex(nonces.at(static_cast(i.as_int64()))))); + } + auto space = lent(signer_nonces.size()); + auto const sum = musig::nonce_aggregate(signer_nonces, space); + BOOST_TEST(all_zero(space)); + if (BOOST_TEST(sum.has_value())) { + auto const written = musig::serialize_aggregate_nonce(*sum); + valid += + static_cast(BOOST_TEST(std::ranges::equal(written, hex(c.at("expected"))))); + // And the sum, parsed back, is written the same: the point at infinity included. + auto const again = musig::parse_aggregate_nonce(written); + BOOST_TEST(again && musig::serialize_aggregate_nonce(*again) == written); + } + } + int refused = 0; + for (auto const& c : doc.at("error_test_cases").as_array()) { + auto const& indices = c.at("pnonce_indices").as_array(); + auto const bad = + index_at(indices, static_cast(c.at("error").at("signer").as_int64())); + refused += + static_cast(BOOST_TEST(musig::parse_public_nonce(hex(nonces.at(bad))).error() == + crypto::error::invalid_point)); + } + std::cout << "nonce_agg: valid=" << valid << " refused=" << refused << '\n'; + BOOST_TEST_EQ(valid, 2); + BOOST_TEST_EQ(refused, 3); +} + +void sign_verify() { + auto const doc = document("sign_verify_vectors.json"); + auto const& keys = doc.at("pubkeys").as_array(); + auto const& nonces = doc.at("pnonces").as_array(); + auto const& sums = doc.at("aggnonces").as_array(); + auto const& messages = doc.at("msgs").as_array(); + int verified = 0; + int skipped = 0; + for (auto const& c : doc.at("valid_test_cases").as_array()) { + auto const message = + hex(messages.at(static_cast(c.at("msg_index").as_int64()))); + if (message.size() != 32) { + ++skipped; + continue; + } + auto const signers = keys_at(keys, c.at("key_indices").as_array()); + auto const key = aggregated(signers); + auto const sum = + parsed_aggregate(sums.at(static_cast(c.at("aggnonce_index").as_int64()))); + scalar message32{}; + std::ranges::copy(message, message32.begin()); + auto const signing_session = session_of(sum, message32, key); + auto const signer = static_cast(c.at("signer_index").as_int64()); + auto const signer_nonce = + parsed_nonce(nonces.at(index_at(c.at("nonce_indices").as_array(), signer))); + auto const part = parsed_signature(c.at("expected")); + BOOST_TEST(musig::serialize_partial_signature(part) == fixed<32>(c.at("expected"))); + verified += static_cast( + BOOST_TEST(musig::partial_signature_verify(part, signer_nonce, signers[signer], key, + signing_session) + .has_value())); + } + // verify_fail: the cases carry no aggregate nonce; the session's is the sum of their nonces. + int failed = 0; + for (auto const& c : doc.at("verify_fail_test_cases").as_array()) { + auto const parsed = musig::parse_partial_signature(hex(c.at("sig"))); + if (!parsed) { + // A partial signature not below the group order. + failed += + static_cast(BOOST_TEST(parsed.error() == crypto::error::invalid_signature)); + continue; + } + auto const signers = keys_at(keys, c.at("key_indices").as_array()); + auto const key = aggregated(signers); + std::vector signer_nonces; + for (auto const& i : c.at("nonce_indices").as_array()) { + signer_nonces.push_back( + parsed_nonce(nonces.at(static_cast(i.as_int64())))); + } + auto space = lent(signer_nonces.size()); + auto const sum = musig::nonce_aggregate(signer_nonces, space); + if (!BOOST_TEST(sum.has_value())) { + continue; + } + auto const message32 = + fixed<32>(messages.at(static_cast(c.at("msg_index").as_int64()))); + auto const signing_session = session_of(*sum, message32, key); + auto const signer = static_cast(c.at("signer_index").as_int64()); + failed += static_cast( + BOOST_TEST(musig::partial_signature_verify(*parsed, signer_nonces[signer], + signers[signer], key, signing_session) + .error() == crypto::error::invalid_signature)); + } + // verify_error: a nonce or a key that does not parse. + int refused = 0; + for (auto const& c : doc.at("verify_error_test_cases").as_array()) { + auto const& error = c.at("error").as_object(); + auto const signer = static_cast(error.at("signer").as_int64()); + if (error.at("contrib").as_string() == "pubnonce") { + auto const bad = index_at(c.at("nonce_indices").as_array(), signer); + refused += static_cast( + BOOST_TEST(musig::parse_public_nonce(hex(nonces.at(bad))).error() == + crypto::error::invalid_point)); + } else { + auto const bad = index_at(c.at("key_indices").as_array(), signer); + refused += + static_cast(BOOST_TEST(secp::parse_public_key(hex(keys.at(bad))).error() == + crypto::error::invalid_public_key)); + } + } + // sign_error: the cases that need no secret nonce of the vector's are refused at parsing. + int sign_refused = 0; + int sign_skipped = 0; + for (auto const& c : doc.at("sign_error_test_cases").as_array()) { + auto const& error = c.at("error").as_object(); + if (error.at("type").as_string() != "invalid_contribution") { + ++sign_skipped; + continue; + } + if (error.at("contrib").as_string() == "aggnonce") { + auto const bad = static_cast(c.at("aggnonce_index").as_int64()); + sign_refused += static_cast( + BOOST_TEST(musig::parse_aggregate_nonce(hex(sums.at(bad))).error() == + crypto::error::invalid_point)); + } else { + auto const bad = index_at(c.at("key_indices").as_array(), + static_cast(error.at("signer").as_int64())); + sign_refused += + static_cast(BOOST_TEST(secp::parse_public_key(hex(keys.at(bad))).error() == + crypto::error::invalid_public_key)); + } + } + std::cout << "sign_verify: verified=" << verified << " skipped=" << skipped + << " verify_fail=" << failed << " verify_error=" << refused + << " sign_error=" << sign_refused << " sign_error_skipped=" << sign_skipped << '\n'; + BOOST_TEST_EQ(verified, 4); + BOOST_TEST_EQ(skipped, 2); + BOOST_TEST_EQ(failed, 3); + BOOST_TEST_EQ(refused, 2); + BOOST_TEST_EQ(sign_refused, 4); + BOOST_TEST_EQ(sign_skipped, 2); +} + +void tweak() { + auto const doc = document("tweak_vectors.json"); + auto const& keys = doc.at("pubkeys").as_array(); + auto const& nonces = doc.at("pnonces").as_array(); + auto const& tweaks = doc.at("tweaks").as_array(); + auto const sum = parsed_aggregate(doc.at("aggnonce")); + auto const message = fixed<32>(doc.at("msg")); + int verified = 0; + for (auto const& c : doc.at("valid_test_cases").as_array()) { + auto const signers = keys_at(keys, c.at("key_indices").as_array()); + auto key = aggregated(signers); + if (!BOOST_TEST( + tweaked(key, tweaks, c.at("tweak_indices").as_array(), c.at("is_xonly").as_array()) + .has_value())) { + continue; + } + auto const signing_session = session_of(sum, message, key); + auto const signer = static_cast(c.at("signer_index").as_int64()); + auto const signer_nonce = + parsed_nonce(nonces.at(index_at(c.at("nonce_indices").as_array(), signer))); + verified += static_cast(BOOST_TEST( + musig::partial_signature_verify(parsed_signature(c.at("expected")), signer_nonce, + signers[signer], key, signing_session) + .has_value())); + } + int refused = 0; + for (auto const& c : doc.at("error_test_cases").as_array()) { + auto key = aggregated(keys_at(keys, c.at("key_indices").as_array())); + auto const before = key.full_public_key(); + auto const done = + tweaked(key, tweaks, c.at("tweak_indices").as_array(), c.at("is_xonly").as_array()); + refused += static_cast(BOOST_TEST(done.error() == crypto::error::invalid_secret_key)); + BOOST_TEST(key.full_public_key() == before); + } + std::cout << "tweak: verified=" << verified << " refused=" << refused << '\n'; + BOOST_TEST_EQ(verified, 5); + BOOST_TEST_EQ(refused, 1); +} + +void sig_agg() { + auto const doc = document("sig_agg_vectors.json"); + auto const& keys = doc.at("pubkeys").as_array(); + auto const& tweaks = doc.at("tweaks").as_array(); + auto const& parts = doc.at("psigs").as_array(); + auto const message = fixed<32>(doc.at("msg")); + int aggregated_count = 0; + for (auto const& c : doc.at("valid_test_cases").as_array()) { + auto key = aggregated(keys_at(keys, c.at("key_indices").as_array())); + if (!BOOST_TEST( + tweaked(key, tweaks, c.at("tweak_indices").as_array(), c.at("is_xonly").as_array()) + .has_value())) { + continue; + } + auto const signing_session = session_of(parsed_aggregate(c.at("aggnonce")), message, key); + std::vector signature_parts; + for (auto const& i : c.at("psig_indices").as_array()) { + signature_parts.push_back( + parsed_signature(parts.at(static_cast(i.as_int64())))); + } + auto space = lent(signature_parts.size()); + auto const signature = + musig::partial_signature_aggregate(signing_session, signature_parts, space); + BOOST_TEST(all_zero(space)); + if (!BOOST_TEST(signature.has_value())) { + continue; + } + BOOST_TEST(std::ranges::equal(*signature, hex(c.at("expected")))); + aggregated_count += static_cast(BOOST_TEST( + secp::verify_schnorr(*signature, message, key.xonly_public_key()).has_value())); + } + int refused = 0; + for (auto const& c : doc.at("error_test_cases").as_array()) { + auto const& indices = c.at("psig_indices").as_array(); + auto const bad = + index_at(indices, static_cast(c.at("error").at("signer").as_int64())); + refused += static_cast( + BOOST_TEST(musig::parse_partial_signature(hex(parts.at(bad))).error() == + crypto::error::invalid_signature)); + } + std::cout << "sig_agg: aggregated=" << aggregated_count << " refused=" << refused << '\n'; + BOOST_TEST_EQ(aggregated_count, 4); + BOOST_TEST_EQ(refused, 1); +} + +scalar draw(std::mt19937_64& generator) { + for (;;) { + scalar out{}; + for (auto& octet : out) { + octet = static_cast(generator()); + } + if (secp256k1_ec_seckey_verify(secp256k1_context_static, out.data()) == 1) { + return out; + } + } +} + +secp::keypair keypair_of(std::span secret_bytes) { + auto made = secp::keypair::make(secret_bytes); + if (!BOOST_TEST(made.has_value())) { + std::exit(boost::report_errors()); + } + return std::move(*made); +} + +secp::public_key public_of(secp::keypair const& key) { + auto const encoded = key.public_key(); + auto const parsed = secp::parse_public_key(*encoded); + if (!BOOST_TEST(parsed.has_value())) { + std::exit(boost::report_errors()); + } + return *parsed; +} + +// One signature of `signer_count` seeded signers, its keys sorted, plain or with an x-only +// tweak: two rounds, every partial signature verified, the aggregate checked as BIP 340's. +void round_trip(std::mt19937_64& generator, std::size_t signer_count, bool with_tweak) { + std::vector signers; + std::vector keys; + for (std::size_t i = 0; i < signer_count; ++i) { + signers.push_back(keypair_of(draw(generator))); + keys.push_back(public_of(signers.back())); + } + // The signers' order is BIP 327's KeySort; each signer finds its own key's place again. + std::vector order(signer_count); + for (std::size_t i = 0; i < signer_count; ++i) { + order[i] = i; + } + std::ranges::sort(order, [&](std::size_t a, std::size_t b) { return keys[a] < keys[b]; }); + std::vector sorted; + for (auto const i : order) { + sorted.push_back(keys[i]); + } + auto key = aggregated(sorted); + if (with_tweak) { + BOOST_TEST(key.tweak_xonly_add(draw(generator)).has_value()); + } + auto const message = draw(generator); + + // Round one: each signer's nonce, the public halves summed. + std::vector secrets; + std::vector publics; + for (auto const i : order) { + auto made = musig::nonce_gen(signers[i], key, message); + if (!BOOST_TEST(made.has_value())) { + return; + } + secrets.push_back(std::move(made->secret_part)); + publics.push_back(made->public_part); + } + auto nonce_space = lent(signer_count); + auto const sum = musig::nonce_aggregate(publics, nonce_space); + BOOST_TEST(all_zero(nonce_space)); + if (!BOOST_TEST(sum.has_value())) { + return; + } + auto const signing_session = session_of(*sum, message, key); + + // Round two: each signer's partial signature, verified by any of them. + std::vector parts; + for (std::size_t k = 0; k < signer_count; ++k) { + auto part = + musig::partial_sign(signers[order[k]], std::move(secrets[k]), key, signing_session); + if (!BOOST_TEST(part.has_value())) { + return; + } + BOOST_TEST( + musig::partial_signature_verify(*part, publics[k], sorted[k], key, signing_session) + .has_value()); + // The same partial signature changed in one bit does not verify. + auto changed = musig::serialize_partial_signature(*part); + changed[31] ^= 0x01U; + auto const reparsed = musig::parse_partial_signature(changed); + if (BOOST_TEST(reparsed.has_value())) { + BOOST_TEST(musig::partial_signature_verify(*reparsed, publics[k], sorted[k], key, + signing_session) + .error() == crypto::error::invalid_signature); + } + parts.push_back(*part); + } + auto signature_space = lent(signer_count); + auto const signature = + musig::partial_signature_aggregate(signing_session, parts, signature_space); + BOOST_TEST(all_zero(signature_space)); + if (BOOST_TEST(signature.has_value())) { + BOOST_TEST(secp::verify_schnorr(*signature, message, key.xonly_public_key()).has_value()); + auto other_message = message; + other_message[0] ^= 0x01U; + BOOST_TEST( + secp::verify_schnorr(*signature, other_message, key.xonly_public_key()).error() == + crypto::error::invalid_signature); + } +} + +void round_trips() { + std::mt19937_64 generator(0x3a5195ULL); + for (int round = 0; round < 16; ++round) { + round_trip(generator, 2, false); + round_trip(generator, 3, false); + round_trip(generator, 2, true); + round_trip(generator, 3, true); + } +} + +void nonce_rules() { + std::mt19937_64 generator(0x90ceULL); + auto const alice = keypair_of(draw(generator)); + auto const bob = keypair_of(draw(generator)); + std::array const keys{public_of(alice), public_of(bob)}; + auto const key = aggregated(keys); + auto const message = draw(generator); + + auto alice_nonce = musig::nonce_gen(alice, key, message, message); + auto bob_nonce = musig::nonce_gen(bob, key); + if (!BOOST_TEST(alice_nonce && bob_nonce)) { + return; + } + std::array const publics{alice_nonce->public_part, + bob_nonce->public_part}; + auto space = lent(2); + auto const sum = musig::nonce_aggregate(publics, space); + if (!BOOST_TEST(sum.has_value())) { + return; + } + auto const signing_session = session_of(*sum, message, key); + + // A nonce made by one key pair, given to another: refused before libsecp256k1 sees it. + BOOST_TEST(musig::partial_sign(bob, std::move(alice_nonce->secret_part), key, signing_session) + .error() == crypto::error::invalid_state); + + // A nonce signs once: the second use of the same object, moved again, is refused, and the + // program does not abort (libsecp256k1's own check of a used nonce is an ARG_CHECK). + auto nonce = std::move(bob_nonce->secret_part); + BOOST_TEST(musig::partial_sign(bob, std::move(nonce), key, signing_session).has_value()); + // NOLINTNEXTLINE(bugprone-use-after-move): the second use of a consumed nonce is what is tested + BOOST_TEST(musig::partial_sign(bob, std::move(nonce), key, signing_session).error() == + crypto::error::invalid_state); + + // A moved-from key pair: refused by nonce_gen and by partial_sign. + auto source = keypair_of(draw(generator)); + auto fresh = musig::nonce_gen(source, key); + auto const target = std::move(source); + BOOST_TEST(target.public_key().has_value()); + // NOLINTBEGIN(bugprone-use-after-move): the moved-from pair is what is tested + BOOST_TEST(musig::nonce_gen(source, key).error() == crypto::error::invalid_state); + if (BOOST_TEST(fresh.has_value())) { + BOOST_TEST(musig::partial_sign(source, std::move(fresh->secret_part), key, signing_session) + .error() == crypto::error::invalid_state); + } + test::expect_empty_keypair(source); + // NOLINTEND(bugprone-use-after-move) + + // A message hash or extra input of 31 bytes. + std::array const short_input{}; + BOOST_TEST(musig::nonce_gen(alice, key, short_input).error() == + crypto::error::invalid_input_size); + BOOST_TEST(musig::nonce_gen(alice, key, message, short_input).error() == + crypto::error::invalid_input_size); + BOOST_TEST(musig::nonce_gen(alice, key, {}, message).has_value()); +} + +void refusals() { + std::mt19937_64 generator(0x7e7ULL); + auto const alice = keypair_of(draw(generator)); + std::array const keys{public_of(alice), + public_of(keypair_of(draw(generator)))}; + auto const key = aggregated(keys); + auto const nonce = musig::nonce_gen(alice, key); + if (!BOOST_TEST(nonce.has_value())) { + return; + } + std::array const publics{nonce->public_part, nonce->public_part}; + + // No keys, nonces or partial signatures: invalid_input_size, the workspace zero afterwards. + auto space = lent(2); + BOOST_TEST(musig::key_aggregate({}, space).error() == crypto::error::invalid_input_size); + BOOST_TEST(all_zero(space)); + std::ranges::fill(space, std::byte{0xa5}); + BOOST_TEST(musig::nonce_aggregate({}, space).error() == crypto::error::invalid_input_size); + BOOST_TEST(all_zero(space)); + auto const sum = musig::nonce_aggregate(publics, space); + if (!BOOST_TEST(sum.has_value())) { + return; + } + auto const signing_session = session_of(*sum, draw(generator), key); + std::ranges::fill(space, std::byte{0xa5}); + BOOST_TEST(musig::partial_signature_aggregate(signing_session, {}, space).error() == + crypto::error::invalid_input_size); + BOOST_TEST(all_zero(space)); + + // A workspace one byte short, and none: refused, the workspace zero afterwards. + auto const short_space = [&] { + std::ranges::fill(space, std::byte{0xa5}); + return std::span(space).first(space.size() - 1); + }; + BOOST_TEST(musig::key_aggregate(keys, short_space()).error() == + crypto::error::invalid_input_size); + BOOST_TEST(all_zero(std::span(space).first(space.size() - 1))); + BOOST_TEST(musig::nonce_aggregate(publics, short_space()).error() == + crypto::error::invalid_input_size); + BOOST_TEST(all_zero(std::span(space).first(space.size() - 1))); + auto const part = musig::parse_partial_signature(scalar{}); + if (BOOST_TEST(part.has_value())) { + std::array const parts{*part, *part}; + BOOST_TEST( + musig::partial_signature_aggregate(signing_session, parts, short_space()).error() == + crypto::error::invalid_input_size); + BOOST_TEST(all_zero(std::span(space).first(space.size() - 1))); + BOOST_TEST(musig::partial_signature_aggregate(signing_session, parts, {}).error() == + crypto::error::invalid_input_size); + } + BOOST_TEST(musig::key_aggregate(keys, {}).error() == crypto::error::invalid_input_size); + BOOST_TEST(musig::nonce_aggregate(publics, {}).error() == crypto::error::invalid_input_size); + + // Encodings of the wrong size. + std::array const nonce_65{}; + std::array const signature_31{}; + BOOST_TEST(musig::parse_public_nonce(nonce_65).error() == crypto::error::invalid_input_size); + BOOST_TEST(musig::parse_aggregate_nonce(nonce_65).error() == crypto::error::invalid_input_size); + BOOST_TEST(musig::parse_partial_signature(signature_31).error() == + crypto::error::invalid_input_size); + // A public nonce of the point at infinity, which only an aggregate nonce may hold. + std::array const zero_nonce{}; + BOOST_TEST(musig::parse_public_nonce(zero_nonce).error() == crypto::error::invalid_point); + BOOST_TEST(musig::parse_aggregate_nonce(zero_nonce).has_value()); +} + +// The aggregate key's full point and x-only form agree, a plain tweak acts on the full point, +// and the tweaks match tweak.hpp's on the same point. +void aggregate_key_forms() { + std::mt19937_64 generator(0xa66ULL); + std::array const keys{public_of(keypair_of(draw(generator))), + public_of(keypair_of(draw(generator)))}; + auto key = aggregated(keys); + auto const full = secp::serialize_public_key(key.full_public_key()); + BOOST_TEST(std::ranges::equal(std::span(full).subspan(1), key.xonly_public_key())); + scalar tweak_bytes{}; + tweak_bytes[31] = 7; + auto const before = key.full_public_key(); + BOOST_TEST(key.tweak_add(tweak_bytes).has_value()); + secp256k1_pubkey expected{}; + auto const encoded = secp::serialize_public_key(before); + BOOST_TEST(secp256k1_ec_pubkey_parse(secp256k1_context_static, &expected, encoded.data(), + encoded.size()) == 1); + BOOST_TEST(secp256k1_ec_pubkey_tweak_add(secp256k1_context_static, &expected, + tweak_bytes.data()) == 1); + std::array expected_bytes{}; + std::size_t written = expected_bytes.size(); + secp256k1_ec_pubkey_serialize(secp256k1_context_static, expected_bytes.data(), &written, + &expected, SECP256K1_EC_COMPRESSED); + BOOST_TEST(secp::serialize_public_key(key.full_public_key()) == expected_bytes); +} + +} // namespace + +int main() { + key_sort(); + key_agg(); + nonce_agg(); + sign_verify(); + tweak(); + sig_agg(); + round_trips(); + nonce_rules(); + refusals(); + aggregate_key_forms(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/support/secp256k1_checks.hpp b/test/support/secp256k1_checks.hpp index cd4dffd4..6bbd6f5f 100644 --- a/test/support/secp256k1_checks.hpp +++ b/test/support/secp256k1_checks.hpp @@ -13,15 +13,59 @@ #include #include #include +#include #include #include #include +#include #include +#include namespace webcpp::test { +/** + * MuSig2's two functions of a signer's key pair answer `invalid_state` for an empty pair: a + * nonce for it, and a partial signature by it with a nonce of a live pair's. + * + * @param key The empty pair. + * @param live A keyed pair, the one signer of the aggregate key. + * @param message The 32-byte message of the session. + */ +inline void expect_empty_musig_signer(webcpp::crypto::curves::secp256k1::keypair const& key, + webcpp::crypto::curves::secp256k1::keypair const& live, + std::array const& message) { + namespace secp = webcpp::crypto::curves::secp256k1; + auto const live_key = secp::parse_public_key(*live.public_key()); + if (!BOOST_TEST(live_key.has_value())) { + return; + } + std::array const keys{*live_key}; + std::array space{}; + auto const signers_key = secp::musig::key_aggregate(keys, space); + if (!BOOST_TEST(signers_key.has_value())) { + return; + } + BOOST_TEST(secp::musig::nonce_gen(key, *signers_key).error() == + webcpp::crypto::error::invalid_state); + auto made = secp::musig::nonce_gen(live, *signers_key); + if (!BOOST_TEST(made.has_value())) { + return; + } + std::array const nonces{made->public_part}; + auto const nonce_sum = secp::musig::nonce_aggregate(nonces, space); + if (!BOOST_TEST(nonce_sum.has_value())) { + return; + } + auto const signing_session = secp::musig::nonce_process(*nonce_sum, message, *signers_key); + if (BOOST_TEST(signing_session.has_value())) { + BOOST_TEST(secp::musig::partial_sign(key, std::move(made->secret_part), *signers_key, + *signing_session) + .error() == webcpp::crypto::error::invalid_state); + } +} + /** * Every operation of a key pair that holds no key answers `invalid_state`: the pair is empty, * as the source of a move is and as a pair is that a tweak refused. @@ -58,6 +102,7 @@ inline void expect_empty_keypair(webcpp::crypto::curves::secp256k1::keypair& key BOOST_TEST(key.ecdh(peer).error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.ecdh_x(peer).error() == webcpp::crypto::error::invalid_state); BOOST_TEST(key.ecdh_point(peer).error() == webcpp::crypto::error::invalid_state); + expect_empty_musig_signer(key, *live, message); } } diff --git a/test/windows_h_after_test.cpp b/test/windows_h_after_test.cpp index cd896ce9..feddd0ca 100644 --- a/test/windows_h_after_test.cpp +++ b/test/windows_h_after_test.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include diff --git a/test/windows_h_before_test.cpp b/test/windows_h_before_test.cpp index b908a461..e9030b99 100644 --- a/test/windows_h_before_test.cpp +++ b/test/windows_h_before_test.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include diff --git a/test/wipe_objects_test.cpp b/test/wipe_objects_test.cpp index 0aa98a1f..749370e1 100644 --- a/test/wipe_objects_test.cpp +++ b/test/wipe_objects_test.cpp @@ -12,7 +12,8 @@ // (the Jamfile's speed), where a store the optimiser may drop is the case. // // One source, one backend per program: WEBCPP_TEST_WIPE_BEARSSL, WEBCPP_TEST_WIPE_CTAES, -// WEBCPP_TEST_WIPE_SECP256K1, WEBCPP_TEST_WIPE_OPENSSL or WEBCPP_TEST_WIPE_SODIUM. +// WEBCPP_TEST_WIPE_SECP256K1 (the key pair, and MuSig2's secret nonce), +// WEBCPP_TEST_WIPE_OPENSSL or WEBCPP_TEST_WIPE_SODIUM. #include @@ -26,6 +27,7 @@ #include #elif defined(WEBCPP_TEST_WIPE_SECP256K1) #include +#include #elif defined(WEBCPP_TEST_WIPE_OPENSSL) #include #include @@ -128,13 +130,13 @@ T keyed(std::uint8_t first) { } } -// The three ways a keyed object stops holding its key. +// The three ways a keyed object stops holding its key; `make` makes one from a first byte. template -void check_wiped(region where) { +void check_wiped(region where, T (*make)(std::uint8_t) = &keyed) { { // The destructor. slot storage; - placed object(storage, keyed(1)); + placed object(storage, make(1)); BOOST_TEST(any_set(storage, where)); object.destroy(); BOOST_TEST(!any_set(storage, where)); @@ -144,7 +146,7 @@ void check_wiped(region where) { // none. slot from_storage; slot to_storage; - placed from(from_storage, keyed(1)); + placed from(from_storage, make(1)); BOOST_TEST(any_set(from_storage, where)); placed to(to_storage, std::move(*from)); BOOST_TEST(!any_set(from_storage, where)); @@ -159,8 +161,8 @@ void check_wiped(region where) { // gives up first. slot from_storage; slot to_storage; - placed from(from_storage, keyed(1)); - placed to(to_storage, keyed(100)); + placed from(from_storage, make(1)); + placed to(to_storage, make(100)); BOOST_TEST(any_set(from_storage, where)); BOOST_TEST(any_set(to_storage, where)); *to = std::move(*from); @@ -189,6 +191,23 @@ constexpr region box_key{ }; #endif +#ifdef WEBCPP_TEST_WIPE_SECP256K1 +// A MuSig2 secret nonce of the key pair of `first`, its key aggregated alone. +crypto::curves::secp256k1::musig::secret_nonce nonce_of(std::uint8_t first) { + namespace secp = crypto::curves::secp256k1; + auto const signer = keyed(first); + auto const signer_key = secp::parse_public_key(*signer.public_key()); + webcpp::test::require(signer_key.has_value()); + std::array const keys{*signer_key}; + std::array space{}; + auto const key = secp::musig::key_aggregate(keys, space); + webcpp::test::require(key.has_value()); + auto made = secp::musig::nonce_gen(signer, *key); + webcpp::test::require(made.has_value()); + return std::move(made->secret_part); +} +#endif + } // namespace int main() { @@ -216,6 +235,10 @@ int main() { using type = crypto::curves::secp256k1::keypair; static_assert(sizeof(type) >= (2 * sizeof(void*)) + sizeof(secp256k1_keypair)); check_wiped({.offset = 2 * sizeof(void*), .size = sizeof(secp256k1_keypair)}); + // A MuSig2 secret nonce: libsecp256k1's secnonce comes first, its two secret scalars and the + // signer's key, zero after the destructor and in the source of a move. + check_wiped( + {.offset = 0, .size = sizeof(secp256k1_musig_secnonce)}, &nonce_of); #elif defined(WEBCPP_TEST_WIPE_OPENSSL) // OpenSSL cleanses the expanded key in EVP_CIPHER_CTX_free (its own, not webcpp's); what // webcpp holds is the pointers, which are null once the key is given up. From 93dba32a4d65ea80388454dee3d3df15c784cd7f Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 20:09:14 -0300 Subject: [PATCH 16/54] crypto: the tweak example drops its tweak and sign tags, which no page includes --- example/key_tweak.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/example/key_tweak.cpp b/example/key_tweak.cpp index 7f0b2fc1..615f76bf 100644 --- a/example/key_tweak.cpp +++ b/example/key_tweak.cpp @@ -102,7 +102,6 @@ int main() { wiped_bytes tweak; payment_tweak(chain_code.bytes, *wallet_public, 7, tweak); - // tag::tweak[] // The server: the wallet's public key plus the tweak, with no secret anywhere. auto const parsed = secp256k1::parse_public_key(*wallet_public); if (!parsed) { @@ -124,9 +123,7 @@ int main() { return 1; } std::printf("tweaked keys match\n"); - // end::tweak[] - // tag::sign[] // The device signs a spend with the payment's key pair; the server verifies under the // x-only form of the key it derived alone (the compressed key without its prefix byte). std::array const message{}; @@ -142,7 +139,6 @@ int main() { return 1; } std::printf("signature verifies under the tweaked public key\n"); - // end::sign[] return 0; } From 5a7a51e440033c9f9aeb3716a727048d133f48cc Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 20:09:35 -0300 Subject: [PATCH 17/54] crypto: the MuSig2 section names invalid_input_size for a nonce or partial signature of the wrong length --- doc/secp256k1.adoc | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index 5bfae59b..7df76e79 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -516,12 +516,13 @@ read what the other signers send, and the `serialize_` functions write it. The functions over many keys, nonces or parts take a `workspace` of `workspace_size(n)` bytes for libsecp256k1's array of pointers, so that nothing is allocated, and wipe it before they return; no items or a short workspace is -`invalid_input_size`. A nonce or a partial signature that does not parse is -`invalid_point` or `invalid_signature`, a tweak out of range -`invalid_secret_key`, and a moved-from key pair or a used nonce -`invalid_state`. The tests check BIP 327's own vectors, those that need no -secret nonce of the vector's: a `secret_nonce` exists only from `nonce_gen`, -and libsecp256k1's own tests, run in the `c-suites` lane, check the rest. +`invalid_input_size`. A nonce or a partial signature of the wrong length is +`invalid_input_size` too, and one that does not parse is `invalid_point` or +`invalid_signature`, a tweak out of range `invalid_secret_key`, and a +moved-from key pair or a used nonce `invalid_state`. The tests check BIP 327's +own vectors, those that need no secret nonce of the vector's: a `secret_nonce` +exists only from `nonce_gen`, and libsecp256k1's own tests, run in the +`c-suites` lane, check the rest. include::generated/backends-musig.adoc[] From 807d967774f6836914058ec3996fc0ab53e8232b Mon Sep 17 00:00:00 2001 From: R Date: Tue, 17 Nov 2026 20:30:58 -0300 Subject: [PATCH 18/54] crypto: silent payments on libsecp256k1, against BIP 352's vectors --- doc/changelog.adoc | 2 +- doc/curves.adoc | 4 +- doc/generated/backends-silent_payments.adoc | 30 + doc/generated/matrix.adoc | 11 + doc/generated/use-cases.adoc | 7 + doc/llms.txt | 11 + doc/secp256k1.adoc | 108 ++- doc/tables/crypto.json | 17 +- example/Jamfile | 5 + example/silent_payment.cpp | 138 ++++ example/silent_payment.expected | 3 + include/webcpp/crypto.hpp | 1 + include/webcpp/crypto/backends/secp256k1.hpp | 6 +- .../curves/secp256k1/silent_payments.hpp | 589 ++++++++++++++ test/Jamfile | 13 + test/crypto_secp256k1_test.cpp | 8 +- test/secp256k1_allocation_test.cpp | 70 +- test/secp256k1_silent_payments_test.cpp | 749 ++++++++++++++++++ test/support/bip352_vectors.c | 62 ++ test/support/bip352_vectors.h | 143 ++++ test/support/secp256k1_checks.hpp | 43 + test/windows_h_after_test.cpp | 1 + test/windows_h_before_test.cpp | 1 + 23 files changed, 2010 insertions(+), 12 deletions(-) create mode 100644 doc/generated/backends-silent_payments.adoc create mode 100644 example/silent_payment.cpp create mode 100644 example/silent_payment.expected create mode 100644 include/webcpp/crypto/curves/secp256k1/silent_payments.hpp create mode 100644 test/secp256k1_silent_payments_test.cpp create mode 100644 test/support/bip352_vectors.c create mode 100644 test/support/bip352_vectors.h diff --git a/doc/changelog.adoc b/doc/changelog.adoc index dac4925a..d7c11328 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -20,7 +20,7 @@ of every version are on webcpp's index page. * Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default, one default per family and target, and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone). -* Added curves::secp256k1: key pairs, BIP340, hedged and recoverable ECDSA, three self-wiping ECDH forms, strict DER, low-S, tweaks, negation, combination, SPKI, PKCS#8, BIP 324's ElligatorSwift and BIP 327's MuSig2. +* Added curves::secp256k1: key pairs, BIP340, hedged and recoverable ECDSA, three self-wiping ECDH forms, strict DER, low-S, tweaks, SPKI, PKCS#8, BIP 324's ElligatorSwift, BIP 327's MuSig2 and BIP 352's silent payments. * Added curves::ed25519 and curves::x25519 on libsodium: strict verification over twelve edge cases, Ed25519ph over hash's sha2_512 (/webcpp/crypto//crypto brings hash), the conversion, agree refusing all-zero secrets, RFC 8410's SPKI and PKCS#8. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::aead: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. * Added ciphers::secretbox and secretbox_xchacha20poly1305, without additional data, hybrid::box, box_xchacha20poly1305 and sealed_box (failed seals and opens zeroing data), and curves::x25519::kx_keypair (crypto_kx) on libsodium, refusing peer keys of small order. diff --git a/doc/curves.adoc b/doc/curves.adoc index 428649c4..a65672ec 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -32,7 +32,9 @@ watch-only wallets (<>); * keys sent as random-looking bytes, BIP 324's ElligatorSwift (<>); * many signers' keys and signatures aggregated into one, BIP 327's MuSig2 -(<>). +(<>); +* one reusable address whose payments look unrelated, BIP 352's silent +payments (<>). Ethereum's `v` encoding of the recovery id, the hash it signs, its transactions and its addresses are a domain library's. The second is Ed25519, diff --git a/doc/generated/backends-silent_payments.adoc b/doc/generated/backends-silent_payments.adoc new file mode 100644 index 00000000..bf6dbaeb --- /dev/null +++ b/doc/generated/backends-silent_payments.adoc @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+curves::secp256k1::silent_payments::create_outputs+`, `+create_label+`, `+create_labeled_spend_key+`, `+make_prevouts_summary+`, `+scan_outputs+`, `+send_workspace_size+`, `+summary_workspace_size+`, `+scan_workspace_size+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|libsecp256k1 +|`+/third_party//secp256k1+` +|`++` +|native, wasip2, wasip3, emscripten (tested by `+secp256k1_silent_payments+`) +|=== + +A call that names no backend takes the family's default on each target, whatever the program links, as <> gives it with its reasons and tests: + +[cols="1,1",options="header"] +|=== +|Target |Default + +|native, wasip2, wasip3, emscripten +|libsecp256k1 +|=== diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index dcc67912..795f8f4e 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -220,6 +220,11 @@ |libsecp256k1 |native, wasip2, wasip3, emscripten |`+secp256k1_musig+`, `+secp256k1_musig_entropy+` + +|`+curves::secp256k1::silent_payments::create_outputs+`, `+create_label+`, `+create_labeled_spend_key+`, `+make_prevouts_summary+`, `+scan_outputs+`, `+send_workspace_size+`, `+summary_workspace_size+`, `+scan_workspace_size+` +|libsecp256k1 +|native, wasip2, wasip3, emscripten +|`+secp256k1_silent_payments+` |=== The same, by target: the backends each operation runs on. @@ -431,4 +436,10 @@ The same, by target: the backends each operation runs on. |libsecp256k1 |libsecp256k1 |libsecp256k1 + +|`+curves::secp256k1::silent_payments::create_outputs+`, `+create_label+`, `+create_labeled_spend_key+`, `+make_prevouts_summary+`, `+scan_outputs+`, `+send_workspace_size+`, `+summary_workspace_size+`, `+scan_workspace_size+` +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 +|libsecp256k1 |=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 7b5cee53..f2ded6b4 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -106,6 +106,13 @@ `+/third_party//secp256k1+` |<> +|Publish one donation address that never shows two payments as related (BIP 352's addresses and transactions are a domain library's) +|In `+curves::secp256k1::silent_payments+`: `+create_outputs+`, `+make_prevouts_summary+`, `+scan_outputs+` +|libsecp256k1 +|`+/webcpp/crypto//crypto+` + +`+/third_party//secp256k1+` +|<> + |Require two devices to sign for a wallet, with one ordinary signature on the chain |In `+curves::secp256k1::musig+`: `+key_aggregate+`, `+nonce_gen+`, `+partial_sign+`, `+partial_signature_aggregate+` |libsecp256k1 diff --git a/doc/llms.txt b/doc/llms.txt index 85c0a786..c286390c 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -160,6 +160,15 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - serialize_aggregate_nonce: Serialises an aggregate nonce (`secp256k1_musig_aggnonce_serialize`). - parse_partial_signature: Parses a partial signature (`secp256k1_musig_partial_sig_parse`). - serialize_partial_signature: Serialises a partial signature (`secp256k1_musig_partial_sig_serialize`). +- [curves::secp256k1::silent_payments::create_outputs, create_label, create_labeled_spend_key, make_prevouts_summary, scan_outputs, send_workspace_size, summary_workspace_size, scan_workspace_size](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-silent-payments): BIP 352's silent payments: the sender's outputs to a reusable address of a scan and a spend key, the recipient's labels, and its scan of a transaction's outputs. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: publish one donation address that never shows two payments as related (BIP 352's addresses and transactions are a domain library's). + - send_workspace_size: The workspace `create_outputs` needs, in bytes. + - summary_workspace_size: The workspace `make_prevouts_summary` needs, in bytes. + - scan_workspace_size: The workspace `scan_outputs` needs, in bytes. + - create_outputs: The sender's outputs (`secp256k1_silentpayments_sender_create_outputs`): one x-only key per recipient, in the recipients' order, from the secret keys of the transaction's eligible inputs, Taproot inputs (their keys negated for an odd y, as BIP 352 says) apart from the others, and the smallest outpoint, which the caller determines. + - create_label: The `m`-th label of a scan key (`secp256k1_silentpayments_recipient_label_create`); 0 is BIP 352's change label. + - create_labeled_spend_key: The spend key of a labelled address (`..._create_labeled_spend_pubkey`). + - make_prevouts_summary: The prevouts' summary (`..._recipient_prevouts_summary_create`) from the eligible inputs' public keys. + - scan_outputs: Scans a transaction's x-only outputs (`..._recipient_scan_outputs`) with the scan key pair and the unlabelled spend key; `label_lookup` is called with a candidate label's 33 bytes and returns its tweak or `std::nullopt`, noexcept (no labels: the default). ## webcpp::crypto::hybrid @@ -245,6 +254,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Find who signed a message or a transaction without being sent their key (Ethereum's signatures)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-recovery): `keypair::sign_recoverable`, `recover` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/recover_signer.cpp. - [Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-tweaks): `seckey_tweak_add`, `pubkey_tweak_add` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/key_tweak.cpp. - [Make a peer-to-peer connection's key exchange look like random bytes (BIP 324's transport; its packets are a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ellswift): `ellswift_create`, `ellswift_decode`, `ellswift_xdh` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ellswift_handshake.cpp. +- [Publish one donation address that never shows two payments as related (BIP 352's addresses and transactions are a domain library's)](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-silent-payments): `create_outputs`, `make_prevouts_summary`, `scan_outputs` (webcpp::crypto::curves::secp256k1::silent_payments); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/silent_payment.cpp. - [Require two devices to sign for a wallet, with one ordinary signature on the chain](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-musig): `key_aggregate`, `nonce_gen`, `partial_sign`, `partial_signature_aggregate` (webcpp::crypto::curves::secp256k1::musig); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/musig_wallet.cpp. - [Make and keep a wallet's key](https://webcpporg.github.io/libs/crypto/#crypto-wallets-key): `keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest (webcpp::crypto::curves::secp256k1); backend libsecp256k1, and AES-GCM's default; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default. Example: example/wallet_key.cpp. - [Sign a Bitcoin SegWit v0 input (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-der): `sign_ecdsa`, `to_der`, `normalize_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdsa_der.cpp. @@ -290,6 +300,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/sealed_records.cpp: Seals data in pieces two ways: one message in chunks with the incremental seal, and a stream as separate records, each bound to its position and to whether it is the last. The number in the additional data stops records from being reordered or replayed at another position, and the last-record flag stops a stream from being cut short without being noticed. Each stream has a key of its own, drawn when the stream starts: the counter IVs 0, 1, 2 of one stream are safe only because no other stream seals under its key. - example/signed_message.cpp: An author signs a message with a BIP340 Schnorr signature and a reader verifies it with the author's public key alone. No server vouches for the message: any change to the text breaks the signature, so peers can trust what they receive from untrusted relays. - example/signed_update.cpp: Checks an update with the publisher's ECDSA signature before installing it. The public key is shipped inside the program, so a tampered download, or one from a mirror that is not the publisher, fails the check and is never run. +- example/silent_payment.cpp: A donation page that publishes one reusable address (BIP 352's silent payments): a pair of public keys, scan and spend. A donor's wallet with one input pays it: the output key it makes is new, tied to the donor's input. The recipient scans the transaction's outputs with its scan key pair, finds the payment, and makes the key pair that spends it with seckey_tweak_add. A second donation to the same address gives an output key unrelated to the first, so that an onlooker sees no two payments to one address. The address's encoding, the transaction and the smallest outpoint's choice are a wallet's (a domain library's); the keys are fixed here, so that the program runs the same each time, where a real wallet draws them from crypto's random device. - example/store_token.cpp: Stores a user's API token encrypted in a database row, bound to the user's id. The id is additional data: authenticated but not encrypted, so a row copied to another user's record no longer opens. Without that binding a database writer could swap the rows of two users. - example/taproot_tweak.cpp: Tweaks an internal key as Bitcoin's Taproot does for a key-path-only output (BIP341): the tweak is a tagged hash of the internal key, and the output key commits to it. The same tweak applied to the key pair lets the owner sign for the output key, so spending needs no script. - example/wallet_key.cpp: Makes a wallet's key pair from a random secret, then seals the secret at rest with AES-256-GCM and restores it. A secret that sits unencrypted on disk, or lingers in memory after use, is the first thing an attacker looks for, so the copies are wiped as soon as they are not needed. diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index 7df76e79..70d4c936 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -46,15 +46,18 @@ check signatures with a public key alone, and `recover` finds the key from a recoverable signature; `parse_public_key` and `serialize_public_key` read and write a `public_key` (<>); `to_der`, `from_der` (strict DER) and `normalize_ecdsa` convert ECDSA's DER and low-S forms; and -`tweak_xonly` tweaks an x-only public key. Four more headers hold the tweaks, +`tweak_xonly` tweaks an x-only public key. Five more headers hold the tweaks, negation and combination of whole keys (``, <>), the keys' SPKI and PKCS#8 (``, <>), ElligatorSwift, keys sent as random-looking bytes (``, -<>), and MuSig2, many signers' one signature -(``, <>). -Every function reads libsecp256k1's canary, so +<>), MuSig2, many signers' one signature +(``, <>), +and silent payments, one reusable address whose payments look unrelated +(``, +<>). Every function reads libsecp256k1's +canary, so that a program linked with another build of the library does not link. include::generated/backends-keypair.adoc[] @@ -565,3 +568,100 @@ tweaked by a tagged hash of it and a script tree's root (link:https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki[BIP 341]); that hash, and every other rule of the protocol, is a domain library's, which passes the tweak to `tweak_xonly_add`. + +[#crypto-secp256k1-silent-payments] +==== Silent payments + +A donation page, an invoice that is paid more than once, a creator's tip jar: +each wants one address to publish for good. With a plain address, every +payment to it is on the chain for anyone to list and add up. A silent payment +address is two public keys, scan and spend; every payment to it lands on a new +output key that only the recipient can tell is theirs, so that an onlooker +sees no two payments to one address, and the sender needs no exchange with the +recipient first +(link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352]). + +It works by ECDH. The sender sums the secret keys of the transaction's +eligible inputs, hashes the transaction's smallest outpoint with the sum of +their public keys, and multiplies the recipient's scan key by both: a secret +only the sender and the holder of the scan key's secret share. A hash of that +secret and of the output's number tweaks the spend key into the output key, a +new one per transaction and per output. The recipient sums the inputs' public +keys instead, multiplies the sum by the same hash and its scan secret, finds +the same secret, and recognises its outputs +(link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352]). +``, namespace +`curves::secp256k1::silent_payments`, offers libsecp256k1's functions: + +* `create_outputs` makes the sender's output keys, one per `recipient` (a scan +and a spend `public_key`, which the sender decodes from the address), from the +key pairs of the Taproot inputs and of the other eligible inputs, apart, and +the smallest outpoint's 36 bytes; +* `make_prevouts_summary` sums the eligible inputs' public keys for the +recipient, into a `prevouts_summary`, and `scan_outputs` scans a transaction's +x-only outputs with the scan key pair and the spend key: each `found_output` +holds the output's key, its `spend_tweak` (a `secret<32>`, which +`seckey_tweak_add` adds to the spend secret key to spend the output, +<>) and the label it was sent to; +* `create_label` makes the scan key's `m`-th label, 0 being BIP 352's change +label, and `create_labeled_spend_key` the spend key of the address with that +label; `scan_outputs` recognises a labelled payment through a lookup the +caller gives, a `noexcept` callable that returns a label's tweak or +`std::nullopt`. + +`create_outputs`, `make_prevouts_summary` and `scan_outputs` take a +`workspace` for libsecp256k1's arrays (`send_workspace_size`, +`summary_workspace_size` and `scan_workspace_size` say how many bytes), so +that nothing is allocated, and wipe it, the inputs' secrets and the found +tweaks in it, before they return. No recipient, no input, no output, outputs +not one per recipient, `found` shorter than the outputs, a short workspace, or +more than `group_limit` (2323) recipients on one scan key is +`invalid_input_size`; a moved-from key pair or a null input `invalid_state`; +inputs whose keys sum to zero `invalid_secret_key` for the sender and +`invalid_public_key` for the recipient, as is an output key that does not +parse; a label that is not a point `invalid_point`. The tests check BIP 352's +own vectors, as libsecp256k1's tests read them from the same file: the input +keys, the smallest outpoint and the recipients' keys, already taken out of +the vectors' transactions and addresses, which are a domain library's. + +include::generated/backends-silent_payments.adoc[] + +*Example.* A donation page publishes one address. A donor's wallet pays it +with one input; the recipient scans the transaction, finds the payment, and +makes the key pair that spends it; a second donation lands on an unrelated key: + +[source,cpp] +---- +include::{examples}/silent_payment.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/silent_payment.expected[] +---- + +*Pitfalls.* + +* The smallest outpoint must be the transaction's, the smallest of all its +inputs, eligible or not. A sender who passes another computes another secret, +and the recipient is unable to find the payment +(link:https://github.com/bitcoin-core/secp256k1/blob/6e2c8bc4ecdc6e71dbe7a368f360d8d453ce435d/include/secp256k1_silentpayments.h[libsecp256k1's silent payments header]). Choosing the inputs and the outpoint is the wallet's, a domain +library's. +* Every output `create_outputs` makes must be in the transaction. The +recipient looks for the outputs to one scan key in order and stops at the +first it does not find, so that a dropped output may hide some or all of the +others (link:https://github.com/bitcoin-core/secp256k1/blob/6e2c8bc4ecdc6e71dbe7a368f360d8d453ce435d/include/secp256k1_silentpayments.h[libsecp256k1's silent payments header]). +* Scanning costs one ECDH per transaction with eligible inputs, whether it +pays the recipient or not, since only the shared secret tells. A full node +does it as blocks arrive; a light client, which must fetch each +transaction's summary data, must plan for that cost +(link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352]). +* Many labels may slow scanning down badly in some wallets, light clients +among them; libsecp256k1 recommends creating the change label alone and +handing out no labelled address (link:https://github.com/bitcoin-core/secp256k1/blob/6e2c8bc4ecdc6e71dbe7a368f360d8d453ce435d/include/secp256k1_silentpayments.h[libsecp256k1's silent payments header]). The change label itself is never +handed out, so that no one else can pay what looks like change +(link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352]). +* The workspaces grow with the counts: `send_workspace_size(r, t, p)` with +the recipients and the inputs, `scan_workspace_size(n)` with the outputs. A +workspace on the stack suits a few; a transaction of thousands of outputs +needs one the program owns on the heap, since WebAssembly's stacks are small. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 70b51fa1..3b91a80b 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -113,7 +113,9 @@ "bip324": ["BIP 324, version 2 P2P encrypted transport protocol", "https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki"], "elligatorswift": ["Chavez-Saab, Rodríguez-Henríquez and Tibouchi, SwiftEC: Shallue-van de Woestijne Indifferentiable Function to Elliptic Curves, 2022", "https://eprint.iacr.org/2022/759"], "openssl-evp-pkey-ec": ["OpenSSL's EVP_PKEY-EC: an EC key's point form and its encodings", "https://docs.openssl.org/master/man7/EVP_PKEY-EC/"], - "musig2": ["Nick, Ruffing and Seurin, MuSig2: Simple Two-Round Schnorr Multi-Signatures, CRYPTO 2021", "https://eprint.iacr.org/2020/1261"] + "musig2": ["Nick, Ruffing and Seurin, MuSig2: Simple Two-Round Schnorr Multi-Signatures, CRYPTO 2021", "https://eprint.iacr.org/2020/1261"], + "bip352": ["BIP 352, Silent Payments", "https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki"], + "libsecp256k1-silentpayments": ["libsecp256k1's silent payments header at webcpp's pin: the smallest outpoint, the outputs to keep, the labels to create", "https://github.com/bitcoin-core/secp256k1/blob/6e2c8bc4ecdc6e71dbe7a368f360d8d453ce435d/include/secp256k1_silentpayments.h"] }, "backends": { "bearssl": { @@ -629,6 +631,18 @@ "what": "BIP 327's MuSig2: many signers' keys aggregated into one, and their two rounds into one BIP 340 signature, each secret nonce consumed by its partial signature.", "section": "crypto-secp256k1-musig", "backends": {"secp256k1": {"tests": ["secp256k1_musig", "secp256k1_musig_entropy"]}} + }, + { + "id": "silent_payments", + "family": "secp256k1", + "free": true, + "functions": ["send_workspace_size", "summary_workspace_size", "scan_workspace_size", "create_outputs", "create_label", "create_labeled_spend_key", "make_prevouts_summary", "scan_outputs"], + "namespace": "curves", + "api": "curves::secp256k1::silent_payments::create_outputs, create_label, create_labeled_spend_key, make_prevouts_summary, scan_outputs, send_workspace_size, summary_workspace_size, scan_workspace_size", + "header": "", + "what": "BIP 352's silent payments: the sender's outputs to a reusable address of a scan and a spend key, the recipient's labels, and its scan of a transaction's outputs.", + "section": "crypto-secp256k1-silent-payments", + "backends": {"secp256k1": {"tests": ["secp256k1_silent_payments"]}} } ], "families": [ @@ -998,6 +1012,7 @@ {"need": "Find who signed a message or a transaction without being sent their key (Ethereum's signatures)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::sign_recoverable`, `recover`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "recover_signer", "section": "crypto-secp256k1-recovery"}, {"need": "Derive child keys for a watch-only wallet (BIP 32's derivation is a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`seckey_tweak_add`, `pubkey_tweak_add`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "key_tweak", "section": "crypto-secp256k1-tweaks"}, {"need": "Make a peer-to-peer connection's key exchange look like random bytes (BIP 324's transport; its packets are a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`ellswift_create`, `ellswift_decode`, `ellswift_xdh`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ellswift_handshake", "section": "crypto-secp256k1-ellswift"}, + {"need": "Publish one donation address that never shows two payments as related (BIP 352's addresses and transactions are a domain library's)", "namespace": "webcpp::crypto::curves::secp256k1::silent_payments", "api": "`create_outputs`, `make_prevouts_summary`, `scan_outputs`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "silent_payment", "section": "crypto-secp256k1-silent-payments"}, {"need": "Require two devices to sign for a wallet, with one ordinary signature on the chain", "namespace": "webcpp::crypto::curves::secp256k1::musig", "api": "`key_aggregate`, `nonce_gen`, `partial_sign`, `partial_signature_aggregate`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "musig_wallet", "section": "crypto-secp256k1-musig"}, {"need": "Make and keep a wallet's key", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make`, `xonly_public_key`, `public_key`; `aes256_gcm` at rest", "backend": "libsecp256k1, and AES-GCM's default", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//gcm-default", "example": "wallet_key", "section": "crypto-wallets-key"}, {"need": "Sign a Bitcoin SegWit v0 input (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`sign_ecdsa`, `to_der`, `normalize_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdsa_der", "section": "crypto-wallets-der"}, diff --git a/example/Jamfile b/example/Jamfile index b978fd2a..3aab1b99 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -69,6 +69,11 @@ webcpp.example ellswift_handshake.cpp : /third_party//secp256k1 ; # rounds of nonces and partial signatures, one BIP 340 signature on the chain. webcpp.example musig_wallet.cpp : /third_party//secp256k1 ; +# A donation page's one reusable address: a donor pays it, the recipient scans +# the transaction, finds the payment and spends it; a second payment to the +# address shares no output key with the first (BIP 352's silent payments). +webcpp.example silent_payment.cpp : /third_party//secp256k1 ; + # A wallet's key pair, its secret sealed at rest and restored. webcpp.example wallet_key.cpp : /third_party//secp256k1 /webcpp/crypto//gcm-default ; diff --git a/example/silent_payment.cpp b/example/silent_payment.cpp new file mode 100644 index 00000000..5a0f7230 --- /dev/null +++ b/example/silent_payment.cpp @@ -0,0 +1,138 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A donation page that publishes one reusable address (BIP 352's silent payments): a pair of +// public keys, scan and spend. A donor's wallet with one input pays it: the output key it makes +// is new, tied to the donor's input. The recipient scans the transaction's outputs with its scan +// key pair, finds the payment, and makes the key pair that spends it with seckey_tweak_add. A +// second donation to the same address gives an output key unrelated to the first, so that an +// onlooker sees no two payments to one address. The address's encoding, the transaction and the +// smallest outpoint's choice are a wallet's (a domain library's); the keys are fixed here, so +// that the program runs the same each time, where a real wallet draws them from crypto's random +// device. +// tag::program[] +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace secp256k1 = webcpp::crypto::curves::secp256k1; +namespace silent_payments = webcpp::crypto::curves::secp256k1::silent_payments; + +namespace { + +std::array repeated(std::uint8_t value) { + std::array bytes{}; + bytes.fill(value); + return bytes; +} + +using output_key = std::array; +using outpoint = std::array; + +// The donor's wallet pays the address with one input: one output key, the transaction's. +bool pay(silent_payments::recipient const& address, secp256k1::keypair const& donor_input, + outpoint const& smallest_outpoint, output_key& paid_key) { + std::array const recipients{address}; + std::array const plain_inputs{&donor_input}; + std::array outputs{}; + // The workspace holds libsecp256k1's arrays and the input's secret; it is wiped on return. + alignas(std::max_align_t) std::array + space{}; + if (!silent_payments::create_outputs(recipients, smallest_outpoint, {}, plain_inputs, outputs, + space)) { + return false; + } + paid_key = outputs[0]; + return true; +} + +} // namespace + +int main() { + // The donation page: its scan and spend key pairs stay with the recipient; the address is + // their two public keys. + auto const scan_pair = secp256k1::keypair::make(repeated(0x51)); + // The spend secret is kept, in a secret<32> that wipes itself, to spend what is found. + webcpp::crypto::secret<32> spend_secret; + std::ranges::fill(spend_secret.writable(), std::uint8_t{0x52}); + auto const spend_pair = secp256k1::keypair::make(spend_secret.bytes()); + auto const donor = secp256k1::keypair::make(repeated(0x53)); + if (!scan_pair || !spend_pair || !donor) { + return 1; + } + auto const scan_key = secp256k1::parse_public_key(*scan_pair->public_key()); + auto const spend_key = secp256k1::parse_public_key(*spend_pair->public_key()); + auto const donor_key = secp256k1::parse_public_key(*donor->public_key()); + if (!scan_key || !spend_key || !donor_key) { + return 1; + } + silent_payments::recipient const address{.scan_key = *scan_key, .spend_key = *spend_key}; + + // The donor pays: the transaction spends one input, whose outpoint is its smallest. + outpoint first_outpoint{}; + first_outpoint.fill(0x01); + output_key first_payment{}; + if (!pay(address, *donor, first_outpoint, first_payment)) { + return 1; + } + + // The recipient sees the transaction: its input's public key and smallest outpoint make the + // summary, and the scan of its outputs finds the payment. + std::array const input_keys{*donor_key}; + alignas(std::max_align_t) std::array + summary_space{}; + auto const summary = + silent_payments::make_prevouts_summary(first_outpoint, {}, input_keys, summary_space); + if (!summary) { + return 1; + } + std::array const transaction_outputs{first_payment}; + std::array found{}; + alignas(std::max_align_t) std::array + scan_space{}; + auto const found_count = silent_payments::scan_outputs(*scan_pair, *spend_key, *summary, + transaction_outputs, found, scan_space); + if (!found_count) { + return 1; + } + std::printf("the recipient found %zu output\n", *found_count); + + // The spend secret plus the found tweak is the output's secret key. + auto const output_secret = secp256k1::seckey_tweak_add(spend_secret, found[0].spend_tweak); + if (!output_secret) { + return 1; + } + auto const spending_pair = secp256k1::keypair::make(output_secret->bytes()); + if (!spending_pair) { + return 1; + } + auto const spending_key = spending_pair->xonly_public_key(); + if (!spending_key || *spending_key != found[0].output_key) { + return 1; + } + std::printf("the spending key matches the output\n"); + + // A second donation from the same wallet, another transaction: another outpoint. + outpoint second_outpoint{}; + second_outpoint.fill(0x02); + output_key second_payment{}; + if (!pay(address, *donor, second_outpoint, second_payment)) { + return 1; + } + if (second_payment != first_payment) { + std::printf("two payments to one address share no output key\n"); + } + return 0; +} + +// end::program[] diff --git a/example/silent_payment.expected b/example/silent_payment.expected new file mode 100644 index 00000000..c74a2adb --- /dev/null +++ b/example/silent_payment.expected @@ -0,0 +1,3 @@ +the recipient found 1 output +the spending key matches the output +two payments to one address share no output key diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index 4c8de8c7..6338a999 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -60,6 +60,7 @@ #include #include #include +#include #include #endif diff --git a/include/webcpp/crypto/backends/secp256k1.hpp b/include/webcpp/crypto/backends/secp256k1.hpp index e2d053de..abade41a 100644 --- a/include/webcpp/crypto/backends/secp256k1.hpp +++ b/include/webcpp/crypto/backends/secp256k1.hpp @@ -9,8 +9,9 @@ every module on. It serves `curves::secp256k1::keypair`, `verify_schnorr`, `verify_ecdsa`, `recover`, the parsed `public_key`, the DER and low-S functions, the x-only tweak, the tweaks and combination of `curves/secp256k1/tweak.hpp`, the SPKI and PKCS#8 of - `curves/secp256k1/formats.hpp`, the ElligatorSwift of `curves/secp256k1/ellswift.hpp` and the - MuSig2 of `curves/secp256k1/musig.hpp`, and its whole C API stays reachable through + `curves/secp256k1/formats.hpp`, the ElligatorSwift of `curves/secp256k1/ellswift.hpp`, the + MuSig2 of `curves/secp256k1/musig.hpp` and the silent payments of + `curves/secp256k1/silent_payments.hpp`, and its whole C API stays reachable through ``. @see "secp256k1", in the guide. @@ -36,6 +37,7 @@ #include #include #include +#include #include diff --git a/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp b/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp new file mode 100644 index 00000000..ef090122 --- /dev/null +++ b/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp @@ -0,0 +1,589 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + secp256k1's silent payments on libsecp256k1 (BIP 352): the sender's outputs to a reusable + address of two keys, scan and spend, the recipient's labels, and the recipient's scan of a + transaction's outputs, which finds its payments and the tweaks that spend them. + Addresses, transactions and the choice of eligible inputs are a domain library's. + + @see "Silent payments", in the guide's secp256k1 chapter. +*/ +#ifndef WEBCPP_CRYPTO_CURVES_SECP256K1_SILENT_PAYMENTS_HPP +#define WEBCPP_CRYPTO_CURVES_SECP256K1_SILENT_PAYMENTS_HPP + +#include + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** + * What `scan_outputs` gives libsecp256k1 as its label context: the caller's lookup, and the + * function that calls it, so that the C callback reaches a C++ callable of any type. + */ +struct secp256k1_label_context { + /** The caller's lookup, which outlives the scan. */ + void const* lookup_object; + /** Calls the lookup with a candidate label's 33 bytes: its tweak's 32 bytes, or null. */ + unsigned char const* (*call_lookup)(void const*, unsigned char const*) noexcept; +}; + +/** + * Calls a lookup of type `LabelLookup` with a candidate label. + * + * @tparam LabelLookup The lookup's type, which satisfies `label_lookup`. + * @param lookup_object The lookup. + * @param label_bytes The candidate label's 33 bytes. + * @return Its tweak's 32 bytes, which stay valid until the next call; null when it is no label. + */ +template +[[nodiscard]] unsigned char const* secp256k1_call_label_lookup( + void const* lookup_object, unsigned char const* label_bytes) noexcept { + auto const found_tweak = (*static_cast(lookup_object))( + std::span(label_bytes, 33)); + return found_tweak ? found_tweak->data() : nullptr; +} + +extern "C" { + +/** + * libsecp256k1's label lookup callback, which reaches the caller's lookup through the + * `secp256k1_label_context` it is given. C linkage, as libsecp256k1's function pointer type has. + * + * @param label_bytes The candidate label's 33 bytes. + * @param label_context The `secp256k1_label_context`. + * @return The label's tweak, or null. + */ +inline unsigned char const* webcpp_crypto_detail_secp256k1_label_lookup( + unsigned char const* label_bytes, void const* label_context) noexcept { + auto const* const context = static_cast(label_context); + return context->call_lookup(context->lookup_object, label_bytes); +} + +} // extern "C" + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::curves::secp256k1::silent_payments { + +/** The size of a transaction's smallest outpoint, serialised: 36 bytes. */ +inline constexpr std::size_t outpoint_size = 36; + +/** The most outputs one scan key's group may hold (BIP 352's limit). */ +inline constexpr std::size_t group_limit = SECP256K1_SILENTPAYMENTS_RECIPIENT_GROUP_LIMIT; + +/** + * A recipient as the sender reads it from the address: its scan and spend keys (decoding + * the address is a domain library's). + */ +struct recipient { + /** The scan key, whose secret the recipient scans with. */ + public_key scan_key; + /** The spend key, labelled or not, which each output tweaks. */ + public_key spend_key; +}; + +/** A label (`secp256k1_silentpayments_label`, serialised) and its tweak. */ +struct label { + /** The label's point, SEC1 compressed: the tweak times the generator. */ + std::array point; + /** The label's tweak, which the scan adds to an output found with this label. */ + std::array tweak; +}; + +/** + * An output the recipient found: its x-only key, the tweak that spends it (added to the + * spend secret key with `seckey_tweak_add`), and the label it was sent to, if any. + */ +struct found_output { + /** The output's x-only key. */ + std::array output_key{}; + /** The spend secret key plus this tweak is the output's secret key. */ + secret<32> spend_tweak; + /** The label the output was sent to, or none for the address without a label. */ + std::optional> label_point; +}; + +/** + * The prevouts' summary a recipient scans with: the sum of the eligible inputs' public keys and + * the input hash (libsecp256k1's prevouts_summary, 101 bytes), public, copied freely, made only by + * `make_prevouts_summary`. + */ +class prevouts_summary { +private: + friend struct webcpp::crypto::detail::secp256k1_access; + + prevouts_summary() noexcept = default; + + secp256k1_silentpayments_prevouts_summary native_value_{}; +}; + +/** + * Whether `LabelLookup` can look up a label for `scan_outputs`. + * + * Called with a candidate label's 33 bytes, it returns the label's 32-byte tweak or + * `std::nullopt`, and is noexcept, since libsecp256k1's C frames are between the scan and the + * lookup. The tweak's bytes stay valid until the lookup is called again. + * + * @tparam LabelLookup The lookup's type. + */ +template +concept label_lookup = + std::is_nothrow_invocable_r_v>, + LabelLookup const&, std::span>; + +/** The lookup of a recipient with no labels: it knows none. */ +struct no_labels { + /** + * Finds no label. + * + * @return `std::nullopt`. + */ + [[nodiscard]] std::optional> operator()( + std::span /*candidate_label*/) const noexcept { + return std::nullopt; + } +}; + +/** + * The workspace `create_outputs` needs, in bytes. + * + * @param recipient_count The number of recipients. + * @param taproot_input_count The number of Taproot inputs. + * @param plain_input_count The number of other eligible inputs. + * @return The recipients' structs and their pointers, the outputs and their pointers, the + * Taproot key pairs' pointers, the plain inputs' secrets and their pointers, and one + * `alignof(std::max_align_t)` of padding per array. + */ +[[nodiscard]] constexpr std::size_t send_workspace_size(std::size_t recipient_count, + std::size_t taproot_input_count, + std::size_t plain_input_count) noexcept { + return (recipient_count * (sizeof(secp256k1_silentpayments_recipient) + sizeof(void*) + + sizeof(secp256k1_xonly_pubkey) + sizeof(void*))) + + (taproot_input_count * sizeof(void*)) + (plain_input_count * (32 + sizeof(void*))) + + (7 * alignof(std::max_align_t)); +} + +/** + * The workspace `make_prevouts_summary` needs, in bytes. + * + * @param taproot_input_count The number of Taproot inputs' x-only keys. + * @param plain_input_count The number of other eligible inputs' keys. + * @return The parsed x-only keys and their pointers, the plain keys' pointers, and one + * `alignof(std::max_align_t)` of padding per array. + */ +[[nodiscard]] constexpr std::size_t summary_workspace_size(std::size_t taproot_input_count, + std::size_t plain_input_count) noexcept { + return (taproot_input_count * (sizeof(secp256k1_xonly_pubkey) + sizeof(void*))) + + (plain_input_count * sizeof(void*)) + (3 * alignof(std::max_align_t)); +} + +/** + * The workspace `scan_outputs` needs, in bytes. + * + * @param output_count The number of the transaction's outputs. + * @return The parsed outputs and their pointers, libsecp256k1's found outputs and their + * pointers, and one `alignof(std::max_align_t)` of padding per array. + */ +[[nodiscard]] constexpr std::size_t scan_workspace_size(std::size_t output_count) noexcept { + return (output_count * (sizeof(secp256k1_xonly_pubkey) + sizeof(void*) + + sizeof(secp256k1_silentpayments_found_output) + sizeof(void*))) + + (4 * alignof(std::max_align_t)); +} + +} // namespace webcpp::crypto::curves::secp256k1::silent_payments + +namespace webcpp::crypto::detail { + +/** + * Whether more than `group_limit` recipients share one scan key, which libsecp256k1 refuses as + * it refuses a sum of zero. A group over the limit holds one of the first `count - group_limit` + * recipients, so only those are counted from. + * + * @param recipients The recipients, more than `group_limit`. + * @return Whether a group is over the limit. + */ +[[nodiscard]] inline bool secp256k1_over_group_limit( + std::span recipients) noexcept { + using curves::secp256k1::silent_payments::group_limit; + for (std::size_t first_index = 0; first_index < recipients.size() - group_limit; + ++first_index) { + auto const& scan_key = recipients[first_index].scan_key; + auto const group_size = std::ranges::count_if( + recipients, + [&scan_key](curves::secp256k1::silent_payments::recipient const& other_recipient) { + return other_recipient.scan_key == scan_key; + }); + if (std::cmp_greater(group_size, group_limit)) { + return true; + } + } + return false; +} + +} // namespace webcpp::crypto::detail + +namespace webcpp::crypto::curves::secp256k1::silent_payments { + +/** + * The sender's outputs (`secp256k1_silentpayments_sender_create_outputs`): one x-only key + * per recipient, in the recipients' order, from the secret keys of the transaction's eligible + * inputs, Taproot inputs (their keys negated for an odd y, as BIP 352 says) apart from the + * others, and the smallest outpoint, which the caller determines. + * + * The context is the first Taproot input's key pair's, else the first plain input's. + * + * Tip: every output made must be in the transaction, and the outpoint must be the transaction's + * smallest, or the recipient never finds the payment. + * + * @tparam Backend The key pairs' backend, `backends::secp256k1`. + * @param recipients The recipients, at least one; a recipient paid twice is listed twice. + * @param smallest_outpoint The smallest outpoint of all the transaction's inputs, serialised. + * @param taproot_inputs The key pairs of the Taproot inputs. + * @param plain_inputs The key pairs of the other eligible inputs. + * @param output_keys One per recipient, where the outputs' x-only keys go. + * @param pointer_space At least `send_workspace_size(recipients.size(), taproot_inputs.size(), + * plain_inputs.size())` bytes; zero when the function returns, whatever it returns. + * @return Nothing; `invalid_input_size` (no recipient, no input at all, outputs not one per + * recipient, a short workspace, more than `group_limit` recipients sharing a scan key, which + * webcpp counts only when there are more recipients than that); `invalid_state` (a moved-from + * key pair, or a null pointer among the inputs); `invalid_secret_key` when libsecp256k1 + * refuses: the inputs' keys sum to zero, or a recipient's spend key gives no output, which only + * a key chosen against the sender can. + */ +template +[[nodiscard]] boost::system::result create_outputs( + std::span recipients, + std::span smallest_outpoint, + std::span> const* const> taproot_inputs, + std::span> const* const> plain_inputs, + std::span> output_keys, workspace pointer_space) noexcept { + static_assert(webcpp::crypto::detail::secp256k1_backend, + WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + // The carver first: it wipes the workspace, the plain inputs' secrets in it, on every return. + webcpp::crypto::detail::secp256k1_workspace carver(pointer_space); + std::size_t const recipient_count = recipients.size(); + std::size_t const taproot_count = taproot_inputs.size(); + std::size_t const plain_count = plain_inputs.size(); + // libsecp256k1 checks the counts with ARG_CHECK, whose callback aborts: refused first here. + if (recipient_count == 0 || (taproot_count == 0 && plain_count == 0) || + output_keys.size() != recipient_count || + pointer_space.size() < send_workspace_size(recipient_count, taproot_count, plain_count)) { + return error::invalid_input_size; + } + using access = webcpp::crypto::detail::secp256k1_access; + // Every pointer is checked before any is used, as libsecp256k1's ARG_CHECKs would. + auto const usable = [](basic_keypair const* input) { + return input != nullptr && access::keyed(*input); + }; + if (!std::ranges::all_of(taproot_inputs, usable) || + !std::ranges::all_of(plain_inputs, usable)) { + return error::invalid_state; + } + auto* const recipient_values = carver.take(recipient_count); + auto* const recipient_pointers = + carver.take(recipient_count); + auto* const output_values = carver.take(recipient_count); + auto* const output_pointers = carver.take(recipient_count); + // Arrays of no elements are nullptr, as libsecp256k1 requires of a side with no input. + auto* const taproot_pointers = carver.take(taproot_count); + auto* const plain_secrets = carver.take>(plain_count); + auto* const plain_pointers = carver.take(plain_count); + if (recipient_values == nullptr || recipient_pointers == nullptr || output_values == nullptr || + output_pointers == nullptr || (taproot_count != 0 && taproot_pointers == nullptr) || + (plain_count != 0 && (plain_secrets == nullptr || plain_pointers == nullptr))) { + return error::invalid_input_size; + } + for (std::size_t index = 0; index < recipient_count; ++index) { + recipient_values[index] = secp256k1_silentpayments_recipient{ + .scan_pubkey = access::point(recipients[index].scan_key), + .spend_pubkey = access::point(recipients[index].spend_key), + .index = index, + }; + recipient_pointers[index] = &recipient_values[index]; + output_values[index] = secp256k1_xonly_pubkey{}; + output_pointers[index] = &output_values[index]; + } + for (std::size_t index = 0; index < taproot_count; ++index) { + taproot_pointers[index] = &access::pair(*taproot_inputs[index]); + } + for (std::size_t index = 0; index < plain_count; ++index) { + secp256k1_keypair_sec(access::context(*plain_inputs[index]), plain_secrets[index].data(), + &access::pair(*plain_inputs[index])); + plain_pointers[index] = plain_secrets[index].data(); + } + auto const* const signer = taproot_count != 0 ? taproot_inputs[0] : plain_inputs[0]; + if (secp256k1_silentpayments_sender_create_outputs( + access::context(*signer), output_pointers, recipient_pointers, recipient_count, + smallest_outpoint.data(), taproot_pointers, taproot_count, plain_pointers, + plain_count) == 0) { + if (recipient_count > group_limit && + webcpp::crypto::detail::secp256k1_over_group_limit(recipients)) { + return error::invalid_input_size; + } + return error::invalid_secret_key; + } + for (std::size_t index = 0; index < recipient_count; ++index) { + // A made output always serialises: libsecp256k1 returns 1. + static_cast(secp256k1_xonly_pubkey_serialize( + secp256k1_context_static, output_keys[index].data(), &output_values[index])); + } + return {}; +} + +/** + * The `m`-th label of a scan key (`secp256k1_silentpayments_recipient_label_create`); 0 is + * BIP 352's change label. + * + * Tip: many labels may slow scanning down in some wallets, light clients among them; create the + * change label alone, and hand out no labelled address and never the change label. + * + * @tparam Backend The key pair's backend, `backends::secp256k1`. + * @param scan_key The scan key pair, whose context makes the label. + * @param label_number The label's integer m. + * @return The label; `invalid_state` moved from; `backend_failure` should the label's hash not + * be a valid scalar, which happens with negligible probability. + */ +template +[[nodiscard]] boost::system::result