diff --git a/bench/operations.hpp b/bench/operations.hpp index dcfb68ee..7e9b293a 100644 --- a/bench/operations.hpp +++ b/bench/operations.hpp @@ -25,6 +25,9 @@ #include #ifdef WEBCPP_CRYPTO_HAS_SECP256K1 #include +#include +#include +#include #endif #include @@ -195,6 +198,258 @@ class secp256k1 { std::array aux_{}; curves::secp256k1::basic_keypair key_; }; + +// The x coordinate of the ECDH shared point of a key pair and a peer's public key, unhashed. +template +class secp256k1_ecdh_x { +public: + static constexpr std::string_view operation = + "x coordinate of the ECDH shared point with a peer's public key"; + + explicit secp256k1_ecdh_x(std::uint8_t seed) + : key_(take(curves::secp256k1::basic_keypair::make( + filled<32>(static_cast(seed | 1U))), + "make")), + peer_(take(curves::secp256k1::basic_keypair::make( + filled<32>(static_cast(seed + 6U))), + "make")), + peer_public_(take(peer_.public_key(), "public_key")) {} + + std::uint8_t run() { + auto const shared = take(key_.ecdh_x(peer_public_), "ecdh_x"); + return shared.bytes()[0]; + } + + bool check() { + auto const own_public = take(key_.public_key(), "public_key"); + auto const shared = take(key_.ecdh_x(peer_public_), "ecdh_x"); + auto const peer_shared = take(peer_.ecdh_x(own_public), "ecdh_x"); + return std::ranges::equal(shared.bytes(), peer_shared.bytes()); + } + +private: + curves::secp256k1::basic_keypair key_; + curves::secp256k1::basic_keypair peer_; + std::array peer_public_{}; +}; + +// The public key recovered from a recoverable ECDSA signature of a 32-byte hash; the signature +// is made once, outside what is measured. +template +class secp256k1_recover { +public: + static constexpr std::string_view operation = + "public key recovered from an ECDSA signature of a 32-byte hash"; + + explicit secp256k1_recover(std::uint8_t seed) + : hash_(filled<32>(static_cast(seed + 3U))), + key_(take(curves::secp256k1::basic_keypair::make( + filled<32>(static_cast(seed | 1U))), + "make")), + signature_(take(key_.sign_recoverable(hash_), "sign_recoverable")) {} + + std::uint8_t run() { + auto const recovered = + take(curves::secp256k1::recover(signature_, hash_), "recover"); + return curves::secp256k1::serialize_public_key(recovered)[1]; + } + + bool check() { + auto const recovered = + take(curves::secp256k1::recover(signature_, hash_), "recover"); + return curves::secp256k1::serialize_public_key(recovered) == + take(key_.public_key(), "public_key"); + } + +private: + std::array hash_{}; + curves::secp256k1::basic_keypair key_; + std::array signature_{}; +}; + +// BIP 324's shared secret of a key pair and a peer, each known by its ElligatorSwift encoding. +template +class secp256k1_ellswift { +public: + static constexpr std::string_view operation = + "BIP 324 shared secret of two ElligatorSwift encodings"; + + explicit secp256k1_ellswift(std::uint8_t seed) + : key_(take(curves::secp256k1::basic_keypair::make( + filled<32>(static_cast(seed | 1U))), + "make")), + peer_(take(curves::secp256k1::basic_keypair::make( + filled<32>(static_cast(seed + 6U))), + "make")), + own_encoding_( + take(curves::secp256k1::ellswift_create(key_, filled<32>(seed)), "ellswift_create")), + peer_encoding_(take(curves::secp256k1::ellswift_create( + peer_, filled<32>(static_cast(seed + 7U))), + "ellswift_create")) {} + + std::uint8_t run() { + auto const shared = + take(curves::secp256k1::ellswift_xdh(key_, own_encoding_, peer_encoding_, + curves::secp256k1::ellswift_party::initiator), + "ellswift_xdh"); + return shared.bytes()[0]; + } + + bool check() { + auto const shared = + take(curves::secp256k1::ellswift_xdh(key_, own_encoding_, peer_encoding_, + curves::secp256k1::ellswift_party::initiator), + "ellswift_xdh"); + auto const peer_shared = + take(curves::secp256k1::ellswift_xdh(peer_, own_encoding_, peer_encoding_, + curves::secp256k1::ellswift_party::responder), + "ellswift_xdh"); + return std::ranges::equal(shared.bytes(), peer_shared.bytes()); + } + +private: + curves::secp256k1::basic_keypair key_; + curves::secp256k1::basic_keypair peer_; + std::array own_encoding_{}; + std::array peer_encoding_{}; +}; + +// A two-signer MuSig2 signature of a 32-byte message: both signers' nonces, the session, both +// partial signatures and their aggregate, the keys aggregated once outside what is measured. +template +class secp256k1_musig { +public: + static constexpr std::string_view operation = + "two-signer MuSig2 signature of a 32-byte message"; + + explicit secp256k1_musig(std::uint8_t seed) + : message_(filled<32>(static_cast(seed + 3U))), + first_(take(curves::secp256k1::basic_keypair::make( + filled<32>(static_cast(seed | 1U))), + "make")), + second_(take(curves::secp256k1::basic_keypair::make( + filled<32>(static_cast(seed + 6U))), + "make")), + signers_key_(aggregate(first_, second_, space_)) {} + + std::uint8_t run() { return sign()[0]; } + + bool check() { + return curves::secp256k1::verify_schnorr(sign(), message_, + signers_key_.xonly_public_key()) + .has_value(); + } + +private: + using space_type = std::array; + + static curves::secp256k1::musig::aggregate_key aggregate( + curves::secp256k1::basic_keypair const& first, + curves::secp256k1::basic_keypair const& second, space_type& space) { + std::array const keys{ + take(curves::secp256k1::parse_public_key(take(first.public_key(), "key")), + "parse_public_key"), + take(curves::secp256k1::parse_public_key(take(second.public_key(), "key")), + "parse_public_key"), + }; + return take(curves::secp256k1::musig::key_aggregate(keys, space), "key_aggregate"); + } + + std::array sign() { + namespace musig = curves::secp256k1::musig; + auto first_nonce = take(musig::nonce_gen(first_, signers_key_, message_), "nonce_gen"); + auto second_nonce = take(musig::nonce_gen(second_, signers_key_, message_), "nonce_gen"); + std::array const nonces{first_nonce.public_part, + second_nonce.public_part}; + auto const nonce_sum = take(musig::nonce_aggregate(nonces, space_), "nonce_sum"); + auto const signing_session = + take(musig::nonce_process(nonce_sum, message_, signers_key_), "session"); + std::array const parts{ + take(musig::partial_sign(first_, std::move(first_nonce.secret_part), signers_key_, + signing_session), + "partial_sign"), + take(musig::partial_sign(second_, std::move(second_nonce.secret_part), signers_key_, + signing_session), + "partial_sign"), + }; + return take(musig::partial_signature_aggregate(signing_session, parts, space_), + "partial_signature_aggregate"); + } + + std::array message_{}; + alignas(std::max_align_t) space_type space_{}; + curves::secp256k1::basic_keypair first_; + curves::secp256k1::basic_keypair second_; + curves::secp256k1::musig::aggregate_key signers_key_; +}; + +// A silent payment output for one recipient, from one input's key pair. +template +class secp256k1_silent_payments { +public: + static constexpr std::string_view operation = "a silent payment output for one recipient"; + + explicit secp256k1_silent_payments(std::uint8_t seed) + : scan_(take(curves::secp256k1::basic_keypair::make( + filled<32>(static_cast(seed | 1U))), + "make")), + spend_key_(public_of(take(curves::secp256k1::basic_keypair::make( + filled<32>(static_cast(seed + 6U))), + "make"))), + input_(take(curves::secp256k1::basic_keypair::make( + filled<32>(static_cast(seed + 8U))), + "make")), + outpoint_(filled(seed)) {} + + std::uint8_t run() { return send()[0]; } + + bool check() { + namespace silent_payments = curves::secp256k1::silent_payments; + std::array, 1> const outputs{send()}; + std::array const input_keys{public_of(input_)}; + alignas(std::max_align_t) + std::array + summary_space{}; + auto const summary = take(silent_payments::make_prevouts_summary( + outpoint_, {}, input_keys, summary_space), + "make_prevouts_summary"); + std::array found{}; + alignas(std::max_align_t) std::array + scan_space{}; + return take(silent_payments::scan_outputs(scan_, spend_key_, summary, outputs, found, + scan_space), + "scan_outputs") == 1; + } + +private: + static curves::secp256k1::public_key public_of( + curves::secp256k1::basic_keypair const& key) { + return take(curves::secp256k1::parse_public_key(take(key.public_key(), "key")), + "parse_public_key"); + } + + std::array send() { + namespace silent_payments = curves::secp256k1::silent_payments; + std::array const recipients{ + silent_payments::recipient{.scan_key = public_of(scan_), .spend_key = spend_key_}}; + std::array const*, 1> const plain_inputs{&input_}; + std::array, 1> outputs{}; + alignas(std::max_align_t) + std::array + space{}; + take(silent_payments::create_outputs(recipients, outpoint_, {}, plain_inputs, + outputs, space), + "create_outputs"); + return outputs[0]; + } + + curves::secp256k1::basic_keypair scan_; + curves::secp256k1::public_key spend_key_; + curves::secp256k1::basic_keypair input_; + std::array outpoint_{}; +}; #endif // An Ed25519 signature of a 32-byte message. diff --git a/build.jam b/build.jam index 4ecdce35..1b3d1f62 100644 --- a/build.jam +++ b/build.jam @@ -210,4 +210,37 @@ rule sealed_box-default-linked ( properties * ) } } alias sealed_box-default : : : : @sealed_box-default-linked ; +rule secp256k1_ellswift-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//secp256k1 ; + case wasip2 : return /third_party//secp256k1 ; + case wasip3 : return /third_party//secp256k1 ; + case emscripten : return /third_party//secp256k1 ; + } +} +alias secp256k1_ellswift-default : : : : @secp256k1_ellswift-default-linked ; +rule secp256k1_musig-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//secp256k1 ; + case wasip2 : return /third_party//secp256k1 ; + case wasip3 : return /third_party//secp256k1 ; + case emscripten : return /third_party//secp256k1 ; + } +} +alias secp256k1_musig-default : : : : @secp256k1_musig-default-linked ; +rule secp256k1_silent_payments-default-linked ( properties * ) +{ + switch [ webcpp-target.target-of $(properties) ] + { + case native : return /third_party//secp256k1 ; + case wasip2 : return /third_party//secp256k1 ; + case wasip3 : return /third_party//secp256k1 ; + case emscripten : return /third_party//secp256k1 ; + } +} +alias secp256k1_silent_payments-default : : : : @secp256k1_silent_payments-default-linked ; # generate.py: end the defaults' aliases diff --git a/doc/backends.adoc b/doc/backends.adoc index 5d861634..28f7ac31 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -82,16 +82,23 @@ ChaCha20-Poly1305 `make`, `seal` and `open`; OpenSSL's `make` and `seal` of both; ctaes's AES; libsodium's Ed25519 key pair and signature, X25519's public key and agreement, its three ChaCha20-Poly1305 AEADs and two secret boxes, `hybrid::box` in both families, the sealed box's `seal` and `open`, and `kx`; -and libsecp256k1's own `ctime_tests.c`. Both checkers run the same paths, -written once (`paths.hpp`), memcheck OpenSSL's besides. Each check is shown to -fail on a planted branch on a key byte, and each path's output is checked to -carry the mark, so that the path is traced, where the checker's shadow keeps -it: MemorySanitizer's loses the mark through a constant-time reduction to one -bit, so the result of `is_all_zero`, X25519's public key and the bytes a -destructor wiped are checked by memcheck alone. dudect's statistics +libsecp256k1's own `ctime_tests.c`; and webcpp's code around libsecp256k1: +the key pair's making, its BIP 340, recoverable and hedged ECDSA signatures and +x-only tweak, ECDH in its three forms, the secret key's tweaks and negation, +PKCS#8's encoding and decoding, ElligatorSwift's `ellswift_create` and +`ellswift_xdh`, MuSig2's `nonce_gen` and `partial_sign`, and silent payments' +`create_outputs`, `create_label` and `scan_outputs`, with the wipe of their +workspaces. Both checkers run the same paths, written once (`paths.hpp`), +memcheck OpenSSL's besides. Each check is shown to fail on a planted branch on +a key byte, and each path's output is checked to carry the mark, so that the +path is traced, where the checker's shadow keeps it: MemorySanitizer's loses +the mark through a constant-time reduction to one bit, so the result of +`is_all_zero`, X25519's public key and the bytes a destructor wiped are checked +by memcheck alone. dudect's statistics (link:https://eprint.iacr.org/2016/1123[Reparaz, Balasch and Verbauwhede]) time -BearSSL's two AEADs' seal and open, ctaes, `equal`, and libsodium's X25519 -agreement and Ed25519 signing natively, on Linux and macOS, and under wasmtime. +BearSSL's two AEADs' seal and open, ctaes, `equal`, libsodium's X25519 +agreement and Ed25519 signing, and libsecp256k1's `ecdh_x` natively, on Linux +and macOS, and under wasmtime. On 64-bit ARM under macOS and Linux, each dudect program first sets the CPU's DIT (data-independent timing) bit, with which the instructions Arm lists take a time independent of their data, and which Apple requires of constant-time @@ -118,8 +125,14 @@ everything else. Whether a tag matched, or a shared secret came out all zero, is public by design, since the operation reports it, but it is computed from the secrets: it is the one kind of value webcpp marks public, where webcpp's code first -branches on it (BearSSL's engines, libsodium's engines and X25519's `agree`), -so that the checkers report every other branch. libsodium branches on its own +branches on it (BearSSL's engines, libsodium's engines, X25519's `agree`, and +each verdict of libsecp256k1's that webcpp reads), so that the checkers report +every other branch. libsecp256k1 marks its own public values (a nonce's retry, +a verdict, a public key it loads) when its context is made with +`SECP256K1_CONTEXT_DECLASSIFY`, which webcpp's contexts are under the +checkers, as its `ctime_tests.c` makes its own; a key pair's public key and a +silent payments label, which webcpp reads from libsecp256k1's structures, are +marked public where webcpp reads them. libsodium branches on its own verdicts inside the functions that compute them; the lane tells memcheck of each of those functions (`sodium_verdicts.supp`), and libsodium is used unchanged. MemorySanitizer approximates a subtraction without its carry, so it diff --git a/doc/changelog.adoc b/doc/changelog.adoc index feedffbe..62c66c95 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -18,9 +18,9 @@ of every version are on webcpp's index page. // tag::unreleased[] * Added crypto, primitives over C backends: ciphers, curves and randomness, errors of fixed values in webcpp.crypto, every result `+[[nodiscard]]+`, and WEBCPP_CRYPTO_HAS_THREADS, defined natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is. * 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 supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default per family and target (secp256k1's modules among them), 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, hedged and recoverable ECDSA, raw and hashed ECDH, strict DER, low-S, tweaks, SPKI, PKCS#8, PEM, BIP 324's ElligatorSwift, BIP 327's MuSig2, 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 b2ff026a..4630790a 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -18,22 +18,55 @@ on a key*, so that two parties who only exchanged public keys share a secret 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 -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 (<>). +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 +(<>). Its functions, by header: + +* `secp256k1.hpp`, the key pair and its signatures and ECDH: `keypair::make`, +and the key pair's `xonly_public_key`, `public_key`, +`public_key_uncompressed`, `sign_schnorr`, `sign_ecdsa`, `sign_recoverable`, +`ecdh`, `ecdh_x`, `ecdh_point` and `tweak_xonly`; `verify_schnorr`, +`verify_ecdsa`, `recover`, `parse_public_key`, `serialize_public_key`, +`to_der`, `from_der`, `normalize_ecdsa` and the x-only key's `tweak_xonly`; +* `secp256k1/tweak.hpp`, tweaks of whole keys, the arithmetic of BIP 32's +derivation and of watch-only wallets: `seckey_tweak_add`, `seckey_tweak_mul`, +`seckey_negate`, `pubkey_tweak_add`, `pubkey_tweak_mul`, `pubkey_negate` and +`pubkey_combine` (<>); +* `secp256k1/formats.hpp`, keys in the SPKI and PKCS#8 files that OpenSSL +exchanges: `encode_spki`, `decode_spki`, `encode_pkcs8` and `decode_pkcs8` +(<>); +* `secp256k1/ellswift.hpp`, keys sent as random-looking bytes, BIP 324's +ElligatorSwift: `ellswift_create`, `ellswift_encode`, `ellswift_decode` and +`ellswift_xdh` (<>); +* `secp256k1/musig.hpp`, many signers' keys and signatures aggregated into +one, BIP 327's MuSig2: `key_aggregate`, `nonce_gen`, `nonce_aggregate`, +`nonce_process`, `partial_sign`, `partial_signature_verify`, +`partial_signature_aggregate`, and the `parse_` and `serialize_` functions of +what the signers send (<>); +* `secp256k1/silent_payments.hpp`, one reusable address whose payments look +unrelated, BIP 352's silent payments: `create_outputs`, `create_label`, +`create_labeled_spend_key`, `make_prevouts_summary` and `scan_outputs` +(<>). + +Ethereum's `v` encoding of the recovery id, the hash it signs, its +transactions and its addresses are a domain library's, and so is BIP 32's +derivation, its HMAC-SHA-512 and its paths, which only adds a tweak computed +there to a whole key +(link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32]). +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[] 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/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/backends-keypair.adoc b/doc/generated/backends-keypair.adoc index 1ca69118..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+`) +|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-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/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/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/constant-time.adoc b/doc/generated/constant-time.adoc index b89a5b82..8d6f31fe 100644 --- a/doc/generated/constant-time.adoc +++ b/doc/generated/constant-time.adoc @@ -34,8 +34,8 @@ |libsecp256k1 |by design: signing and key generation are constant time and constant memory access; link:https://github.com/bitcoin-core/secp256k1#readme[libsecp256k1's README] -|Valgrind's memcheck (Linux): secp256k1 (libsecp256k1's own `+ctime_tests.c+`); MemorySanitizer (Linux, clang): secp256k1 (libsecp256k1's own `+ctime_tests.c+`) -|not measured yet +|Valgrind's memcheck (Linux): secp256k1 (libsecp256k1's own `+ctime_tests.c+`, and webcpp's code around it: the key pair's making, its signatures and x-only tweak, ECDH in three forms, the secret key's tweaks and negation, and PKCS#8), ElligatorSwift (libsecp256k1's own `+ctime_tests.c+`, and webcpp's `+ellswift_create+` and `+ellswift_xdh+` around it), MuSig2 (libsecp256k1's own `+ctime_tests.c+`, and webcpp's `+nonce_gen+` and `+partial_sign+` around it), BIP 352 silent payments (libsecp256k1's own `+ctime_tests.c+`, and webcpp's `+create_outputs+`, `+create_label+` and `+scan_outputs+` around it, each workspace's wipe included); MemorySanitizer (Linux, clang): secp256k1 (the same paths as memcheck's), ElligatorSwift (the same paths as memcheck's), MuSig2 (the same paths as memcheck's), BIP 352 silent payments (the same paths as memcheck's); dudect: secp256k1 (`+ecdh_x+`) +|dudect: secp256k1 (`+ecdh_x+`) |not measured yet |not measured yet diff --git a/doc/generated/default-aliases.adoc b/doc/generated/default-aliases.adoc index eef8745d..511a435e 100644 --- a/doc/generated/default-aliases.adoc +++ b/doc/generated/default-aliases.adoc @@ -80,4 +80,19 @@ |X25519-XSalsa20-Poly1305 sealed box |`+/third_party//sodium+` on every target |<> + +|`+/webcpp/crypto//secp256k1_ellswift-default+` +|ElligatorSwift +|`+/third_party//secp256k1+` on every target +|<> + +|`+/webcpp/crypto//secp256k1_musig-default+` +|MuSig2 +|`+/third_party//secp256k1+` on every target +|<> + +|`+/webcpp/crypto//secp256k1_silent_payments-default+` +|BIP 352 silent payments +|`+/third_party//secp256k1+` on every target +|<> |=== diff --git a/doc/generated/defaults.adoc b/doc/generated/defaults.adoc index ba45b810..4f46ec99 100644 --- a/doc/generated/defaults.adoc +++ b/doc/generated/defaults.adoc @@ -118,4 +118,22 @@ |libsodium |the only backend that has it: libsodium's own C code, which draws the key pair of each message from its own generator, the same on every target (link:https://doc.libsodium.org/public-key_cryptography/sealed_boxes[libsodium's documentation, sealed boxes]) |`+box_sodium+`, `+default_backend_none_linked+` + +|ElligatorSwift +|native, wasip2, wasip3, emscripten +|libsecp256k1 +|the only backend (link:https://github.com/bitcoin-core/secp256k1#readme[libsecp256k1's README]) +|`+secp256k1_ellswift+`, `+default_backend_none_linked+` + +|MuSig2 +|native, wasip2, wasip3, emscripten +|libsecp256k1 +|the only backend (link:https://github.com/bitcoin-core/secp256k1#readme[libsecp256k1's README]) +|`+secp256k1_musig+`, `+default_backend_none_linked+` + +|BIP 352 silent payments +|native, wasip2, wasip3, emscripten +|libsecp256k1 +|the only backend (link:https://github.com/bitcoin-core/secp256k1#readme[libsecp256k1's README]) +|`+secp256k1_silent_payments+`, `+default_backend_none_linked+` |=== diff --git a/doc/generated/jamfiles.adoc b/doc/generated/jamfiles.adoc index 03be07f9..c46be348 100644 --- a/doc/generated/jamfiles.adoc +++ b/doc/generated/jamfiles.adoc @@ -247,6 +247,54 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secp256k1_default/secp256k1_default.outcome[tag=output] ---- +`+secp256k1_ellswift_default+`:: Two key pairs' ElligatorSwift encodings, each decoded to its public key, and both sides of BIP 324's exchange agreeing, on ElligatorSwift's default on every target, with the one line `+/webcpp/crypto//secp256k1_ellswift-default+`, which links libsecp256k1. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secp256k1_ellswift_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secp256k1_ellswift_default/secp256k1_ellswift_default.outcome[tag=output] +---- + +`+secp256k1_musig_default+`:: Two key pairs' public keys aggregated with BIP 327's MuSig2, a message signed in its two rounds and the aggregate verified as one BIP 340 signature, on MuSig2's default on every target, with the one line `+/webcpp/crypto//secp256k1_musig-default+`, which links libsecp256k1. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secp256k1_musig_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secp256k1_musig_default/secp256k1_musig_default.outcome[tag=output] +---- + +`+secp256k1_silent_payments_default+`:: A BIP 352 silent payments recipient, its scan and spend keys, paid from one input and the payment found by a scan of the output, on silent payments' default on every target, with the one line `+/webcpp/crypto//secp256k1_silent_payments-default+`, which links libsecp256k1. ++ +Its Jamfile, built and run on native, wasip2, wasip3, emscripten: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secp256k1_silent_payments_default/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secp256k1_silent_payments_default/secp256k1_silent_payments_default.outcome[tag=output] +---- + `+secretbox_xchacha20poly1305_default+`:: A case of libsodium's XChaCha20 secret boxes, sealed and opened on its default on every target, with the one line `+/webcpp/crypto//secretbox_xchacha20poly1305-default+`, which links libsodium. + Its Jamfile, built and run on native, wasip2, wasip3, emscripten: diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index b63d68eb..795f8f4e 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+`, `+secp256k1_recovery+` |`+curves::secp256k1::verify_schnorr+`, `+verify_ecdsa+` |libsecp256k1 @@ -190,6 +190,41 @@ |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+` + +|`+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+` + +|`+curves::secp256k1::ellswift_encode+`, `+ellswift_decode+`, `+ellswift_create+`, `+ellswift_xdh+` +|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+` + +|`+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. @@ -365,4 +400,46 @@ 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 + +|`+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 + +|`+curves::secp256k1::ellswift_encode+`, `+ellswift_decode+`, `+ellswift_create+`, `+ellswift_xdh+` +|libsecp256k1 +|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 + +|`+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/messages.adoc b/doc/generated/messages.adoc index 58dd2f67..e76f17c0 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -109,6 +109,12 @@ The fix: Leave the policy out, as in `+curves::ed25519::verify(public_key, messa The fix: Name `+curves::ed25519::ph+`: RFC 8032 defines Ed25519ph over SHA-512. +|`+ellswift_other_backend+` +|native, wasip2 +|`+webcpp::crypto: bearssl has no ElligatorSwift. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).+` + +The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::ellswift_decode(encoded_key)+`. + |`+gcm_default_openssl_not_linked+` |native |`+webcpp::crypto: AES-GCM's default backend on this target is OpenSSL, 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_OPENSSL=1 and link libcrypto)+` @@ -139,6 +145,24 @@ The fix: As `+heavy_without_threads+`. The fix: Add `+/webcpp/crypto//kx-default+`, which links `+/third_party//sodium+` on every target. +|`+label_lookup_by_value+` +|native, wasip2 +|`+no matching function for call to 'scan_outputs'+` + +The fix: Return `+std::optional>+`, a span over a tweak the lookup keeps, such as a map's entry; never the tweak by value. + +|`+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. + +|`+musig_other_backend+` +|native, wasip2 +|`+webcpp::crypto: bearssl has no MuSig2. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).+` + +The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::musig::parse_public_nonce(encoded_nonce)+`. + |`+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)+` @@ -189,7 +213,7 @@ The fix: Add `+/third_party//secp256k1+`. |`+secp256k1_other_backend+` |native, wasip2 -|`+webcpp::crypto: curves::secp256k1 runs on libsecp256k1 alone. Name backends::secp256k1, or leave the backend out, as in curves::secp256k1::keypair.+` +|`+webcpp::crypto: bearssl has no secp256k1. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).+` The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::keypair+`. @@ -199,6 +223,12 @@ The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp2 The fix: Give `+secret+` the number of bytes it holds, at least one, as in `+secret<32>+`. +|`+silent_payments_other_backend+` +|native, wasip2 +|`+webcpp::crypto: bearssl has no BIP 352 silent payments. The backends that have it: secp256k1 (native, wasip2, wasip3, emscripten).+` + +The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::silent_payments::make_prevouts_summary(...)+`. + |`+sodium_not_linked+` |native, wasip2, wasip3 |`+webcpp::crypto: the backend libsodium is used and not linked. In the program's Jamfile, add /third_party//sodium beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//sodium ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` @@ -920,6 +950,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Name `+curves::ed25519::ph+`: RFC 8032 defines Ed25519ph over SHA-512. +|`+ellswift_other_backend+` +|the compile +|Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::ellswift_decode(encoded_key)+`. + |`+gcm_default_openssl_not_linked+` |the compile |Natively the default is OpenSSL: add `+/webcpp/crypto//gcm-default+`, which links `+/webcpp/crypto//openssl+` there, or name BearSSL in the type, as in `+gcm>+`. @@ -936,6 +970,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Add `+/webcpp/crypto//kx-default+`, which links `+/third_party//sodium+` on every target. +|`+label_lookup_by_value+` +|the compile +|Return `+std::optional>+`, a span over a tweak the lookup keeps, such as a map's entry; never the tweak by value. + |`+memory_missing_definition_install+` |the link |Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. @@ -948,6 +986,14 @@ 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. + +|`+musig_other_backend+` +|the compile +|Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::musig::parse_public_nonce(encoded_nonce)+`. + |`+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. @@ -976,6 +1022,10 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Give `+secret+` the number of bytes it holds, at least one, as in `+secret<32>+`. +|`+silent_payments_other_backend+` +|the compile +|Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::silent_payments::make_prevouts_summary(...)+`. + |`+sodium_not_linked+` |the compile |Add `+/third_party//sodium+`. diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index 4bafb223..a1abcebb 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, recoverable signatures, ECDH in three forms, tweaks, ElligatorSwift, MuSig2, silent payments, 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,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, 64 bytes as ElligatorSwift (link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol]); 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 |Signature sizes -|64 bytes; ECDSA in DER up to 72 +|64 bytes, MuSig2's aggregate too (link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures]); 65 bytes recoverable; ECDSA in DER up to 72 |64 bytes |none: no signatures @@ -37,12 +37,12 @@ |agreement of a secret key and a public key: native, libsodium 15.9 µs; wasip2, libsodium 40.4 µs; wasip3, libsodium 40.4 µs; emscripten, libsodium 35.5 µs (2026-11-19, Apple M5 Max; <>) |Constant time, measured -|libsecp256k1 (libsecp256k1's own `+ctime_tests.c+`): native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten (<>) +|libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `+ctime_tests.c+`, and webcpp's code around it: the key pair's making, its signatures and x-only tweak, ECDH in three forms, the secret key's tweaks and negation, and PKCS#8), MemorySanitizer (Linux, clang; the same paths as memcheck's) and dudect (`+ecdh_x+`), nothing found; wasip2, dudect (`+ecdh_x+`), nothing found; not measured yet on wasip3, emscripten (<>) |libsodium: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect, nothing found; wasip2, dudect, nothing found; not measured yet on wasip3, emscripten (<>) |libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found, and dudect: nothing found with arm64's DIT (data-independent timing) bit set, as the lane runs dudect on macOS and Linux on arm64 (elsewhere its harness sets no DIT) and as Apple requires of constant-time code (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]); without it, dudect times `agree` with an all-zero secret key against random ones at \|t\| 6.7 to 14.5, against the threshold 10, on an Apple M5 Max, from a release build (2026-11-19): about one nanosecond in 15 µs. libsodium does not set DIT: a program on Apple silicon sets it around its secret operations (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]); wasip2, dudect: an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at \|t\| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads \|t\| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next; not measured yet on wasip3, emscripten (<>) |Standards -|link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1], link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979, deterministic ECDSA nonces] +|link:https://www.secg.org/sec2-v2.pdf[SEC 2, Recommended Elliptic Curve Domain Parameters], link:https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki[BIP 340, Schnorr signatures for secp256k1], link:https://www.rfc-editor.org/rfc/rfc6979[RFC 6979, deterministic ECDSA nonces], link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol], link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures], link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352, Silent Payments] |link:https://www.rfc-editor.org/rfc/rfc8032[RFC 8032, the Edwards-curve Digital Signature Algorithm (EdDSA)], link:https://csrc.nist.gov/pubs/fips/186-5/final[FIPS 186-5, the Digital Signature Standard, which adds EdDSA] |link:https://www.rfc-editor.org/rfc/rfc7748[RFC 7748, Elliptic Curves for Security (X25519 and X448)] @@ -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]); 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]), in DER or PEM (link:https://www.rfc-editor.org/rfc/rfc7468[RFC 7468, textual encodings of PKIX, PKCS and CMS structures (PEM)]); Bitcoin's version 2 transport, whose keys are ElligatorSwift encodings (link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324, version 2 P2P encrypted transport protocol]); MuSig2's multisignatures (link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327, MuSig2 for BIP340-compatible multi-signatures]); silent payments (link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352, Silent Payments]), the addresses and transactions being a domain library's |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/namespace-root.adoc b/doc/generated/namespace-root.adoc index a32f5422..12d8cb36 100644 --- a/doc/generated/namespace-root.adoc +++ b/doc/generated/namespace-root.adoc @@ -43,6 +43,6 @@ |you need a random number an attacker must not predict; never `std::mt19937` or `rand` (link:https://cwe.mitre.org/data/definitions/338.html[CWE-338, a weak generator used for security]) |you compare anything secret; never `==` or `memcmp` on a MAC |you branch on a failure: forged data, a wrong size, no entropy -|a key goes to or comes from a file, a form or a tool as `-----BEGIN PUBLIC KEY-----` text; with the `encode_spki` and `encode_pkcs8` of `curves::ed25519` or `curves::x25519` +|a key goes to or comes from a file, a form or a tool as `-----BEGIN PUBLIC KEY-----` text; with the `encode_spki` and `encode_pkcs8` of `curves::ed25519`, `curves::x25519` or `curves::secp256k1` |a native program on OpenSSL must allocate only from its own arena; on WebAssembly, BearSSL allocates nothing |=== diff --git a/doc/generated/sizes.adoc b/doc/generated/sizes.adoc index 0ce682ef..5d1d7391 100644 --- a/doc/generated/sizes.adoc +++ b/doc/generated/sizes.adoc @@ -49,6 +49,18 @@ The lane sizes measured on 2026-11-19, at variant=release: native, clang-21 on D |+117,545 B, gzip +56,024 B |+85,827 B, gzip +34,071 B +|secp256k1 on libsecp256k1: x coordinate of the ECDH shared point with a peer's public key +|+117,152 B, gzip +81,857 B +|+214,304 B, gzip +84,102 B +|+216,049 B, gzip +84,945 B +|+175,258 B, gzip +63,047 B + +|secp256k1 on libsecp256k1: public key recovered from an ECDSA signature of a 32-byte hash +|+1,173,856 B, gzip +1,146,391 B +|+1,293,150 B, gzip +1,142,527 B +|+1,294,892 B, gzip +1,143,152 B +|+203,439 B, gzip +71,668 B + |Ed25519 on libsodium: signature of a 32-byte message |+86,440 B, gzip +64,421 B |+74,905 B, gzip +44,662 B @@ -132,6 +144,26 @@ The lane sizes measured on 2026-11-19, at variant=release: native, clang-21 on D |not measured yet |not measured yet |not measured yet + +|ElligatorSwift on libsecp256k1: BIP 324 shared secret of two ElligatorSwift encodings +|+133,528 B, gzip +98,241 B +|+272,419 B, gzip +103,703 B +|+274,172 B, gzip +104,395 B +|+229,445 B, gzip +82,050 B + +|MuSig2 on libsecp256k1: two-signer MuSig2 signature of a 32-byte message +|+1,206,992 B, gzip +1,167,336 B +|+1,353,199 B, gzip +1,161,626 B +|+1,354,601 B, gzip +1,162,560 B +|+250,718 B, gzip +90,694 B + +|BIP 352 silent payments on libsecp256k1: a silent payment output for one recipient +|+1,190,408 B, gzip +1,154,145 B +|+1,318,313 B, gzip +1,147,745 B +|+1,320,113 B, gzip +1,148,250 B +|+215,607 B, gzip +77,908 B |=== OpenSSL: its cells differ by a few bytes whatever the operation: each fetches its algorithm by name from OpenSSL's default provider (link:https://docs.openssl.org/3.5/man7/crypto/[OpenSSL 3.5's crypto(7), algorithm fetching]), and a static link brings the provider's algorithms with it, not the operation's alone. + +libsecp256k1: a row that recovers a key or computes with a public point other than the generator (`recover`, MuSig2's session, a silent payment's output) links the precomputed table of libsecp256k1's variable-time multiplication too, built at window 15 natively and on WASI and at window 2 on Emscripten, the small tables (link:https://github.com/bitcoin-core/secp256k1/blob/master/configure.ac[libsecp256k1's configure.ac, the precomputed tables' trade]). diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index a214f60a..8a4c9ec1 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -71,13 +71,63 @@ |<> |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+` +|<> + +|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+` +|<> + +|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+` +|<> + +|Store or exchange a secp256k1 key with OpenSSL or a config file +|In `+curves::secp256k1+`: `+encode_spki+`, `+decode_spki+`, `+encode_pkcs8+`, `+decode_pkcs8+`; `+webcpp::crypto::pem::armour+`, `+unarmour+` +|libsecp256k1, libsodium for PEM +|`+/webcpp/crypto//crypto+` + +`+/third_party//secp256k1+` + +`+/webcpp/crypto//pem-default+` +|<> + +|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+` +|<> + +|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 +|`+/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..a25acfff 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -1,6 +1,6 @@ # webcpp::crypto -> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only tweak), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. +> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. Generated by doc/tables/generate.py with the page's tables. Page: https://webcpporg.github.io/libs/crypto/ @@ -62,13 +62,17 @@ 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, 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). - 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. @@ -114,6 +118,57 @@ 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`. +- [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; `pem::armour` makes either PEM text. Header . Backends: libsecp256k1 (/third_party//secp256k1) on native, wasip2, wasip3, emscripten. Default: libsecp256k1 on native, wasip2, wasip3, emscripten. Use it to: store or exchange a secp256k1 key with OpenSSL or a config file. + - 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. +- [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. +- [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`). +- [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 a span over its tweak, in bytes the lookup owns, or `std::nullopt`, noexcept (no labels: the default). ## webcpp::crypto::hybrid @@ -149,12 +204,15 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - X25519-XSalsa20-Poly1305 box, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, NaCl's `crypto_box`, the same on every target ([libsodium's documentation, public-key authenticated encryption](https://doc.libsodium.org/public-key_cryptography/authenticated_encryption)). - X25519-XChaCha20-Poly1305 box, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, the same on every target ([libsodium's documentation, public-key authenticated encryption](https://doc.libsodium.org/public-key_cryptography/authenticated_encryption)). - X25519-XSalsa20-Poly1305 sealed box, native, wasip2, wasip3, emscripten: libsodium; the only backend that has it: libsodium's own C code, which draws the key pair of each message from its own generator, the same on every target ([libsodium's documentation, sealed boxes](https://doc.libsodium.org/public-key_cryptography/sealed_boxes)). +- ElligatorSwift, native, wasip2, wasip3, emscripten: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). +- MuSig2, native, wasip2, wasip3, emscripten: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). +- BIP 352 silent payments, native, wasip2, wasip3, emscripten: libsecp256k1; the only backend ([libsecp256k1's README](https://github.com/bitcoin-core/secp256k1#readme)). ## Constant time, measured - AES-GCM: BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect, nothing found; wasip2, dudect, nothing found; not measured yet on wasip3, emscripten. OpenSSL (seal alone: its open branches on the verdict inside OpenSSL): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3. - AES block cipher: OpenSSL: not measured yet. ctaes: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect, nothing found; wasip2, dudect, nothing found; not measured yet on wasip3, emscripten. -- secp256k1: libsecp256k1 (libsecp256k1's own `ctime_tests.c`): native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. +- secp256k1: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's code around it: the key pair's making, its signatures and x-only tweak, ECDH in three forms, the secret key's tweaks and negation, and PKCS#8), MemorySanitizer (Linux, clang; the same paths as memcheck's) and dudect (`ecdh_x`), nothing found; wasip2, dudect (`ecdh_x`), nothing found; not measured yet on wasip3, emscripten. - Ed25519: libsodium: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect, nothing found; wasip2, dudect, nothing found; not measured yet on wasip3, emscripten. - X25519: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found, and dudect: nothing found with arm64's DIT (data-independent timing) bit set, as the lane runs dudect on macOS and Linux on arm64 (elsewhere its harness sets no DIT) and as Apple requires of constant-time code ([Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations](https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations)); without it, dudect times `agree` with an all-zero secret key against random ones at |t| 6.7 to 14.5, against the threshold 10, on an Apple M5 Max, from a release build (2026-11-19): about one nanosecond in 15 µs. libsodium does not set DIT: a program on Apple silicon sets it around its secret operations ([Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations](https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations)); wasip2, dudect: an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at |t| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set ([Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations](https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations)): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads |t| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next; not measured yet on wasip3, emscripten. - crypto_kx: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. @@ -167,6 +225,9 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - X25519-XSalsa20-Poly1305 box: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. - X25519-XChaCha20-Poly1305 box: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. - X25519-XSalsa20-Poly1305 sealed box: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. +- ElligatorSwift: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `ellswift_create` and `ellswift_xdh` around it) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. +- MuSig2: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `nonce_gen` and `partial_sign` around it) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. +- BIP 352 silent payments: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's `create_outputs`, `create_label` and `scan_outputs` around it, each workspace's wipe included) and MemorySanitizer (Linux, clang; the same paths as memcheck's), nothing found; not measured yet on wasip2, wasip3, emscripten. ## Rules of use @@ -174,9 +235,9 @@ 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. -- [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. +- [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 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)). - [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. @@ -194,7 +255,14 @@ 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-p2p-nostr-dm): `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-wallets-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. +- [Store or exchange a secp256k1 key with OpenSSL or a config file](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-formats): `encode_spki`, `decode_spki`, `encode_pkcs8`, `decode_pkcs8`; `webcpp::crypto::pem::armour`, `unarmour` (webcpp::crypto::curves::secp256k1); backend libsecp256k1, libsodium for PEM; Jamfile /webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//pem-default. Example: example/secp256k1_key_formats.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-p2p-v2): `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-wallets-silent): `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-wallets-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. @@ -220,20 +288,29 @@ 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/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. - 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_network.cpp: The wallet of musig_wallet.cpp with its two devices apart: every public piece of BIP 327's MuSig2 crosses the network as bytes. Each device sends its public nonce, 66 bytes, to a coordinator, which holds no secret: it sums the nonces and sends the aggregate nonce, 66 bytes, back. Each device then signs and sends its partial signature, 32 bytes; the coordinator parses each part and checks it with partial_signature_verify before it adds the parts, so that a part damaged on the way, or a faulty signer's, is refused by name rather than spoiling the signature. The devices' secrets are fixed here, so that the program runs the same each time; the nonces are fresh in every run, and nothing random is printed. +- example/musig_taproot.cpp: The wallet of musig_wallet.cpp receiving to a Taproot output (BIP 341) with a key path only: the two signers' aggregate key is the internal key, and the output key on the chain is that key tweaked by its TapTweak tagged hash. The tweak is applied to the aggregate key with tweak_xonly_add before any nonce is made, since the session and the partial signatures need the key as tweaked, and nonce_gen mixes in the key it is given (BIP 327's NonceGen takes it only as an optional input); then the signers run MuSig2's two rounds as before, and the signature verifies under the output key and not under the internal one. The tweak's hash is the protocol's, which a domain library computes; it is shown here with webcpp::hash's SHA-256. The devices' secrets are fixed here, so that the program runs the same each time; the nonces are fresh in every run, and nothing random is printed. +- 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. - 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. +- example/secp256k1_key_formats.cpp: A server's secp256k1 key in files that OpenSSL also reads: its public key written as PEM SPKI for a configuration file that its clients read, and read back; its key pair written as PEM PKCS#8 for the server's own key file, which is never printed, and read back. The secret is the fixed 0x11 repeated, so that the output is fixed: a real server draws its own. - 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/memory.adoc b/doc/memory.adoc index 9986b01d..f4d53d64 100644 --- a/doc/memory.adoc +++ b/doc/memory.adoc @@ -14,9 +14,15 @@ 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` and the verifications. The counting tests of `test/` prove it, every -`operator new` and the C library's allocator counted. +`begin_seal`, `update`, `result`, `encrypt`, `decrypt`, `fill`, the signatures +(hedged and recoverable too), `ecdh`, `ecdh_x`, `ecdh_point`, the verifications, +`recover`, `parse_public_key`, `serialize_public_key`, the tweaks and negations, +`pubkey_combine` (in a `workspace` the caller lends), the SPKI and PKCS#8 +encoders and decoders (`decode_pkcs8` makes a key pair, whose context is the one +allocation above), and `ellswift_*`, MuSig2's functions and silent payments' +(each over a `workspace` the caller lends, where it takes one). 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/p2p.adoc b/doc/p2p.adoc index 54bd16f8..052525c9 100644 --- a/doc/p2p.adoc +++ b/doc/p2p.adoc @@ -151,6 +151,86 @@ 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` (<>). + +[#crypto-p2p-nostr-dm] +=== A shared key in Nostr's direct messages + +*The problem.* A Nostr chat app sends a private message to a contact through +public relays, which keep every event and serve it to anyone who asks. The two +users know each other only by their public keys, the secp256k1 keys that sign +their notes. + +*The idea.* Each side combines its secret key with the other's public key, an +ECDH, and both find the same shared point. Nostr's encrypted payloads take its +x coordinate unhashed, and derive from it a conversation key, HKDF-extract +with the salt `nip44-v2`, then a key for each message +(link:https://github.com/nostr-protocol/nips/blob/master/44.md[NIP-44]). +`ecdh_x` gives the x coordinate as a `secret<32>` +(<>); the conversation key and everything after it, +the message keys, the padding and the payload's format, are NIP-44's, which a +domain library built on crypto and hash, such as a future webcpp::nostr, +derives. The example computes the conversation key only to show where the x +coordinate goes: + +[source,cpp] +---- +include::{examples}/ecdh_x_coordinate.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/ecdh_x_coordinate.expected[] +---- + +This section names no application. + +*Mistakes to avoid.* Hashing the x coordinate differently on the two sides: +`ecdh` hashes the compressed shared point with SHA-256, libsecp256k1's +default, and a side that uses it while the other takes the raw x coordinate +gets another key, so that every message fails to open with nothing pointing at +the cause. Reusing the conversation key as a message key: it is the same for +every message between the two users, in both directions; NIP-44 derives each +message's keys from it and a fresh 32-byte nonce, and a program that encrypts +with the conversation key itself repeats its keys across messages. + +[#crypto-p2p-v2] +=== A handshake an observer cannot recognise + +*The problem.* A node of a peer-to-peer network, a Bitcoin node or a +messenger, opens connections that a box on the path may want to recognise and +block. A handshake that starts with a public key is easy to spot: a compressed +key begins with 02 or 03, and its next 32 bytes are always the x coordinate of +a point of the curve, which only about half of all random strings are. + +*The idea.* Bitcoin's version 2 transport sends each peer's key as an +ElligatorSwift encoding instead: 64 bytes, made from the key pair and fresh +randomness, that cannot be told from random ones; both peers compute the same +secret from the two encodings +(link:https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki[BIP 324]; +<>). The secret feeds the protocol's key schedule; +that schedule and the protocol's packets are BIP 324's, a domain library's. + +[source,cpp] +---- +include::{examples}/ellswift_handshake.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/ellswift_handshake.expected[] +---- + +The encodings hide that a key exchange happens, not who takes part: both peers' +addresses stay visible to whoever watches the connection. This section names no +application. + +*Mistakes to avoid.* Draw fresh randomness for every encoding: the same key +with the same randomness gives the same 64 bytes, which links two connections +of one node. Pass the two encodings in the protocol's order, the initiator's +first, and name the right party: a side that passes them in its own order +computes another secret, and the connection fails with nothing pointing at the +cause. Never use the secret as a key by itself: BIP 324 derives its session's +keys from it with HKDF. diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index acd87098..9569a0ef 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -24,26 +24,60 @@ 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; -* *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. +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 +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 -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. +else (<>). The namespace's functions, by header: + +* ``: the key pair's `make`, its public +keys (`xonly_public_key`, `public_key`, `public_key_uncompressed`), its +signatures (`sign_schnorr`, `sign_ecdsa`, hedged or not, and +`sign_recoverable`), its ECDH (`ecdh`, `ecdh_x`, `ecdh_point`) and its tweak +in place (`tweak_xonly`); `verify_schnorr` and `verify_ecdsa`, which check a +signature with a public key alone; `recover`, which finds the key of a +recoverable signature (<>); `parse_public_key` +and `serialize_public_key`, which read and write a `public_key` +(<>); `to_der`, `from_der` (strict DER) and +`normalize_ecdsa`, ECDSA's DER and low-S forms; and `tweak_xonly`, the tweak +of an x-only public key; +* ``: `seckey_tweak_add`, +`seckey_tweak_mul` and `seckey_negate`, `pubkey_tweak_add`, +`pubkey_tweak_mul` and `pubkey_negate`, and `pubkey_combine` with its +`combine_workspace_size`: the tweaks, negation and combination of whole keys +(<>); +* ``: `encode_spki`, +`decode_spki`, `encode_pkcs8` and `decode_pkcs8`, the keys' SPKI and PKCS#8, +which `pem` writes as PEM text (<>); +* ``: `ellswift_create`, +`ellswift_encode`, `ellswift_decode` and `ellswift_xdh`, keys sent as +random-looking bytes (<>); +* ``, namespace `musig`: +`key_aggregate` (and the aggregate key's `xonly_public_key`, +`full_public_key`, `tweak_add` and `tweak_xonly_add`), `nonce_gen`, +`nonce_aggregate`, `nonce_process`, `partial_sign`, +`partial_signature_verify` and `partial_signature_aggregate`, +the `parse_` and `serialize_` functions of the public nonce, the aggregate +nonce and the partial signature, and `workspace_size`: many signers' one +signature (<>); +* ``, namespace +`silent_payments`: `create_outputs`, `create_label`, +`create_labeled_spend_key`, `make_prevouts_summary` and `scan_outputs`, with +`send_workspace_size`, `summary_workspace_size` and `scan_workspace_size`: +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[] @@ -87,3 +121,655 @@ 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[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 +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]). 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 +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. + +[#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, PKCS#8 and PEM + +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: 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, +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. + +A configuration file, a terminal or a form carries text, not DER. PEM is the +DER in base64 between a `-----BEGIN PUBLIC KEY-----` or +`-----BEGIN PRIVATE KEY-----` line and its `-----END` line +(link:https://www.rfc-editor.org/rfc/rfc7468[RFC 7468]), the form OpenSSL's +`-pubout` and `genpkey` write. `pem::armour` and `pem::unarmour` +(``, <>) write and read it around +these functions' bytes, with the labels `pem::public_key_label` and +`pem::private_key_label`, as strictly as the decoders read DER: another label, +lines of another length than 64 or a carriage return are `invalid_encoding`. +PEM needs libsodium's target, whose base64 runs in a time that does not depend +on the bytes, those of a private key included: a program that writes or reads +PEM links `/webcpp/crypto//pem-default` (or `/third_party//sodium`) beside +`/third_party//secp256k1`. The tests compare the text that `pem::armour` +writes with that of OpenSSL's `PEM_write_bio_PUBKEY` and +`PEM_write_bio_PrivateKey`, character for character. + +include::generated/backends-key_formats.adoc[] + +*Example.* A server's key pair from the fixed secret `0x11` repeated: its +public key written as PEM SPKI for a configuration file and read back, and its +key pair written as PEM PKCS#8 for its own key file, never printed, and read +back: + +[source,cpp] +---- +include::{examples}/secp256k1_key_formats.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/secp256k1_key_formats.expected[] +---- + +*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 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, and so does +its PEM text: base64 is an encoding, not encryption. Keep both where only the +program reads them, out of source control, or seal them at rest +(<>), and wipe the buffers when done, as `secret` does. + +[#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. + +[#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 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[] + +*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[] +---- + +*Example.* The same wallet with its devices apart. Every public piece crosses +the network as bytes: each public nonce in 66, the aggregate nonce a +coordinator sums in 66, each partial signature in 32. The coordinator, which +holds no secret, parses each part and checks it with +`partial_signature_verify` before it adds the parts, so that a part damaged on +the way is refused by name: + +[source,cpp] +---- +include::{examples}/musig_network.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/musig_network.expected[] +---- + +*Example.* The wallet's aggregate key as the internal key of a Taproot output +spent by its key path +(link:https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki[BIP 341]). +`tweak_xonly_add` tweaks it by its TapTweak tagged hash before any nonce is +made, since the session and the partial signatures need the key as tweaked, +and `nonce_gen` mixes in the key it is given (BIP 327's NonceGen takes it only +as an optional input); the signature then verifies under the output key and +not under the internal one. +The hash is the protocol's, a domain library's to compute; the example shows +it with webcpp::hash's SHA-256: + +[source,cpp] +---- +include::{examples}/musig_taproot.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/musig_taproot.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`. + +[#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 exactly +`std::optional>`: a span over the label's +tweak, in bytes the lookup owns for the call, since libsecp256k1 reads them +after it returns, or `std::nullopt`. A tweak returned by value is refused at +compile time. + +`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]). +* A wallet always scans for the change label, recovery from a seed included, +whether it made other labels or not +(link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352]). +`scan_outputs` defaults to `no_labels`: a wallet that scans so misses every +change output it sent itself, and its balance looks short. +* 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. On Emscripten the stack is 64 KiB by +default and cannot grow, and a program built without assertions that +overruns it fails silently, with no check of overflows by default +(link:https://emscripten.org/docs/tools_reference/settings_reference.html[Emscripten's settings reference]): +the workspace then overwrites the program's other memory instead of +stopping it. +On wasip2 and wasip3 the stack is likewise a region of the linear memory +that grows downward +(link:https://github.com/WebAssembly/tool-conventions/blob/main/BasicCABI.md[the WebAssembly tool conventions' basic C ABI]); +this page states no default size and no overflow behaviour for it, so a +workspace of more than a few recipients or outputs belongs on the heap there +too. diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index f8f43b63..92520917 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1,7 +1,7 @@ { "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (X25519 on wasip2, an open finding, and natively without arm64's DIT, the cause of both), with `constant_time_checker` naming the checker that measured it where that is not every checker of the target, and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it (a row of some of `compilers` restates its target's default for them, with a reason of their own, and each compiler of a target has one row), from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. A comparison table's cell {speed:} or {constant_time:} is written from doc/performance.json or from the family's `constant_time`, and each cell of a column a namespace lists in `cited` cites a source or begins with \"none\". Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", "page": "https://webcpporg.github.io/libs/crypto/", - "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA, ECDH, the x-only tweak), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", + "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator and a constant-time equal, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", "targets": ["native", "wasip2", "wasip3", "emscripten"], "compilers": {"clang": "Clang", "gcc": "GCC", "msvc": "MSVC"}, "checkers": {"memcheck": "Valgrind's memcheck (Linux)", "msan": "MemorySanitizer (Linux, clang)", "dudect": "dudect"}, @@ -104,7 +104,19 @@ "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"], + "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/"], + "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"], + "emscripten-settings": ["Emscripten's compiler settings reference: STACK_SIZE (64 KiB, fixed) and STACK_OVERFLOW_CHECK", "https://emscripten.org/docs/tools_reference/settings_reference.html"] }, "backends": { "bearssl": { @@ -158,7 +170,8 @@ "own_api": "`` and its modules", "allocation": "`keypair::make` allocates the signing context, once, in the `std::pmr::memory_resource` it is given; nothing else allocates", "constant_time": "by design: signing and key generation are constant time and constant memory access", - "constant_time_sources": ["libsecp256k1"] + "constant_time_sources": ["libsecp256k1"], + "size_note": "a row that recovers a key or computes with a public point other than the generator (`recover`, MuSig2's session, a silent payment's output) links the precomputed table of libsecp256k1's variable-time multiplication too, built at window 15 natively and on WASI and at window 2 on Emscripten, the small tables ({secp256k1-configure})." }, "sodium": { "without_b2": "link libsodium built with webcpp's src/canary_sodium.c", @@ -273,13 +286,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", "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 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"]}} + "backends": {"secp256k1": {"tests": ["secp256k1", "secp256k1_bip340", "secp256k1_xonly_tweak", "secp256k1_ecdh", "secp256k1_recovery"]}} }, { "id": "verify", @@ -549,6 +562,89 @@ "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"]}} + }, + { + "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; `pem::armour` makes either PEM text.", + "section": "crypto-secp256k1-formats", + "backends": {"secp256k1": {"tests": ["secp256k1_formats", "secp256k1_formats_openssl"]}} + }, + { + "id": "ellswift", + "family": "secp256k1_ellswift", + "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"]}} + }, + { + "id": "musig", + "family": "secp256k1_musig", + "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"]}} + }, + { + "id": "silent_payments", + "family": "secp256k1_silent_payments", + "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": [ @@ -602,6 +698,7 @@ "group": "curves::secp256k1", "since": "0.1", "measured": "BIP340 signature of a 32-byte message", + "sized_operations": {"ecdh_x": "x coordinate of the ECDH shared point with a peer's public key", "recover": "public key recovered from an ECDSA signature of a 32-byte hash"}, "header": "", "names": [ {"name": "secp256k1", "title": "secp256k1", "type": "curves::secp256k1::basic_keypair<{backend}>"} @@ -610,7 +707,7 @@ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "secp256k1", "tests": ["secp256k1", "default_backend_none_linked"], "why": "the only backend ({libsecp256k1})"} ], "backends": { - "secp256k1": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}, "lane_note": "libsecp256k1's own `ctime_tests.c`"} + "secp256k1": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "lane_note": {"memcheck": "libsecp256k1's own `ctime_tests.c`, and webcpp's code around it: the key pair's making, its signatures and x-only tweak, ECDH in three forms, the secret key's tweaks and negation, and PKCS#8", "msan": "the same paths as memcheck's", "dudect": "`ecdh_x`"}} } }, { @@ -822,6 +919,57 @@ "backends": { "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan"]}} } + }, + { + "name": "secp256k1_ellswift", + "title": "ElligatorSwift", + "group": "curves", + "since": "0.2", + "measured": "BIP 324 shared secret of two ElligatorSwift encodings", + "header": "", + "names": [ + {"name": "secp256k1_ellswift", "title": "ElligatorSwift"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "secp256k1", "tests": ["secp256k1_ellswift", "default_backend_none_linked"], "why": "the only backend ({libsecp256k1})"} + ], + "backends": { + "secp256k1": {"targets": "all", "runtime": false, "lane": {"native": ["memcheck", "msan"]}, "lane_note": {"memcheck": "libsecp256k1's own `ctime_tests.c`, and webcpp's `ellswift_create` and `ellswift_xdh` around it", "msan": "the same paths as memcheck's"}} + } + }, + { + "name": "secp256k1_musig", + "title": "MuSig2", + "group": "curves", + "since": "0.2", + "measured": "two-signer MuSig2 signature of a 32-byte message", + "header": "", + "names": [ + {"name": "secp256k1_musig", "title": "MuSig2"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "secp256k1", "tests": ["secp256k1_musig", "default_backend_none_linked"], "why": "the only backend ({libsecp256k1})"} + ], + "backends": { + "secp256k1": {"targets": "all", "runtime": false, "lane": {"native": ["memcheck", "msan"]}, "lane_note": {"memcheck": "libsecp256k1's own `ctime_tests.c`, and webcpp's `nonce_gen` and `partial_sign` around it", "msan": "the same paths as memcheck's"}} + } + }, + { + "name": "secp256k1_silent_payments", + "title": "BIP 352 silent payments", + "group": "curves", + "since": "0.2", + "measured": "a silent payment output for one recipient", + "header": "", + "names": [ + {"name": "secp256k1_silent_payments", "title": "BIP 352 silent payments"} + ], + "default": [ + {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "secp256k1", "tests": ["secp256k1_silent_payments", "default_backend_none_linked"], "why": "the only backend ({libsecp256k1})"} + ], + "backends": { + "secp256k1": {"targets": "all", "runtime": false, "lane": {"native": ["memcheck", "msan"]}, "lane_note": {"memcheck": "libsecp256k1's own `ctime_tests.c`, and webcpp's `create_outputs`, `create_label` and `scan_outputs` around it, each workspace's wipe included", "msan": "the same paths as memcheck's"}} + } } ], "rules": [ @@ -829,9 +977,9 @@ {"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": "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": "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 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})."}, {"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."}, @@ -859,7 +1007,7 @@ ["`random_device`", "Keys, IVs, tokens, nonces: every secret a program draws", "``", "`entropy_unavailable`, `errc::not_supported`", "{getentropy}, {bcryptgenrandom}, {getrandomvalues}, {wasi-random}", "you need a random number an attacker must not predict; never `std::mt19937` or `rand` ({cwe338})"], ["`equal`", "Checking a tag, a MAC or a token", "``", "none: it returns `bool`", "{cwe208}", "you compare anything secret; never `==` or `memcmp` on a MAC"], ["`error`", "Telling failures apart", "``", "its values are the errors", "none", "you branch on a failure: forged data, a wrong size, no entropy"], - ["`pem`", "A key's SPKI or PKCS#8 as text, to paste, store or exchange with OpenSSL", "``", "`invalid_encoding`, `invalid_input_size`", "{rfc7468}, {libsodium-base64}", "a key goes to or comes from a file, a form or a tool as `-----BEGIN PUBLIC KEY-----` text; with the `encode_spki` and `encode_pkcs8` of `curves::ed25519` or `curves::x25519`"], + ["`pem`", "A key's SPKI or PKCS#8 as text, to paste, store or exchange with OpenSSL", "``", "`invalid_encoding`, `invalid_input_size`", "{rfc7468}, {libsodium-base64}", "a key goes to or comes from a file, a form or a tool as `-----BEGIN PUBLIC KEY-----` text; with the `encode_spki` and `encode_pkcs8` of `curves::ed25519`, `curves::x25519` or `curves::secp256k1`"], ["`openssl_memory_resource`", "Keeping every allocation of OpenSSL's in the program's own resource, natively", "``", "`memory_functions_refused`, `memory_functions_not_installed`", "{openssl-mem}", "a native program on OpenSSL must allocate only from its own arena; on WebAssembly, BearSSL allocates nothing"] ] }, @@ -887,7 +1035,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, recoverable signatures, ECDH in three forms, tweaks, ElligatorSwift, MuSig2, silent payments, SPKI and PKCS#8", "about 128 bits ({sec2})", "secret 32 bytes; public 33 bytes compressed, 65 bytes uncompressed ({sec1}), 32 bytes x-only, 64 bytes as ElligatorSwift ({bip324}); SPKI 56 or 88 bytes ({rfc5480}), PKCS#8 135 bytes ({rfc5208}, {rfc5915})", "64 bytes, MuSig2's aggregate too ({bip327}); 65 bytes recoverable; ECDSA in DER up to 72", "{speed:secp256k1}", "{constant_time:secp256k1}", "{sec2}, {bip340}, {rfc6979}, {bip324}, {bip327}, {bip352}", "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}), in DER or PEM ({rfc7468}); Bitcoin's version 2 transport, whose keys are ElligatorSwift encodings ({bip324}); MuSig2's multisignatures ({bip327}); silent payments ({bip352}), the addresses and transactions being a domain library's"], ["`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 +1061,14 @@ {"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-p2p-nostr-dm", "answers": "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-wallets-recovery", "answers": "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": "Store or exchange a secp256k1 key with OpenSSL or a config file", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`encode_spki`, `decode_spki`, `encode_pkcs8`, `decode_pkcs8`; `webcpp::crypto::pem::armour`, `unarmour`", "backend": "libsecp256k1, libsodium for PEM", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1 /webcpp/crypto//pem-default", "example": "secp256k1_key_formats", "section": "crypto-secp256k1-formats"}, + {"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-p2p-v2", "answers": "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-wallets-silent", "answers": "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-wallets-musig", "answers": "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"}, @@ -941,6 +1096,9 @@ "gcm_default": "AES-256-GCM on its default on every target, with the one line `/webcpp/crypto//gcm-default`, which links OpenSSL natively and BearSSL on WebAssembly; the same program as `web`.", "openssl_linked": "OpenSSL, built from source, named in the type: natively and on WASI.", "secp256k1_default": "BIP 340's first test vector, signed and verified on secp256k1's default on every target, with the one line `/webcpp/crypto//secp256k1-default`, which links libsecp256k1.", + "secp256k1_ellswift_default": "Two key pairs' ElligatorSwift encodings, each decoded to its public key, and both sides of BIP 324's exchange agreeing, on ElligatorSwift's default on every target, with the one line `/webcpp/crypto//secp256k1_ellswift-default`, which links libsecp256k1.", + "secp256k1_musig_default": "Two key pairs' public keys aggregated with BIP 327's MuSig2, a message signed in its two rounds and the aggregate verified as one BIP 340 signature, on MuSig2's default on every target, with the one line `/webcpp/crypto//secp256k1_musig-default`, which links libsecp256k1.", + "secp256k1_silent_payments_default": "A BIP 352 silent payments recipient, its scan and spend keys, paid from one input and the payment found by a scan of the output, on silent payments' default on every target, with the one line `/webcpp/crypto//secp256k1_silent_payments-default`, which links libsecp256k1.", "ed25519_default": "RFC 8032's first Ed25519 test, signed and verified on Ed25519's default on every target, with the one line `/webcpp/crypto//ed25519-default`, which links libsodium.", "x25519_default": "RFC 7748's shared secret on X25519's default on every target, with the one line `/webcpp/crypto//x25519-default`, which links libsodium.", "kx_default": "libsodium's `crypto_kx` test, the client's and the server's session keys from each other's public key, on its default on every target, with the one line `/webcpp/crypto//kx-default`, which links libsodium.", @@ -1013,6 +1171,11 @@ "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.", + "ellswift_other_backend": "Name `backends::secp256k1`, or leave the backend out: `curves::secp256k1::ellswift_decode(encoded_key)`.", + "musig_other_backend": "Name `backends::secp256k1`, or leave the backend out: `curves::secp256k1::musig::parse_public_nonce(encoded_nonce)`.", + "silent_payments_other_backend": "Name `backends::secp256k1`, or leave the backend out: `curves::secp256k1::silent_payments::make_prevouts_summary(...)`.", + "label_lookup_by_value": "Return `std::optional>`, a span over a tweak the lookup keeps, such as a map's entry; never the tweak by value.", "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/doc/tables/generate.py b/doc/tables/generate.py index 6d69c325..9af2cffb 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -612,6 +612,21 @@ def doc_comment(text: str) -> List[str]: return ['/**'] + [f' * {line}' for line in textwrap.wrap(text, 97)] + [' */'] +def possessive(title: str) -> str: + """A title in the possessive: an apostrophe alone after an s, else 's.""" + return title + ("'" if title.endswith('s') else "'s") + + +def namespace_of(family: Data) -> str: + """The namespace a family's comment names: its group, or, where its header's directory is + deeper inside that group (curves/secp256k1/ellswift.hpp for the group `curves`), that + directory's namespace.""" + directory = family['header'].strip('<>').split('/')[2:-1] + deeper = '::'.join(directory) + group = family['group'] + return deeper if deeper.startswith(group + '::') else group + + def program_type(data: Data, written: str, backend: str) -> str: """A type of crypto.json, written from webcpp::crypto, as the generated test names it: each of crypto's namespaces that starts a name is reached through `crypto::`, and `{backend}` is @@ -652,10 +667,10 @@ def capabilities_header(data: Data) -> str: algorithms = [entry['name'] for entry in family['names']] listed = ', '.join(f'`{tag_of(family, name)}`' for name in algorithms) if algorithms == [family['name']]: - text = (f'The family {family["title"]}, of `{family["group"]}`, also the tag of its ' - 'one algorithm.') + text = (f'The family {family["title"]}, of `{namespace_of(family)}`, also the tag of ' + 'its one algorithm.') else: - text = (f'The family {family["title"]}, of `{family["group"]}`; its algorithms: ' + text = (f'The family {family["title"]}, of `{namespace_of(family)}`; its algorithms: ' f'{listed}.') out += doc_comment(text) + [f'struct {family["name"]};', ''] named += [(family, entry) for entry in family['names'] if entry['name'] != family['name']] @@ -743,8 +758,8 @@ def capabilities_header(data: Data) -> str: lines.append(f'static_assert({known}, "webcpp::crypto: {family["title"]} has no ' f'backend of that name. The backends that have it: {have}.")') out.append(opening([target], index == 0)) - out += doc_comment(f'The refusals of the family {family["title"]}\'s primary engine ' - f'for `Backend`, on {target}.') + [ + out += doc_comment(f'The refusals of the family {possessive(family["title"])} primary ' + f'engine for `Backend`, on {target}.') + [ f'#define WEBCPP_CRYPTO_DETAIL_REFUSE_{family["name"].upper()}(Backend) \\'] out += [f' {line}; \\' for line in lines[:-1]] + [f' {lines[-1]}'] out.append('#endif') @@ -770,7 +785,7 @@ def needs(data: Data, family: Data, target: str, backend: str) -> str: of a backend not linked, what a build without b2 defines and links. The text holds on every target where the default is that backend, so that one message test checks it on each.""" facts = data['backends'][backend] - head = (f'webcpp::crypto: {family["title"]}\'s default backend on this target is ' + head = (f'webcpp::crypto: {possessive(family["title"])} default backend on this target is ' f'{facts["title"]}, which is not linked') alias = f'/webcpp/crypto//{family["name"]}-default' add = (f'Add {alias}, the default\'s library on every target, to the program\'s Jamfile, as ' @@ -932,8 +947,9 @@ def defaults_header(data: Data) -> str: def capabilities_test(data: Data) -> str: """test/capabilities_test.cpp: `supports_v` of every cell on the target being compiled, each - present cell made through its family's own type where its backend is linked, and each - family's refusal parsed.""" + present cell made through its family's own type where its backend is linked (a family of + free functions, whose names give no `type`, has none to make), and each family's refusal + parsed.""" tags = tags_of(data) headers = sorted({family['header'] for family in data['families']} | {'', ''}) @@ -979,6 +995,9 @@ def capabilities_test(data: Data) -> str: continue out += [opening(targets), f'static_assert({trait});', '#else', f'static_assert(!{trait});', '#endif'] + if 'type' not in entry: + # A family of free functions names no type a program makes. + continue algorithm = program_type(data, entry['type'], backend) made += [f'#if ({condition(targets)}) && defined(WEBCPP_CRYPTO_HAS_' f'{backend.upper()})', @@ -1803,11 +1822,12 @@ def llms_default(data: Data, operation: Data) -> str: def llms_uses(data: Data, operation: Data) -> str: - """The use cases of the decision table that an operation answers: of its section, naming - one of its names.""" + """The use cases of the decision table that an operation answers: of its section, or whose + `answers` names it where the use case links a teaching chapter instead, naming one of its + names.""" named = [part.rpartition('::')[2] for part in operation['api'].split(', ')] needs = [entry['need'][:1].lower() + entry['need'][1:] for entry in data['use_cases'] - if entry['section'] == operation['section'] + if entry.get('answers', entry['section']) == operation['section'] and any(re.search(rf'\b{re.escape(name)}\b', entry['api']) for name in named)] return f' Use it to: {"; ".join(needs)}.' if needs else '' diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 6e8e965f..1adb96c6 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -711,6 +711,46 @@ def test_a_type_names_only_crypto_s_namespaces_from_the_root(_: Path) -> None: assert 'crypto::curves::ed25519::basic' in test, test +def test_a_family_of_functions_has_no_type_to_make(_: Path) -> None: + # A family whose operations are free functions names no algorithm type: its cells are + # asserted through the test's own `algorithm`, and nothing is made. + data = small_table() + del data['families'][0]['names'][0]['type'] + test = generate.capabilities_test(data) + assert ('static_assert(crypto::supports_v, ' + 'backends::sodium>);\n') in test, test + assert 'webcpp::test::made<' not in test, test + + +def test_a_title_ending_in_s_takes_an_apostrophe_alone(_: Path) -> None: + # "BIP 352 silent payments's" is not English: a title that ends in s is possessive with the + # apostrophe alone, in the default's refusal and the primary engine's Doc Comment. + data = small_table() + family = data['families'][0] + family['title'] = 'BIP 352 silent payments' + text = generate.needs(data, family, 'native', 'sodium') + assert "webcpp::crypto: BIP 352 silent payments' default backend" in text, text + header = generate.capabilities_header(data) + assert "The refusals of the family BIP 352 silent payments' primary engine" in header, header + assert "payments's" not in header, header + + +def test_a_family_s_comment_names_the_namespace_of_its_header(_: Path) -> None: + # A family of a module header (curves/secp256k1/ellswift.hpp) is of the namespace that + # header's directory names, deeper than the plan's group `curves`; a family whose group is + # already deeper than its header keeps its group. + data = small_table() + family = data['families'][0] + family['group'] = 'curves' + family['header'] = '' + header = generate.capabilities_header(data) + assert 'The family Ed25519, of `curves::ed25519`, also the tag' in header, header + family['group'] = 'curves::ed25519' + family['header'] = '' + header = generate.capabilities_header(data) + assert 'The family Ed25519, of `curves::ed25519`, also the tag' in header, header + + def test_the_check_prints_each_file_that_differs(scratch: Path) -> None: files = {scratch / 'include/a.hpp': 'one\n', scratch / 'test/b.cpp': 'two\n'} generated = scratch / 'doc/generated' @@ -1089,6 +1129,16 @@ def test_a_use_case_joins_the_operation_it_names(_: Path) -> None: ' Use it to: encrypt chat messages.') +def test_a_use_case_that_links_a_teaching_section_joins_the_operation_it_answers(_: Path) -> None: + data = {'use_cases': [ + {'need': 'Find who signed a message', 'api': '`recover`', 'section': 'teaching', + 'answers': 'reference'}, + {'need': 'Recover elsewhere', 'api': '`recover`', 'section': 'teaching'}]} + assert generate.llms_uses(data, {'api': 'curves::secp256k1::recover', + 'section': 'reference'}) == ( + ' Use it to: find who signed a message.') + + def test_a_measurement_not_built_at_release_is_refused(scratch: Path) -> None: import json written(scratch, 'doc/performance.json', json.dumps(measured(22.5))) @@ -1304,6 +1354,9 @@ def test_a_namespace_table_is_split_into_its_parts(_: Path) -> None: test_the_default_s_refusal_says_what_the_program_needs, test_a_refusal_holds_on_its_target, test_a_type_names_only_crypto_s_namespaces_from_the_root, + test_a_family_of_functions_has_no_type_to_make, + test_a_title_ending_in_s_takes_an_apostrophe_alone, + test_a_family_s_comment_names_the_namespace_of_its_header, test_the_check_prints_each_file_that_differs, test_the_check_names_a_file_that_differs, test_the_size_matrix_reads_the_lane_s_tables, @@ -1323,6 +1376,7 @@ def test_a_namespace_table_is_split_into_its_parts(_: Path) -> None: test_the_namespaces_and_backends_come_from_the_data, test_every_api_page_lists_its_default_per_target, test_a_use_case_joins_the_operation_it_names, + test_a_use_case_that_links_a_teaching_section_joins_the_operation_it_answers, test_a_measurement_not_built_at_release_is_refused, test_a_speed_cell_names_each_operation_and_refuses_an_unknown_backend, test_a_measured_cell_escapes_the_bars_of_its_finding, diff --git a/doc/tables/sizes.json b/doc/tables/sizes.json index 17784ee8..5c8d985d 100644 --- a/doc/tables/sizes.json +++ b/doc/tables/sizes.json @@ -122,6 +122,38 @@ "over_baseline": 14207, "gzip_over_baseline": 5422 }, + { + "program": "secp256k1_ellswift_secp256k1", + "file": "js", + "bytes": 10109, + "gzip": 3595, + "over_baseline": 352, + "gzip_over_baseline": 123 + }, + { + "program": "secp256k1_ellswift_secp256k1", + "file": "wasm", + "bytes": 249284, + "gzip": 91443, + "over_baseline": 229093, + "gzip_over_baseline": 81927 + }, + { + "program": "secp256k1_musig_secp256k1", + "file": "js", + "bytes": 10106, + "gzip": 3593, + "over_baseline": 349, + "gzip_over_baseline": 121 + }, + { + "program": "secp256k1_musig_secp256k1", + "file": "wasm", + "bytes": 270560, + "gzip": 100089, + "over_baseline": 250369, + "gzip_over_baseline": 90573 + }, { "program": "secp256k1_secp256k1", "file": "js", @@ -138,6 +170,54 @@ "over_baseline": 85484, "gzip_over_baseline": 33955 }, + { + "program": "secp256k1_secp256k1_ecdh_x", + "file": "js", + "bytes": 10107, + "gzip": 3593, + "over_baseline": 350, + "gzip_over_baseline": 121 + }, + { + "program": "secp256k1_secp256k1_ecdh_x", + "file": "wasm", + "bytes": 195099, + "gzip": 72442, + "over_baseline": 174908, + "gzip_over_baseline": 62926 + }, + { + "program": "secp256k1_secp256k1_recover", + "file": "js", + "bytes": 10108, + "gzip": 3594, + "over_baseline": 351, + "gzip_over_baseline": 122 + }, + { + "program": "secp256k1_secp256k1_recover", + "file": "wasm", + "bytes": 223279, + "gzip": 81062, + "over_baseline": 203088, + "gzip_over_baseline": 71546 + }, + { + "program": "secp256k1_silent_payments_secp256k1", + "file": "js", + "bytes": 10116, + "gzip": 3600, + "over_baseline": 359, + "gzip_over_baseline": 128 + }, + { + "program": "secp256k1_silent_payments_secp256k1", + "file": "wasm", + "bytes": 235439, + "gzip": 87296, + "over_baseline": 215248, + "gzip_over_baseline": 77780 + }, { "program": "x25519_sodium", "file": "js", @@ -280,6 +360,22 @@ "over_baseline": 1104, "gzip_over_baseline": 8057 }, + { + "program": "secp256k1_ellswift_secp256k1", + "file": "executable", + "bytes": 184776, + "gzip": 101420, + "over_baseline": 133528, + "gzip_over_baseline": 98241 + }, + { + "program": "secp256k1_musig_secp256k1", + "file": "executable", + "bytes": 1258240, + "gzip": 1170515, + "over_baseline": 1206992, + "gzip_over_baseline": 1167336 + }, { "program": "secp256k1_secp256k1", "file": "executable", @@ -288,6 +384,30 @@ "over_baseline": 67368, "gzip_over_baseline": 56001 }, + { + "program": "secp256k1_secp256k1_ecdh_x", + "file": "executable", + "bytes": 168400, + "gzip": 85036, + "over_baseline": 117152, + "gzip_over_baseline": 81857 + }, + { + "program": "secp256k1_secp256k1_recover", + "file": "executable", + "bytes": 1225104, + "gzip": 1149570, + "over_baseline": 1173856, + "gzip_over_baseline": 1146391 + }, + { + "program": "secp256k1_silent_payments_secp256k1", + "file": "executable", + "bytes": 1241656, + "gzip": 1157324, + "over_baseline": 1190408, + "gzip_over_baseline": 1154145 + }, { "program": "x25519_sodium", "file": "executable", @@ -414,6 +534,22 @@ "over_baseline": 17489, "gzip_over_baseline": 5984 }, + { + "program": "secp256k1_ellswift_secp256k1", + "file": "wasm", + "bytes": 336841, + "gzip": 128107, + "over_baseline": 272419, + "gzip_over_baseline": 103703 + }, + { + "program": "secp256k1_musig_secp256k1", + "file": "wasm", + "bytes": 1417621, + "gzip": 1186030, + "over_baseline": 1353199, + "gzip_over_baseline": 1161626 + }, { "program": "secp256k1_secp256k1", "file": "wasm", @@ -422,6 +558,30 @@ "over_baseline": 115797, "gzip_over_baseline": 55251 }, + { + "program": "secp256k1_secp256k1_ecdh_x", + "file": "wasm", + "bytes": 278726, + "gzip": 108506, + "over_baseline": 214304, + "gzip_over_baseline": 84102 + }, + { + "program": "secp256k1_secp256k1_recover", + "file": "wasm", + "bytes": 1357572, + "gzip": 1166931, + "over_baseline": 1293150, + "gzip_over_baseline": 1142527 + }, + { + "program": "secp256k1_silent_payments_secp256k1", + "file": "wasm", + "bytes": 1382735, + "gzip": 1172149, + "over_baseline": 1318313, + "gzip_over_baseline": 1147745 + }, { "program": "x25519_sodium", "file": "wasm", @@ -548,6 +708,22 @@ "over_baseline": 17528, "gzip_over_baseline": 5911 }, + { + "program": "secp256k1_ellswift_secp256k1", + "file": "wasm", + "bytes": 348232, + "gzip": 131827, + "over_baseline": 274172, + "gzip_over_baseline": 104395 + }, + { + "program": "secp256k1_musig_secp256k1", + "file": "wasm", + "bytes": 1428661, + "gzip": 1189992, + "over_baseline": 1354601, + "gzip_over_baseline": 1162560 + }, { "program": "secp256k1_secp256k1", "file": "wasm", @@ -556,6 +732,30 @@ "over_baseline": 117545, "gzip_over_baseline": 56024 }, + { + "program": "secp256k1_secp256k1_ecdh_x", + "file": "wasm", + "bytes": 290109, + "gzip": 112377, + "over_baseline": 216049, + "gzip_over_baseline": 84945 + }, + { + "program": "secp256k1_secp256k1_recover", + "file": "wasm", + "bytes": 1368952, + "gzip": 1170584, + "over_baseline": 1294892, + "gzip_over_baseline": 1143152 + }, + { + "program": "secp256k1_silent_payments_secp256k1", + "file": "wasm", + "bytes": 1394173, + "gzip": 1175682, + "over_baseline": 1320113, + "gzip_over_baseline": 1148250 + }, { "program": "x25519_sodium", "file": "wasm", @@ -575,5 +775,5 @@ ] } ], - "digest": "d92449e7da23410f7ff00d5d9c8bb33823c6f57294eee6ea8a7ceac09767b07a" + "digest": "2386dc15472f2e685d8828e0e486cd217f85826e889780554e2b77a7e87e1f0e" } diff --git a/doc/testing.adoc b/doc/testing.adoc index 94cc0be6..1be35eda 100644 --- a/doc/testing.adoc +++ b/doc/testing.adoc @@ -52,12 +52,15 @@ 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, 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..95017c8d 100644 --- a/doc/wallets.adoc +++ b/doc/wallets.adoc @@ -131,11 +131,133 @@ 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 key and the Merkle root), so the tweaked secret key is as sensitive as the original: anyone who knows the tweak and either secret key knows the other. Check the domain library's tweak against BIP 341's published vectors. + +[#crypto-wallets-recovery] +=== Who signed this? Recoverable signatures + +*The problem.* A wallet app receives a request that another wallet signed: a +transaction to relay, or a message that proves who owns an account. The +request carries the signed bytes and the signature, but no public key, and the +app must know whose key signed it before it acts on it. + +*The idea.* An ECDSA signature leaves its signer's public key one of a few +candidates; a recoverable signature adds the id, 0 to 3, of the one that +verifies, so that a reader computes the signer's key from the signature and +the hash alone. Ethereum finds a transaction's sender this way +(link:https://ethereum.github.io/yellowpaper/paper.pdf[Ethereum's yellow paper, +appendix F]). `sign_recoverable` makes the 65 bytes, and `recover` finds the +key (<>). Recovery finds some key for almost any +signature and any hash: what makes it a check is the comparison with the key +the reader expects. + +[source,cpp] +---- +include::{examples}/recover_signer.cpp[tag=recover,indent=0] +---- + +[listing] +---- +include::{examples}/recover_signer.expected[] +---- + +Ethereum compares addresses rather than keys, the last 20 bytes of the +Keccak-256 of the uncompressed key (the yellow paper, appendix F), and a wallet +signs a message after EIP-191's prefix +(link:https://eips.ethereum.org/EIPS/eip-191[EIP-191]). Both are the protocol's +rules, which a domain library built on crypto, such as a future +webcpp::ethereum, computes; crypto holds the signature and the recovery. This +section names no application. + +*Mistakes to avoid.* Never trust a recovered key on its own: a changed or +forged message recovers some other key rather than failing, so compare the +key, or the address made from it, with the one expected before acting. Hash +exactly what the signer hashed: a message hashed without EIP-191's prefix, or +with another, recovers another key, which looks like a wrong signer rather +than a wrong hash. + +[#crypto-wallets-musig] +=== Two devices, one signature: MuSig2 + +*The problem.* A wallet split across a phone and a laptop, so that a thief who +takes one device takes nothing: spending needs both. A script that asks for +two signatures shows on the chain that two keys hold the coins, and costs more +to spend. + +*The idea.* MuSig2 aggregates the two public keys into one, and the two +devices' partial signatures into one BIP 340 signature under it, which the +chain checks as any single signer's +(link:https://github.com/bitcoin/bips/blob/master/bip-0327.mediawiki[BIP 327]). +It takes two rounds: each device makes a nonce and sends its public half; with +both in, each signs its part, and the parts add up to the signature +(<>). + +[source,cpp] +---- +include::{examples}/musig_wallet.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/musig_wallet.expected[] +---- + +The wallet's address, its transactions and the hash each device signs are a +domain library's. This section names no application. + +*Mistakes to avoid.* Reusing a nonce: two partial signatures with one nonce +give away the secret key, so a nonce is made when the signature is made, never +stored, and never restored from a backup; `partial_sign` takes it by value and +refuses one already used. Signing before every nonce is in: a device that +signs while the other can still choose its nonce lets it steer the final nonce, +which the two rounds exist to prevent +(link:https://eprint.iacr.org/2020/1261[Nick, Ruffing and Seurin, MuSig2]). A +naive key sum: the plain sum of the two public keys, `pubkey_combine`, is not +a multisignature, since a device that announces its key after seeing the +other's can choose one that cancels it and spend alone; `key_aggregate` weighs +each key by a hash of all of them (BIP 327). + +[#crypto-wallets-silent] +=== A reusable address: silent payments + +*The problem.* A donation page 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, and a fresh address for each payer needs a server that hands them out. + +*The idea.* A silent payment address is two public keys, scan and spend. The +sender combines the secret keys of its transaction's inputs with the scan key +into a secret only it and the recipient share, an ECDH, and tweaks the spend +key with it into an output key that is new for each transaction; the +recipient scans each transaction with its scan secret and recognises its +outputs (link:https://github.com/bitcoin/bips/blob/master/bip-0352.mediawiki[BIP 352]; +<>). + +[source,cpp] +---- +include::{examples}/silent_payment.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/silent_payment.expected[] +---- + +The address's encoding, the choice of inputs and the transaction are a domain +library's. This section names no application. + +*Mistakes to avoid.* The outpoint: it must be the smallest of all the +transaction's inputs, eligible or not; with another, the sender computes +another secret and the recipient never finds the payment. A dropped output: +every output `create_outputs` makes must be in the transaction, since the +recipient looks for them in order and stops at the first it does not find +(link:https://github.com/bitcoin-core/secp256k1/blob/6e2c8bc4ecdc6e71dbe7a368f360d8d453ce435d/include/secp256k1_silentpayments.h[libsecp256k1's silent payments header]). +Scanning cost: the recipient pays one ECDH for every transaction with eligible +inputs, its own or not, which a light client must plan for (BIP 352). diff --git a/example/Jamfile b/example/Jamfile index 0695d5b3..1bb07bed 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -49,6 +49,46 @@ 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 recoverable signature: a reader finds the signer's key from the signature +# 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 server's secp256k1 key in files OpenSSL reads: its public key as PEM SPKI +# for a configuration file, its key pair as PEM PKCS#8, each read back; PEM on +# its default, libsodium. +webcpp.example secp256k1_key_formats.cpp : /third_party//secp256k1 + /webcpp/crypto//pem-default ; + +# 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 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 ; + +# The same wallet with its devices apart: public nonces, the aggregate nonce and +# partial signatures cross the network as bytes, and the coordinator checks +# each part, refusing one damaged on the way. +webcpp.example musig_network.cpp : /third_party//secp256k1 ; + +# The wallet's aggregate key as a Taproot internal key: tweaked by its BIP 341 +# TapTweak before any nonce, the signature verifies under the output key only. +webcpp.example musig_taproot.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/ecdh_session.cpp b/example/ecdh_session.cpp index be3f3304..83c9565d 100644 --- a/example/ecdh_session.cpp +++ b/example/ecdh_session.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -22,9 +23,11 @@ #include #include #include +#include #include #include #include +#include namespace crypto = webcpp::crypto; namespace secp256k1 = webcpp::crypto::curves::secp256k1; @@ -126,10 +129,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,22 +171,28 @@ 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)) { - 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[] - 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; - } std::array iv{}; if (!crypto::random_device().fill(iv)) { return 1; diff --git a/example/ecdh_x_coordinate.cpp b/example/ecdh_x_coordinate.cpp new file mode 100644 index 00000000..1cbdb394 --- /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(), crypto::secret<32>::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/example/ellswift_handshake.cpp b/example/ellswift_handshake.cpp new file mode 100644 index 00000000..e4da9ebf --- /dev/null +++ b/example/ellswift_handshake.cpp @@ -0,0 +1,76 @@ +// 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; + } + + // 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"); + 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/example/key_tweak.cpp b/example/key_tweak.cpp new file mode 100644 index 00000000..615f76bf --- /dev/null +++ b/example/key_tweak.cpp @@ -0,0 +1,145 @@ +// 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 +#include + +namespace crypto = webcpp::crypto; +namespace secp256k1 = webcpp::crypto::curves::secp256k1; +namespace hash2 = boost::hash2; + +namespace { + +// 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{}; + + wiped_bytes() = default; + wiped_bytes(wiped_bytes const&) = delete; + wiped_bytes& operator=(wiped_bytes const&) = delete; + + ~wiped_bytes() { wipe(bytes); } +}; + +// The tweak of payment `number`: HMAC-SHA-256 under the chain code of the compressed public key +// 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{ + static_cast(number >> 24U), + static_cast(number >> 16U), + static_cast(number >> 8U), + static_cast(number), + }; + mac.update(index.data(), index.size()); + auto digest = mac.result(); + std::copy_n(digest.data(), tweak.bytes.size(), tweak.bytes.begin()); + wipe(digest); + wipe(mac); +} + +} // 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; + 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.bytes); + 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; + } + // The tweak and the tweaked secret give back the secret: the tweak is wiped too. + wiped_bytes tweak; + payment_tweak(chain_code.bytes, *wallet_public, 7, 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.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.bytes, tweak.bytes); + 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"); + + // 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"); + 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/example/musig_network.cpp b/example/musig_network.cpp new file mode 100644 index 00000000..ab3c6ca7 --- /dev/null +++ b/example/musig_network.cpp @@ -0,0 +1,187 @@ +// 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 wallet of musig_wallet.cpp with its two devices apart: every public piece of BIP 327's +// MuSig2 crosses the network as bytes. Each device sends its public nonce, 66 bytes, to a +// coordinator, which holds no secret: it sums the nonces and sends the aggregate nonce, 66 +// bytes, back. Each device then signs and sends its partial signature, 32 bytes; the +// coordinator parses each part and checks it with partial_signature_verify before it adds the +// parts, so that a part damaged on the way, or a faulty signer's, is refused by name rather +// than spoiling the signature. The devices' secrets are fixed here, so that the program runs +// the same each time; the nonces are fresh in every run, and nothing random is printed. +// tag::program[] +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace secp256k1 = webcpp::crypto::curves::secp256k1; +namespace musig = webcpp::crypto::curves::secp256k1::musig; + +namespace { + +using public_nonce_bytes = std::array; +using aggregate_nonce_bytes = std::array; +using partial_signature_bytes = std::array; + +std::array repeated(std::uint8_t value) { + std::array bytes{}; + bytes.fill(value); + return bytes; +} + +// The wallet's key, which each party aggregates from the two public keys it received: sorted +// (BIP 327's KeySort), it is the same key on every party. +std::optional wallet_key_of(secp256k1::public_key const& first, + secp256k1::public_key const& second) { + std::array keys{first, second}; + std::ranges::sort(keys); + alignas(std::max_align_t) std::array space{}; + auto aggregated = musig::key_aggregate(keys, space); + if (!aggregated) { + return std::nullopt; + } + return *aggregated; +} + +// The coordinator's checks on what arrived: each part parsed from its 32 bytes, then checked +// against its signer's public nonce and key; the first refusal is returned. +boost::system::result received_part( + partial_signature_bytes const& wire, musig::public_nonce const& signer_nonce, + secp256k1::public_key const& signer_key, musig::aggregate_key const& wallet_key, + musig::session const& signing_session) { + auto part = musig::parse_partial_signature(wire); + if (!part) { + return part.error(); + } + auto const checked = musig::partial_signature_verify(*part, signer_nonce, signer_key, + wallet_key, signing_session); + if (!checked) { + return checked.error(); + } + return part; +} + +} // namespace + +int main() { + // Each device's key pair; each publishes its public key, which every party parses. + 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; + } + auto const wallet_key = wallet_key_of(*phone_key, *laptop_key); + if (!wallet_key) { + return 1; + } + + // The spend both approve: the transaction's 32-byte hash, as a domain library computes it. + auto const message = repeated(0x5a); + + // Round one, on each device: a nonce for this signature, its public half sent as bytes. + 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; + } + public_nonce_bytes const phone_nonce_wire = + musig::serialize_public_nonce(phone_nonce->public_part); + public_nonce_bytes const laptop_nonce_wire = + musig::serialize_public_nonce(laptop_nonce->public_part); + std::printf("each device sends its public nonce: %zu bytes\n", phone_nonce_wire.size()); + + // The coordinator parses both public nonces, sums them and sends the sum back as bytes. + auto const phone_nonce_in = musig::parse_public_nonce(phone_nonce_wire); + auto const laptop_nonce_in = musig::parse_public_nonce(laptop_nonce_wire); + if (!phone_nonce_in || !laptop_nonce_in) { + return 1; + } + std::array const nonces{*phone_nonce_in, *laptop_nonce_in}; + alignas(std::max_align_t) std::array space{}; + auto const nonce_sum = musig::nonce_aggregate(nonces, space); + if (!nonce_sum) { + return 1; + } + aggregate_nonce_bytes const nonce_sum_wire = musig::serialize_aggregate_nonce(*nonce_sum); + std::printf("the coordinator sends the aggregate nonce: %zu bytes\n", nonce_sum_wire.size()); + + // Round two, on each device: the aggregate nonce parsed, the session made (the same on both, + // so made once here), the part signed (which consumes the secret nonce) and sent as bytes. + auto const nonce_sum_in = musig::parse_aggregate_nonce(nonce_sum_wire); + if (!nonce_sum_in) { + return 1; + } + auto const device_session = musig::nonce_process(*nonce_sum_in, message, *wallet_key); + if (!device_session) { + return 1; + } + auto const phone_part = musig::partial_sign(*phone, std::move(phone_nonce->secret_part), + *wallet_key, *device_session); + auto const laptop_part = musig::partial_sign(*laptop, std::move(laptop_nonce->secret_part), + *wallet_key, *device_session); + if (!phone_part || !laptop_part) { + return 1; + } + partial_signature_bytes const phone_part_wire = musig::serialize_partial_signature(*phone_part); + partial_signature_bytes const laptop_part_wire = + musig::serialize_partial_signature(*laptop_part); + std::printf("each device sends its partial signature: %zu bytes\n", phone_part_wire.size()); + + // The coordinator makes the same session from the nonce sum it sent, and checks each part + // before it adds them. + auto const signing_session = musig::nonce_process(*nonce_sum, message, *wallet_key); + if (!signing_session) { + return 1; + } + auto const phone_part_in = + received_part(phone_part_wire, *phone_nonce_in, *phone_key, *wallet_key, *signing_session); + auto const laptop_part_in = received_part(laptop_part_wire, *laptop_nonce_in, *laptop_key, + *wallet_key, *signing_session); + if (!phone_part_in || !laptop_part_in) { + return 1; + } + std::printf("both partial signatures parse and verify\n"); + + // The same check refuses the laptop's part with one byte flipped on the way. + partial_signature_bytes damaged_wire = laptop_part_wire; + damaged_wire.back() ^= 0x01U; + auto const damaged = + received_part(damaged_wire, *laptop_nonce_in, *laptop_key, *wallet_key, *signing_session); + if (damaged) { + return 1; + } + std::string const reason = damaged.error().message(); + std::printf("a part with one byte flipped is refused: %s\n", reason.c_str()); + + // The parts add up to one BIP 340 signature under the wallet's one x-only key. + std::array const parts{*phone_part_in, *laptop_part_in}; + 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: %zu bytes\n", + signature->size()); + return 0; +} + +// end::program[] diff --git a/example/musig_network.expected b/example/musig_network.expected new file mode 100644 index 00000000..e91c9ce6 --- /dev/null +++ b/example/musig_network.expected @@ -0,0 +1,6 @@ +each device sends its public nonce: 66 bytes +the coordinator sends the aggregate nonce: 66 bytes +each device sends its partial signature: 32 bytes +both partial signatures parse and verify +a part with one byte flipped is refused: the signature does not verify or is not a valid encoding +the aggregate signature verifies as one BIP 340 signature: 64 bytes diff --git a/example/musig_taproot.cpp b/example/musig_taproot.cpp new file mode 100644 index 00000000..75441fb4 --- /dev/null +++ b/example/musig_taproot.cpp @@ -0,0 +1,151 @@ +// 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 wallet of musig_wallet.cpp receiving to a Taproot output (BIP 341) with a key path only: +// the two signers' aggregate key is the internal key, and the output key on the chain is that +// key tweaked by its TapTweak tagged hash. The tweak is applied to the aggregate key with +// tweak_xonly_add before any nonce is made, since the session and the partial signatures need +// the key as tweaked, and nonce_gen mixes in the key it is given (BIP 327's NonceGen takes it +// only as an optional input); then the signers run MuSig2's two rounds as before, and the +// signature verifies under the output key and not under the internal one. The tweak's hash is +// the protocol's, which a domain library computes; it is shown here with webcpp::hash's SHA-256. +// The devices' secrets are fixed here, so that the program runs the same each time; the nonces +// are fresh in every run, and nothing random is printed. +// tag::program[] +#include +#include +#include +#include + +#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; +} + +// BIP 340's tagged hash, SHA-256(SHA-256(tag) || SHA-256(tag) || data), with which BIP 341 +// derives the tweak: the tag keeps a hash made for one purpose from being valid for another. +std::array tagged_hash(std::string_view tag, std::span data) { + webcpp::hash::sha2_256 tag_hash; + tag_hash.update(tag.data(), tag.size()); + auto const prefix = tag_hash.result(); + + webcpp::hash::sha2_256 hash; + hash.update(prefix.data(), prefix.size()); + hash.update(prefix.data(), prefix.size()); + hash.update(data.data(), data.size()); + auto const digest = hash.result(); + std::array out{}; + std::ranges::copy(digest, out.begin()); + return out; +} + +} // 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; + } + + // The keys sorted and aggregated: the output's internal key. + std::array keys{*phone_key, *laptop_key}; + std::ranges::sort(keys); + alignas(std::max_align_t) std::array space{}; + auto wallet_key = musig::key_aggregate(keys, space); + if (!wallet_key) { + return 1; + } + auto const internal_key = wallet_key->xonly_public_key(); + std::printf("internal key aggregated from %zu signers\n", keys.size()); + + // BIP 341's tweak of a key-path-only output, the tagged hash of the internal key, applied + // as an x-only tweak before any nonce is made: the output key is the key on the chain. + auto const tweak = tagged_hash("TapTweak", internal_key); + if (!wallet_key->tweak_xonly_add(tweak)) { + return 1; + } + auto const output_key = wallet_key->xonly_public_key(); + if (output_key == internal_key) { + return 1; + } + std::printf("output key tweaked with TapTweak, a key other than the internal key\n"); + + // The spend both approve: the transaction's 32-byte hash (BIP 341's signature message), as + // a domain library computes it. + auto const message = repeated(0x5a); + + // MuSig2's two rounds under the tweaked key: a nonce each, the session, a part each. + 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; + } + 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; + } + 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"); + + // One BIP 340 signature: valid under the output key, which spends the output by its key + // path, and not under the internal 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, output_key)) { + return 1; + } + std::printf("the signature verifies under the output key\n"); + auto const under_internal = secp256k1::verify_schnorr(*signature, message, internal_key); + if (under_internal) { + return 1; + } + std::string const reason = under_internal.error().message(); + std::printf("under the internal key it is refused: %s\n", reason.c_str()); + return 0; +} + +// end::program[] diff --git a/example/musig_taproot.expected b/example/musig_taproot.expected new file mode 100644 index 00000000..426e51da --- /dev/null +++ b/example/musig_taproot.expected @@ -0,0 +1,5 @@ +internal key aggregated from 2 signers +output key tweaked with TapTweak, a key other than the internal key +both partial signatures verify +the signature verifies under the output key +under the internal key it is refused: the signature does not verify or is not a valid encoding diff --git a/example/musig_wallet.cpp b/example/musig_wallet.cpp new file mode 100644 index 00000000..3956e6a4 --- /dev/null +++ b/example/musig_wallet.cpp @@ -0,0 +1,112 @@ +// 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/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/example/secp256k1_key_formats.cpp b/example/secp256k1_key_formats.cpp new file mode 100644 index 00000000..d9ca6a92 --- /dev/null +++ b/example/secp256k1_key_formats.cpp @@ -0,0 +1,112 @@ +// 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 server's secp256k1 key in files that OpenSSL also reads: its public key written as PEM SPKI +// for a configuration file that its clients read, and read back; its key pair written as PEM +// PKCS#8 for the server's own key file, which is never printed, and read back. The secret is +// the fixed 0x11 repeated, so that the output is fixed: a real server draws its own. +// tag::program[] +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; +namespace pem = webcpp::crypto::pem; +namespace secp256k1 = webcpp::crypto::curves::secp256k1; + +namespace { + +// The public key as PEM SPKI, compressed, printed as the configuration file holds it, and read +// back from that text: the same key. +bool public_key_to_pem(secp256k1::public_key const& key) { + std::array spki{}; + auto const size = secp256k1::encode_spki(key, spki); + if (!size) { + return false; + } + std::array + text{}; + auto const written = pem::armour(pem::public_key_label, std::span(spki).first(*size), text); + if (!written) { + return false; + } + std::string_view const config(text.data(), *written); + std::printf("%.*s", static_cast(config.size()), config.data()); + + std::array read{}; + auto const read_size = pem::unarmour(pem::public_key_label, config, read); + if (!read_size) { + return false; + } + auto const back = secp256k1::decode_spki(std::span(read).first(*read_size)); + return back && *back == key; +} + +// The key pair as PEM PKCS#8, which holds the secret: the DER and the text are kept in +// secret, which wipes itself, the text as its bytes' characters. Read back, it is a key pair +// of the same public key. +bool key_pair_to_pem(secp256k1::keypair const& key_pair) { + crypto::secret pkcs8; + auto const size = secp256k1::encode_pkcs8(key_pair, pkcs8.writable()); + if (!size) { + return false; + } + constexpr std::size_t file_size = + pem::armoured_size(pem::private_key_label.size(), secp256k1::max_pkcs8_size); + crypto::secret file; + std::span const text(reinterpret_cast(file.writable().data()), file_size); + auto const written = pem::armour(pem::private_key_label, pkcs8.bytes().first(*size), text); + if (!written) { + return false; + } + + crypto::secret read; + auto const read_size = pem::unarmour(pem::private_key_label, + std::string_view(text.data(), *written), read.writable()); + if (!read_size) { + return false; + } + auto const back = secp256k1::decode_pkcs8(read.bytes().first(*read_size)); + if (!back) { + return false; + } + auto const back_key = back->public_key(); + auto const original_key = key_pair.public_key(); + return back_key && original_key && *back_key == *original_key; +} + +// The server's files written and read back. +bool store_and_read(secp256k1::keypair const& key_pair) { + auto const encoded = key_pair.public_key(); + if (!encoded) { + return false; + } + auto const key = secp256k1::parse_public_key(*encoded); + return key && public_key_to_pem(*key) && key_pair_to_pem(key_pair); +} + +} // namespace + +int main() { + std::array secret_key{}; + secret_key.fill(0x11); + auto const key_pair = secp256k1::keypair::make(secret_key); + if (!key_pair || !store_and_read(*key_pair)) { + std::printf("failed\n"); + return 1; + } + std::printf("read back: same key\n"); + return 0; +} + +// end::program[] diff --git a/example/secp256k1_key_formats.expected b/example/secp256k1_key_formats.expected new file mode 100644 index 00000000..14c47020 --- /dev/null +++ b/example/secp256k1_key_formats.expected @@ -0,0 +1,5 @@ +-----BEGIN PUBLIC KEY----- +MDYwEAYHKoZIzj0CAQYFK4EEAAoDIgADTzVb3LfMCvco7zzOuWFdkGhLtbLKX4Wa +sPC3BAdYcao= +-----END PUBLIC KEY----- +read back: same key 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 b54685fb..6338a999 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -57,6 +57,11 @@ #ifdef WEBCPP_CRYPTO_HAS_SECP256K1 #include +#include +#include +#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 28d71f32..abade41a 100644 --- a/include/webcpp/crypto/backends/secp256k1.hpp +++ b/include/webcpp/crypto/backends/secp256k1.hpp @@ -7,8 +7,12 @@ /** 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, 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`, 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. */ @@ -27,9 +31,13 @@ #include #include +#include #include +#include #include +#include #include +#include #include diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index bd674187..d9ba1c7e 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -5,8 +5,10 @@ // https://www.boost.org/LICENSE_1_0.txt) /** - 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. + 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, the tweak of an x-only + key, and the workspace a function over many keys borrows. @see "secp256k1", in the guide. */ @@ -17,37 +19,181 @@ #include #include +#include #include #include #include #include // lint-world: the context's randomisation, its purpose +#include #include #include #include +#include #include #include +#include +#include #include #include #include #include -// clang-format off -/** The refusal of a backend other than libsecp256k1 by `curves::secp256k1`. */ -#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; + + /** + * 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 +#if defined(WEBCPP_CRYPTO_DETAIL_CT_VALGRIND) || defined(WEBCPP_CRYPTO_DETAIL_CT_MSAN) +/** + * The flags of a context that signs and verifies, under a constant-time checker: + * `SECP256K1_CONTEXT_DECLASSIFY`, so that libsecp256k1 marks its own public values public (a + * nonce's retry, a verdict), as its `ctime_tests.c` does; the checker then reports any other + * branch on a secret. + */ +inline constexpr unsigned secp256k1_context_flags = SECP256K1_CONTEXT_DECLASSIFY; +#else /** The flags of a context that signs and verifies: none. */ inline constexpr unsigned secp256k1_context_flags = SECP256K1_CONTEXT_NONE; +#endif /** 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) +/** + * Whether libsecp256k1 accepted: what it returned on a secret, marked public for the + * constant-time checks (`WEBCPP_CRYPTO_DETAIL_DECLASSIFY`) where webcpp branches on it, as its + * `ctime_tests.c` marks each verdict. + * + * @param returned What the function returned: 1, or 0 when it refused. + * @return Whether it accepted. + */ +[[nodiscard]] inline bool secp256k1_accepted(int returned) noexcept { + // Not const: the comparison reads it again after the mark (detail/declassify.hpp's tip). + // NOLINTNEXTLINE(misc-const-correctness): see above + int verdict = returned; + WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&verdict, sizeof verdict); + return verdict != 0; +} + +/** + * A key pair's public key, marked public (`WEBCPP_CRYPTO_DETAIL_DECLASSIFY`): libsecp256k1 + * derives it from the secret and marks it public only where it loads the key pair itself, and + * its `ctime_tests.c` marks a key pair's public key by hand where it reads one. + * + * @param context The key pair's context, or the static one. + * @param key_pair libsecp256k1's key pair. + * @return The public key. + */ +[[nodiscard]] inline secp256k1_pubkey secp256k1_public_point( + secp256k1_context const* context, secp256k1_keypair const& key_pair) noexcept { + secp256k1_pubkey public_point{}; + // libsecp256k1 returns 1 always: a key pair holds its public key. + static_cast(secp256k1_keypair_pub(context, &public_point, &key_pair)); + WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&public_point, sizeof public_point); + return public_point; +} + /** * The error of a key pair whose context could not be randomised: every failure of the * generator is `entropy_unavailable`, the library's one word for it. @@ -72,6 +218,69 @@ 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 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`. + */ +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 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)`. + * + * @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 @@ -135,6 +344,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`. * @@ -143,6 +387,44 @@ struct secp256k1_secret { template inline constexpr bool secp256k1_backend = std::is_same_v; +/** + * The refusal of `Backend` by a function of the secp256k1 family `Family`: empty for + * libsecp256k1, the families' one backend; for any other, a specialisation per family whose body + * is the family's generated refusal (`detail/capabilities.hpp`, design D33), which names the + * backends that have the family. secp256k1 has no engine trait, so the refusal is reached here, + * where `secp256k1_refuses_others` instantiates it. The generated macro cannot stand bare in a + * function: for libsecp256k1 itself it asserts both "linked" and "not linked", so it always + * fails there; in an engine's primary template, reached only for another backend, that is right. + * + * @tparam Family The family's tag, `families::secp256k1` or one of its modules'. + * @tparam Backend The backend a function or the key pair names. + * @tparam Accepted Whether `Backend` is libsecp256k1. + */ +template > +struct secp256k1_refusal {}; + +/** + * The refusal of a backend other than libsecp256k1 by the family `families::secp256k1`: the key + * pair and the functions of `curves/secp256k1.hpp`, `tweak.hpp` and `formats.hpp`. + * + * @tparam Backend The backend named. + */ +template +struct secp256k1_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1(Backend); +}; + +/** + * True: reading it instantiates `secp256k1_refusal`, which stops the build with + * the family's generated refusal where `Backend` is not libsecp256k1. A function's + * `static_assert` of it is the family's one refusal, with no second message of its own. + * + * @tparam Family The family's tag. + * @tparam Backend The backend a function or the key pair names. + */ +template +inline constexpr bool secp256k1_refuses_others = sizeof(secp256k1_refusal) != 0; + } // namespace webcpp::crypto::detail namespace webcpp::crypto::curves::secp256k1 { @@ -150,6 +432,96 @@ 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. */ + compressed, + /** 65 bytes: 04, x, y; Ethereum's form, and OpenSSL's default. */ + uncompressed, +}; + +/** + * The size of a point in `Form`: 33 for the compressed form, 65 for the uncompressed one. + * + * @tparam Form The SEC1 form. + */ +template +inline constexpr std::size_t point_size = 33; + +/** The size of an uncompressed point: 65. */ +template <> +inline constexpr std::size_t point_size = 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. */ @@ -166,8 +538,7 @@ struct tweaked_xonly_key { */ template > class basic_keypair { - static_assert(webcpp::crypto::detail::secp256k1_backend, - WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + static_assert(webcpp::crypto::detail::secp256k1_refuses_others); public: /** The backend. */ @@ -199,7 +570,8 @@ class basic_keypair { } webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); - if (secp256k1_ec_seckey_verify(secp256k1_context_static, secret_bytes.data()) == 0) { + if (!webcpp::crypto::detail::secp256k1_accepted( + secp256k1_ec_seckey_verify(secp256k1_context_static, secret_bytes.data()))) { return error::invalid_secret_key; } webcpp::crypto::detail::secp256k1_secret context_seed; @@ -213,11 +585,10 @@ class basic_keypair { made_object.context_ = secp256k1_context_preallocated_create( memory_resource->allocate(context_size(), alignof(std::max_align_t)), webcpp::crypto::detail::secp256k1_context_flags); - int const randomise_status = - secp256k1_context_randomize(made_object.context_, context_seed.bytes.data()); - if (randomise_status == 0 || - secp256k1_keypair_create(made_object.context_, &made_object.keypair_, - secret_bytes.data()) == 0) { + bool const randomised = webcpp::crypto::detail::secp256k1_accepted( + secp256k1_context_randomize(made_object.context_, context_seed.bytes.data())); + if (!randomised || !webcpp::crypto::detail::secp256k1_accepted(secp256k1_keypair_create( + made_object.context_, &made_object.keypair_, secret_bytes.data()))) { return error::backend_failure; } made_object.keyed_ = true; @@ -287,17 +658,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); } /** @@ -319,9 +690,9 @@ class basic_keypair { secp256k1_schnorrsig_extraparams extra_parameters = SECP256K1_SCHNORRSIG_EXTRAPARAMS_INIT; extra_parameters.ndata = aux_randomness.bytes.data(); std::array output_bytes{}; - if (secp256k1_schnorrsig_sign_custom(context_, output_bytes.data(), message_bytes.data(), - message_bytes.size(), &keypair_, - &extra_parameters) == 0) { + if (!webcpp::crypto::detail::secp256k1_accepted(secp256k1_schnorrsig_sign_custom( + context_, output_bytes.data(), message_bytes.data(), message_bytes.size(), + &keypair_, &extra_parameters))) { return error::backend_failure; } return output_bytes; @@ -335,20 +706,52 @@ 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 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( + 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 (!webcpp::crypto::detail::secp256k1_accepted( + secp256k1_ecdsa_sign_recoverable(context_, &signature_value, message_hash.data(), + secret_bytes.bytes.data(), nullptr, nullptr))) { 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; } @@ -357,26 +760,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); } /** @@ -399,7 +815,8 @@ class basic_keypair { return error::invalid_state; } webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - if (secp256k1_keypair_xonly_tweak_add(context_, &keypair_, tweak_bytes.data()) == 0) { + if (!webcpp::crypto::detail::secp256k1_accepted( + secp256k1_keypair_xonly_tweak_add(context_, &keypair_, tweak_bytes.data()))) { release(); return error::invalid_secret_key; } @@ -407,8 +824,93 @@ 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 const public_point = + webcpp::crypto::detail::secp256k1_public_point(context_, keypair_); + std::array output_bytes{}; + std::size_t written_size = output_bytes.size(); + 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 (!webcpp::crypto::detail::secp256k1_accepted( + secp256k1_ecdsa_sign(context_, &signature_bytes, message_hash.data(), + secret_bytes.bytes.data(), nullptr, nonce_data))) { + 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. + * + * @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 (!webcpp::crypto::detail::secp256k1_accepted( + secp256k1_ecdh(context_, shared_secret.writable().data(), &parsed_value, + secret_bytes.bytes.data(), hash_function, nullptr))) { + 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); } @@ -432,6 +934,131 @@ 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 {}; +} + +} // 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_refuses_others); + 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_refuses_others); + 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_refuses_others); + 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; + } + 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`). @@ -446,8 +1073,7 @@ template > [[nodiscard]] boost::system::result verify_schnorr( std::span signature_bytes, std::span message_bytes, std::span xonly_key_bytes) noexcept { - static_assert(webcpp::crypto::detail::secp256k1_backend, - WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); secp256k1_xonly_pubkey parsed_key{}; @@ -477,8 +1103,7 @@ template > std::span signature_bytes, std::span message_hash, std::span public_key_bytes) noexcept { - static_assert(webcpp::crypto::detail::secp256k1_backend, - WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); secp256k1_pubkey parsed_key{}; @@ -510,8 +1135,7 @@ template > [[nodiscard]] boost::system::result to_der( std::span compact_signature, std::span output_bytes) noexcept { - static_assert(webcpp::crypto::detail::secp256k1_backend, - WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + static_assert(webcpp::crypto::detail::secp256k1_refuses_others); if (output_bytes.size() < max_der_size) { return error::invalid_input_size; } @@ -542,8 +1166,7 @@ template > template > [[nodiscard]] boost::system::result> from_der( std::span der_signature) noexcept { - static_assert(webcpp::crypto::detail::secp256k1_backend, - WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + static_assert(webcpp::crypto::detail::secp256k1_refuses_others); if (der_signature.empty()) { return error::invalid_signature; } @@ -574,8 +1197,7 @@ template > template > [[nodiscard]] boost::system::result> normalize_ecdsa( std::span compact_signature) noexcept { - static_assert(webcpp::crypto::detail::secp256k1_backend, - WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); secp256k1_ecdsa_signature parsed_value{}; @@ -606,8 +1228,7 @@ template > [[nodiscard]] boost::system::result tweak_xonly( std::span xonly_key_bytes, std::span tweak_bytes) noexcept { - static_assert(webcpp::crypto::detail::secp256k1_backend, - WEBCPP_CRYPTO_DETAIL_SECP256K1_ONLY); + static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); secp256k1_xonly_pubkey parsed_key{}; diff --git a/include/webcpp/crypto/curves/secp256k1/ellswift.hpp b/include/webcpp/crypto/curves/secp256k1/ellswift.hpp new file mode 100644 index 00000000..284a1c2d --- /dev/null +++ b/include/webcpp/crypto/curves/secp256k1/ellswift.hpp @@ -0,0 +1,187 @@ +// 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 +#include +#include + +namespace webcpp::crypto::detail { + +/** + * The refusal of a backend other than libsecp256k1 by the family `families::secp256k1_ellswift`: + * the functions of `curves/secp256k1/ellswift.hpp`. + * + * @tparam Backend The backend named. + */ +template +struct secp256k1_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1_ELLSWIFT(Backend); +}; + +} // namespace webcpp::crypto::detail + +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 crypto's 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_refuses_others); + 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_refuses_others); + 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 crypto's 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_refuses_others); + 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 (!webcpp::crypto::detail::secp256k1_accepted( + secp256k1_ellswift_create(access::context(key_pair), encoded_key.data(), + seckey32.bytes.data(), randomness.data()))) { + 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_refuses_others); + 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 (!webcpp::crypto::detail::secp256k1_accepted(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))) { + return error::backend_failure; + } + return shared_secret; +} + +} // namespace webcpp::crypto::curves::secp256k1 + +#endif // WEBCPP_CRYPTO_CURVES_SECP256K1_ELLSWIFT_HPP diff --git a/include/webcpp/crypto/curves/secp256k1/formats.hpp b/include/webcpp/crypto/curves/secp256k1/formats.hpp new file mode 100644 index 00000000..e3587029 --- /dev/null +++ b/include/webcpp/crypto/curves/secp256k1/formats.hpp @@ -0,0 +1,249 @@ +// 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. `pem::armour` and + `pem::unarmour` (``, on libsodium) turn either into PEM text. + + @see "Keys in files: SPKI, PKCS#8 and PEM", 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 +#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_refuses_others); + webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); + if (output_bytes.size() < max_spki_size) { + return error::invalid_input_size; + } + 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_refuses_others); + 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_refuses_others); + 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; + } + if (output_bytes.size() < max_pkcs8_size) { + return error::invalid_input_size; + } + 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 const public_point = webcpp::crypto::detail::secp256k1_public_point( + secp256k1_context_static, 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_refuses_others); + 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{}; + // Not const: the branch reads it again after the mark (detail/declassify.hpp's tip); the + // comparison runs on the secret's bytes, and its verdict is public. + // NOLINTNEXTLINE(misc-const-correctness): see above + bool is_same = + encode_pkcs8(*made_pair, encoded_again).has_value() && equal(encoded_again, pkcs8_bytes); + WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&is_same, sizeof is_same); + 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/musig.hpp b/include/webcpp/crypto/curves/secp256k1/musig.hpp new file mode 100644 index 00000000..e66e27bd --- /dev/null +++ b/include/webcpp/crypto/curves/secp256k1/musig.hpp @@ -0,0 +1,741 @@ +// 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 +#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; +}; + +/** + * The refusal of a backend other than libsecp256k1 by the family `families::secp256k1_musig`: the + * functions of `curves/secp256k1/musig.hpp`. + * + * @tparam Backend The backend named. + */ +template +struct secp256k1_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1_MUSIG(Backend); +}; + +} // 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_refuses_others); + 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_refuses_others); + 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 const signer_point = webcpp::crypto::detail::secp256k1_public_point( + access::context(signer), access::pair(signer)); + auto made_secret = access::make_opaque(); + auto made_public = access::make_opaque(); + auto& state = access::native(made_secret); + if (!webcpp::crypto::detail::secp256k1_accepted(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()))) { + 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_refuses_others); + 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_refuses_others); + 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_refuses_others); + 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 const signer_point = webcpp::crypto::detail::secp256k1_public_point( + access::context(signer), 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 (!webcpp::crypto::detail::secp256k1_accepted(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)))) { + 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_refuses_others); + 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_refuses_others); + 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_refuses_others); + 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_refuses_others); + 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_refuses_others); + 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_refuses_others); + 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_refuses_others); + 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_refuses_others); + 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/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp b/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp new file mode 100644 index 00000000..87269d68 --- /dev/null +++ b/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp @@ -0,0 +1,623 @@ +// 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 +#include +#include +#include + +namespace webcpp::crypto::detail { + +/** + * The refusal of a backend other than libsecp256k1 by the family + * `families::secp256k1_silent_payments`: the functions of `curves/secp256k1/silent_payments.hpp`. + * + * @tparam Backend The backend named. + */ +template +struct secp256k1_refusal { + WEBCPP_CRYPTO_DETAIL_REFUSE_SECP256K1_SILENT_PAYMENTS(Backend); +}; + +/** + * 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 { + // Exactly the concept's type: its span points into storage the lookup owns. + std::optional> 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 exactly + * `std::optional>`: a span over the label's 32-byte tweak, or + * `std::nullopt`. The lookup owns the bytes the span points into for the call: they stay valid + * until the lookup is called again, since libsecp256k1 reads them after the lookup returns. A + * result returned by value, such as a `std::array` or a `std::optional` of one, would be gone by + * then, so no other result type is accepted, a convertible one included. The lookup is noexcept, + * since libsecp256k1's C frames are between the scan and the lookup. + * + * @tparam LabelLookup The lookup's type. + */ +template +concept label_lookup = + std::is_nothrow_invocable_v> && + std::same_as>, + std::optional>>; + +/** 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. The recipients' pointers are sorted in place by scan key, as + * libsecp256k1 sorts them, and each run of one key is counted: O(n log n), nothing allocated. + * + * @param recipient_pointers The recipients' pointers, in the workspace. + * @return Whether a group is over the limit. + */ +[[nodiscard]] inline bool secp256k1_over_group_limit( + std::span recipient_pointers) noexcept { + auto const scan_key_order = [](secp256k1_silentpayments_recipient const* left_recipient, + secp256k1_silentpayments_recipient const* right_recipient) { + return secp256k1_ec_pubkey_cmp(secp256k1_context_static, &left_recipient->scan_pubkey, + &right_recipient->scan_pubkey) < 0; + }; + std::ranges::sort(recipient_pointers, scan_key_order); + std::size_t group_size = 0; + for (std::size_t index = 0; index < recipient_pointers.size(); ++index) { + bool const same_group = + index != 0 && !scan_key_order(recipient_pointers[index - 1], recipient_pointers[index]); + group_size = same_group ? group_size + 1 : 1; + if (group_size > curves::secp256k1::silent_payments::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_refuses_others); + 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 (!webcpp::crypto::detail::secp256k1_accepted(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))) { + if (recipient_count > group_limit && webcpp::crypto::detail::secp256k1_over_group_limit( + std::span(recipient_pointers, recipient_count))) { + 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