diff --git a/.gitignore b/.gitignore index a6516011..6db4c4e1 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ doc/html/ +node_modules +.node-modules/ diff --git a/AGENTS.md b/AGENTS.md index 3dc58ab5..c355acfe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,18 +9,40 @@ specific to crypto. ## What crypto is -- **webcpp's own library** (`"port-of": null`) over C backends: BearSSL, OpenSSL, ctaes and - libsecp256k1. The algorithms are the backends'; crypto is the interface shaped as Boost.Hash2's. +- **webcpp's own library** (`"port-of": null`) over C backends: BearSSL, OpenSSL, ctaes, + libsecp256k1 and libsodium (the superproject's `/third_party//sodium`, shared with + webcpp::hash). The algorithms are the backends'; crypto is the interface shaped as Boost.Hash2's. - **No oracle.** No original runs beside crypto: the evidence is the published vectors (the GCM - specification's cases, Wycheproof, FIPS 197, BIP340 and BIP341), the backends' own suites in the - lane `c-suites`, and the agreement tests, which compare two backends on random inputs (BearSSL - and OpenSSL on AES-GCM, ctaes and OpenSSL on the block cipher). + specification's cases, Wycheproof, FIPS 197, RFC 8439 and RFC 8032, BIP340 and BIP341), the + backends' own suites in the lane `c-suites`, and the agreement tests, which compare two backends + on random inputs. +- **One default backend per family and target, with its reason; no profile.** The capability table + (`supports_v`, `default_backend_t`) is generated, never read from a measurement. + +## The generators + +- `doc/tables/generate.py` reads `doc/tables/crypto.json`, the test Jamfiles, the message tests and + the superproject's Jamfile fixtures, and writes `doc/generated/*.adoc`, `doc/llms.txt`, + `include/webcpp/crypto/detail/capabilities.hpp`, `detail/defaults.hpp`, the defaults' aliases in + `build.jam`, `test/capabilities_test.cpp` and the Ed25519 cases' table from + `meta/ed25519_cases.json`. Each says it is generated: never edit it, change `crypto.json` or the + generator and run it again. `generate.py --check` writes nothing and fails on a difference; the + doc build runs it and `generate_test.py` (its tests, written first). +- A new family, backend, message test, fixture or MSVC case needs its `crypto.json` entry in the + same commit (`fixes` for each message, `fixtures` for each fixture, `lane` for the constant-time + lane's paths); the generator names what is missing. +- `generate.py --sizes ...` reads the own lane `sizes` (built at `variant=release`) into + `doc/tables/sizes.json`; `doc/performance.json` is `bench/collect.py`'s, release builds only. + Nothing that states a size or a speed is typed by hand. ## Cautions -- A backend's header supplies only the four traits (`block_state`, `block_engine`, `gcm_state`, - `gcm_engine`); every guard lives in the algorithm types. +- An algorithm type does every guard; a backend's header supplies only the six traits of + `detail/engines.hpp` (`block_state`, `block_engine`, `gcm_state`, `gcm_engine`, `aead_state`, + `aead_engine`) and, for the curves and `hybrid`, the functions of its own header. - A test of a backend is a `.cpp` of its own per backend, never a define that changes the backend of one source (spec section 4.3's pitfall). - Every C library is unchanged upstream code. A moved pin is a change of its own (CODING-GUIDELINES.md chapter 5, rule 12). +- X25519's constant time on wasip2 is an open finding (the page's constant-time table): do not + describe it as a pass. diff --git a/LICENSE-LIBSODIUM-DOC.txt b/LICENSE-LIBSODIUM-DOC.txt new file mode 100644 index 00000000..31177b5a --- /dev/null +++ b/LICENSE-LIBSODIUM-DOC.txt @@ -0,0 +1,13 @@ +Copyright (c) 2014-2026, Frank Denis + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/LICENSE-LIBSODIUM.txt b/LICENSE-LIBSODIUM.txt new file mode 100644 index 00000000..95c22fba --- /dev/null +++ b/LICENSE-LIBSODIUM.txt @@ -0,0 +1,18 @@ +/* + * ISC License + * + * Copyright (c) 2013-2026 + * Frank Denis + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/README.md b/README.md index 2e1d1cc2..c2dc799a 100644 --- a/README.md +++ b/README.md @@ -7,17 +7,28 @@ MSVC), wasip2, wasip3 and Emscripten. - `webcpp::crypto`: a `random_device` that reads the operating system's or the browser's generator, a constant-time `equal` for tags and MACs, and `error`, every failure's value. - `webcpp::crypto::ciphers`: AES-GCM (`gcm`, `aes128_gcm`, `aes256_gcm`) with keys of 16, 24 and - 32 bytes, and the AES block cipher (`aes128`, `aes192`, `aes256`). + 32 bytes, the AES block cipher (`aes128`, `aes192`, `aes256`), the ChaCha20-Poly1305 AEADs, and + NaCl's and libsodium's secret boxes (`secretbox`, `secretbox_xchacha20poly1305`). - `webcpp::crypto::curves::secp256k1`: BIP 340 Schnorr and ECDSA signatures, their verification, ECDH, ECDSA's strict DER and low-S forms, and the x-only tweak. +- `webcpp::crypto::curves::ed25519`: Ed25519 signatures (RFC 8032) with strict verification, the + X25519 secret key of a key pair, and Ed25519ph over SHA-512 for a message given in pieces. +- `webcpp::crypto::curves::x25519`: X25519 key agreement (RFC 7748), refusing an all-zero shared + secret, `curves::ed25519::to_x25519_public` for a peer known by its Ed25519 key, and + `kx_keypair`, libsodium's `crypto_kx`, a session key for each direction of a client and a server. +- Ed25519's and X25519's keys in RFC 8410's SPKI and PKCS#8, as OpenSSL and WebCrypto write them, + and `webcpp::crypto::pem` for their PEM text, each decoded strictly. +- `webcpp::crypto::hybrid`: NaCl's and libsodium's boxes between two key pairs (`box`, + `box_xchacha20poly1305`), refusing a peer key of small order, and sealed boxes (`sealed_box`), + anonymous encryption to a public key. The algorithms are those of widely used, reviewed C libraries, each a backend that a program names in its own Jamfile and that webcpp builds from its sources: BearSSL (`/third_party//bearssl`), OpenSSL 3.5.9 (`/webcpp/crypto//openssl`, never the system's, refused -on Emscripten), ctaes (`/third_party//ctaes`) and libsecp256k1 (`/third_party//secp256k1`). Which -operation runs on which backend and target is the page's generated table, from the tests that run -each. Hashing and HMAC stay with Boost.Hash2. Protocols built on these primitives (Bitcoin, -Ethereum, Nostr) belong to domain libraries. +on Emscripten), ctaes (`/third_party//ctaes`), libsecp256k1 (`/third_party//secp256k1`) and +libsodium (`/third_party//sodium`). Which operation runs on which backend and target is the +page's generated table, from the tests that run each. Hashing and HMAC stay with Boost.Hash2. +Protocols built on these primitives (Bitcoin, Ethereum, Nostr) belong to domain libraries. ## Building and testing @@ -46,4 +57,7 @@ from `doc/tables/crypto.json` and the tests; `b2 libs/crypto/doc` checks them. crypto is under the Boost Software License, Version 1.0 (`LICENSE_1_0.txt`). The backends keep their own: BearSSL is MIT (`LICENSE-BEARSSL.txt`), ctaes is MIT (`LICENSE-CTAES.txt`), -libsecp256k1 is MIT (`LICENSE-SECP256K1.txt`) and OpenSSL is Apache-2.0. +libsecp256k1 is MIT (`LICENSE-SECP256K1.txt`), libsodium is ISC (`LICENSE-LIBSODIUM.txt`) and +OpenSSL is Apache-2.0. The documentation's sections on libsodium's families adapt parts of +libsodium's documentation (`jedisct1/libsodium-doc`), which is ISC +(`LICENSE-LIBSODIUM-DOC.txt`). diff --git a/bench/Jamfile b/bench/Jamfile new file mode 100644 index 00000000..4364b615 --- /dev/null +++ b/bench/Jamfile @@ -0,0 +1,38 @@ +# 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 throughput of each family's fixed operation per backend (throughput.cpp, +# bench/operations.hpp). throughput_check is the correctness test of the +# measured program, run in every lane of test/ (test/Jamfile builds this +# project): each operation checked once, never timed. The measurement itself +# is made by hand by collect.py, which runs the program built here at +# variant=release and writes doc/performance.adoc; no lane measures it. + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; +import webcpp-target ; + +webcpp.targets native wasip2 wasip3 emscripten ; + +# OpenSSL on the targets that have it; Emscripten has none. +rule with-openssl ( properties * ) +{ + if [ webcpp-target.target-of $(properties) ] in native wasip2 wasip3 + { + return /webcpp/crypto//openssl ; + } +} + +.requirements = /third_party//bearssl /third_party//ctaes + /third_party//secp256k1 /third_party//sodium + @with-openssl ; +webcpp.run throughput_check : throughput.cpp : $(.requirements) ; + +# The same program at variant=release, the one collect.py measures, built and +# run by hand (doc/performance.adoc); no lane measures it. +exe throughput : throughput.cpp : $(.requirements) release ; +explicit throughput ; diff --git a/bench/collect.py b/bench/collect.py new file mode 100755 index 00000000..4a9eb484 --- /dev/null +++ b/bench/collect.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python3 +# 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) + +"""Measures bench/throughput.cpp on each target and renders its data, after webcpp::hash's. + + collect.py --exe native= --exe wasip2= ... --invocations 5 \\ + --data libs/crypto/doc/performance.json --page libs/crypto/doc/performance.adoc + +Run from the superproject's root (the launchers' paths, tools/boost/asio-wasip2/run.sh and its +wasip3 twin, are relative to it), with the program bench/Jamfile builds at variant=release, +`b2 libs/crypto/bench//throughput` on each target; --data and --page are relative to the same +root. + +The page is built only from release builds: a program whose build directory, b2's +bench///..., is not variant=release, or does not say, is refused before anything +runs, and `--render-only` refuses data whose build is not BUILD. + +Each cell (a family on a backend, on a target) is run INVOCATIONS times, round-robin over the +cells so that a change of load on a shared machine falls on all of them alike; each invocation +times five runs of the family's fixed operation and reports their median, in microseconds per +operation. The data holds, per cell, every invocation's median, their median, and the fastest and +slowest single run. The operation each cell's program reports must be the one +doc/tables/crypto.json states for its family (the size matrix's), or the cell is refused. A time +never fails this script: only a program that does not run, or a cell it does not know, does. +`--render-only` rewrites the page from the data. + +libsodium's x86-64 assembly (HAVE_AMD64_ASM, design D7) is recorded beside the table as not +measured yet, with its reason, until an x86-64 machine runs a scratch build of it by hand. +""" + +import argparse +import datetime +import json +import os +import platform +import subprocess +import sys +from pathlib import Path + +# What the page is built from, and only from: bench/Jamfile's throughput, at variant=release. +BUILD = "variant=release" +RELEASE_ONLY = ( + "the page is built only from release builds: bench/Jamfile's throughput at " + BUILD +) + +LAUNCHERS = { + "native": [], + "wasip2": ["tools/boost/asio-wasip2/run.sh"], + "wasip3": ["tools/boost/asio-wasip3/run.sh"], + "emscripten": ["node"], +} +TARGETS = ["native", "wasip2", "wasip3", "emscripten"] +CRYPTO_JSON = Path(__file__).resolve().parent.parent / "doc/tables/crypto.json" +# Design D7's libsodium x86-64 assembly: the rows the page records, and why they are not measured. +AMD64_ASM = { + "rows": ["Ed25519 signature, libsodium with HAVE_AMD64_ASM", + "X25519 agreement, libsodium with HAVE_AMD64_ASM"], + "status": "not measured yet", + "reason": "x86-64 assembly runs only on an x86-64 machine; this page's machine is arm64. " + "D7 asks for the rows recorded, never used: webcpp builds libsodium without it.", +} + + +def variant_of(exe): + """The variant b2 built exe at, as its build directory names it, bench///...; + None when its path does not say.""" + parts = Path(exe).resolve().parts + if "bench" not in parts: + return None + last = len(parts) - 1 - parts[::-1].index("bench") + after = parts[last + 1:] + return after[1] if len(after) > 2 else None + + +def check_release(exes): + """Exits naming each program not built at variant=release, before anything runs.""" + others = [] + for target, exe in exes.items(): + variant = variant_of(exe) + if variant is None: + others.append(f"{target}={exe} is not in b2's bench///..., so its " + "variant cannot be read") + elif variant != "release": + others.append(f"{target}={exe} was built at variant={variant}") + if others: + sys.exit("collect.py: " + ", ".join(others) + ": " + RELEASE_ONLY) + + +def crypto_json(): + with open(CRYPTO_JSON, encoding="utf-8") as f: + return json.load(f) + + +def median(values): + values = sorted(values) + n = len(values) + return values[n // 2] if n % 2 else (values[n // 2 - 1] + values[n // 2]) / 2 + + +def tool_version(command): + try: + out = subprocess.run(command, capture_output=True, text=True, check=False) + return (out.stdout or out.stderr).strip().splitlines()[0] + except (OSError, IndexError): + return "unknown" + + +def sysctl(name): + try: + out = subprocess.run(["sysctl", "-n", name], capture_output=True, text=True, check=False) + return out.stdout.strip() + except OSError: + return "" + + +def machine(): + return { + "cpu": sysctl("machdep.cpu.brand_string") or platform.processor() or platform.machine(), + "architecture": platform.machine(), + "cores": os.cpu_count(), + "memory_gib": int(sysctl("hw.memsize") or 0) // 2**30, + "os": f"{platform.system()} {platform.release()}", + "wasmtime": tool_version(["wasmtime", "--version"]), + "node": tool_version(["node", "--version"]), + } + + +def run(target, command): + done = subprocess.run(LAUNCHERS[target] + command, capture_output=True, text=True, + check=False) + if done.returncode != 0: + sys.exit(f"{target} {' '.join(command[1:])}: exit {done.returncode}\n" + f"{done.stdout}{done.stderr}") + return done.stdout + + +def cells_of(target, exe, families): + """The cells the program was built with, which it lists without measuring; each must be a + family of crypto.json.""" + cells = [tuple(line.split()) for line in run(target, [exe, "--list"]).splitlines() if line] + for family, backend in cells: + if family not in families: + sys.exit(f"collect.py: {target} lists {family} {backend}, and crypto.json has no " + f"family {family}") + return cells + + +def measure(exes, invocations): + data = crypto_json() + families = {family["name"]: family for family in data["families"]} + cases = {} + for target, exe in exes.items(): + for family, backend in cells_of(target, exe, families): + cases[(target, family, backend)] = {"exe": exe, "results": []} + loads = [os.getloadavg()] + for _ in range(invocations): + for (target, family, backend), case in cases.items(): + line = run(target, [case["exe"], family, backend, "--runs", "5"]).strip() + case["results"].append(json.loads(line.splitlines()[-1])) + loads.append(os.getloadavg()) + out = [] + for (target, family, backend), case in cases.items(): + results = case["results"] + stated = families[family]["measured"] + if results[0]["operation"] != stated: + sys.exit(f"collect.py: {target} {family} {backend} measures " + f"{results[0]['operation']!r}, and crypto.json states {stated!r}") + medians = [r["median_us"] for r in results] + runs = [t for r in results for t in r["runs_us"]] + out.append({ + "family": family, + "backend": backend, + "target": target, + "operation": stated, + "compiler": results[0]["compiler"], + "repetitions": [r["repetitions"] for r in results], + "invocations": len(results), + "runs_per_invocation": len(results[0]["runs_us"]), + "invocation_medians_us": medians, + "median_us": median(medians), + "min_us": min(runs), + "max_us": max(runs), + }) + return { + "measurement": "each family's fixed operation per backend and target, " + "bench/operations.hpp", + "date": datetime.date.today().isoformat(), + "machine": machine(), + "load_average_before_after": [list(loads[0]), list(loads[1])], + "build": BUILD, + "cases": out, + "amd64_asm": AMD64_ASM, + } + + +# When the page warns that the machine was loaded: a shared machine shows in the spread before a +# single core is short, so the threshold is half the cores. +LOADED_RULE = "the larger of the two 1-minute load averages exceeds half the core count" + + +def loaded(data): + """Whether the measurement ran on a loaded machine, by LOADED_RULE.""" + load = data["load_average_before_after"] + return max(load[0][0], load[1][0]) > (data["machine"]["cores"] or 1) / 2 + + +def fmt_load(load): + return "/".join(f"{x:.0f}" for x in load) + + +def fmt_us(value): + """Microseconds as the page shows them: two decimals, or three significant digits below 1.""" + return f"{value:,.2f}" if value >= 1 else f"{value:.3g}" + + +def per_second(case): + """What a cell does in a second: MiB for a seal, operations for the rest.""" + if case["operation"].startswith("seal of 16 KiB"): + return f"{16 / 1024 / (case['median_us'] / 1e6):,.0f} MiB/s" + return f"{1e6 / case['median_us']:,.0f} operations/s" + + +def render(data, page): + table = crypto_json() + titles = {family["name"]: family["title"] for family in table["families"]} + order = [family["name"] for family in table["families"]] + backends = {name: facts["title"] for name, facts in table["backends"].items()} + machine_info = data["machine"] + lines = [ + "// 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 bench/collect.py from doc/performance.json: do not edit.", + "", + "[#crypto-performance]", + "=== Throughput", + "", + "How long each family's fixed operation takes on each backend and target, the operation", + "the size matrix's programs call (bench/operations.hpp). A dated reference, measured by", + "hand, that decides nothing: every default is chosen by the reason", + "<> states, whatever these figures say.", + "", + f"Measured on {data['date']} on {machine_info['cpu']} ({machine_info['architecture']}),", + f"{machine_info['cores']} cores, {machine_info['memory_gib']} GiB, {machine_info['os']};", + f"WebAssembly under {machine_info['wasmtime']} (wasip2, wasip3) and node", + f"{machine_info['node']} (Emscripten); built with {data['build']}. The CI's runners", + "are measured when the owner runs this by hand on them.", + "", + "Each cell is the median of its invocations' medians, each of five timed runs, in", + "microseconds per operation, with the fastest and slowest single run beside it: the", + "spread is part of the result.", + "", + ] + load = data["load_average_before_after"] + lines += [ + f"The machine's 1, 5 and 15 minute load averages were {fmt_load(load[0])} before and", + f"{fmt_load(load[1])} after, on {machine_info['cores']} cores.", + "", + ] + if loaded(data): + lines += [ + "WARNING: the machine was shared and loaded while this was measured (rule: " + + LOADED_RULE + "). Read the spread, not a single figure.", + "", + ] + lines += [ + '[cols="3,2,1,1,1,1,2",options="header"]', + "|===", + "| Operation | Backend | Target | Median (µs) | Fastest (µs) | Slowest (µs) " + "| Per second", + ] + cases = sorted(data["cases"], key=lambda c: (order.index(c["family"]), c["backend"], + TARGETS.index(c["target"]))) + for c in cases: + lines += [ + "", + f"| {titles[c['family']]}: {c['operation']}", + f"| {backends[c['backend']]}", + f"| {c['target']}", + f"| {fmt_us(c['median_us'])}", + f"| {fmt_us(c['min_us'])}", + f"| {fmt_us(c['max_us'])}", + f"| {per_second(c)}", + ] + lines += [ + "|===", + "", + "Compilers: " + "; ".join( + f"{target}: {c['compiler']}" for target in TARGETS + for c in [next((c for c in cases if c["target"] == target), None)] if c) + ".", + "", + "OpenSSL is not built for Emscripten, so its rows are native and WASI only; on WASI it", + "is built `no-asm`, natively with its assembly.", + "", + "libsodium's x86-64 assembly (design D7): " + + "; ".join(data["amd64_asm"]["rows"]) + f": {data['amd64_asm']['status']}. " + + data["amd64_asm"]["reason"], + "", + ] + with open(page, "w", encoding="utf-8") as f: + f.write("\n".join(lines)) + + +def main(): + parser = argparse.ArgumentParser(description="Measures bench/throughput.cpp on each target.") + parser.add_argument("--exe", action="append", default=[], metavar="TARGET=PATH") + parser.add_argument("--invocations", type=int, default=5) + parser.add_argument("--data", required=True) + parser.add_argument("--page", required=True) + parser.add_argument("--render-only", action="store_true") + args = parser.parse_args() + if args.render_only: + with open(args.data, encoding="utf-8") as f: + data = json.load(f) + if data.get("build") != BUILD: + sys.exit(f"collect.py: {args.data} was measured with build {data.get('build')}, not " + f"{BUILD}: {RELEASE_ONLY}") + else: + exes = dict(item.split("=", 1) for item in args.exe) + unknown = sorted(set(exes) - set(TARGETS)) + if unknown: + sys.exit(f"collect.py: no target {', '.join(unknown)}; the targets are " + f"{', '.join(TARGETS)}") + check_release(exes) + data = measure(exes, args.invocations) + with open(args.data, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2) + f.write("\n") + render(data, args.page) + + +if __name__ == "__main__": + main() diff --git a/bench/operations.hpp b/bench/operations.hpp new file mode 100644 index 00000000..dcfb68ee --- /dev/null +++ b/bench/operations.hpp @@ -0,0 +1,258 @@ +// 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) + +// Each family's fixed operation, the one its size (test/sizes/) and its throughput +// (bench/throughput.cpp) measure: an operation of a family on a backend is the class +// `` below, made once from a seed byte, outside what is measured. Its `run()` does +// the operation once and returns a byte of what it gave, which the caller prints or folds in, so +// that the optimiser keeps it; its `check()` says whether the operation's result is right (an open +// of what it sealed, a verification of what it signed, both sides of an agreement). An operation +// the library refuses ends the program: a figure measured on a failure would be a wrong one. +// `operation` names what is measured, the text crypto.json's family states (bench/collect.py +// checks that the two agree). A seal repeats under one key and one IV: a measurement, never a use. + +#ifndef WEBCPP_CRYPTO_BENCH_OPERATIONS_HPP +#define WEBCPP_CRYPTO_BENCH_OPERATIONS_HPP + +#include +#include +#include +#include +#include +#include +#ifdef WEBCPP_CRYPTO_HAS_SECP256K1 +#include +#endif + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::crypto::bench { + +// The bytes an AEAD seals at once. +inline constexpr std::size_t message_size = std::size_t{16} * 1024; + +// Ends the program, naming the operation the library refused. +[[noreturn]] inline void refused(std::string_view what) { + static_cast( + std::fprintf(stderr, "refused: %.*s\n", static_cast(what.size()), what.data())); + std::exit(1); +} + +// N bytes, each of them value. +template +std::array filled(std::uint8_t value) { + std::array bytes{}; + bytes.fill(value); + return bytes; +} + +// What a result holds, or the end of the program. +template +auto take(Result&& result, std::string_view what) { + if (!result) { + refused(what); + } + return *std::forward(result); +} + +// The baseline's operation (test/sizes/baseline.cpp): nothing of crypto, the harness alone, a +// result taken and refused as every operation's is, so that what a sized program adds to the +// baseline is its operation's code, not the harness's. +class nothing { +public: + static constexpr std::string_view operation = "nothing: the harness alone"; + + explicit nothing(std::uint8_t seed) : seed_(seed) {} + + [[nodiscard]] std::uint8_t run() const { + boost::system::result const made = + seed_ == 0 ? boost::system::result(error::backend_failure) + : boost::system::result(seed_); + return take(made, "nothing"); + } + + static bool check() { return true; } + +private: + std::uint8_t seed_; +}; + +// The encryption of one 16-byte block with a 256-bit key. +template +class block_encryption { +public: + static constexpr std::string_view operation = "encryption of one 16-byte block, 256-bit key"; + + explicit block_encryption(std::uint8_t seed) + : block_(filled(static_cast(seed + 1U))), + cipher_(take(Cipher::make(filled(seed)), "make")) {} + + std::uint8_t run() { + if (!cipher_.encrypt(block_)) { + refused("encrypt"); + } + return block_[0]; + } + + bool check() { + auto const plain = block_; + static_cast(run()); + bool const changed = block_ != plain; + if (!cipher_.decrypt(block_)) { + refused("decrypt"); + } + return changed && block_ == plain; + } + +private: + std::array block_{}; + Cipher cipher_; +}; + +// The seal of 16 KiB, in place, without additional data. +template +class aead_seal { +public: + static constexpr std::string_view operation = "seal of 16 KiB, 256-bit key"; + + explicit aead_seal(std::uint8_t seed) + : iv_(filled(static_cast(seed + 2U))), + data_(filled(seed)), + aead_(take(Aead::make(filled(seed)), "make")) {} + + std::uint8_t run() { return take(aead_.seal(iv_, {}, data_), "seal").data()[0]; } + + bool check() { + auto const plain = data_; + auto const tag = take(aead_.seal(iv_, {}, data_), "seal"); + bool const changed = data_ != plain; + return changed && aead_.open(iv_, {}, data_, tag).has_value() && data_ == plain; + } + +private: + std::array iv_{}; + std::array data_{}; + Aead aead_; +}; + +// AES-256-GCM. +template +using gcm = aead_seal>>; + +// The AES block cipher. +template +using aes_block = block_encryption>; + +// ChaCha20-Poly1305 (RFC 8439). +template +using chacha20_poly1305 = aead_seal>; + +// The original ChaCha20-Poly1305. +template +using chacha20_poly1305_original = aead_seal>; + +// XChaCha20-Poly1305. +template +using xchacha20_poly1305 = aead_seal>; + +#ifdef WEBCPP_CRYPTO_HAS_SECP256K1 +// A BIP340 signature of a 32-byte message on secp256k1. +template +class secp256k1 { +public: + static constexpr std::string_view operation = "BIP340 signature of a 32-byte message"; + + explicit secp256k1(std::uint8_t seed) + : message_(filled<32>(static_cast(seed + 3U))), + key_(take(curves::secp256k1::basic_keypair::make( + filled<32>(static_cast(seed | 1U))), + "make")) {} + + std::uint8_t run() { return take(key_.sign_schnorr(message_, aux_), "sign")[0]; } + + bool check() { + auto const signature = take(key_.sign_schnorr(message_, aux_), "sign"); + auto const public_key = take(key_.xonly_public_key(), "xonly_public_key"); + return curves::secp256k1::verify_schnorr(signature, message_, public_key) + .has_value(); + } + +private: + std::array message_{}; + std::array aux_{}; + curves::secp256k1::basic_keypair key_; +}; +#endif + +// An Ed25519 signature of a 32-byte message. +template +class ed25519 { +public: + static constexpr std::string_view operation = "signature of a 32-byte message"; + + explicit ed25519(std::uint8_t seed) + : message_(filled<32>(static_cast(seed + 4U))), + key_(take(curves::ed25519::basic_keypair::make(filled<32>(seed)), "make")) {} + + std::uint8_t run() { return take(key_.sign(message_), "sign")[0]; } + + bool check() { + auto const signature = take(key_.sign(message_), "sign"); + auto const public_key = take(key_.public_key(), "public_key"); + return curves::ed25519::verify(public_key, message_, + signature) + .has_value(); + } + +private: + std::array message_{}; + curves::ed25519::basic_keypair key_; +}; + +// An X25519 agreement of a secret key with a peer's public key. +template +class x25519 { +public: + static constexpr std::string_view operation = "agreement of a secret key and a public key"; + + explicit x25519(std::uint8_t seed) { + secret_.fill(seed); + peer_secret_.fill(static_cast(seed + 5U)); + peer_public_ = take(curves::x25519::public_key(peer_secret_), "public_key"); + } + + std::uint8_t run() { + auto const shared = take(curves::x25519::agree(secret_, peer_public_), "agree"); + return shared.bytes()[0]; + } + + bool check() { + auto const own_public = take(curves::x25519::public_key(secret_), "public_key"); + auto const shared = take(curves::x25519::agree(secret_, peer_public_), "agree"); + auto const peer_shared = + take(curves::x25519::agree(peer_secret_, own_public), "agree"); + return std::ranges::equal(shared.bytes(), peer_shared.bytes()); + } + +private: + std::array secret_{}; + std::array peer_secret_{}; + std::array peer_public_{}; +}; + +} // namespace webcpp::crypto::bench + +#endif // WEBCPP_CRYPTO_BENCH_OPERATIONS_HPP diff --git a/bench/throughput.cpp b/bench/throughput.cpp new file mode 100644 index 00000000..d075e42a --- /dev/null +++ b/bench/throughput.cpp @@ -0,0 +1,217 @@ +// 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 throughput of each family's fixed operation (bench/operations.hpp) on each backend this +// build links: AES-256-GCM on BearSSL and OpenSSL, the AES block cipher on ctaes and OpenSSL, +// BIP340 signing on libsecp256k1, Ed25519 signing and X25519 agreement on libsodium, and the +// ChaCha20-Poly1305 family on libsodium, BearSSL and OpenSSL (OpenSSL natively and on WASI only). +// +// Run with a family and a backend, `throughput [--runs N]`, it repeats the +// operation enough times for a run to last at least 50 ms, times N runs (5 by default), and prints +// one JSON line: the family, the backend, the operation, the target, the compiler, the repetitions +// of a run, each run's microseconds per operation and their median. `--list` prints the cells this +// build has, one " " per line. Run with no argument, it is the correctness test: +// each cell's operation is checked once (an open of what it sealed, a verification of what it +// signed, both sides of an agreement), and the program exits 0 only when every check holds. A +// measurement never fails on its time; bench/collect.py runs it and writes doc/performance.adoc. + +#include +#include +#include +#include +#ifdef WEBCPP_CRYPTO_HAS_OPENSSL +#include +#endif + +#include "operations.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace bench = webcpp::crypto::bench; +namespace backends = webcpp::crypto::backends; + +namespace { + +#ifdef WEBCPP_TARGET_WASIP2 +constexpr std::string_view target = "wasip2"; +#elif defined(WEBCPP_TARGET_WASIP3) +constexpr std::string_view target = "wasip3"; +#elif defined(WEBCPP_TARGET_EMSCRIPTEN) +constexpr std::string_view target = "emscripten"; +#else +constexpr std::string_view target = "native"; +#endif + +// The compiler, as it names itself: MSVC defines no __VERSION__. +#ifdef __VERSION__ +constexpr std::string_view compiler = __VERSION__; +#elif defined(_MSC_FULL_VER) +#define WEBCPP_CRYPTO_BENCH_STRING(x) #x +#define WEBCPP_CRYPTO_BENCH_VERSION(x) WEBCPP_CRYPTO_BENCH_STRING(x) +constexpr std::string_view compiler = "MSVC " WEBCPP_CRYPTO_BENCH_VERSION(_MSC_FULL_VER); +#else +constexpr std::string_view compiler = "unknown"; +#endif + +// The shortest run measured, in seconds: long enough that the clock's resolution is no part of it. +constexpr double shortest_run = 0.05; + +// A cell: a family on a backend, its operation, and what measures and checks it. +struct cell { + std::string_view family; + std::string_view backend; + std::string_view operation; + void (*measure)(std::string_view family, int runs); + bool (*check)(); +}; + +// The seconds of `repetitions` operations, with a byte folded from their results. +template +double timed(Operation& operation, std::uint64_t repetitions, std::uint8_t& folded) { + auto const start = std::chrono::steady_clock::now(); + for (std::uint64_t i = 0; i < repetitions; ++i) { + folded = static_cast(folded ^ operation.run()); + } + return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); +} + +void print_string(char const* key, std::string_view value) { + std::printf(R"("%s": "%.*s", )", key, static_cast(value.size()), value.data()); +} + +template +void measure(std::string_view family, int runs) { + Operation operation(1); + std::uint8_t folded = 0; + std::uint64_t repetitions = 1; + while (timed(operation, repetitions, folded) < shortest_run) { + repetitions *= 2; + } + std::vector per_operation_us; + per_operation_us.reserve(static_cast(runs)); + for (int run = 0; run < runs; ++run) { + per_operation_us.push_back(timed(operation, repetitions, folded) * 1e6 / + static_cast(repetitions)); + } + std::vector sorted = per_operation_us; + std::ranges::sort(sorted); + std::size_t const middle = sorted.size() / 2; + double const median = + sorted.size() % 2 != 0 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2; + std::printf("{"); + print_string("family", family); + print_string("backend", Operation::backend_name); + print_string("operation", Operation::operation); + print_string("target", target); + print_string("compiler", compiler); + std::printf(R"("repetitions": %llu, "runs_us": [)", + static_cast(repetitions)); + for (std::size_t i = 0; i < per_operation_us.size(); ++i) { + std::printf("%s%.4f", i == 0 ? "" : ", ", per_operation_us[i]); + } + std::printf(R"(], "median_us": %.4f, "folded": %u})", median, static_cast(folded)); + std::printf("\n"); +} + +template +bool check() { + Operation operation(1); + return operation.check(); +} + +// The operation of a family on Backend, which also names its backend. +template