diff --git a/README.md b/README.md index dd0e79f..fbd5239 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ tag is placed. | asio | [genesis](libraries/asio/openspec/changes/genesis) | asio: Boost.Asio across native, browsers and WASI | wrapper | implementing | | 2026-10-11 | [code](https://github.com/webcpporg/asio) | | beast | [genesis](libraries/beast/openspec/changes/genesis) | beast: existing Boost.Beast applications on WASIp2, WASIp3 and Emscripten | wrapper | implementing | | 2026-11-06 | [code](https://github.com/webcpporg/beast) | | cobalt | [genesis](libraries/cobalt/openspec/changes/genesis) | cobalt: existing Boost.Cobalt applications on native, browsers and WASIp2/P3 | wrapper | implementing | | 2026-11-06 | [code](https://github.com/webcpporg/cobalt) | +| codecs | [genesis](libraries/codecs/openspec/changes/genesis) | codecs: one contract for turning bytes and values into text and back, one header per format, tokens like Boost.URL | own | implementing | | 2026-11-24 | [code](https://github.com/webcpporg/codecs) | | config | [genesis](libraries/config/openspec/changes/archive/2026-10-09-genesis) | config: webcpp's configuration, the target, exceptions and version every library includes first | own | implemented | 0.1.0 | 2026-10-09 | [code](https://github.com/webcpporg/config/tree/2fad162) | | crypto | [genesis](libraries/crypto/openspec/changes/genesis) | crypto: authenticated encryption, randomness and secp256k1 over C backends | wrapper | implementing | | 2026-10-11 | [code](https://github.com/webcpporg/crypto) | | crypto | [foundation](libraries/crypto/openspec/changes/foundation) | crypto: the cryptographic foundation, every backend in full, one default per family and a browser backend | wrapper | accepted | | 2026-11-14 | | diff --git a/libraries/codecs/openspec/changes/genesis/.openspec.yaml b/libraries/codecs/openspec/changes/genesis/.openspec.yaml new file mode 100644 index 0000000..8d82f41 --- /dev/null +++ b/libraries/codecs/openspec/changes/genesis/.openspec.yaml @@ -0,0 +1,11 @@ +schema: spec-driven +created: 2026-11-24 +webcpp: + library: codecs + title: "codecs: one contract for turning bytes and values into text and back, one header per format, tokens like Boost.URL" + kind: own + port_of: null + status: implementing + release: null + implementation: https://github.com/webcpporg/codecs + decided: 2026-11-24 diff --git a/libraries/codecs/openspec/changes/genesis/design.md b/libraries/codecs/openspec/changes/genesis/design.md new file mode 100644 index 0000000..1d2f488 --- /dev/null +++ b/libraries/codecs/openspec/changes/genesis/design.md @@ -0,0 +1,1722 @@ +## Context + +webcpp converts bytes to text in four places today, each its own way: + +- webcpp::trystero, `libs/trystero/include/webcpp/trystero/protocol/text.hpp`: `to_hex` and + `base64_encode` return a `std::pmr::string`, `from_hex` and `base64_decode` a + `std::optional`; no error value says what was wrong, and the tables are indexed by the + data. +- webcpp::document, `libs/document/include/webcpp/document/traits.hpp`: the byte policies + `base64` (RFC 4648 with padding, the default) and `base64url` (section 5, without padding), with + their own alphabet constant. +- webcpp::crypto's `formats` change (approved 2026-11-22, not built): `crypto::encode(format, + value)` and `crypto::decode(format, input)` with the format as a value, a fixed result + `crypto::encoded`, a PEM armor of crypto's own. +- webcpp::hash has no base58check yet; Bitcoin's addresses, WIF keys and BIP-32 extended keys need + it. + +The prior art (checked by the owner): Boost has no general codec library. `boost/algorithm/hex.hpp` +is hex alone, over iterators, failing by exception; Boost.Serialization's base64 is a chain of +dataflow iterators without padding; Boost.Beast's base64 is in `detail`; Boost.URL's +percent-encoding (`encoded_size`, `encode` into a buffer or a `StringToken`, `decoded_size`, +`decode`) is the model this library follows. WG21 has no `std::base64` proposal. cppcodec gives one +class per variant with a fixed set of output types; @scure/base composes small coders +(`chain(radix2(5), alphabet(...), join(''))`); RustCrypto's `der` lets a type implement `Encode` +and `Decode`, which is `value_codec` here. + +## Goals / Non-Goals + +**Goals:** one contract for every conversion of bytes or typed values to and from text or bytes +in webcpp; formats as values, each in its own header; results through tokens that interoperate +with Boost.URL; no heap when sizes are known at compile time; secrecy carried by the types and +honoured by every buffer the library touches; constant time where a secret passes through hex, +base32, base64, bech32 or the armor, and through base58 when the operation is secret; errors as values; every target webcpp builds for. +The conversion contract of all of webcpp (owner decisions 15 and 16): a one-shot transformer and +a stream transformer of any input type to any output type, which codecs' formats implement and a +later library of other data (webcpp::media) implements unchanged; native streaming for every text +format that can stream, composed by types alone. + +**Non-goals:** webcpp::media (audio, video, photos over FFmpeg, libwebp or WebCodecs), a later +and separate library that implements this contract; nothing in this change is written for it +beyond the contract's generality and a test with a toy non-byte transformer (owner decision 15); +an asynchronous helper (`async_transcode` over asio's or cobalt's sources and sinks), a possible +later change (owner decision 21); streaming of typed values (`value_codec`), which are whole; +MIME's line-wrapped base64 (76 columns); RFC 7468's explanatory text and RFC 1421's headers +around an armor; base58's double SHA-256 checksum (what Bitcoin calls Base58Check, webcpp::hash's +`base58_with_checksum`, owner decision 26) and crypto's key formats, which are their libraries' follow-ups; +segwit's rules over bech32 (version 0 in bech32 and 1 and above in bech32m, the valid program +sizes, the networks' prefixes) and Lightning's invoice fields, a future webcpp::bitcoin's (owner +decision 27); ASN.1 in general; the migration of trystero, document, hash and crypto, +each a change of its own library. + +**Anti-goals:** a format registered by the core header; a format reachable without its header; a +heap allocation where the size is known at compile time; a secret in an unwiped buffer of the +library's; a table lookup or a branch on secret data in hex, base32, base64, bech32 or the armor, or in +base58 when the operation is secret; a timing guard, a wipe, a secret type or a constant-time +primitive of codecs' own (webcpp::secure's, owner decision 14); a heap allocation, a virtual call +or a `std::function` in a stream transformer's processing loop; a concept that assumes bytes, +characters, constant time or secrecy; a category tag (encoder, decoder) on a transformer. + +## Owner decisions (2026-11-24, binding) + +1. **Purpose.** One vocabulary for converting bytes and typed values to and from text or bytes + across webcpp, instead of each library's own encode and decode. trystero's `text.hpp` and + document's byte policies migrate later, in follow-ups. (Widened by decision 15: the core's + contract is webcpp's conversion contract for any data, not bytes and text alone.) +2. **The core header ``** has no dependencies and registers no format. It holds + `codec` (bytes to and from text), `value_codec` (a typed value to and + from bytes or text), the concepts `format`, `encodable` and `decodable`, + `encoded_size(format, input)`, `max_decoded_size(format, input)`, the buffer forms + `encode(format, input, std::span out) -> result` and `decode(format, text, + std::span out) -> result`, the token forms `encode(format, input, + token = {})` and `decode(format, text, token = {})`, the typed `decode(format, input) -> + result`, the tokens of `codecs::tokens` (`append_to`, `assign_to`, `fixed`, `secret`, + `return_string`) whose contract a Boost.URL `StringToken` also satisfies, `codecs::error` + (`invalid_character`, `invalid_length`, `invalid_padding`, `checksum_mismatch`, + `invalid_prefix`, `mixed_case`, `output_too_small`, ...) as an error code enumeration, and + composition, `codecs::over`. (Extended by decisions 15 to 18: the core also + holds the two transformer concepts, the flow state, `pipe`, `drain`, `buffered`, `encoder` and + `decoder`; every item above is unchanged.) +3. **The default result** (option B): a fixed-capacity, no-heap `codecs::text` or + `codecs::bytes` when the input's size is known at compile time (`std::array`, + `std::span`, `crypto::secret`, fixed-size typed values), with a capacity `N` and an + actual size, as a `static_vector`, converting to `std::string_view` or `std::span`; otherwise + `std::string` or `std::vector`. +4. **Secrecy.** An output is secret when `codecs::is_secret_v` is true (a type-level trait a + library specializes; crypto does for `crypto::secret`) or when `value_codec::secret` is + true (format-level, as PKCS#8 of a key pair). Secret outputs are `secret_text` and + `secret_bytes` (no heap, wiped on destruction), or `codecs::secret_string` (heap, wiped) when + the size is known only at run time. Decoding follows the requested type. +5. **Formats in `codecs::formats`, one header each,** included only by whoever uses them: + `hex.hpp` (`hex`, lower or upper), `base32.hpp` (`base32`, `base32hex`, a padding option, RFC + 4648 sections 6 and 7), `base58.hpp` (`base58`, Bitcoin's alphabet by default), `base64.hpp` + (`base64`, `base64url`, a padding option, RFC 4648 sections 4 and 5), `bech32.hpp` (`bech32`, + `bech32m` with their human-readable part, BIP-173 and BIP-350; decoding yields the + human-readable part and the data), `percent.hpp` (`percent{CharSet, encoding_opts}`, an adapter + over Boost.URL's `encoded_size`, `encode` and `decode` taking any Boost.URL `CharSet`; only this + header depends on Boost.URL, as webcpp::lexical already does). (base58 becomes a template over + its bound and its alphabet by decision 25, and over its checksum by decision 26; + `formats::base58` keeps Bitcoin's alphabet. bech32 becomes a template over its variant, its + maximum length and its data by decision 27; `formats::bech32` and `formats::bech32m` stay.) +6. **Constant time, always, for hex, base64 and bech32**: no table lookup indexed by a secret + (libsodium's `sodium_bin2hex` and `sodium_bin2base64` as the reference), tested on the + constant-time lane (ctgrind and dudect) as crypto is. +7. **Not in codecs:** base58check is webcpp::hash's (``, + `hash::formats::base58check`, double SHA-256). webcpp::crypto registers its key formats + (`crypto::formats::spki`, `pkcs8`, `der`, `raw` with its point forms, `pem(...)`) through + `value_codec` in each curve's formats header; `crypto::encode` and `crypto::decode` no longer + exist. Both are follow-up changes of those libraries. (Decision 26 names hash's format + `hash::formats::base58_with_checksum`: codecs' `basic_base58` with hash's double SHA-256 + checksum as its third parameter.) +8. **Tests:** RFC 4648 section 10, BIP-173 and BIP-350's vectors, Bitcoin Core's base58 vectors, + Boost.URL's own behaviour for percent; a counting `operator new` test proving the no-heap forms; + constant-time tests; a fuzz target per decoder. +9. **Conventions:** the repository's library conventions (the Boost Software License, b2, the + lanes, the documentation page, CODING-GUIDELINES, public names spelled out except an + algorithm's proper name), as hash's and crypto's genesis followed them. + +## Owner answers to the open questions (2026-11-24, binding) + +10. **Order (O1):** codecs comes before crypto's `formats` change, which is revised onto codecs + when its work starts (not in this genesis). +11. **More constant time (O2):** base32 is constant time always, as hex, base64 and bech32; + base58 is constant time when the operation is secret (a secret input or a secret + destination, D10). This widens decision 6. +12. **One DIT guard (O3):** the guard moves into webcpp::config, shared by crypto, hash and codecs, + by config's change `timing-guard`, which lands before codecs is implemented. codecs uses + config's guard and keeps no copy. (Its placement is superseded by decision 14: the guard is + webcpp::secure's, and config's change is withdrawn.) +13. **The armor (O4):** RFC 7468's textual encoding is a codecs format, `formats::armor(label)`, in + its own header ``, composable; crypto's `pem(spki)` becomes + `over` in its `formats` change. This narrows decision 7: crypto registers DER and + its other key formats, not the armor. + +## Owner decision on webcpp::secure (2026-11-24, later the same day, binding) + +14. **codecs builds on webcpp::secure.** The DIT guard, crypto's `erase_secret` and `secret`, + the declassify marker and the constant-time building blocks are a new library, + webcpp::secure (`libraries/secure/openspec/changes/genesis/`), on which crypto, hash and codecs + depend; config stays macros only, and its change `timing-guard` is withdrawn. codecs uses + `secure::timing_guard` (engaged for secret operations only), `secure::erase_secret` for every + wipe, `secure::secret` as the fixed secret value it specializes `is_secret` and + `fixed_byte_storage` for, `secure::declassify` before a verdict it branches on, and + `secure::constant_time`'s blocks for its arithmetic on masks; it keeps none of its own. This + replaces decision 12's placement and the mentions of `crypto::secret` in decisions 3 and 4. + +## Owner decisions (2026-11-25, binding) + +15. **The conversion contract of all of webcpp.** The core `` defines the + contract every conversion in webcpp implements, generic enough that a later, separate library + (webcpp::media: audio, video and photos, over backends such as FFmpeg, libwebp and WebCodecs) + implements the same concepts without changing them. Media is not in this change and not a + focus now (a non-goal), but the concepts assume no bytes and no characters (an input or output + type may be any type, a compressed packet or a decoded frame), assume neither constant time + nor secrecy (those stay optional traits of codecs' text formats), allow one input to produce + zero or many outputs (B-frames) and allow stateful transformers. This widens decision 1. +16. **Two concepts.** `one_shot_transformer` (`input_type`, `output_type`, + `transform(input, output)` returning a `result`) and `stream_transformer` (`send(input)`, + `receive(output)`, `flush()`, `reset()`), FFmpeg's `send_packet` and `receive_frame` model. The + flow state (more input needed, more output pending, finished) is reported apart from + `codecs::error`, since it is not an error. The exact shapes are the design's (D17, D18): one + concept pair for every kind of data, not one per kind. +17. **No encoder or decoder category tags.** Composition is made safe by types alone: + `codecs::pipe(a, b)` compiles only when `a`'s `output_type` is compatible with `b`'s + `input_type`. The core also gives `codecs::drain(t, sink)` and `codecs::buffered`, an + adapter that makes any one-shot transformer a stream transformer (it accumulates until + `flush`). The one-shot `over` stays. +18. **Streams of the text formats.** `codecs::encoder(format)` and `codecs::decoder(format)` build + stream transformers for the text formats; the one-shot `encode` and `decode` are unchanged. +19. **Native streaming:** hex, base32 and base32hex, base64 and base64url, percent and the armor. + base58 does not stream natively (a whole-number conversion) and streams through `buffered`. + bech32 encodes as a stream; its decoder holds its output until `flush`, so that nothing is + delivered before the checksum is verified (its inputs are at most about 90 characters by + default, under a settable maximum). (That maximum is a template parameter by decision 27.) +20. **No heap in the processing loop.** A stream transformer keeps only its minimal pending state + and writes into buffers the caller provides. In a secret operation the pending state is wiped + by `secure::erase_secret` on `reset`, on destruction and on move; chunk boundaries are public. + Each format's constant-time properties carry over to its stream form. +21. **Async stays out of the core.** A conversion is CPU work; asynchrony comes from the sources and + sinks (asio, cobalt). An `async_transcode` helper is a possible later change and a non-goal + here. +22. **Conventions.** Names spelled out, snake_case, webcpp's style; errors through `result` with + an `error_code`, never a status type; no virtual call and no `std::function` in the hot path. +23. **Allocator-aware, in the standard library's style, with pmr aliases.** Only what allocates + takes an allocator: the heap results (`std::string` and `std::vector`), the heap + secret types, `buffered`, `over`'s unbounded intermediate and base58's decode + into a token. The native stream transformers, `text`, `bytes` and the buffer forms + allocate nothing and take none. `append_to` and `assign_to` accept any + `std::basic_string` and `std::vector` (so + `std::pmr::string` works); the returning tokens (`return_string`, the heap form of `secret`) + take an optional allocator, `tokens::return_string(std::pmr::polymorphic_allocator{&arena})`. + The heap secret types become templates, `basic_secret_string` and + `basic_secret_byte_vector`; `secret_string` and `secret_byte_vector` are their + `std::allocator` aliases and `codecs::pmr::secret_string` and `codecs::pmr::secret_byte_vector` + their `std::pmr::polymorphic_allocator` aliases. Every byte is wiped by `secure::erase_secret` + before the allocator gets the memory back, the old buffer included when the container grows, + with any allocator (an arena's included). `buffered` and `over`'s intermediate + take an allocator; propagation follows the standard library (`std::allocator_traits`). With no + allocator given, `std::allocator` is used and the approved API does not change. Why: webcpp's + libraries (trystero, idna, lexical, pratt) use `std::pmr`; a template `Allocator` parameter + serves `std::pmr` and static allocators alike with no virtual call, which a + `std::pmr::memory_resource*` alone would not (the zero-overhead guideline); the future media + library follows the same pattern (pools for frames and packets). (The coordinator relayed it as + the owner's ninth decision of 2026-11-25; it is numbered 23 here, after decisions 15 to 22.) + This extends decisions 2 and 4 and D8 to D11, D13 and D19 (D22). (Decision 25 takes base58's + decode off this list: its scratch is in place, sized by its template, and its decode into a + token allocates only through the token.) +24. **Exceptions follow chapter 6 as written** (settles O7). Every library compiles and works in a + build without exceptions, but a library is not barred from throwing when exceptions are + available; D1's "no function of the library throws" was stricter than the owner meant and is + replaced. For codecs: data and configuration errors stay values (`result` with + `codecs::error`) in both builds, as the API's choice. With exceptions, an allocator's exception + (`std::bad_alloc`, or whatever the user's allocator throws) propagates out of codecs + unchanged, as the standard library's containers' do; the functions that may allocate are + therefore not `noexcept`, and every other function stays `noexcept`. The strong guarantee + where it is cheap: a token is untouched by a failed operation (D8), and a secret buffer is + wiped on the way out, so that the exception leaks no secret. Without exceptions, an allocator + failure follows the build's handler (`boost::throw_exception`'s, or the allocator's own), as + the standard containers' does; codecs adds no handling. No throwing convenience API is added. + +## Owner decisions (2026-11-26, binding) + +25. **base58 is a template over its bound and its alphabet** (answers the plan's question Q1 and + replaces its ruling R6's fixed ceiling). `codecs::formats` declares + `template struct basic_base58` + (the third parameter is decision 26's; the name spelled out, `basic_` as in `basic_string`). + Its `maximum_bytes` is `MaximumBytes`; its `maximum_characters` is derived from it, never a + second parameter, so that no inconsistent pair exists: the exact length of the longest + encoding of `MaximumBytes` bytes, ceil(MaximumBytes * log(256) / log(58)), which the + leading-zero rule (one character a leading zero byte) never exceeds. An alphabet is a type + with `static constexpr std::string_view characters`, 58 distinct characters (a + `static_assert` checks it), so that its tables are built at compile time and a program can + define its own; codecs gives `bitcoin_alphabet`, `ripple_alphabet` and `flickr_alphabet`. The + run-time `base58_alphabet` enumeration and the `base58(alphabet)` option are gone. The named + instances are `base58_bitcoin_t`, `base58_ripple_t` and `base58_flickr_t`, each + `basic_base58<100, ...>` of its alphabet, with the objects `base58_bitcoin`, `base58_ripple` + and `base58_flickr`; `formats::base58` is `base58_bitcoin`, the default: Bitcoin's alphabet up + to 100 bytes, which covers Bitcoin's addresses (25 bytes), WIF keys (38), BIP-32 extended keys + (82), Solana's keys (up to 64) and IPFS's CIDv0 (34). A caller who needs more names it, + `basic_base58<16384, bitcoin_alphabet>{}`. Every instance keeps its scratch in place, sized by + its template, so that the contract holds for each (exact sizes, `noexcept`, no heap); past + `maximum_bytes` or `maximum_characters` every operation is `input_too_long`, checked before + any read. The public path is Bitcoin Core's algorithm and the secret path the constant-time + one, as planned. This changes B15, D13 and D22 (base58's decode takes no allocator), and + narrows decisions 5 and 23. +26. **base58's checksum is its third template parameter** (extends decision 25). In + `template struct basic_base58`, + `base58_alphabet` is the concept an alphabet type satisfies (the enumeration of that name + being gone), and `MaximumBytes` counts the payload without the checksum; `maximum_characters` + is derived from the payload's bound plus the checksum's size. codecs defines + `struct no_checksum {}` and the concept `base58_checksum`, satisfied by `no_checksum` or by a + type with `static constexpr std::size_t size` and + `static void compute(std::span payload, std::span out) noexcept`, + which must be constant time, since it runs on secrets. codecs knows no checksum algorithm: it + depends on config and secure alone, and hash registers into codecs, so codecs never depends on + hash. With a checksum, encode appends `compute(payload)`; decode converts, splits the checksum + off, recomputes it and compares the two with `secure::constant_time_equal` (inside the engaged + guard when the operation is secret), and returns the payload without the checksum; + `checksum_mismatch` on a mismatch, `invalid_length` when the decoded bytes are fewer than the + checksum's size. The named instances have no checksum. The double SHA-256 checksum and + `hash::formats::base58_with_checksum`, which is + `basic_base58<100, bitcoin_alphabet, hash::checksums::double_sha256>` and what Bitcoin calls + Base58Check, belong to hash's follow-up change, not to codecs (this renames decision 7's + `hash::formats::base58check`); the page says so. codecs' own tests use a checksum of the + tests' own as the third parameter. +27. **bech32 is a template over its variant, its maximum length and its data** (replaces B18's + run-time `maximum_length`). `enum class bech32_variant : unsigned char { bech32 = 1, bech32m = 2 }` + names the checksum's constant (BIP-173's and BIP-350's). Two data tags: `struct bech32_bytes {}`, + the default, bytes regrouped from 8 bits to 5 with zero padding and the padding checked + strictly on decode (`invalid_padding`), and `struct bech32_words {}`, each element a 5-bit + value from 0 to 31 used as it is (a value above 31 on encode is `invalid_character`; no padding + to check). The name "words" is the owner's choice, the term of bitcoinjs's bech32 package; the + page says that a word here is a 5-bit value, not a machine word. + `template class basic_bech32`: + the maximum length is a template parameter, so that the scratch, the stream decoder's hold and + the results are in place with no heap, and a text past it is `input_too_long`. The + human-readable part stays a run-time value held in place (a `text<83>`, 1 to 83 characters of + 33 to 126; an invalid one is a fault of the configuration, `invalid_prefix`, before any data), + set by `operator()(std::string_view)`; a default-constructed format decodes any prefix; + `.words()` returns the same format with `Data = bech32_words`. The names: `bech32_t` and + `bech32`, `bech32m_t` and `bech32m` (90 characters, bytes); a Lightning invoice's length is + reached by naming a larger instance, `basic_bech32`. + `template struct bech32_parts` holds the `text<83>` human-readable part and the + data in place, sized from the maximum length, for the typed decode. `bech32.hpp` also gives + `append_words_from_bytes(Words&, std::span)` (BIP-173's `convertbits` + from 8 to 5, zero padding) and + `result bytes_from_words(std::span words, std::span out) noexcept` + (from 5 to 8, at most 4 padding bits, all zero, else `invalid_padding`; `output_too_small`). + Unchanged: lower-case output, the `mixed_case` refusal, the prefix check, the variant's + checksum, constant time always (decision 6), the native stream encoder, and the decoder that + holds its output until `flush`, its capacity in characters. Outside codecs, for a future + webcpp::bitcoin: version 0 in bech32 and 1 and above in bech32m, the valid program sizes, the + networks' prefixes, the parsing of Lightning's fields. This changes B18, D13 and D20. + +## The owner's rulings during the implementation (2026-11-26 to 2026-11-30, binding) + +Two rulings of the owner, relayed while the plan was built, change what this design says; the +decisions below carry them, each marked "changed 2026-11-30, as built". The controller's rulings +and the pre-flight's findings (F1 to F28), which change no owner decision, are listed one line +each, with what each costs if wrong, in `reference/STATUS.md`, section "Rulings during +implementation". + +- **No two-word naming rule (2026-11-26).** Locals and parameters need not be named with two + words; hash's `user_globals` test is not applied to codecs, and the pre-flight's F15 is + withdrawn. The renames already made stay. A parameter that hides a member still fails the + library's own MSVC `/W4 /WX` build (C4458), so the call operators of the configured formats name + their parameters `chosen_*` (F14). +- **`tokens::assign_to` leaves its target untouched (2026-11-26).** When a value codec fails after + `prepare`, the string or vector of `assign_to` reads as it did: the core converts into a scratch + first, in place when the static bound is at most 4096 elements and from the target's allocator + otherwise, assigns (by one copy that keeps the target's capacity) only on success, and wipes the + scratch in a secret operation (D8). A token of the program's own keeps the documented limit. + +## Decisions + +### D1. The library, its targets and its headers + +Namespace `webcpp::codecs`, with `codecs::formats`, `codecs::tokens` and `codecs::detail`; +macros `WEBCPP_CODECS_*`; include guards `WEBCPP_CODECS__HPP`; the error category +`webcpp.codecs`; ``, included first by every public header, which +includes `` first and defines `WEBCPP_CODECS_NO_EXCEPTIONS` by chapter 6's +rule. Errors of the data and of the configuration are values (`result` with `codecs::error`) +in every build; codecs throws nothing of its own. With exceptions available, an allocator's +exception propagates out of the functions that allocate (D22), which are not `noexcept`; every +other function is `noexcept`. The library compiles and works without exceptions, chapter 6's rule +as written (owner decision 24, which replaces this paragraph's earlier "no function of the +library throws"). Changed 2026-11-30, as built: codecs' own headers read a result with +`unsafe_value()` and never call `value()`, but Boost.System's `result` checks `value()`, +`operator*` and `operator->` through `boost::throw_exception`, so a program that reads codecs' +results that way with exceptions off links `/webcpp//throw_exception` (webcpp's handler), as the +page says; codecs' own targets need nothing of it. Every header spells `(std::min)`, +`(std::max)` and `(std::numeric_limits::max)()`, so that a program that includes +`` before or after codecs builds (crypto's rule; a test of each order runs on MSVC). + +``` +include/webcpp/codecs.hpp the core: the contract, the tokens, the results, the errors, over, + the transformer concepts, flow, pipe, drain, buffered, encoder, decoder +include/webcpp/codecs/config.hpp +include/webcpp/codecs/hex.hpp formats::hex +include/webcpp/codecs/base32.hpp formats::base32, formats::base32hex +include/webcpp/codecs/base58.hpp formats::basic_base58, its alphabets and checksum concepts, base58 +include/webcpp/codecs/base64.hpp formats::base64, formats::base64url +include/webcpp/codecs/bech32.hpp formats::basic_bech32, bech32, bech32m, bech32_parts, the word helpers +include/webcpp/codecs/percent.hpp formats::percent (Boost.URL) +include/webcpp/codecs/armor.hpp formats::armor, armor_parts (RFC 7468) +include/webcpp/codecs/detail/... the operations (the wipe and the constant-time blocks are secure's) +``` + +`build.jam` declares two targets: `codecs` (`include`, Boost's headers, config's +target and secure's, `/webcpp/secure//secure`) and `percent` (`codecs` plus `/webcpp//boost_url`, as chapter 10 says a library +that needs Boost.URL names it). A program that includes `percent.hpp` names +`/webcpp/codecs//percent`; one that does not never builds Boost.URL. + +**A recorded departure from chapter 3's convenience header.** `` is the core and +includes no format header: owner decision 2 makes it register nothing, and owner decision 5 makes a +forgotten format header an undeclared name. Chapter 3 lets a convenience header leave out a header +that brings a heavy dependency; this one leaves out all seven for a different reason, which the +library's entry in chapter 17 records with the owner's decision. There is no `formats.hpp` that +includes them all (builder's call, B1). + +### D2. Formats are values + +A format is a value of a copyable type with a `static constexpr std::string_view name`, passed +first, as webcpp::crypto's formats are (`crypto::raw(crypto::compressed)`). Each format header +declares an `inline constexpr` object for each name, of a type `_t`, and a format with +options is configured by calling it, which returns a configured copy: + +```cpp +namespace formats = webcpp::codecs::formats; +codecs::encode(formats::hex, digest); // lower case +codecs::encode(formats::hex(formats::letter_case::upper), digest); +codecs::encode(formats::base64url(formats::padding::written), key); +codecs::encode(formats::bech32("npub"), public_key_bytes); +codecs::encode(formats::percent(boost::urls::pchars), segment); +``` + +Builder's call (B2): the call-to-configure shape, rather than aggregates with designated +initializers, so that crypto's formats and codecs' read alike, and a configured format is still a +constant expression where its arguments are. + +### D3. `codec`: bytes to text and back + +`codec` is a class template the core declares and never defines; a format header +specializes it for its format's type. A specialization has: + +```cpp +template <> struct codec { + // True when encode and decode run in constant time (D12). + static constexpr bool constant_time = true; + // A bound on the text of `input_size` bytes, over every option of the format; constexpr. + static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept; + // A bound on the bytes of `text_size` characters; constexpr. + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept; + // The exact size of the text this format writes for `input`. + static std::size_t encoded_size(formats::hex_t const& format, std::span input) noexcept; + // The exact size of the bytes `text` decodes to, the whole text checked. + static result decoded_size(formats::hex_t const& format, std::string_view text) noexcept; + static result encode(formats::hex_t const& format, std::span input, + std::span output) noexcept; + static result decode(formats::hex_t const& format, std::string_view text, + std::span output) noexcept; +}; +``` + +Every public function of the core is written once over this contract; a format writes only these +six functions. `max_encoded_size` and `max_decoded_size` are the bounds the fixed results take +their capacity from, so they are constexpr in the size alone (bech32's bound counts the longest +human-readable part, 83 characters, and stops at its `MaximumLength`, owner decision 27). + +A format that streams natively also specializes a second point, `stream_codec` (D20); +`codec` is unchanged by the streaming decisions and stays the one-shot contract every +format writes. + +Changed 2026-11-30, as built (plan ruling R3, pre-flight F17 and the controller's rulings of +Tasks 7, 11 and 24): the six functions stay the contract, and four things are added to it. + +- **The parameter types are D3's, never deduced.** Each function takes + `std::span` for the bytes read, `std::string_view` for the text read and + `std::span` or `std::span` for the output. The core gives the bytes or the + text of an input whose type states its size (`std::array`, `text`) as a + `detail::bounded_bytes` or a `detail::bounded_text`, a view that converts to those types + implicitly and `noexcept`, so that a codec's `noexcept` reaches the operation; the view is no + range, so a function template that deduced its parameter would get the view and could not read + it. `over` is the one codec that takes the views, to read the bound they state. A test keeps a + program's codec of exactly D3's signatures working over a `std::array` input in the buffer, + default and token forms. +- **The secret overloads (plan ruling R7).** A format whose arithmetic differs when the operation + is secret (base58's) adds overloads of `encoded_size`, `decoded_size`, `encode` or `decode` + whose first parameter is `detail::secret_tag`, the one name of `detail` a format's header + names; the core calls them in a secret operation when they exist, and the function without the + tag otherwise. A value codec's `encoded_size`, `encode` and `decode` take it alike (the + controller's ruling of Task 7, so that a value codec under `over` made secret by a token runs + its secret arithmetic). An overload whose result type differs from the function without the + tag, or whose parameters the core's arguments do not convert to, stops the build. +- **The configuration hook.** A format that has a configuration (a human-readable part, a label, + an option that can be wrong) adds + `static constexpr std::optional configuration_fault(Format const&) noexcept`. The core + calls it first in every form, before any size check and any data, and returns its error + unchanged, so that a fault of the configuration wins over every data error (B23); a stream + transformer asks it when it is made and reports it from its first call and every call after, + `reset` included, and never builds the stream codec with it. bech32 and the armor implement it; + a codec without it is of a format with no configuration. A non-static hook, or one of another + signature, stops the build. +- **The encode hook.** A format whose encode refuses an input that its decode has nothing to say + of (bech32 with no human-readable part, a text past its longest or a word above 31 in words + mode; the armor with no label) adds + `static constexpr std::optional encode_fault(Format const&, std::span) noexcept`. + The core calls it in every encode form after `configuration_fault` and before its own size + check, so that the fault does not depend on the input's size, and before any token is prepared + or any result made; a hook that reads the input checks the input's size itself, and reads + secret bytes in constant time, the verdict declassified once. `over` forwards its links' hooks + (D11). +- **The sizes of a refused input.** The bounds saturate at `SIZE_MAX`, which means "does not + fit": every form refuses an input whose bound saturates with `input_too_long` before it reads + it, and a format's output size of `SIZE_MAX` is `input_too_long` before the capacity check and + before `prepare`. A size with no error channel (the codec's `encoded_size`, the core's + `codecs::encoded_size`, a transformer's `output_size`) keeps one rule for an input the encode + refuses: `SIZE_MAX` when it is refused for its size, 0 when it is refused for a fault of the + configuration or of the encode. bech32's `encoded_size` is `SIZE_MAX` for a text past its + `MaximumLength`. + +### D4. `value_codec`: typed values + +`value_codec` is declared and never defined in the core; a library specializes it +for a format and a type it owns, in the header that defines the pair (crypto's in each curve's +formats header). A specialization has: + +```cpp +template <> struct value_codec { + static constexpr codecs::output_kind output = codecs::output_kind::bytes; // or text + static constexpr bool secret = true; // optional; false when absent + static constexpr std::size_t max_encoded_size = 138; // optional; a fixed result when present + // Format and Value below are the specialization's two arguments. + static std::size_t encoded_size(Format const&, Value const&) noexcept; + static result encode(Format const&, Value const&, std::span output) noexcept; + static result decode(Format const&, std::span input) noexcept; +}; +``` + +A text-output value codec writes into `std::span` and reads `std::string_view`; the buffer +form of `encode` takes a `std::span` for a value codec of bytes, a `std::span` +for everything else. A value +codec may encode only, or decode only (`encodable` and `decodable` look at each function). The +errors a value codec returns are any `error_code` (crypto's own category for an invalid key); the +core adds none of its own to them. Builder's call (B3): `output_kind` names the direction's +element, so that `over` and the default result know whether a value's encoding is text or bytes. + +### D5. The concepts and the refusal + +- `format`: `std::copyable` and `F::name` converts to `std::string_view`. +- `encodable`: `format` and either `V` is a byte input (D7) and `codec` is + specialized, or `value_codec` is specialized with `encode` and `encoded_size`. +- `decodable`: `format` and either `V` is a byte result the core builds (`std::string`, + `std::vector`, `std::array`, `bytes`, `secret_bytes`, + `secret_byte_vector`, or a type of `fixed_byte_storage`, D9) and `codec` is specialized, or + `value_codec` is specialized with `decode`. + +A call with a pair that is neither stops the build in a `static_assert` in the core whose message +names the format's `name`, says that the format does not convert this type, and says to include +the format's header or to specialize `value_codec`. A format whose header was not included is not +reached at all: its name is undeclared. + +Changed 2026-11-30, as built (plan ruling R2, pre-flight F1 to F3): a C++20 `static_assert` +message is a literal and cannot hold `F::name`, so the refusal names the format through its +requirement, `detail::converts`, which clang's "static assertion failed due to +requirement" line prints with the format's type in full (`webcpp::codecs::formats::hex_t`); the +literal says "this format does not convert this type; include the format's header, or specialize +webcpp::codecs::value_codec for the format and the type". The core declares the empty namespace +`codecs::formats`, so that a forgotten header is "no member named 'base64' in namespace +'webcpp::codecs::formats'". Every entry point that refuses (the default, token and typed forms of +`encode` and `decode`, `encoded_size`, `drain`, `pipe`, `encoder`, `decoder`) is constrained at +most on `format` and refuses in its body, and the refusals are tested by message cases (clang's +`-verify`), with a compile-fail twin of each built where the message case is not (gcc, MSVC, +Emscripten). + +These three concepts are about formats. The two transformer concepts, `one_shot_transformer` +and `stream_transformer`, are about objects that convert, and know nothing of formats (D17); +a format becomes a transformer through `encoder` and `decoder` (D20). + +### D6. The sizes + +`encoded_size(format, input)` is the exact size of the text (or the bytes, for a value codec of +bytes); `max_decoded_size(format, text)` a bound that needs no pass over the text (it is +`codec::max_decoded_size(text.size())`). A program that wants the exact decoded size decodes +into a token, which does the full pass (D8); `codec::decoded_size` stays the format author's +function and not a free function (builder's call, B4), since the owner's list of free functions +has the bound alone. + +Changed 2026-11-30, as built: `encoded_size` has no error channel, and gives `SIZE_MAX` for an +input every `encode` refuses for its size and 0 for one refused for a fault of the configuration +or of the encode (D3). It is a constant expression where the format and the input are, the +input's bytes are `std::uint8_t` or `unsigned char` (not `char` or `std::byte`) and the input is +not secret; of a secret input it holds the +timing guard and runs the format's secret arithmetic, as the buffer encode does (D10). + +### D7. Inputs + +A byte input is anything `std::span` is made from, `char`, `unsigned char` +and `std::byte` elements included; a text input is anything `std::string_view` is made from, a +contiguous range of `char` included. The input's size is known at compile time when the type has +a static extent: `std::array`, `T[N]` (a byte array; a string literal is read as a +`std::string_view`, its size not static, builder's call B5), `std::span`, `text` and +`bytes` (their capacity), and any type with a `static constexpr std::size_t size()` that +converts to `std::span`, which is `secure::secret`'s shape. +`codecs::static_input_size_v` gives that size, or `std::dynamic_extent`. + +### D8. Tokens + +The token contract is Boost.URL's, so that `boost::urls::string_token::return_string`, +`append_to` and `assign_to` work as given: + +- a **text token** `T` has `typename T::result_type`, `t.prepare(n)` returning `char*` to `n` + characters, and `t.result()` convertible to `result_type`; +- a **byte token** is the same with `prepare` returning a pointer to an element of one byte + (`char`, `unsigned char`, `std::uint8_t` or `std::byte`), so a Boost.URL token also receives + decoded bytes as a `std::string`; +- the core calls `prepare` at most once, with the exact size, then `result` once, as Boost.URL + does. Every check of the input is done before `prepare`: a failure leaves the token untouched + (an allocator's exception thrown by a returning token's `prepare` too, owner decision 24), + and nothing of codecs' own fails after `prepare` (a value codec's error and the outer link of a + heap `over` can, below). The token forms return `result`; +- a token may declare `static constexpr std::size_t capacity`, which the core compares with the + exact size before `prepare`, refusing with `output_too_small`, and `static constexpr bool + secret`, which makes the operation secret (D10). + +codecs' own tokens are tags of `codecs::tokens` that the core turns into the concrete token for the +direction (text for `encode`, bytes for `decode`), builder's call B6: one name serves both +directions. + +| Token | encode gives | decode gives | +| --- | --- | --- | +| `tokens::automatic` (the default, `= {}`) | the default result (D9) | the default result (D9) | +| `tokens::return_string`, `tokens::return_string(allocator)` | `std::string`, or `std::basic_string, A>` | the same, holding the bytes | +| `tokens::append_to(s)` | appends to `s`, any `std::basic_string` | appends to `s`, such a string or any `std::vector` | +| `tokens::assign_to(s)` | assigns to `s` | assigns to `s` | +| `tokens::fixed` | `text` | `bytes` | +| `tokens::secret`, `tokens::secret(allocator)` | `secret_text`, or `basic_secret_string` | `secret_bytes`, or `basic_secret_byte_vector` | + +`append_to` and `assign_to` return a reference to their string, as Boost.URL's do, and use the +string's own allocator; `std::pmr::string` and `std::pmr::vector` work (owner +decision 23). `return_string` and `secret` take an optional allocator, rebound to their element +through `std::allocator_traits`; with none, `std::allocator`. `tokens::secret` gives the fixed form +when the bound is known at compile time, as the default does, and then ignores the allocator. A +token that allocates exposes `get_allocator()`, as a standard container does; no operation of +codecs reads it (base58's scratch is in place, owner decision 25). The default token's name, `automatic`, is builder's call B7. + +Changed 2026-11-30, as built. **The order of the checks**, which every token shares: a fault of +the format's configuration, then a fault of the format's encode (D3's hooks), then every other +check of the input (a saturating bound is `input_too_long`, a text is checked whole), then the +token's `capacity` against the exact size (`output_too_small`), then one `prepare` with the exact +size, the conversion and one `result`. Two failures can still come after `prepare`: a value +codec's own error from its `encode`, and the outer link of an `over` with a heap intermediate, +whose fault is found by its encode (D11). For both, codecs' own tokens are restored: `append_to` +is put back as it was, `return_string` builds nothing the caller sees, and `assign_to` +converts into a scratch first and copies it into its container only on success (the owner's +ruling of 2026-11-26: the scratch in place when the static bound is at most 4096 elements, from +the container's allocator otherwise, wiped and released at once in a secret operation), so its +container is untouched; a token of the program's own is left as `prepare` made it, as documented. +A decode into a token converts twice when the format's exact size needs the conversion (base58's +`decoded_size` and then its `decode`, both in place), the core's uniform order. + +### D9. The default result and the fixed results + +With no token, `encode` gives, by D7 and D4: + +| The input | Not secret | Secret | +| --- | --- | --- | +| bytes of static size `N` | `text::max_encoded_size(N)>` | `secret_text<...>` | +| a value whose value codec has `max_encoded_size` | `text` or `bytes` by `output` | `secret_text` or `secret_bytes` | +| anything else | `std::string` or `std::vector` | `secret_string` or `secret_byte_vector` | + +and `decode` gives `bytes::max_decoded_size(N)>` for a text of static size `N` (a +`text` from an earlier `encode` round-trips with no heap), `std::vector` +otherwise; a decode is secret only through its token or its requested type (D10). + +`text` and `bytes` hold `N` elements in place and a size; they are regular types, compare +by content, have `size()`, `data()`, `static constexpr capacity()`, `view()` (a `std::string_view` +or a `std::span`) and convert implicitly to that view on an lvalue; the +conversion of an rvalue is deleted, as `secure::secret`'s is, so that no view dangles. Their bytes +past `size()` are zero. Builder's call B8: the members' names. + +Typed decode into fixed byte types (`decodable`, D5): `std::array` requires +exactly `N` bytes (`invalid_length`); `bytes` and `secret_bytes` take up to `N` +(`output_too_small`). A library's own fixed secret type joins by specializing +`codecs::fixed_byte_storage` with its size and a function giving the writable span (codecs +itself does for `secure::secret` through its `writable()`, owner decision 14), builder's call B9. + +Typed decode into a heap type takes any allocator (owner decision 23): `decode(format, input)` +for `V` a `std::basic_string`, a `std::vector`, a +`basic_secret_byte_vector` or a `basic_secret_string`, and `decode(format, input, +allocator)` to pass the allocator, the result constructed with it (a default-constructed `A` +otherwise, so `decode>` uses the default memory resource). + +### D10. Secrecy + +`codecs::is_secret` is a trait, false by default, that a library specializes for its secret +types; `is_secret_v` reads it through `std::remove_cvref_t`. An operation is secret when the +value's `is_secret_v` is true, the value codec's `secret` is true, the token's `secret` is true, +or the requested type of a typed decode is secret (`is_secret_v`, or `secret_bytes`, +`secret_byte_vector`). A secret operation: + +- returns a secret result type: `secret_text`, `secret_bytes` (in place, move-only, wiped on + destruction and on move by volatile stores, copied only by `clone()`) or `secret_string`, + `secret_byte_vector` (on the heap, move-only, wiped before the memory is freed, never through + `std::basic_string`, whose small buffer an allocator cannot wipe; builder's call B10, the bytes + type's name). The heap types are the `std::allocator` aliases of `basic_secret_string` + and `basic_secret_byte_vector`, with `codecs::pmr::secret_string` and + `codecs::pmr::secret_byte_vector` over `std::pmr::polymorphic_allocator` (owner decision 23, + D22); they wipe every byte before the allocator gets memory back, on destruction, on + `shrink_to_fit`, and the old buffer when they grow; +- wipes every buffer of the library's that held its bytes: `over`'s intermediate (D11), a value + codec's scratch, a decode's temporaries; +- holds the timing guard (D12). + +Every wipe is `secure::erase_secret` (volatile stores, then a signal fence): the in-place secret +results erase their storage, the heap ones erase their bytes before the memory is freed, and the +temporaries are erased before they go. The core specializes `is_secret` and `fixed_byte_storage` +for `secure::secret`, so that `encode(formats::hex, key)` of a `secure::secret<32>` gives a +`secret_text<64>` and `decode>(formats::base64, text)` is a secret operation +with no heap. codecs includes no other webcpp library but config and secure (owner decision 14). + +Changed 2026-11-30, as built (the controller's rulings of Tasks 6 and 20): + +- **A secret operation into an explicit token that is not secret** (`return_string`, `fixed`, + `append_to`, `assign_to`, a Boost.URL token) runs guarded, with the format's secret arithmetic, + and returns the token's own `result_type`, since the caller chose the token: only + `tokens::automatic` and `tokens::secret` give the secret result types above. Every token the core + makes (the returning token, `fixed`, the tail `append_to` added) is wiped when it is abandoned + and where a result is cut to its written size, and the library's own intermediates are wiped as + always; what the caller's string then holds is the caller's to erase. +- **The sizes and the buffer encode of a secret input are secret too**: `encoded_size` and + `encode(format, input, span)` of a secret value hold the guard and run the secret arithmetic. +- **What a wipe covers.** The wipe rule covers the memory buffers the library owns or passes by + pointer (scratches, intermediates, carries, holds, error masks, token buffers); a scalar + returned by value (a decoder's `std::optional`, a character or digit local) is not + a buffer of the library's and is not wiped. + +### D11. Composition: `over` + +`codecs::over` is a format: encoding encodes with `Inner`, then encodes that output +with `Outer`; decoding decodes with `Outer`, then decodes that output with `Inner`. `Inner` is a +codec or a value codec's format; `Outer` is a codec (text is read as bytes when it feeds +`Outer`). Its `name` is `Outer::name` then `" over "` then `Inner::name`; CTAD builds it from +values, `codecs::over{formats::base64, crypto::formats::der}`. A chain is constant time when every +link is, secret when any link's operation is. The intermediate is held in place when its bound is +known at compile time and on the heap otherwise, and wiped when the chain is secret. The heap +intermediate comes from `over`'s allocator: `over>`, +`over{outer, inner, allocator}` by class template argument deduction, the allocator held in the +format value and used for nothing else (owner decision 23, D22); `over` as approved +is unchanged. PEM is +`over`: the armor writes base64 itself (D13), and crypto's `pem(spki)` becomes +`over{formats::armor("PUBLIC KEY"), crypto::formats::spki}` in its follow-up (owner decision 13). + +`over` stays one-shot (owner decision 17), and its stream counterpart is `pipe` (D19). +`codecs::encoder(over{outer, inner})` returns a `format_encoder` like every other format (D20): a +one-shot transformer always, whose `transform` is `over`'s encode, and also a stream transformer, +through a `pipe(encoder(inner), encoder(outer))` it holds, when both links are codecs that stream +natively; `decoder` likewise, through `pipe(decoder(outer), decoder(inner))`. An `over` with a +value codec's format has no transformer (D20), and one with a link that does not stream natively +has the one-shot transformer alone (coordinator ruling, B43). + +Changed 2026-11-30, as built (plan ruling R3, pre-flight F17, the controller's rulings of Tasks 7, +11 and 24): + +- **Where the intermediate lives.** In place, in the frame of each function of `over`, whenever + its bound is known at compile time (the input's type states its size, or the value codec states + `max_encoded_size`), with no cap: the spec's "`over` with a static bound allocates nothing" + binds, and the cost, an array of the middle bound in each level of a chain of chains, is + documented. On the heap, from `over`'s allocator, for an input of a dynamic extent; a caller + with a large static input who wants the heap passes a view of a dynamic extent, which is the + only way to the heap intermediate (no allocator form names it). +- **The heap intermediate allocates in every form.** `over`'s exact `encoded_size` and + `decoded_size` run the inner link into the intermediate (R3), so with a heap intermediate the + sizes, `encode` and `decode` allocate and are not `noexcept`, and so are the core's buffer forms + over such an `over`, the one allocating buffer form (F17; refusing the buffer form was rejected, + since `over{hex, base58}` would have none). With a static bound every form is `noexcept` and + allocates nothing. +- **Secret chains** run each link's secret arithmetic: a value-codec `over` made secret by its + token calls the value codec's `secret_tag` overloads (D3) and wipes its intermediate. +- **The order of a chain's faults.** A fault of a link's configuration is the chain's, the outer + link's first, before any data of either link, in every form and in the chain's streams. A fault + of a link's encode (`encode_fault`) is the chain's before any `prepare`: the inner link's always, + and the outer link's on the intermediate when the intermediate is in place, which the chain finds + by running the inner link into it; with a heap intermediate the outer link's is found by its + encode after `prepare` (a `noexcept` probe cannot allocate), and codecs' tokens are restored + (D8). A data error of a decode is the outer link's first, then the inner link's, an exception + to the lowest-value rule (B23): the outer link's text is read before the inner link's bytes + exist. +- **A chain's streams** are a `piped` of the links' streams and keep `piped`'s move window (D19). + +### D12. Constant time + +hex, base32, base32hex, base64, base64url, bech32, bech32m and the armor are constant time on +every call; base58 is constant time when the operation is secret (owner decisions 6 and 11). + +Each of the first computes its alphabet by arithmetic on masks, never by indexing a table with a data +byte, and never branches on a data byte; decoding accumulates an error mask over the whole input +and reports it once at the end, so the position of a bad character is not revealed (only its +kind). What is public: the input's length, the format's options, bech32's human-readable part, the +armor's structure and the result's success. The armor's structure is public (coordinator ruling, +B45): its line endings (a line feed, or a carriage return and a line feed), the optional final +line ending, the boundary lines and their positions, and the label, which RFC 7468 makes a public +type marker; the armor's decoder may branch on that structure, and only the symbols of its base64 +payload are decoded in constant time. bech32's checksum (BIP-173's `polymod`) replaces its conditional XOR by a +mask. libsodium's `sodium_bin2hex`, `sodium_hex2bin`, `sodium_bin2base64` and `sodium_base642bin` +are the reference for the arithmetic. + +These formats are constant time on every call, secret or not; the cost is a few operations a byte. +base32's 5-bit groups are computed with the same masks as base64's 6-bit groups. + +base58, secret: the conversion runs over the whole input whatever its value, a fixed number of +limb operations for the input's length (no early exit at the most significant non-zero limb, no +skip of leading zeros), and its alphabet is computed by masks; the count of leading zero bytes is +found by a mask scan. The output's length depends on the value (leading zeros and magnitude), +which is inherent to base58: that length is public, as the text itself is. base58, not secret: +Bitcoin Core's algorithm, quadratic, with its early exits. For every instance of `basic_base58`, +`codec>::constant_time` is false; the base58 codec has a second flag, +`constant_time_when_secret`, true, which the constant-time lane reads (builder's call B24). With a +checksum (owner decision 26), a secret operation computes it with the policy's `compute`, constant +time by the concept's contract, and compares it with `secure::constant_time_equal` inside the +engaged guard; that verdict passes through `secure::declassify` before the branch that reports +`checksum_mismatch`. + +On arm64 a secret operation also sets DIT for its duration through secure's timing guard +(`secure::timing_guard`, owner decisions 12 and 14), engaged only when the operation is secret, as +hash engages it only for a keyed call. + +The masks are secure's (`secure::constant_time`, owner decision 14): `is_in_range_mask` and +`select` map a 4, 5 or 6-bit value to its character and back, `lookup` reads base58's and bech32's +alphabets and bech32's generator whole, `select_bytes` and `less_mask` serve secret base58's limb +arithmetic, and every mask passes through `value_barrier`. A decode's accumulated error mask is +passed to `secure::declassify` before the one branch that reports it, so the constant-time lane +reports every other branch on the input and not that one; the lane defines +`WEBCPP_SECURE_CT_VALGRIND` or `WEBCPP_SECURE_CT_MSAN` as crypto's does. percent is not constant +time. + +The stream forms keep every property above (owner decision 20, D21): each call's work depends on +the sizes of its spans and of the pending state alone, the error mask is accumulated across every +call and reported once, after `flush`, through `secure::declassify`, and a secret stream holds an +engaged guard in each of its calls. Chunk boundaries (the sizes of the spans a caller passes) are +public, as the input's length is. + +Changed 2026-11-30, as built (the controller's ruling of Task 16): where `=` sits in a padded +base64 or base32 text is data, public only for a valid text's last group, so it is never +declassified group by group. The one-shot decoder computes the byte count by masks and +declassifies it once, after the verdict, and writes under the public guard `index < count`. A +padded stream decoder holds the bytes of a group's places that can be `=` in the last group (the +third and fourth of base64, at most two bytes; the fourth, fifth, seventh and eighth of base32) +until the next character shows the group is not the last, or until `flush`, which +declassifies the final count with the verdict; an unpadded decoder delivers as it reads, any `=` +being a fault. The armor's decoder reads its payload through base64's. + +### D13. The formats + +- **hex** (`hex.hpp`): `formats::hex`, `letter_case::lower` by default, `upper` by option. Decode + takes either case, mixed included (builder's call B12), refuses an odd length + (`invalid_length`) and any other character (`invalid_character`). +- **base32** (`base32.hpp`): `formats::base32` (section 6's alphabet) and `formats::base32hex` + (section 7's), `padding::written` by default for both, `padding::omitted` by option. Encode + writes upper case; decode takes either case (builder's call B13), refuses padding when it is + omitted and requires it when written (`invalid_padding`), refuses a length no encoding has + (`invalid_length`) and non-zero trailing bits (`invalid_padding`), RFC 4648 section 3.5's + canonical form. +- **base58** (`base58.hpp`, owner decisions 25 and 26): `formats::basic_base58`. `Alphabet` is a type that satisfies the concept + `base58_alphabet`, its `static constexpr std::string_view characters` 58 distinct characters + (a `static_assert` in `basic_base58` says so), from which the tables are built at compile time; + codecs gives `bitcoin_alphabet`, `ripple_alphabet` and `flickr_alphabet` (builder's call B14: + the alphabets in use), and a program may define its own. `Checksum` satisfies the concept + `base58_checksum`: `no_checksum`, or a type with `static constexpr std::size_t size` and a + `noexcept`, constant-time `static void compute(std::span payload, + std::span out)`; codecs defines no checksum algorithm. `maximum_bytes` is + `MaximumBytes`, the payload's bound without the checksum; `maximum_characters` is derived from + it, never given: the length of the longest encoding of `maximum_bytes` plus the checksum's + size, ceil(n * log(256) / log(58)) for n bytes, which the leading-zero rule never exceeds (137 + for 100 bytes). `base58_bitcoin`, `base58_ripple` and `base58_flickr` (of the types + `base58_bitcoin_t`, `base58_ripple_t` and `base58_flickr_t`) are the instances of 100 bytes with + no checksum, and `formats::base58` is `base58_bitcoin`; a caller who needs more names an + instance, `basic_base58<16384, bitcoin_alphabet>{}`. Leading zero bytes are leading + first-alphabet characters, as Bitcoin Core's `EncodeBase58`. The conversion is quadratic in the + length, and the bound caps it (builder's call B15, changed by owner decision 25): an input past + `maximum_bytes` or a text past `maximum_characters` is `input_too_long`, refused by its public + length before any read (it is then the only fault reported), and a decode whose payload would + be longer than `maximum_bytes` is `input_too_long` too, the result's length being public (D12). + Every operation works in an in-place scratch sized by the template for the larger of the two + bounds, so that the contract holds for every instance: exact sizes, `noexcept`, no heap; the + scratch is wiped when the operation is secret, and a decode into a token allocates only through + the token. With a checksum, encode appends `compute(payload)`; decode converts, splits the last + `size` bytes off, recomputes the checksum of the rest and compares the two (D12), and gives the + payload without the checksum: `checksum_mismatch` when they differ, `invalid_length` when fewer + than `size` bytes were decoded. Bitcoin's Base58Check is webcpp::hash's + `hash::formats::base58_with_checksum`, this template with hash's double SHA-256 checksum (owner + decisions 7 and 26), not codecs'. base58 does not stream natively (every output digit depends on + the whole input); it streams through `buffered` (owner decision 19, D20). +- **base64** (`base64.hpp`): `formats::base64` (section 4, `padding::written` by default) and + `formats::base64url` (section 5, `padding::omitted` by default, as JOSE and document's policy + write it), each with the other padding by option (builder's call B16: the defaults). Decode is + canonical: no line break, no whitespace, no character of the other alphabet, padding as the + option says, zero trailing bits. +- **bech32** (`bech32.hpp`, owner decision 27): `formats::basic_bech32`, `Variant` a `bech32_variant` (`bech32` for BIP-173's checksum + constant, `bech32m` for BIP-350's), `MaximumLength` the longest text in characters (a + `static_assert` refuses one below 8, the shortest text: a one-character human-readable part, the + separator and the six checksum characters; this replaces the plan's run-time check of a bad + `maximum_length`), `Data` the data tag. `formats::bech32` and `formats::bech32m` (of the types + `bech32_t` and `bech32m_t`) are the instances of 90 characters, as BIP-173 says, over bytes; a + Lightning invoice or a longer NIP-19 form is read by a larger instance, + `basic_bech32{}("lnbc")` (builder's call B18, changed by owner + decision 27). The human-readable part is configured by a call, `formats::bech32("bc")`, and held + in the format value (up to 83 characters, in place, so the format never dangles; builder's call + B17). With `bech32_bytes` (the default) the data are bytes, regrouped into 5-bit groups with zero + padding as BIP-173's `convertbits` does, and checked strictly on decode (at most 4 padding bits, + all zero; `invalid_padding`). With `bech32_words` (`formats::bech32("bc").words()`) each element + is one 5-bit value, a word, written and read as it is: a value above 31 on encode is + `invalid_character`, and there is no padding to check. Decode refuses mixed case (`mixed_case`), + a human-readable part other than the format's (`invalid_prefix`), a bad checksum + (`checksum_mismatch`), a text past `MaximumLength` (`input_too_long`), a human-readable part + outside 1 to 83 characters of 33 to 126 (`invalid_prefix`, a fault of the configuration when it + is the format's, checked before any data). Encoding writes lower case. Every bound, the scratch + and the results are in place, sized from `MaximumLength`: no form of bech32 allocates. The typed + decode `decode(formats::bech32, text)` with no human-readable part + in the format accepts any and yields both: `bech32_parts{human_readable_part, + data}` (a `text<83>` and the data in place; the owner's `bech32_parts` takes + `MaximumLength` as a second parameter, 90 by default, since its data is sized from it, and each + format names its own as `parts_type`). The public name is `human_readable_part`, spelled + out (BIP-173's "hrp" is an abbreviation), builder's call B19. `append_words_from_bytes(words, + bytes)` appends `convertbits` from 8 to 5 with zero padding to any container with `push_back`, + and `bytes_from_words(words, out)` regroups from 5 to 8 (`invalid_character` above 31, + `invalid_padding` for more than 4 padding bits or a non-zero one, `output_too_small`), so that a + segwit address is a version word followed by `append_words_from_bytes(program)` in words mode. + Writing the version as a byte in bytes mode gives another text, the pitfall the page names. The + segwit rules (which variant for which version, the program sizes, the networks' prefixes) and + Lightning's fields are outside codecs, a future webcpp::bitcoin's (owner decision 27). Its + stream encoder writes as it goes; its stream decoder holds the raw characters until `flush` + verifies the checksum (owner decision 19, D20). +- **percent** (`percent.hpp`): `formats::percent` is `percent(boost::urls::unreserved_chars, + boost::urls::encoding_opts{})`, and `percent(char_set, options)` takes any Boost.URL `CharSet` + and `encoding_opts`. `encoded_size` and `encode` call `boost::urls::encoded_size` and + `boost::urls::encode`; `decode` calls `boost::urls::decoded_size` and `boost::urls::decode`, so + the result is Boost.URL's, byte for byte, and Boost.URL's errors map to `invalid_character` (a + bad hex digit) and `invalid_length` (a truncated escape), builder's call B20. As Boost.URL's + `decode`, it does not check that unescaped characters are in the `CharSet`. +- **armor** (`armor.hpp`, RFC 7468): `formats::armor` configured with a label, + `formats::armor("PUBLIC KEY")`, held in the format value (up to 64 characters of RFC 7468's + `label` grammar, in place; builder's call B25). Its input is the bytes (the DER), not base64: it + writes `-----BEGIN (basic_secret_string the same over char, view() a string_view): +// explicit basic_secret_byte_vector(A const& allocator = A()) noexcept; +// move constructor (noexcept), move assignment (std::allocator_traits' propagation; between +// unequal non-propagating allocators: copies into the target's memory, wipes the source's); +// copy deleted; clone() const; ~ wipes then deallocates; +// size(), capacity(), empty(), data(), view() const& (&& deleted), get_allocator(); +// append(std::span), reserve(n), resize_for_overwrite(n) (the token's prepare), +// clear() (wipes), shrink_to_fit(): every growth allocates the new buffer, copies, wipes the old +// one, then deallocates it; a throwing allocation leaves the value as it was. +``` + Every wipe is `secure::erase_secret` over the bytes before `deallocate` (the whole capacity, not + the size). The allocating members are not `noexcept`. `test/support/wipe_recorder.hpp`: defines + `webcpp::secure::test::wipe_record` recording each wipe's address, size and whether it read zero, + for a program built with `WEBCPP_SECURE_TEST_WIPE_RECORD`. + +- [ ] **Step 1: Write the failing tests.** + - `secret_fixed_test.cpp` (with the wipe seam): `secret_text<64>` and `secret_bytes<32>` are + not copyable (`!std::is_copy_constructible_v`), are movable; a move leaves the source size 0 + and records one wipe of its storage; `clone()` equals; destruction in placement storage + records one wipe of the object's storage, zero at the record (the spec's scenario's "after its + destruction its storage reads zero through the test seam"). + - `secret_heap_test.cpp`: with `wipe_checking_allocator`: a `basic_secret_byte_vector` given 32 + bytes, then appended past its capacity twice, then destroyed: three deallocations, every + buffer zero at its deallocation; the same for `basic_secret_string`; `shrink_to_fit` and + `clear` wipe; a move between unequal `non_propagating_allocator`s copies into the target's + memory and wipes the source's buffer; `secret_string` is + `basic_secret_string>` (`std::is_same_v`, the spec's scenario "The + approved spelling is unchanged"). + - `allocator_test.cpp` gains `codecs::pmr::secret_byte_vector` and `codecs::pmr::secret_string` + over the arena: the arena records, the global counter does not. + - `allocator_throw_test.cpp` gains: a `basic_secret_byte_vector>` + holding 16 bytes whose growth throws keeps its 16 bytes, and the new buffer, if one was + allocated, is deallocated zero. + - `allocation_test.cpp` gains the fixed secret types; `noexcept_test.cpp` gains `noexcept` of + the fixed secret types' members and of the heap types' move constructor, `!noexcept` of + `append`, `reserve`, `clone`. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//secret_heap`. +- [ ] **Step 3: Write `secret_types.hpp`.** +- [ ] **Step 4: Run** the five local lanes over `libs/codecs/test`. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: the secret results, in place and on the heap with any allocator, every buffer wiped before it is returned`. Lint step. + +--- + +### Task 6: Secret operations + +Model tier: most capable. Covers tasks.md 2.5's operations. + +**Files:** +- Create: `include/webcpp/codecs/detail/core/secrecy.hpp`; `test/support/timing_seam.hpp`, + `test/support/timing_dit.hpp` (secure's, `timing_library = "codecs"`, namespace + `webcpp::codecs::test`, `#define WEBCPP_SECURE_TIMING_ENTERED(where) (::webcpp::codecs::test::timing_entered(where))`), + `test/secret_operation_test.cpp`, `test/timing_test.cpp` +- Modify: `detail/core/operations.hpp`, `detail/core/tokens.hpp` (`tokens::secret`), + `test/Jamfile`, `test/allocator_test.cpp`, `test/allocator_throw_test.cpp`, + `test/allocation_test.cpp`, `test/noexcept_test.cpp`, `codecs.hpp` + +**Interfaces:** +- Consumes: Tasks 3 to 5; secure's `timing_guard`, `secret`, `erase_secret`. +- Produces: + +```cpp +namespace webcpp::codecs { +template struct is_secret : std::false_type {}; +template inline constexpr bool is_secret_v = is_secret>::value; +template struct is_secret> : std::true_type {}; +template struct fixed_byte_storage>; // writable() through secret's +template struct is_secret> : std::true_type {}; // and secret_bytes, +template struct is_secret> : std::true_type {}; // the heap types +namespace tokens { +template > struct secret_t { + static constexpr bool secret = true; + Allocator allocator; + template constexpr secret_t operator()(Other const& other) const noexcept; +}; +inline constexpr secret_t<> secret{}; +} +namespace detail { +template inline constexpr bool secret_operation_v = /* D10 */; +} +} +``` + A secret operation (D10): returns D9's secret column; holds `secure::timing_guard const timing_scope{true};` + in the core's function that runs it (the codec runs inside it), and a public one holds none + (B11); every temporary of the core (a typed decode's buffer before it is moved into the result) + is wiped by `secure::erase_secret` through a scope guard, also when an allocation throws. + `tokens::secret` gives the fixed form when the bound is static (ignoring its allocator), else + `basic_secret_string` or `basic_secret_byte_vector`. + +- [ ] **Step 1: Write the failing tests.** + - `secret_operation_test.cpp` (wipe seam defined): a test type `key32` with `is_secret` and a + static `size()` of 32 encodes with `letters` to `result>` (the spec's scenario + "A secret type encodes to a wiped text", here on `letters`; Task 13 adds hex's); + `encode(letters, secure::secret<32>)` is `result>`; + `decode>(letters, text)` gives the secret and records the wipe of its + temporary; `decode>(letters, text)` is secret; `decode(letters, text, tokens::secret)` + of a run-time text is `result`; of a `text<64>` `result>`; + a value codec with `secret = true` (a `be16` variant of the test's own) gives `secret_bytes<2>`; + the counting `operator new` sees no allocation in the fixed secret forms. + - `timing_test.cpp` (seam first): encoding `key32` with `letters` raises `timing_entries` by + exactly one and `timing_first_entry` names codecs' `encode`; encoding public bytes raises it + by none (the spec's scenario "A secret operation sets DIT through secure", here on `letters`; + Task 13 adds hex's); where `WEBCPP_SECURE_TIMING_COVERED` and `secure::cpu_has_dit()`, DIT + reads set inside a value codec of the test's own that records `secure::dit_is_set()` during a + secret encode, and clear after it. + - `allocator_test.cpp` gains `tokens::secret(std::pmr::polymorphic_allocator{&arena})`; + `allocator_throw_test.cpp` gains `tokens::secret(throwing)` on a secret encode: the exception + reaches the test and every buffer it had allocated was deallocated zero; + `noexcept_test.cpp` gains the fixed secret forms (`noexcept`) and the heap ones (`!noexcept`). +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//secret_operation`. +- [ ] **Step 3: Write `secrecy.hpp`, `tokens::secret` and the secret paths** of `operations.hpp`. +- [ ] **Step 4: Run** the five local lanes over `libs/codecs/test`. Expected: pass; on this Mac + (arm64, FEAT_DIT) the DIT check runs. +- [ ] **Step 5: Commit, lint.** `codecs: secret operations, by the value's type, the value codec, the token or the requested type, under secure's guard, every temporary wiped`. Lint step. + +--- + +### Task 7: Composition: `over` + +Model tier: standard. Covers tasks.md 2.6. Ends with MSVC checkpoint 1. + +**Files:** +- Create: `include/webcpp/codecs/detail/core/over.hpp`; `test/over_test.cpp` +- Modify: `test/Jamfile`, `test/allocator_test.cpp`, `test/allocator_throw_test.cpp`, + `test/allocation_test.cpp`, `test/noexcept_test.cpp`, `codecs.hpp` + +**Interfaces:** +- Consumes: Tasks 2 to 6. +- Produces: + +```cpp +namespace webcpp::codecs { +template > +struct over { + Outer outer; + Inner inner; + Allocator allocator; // used for the heap intermediate alone + static constexpr std::string_view name = /* Outer::name, " over ", Inner::name, in a static array */; +}; +template over(Outer, Inner) -> over; +template over(Outer, Inner, Allocator) -> over; +template struct codec>; +} +``` + `over` is a format through `codec>` (and a value codec's `over` through + `value_codec, Value>`), whose bounds compose the links'. Its intermediate is in place + (`std::array`) when the links' bound is static, else from `allocator`; it is wiped when the + chain is secret. Its exact `encoded_size` and `decoded_size` run the inner link into the + intermediate (ruling R3): with a heap intermediate they allocate, so those, and `over`'s + encode and decode with a heap intermediate, are not `noexcept`; with a static bound they are + `noexcept` and allocate nothing. A chain is constant time when both links are, secret when any + link's operation is. + +- [ ] **Step 1: Write the failing tests** (`over_test.cpp`): `over{letters, letters}` has `name` + "letters over letters"; 16 bytes encode to the letters of the letters (64 characters) and + decode back, with no allocation for a `std::array` input (the spec's scenario "Hex over base64", + here on test formats; Task 16 adds the real one); `over{letters, be16}` encodes `number{0x1234}` + to `"bcde"` and decodes back; a secret chain (`key32` inside) gives `secret_text<128>` and + records the wipe of its intermediate; `over{letters, letters, std::pmr::polymorphic_allocator{&arena}}` + on a `std::vector` input takes its intermediate from the arena (allocator_test row); + `allocator_throw_test.cpp` row: a throwing intermediate allocation on a secret chain leaves no + unwiped buffer; `noexcept_test.cpp` rows for both intermediates. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//over`. +- [ ] **Step 3: Write `over.hpp`.** +- [ ] **Step 4: Run** the five local lanes over `libs/codecs/test`. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: over, a format of two links, its intermediate in place or from its allocator and wiped when secret`. Lint step. +- [ ] **Step 6: MSVC checkpoint 1.** After `$W/codecs/refresh-tree.sh`: x64 debug on 14.3 and 14.5 + over `libs/codecs/test`. Expected: `new failures:` empty, no warning at `/W4 /WX`. A failure is + fixed in this task's area, committed, and the checkpoint re-run. + +--- + +### Task 8: The transformer contract and the toy media types + +Model tier: most capable (the contract of all of webcpp). Covers tasks.md 2.8, 2.9's types. + +**Files:** +- Create: `include/webcpp/codecs/detail/core/transformer.hpp`; `test/support/toy_media.hpp`, + `test/support/doubler.hpp`, `test/transformer_test.cpp`, `test/toy_media_test.cpp` +- Modify: `test/Jamfile`, `test/allocation_test.cpp`, `codecs.hpp` + +**Interfaces:** +- Produces (D17, D18, verbatim): + +```cpp +namespace webcpp::codecs { +namespace detail { template concept transformer_types = /* D17 */; } +template concept one_shot_transformer = /* D17 */; +template concept stream_transformer = /* D17 */; +enum class flow : unsigned char { needs_input = 1, output_pending = 2, finished = 3 }; +struct step { std::size_t count; codecs::flow flow; }; +template struct capacity_t { static constexpr std::size_t value = N; }; +template inline constexpr capacity_t capacity{}; +struct secret_operation_t {}; +inline constexpr secret_operation_t secret_operation{}; +template inline constexpr bool is_constant_time_v = /* T::constant_time when present, else false */; +template inline constexpr std::size_t default_capacity_v = + sizeof(Element) >= 512 ? 1 : 512 / sizeof(Element); // B32 +namespace detail { +template concept compatible_elements = /* D19 */; +template concept has_max_output_size = /* T::max_output_size(std::size_t) */; +template concept has_constant_max_output_size = /* usable in a constant expression */; +} +} +// test/support/toy_media.hpp, namespace webcpp::codecs::test: +// struct packet { std::uint32_t index; std::uint8_t frames; }; // frames: 0, 1 or 2 +// struct frame { std::uint32_t index; std::array pixels; }; +// struct image { std::uint32_t index; std::uint64_t checksum; }; +// class packets_to_frames: a stream_transformer of packet to frame, stateful: each packet yields +// `frames` frames whose index is the packet's index times 2 plus their rank, pixels +// {index, index + 1, index + 2, index + 3}, and holds the last frame back until the next packet or +// flush (a B-frame's reordering): frames come out in index order; +// struct frame_to_bytes: one-shot, frame to std::uint8_t, writes 2 + (index % 3) bytes +// (the index's low byte, then pixels' low bytes), no max_output_size (variable); +// struct frame_to_bytes_bounded: the same with static constexpr max_output_size(n) = 4 * n; +// struct frame_to_image: one-shot, frame to image, one image a frame, +// static constexpr max_output_size(n) = n. +``` + +- [ ] **Step 1: Write the failing tests.** + - `transformer_test.cpp`: a stream transformer of the test's own, `test::doubler` in + `support/doubler.hpp`, which Task 9 also uses (char to char, + writes each character twice, holds the second when the output had room for one; its pending + state one character): `stream_transformer`, `!one_shot_transformer`; the + protocol's states (D18): starts in `needs_input`; `send("ab")` gives `{2, output_pending}`; + a second `send` gives `{0, output_pending}`; `receive` into a span of 3 gives `{3, output_pending}` + with "aab"; into 8 gives `{1, needs_input}` with "b"; `receive` of an empty span gives + `{0, state}`; `flush()` gives `finished`; `send` after it `{0, finished}`; a second `flush` + returns the state; `reset()` returns to `needs_input` and `send` is accepted; + `is_constant_time_v` is false and true for a type with `constant_time = true`; + `default_capacity_v == 512`, `default_capacity_v == 128`, + `default_capacity_v> == 1`; `flow` is never an `error_code` + (`!boost::system::is_error_code_enum::value`). + - `toy_media_test.cpp`: `stream_transformer`, + `one_shot_transformer`, `one_shot_transformer`; + five packets with frames {1, 0, 2, 1, 2} streamed one a send, received one frame a receive, + give frames 0, 4, 5, 6, 8, 9 in order (the hold-back delays frame 9 until `flush`); the one-shot + transformers' outputs for frame 4. + - `allocation_test.cpp` gains the toy transformers' calls (no allocation). +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//transformer`. +- [ ] **Step 3: Write `transformer.hpp`.** +- [ ] **Step 4: Run** the five local lanes over `libs/codecs/test`. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: the conversion contract, one-shot and stream transformers of any data, the flow and the toy media types that prove it`. Lint step. + +--- + +### Task 9: `pipe` and `drain` + +Model tier: most capable. Covers tasks.md 2.10 (public; secrecy in Task 12). + +**Files:** +- Create: `include/webcpp/codecs/detail/core/pipe.hpp`; `test/pipe_test.cpp`, + `test/drain_test.cpp`, `test/messages/pipe_incompatible/`, `test/messages/pipe_one_shot/` +- Modify: `test/Jamfile`, `test/messages/Jamfile`, `test/allocation_test.cpp`, + `test/noexcept_test.cpp`, `codecs.hpp` + +**Interfaces:** +- Consumes: Task 8. +- Produces: + +```cpp +namespace webcpp::codecs { +template +class piped; // input_type First::input_type, output_type Second::output_type; constant_time + // when both are; every member noexcept; moved-from is reset +template +[[nodiscard]] auto pipe(First first, Second second) noexcept; // Capacity default_capacity_v +template +[[nodiscard]] auto pipe(First first, Second second, capacity_t) noexcept; +template +[[nodiscard]] auto pipe(First first, Second second, Third third, Rest... rest) noexcept; // left fold +template +[[nodiscard]] result drain(T& transformer, Sink&& sink); // noexcept when the sink is +template +[[nodiscard]] result drain(T& transformer, Sink&& sink, capacity_t); +template +[[nodiscard]] result drain(T& transformer, Sink&& sink, std::span buffer); +} +``` + `pipe`'s refusals, in its body: `static_assert(stream_transformer && stream_transformer, "webcpp::codecs: pipe and drain take stream transformers; make a one-shot transformer one with codecs::each (per item) or codecs::buffered (accumulating)");` + then `static_assert(detail::compatible_elements, "webcpp::codecs: the first transformer's output_type is not the second's input_type");` + (the requirement line names both types, ruling R2); `drain` holds the first. The pipe's + algorithm is D19's: `receive` moves `first`'s output into the intermediate, sends it to + `second`, and receives `second`'s output into the caller's span while it has room; the first + error of either is the pipe's and is returned by every later call until `reset`. A sink + returns `void` or `result`; its error stops the drain and is returned. + +- [ ] **Step 1: Write the failing tests.** + - `pipe_test.cpp`: `pipe(doubler, doubler)` quadruples each character, for every input split + into chunks of 1, 2 and 7, and output spans of 1 and 1024; `pipe(a, b, capacity<1>)` the same + (the intermediate of one element); `pipe(a, b, c)` is `piped, C, 512>`; + `compatible_elements` and `` hold, `` + does not; an error transformer of the test's own (`failing`, which reports + `invalid_character` at `flush`) as `second` makes the pipe return it, then again on every call + until `reset`; a moved-from pipe, after a move mid-stream, converts a new input from the + start (Review Focus 5); the toy `pipe(packets_to_frames, each(...))` waits for Task 10. + - `drain_test.cpp`: `drain` stops at `needs_input` after a send and at `finished` after + `flush`; the sink sees non-empty pieces whose concatenation is the output; with `capacity<3>` + pieces are at most 3; with a caller's span of 5, at most 5; a sink that returns an error at its + second piece stops the drain, which returns that error, and is not called again (the spec's + scenario). + - `messages/pipe_incompatible`: `pipe(doubler, test::packets_to_frames{})`, expected error the + requirement line `detail::compatible_elements`. + `messages/pipe_one_shot`: `pipe(doubler, test::frame_to_image{})`, the first message. + - `allocation_test.cpp`: `pipe` and `drain` after construction allocate nothing; + `noexcept_test.cpp`: `piped`'s members and `drain` with a `noexcept` sink are `noexcept`. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//pipe`. +- [ ] **Step 3: Write `pipe.hpp`.** +- [ ] **Step 4: Run** the five local lanes over `libs/codecs/test`. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: pipe and drain, composed by element types alone, in place, with their refusals`. Lint step. + +--- + +### Task 10: `each` and `buffered` + +Model tier: most capable. Covers tasks.md 2.11 (public; secrecy in Task 12). + +**Files:** +- Create: `include/webcpp/codecs/detail/core/adapters.hpp`; `test/each_test.cpp`, + `test/buffered_test.cpp`, `test/messages/each_capacity_too_small/`, + `test/messages/buffered_without_bound/` +- Modify: `test/toy_media_test.cpp`, `test/Jamfile`, `test/messages/Jamfile`, + `test/allocator_test.cpp`, `test/allocator_throw_test.cpp`, `test/allocation_test.cpp`, + `test/noexcept_test.cpp`, `codecs.hpp` + +**Interfaces:** +- Consumes: Tasks 8, 9. +- Produces (D19, D22): + +```cpp +namespace webcpp::codecs { +template > +class each; // + [[nodiscard]] std::size_t completed_items() const noexcept; +template > +class buffered; +template each(T) -> each; +template each(T, capacity_t) -> each>; +template each(T, Allocator) -> each; +// buffered: the same three guides +} +``` + `each` and `buffered` with `capacity_t` allocate nothing and every member is `noexcept`; + with an allocator, construction, `send`, `receive` and `flush` may allocate and are not + `noexcept`, and a `send` that throws accepts nothing. `each>` holds + `static_assert(detail::has_constant_max_output_size && N >= T::max_output_size(1), "webcpp::codecs: each(transformer, capacity) needs T::max_output_size(1) as a constant expression and N >= it; declare max_output_size, raise N, or pass an allocator");` + `buffered>`: `static_assert(detail::has_constant_max_output_size, "webcpp::codecs: buffered(transformer, capacity) needs T::max_output_size(N) as a constant expression; declare it, or pass an allocator");` + An input past `N` is accepted, counted, and `flush` reports `input_too_long`. The heap forms + grow by `output_size`, then `max_output_size`, then doubling while `transform` reports + `output_too_small` (D19). The allocator is rebound through `std::allocator_traits` for the + other element. + +- [ ] **Step 1: Write the failing tests.** + - `each_test.cpp`: five frames through `each(frame_to_image)` into a span of one image a + receive give five images in order (the spec's scenario "Per item"); `each(frame_to_bytes_bounded, capacity<64>)` + into spans of 3 bytes gives each frame's bytes, no receive mixing two frames, and + `completed_items()` counting 1 to 5 at the boundaries; `flush` after the last item gives + `finished` at once; an item whose `transform` fails is reported by the receive that + transforms it; `each(frame_to_bytes, std::pmr::polymorphic_allocator{&arena})` + (no constant bound) works and the arena records; a moved-from `each` restarts. + - `buffered_test.cpp`: `buffered(letters_one_shot{}, capacity<64>)` (a one-shot transformer + of `std::uint8_t` to `char` over `letters`' codec, written in the test, + `static constexpr max_output_size(n) = 2 * n`) over 40 bytes in chunks of 7: + every receive before `flush` gives nothing, the output after `flush` equals the one-shot form, + no allocation counted (the spec's scenario "Accumulating", here on `letters`; Task 19 adds + base58's); 65 bytes into `capacity<64>` give `input_too_long` at `flush`; the heap form with + the arena; a moved-from `buffered` restarts. + - `toy_media_test.cpp` gains `pipe(packets_to_frames, each(frame_to_image, capacity<1>))` + (frames to images through a pipe, no allocation). + - `messages/each_capacity_too_small`: `each(frame_to_bytes_bounded{}, capacity<2>)`; + `messages/buffered_without_bound`: `buffered(frame_to_bytes{}, capacity<8>)`. + - `allocator_throw_test.cpp`: `buffered` and `each` with `throwing_allocator`: a throwing + `send` accepts nothing and the stream converts the same input after the exception; a + throwing `flush` leaves it resettable. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//each`. +- [ ] **Step 3: Write `adapters.hpp`.** +- [ ] **Step 4: Run** the five local lanes over `libs/codecs/test`. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: each and buffered, a one-shot transformer as a stream per item or accumulating, in place or with an allocator`. Lint step. + +--- + +### Task 11: Formats as transformers: `stream_codec`, `encoder`, `decoder` + +Model tier: most capable (B23, B43, B44, the protocol's error rules). Covers tasks.md 2.12. + +**Files:** +- Create: `include/webcpp/codecs/detail/core/format_transformer.hpp`; + `test/support/chunkings.hpp`, `test/format_transformer_test.cpp`, + `test/messages/encoder_of_value_format/`, `test/messages/capacity_without_hold/`, + `test/messages/drain_of_one_shot/` +- Modify: `test/support/letters.hpp` (its `stream_codec`, and a configurable variant), + `test/Jamfile`, `test/messages/Jamfile`, `test/allocation_test.cpp`, `test/noexcept_test.cpp`, + `codecs.hpp` + +**Interfaces:** +- Consumes: Tasks 2, 7 to 10. +- Produces (D20): + +```cpp +namespace webcpp::codecs { +struct stream_options { bool secret = false; std::size_t capacity = 0; }; // structural +template struct stream_codec; // declared, never defined +// a specialization: template class encoder; ... decoder; +// each a stream_transformer constructed from Format const&; a decoder that holds its input +// declares static constexpr bool holds = true and takes Options.capacity (0: its default) +template class format_encoder; // std::uint8_t -> char +template class format_decoder; // char -> std::uint8_t +template [[nodiscard]] auto encoder(F const& format) noexcept; +template [[nodiscard]] auto encoder(F const& format, secret_operation_t) noexcept; +template [[nodiscard]] auto decoder(F const& format) noexcept; +template [[nodiscard]] auto decoder(F const& format, secret_operation_t) noexcept; +template [[nodiscard]] auto decoder(F const& format, capacity_t) noexcept; +template [[nodiscard]] auto decoder(F const& format, secret_operation_t, capacity_t) noexcept; +template [[nodiscard]] auto decoder(F const& format, capacity_t, secret_operation_t) noexcept; +} +// test/support/chunkings.hpp: for_each_chunking(std::span, callback) calls back with every +// split into two and three chunks, chunks of one element, and 32 random chunkings +// (std::mt19937_64{20261126}); stream_whole(transformer, chunks, output_span_size) -> result>. +``` + `format_encoder` is a `one_shot_transformer` always (`transform` is `codec::encode` into the + span, `max_output_size` is `codec::max_encoded_size`, `output_size(input)` is + `codec::encoded_size`) and a `stream_transformer` through members constrained on + `stream_codec` being specialized; its `constant_time` is `codec::constant_time`. It + forwards `human_readable_part()` and `label()` when the stream decoder has them (B39). + `encoder(over{outer, inner})` streams through a held `pipe(encoder(inner), encoder(outer))` + when both links stream, and `decoder` through `pipe(decoder(outer), decoder(inner))` (B43). + Refusals: `encoder` and `decoder` of a value codec's format: + `"webcpp::codecs: a value codec's format has no transformer; typed values are converted whole by codecs::encode and codecs::decode"`; + `decoder(format, capacity)` of a format whose decoder does not hold: + `"webcpp::codecs: codecs::capacity sets the hold of a decoder that holds its input, as bech32's; this format's decoder holds nothing"`. + The error rules every `stream_codec` keeps (D18, B23, B44), which this task's test pins on + `letters` and every format task on its own: a configuration fault is reported by the first + call; data faults after `flush` by the first call that processed the whole input, the + one-shot form's error; that call writes nothing; after an error every call returns it until + `reset`. + `letters`' `stream_codec`: the encoder holds one letter the output had no room for; the decoder + holds one letter of a pair and the error mask. The configurable variant, `letters_t` with a + `bool configured_fault` member set by `letters(true)`, reports `invalid_prefix` before any data. + +- [ ] **Step 1: Write the failing tests** (`format_transformer_test.cpp`): + `one_shot_transformer` and `stream_transformer<...>`; + `test::whole_letters` (in `support/letters.hpp`: `letters`' codec, under the name + "whole_letters", with no `stream_codec`) gives a one-shot transformer only + (`!stream_transformer`); `encoder(letters)` over every chunking of 0, 1, 31, 32, 33 and 1000 + random bytes, with output spans of 1 and 1024, equals `encode(letters, bytes)`; `decoder` the + same over valid texts and over invalid ones (`"abq"` split everywhere: `invalid_character` + after `flush`, the one-shot's error); `send` 64 bytes then 4 more before any receive gives + `{64, output_pending}` then `{0, output_pending}` (the spec's scenario, here on `letters`; Task + 13 adds hex's); a decoder sent 4000 valid letters and drained, then 96 letters whose last is + `z`, flushed, and received into a span of 1024 returns `invalid_character` with the span + unchanged (B44, the spec's scenario on `letters`; Task 16 adds base64's); the configured + fault is reported by the first `send`, before data, in both forms (B23); after an error both + receives return it and after `reset` a valid text decodes; `encoder(over{letters, letters})` is + a stream transformer equal to the one-shot `over` for every chunking; `encoder(over{letters, be16})` + stops the build (a `requires` probe is false); a moved-from encoder restarts. + Messages: `encoder_of_value_format` (`encoder(test::be16)`), `capacity_without_hold` + (`decoder(test::letters, capacity<8>)`), `drain_of_one_shot` (`drain(encoder(test::whole_letters), sink)`, + the `pipe` message of Task 9). `allocation_test.cpp`: every stream call allocates nothing. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//format_transformer`. +- [ ] **Step 3: Write `format_transformer.hpp`** and `letters`' `stream_codec`. +- [ ] **Step 4: Run** the five local lanes over `libs/codecs/test`. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: encoder and decoder, a format's one-shot transformer always and its stream through stream_codec, with the protocol's error rules`. Lint step. + +--- + +### Task 12: Secret streams + +Model tier: most capable. Covers tasks.md 2.13 and D21's secrecy. Ends with MSVC checkpoint 2. + +**Files:** +- Create: `test/secret_stream_test.cpp` +- Modify: `detail/core/pipe.hpp`, `detail/core/adapters.hpp`, + `detail/core/format_transformer.hpp`, `test/support/letters.hpp` (its stream codec wipes its + pending state when `Options.secret`), `test/Jamfile`, `test/allocation_test.cpp` + +**Interfaces:** +- Produces: `is_secret>` and `is_secret>` true when + `O.secret`; `is_secret>` when either part is; `is_secret>` and + `is_secret>` when `T` is. A secret transformer is move-only; each of its + public calls holds `secure::timing_guard const timing_scope{true};` (nesting with its parts'); + `reset`, the destructor and the moved-from object wipe its pending state, `pipe`'s + intermediate, `buffered`'s and `each`'s storage with `secure::erase_secret`; `drain` wipes its + buffer before it returns when the transformer is secret. A `stream_codec` sees `Options.secret` + and wipes its own carries. + +- [ ] **Step 1: Write the failing tests** (`secret_stream_test.cpp`, both seams first, a probe + transformer of the test's own, `dit_probe` (`std::uint8_t` to `std::uint8_t`, copies, records + `secure::dit_is_set()` in each call, `is_secret` specialized)): + - `pipe(encoder(letters, secret_operation), encoder(letters, secret_operation))` over 31 bytes: + `timing_entries` grows by at least one per call of the pipe, `std::is_copy_constructible_v` + is false; where `WEBCPP_SECURE_TIMING_COVERED` and `secure::cpu_has_dit()`, + `pipe(dit_probe, dit_probe)` records DIT set in every call and `secure::dit_is_set()` is clear + after each (the "count back to zero" of D15, ruling R4); `each` and `buffered` over secret + parts the same; + - 31 secret bytes into a secret encoder of `letters` with output spans of one letter (leaving + one letter pending), then a move, `reset` of the target and destruction of both: the wipe + seam records the pending state's wipe in the source after the move, at `reset` and at + destruction (the spec's scenario "A secret stream's state is wiped", here on `letters`; Task + 16 adds base64's); `pipe`'s intermediate, `buffered`'s storage and `drain`'s buffer are + recorded wiped likewise; a moved-from secret encoder restarts (Review Focus 5). +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//secret_stream`. +- [ ] **Step 3: Implement** the secrecy of the four transformers and `drain`. +- [ ] **Step 4: Run** the five local lanes over `libs/codecs/test`. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: secret streams, move-only, a guard in every call nesting with their parts', their pending state wiped on reset, move and destruction`. Lint step. +- [ ] **Step 6: MSVC checkpoint 2.** x64 debug on 14.3 and 14.5 over `libs/codecs/test`, and + arm64 debug on 14.5 over `libs/codecs/test//timing libs/codecs/test//secret_stream libs/codecs/test//secret_operation`. + Expected: `new failures:` empty; on arm64 the DIT checks run. + +--- + +### Task 13: hex + +Model tier: standard (the first real format sets the pattern). Covers tasks.md 3.1. + +**Files:** +- Create: `include/webcpp/codecs/hex.hpp`, `include/webcpp/codecs/detail/formats/hex.hpp`; + `test/hex_test.cpp`, `test/hex_stream_test.cpp`, `test/messages/refused_pair_hex/`, + `test/messages/pipe_char_to_packet/` +- Modify: `test/toy_media_test.cpp`, `test/secret_operation_test.cpp`, `test/timing_test.cpp`, + `test/format_transformer_test.cpp`, `test/Jamfile` (its headers-alone list gains + `codecs/hex.hpp codecs/detail/formats/*.hpp`), `test/messages/Jamfile`, + `test/allocation_test.cpp` + +**Interfaces:** +- Produces: + +```cpp +namespace webcpp::codecs::formats { +enum class letter_case : unsigned char { lower = 1, upper = 2 }; +struct hex_t { + static constexpr std::string_view name = "hex"; + letter_case written_case = letter_case::lower; + [[nodiscard]] constexpr hex_t operator()(letter_case chosen) const noexcept; +}; +inline constexpr hex_t hex{}; +} +// codec: constant_time = true; max_encoded_size(n) = 2n (saturating), +// max_decoded_size(n) = n / 2; stream_codec (D20's table). +``` + The arithmetic is libsodium's `sodium_bin2hex` and `sodium_hex2bin` over secure's blocks: a + nibble `v` to its character by `select(is_less_mask(v, 10), '0' + v, base + v - 10)` (`base` + `'a'` or `'A'`, public); a character to its nibble by `is_in_range_mask` over `'0'..'9'`, + `'a'..'f'` and `'A'..'F'` (each byte cast to `std::uint8_t` first, Review Focus 1), the error + mask OR-accumulated and passed to `secure::declassify` before the one branch; an odd length is + `invalid_length`, reported after the mask (B23: `invalid_character` wins). + +- [ ] **Step 1: Write the failing tests.** + - `hex_test.cpp`: RFC 4648 section 10's base16 vectors ("" -> "", "f" -> "66", ... "foobar" -> + "666F6F626172") with `hex(letter_case::upper)`, lower case by default, each decoding back + from either case and from mixed case (the spec's scenario); 32 bytes in 63 characters + `output_too_small` (the spec's scenario "A short buffer"); `std::array` + round trip as `text<64>` and `bytes<32>` with no allocation (the spec's scenario "A digest's + hex with no heap"); `decode>` of 64 and of 62 digits (the spec's + scenario); `boost::urls::string_token::append_to` (the spec's scenario "Boost.URL's token", + the test's requirement naming `/webcpp/codecs//percent`); `tokens::append_to` of a + `std::pmr::string` and `return_string(pmr)` over an arena (the spec's scenario "A pmr string + token"); every one of the 256 byte values at the first and the second position of a pair: + the verdict equals a plain table's (Review Focus 1); `"abc\n"` is `invalid_character`; + decoding in place into the text's own buffer (Review Focus 4); empty input in each form + (Review Focus 3); `max_encoded_size(SIZE_MAX) == SIZE_MAX`. + - `hex_stream_test.cpp`: every vector and 1000 random bytes through `encoder(hex)` and + `decoder(hex)` for every chunking (`chunkings.hpp`) equal the one-shot forms, errors + included; `send` 64 bytes then 4 more (the spec's scenario "Send while output is pending"); + a finished encoder's `send` is `{0, finished}`, and a decoder whose `flush` reported + `invalid_character` returns it twice and decodes after `reset` (the spec's scenario "After + the end and after an error"); reading a "file" of 64 KiB in 4096-byte chunks into one buffer, + sending each, draining into a fixed span before the next: equal to the one-shot form, no + allocation (the spec's "A file ... with no heap", here on hex; Task 16 adds base64's). + - `secret_operation_test.cpp` and `timing_test.cpp` gain the spec's scenarios on hex: `key32` + encodes to `secret_text<64>`, whose storage reads zero through the wipe seam after its + destruction; `secure::secret<32>` to `secret_text<64>` and back with + `decode>`, both secret, no heap; `decode>(formats::hex, text)` + secret, its temporaries recorded wiped, no heap; one guard entered for the secret call, in + codecs' function, none for the public one. + - `toy_media_test.cpp` gains the spec's scenario "A toy media transformer satisfies the + contract": `pipe(pipe(packets_to_frames, each(frame_to_bytes_bounded, capacity<16>)), encoder(hex))` + compiles and five packets give the hex of the frames' bytes in order. + - Messages: `refused_pair_hex` (`decode(formats::hex, text)`, the + requirement line names `webcpp::codecs::formats::hex_t`), `pipe_char_to_packet` + (`pipe(encoder(formats::hex), test::packets_to_frames{})`, names `char` and + `webcpp::codecs::test::packet`). + - `allocation_test.cpp`: hex's buffer, fixed and secret fixed forms and its streams. +- [ ] **Step 2: Run, expect failure.** `B2 toolset=clang libs/codecs/test//hex`. +- [ ] **Step 3: Write `hex.hpp`** (format, codec, stream codec; the arithmetic in + `detail/formats/hex.hpp`, shared with no one). +- [ ] **Step 4: Run** the five local lanes over `libs/codecs/test`. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: hex, constant time, its stream, RFC 4648's base16 vectors`. Lint step. + +--- + +### Task 14: The constant-time lane + +Model tier: most capable (checkers' semantics, planted leaks, CI wiring). Covers tasks.md 4.1's +lane, over hex; each later format task adds its paths. + +**Files (libs/codecs/test/constant_time/):** +- Create: `Jamfile`, `paths.hpp`, `ctgrind_test.cpp`, `ctgrind_planted_test.cpp`, + `msan_test.cpp`, `msan_planted_test.cpp`, `dudect.hpp`, `dudect_test.cpp`, + `dudect_planted_test.cpp`, `dudect_harness_test.cpp`, `dudect_judge.py`, `valgrind.mjs`, + `msan_report.mjs`, `package.json`, `package-lock.json` (secure's lane copied, `secure` -> + `codecs` in names, `webcpp-codecs-constant-time`) +- Create: `test/support/constant_time_marks.hpp` (secure's, namespace `webcpp::codecs::test`, O5) +- Modify: `libs/codecs/test/Jamfile` (`build-project constant_time ;`) +- Modify (superproject): `tools/ci/matrix.py` (`OWN_LANE_PACKAGES` gains + `('codecs', 'constant-time', 'native'): ('valgrind', 'llvm-18', 'libclang-rt-18-dev')`), + `tools/ci/matrix_test.py`, `.github/workflows/library.yml` (the "Judge dudect" step also for + `matrix.library == 'codecs'`), `tools/test/codecs_dudect_judge_test.py` (secure's form) + +**Interfaces:** +- Consumes: hex (Task 13), secret streams (Task 12), secure's `declassify` and blocks. +- Produces: the own lane `constant-time` of codecs; `paths.hpp`'s + `template int format_paths()`, to which each format task adds its block. + +- [ ] **Step 1: Write the lane, planted leak first.** `paths.hpp`: for hex, encode and decode of + 64 secret bytes (one-shot, buffer form and `secret_text`), the stream form in chunks of 7 + (fixed, public) with output spans of 5, every input marked secret with + `Checker::mark_secret`; a decode's verdict reaches `Checker::verdict` only after + `secure::declassify` (the library's own branch); an invalid text's error mask likewise. + Planted, each `[[gnu::noinline]]`: `planted_hex` (a hex encode that indexes + `"0123456789abcdef"[nibble]`), under `WEBCPP_TEST_CODECS_PLANTED_HEX`. `dudect_test.cpp`: + hex decode of 64 characters (class 0: all `'0'`; class 1: random valid), hex encode (zeros vs + random), each with the A/A control; `dudect_planted_test.cpp`: the planted hex, which must + exceed the threshold. The Jamfile is secure's (CTGRIND, MSAN, DUDECT blocks, `webcpp.lane + constant-time : ... : native ;`) with codecs' names and `WEBCPP_SECURE_CT_VALGRIND` / + `WEBCPP_SECURE_CT_MSAN` as the defines (secure's `declassify` reads them). +- [ ] **Step 2: See the planted leak fail and the rest pass, natively on Linux.** + `$W/heavy.sh codecs $W/codecs/ct-run/linux.sh codecs constant-time` (commit and refresh first). + Expected: the lane exits 0: memcheck and MemorySanitizer pass on the paths and report + `planted_hex` in its own frame; dudect below the threshold with its A/A control, the planted + one above. +- [ ] **Step 3: On this Mac** (dudect only): + `B2 toolset=clang libs/codecs/test/constant_time//dudect libs/codecs/test/constant_time//dudect_planted libs/codecs/test/constant_time//dudect_harness`. + Expected: pass. +- [ ] **Step 4: The superproject's wiring.** `python3 tools/ci/matrix_test.py`, + `python3 tools/test/codecs_dudect_judge_test.py`, + `python3 tools/ci/matrix.py own-lanes --library codecs --user-config .local/user-config.jam`. + Expected: pass. +- [ ] **Step 5: Commit, lint.** codecs: `codecs: the constant-time lane, memcheck, MemorySanitizer and dudect over hex, with a planted leak that must fail`; superproject: `ci: codecs' constant-time lane, its packages and dudect's judge`. Lint step. + +--- + +### Task 15: The fuzz lane + +Model tier: most capable (a lane webcpp has not had before, ruling R5). Covers tasks.md 4.2's +lane, over hex and `over`; each later format task adds its target. + +**Files (libs/codecs/test/fuzz/):** +- Create: `Jamfile`, `fuzz.mjs`, `package.json`, `package-lock.json`, `target.hpp`, + `hex_fuzz.cpp`, `over_fuzz.cpp`, `corpus/hex/*`, `corpus/over/*` +- Create: `test/support/fuzz_replay_main.cpp` +- Modify: `libs/codecs/test/Jamfile` (`build-project fuzz ;`) +- Modify (superproject): `tools/ci/matrix.py` (`('codecs', 'fuzz', 'native'): ('llvm-18', 'libclang-rt-18-dev')`), + `tools/ci/matrix_test.py` + +**Interfaces:** +- Produces: the own lane `fuzz`; `target.hpp`'s helpers, which every target uses: + +```cpp +namespace webcpp::codecs::test { +// Decodes `input` as text one-shot (buffer form, no allocation counted), and as a stream split at +// the points the next input bytes choose; asserts both give the same bytes and error; if it +// decoded, encodes the bytes and asserts the text equals `input` (case folded where the format +// decodes either case). Aborts (__builtin_trap) on a mismatch. +template +void check_decoder(Format const& format, std::span input, bool fold_case); +} +// each _fuzz.cpp: extern "C" int LLVMFuzzerTestOneInput(std::uint8_t const*, std::size_t) +``` + No-heap: under libFuzzer, `__sanitizer_install_malloc_and_free_hooks` counts allocations inside + the buffer form; in the replay build, `support/counting.hpp`. The Jamfile: + +```jam +project : requirements /webcpp/codecs//codecs ; +import webcpp regex ; +webcpp.targets native wasip2 wasip3 emscripten ; +webcpp.original node ; +# clang-on-linux: secure's test/constant_time/Jamfile rule, copied. +FUZZ = -fsanitize=fuzzer,address,undefined -fsanitize=fuzzer,address,undefined + release on @clang-on-linux ; +path-constant FUZZ_CORPUS : corpus ; +.corpus = [ regex.replace $(FUZZ_CORPUS) "\\\\" "/" ] ; +# Each target is replayed on every lane, with exceptions on and off, over its +# corpus and 4096 inputs of a fixed xorshift stream: the assertions run +# everywhere with no fuzzing engine. libFuzzer runs it natively on Linux. +rule codecs-fuzz ( name ) +{ + local replay = $(name)_fuzz.cpp ../support/fuzz_replay_main.cpp ; + local data = "\"WEBCPP_TEST_CODECS_FUZZ_CORPUS=\\\"$(.corpus)/$(name)\\\"\"" + [ webcpp.data $(FUZZ_CORPUS)/$(name) ] [ glob corpus/$(name)/* ] ; + webcpp.run $(name)_replay : $(replay) : $(data) ; + webcpp.run $(name)_replay_no_exceptions : $(replay) : $(data) off ; + webcpp.drive $(name)_fuzz : $(name)_fuzz.cpp : $(FUZZ) : fuzz.mjs + : --corpus $(FUZZ_CORPUS)/$(name) --seconds 60 : native ; +} +codecs-fuzz hex ; +codecs-fuzz over ; +webcpp.lane fuzz : hex_fuzz over_fuzz : native ; +``` + (the define's quoting is blake3_vectors' in `third_party/Jamfile`, chapter 8's form; the + implementer checks it on Windows paths' backslashes.) `fuzz.mjs` runs the program with + `-max_total_time= -seed=20261126 -timeout=10 ` and passes + with its exit status; a crash's input is printed in base64. `over_fuzz.cpp` fuzzes + `over{formats::hex, formats::hex}`. + +- [ ] **Step 1: Write the targets and the replay**; the corpus: hex's RFC vectors' texts, an odd + text, a text with each invalid class, one file each. +- [ ] **Step 2: Run the replays** on the five local lanes + (`libs/codecs/test/fuzz//hex_replay libs/codecs/test/fuzz//over_replay`). Expected: pass. Plant + a defect (hex decode accepting `'g'` as 16) locally, see `hex_replay` fail, revert. +- [ ] **Step 3: The lane on Linux.** `$W/heavy.sh codecs $W/codecs/ct-run/linux.sh codecs fuzz`. + Expected: both targets run their 60 seconds, exit 0. +- [ ] **Step 4: The superproject's wiring.** `python3 tools/ci/matrix_test.py`, + `python3 tools/ci/matrix.py own-lanes --library codecs --user-config .local/user-config.jam` + (two entries). Expected: pass. +- [ ] **Step 5: Commit, lint.** codecs: `codecs: the fuzz lane, libFuzzer on Linux and a replay on every lane, over hex and over`; superproject: `ci: codecs' fuzz lane and its packages`. Lint step. + +--- + +### Tasks 16 to 21: the formats (one pattern) + +Each format task writes, beside its own vectors and refusals, the same set of checks, which its +steps name as "the format checks": +- `_test.cpp`: its vectors through the buffer, token, default and typed forms; every + error of the spec's requirement for the format, one input each, and an input with two faults + giving the lowest value (B23); every one of the 256 byte values in each position class against + a plain table (Review Focus 1); in-place decode where the format allows it (Review Focus 4); + empty input (Review Focus 3); its bounds saturating at `SIZE_MAX` (Review Focus 2); + `codec::constant_time` as the spec says. +- `_stream_test.cpp`: every vector, valid and invalid, and 1000 random inputs, through + its stream encoder and decoder for every chunking (`chunkings.hpp`), output spans of 1 and 1024, + equal to the one-shot forms, errors after `flush` (B29); a configuration fault (where the + format has one) by the first call in both forms (B23); a failing call writes nothing (B44); a + secret encoder's and decoder's pending state recorded wiped on `reset`, move and destruction. +- `allocation_test.cpp`: its buffer, fixed, secret fixed and `tokens::fixed` forms, and its + stream encoder and decoder over 1 MiB of random bytes (or their text) in random chunks, nothing + counted after construction. +- The constant-time lane: its block in `paths.hpp` (one-shot, and the stream made with + `codecs::secret_operation` at fixed chunk sizes, every input secret, every verdict + declassified) and its dudect case, the lane run on Linux + (`ct-run/linux.sh codecs constant-time`, exit 0) and dudect on this Mac. +- The fuzz lane: `_fuzz.cpp` (each name of the header its own target), its corpus, its + `codecs-fuzz` line and `webcpp.lane fuzz` entry; replays on the five local lanes; the lane run + on Linux (`ct-run/linux.sh codecs fuzz`, exit 0). +- `test/Jamfile`: its tests, and its public header in the headers-alone list. +- Runs: the five local lanes over `libs/codecs/test`; then the commit and the lint step. + +### Task 16: base64 and base64url + +Model tier: standard. Covers tasks.md 3.2. + +**Files:** create `include/webcpp/codecs/base64.hpp`, `include/webcpp/codecs/detail/formats/base64.hpp` +(the 6-bit arithmetic, which armor reuses), `include/webcpp/codecs/detail/formats/options.hpp` +(`formats::padding`, shared with base32), `test/base64_test.cpp`, `test/base64_stream_test.cpp`, +`test/constant_time/` additions, `test/fuzz/base64_fuzz.cpp`, `test/fuzz/base64url_fuzz.cpp`, +corpora; modify `test/over_test.cpp`, `test/tokens_test.cpp`, `test/format_transformer_test.cpp`, +`test/secret_stream_test.cpp`, `test/Jamfile`, the lanes' Jamfiles. + +**Interfaces:** + +```cpp +namespace webcpp::codecs::formats { +enum class padding : unsigned char { written = 1, omitted = 2 }; +struct base64_t { // base64url_t the same, name "base64url", padding omitted + static constexpr std::string_view name = "base64"; + formats::padding padding_option = padding::written; + [[nodiscard]] constexpr base64_t operator()(formats::padding chosen) const noexcept; +}; +inline constexpr base64_t base64{}; +inline constexpr base64url_t base64url{}; +} +namespace webcpp::codecs::detail::base64_arithmetic { // used by base64.hpp and armor.hpp +template constexpr std::uint8_t symbol_of(std::uint8_t six_bits) noexcept; +template constexpr std::uint8_t six_bits_of(std::uint8_t symbol, std::uint8_t& error_mask) noexcept; +} +``` + libsodium's `sodium_bin2base64` and `sodium_base642bin` arithmetic over secure's blocks. + Decode is canonical (D13); with padding written the length is a multiple of 4 + (`invalid_length` otherwise), with padding omitted a length of 4k+1 is `invalid_length`. + +- [ ] **Step 1: Write the failing tests:** the format checks, with RFC 4648 section 10's vectors + both paddings, `{0xfb, 0xff}` as `"+/8="` and `"-_8"` (the spec's scenario), `"Zh=="` + `invalid_padding` (the spec's scenario), `"Zm9v\n"` and `"Zm9v Zm9v"` `invalid_character`, + `"Zm9"` with padding written `invalid_length`, a base64url character in base64 + `invalid_character`; `encoded_size(base64, "foob" as bytes)` 8 and `max_decoded_size(base64, "Zm9vYg==")` + 6 in a `static_assert`, the decode writing 4 (the spec's scenario "The exact size and the + bound"); `tokens::fixed<54>{}` for 40 bytes `output_too_small` with no `prepare` (the spec's + scenario); a `std::vector` input gives `result` (the spec's scenario "A run-time + input"); `over{hex, base64}` of 16 bytes is the hex of the base64 and allocates nothing (the + spec's scenario "Hex over base64"); `pipe(encoder(base64), encoder(hex))` over 1000 random + bytes in chunks of 7 drained into a `std::string` equals `encode(over{hex, base64}, bytes)` + (the spec's scenario "A stream over equals the one-shot over"); the base64 decoder's B44 + scenario (4000 valid characters, then 96 whose last is `*`); the file of 64 KiB through + `encoder(base64)` with no allocation (the spec's scenario "A file in base64 with no heap"); + 31 secret bytes into `encoder(base64, secret_operation)` leaving one byte pending, then move, + `reset` and destruction (the spec's scenario "A secret stream's state is wiped"); and the + guard-nesting pipe of base64 and hex encoders (the spec's scenario "Guards nest in a secret + pipe"). +- [ ] **Step 2: Run, expect failure;** **Step 3: write the header;** **Step 4: run** the format + checks' runs. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: base64 and base64url, constant time, canonical, their streams`. Lint step. + +### Task 17: bech32 and bech32m + +Model tier: most capable (the hold, the checksum by masks, the parts). Covers tasks.md 3.3. + +**Files:** create `include/webcpp/codecs/bech32.hpp`, `include/webcpp/codecs/detail/formats/bech32.hpp`, +`include/webcpp/codecs/detail/formats/bounded_label.hpp` (shared with armor), +`test/bech32_test.cpp`, `test/bech32_vectors.hpp` (BIP-173's and BIP-350's valid and invalid +lists and their segwit addresses with their scriptPubKeys, and BOLT 11's first example invoice, +each cited, ruling R8: no file of `third_party/libs` holds a BOLT 11 invoice, `bips` has BIP-173 +and BIP-350 only), `test/bech32_stream_test.cpp`, `test/messages/bech32_maximum_length_too_small/`, +the lanes' additions (`bech32_fuzz.cpp`, `bech32m_fuzz.cpp`, `bech32_words_fuzz.cpp`); modify +`test/Jamfile`, `test/messages/Jamfile`. + +**Interfaces:** + +```cpp +namespace webcpp::codecs::detail { +template class bounded_label { // up to N chars in place; constexpr from string_view +public: // longer: holds nothing and overflowed() is true + constexpr bounded_label() noexcept = default; + constexpr explicit bounded_label(std::string_view label) noexcept; + [[nodiscard]] constexpr std::string_view view() const noexcept; + [[nodiscard]] constexpr bool empty() const noexcept; + [[nodiscard]] constexpr bool overflowed() const noexcept; +}; +} +namespace webcpp::codecs::formats { +enum class bech32_variant : unsigned char { bech32 = 1, bech32m = 2 }; // the checksum's constant: 1, 0x2bc830a3 +struct bech32_bytes {}; // the default: bytes, 8 to 5 bits with zero padding, padding checked on decode +struct bech32_words {}; // each element one 5-bit value, 0 to 31, as it is (a word is 5 bits, not a machine word) + +template +struct bech32_parts { + text<83> human_readable_part; + bytes(MaximumLength)> data; // MaximumLength - 8 words, or their whole bytes +}; + +template +class basic_bech32 { + static_assert(MaximumLength >= 8, "webcpp::codecs: a bech32 maximum length is at least 8 characters"); +public: + static constexpr std::string_view name = Variant == bech32_variant::bech32 ? "bech32" : "bech32m"; + static constexpr std::size_t maximum_length = MaximumLength; + using data_type = Data; + using parts_type = bech32_parts; + constexpr basic_bech32() noexcept = default; // no human-readable part: decodes any + [[nodiscard]] constexpr basic_bech32 operator()(std::string_view chosen_part) const noexcept; + [[nodiscard]] constexpr basic_bech32 words() const noexcept; + [[nodiscard]] constexpr std::string_view human_readable_part() const noexcept; +private: + detail::bounded_label<83> part_; +}; +using bech32_t = basic_bech32; +using bech32m_t = basic_bech32; +inline constexpr bech32_t bech32{}; +inline constexpr bech32m_t bech32m{}; + +// BIP-173's convertbits from 8 to 5 with zero padding, appended to any container with push_back. +template void append_words_from_bytes(Words& words, std::span bytes); +// From 5 to 8: a value above 31 invalid_character; more than 4 padding bits or a non-zero one +// invalid_padding; output_too_small. Constant time, as the format. +[[nodiscard]] result bytes_from_words(std::span words, + std::span out) noexcept; +} +// codec> for every instance; value_codec, +// bech32_parts>: decode only (output_kind::text input), any human-readable part when the +// format has none (R12). stream_codec: the encoder writes as it goes and the checksum at flush; +// the decoder holds raw characters in place (Options.capacity, MaximumLength when 0, B47; a +// capacity above MaximumLength stops the build in decoder's static_assert) and gives +// human_readable_part() after a successful flush. +``` + The parameter is `chosen_part` (F14, MSVC's C4458); `chosen_maximum` is gone with the run-time + maximum. F25 is replaced: a maximum length below the shortest valid text (8) can no longer + exist at run time; `basic_bech32`'s `static_assert` stops the build, tested by the message case + `messages/bech32_maximum_length_too_small` (owner decision 27). The configuration's one fault, + checked first (B23): a human-readable part over 83 characters (`overflowed()`), outside 33 to + 126, or empty on encode: `invalid_prefix`. `polymod`'s conditional XOR is `select` by a mask + over the five generator words (D12), its final constant the variant's; the alphabet by `lookup` + over the 32-entry table and its inverse by masks; in words mode the encoder's verdict on a + value above 31 is accumulated by a mask, as a decode's. Every bound comes from `MaximumLength` + and 83 characters of human-readable part: the scratch, the hold and `bech32_parts` are in place, + and no form allocates. Decode with no human-readable part in the format accepts any (D20's rule + for the stream, the same one-shot, R12). + +- [ ] **Step 1: Write the failing tests:** the format checks, with every valid string of BIP-173 + decoded with `bech32` and of BIP-350 with `bech32m` (each passes the checksum and case checks; + those whose data regroup with at most 4 zero padding bits decode and encode back to their + lower-case form; the others are `invalid_padding`), every invalid string refused with the error + the test's table maps its reason to (the spec's scenario "BIP-173's and BIP-350's lists"); + 32 bytes with `bech32("npub")` give a text of 63 characters starting `npub1` that decodes back + (the spec's scenario); `decode(formats::bech32, text)` gives the + part and the data, with no allocation counted. Words mode (owner decision 27): every valid + segwit address of BIP-173 (version 0) and BIP-350, built from its scriptPubKey as the version + word (`OP_0` is 0, `OP_1` to `OP_16` are 1 to 16) followed by `append_words_from_bytes(program)` + into a `std::vector`, encoded with `formats::bech32(prefix).words()` for version 0 + and `formats::bech32m(prefix).words()` above, gives the address in lower case, and its decode + gives the words back, `bytes_from_words` of all but the first giving the program (the spec's + scenario "Segwit addresses in words mode"); a word of 32 on encode is `invalid_character`; the + Taproot address `bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0` from its + program in words mode, and a different text from the byte 0x01 followed by the program in bytes + mode (the spec's scenario "A version as a byte is another text"). `bytes_from_words`: 8 words + give 5 bytes with no padding; 2 words (2 padding bits, zero) give 1 byte; 3 words (7 padding + bits) are `invalid_padding`; a non-zero padding bit is `invalid_padding`; a value of 32 is + `invalid_character`; an output one byte short is `output_too_small`. + `basic_bech32{}("lnbc").words()` decodes BOLT 11's first example + invoice ("Please make a donation of any amount using payment_hash 0001...0102", the text + copied from BOLT 11's "Examples" section with its source cited) to its words, the first seven + reading 1496314658, the example's timestamp, one-shot and through its stream decoder; the same + text through `formats::bech32("lnbc").words()` is `input_too_long`, its stream having delivered + nothing (the spec's scenario "A Lightning invoice through a larger instance"); + `messages/bech32_maximum_length_too_small`: names `basic_bech32`, + the expected line holding "a bech32 maximum length is at least 8 characters" (the spec's + scenario "A maximum length below the shortest text"). A valid text sent to + `decoder(formats::bech32("bc"))` one character at a time, receiving after each, gives zero bytes + before `flush` and the data after it; with its last character changed, `checksum_mismatch` with + no byte ever delivered (the spec's scenario "The stream decoder holds until the checksum"); + `decoder(basic_bech32{}("lnbc"), capacity<128>)` holds 128 + characters, a 300-character text giving `input_too_long` at `flush`; a text with an invalid + character and a bad checksum, under a human-readable part of 84 characters, gives + `invalid_prefix` by the stream's first call and one-shot (the spec's scenario "A configuration + fault wins"). The fuzz targets `bech32`, `bech32m` and `bech32_words` (over + `formats::bech32.words()`), each re-encoding what decodes with the human-readable part its + `parts_type` decode returned (F8). +- [ ] **Steps 2 to 4** as the pattern. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: bech32 and bech32m as a template over the variant, the maximum length and the data, constant time, the parts and the word helpers, a stream encoder and a decoder that holds until its checksum passes`. Lint step. + +### Task 18: base32 and base32hex + +Model tier: standard. Covers tasks.md 3.4. + +**Files:** create `include/webcpp/codecs/base32.hpp`, `include/webcpp/codecs/detail/formats/base32.hpp`, +`test/base32_test.cpp`, `test/base32_stream_test.cpp`, the lanes' additions (`base32_fuzz.cpp`, +`base32hex_fuzz.cpp`); modify `test/Jamfile`. + +**Interfaces:** `formats::base32_t` (name "base32", RFC 4648 section 6) and `formats::base32hex_t` +(name "base32hex", section 7), each with `formats::padding padding_option = padding::written` +and `operator()(padding)`; `inline constexpr` objects `base32`, `base32hex`. The 5-bit arithmetic +by the same masks as base64's (D12); encode writes upper case, decode takes either (B13); a length +no encoding has (with padding: not a multiple of 8, or a padding run of other than 1, 3, 4 or 6 +characters; without: a remainder of 1, 3 or 6) is `invalid_length`; non-zero trailing bits and +padding against the option `invalid_padding`. + +- [ ] **Step 1: Write the failing tests:** the format checks, with RFC 4648 section 10's base32 + and base32hex vectors, padded and unpadded (the spec's scenario "RFC 4648's vectors"), each + decoding back from lower case; `"MZXW6==="` with padding omitted `invalid_padding`; `"MZXW6YQ"` + unpadded decodes and padded is `invalid_length`; `"MY======"` decodes to "f" and `"MZ======"` + (a non-zero trailing bit) is `invalid_padding`. +- [ ] **Steps 2 to 4** as the pattern. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: base32 and base32hex, constant time, their streams`. Lint step. + +### Task 19: base58, its vectors and a format registered outside codecs + +Model tier: most capable (the secret constant-time conversion beside Bitcoin Core's). Covers +tasks.md 3.5 and 3.8's interoperation test. + +**Files:** create `include/webcpp/codecs/base58.hpp`, `include/webcpp/codecs/detail/formats/base58.hpp`, +`test/base58_test.cpp`, `test/base58_buffered_test.cpp`, `test/interoperation_test.cpp`, +`test/support/base58_checksum.hpp` (the tests' own checksum policy, since codecs has no hash, +owner decision 26: `test::rotate_xor_checksum`, `size` 4, a 32-bit state from 0, for each byte +`state = std::rotl(state, 5) ^ byte`, written big-endian, no branch and no table on the data; and +`test::base58_with_checksum`, of the type `formats::basic_base58<100, formats::bitcoin_alphabet, +test::rotate_xor_checksum>`, the form of hash's follow-up), `test/messages/drain_of_base58/`, +`test/messages/base58_alphabet_not_distinct/`, `test/messages/base58_with_checksum_unseen/` +(F13), the lanes' additions (`base58_fuzz.cpp`, `base58_with_checksum_fuzz.cpp`); modify +`test/Jamfile`, `test/messages/Jamfile`, `test/allocator_test.cpp`, `test/allocator_throw_test.cpp`. +Modify (superproject): `third_party/Jamfile` (the target `bitcoin_base58_vectors`, blake3_vectors' +form: `WEBCPP_TEST_BITCOIN_BASE58_VECTORS`, `[ webcpp.data $(BITCOIN)/src/test/data ]`, +`libs/bitcoin/src/test/data/base58_encode_decode.json`, `@bitcoin-checked-out`, +explicit; its comment: Bitcoin Core's base58 vectors, MIT, read at run time by codecs' tests), +`CODING-GUIDELINES.md` chapter 10's table (a row `bitcoin_base58_vectors`). + +**Interfaces:** + +```cpp +namespace webcpp::codecs::formats { +// An alphabet is a type (owner decision 25); its tables are built at compile time. +template +concept base58_alphabet = std::same_as; + +// A checksum is a policy type (owner decision 26); codecs defines none but no_checksum. +struct no_checksum {}; +template +concept base58_checksum = std::same_as + || (std::same_as + && requires(std::span payload, std::span out) { + { Checksum::compute(payload, out) } noexcept -> std::same_as; // constant time: it runs on secrets + }); + +template +struct basic_base58 { + static_assert(detail::is_base58_alphabet(Alphabet::characters), + "a base58 alphabet is 58 distinct characters"); + using alphabet_type = Alphabet; + using checksum_type = Checksum; + static constexpr std::string_view name = "base58"; + static constexpr std::size_t maximum_bytes = MaximumBytes; // the payload, without the checksum + static constexpr std::size_t checksum_size = detail::base58_checksum_size; // 0 for no_checksum + static constexpr std::size_t maximum_characters = // derived, never a parameter + detail::base58_encoded_length(MaximumBytes + checksum_size); +}; + +struct bitcoin_alphabet { + static constexpr std::string_view characters = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; +}; +struct ripple_alphabet { + static constexpr std::string_view characters = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"; +}; +struct flickr_alphabet { + static constexpr std::string_view characters = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; +}; + +using base58_bitcoin_t = basic_base58<100, bitcoin_alphabet>; +using base58_ripple_t = basic_base58<100, ripple_alphabet>; +using base58_flickr_t = basic_base58<100, flickr_alphabet>; +inline constexpr base58_bitcoin_t base58_bitcoin{}; +inline constexpr base58_ripple_t base58_ripple{}; +inline constexpr base58_flickr_t base58_flickr{}; +inline constexpr base58_bitcoin_t base58{}; // the default: base58_bitcoin +} +// codec>, every instance: +// constant_time = false; constant_time_when_secret = true (B24); no stream_codec. +``` + `detail::base58_encoded_length(n)` is the number of base-58 digits of 256^n - 1, + ceil(n * log(256) / log(58)), computed at compile time in integers: a rational bound of + log(256) / log(58) from below and one from above must give the same ceiling for `n`, or a + `static_assert` stops the build. The leading-zero rule never gives more (k leading zero bytes + write k characters, fewer than their share of the ceiling). Its values: 137 for 100 bytes, 143 + for 104, 350 for 256, 1399 for 1024, 22375 for 16384. + Every operation of every instance works in an in-place scratch sized by the template for the + larger of the two bounds (owner decision 25, F12), so that the sizes are exact, `noexcept` and + allocation-free for each instance: an input longer than `maximum_bytes` or a text longer than + `maximum_characters` is `input_too_long`, checked by its length before any read (then the only + fault reported); a decode whose payload would be longer than `maximum_bytes` is `input_too_long` + too, found after the conversion, its length public (D12), since a text within + `maximum_characters` can decode to more (F12: 137 `1`s give 137 zero bytes, 137 `z`s 101 bytes); + within the bounds the faults follow B23. A decode into a token converts once into the scratch + and gives the token the exact size: it allocates only through the token's `prepare`, never from + its `get_allocator()` (F18). Public: Bitcoin Core's `EncodeBase58` and `DecodeBase58` + (quadratic, early exits). Secret (the core passes the operation's secrecy to the codec through a + `detail::secret_tag` overload of `encode`, `decode`, `encoded_size` and `decoded_size`, ruling + R7): every limb of the scratch's bound for the input's length processed, no early exit, leading + zero bytes and characters counted by a mask scan, the alphabet by `lookup` over the type's + compile-time table and its inverse by masks; the scratch wiped. With a checksum (owner decision + 26): encode writes `Checksum::compute(payload, out)` into the scratch after the payload and + converts both; decode converts, refuses fewer than `checksum_size` bytes with `invalid_length`, + recomputes the checksum of the payload into a local (wiped when secret), compares the two with + `secure::constant_time_equal`, inside the engaged guard in a secret operation, passes the + verdict through `secure::declassify` before the branch that reports `checksum_mismatch`, and + writes the payload alone; `encoded_size` counts the checksum's characters and `decoded_size` + leaves its bytes out. + +- [ ] **Step 1: Write the failing tests:** `base58_test.cpp`: Bitcoin Core's + `base58_encode_decode.json` (read through `WEBCPP_TEST_BITCOIN_BASE58_VECTORS`, test + requirement `/webcpp/third_party//bitcoin_base58_vectors`) holds 21 pairs; its largest + input is 256 bytes (the bytes 0x00 to 0xFF, a 348-character text), the only one past 100 bytes, + the next largest 98. The 20 pairs of at most 100 bytes are encoded and decoded through + `formats::base58`, and all 21 through `formats::basic_base58<256, formats::bitcoin_alphabet>{}`, + public and secret (a `key32`-like secret type of each length the file holds, through + `tokens::secret`), each text and byte string the file's; the 256-byte input and its text through + `formats::base58` are `input_too_long` (the spec's scenario "Bitcoin Core's vectors"). The three + named alphabets on one input through `base58_bitcoin`, `base58_ripple` and `base58_flickr` + (Ripple's and Flickr's texts are Bitcoin's with each character replaced by the character of the + same digit in their alphabet). An alphabet of the test's own, `test::reversed_alphabet` + (Bitcoin's characters reversed), through `formats::basic_base58<100, test::reversed_alphabet>{}`: + a round trip, its text Bitcoin's with each character replaced by the character of the same + digit, `'0'` `invalid_character` (the spec's scenario "An alphabet of the program's own", its + first half); `static_assert(!formats::base58_alphabet)`. `'0'`, `'O'`, `'I'`, `'l'` and + every byte outside the alphabet `invalid_character`. The bounds of each instance (owner decision + 25, F12): `static_assert`s of `maximum_characters`, 137 for `base58`, `base58_ripple` and + `base58_flickr`, 350 for `basic_base58<256, bitcoin_alphabet>`, 1399 for + `basic_base58<1024, bitcoin_alphabet>`, 22375 for `basic_base58<16384, bitcoin_alphabet>` and + 143 for `test::base58_with_checksum`; through `formats::base58`, 100 bytes of `0xFF` round trip + (137 characters), 101 bytes are `input_too_long` from `encode`, `encoded_size` and the buffer + form, and 138 characters, 137 `1`s (137 zero bytes) and 137 `z`s (101 bytes) are + `input_too_long` from `decode`; through `formats::basic_base58<1024, formats::bitcoin_alphabet>{}`, + the same 101 bytes round trip (the spec's scenario "The default's bound and a larger + instance"), 1024 bytes of `0xFF` round trip (1399 characters), and 1025 bytes, 1400 characters, + 1399 `1`s and 1399 `z`s (1025 bytes) are `input_too_long`; the size functions and the buffer + forms of `basic_base58<16384, bitcoin_alphabet>` are `noexcept` (`static_assert`s; its stack + scratch is not run on the wasm lanes). Review Focus 1 to 3 (no in-place decode: the page says + so). `messages/base58_alphabet_not_distinct`: names `formats::basic_base58<100, repeated>`, + where `repeated` is Bitcoin's alphabet with `z` replaced by `1`; the expected line holds "a + base58 alphabet is 58 distinct characters" (the spec's scenario "An alphabet of the program's + own", its second half; a message case, as F2 rules for every refusal). + `base58_buffered_test.cpp`: 40 bytes into `buffered(encoder(formats::base58), capacity<64>)` in + chunks of 7 give nothing before `flush` and the one-shot text after it, no allocation (the + spec's scenario "Accumulating: base58 over byte chunks"); every vector through + `buffered(encoder(formats::basic_base58<256, formats::bitcoin_alphabet>{}), capacity<1024>)` + (the spec's scenario "base58 streams only through buffered", its second half); + `messages/drain_of_base58`: `drain(encoder(formats::base58), sink)`, the message names + `codecs::buffered` (its first half). `allocator_test.cpp`: `buffered(encoder(base58), pmr)` + and a base58 decode into a `std::pmr::vector` token over the arena (the token's own allocation, + no scratch), the global counter none; `over{formats::hex, formats::base58, pmr}`; + `allocator_throw_test.cpp`: a base58 decode of a secret text into a `tokens::secret(throwing)` + token and `over`'s heap intermediate with base58, the exception reaching the test and every + buffer deallocated zero. `interoperation_test.cpp`, one translation unit (F13): includes + `"support/base58_checksum.hpp"`; `static_assert(formats::base58_checksum)`, + and `!formats::base58_checksum` of a type whose `compute` is not `noexcept` and of one with no + `size`; `encode(test::base58_with_checksum, payload)` equals + `encode(formats::basic_base58<104, formats::bitcoin_alphabet>{}, payload followed by its checksum)` + and decodes back to the payload alone; an empty payload encodes its checksum alone and decodes + back to nothing; a changed character is `checksum_mismatch`; `"2g"` (one byte) is + `invalid_length`; 101 bytes, 144 characters and 143 `z`s (105 bytes) are `input_too_long`; a + `secure::secret<32>` payload encoded and decoded through `tokens::secret` as secret operations, + the seam recording the guard in each, and a changed character `checksum_mismatch` in the secret + decode (the spec's scenarios "A checksum as the third parameter" and "A base58 checksum of + hash's kind"). `messages/base58_with_checksum_unseen` (F13): a source that includes + `` alone and names `codecs::test::base58_with_checksum`, the expected + line "no member named 'base58_with_checksum' in namespace 'webcpp::codecs::test'" (the + `forgotten_header` form; the spec's scenario "A base58 checksum of hash's kind", its last + clause). + The constant-time lane: base58's secret encode and decode of a fixed length in `paths.hpp`, and + `test::base58_with_checksum`'s secret decode (its checksum compared inside the guard, the + verdict declassified), and its dudect case (secret decode of a fixed length, two classes). The + fuzz targets `base58` (over `formats::base58`) and `base58_with_checksum` (over the test's + instance), each stream form `buffered(decoder(format), capacity)` + (F8), inputs past the bounds included. +- [ ] **Steps 2 to 4** as the pattern, and `python3 tools/test/third_party_test.py`. Expected: + pass. +- [ ] **Step 5: Commit, lint.** codecs: `codecs: base58 as a template over its bound, alphabet and checksum, Bitcoin Core's algorithm and a constant-time one for secrets, its vectors, and a checksum registered outside codecs`; superproject: `third_party: Bitcoin Core's base58 vectors, test data of codecs`. Lint step. + +### Task 20: percent over Boost.URL + +Model tier: standard. Covers tasks.md 3.6. + +**Files:** create `include/webcpp/codecs/percent.hpp` (all of percent, no `detail/formats/` file, +so that the first headers-alone call's glob stays free of Boost.URL), `test/percent_test.cpp`, `test/percent_stream_test.cpp`, `test/fuzz/percent_fuzz.cpp` (requirement +`/webcpp/codecs//percent`); modify `test/Jamfile` (the percent tests name +`/webcpp/codecs//percent`; `webcpp.headers-alone codecs : ../include : codecs/percent.hpp : /webcpp/codecs//percent ;`), `test/allocation_test.cpp` (a second program, +`allocation_percent_test.cpp`, with the percent target, so the core's allocation test does not +link Boost.URL). + +**Interfaces:** + +```cpp +namespace webcpp::codecs::formats { +struct percent_t { + static constexpr std::string_view name = "percent"; + boost::urls::grammar::lut_chars char_set = boost::urls::unreserved_chars; + boost::urls::encoding_opts options{}; + template // any Boost.URL CharSet, held as lut_chars (ruling R9) + [[nodiscard]] constexpr percent_t operator()(CharSet const& chosen, + boost::urls::encoding_opts options = {}) const noexcept; +}; +inline constexpr percent_t percent{}; +} +// codec: constant_time = false; encoded_size and encode call +// boost::urls::encoded_size and boost::urls::encode (after the size check); decoded_size and decode +// call boost::urls::decoded_size and boost::urls::decode; bad_pct_hexdig -> invalid_character, +// incomplete_encoding -> invalid_length, any other Boost.URL error -> invalid_character (B20). +// stream_codec (D20's table): the same CharSet and options character by character. +``` + +- [ ] **Step 1: Write the failing tests:** the format checks but the constant-time lane (percent + is not constant time), with: 1000 random byte strings encoded and decoded with + `percent(unreserved_chars)`, `percent(pchars)` and `percent(pchars, encoding_opts(true))`, + every text and byte string equal to Boost.URL's own functions' (the spec's scenario + "Boost.URL as the oracle"), and every `CharSet` Boost.URL's `rfc/` headers name; the examples of + Boost.URL's documentation of `encode` and `decode`; `"%4"` `invalid_length`, `"%4g"` + `invalid_character`; the stream forms on every chunking equal to Boost.URL's one-shot + functions. A program that includes `` and names `/webcpp/codecs//codecs` + builds no Boost.URL (Task 23's user Jamfile fixture checks it, the spec's scenario). +- [ ] **Steps 2 to 4** as the pattern (no constant-time block). Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: percent, an adapter over Boost.URL's percent-encoding with any CharSet, and its stream`. Lint step. + +### Task 21: armor (RFC 7468) + +Model tier: most capable (a structure that is public around a payload that is not). Covers +tasks.md 3.7. Ends with MSVC checkpoint 3. + +**Files:** create `include/webcpp/codecs/armor.hpp`, `include/webcpp/codecs/detail/formats/armor.hpp`, +`test/armor_test.cpp`, `test/armor_stream_test.cpp`, `test/armor_openssl_test.cpp`, +`test/data/armor/` (RFC 7468's examples, cited, with their DER; and the PEM files the OpenSSL +oracle wrote, each with the `openssl` command line in a comment file, ruling R8), the lanes' +additions (`armor_fuzz.cpp`); modify `test/Jamfile`. + +**Interfaces:** + +```cpp +namespace webcpp::codecs::formats { +struct armor_t { + static constexpr std::string_view name = "armor"; + detail::bounded_label<64> label; + [[nodiscard]] constexpr armor_t operator()(std::string_view label) const noexcept; +}; +inline constexpr armor_t armor{}; +struct armor_parts { text<64> label; std::vector data; }; +} +// value_codec: decode only. stream_codec: D20's table, +// label() after a successful flush. Its payload through detail::base64_arithmetic's +// symbol_of and six_bits_of. +``` + The configuration's faults, first (B23): a label over 64 characters or outside RFC 7468's + `label` grammar, or none on encode: `invalid_prefix`. Public (B45): line endings, the final + line ending, the boundaries and their positions, the label; the decoder may branch on them. + `over` works for any bytes format. + +- [ ] **Step 1: Write the failing tests:** the format checks (the constant-time block covers the + payload only, the structure being public), with: each RFC 7468 example decoded with `armor` + configured with its label gives its DER, and the certificate example with `armor("PUBLIC KEY")` + is `invalid_prefix` (the spec's scenario); CRLF lines, no final line ending, a 65-character + line and a short line before the last (`invalid_length`), explanatory text before the BEGIN + line, an RFC 1421 header, a space in a line, `-----END PRIVATE KEY-----` under a BEGIN of + `PUBLIC KEY` (`invalid_prefix`); `decode(formats::armor, text)` gives + the label and the data; encode with no label is `invalid_prefix`; + `over{formats::armor("PUBLIC KEY"), formats::hex}` round trips; a DER streamed through + `encoder(formats::armor("PUBLIC KEY"))` in chunks of 5 bytes equals the one-shot armor, and + through `decoder(formats::armor)` gives the DER and `label() == "PUBLIC KEY"` (the spec's + scenario "Armor as a stream"). `armor_openssl_test.cpp` (requirement + `/webcpp/third_party//openssl`, native, `msvc:no`, ruling R8): a P-256 + public key's SPKI DER and three other DERs (1, 48 and 1000 bytes) encoded with `armor` equal, byte + for byte, `PEM_write_bio`'s output for the same DER and label, and decode back (the spec's + scenario "OpenSSL's PEM"); `armor_test.cpp` checks the PEM files of `test/data/armor/` on every + lane. +- [ ] **Steps 2 to 4** as the pattern. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: armor, RFC 7468's strict textual encoding, constant time over its payload, its parts and its stream, OpenSSL as its oracle`. Lint step. +- [ ] **Step 6: MSVC checkpoint 3.** x64 debug on 14.3 and 14.5 over `libs/codecs/test` + (`/webcpp//boost_url` built for percent's tests). Expected: `new failures:` empty. + +--- + +### Task 22: The documentation and the examples + +Model tier: standard. Covers tasks.md 5.1. + +**Files:** +- Create: `doc/overview.adoc`, `doc/formats.adoc` (one section per format: what it is, an + example, its pitfalls: base58's quadratic cost, its bound (100 bytes for `formats::base58`, a + larger instance named by `basic_base58`, its scratch in place, on the stack), an + alphabet of a program's own as a type, its checksum parameter (webcpp::hash's + `base58_with_checksum` is what Bitcoin calls Base58Check; a checksum's `compute` must be + constant time) and its constant time only when secret; bech32's maximum length as a template + parameter (a larger instance for Lightning) and its hold, its bytes and words modes (a word is a + 5-bit value, not a machine word; a segwit version is a word, never a byte, the pitfall shown by + BIP-350's Taproot address), and what it leaves to a future webcpp::bitcoin (versions, program + sizes, networks' prefixes, Lightning's fields); percent's `CharSet` and its own target; the armor's + strict form; which formats decode in place), `doc/tokens.adoc` (with Boost.URL's), `doc/results.adoc` + (default and fixed results, typed decode), `doc/secrecy.adoc`, `doc/composition.adoc` (`over`), + `doc/streams.adoc` (the two concepts, the flow, the borrowed input first, `pipe`, `drain`, + `each`, `buffered`, which formats stream natively, errors after `flush` and discarding what was + received), `doc/allocators.adoc` (`codecs::pmr`, tokens with an allocator, what allocates, what + happens when an allocator throws), `doc/writing_a_format.adoc` (`codec`, `value_codec`, + `is_secret`, `fixed_byte_storage`, `stream_codec`), `doc/writing_a_transformer.adoc` (the toy + frames as the example), included by `codecs.adoc` +- Create: `example/{digest_hex,key_base64,nostr_bech32,pem,stream_file,toy_frames,percent_segment,base58_address}.cpp`, + each with `.expected`, each `webcpp.example` in `example/Jamfile` (`percent_segment` with + `/webcpp/codecs//percent`), quoted in the pages by tags +- Modify: `doc/changelog.adoc` (Unreleased: one line per public header and one for the stream + contract, AGENTS.md chapter 5's form), `README.md` (no longer "being built"), `AGENTS.md` + +- [ ] **Step 1: Write the failing examples:** the `.expected` files; `B2 toolset=clang libs/codecs/example` + fails (missing programs). +- [ ] **Step 2: Write the examples and the pages; run** the examples on the five local lanes and + `B2 libs/codecs/doc doc`. Expected: pass; the page has every section of the spec's requirement + "Documentation: the page", the reference strict, the index entry. +- [ ] **Step 3: Commit, lint.** `codecs: the page, one section per format, tokens, secrecy, streams, allocators and writing a format or a transformer, every example run`. Lint step. + +--- + +### Task 23: The superproject + +Model tier: standard. Every place the superproject names a library, as secure's Task 12 found: + +| File | Change | Task | +| --- | --- | --- | +| `.gitmodules`, `libs/codecs` | the submodule | preflight | +| `AGENTS.md` | the libraries table gains codecs' row ("one contract for converting bytes and values to text and back, and any data through streams; seven formats; webcpp's own" / native, wasip2, wasip3, emscripten; its own lanes `constant-time` and `fuzz` / a submodule at `libs/codecs`; depends on config and secure, percent also on Boost.URL); the layout's list of `libs//` gains codecs | 23 | +| `doc/releases/0.1.0.adoc` (or the version in preparation) | New Libraries: codecs, one sentence; Tools and build: `codecs_jamfiles_test.py`, `codecs_dudect_judge_test.py`, the two own lanes in `matrix.py`, `bitcoin_base58_vectors` | 23 | +| `CODING-GUIDELINES.md` | chapter 17: "### codecs (bytes and values to text and back, and the conversion contract; own; accepted 2026-11-26, built, not merged)" with its decisions (owner decisions 1 to 27, D1 to D22, B1 to B47 with this plan's rulings) each with its `Source:`; chapter 1's list of tools tests gains codecs' | 23 | +| `tools/ci/matrix.py`, `tools/ci/matrix_test.py`, `.github/workflows/library.yml` | the two own lanes, packages, judge | 14, 15 | +| `third_party/Jamfile`, chapter 10's table | `bitcoin_base58_vectors` | 19 | +| `tools/test/codecs_jamfiles_test.py`, `tools/test/fixtures/codecs_jamfiles/` | new (below) | 23 | +| `tools/test/codecs_dudect_judge_test.py` | new | 14 | + +**Files (superproject):** `tools/test/codecs_jamfiles_test.py` (secure_jamfiles_test.py's form, +libraries `('config', 'secure', 'codecs')`); fixtures `program/` (`exe app : app.cpp /webcpp/codecs//codecs ;`, +`app.cpp` includes ``, encodes and decodes a digest, prints the hex and +`round trip`; outcome: targets native wasip2 wasip3 emscripten, build succeeds, run prints both +lines, `not-contains: boost_url`: the spec's scenario "A program that encodes hex builds no +compiled library"), `program_no_exceptions/` (the same with `off`), +`percent/` (`exe app : app.cpp /webcpp/codecs//percent ;`, a path segment encoded with `pchars`; +every target; the spec's scenario "percent needs its own target"). + +- [ ] **Step 1: Write** the fixtures and the test; `python3 tools/test/codecs_jamfiles_test.py` + passes. +- [ ] **Step 2: Write** the table's changes for Task 23. +- [ ] **Step 3: The gitlink.** `git add libs/codecs` (nothing else) and commit + `libs/codecs: the gitlink at codecs built ()`. +- [ ] **Step 4: Run.** `B2 doc`, `python3 tools/test/doc_test.py`, `python3 tools/release/release.py`'s + check of the notes if it runs offline. Expected: pass. +- [ ] **Step 5: Commit, lint.** `build: register codecs, a library of the superproject`, + `tools: codecs_jamfiles_test, a user's Jamfile of webcpp::codecs on every target`, + `guidelines: codecs is accepted and built, in chapter 17`. Lint step. + +--- + +### Task 24: The delivery (a checklist the controller runs) + +Model tier: the controller; the final review by the most capable model. + +- [ ] The superproject: `git fetch origin`; if `origin/main` moved, merge it (never rebase), + re-run the tasks' lanes it touches, commit. +- [ ] Commit everything; `$W/codecs/refresh-tree.sh`. +- [ ] Lanes, each from scratch, one build directory each, through heavy.sh: + +```bash +B2="env -u CPATH -u CPLUS_INCLUDE_PATH -u C_INCLUDE_PATH b2 --user-config=.local/user-config.jam" +H="$W/heavy.sh codecs"; L=codecs +$H $B2 -a --dump-tests --build-dir=bin/lane-clang --out-xml=clang.$L.xml toolset=clang libs/$L/test libs/$L/example +$H $B2 -a --dump-tests --build-dir=bin/lane-gcc-15 --out-xml=gcc-15.$L.xml toolset=gcc-15 libs/$L/test libs/$L/example +$H $B2 -a --dump-tests --build-dir=bin/lane-wasip2 --out-xml=wasip2.$L.xml toolset=clang-wasip2 testing.launcher=tools/boost/asio-wasip2/run.sh libs/$L/test libs/$L/example +$H $B2 -a --dump-tests --build-dir=bin/lane-wasip3 --out-xml=wasip3.$L.xml toolset=clang-wasip3 testing.launcher=tools/boost/asio-wasip3/run.sh libs/$L/test libs/$L/example +$H $B2 -a --dump-tests --build-dir=bin/lane-emscripten --out-xml=emscripten.$L.xml toolset=emscripten libs/$L/test libs/$L/example +``` + (wasip2 and wasip3 with `WEBCPP_WASIP2_TEST_TIMEOUT=1800 WEBCPP_WASIP3_TEST_TIMEOUT=1800`); + every test with its `_no_exceptions` twin. +- [ ] The own lanes: `$H $W/codecs/ct-run/linux.sh codecs constant-time`, + `$H $W/codecs/ct-run/linux.sh codecs fuzz`; natively on this Mac the dudect programs. +- [ ] MSVC on the VM, the essential set: `run-lane.sh 14.3` and `14.5`, x64 debug, over + `libs/codecs/test libs/codecs/example`; `14.5 --arch arm64` debug over the timing and secret + tests (`//timing //secret_operation //secret_stream`) and + `libs/codecs/test/constant_time//dudect` (its Jamfile builds it at release). Each + `summarize.sh`: `new failures:` empty. +- [ ] Docs and tools: `$B2 doc`, every `tools/test/*_test.py` the stream touched + (`codecs_jamfiles_test.py`, `codecs_dudect_judge_test.py`, `third_party_test.py`, + `doc_test.py`), `python3 tools/ci/matrix_test.py`. +- [ ] The report: `python3 tools/report/report.py` over the XML files, every cell green. +- [ ] Lints: macOS full `$H tools/lint/lint.sh --clang-format .local/wasi-sdk/bin/clang-format --clang-tidy .local/wasi-sdk/bin/clang-tidy`; + Linux full `$H $W/linux-lint/run.sh --full $W/codecs/lane-tree`. Clean. +- [ ] The final whole-branch review (most capable model) over codecs and the superproject; fixes + in their own commits; lanes a fix touches re-run. +- [ ] This change in proposals: `tasks.md`'s items ticked, `.openspec.yaml` status `implementing` + and `implementation: https://github.com/webcpporg/codecs`, `design.md` and `spec.md` true to + the build (this plan's rulings R3 and R7 written into D11, D22 and the requirements they touch; + R6 needs nothing more, owner decisions 25 and 26 having written base58's bound into D13, D22 + and the spec), `reference/STATUS.md` dated; `python3 tools/proposals.py readme` + and `check` (0 problems). +- [ ] Pull requests, in merge order: codecs (its first commit pushed as `main` of the empty + repository, then `codecs/genesis` onto it, merged with a merge commit), then the superproject + (gitlink at codecs' merged `main`, `tools/`, `third_party/`, guidelines, notes), then the + proposals; merged by the owner's standing instruction or by the owner; no CI gates them; one + CI at the end on the superproject's `main`. + +## Rulings (the planner's) + +- **R1:** the core is one public header, ``, split into internal parts under + `include/webcpp/codecs/detail/core/`, whose public names are documented in `webcpp::codecs`; a + program never includes a part. This keeps D1's file list (core, config, seven formats, detail) + and chapter 3's one-responsibility files; `meta/include-boundaries.json` enforces that the core + includes no format and no Boost.URL. +- **R2:** a refusal's `static_assert` names the types through its requirement + (`detail::converts`, `detail::compatible_elements`): C++20's message + is a literal and cannot embed `F::name`, and clang's "static assertion failed due to + requirement '...'" line, which `webcpp.compile-diagnostic` matches, prints the format's or the + elements' type in full. The core also declares the empty namespace `codecs::formats`, so that a + forgotten header is "no member named 'base64' in namespace 'webcpp::codecs::formats'". +- **R3:** `over`'s exact `encoded_size` and `decoded_size` run the inner link into the + intermediate; with a heap intermediate they allocate and are not `noexcept` (D22's list gains + them), with a static bound they are `noexcept` and allocate nothing. +- **R4:** the spec's "the count of engaged guards returns to zero after each call" is checked as + `secure::dit_is_set()` reading clear after each call on a covered CPU (the guard's only + observable exit), and the guards' entry by the seam recorder (`timing_entries`), since secure's + seam reports entries, not exits. +- **R5:** the fuzz lane is new to webcpp: libFuzzer (clang 18 on Linux, `-fsanitize=fuzzer,address,undefined`, + a release build, 60 seconds a target, a fixed seed) driven by `fuzz.mjs`, and every target also + built as a replay program on every lane over its corpus and 4096 fixed pseudo-random inputs, so + that the assertions run on every lane and a target that does not compile is seen at once. The + no-heap assertion uses ASan's allocation hooks under libFuzzer and the counting `operator new` + in the replay. +- **R6 (superseded by owner decisions 25 and 26, 2026-11-26; owner question Q1, answered):** the + ruling was a fixed ceiling, `maximum_bytes = 1024` and `maximum_characters = 1400`, changing + B15. Its reason stands: without a bound the approved contract cannot hold for base58 + (`codec::encoded_size` and `decoded_size` must be exact, `noexcept` and allocation-free, D3 + and the spec, and base58's exact size exists only after a quadratic conversion that needs a + working number as long as the input), and a bound caps the quadratic cost a text from outside + can force. The owner put the bound in the type: base58 is + `basic_base58`, `maximum_characters` derived + from `MaximumBytes` and the checksum's size, the alphabet a type satisfying `base58_alphabet`, + the checksum a type satisfying `base58_checksum`; `formats::base58` is `base58_bitcoin`, 100 + bytes of Bitcoin's alphabet, and a caller who needs more names a larger instance. Every + instance works in an in-place scratch sized by its template; past either bound every operation + is `input_too_long`, and F12 adds the decoded payload's bound. base58's decode into a token + allocates only through the token's own `prepare`, never a scratch: D13 and D22 say so (owner + decision 25), and the tests keep the arena row (the token's allocation goes to the arena). +- **R7:** a codec whose arithmetic differs when the operation is secret (base58, every instance of + `basic_base58`) offers overloads + of its functions taking `detail::secret_tag` first; the core calls them in a secret operation + when they exist. It is the one extension of D3's six functions, internal to the core and the + format, and invisible to a format that does not need it. +- **R8:** test data follows chapter 10. Bitcoin Core's `base58_encode_decode.json` is read at run + time from the superproject's existing submodule `third_party/libs/bitcoin` through a new + test-data target, `bitcoin_base58_vectors` (blake3_vectors' form), rather than copied into + `test/data/` as D15 said. BIP-173's and BIP-350's vectors, RFC 4648's and RFC 7468's examples are + written in the tests with their source cited, as webcpp's tests write RFC vectors (the BIPs + hold them in prose, not in a file). OpenSSL's `PEM_write_bio` runs as the armor's oracle + natively on clang and gcc (`/webcpp/third_party//openssl`, a test-only target; not on MSVC, + where the essential set does not build OpenSSL for codecs), and the PEM files it wrote are kept + in `test/data/armor/`, so that every lane compares against them. +- **R9:** `percent_t` holds Boost.URL's `lut_chars` and `percent(char_set, options)` converts any + `CharSet` to it (Boost.URL's own constructor from a predicate): one format type, identical + membership, `inline constexpr` objects. +- **R10:** the default token is the type `tokens::automatic` (so that `token = {}` names it) and + `tokens::fixed` a class template (the spec writes `tokens::fixed<54>{}`); `return_string` and + `secret` are objects callable with an allocator (B40); `append_to` and `assign_to` functions. +- **R11:** tasks.md 1.2's chapter 17 entry moves to Task 23, with every other superproject + registration, so that it records the library as built. +- **R12:** a bech32 or armor format with no human-readable part or label (a default-constructed + `basic_bech32`, owner decision 27) decodes any, one-shot as the stream (D20 says so for the stream; the one-shot form follows, since every stream equals + its one-shot form). +- **R13:** the order of the formats: hex first, then the constant-time and fuzz lanes, so that + every later format is checked by both lanes in its own task; base64 before bech32 and armor + (armor reuses its arithmetic); tasks.md's 2.7, 2.9, 2.13 and 3.8 are folded into the tasks + whose forms they test (2.7's allocator and allocation tests grow in Tasks 2 to 11; 2.9's toy + types in Task 8, its pipelines in Tasks 10 and 13; 2.13 in Task 12; 3.8's allocation rows in + each format task and its interoperation test in Task 19). + +### Where the build departed (2026-11-30) + +Each line names a place where the build differs from this plan's text; the ruling behind it, with +its cost if wrong, is in `STATUS.md` (beside this file), section "Rulings during implementation", +and `design.md` and the spec carry the change. + +- **R2:** as ruled; the message cases match the requirement line, and a compile-fail twin of each is built off clang (F19). +- **R3:** widened by F17: the core's buffer forms over a heap `over` allocate and are not `noexcept` too. +- **R7:** extended to value codecs (Task 7), and joined by two optional hooks of D3, `configuration_fault` (Task 11) and `encode_fault` (Task 24), with one size sentinel rule (Task 24). +- **Tasks 3 to 7, the two-word rule and `user_globals` (F15):** never applied, by the owner's ruling of 2026-11-26. +- **Task 4, `get_allocator`:** no token allocator hook (F18), under owner decision 25. +- **Task 6, `assign_to`:** a scratch first, in place up to 4096 elements, by the owner's ruling of 2026-11-26; a secret operation into an explicit token returns the token's type. +- **Task 7, the inputs of a codec:** a static input reaches a codec as a bounded view that converts to D3's span types. +- **Task 13, include boundary 1:** narrowed so that `detail/formats/` headers include one another. +- **Task 14, `dudect_planted`:** an early-exit hex validation, not the table-indexed hex, which memcheck and MemorySanitizer keep. +- **Task 15, the fuzz split:** from a seed prefix the fuzzer controls, with a checking `std::pmr` resource for `over`. +- **Task 16, base64's padded decoder:** holds a group's last places until the next character or `flush`; the padding's layout is never declassified per group. +- **Task 18, base32's runs of `=`:** `invalid_padding`, not `invalid_length`, at a valid length; `maximum_hold` added to the core for bech32's hold. +- **Task 18, random chunkings:** every chunking for the first 40 random inputs, random chunkings beyond. +- **Task 19, base58's token decode:** converts twice (`decoded_size`, then `decode`), not once; its bound faults come before the lowest-value rule. +- **Task 21, the armor's errors:** structure first (boundaries, then lines), then base64's by the lowest value. +- **Tasks 21 to 24, the fix rounds:** verified scoped by the owner's ruling of 2026-11-30; full lanes on the final head. + +## Owner's questions + +- **Q1 (R6), answered by the owner on 2026-11-26 (owner decisions 25 and 26):** the question was + base58 with a ceiling of 1024 bytes and 1400 characters, past which it is `input_too_long`, + instead of no ceiling (B15) and a scratch from the token's allocator (D13, D22, owner decision + 23's "base58's decode into a token"). The answer: base58 is a template over its bound, its + alphabet and its checksum, `basic_base58`, + 100 bytes for `formats::base58`, its scratch in place, `input_too_long` past its bound. The + design and the spec say so already; Task 19 builds it. + +## Follow-ups (not tasks of this change) + +Each is a change of its own library, written after codecs is accepted and merged (proposal, +"Other proposals"): +- `libraries/trystero`: `protocol/text.hpp`'s `to_hex`, `from_hex`, `base64_encode` and + `base64_decode` replaced by codecs' hex and base64. +- `libraries/document`: its `base64` and `base64url` byte policies over codecs' formats. +- `libraries/hash`: `hash::checksums::double_sha256`, a `codecs::formats::base58_checksum` (4 + bytes, the first four of SHA-256 applied twice), and `hash::formats::base58_with_checksum`, + `codecs::formats::basic_base58<100, codecs::formats::bitcoin_alphabet, hash::checksums::double_sha256>`, + what Bitcoin calls Base58Check (owner decision 26), in a header of hash's that its change names; + hash then depends on codecs, never the reverse. +- `libraries/crypto`: its approved `formats` change revised onto codecs: key formats through + `value_codec` in each curve's formats header, PEM as `over`, `crypto::encode` and + `crypto::decode` removed. diff --git a/libraries/codecs/openspec/changes/genesis/specs/codecs/spec.md b/libraries/codecs/openspec/changes/genesis/specs/codecs/spec.md new file mode 100644 index 0000000..89110f4 --- /dev/null +++ b/libraries/codecs/openspec/changes/genesis/specs/codecs/spec.md @@ -0,0 +1,370 @@ +## ADDED Requirements + +### Requirement: Library: header-only targets, names and headers +The library SHALL be header-only C++20 in namespace `webcpp::codecs` (with `webcpp::codecs::formats`, `webcpp::codecs::tokens` and `webcpp::codecs::detail`), with public headers under `` and ``, macros prefixed `WEBCPP_CODECS_`, include guards `WEBCPP_CODECS__HPP` and the error category `webcpp.codecs`. Every public header MUST include `` first, which includes `` first and defines `WEBCPP_CODECS_NO_EXCEPTIONS` exactly when `WEBCPP_HAS_EXCEPTIONS` is not defined or a developer defines it. `build.jam` MUST declare the target `/webcpp/codecs//codecs` (the headers, Boost's headers, `/webcpp/config//config` and `/webcpp/secure//secure`) and the target `/webcpp/codecs//percent` (`codecs` and `/webcpp//boost_url`). Errors of the data and of the configuration SHALL be values (`result` with `codecs::error`) in every build, and the library SHALL throw nothing of its own; with exceptions available, an allocator's exception MUST propagate unchanged out of the functions that allocate, which MUST NOT be `noexcept`, and every other function MUST be `noexcept` (conditionally on the code of a part, a transformer or a format copy it runs, where it runs one); the library MUST compile and work without exceptions, an allocator's failure then following the build's handler with no handling added by codecs. codecs' headers MUST read results with `unsafe_value()`; a program that reads codecs' results through `value()`, `operator*` or `operator->` with exceptions off links `/webcpp//throw_exception`, which the page MUST say. Every header MUST build with `` included before or after it. + +#### Scenario: A program that encodes hex builds no compiled library +- **WHEN** a Jamfile reads `exe app : app.cpp /webcpp/codecs//codecs ;` and `app.cpp` includes `` and encodes and decodes a digest +- **THEN** it builds and runs on native, wasip2, wasip3 and Emscripten, with exceptions on and off, and Boost.URL is not built + +#### Scenario: percent needs its own target +- **WHEN** a program includes `` and names `/webcpp/codecs//percent` +- **THEN** it builds and links Boost.URL as webcpp::lexical does, on every target + +### Requirement: Core: the core header depends on nothing and registers no format +`` SHALL declare the contract (`codec`, `value_codec`, `stream_codec`, `is_secret`, `fixed_byte_storage`, the concepts, the sizes, the buffer, token and typed forms, the tokens, `text`, `bytes`, the secret result types and their `codecs::pmr` aliases, `error`, `over`, the transformer concepts `one_shot_transformer` and `stream_transformer`, `flow`, `step`, `pipe`, `drain`, `buffered`, `encoder`, `decoder`, `capacity` and `secret_operation`) and include no format header, no other webcpp library's header but config's and webcpp::secure's, and no compiled library's header. A format SHALL be reachable only through its own header, so that a program that names `codecs::formats::hex` without including `` does not compile because the name is undeclared. This is the library's recorded departure from chapter 3's convenience header, by the owner's decision. + +#### Scenario: A forgotten format header +- **WHEN** a translation unit includes only `` and calls `codecs::encode(codecs::formats::base64, bytes)` +- **THEN** compilation stops at the undeclared name `base64` + +### Requirement: Core: errors are values +Every function that can fail SHALL return `boost::system::result`. The enumeration `codecs::error` MUST be a `boost::system` error code enumeration with the fixed values `invalid_character = 1`, `invalid_length = 2`, `invalid_padding = 3`, `checksum_mismatch = 4`, `invalid_prefix = 5`, `mixed_case = 6`, `output_too_small = 7` and `input_too_long = 8`, never reused, in a category named `webcpp.codecs` with a fixed identity and no mutable state, each value with a message; an input with several faults of its data MUST report the one with the lowest value, and a fault of the format's configuration MUST be checked first and win over every data error, a fault of the format's encode (`encode_fault`) coming next, before the size check. Three orders stand outside the lowest-value rule, each because what is checked first is public: base58's bound faults come first (an input or a text past its bound is the only fault reported, and a decoded payload past the bound is reported after the text's characters and length and before its checksum); the armor's structure comes first (its boundaries, `invalid_prefix`, then its lines, `invalid_length`, then base64's faults of the payload by the lowest value); and `over`'s decode reports the outer link's error before the inner link's. A value codec MAY return an error code of its own library's category. + +#### Scenario: Every value has its message +- **WHEN** a test makes the `error_code` of each value and reads `message()` and `category().name()` +- **THEN** each message is non-empty and distinct and the name is `webcpp.codecs`, with exceptions on and off + +### Requirement: Contract: codec for bytes and text +`codecs::codec` SHALL be declared and not defined by the core; a format header MUST specialize it for its format's type with `constant_time`, the constexpr bounds `max_encoded_size(std::size_t)` and `max_decoded_size(std::size_t)` that hold for every option of the format, `encoded_size(format, input)` (exact), `decoded_size(format, text)` (exact, the whole text checked), `encode(format, input, std::span)` and `decode(format, text, std::span)`, each `noexcept`, each taking D3's parameter types (`std::span`, `std::string_view`, `std::span`, `std::span`) and never a deduced one; the core MAY pass an input of static size as a view that converts to them implicitly and `noexcept`. Every public operation of the core MUST be written over these functions alone. A codec MAY add three kinds of optional function, each of another signature stopping the build: overloads of `encoded_size`, `decoded_size`, `encode` or `decode` taking `detail::secret_tag` first, which the core MUST call in a secret operation (their result types the same as the functions without the tag); `static constexpr std::optional configuration_fault(format) noexcept`, which the core MUST call first in every form, before any size check and any data, a stream transformer reporting its fault from its first call and every call after, `reset` included; and `static constexpr std::optional encode_fault(format, std::span) noexcept`, which the core MUST call in every encode form after `configuration_fault`, before its own size check and before any token is prepared or any result made. The bounds MUST saturate at `SIZE_MAX`, an input whose bound saturates MUST be refused with `input_too_long` before it is read, and a size with no error channel (the codec's `encoded_size`, `codecs::encoded_size`, a transformer's `output_size`) MUST be `SIZE_MAX` for an input every encode refuses for its size and 0 for one refused for a fault of the configuration or of the encode. + +#### Scenario: A format of the test's own +- **WHEN** a test specializes `codec` for a format type of its own that writes each byte as two letters `a` to `p` +- **THEN** `encode`, `decode`, the sizes, every token, the default results and `over` work with it as with `formats::hex` + +#### Scenario: An encode the format refuses prepares no token +- **WHEN** 3 bytes are encoded with `formats::bech32` (no human-readable part) and 60 bytes with `formats::bech32("bc")`, into Boost.URL's `assign_to` and `append_to`, codecs' tokens and a token of the program's own +- **THEN** the first is `invalid_prefix` and the second `input_too_long`, whatever the input's size, no token is prepared and every string reads as before; `encoded_size` gives 0 for the first and `SIZE_MAX` for the second + +### Requirement: Contract: value_codec for typed values +`codecs::value_codec` SHALL be declared and not defined by the core; a library MUST be able to specialize it for a format and a type it owns with `output` (`output_kind::bytes` or `output_kind::text`), optionally `secret` and a static `max_encoded_size`, `encoded_size(format, value)`, `encode(format, value, output_span)` and `decode(format, input) -> result`, encoding only, decoding only, or both, and MAY add overloads of `encoded_size`, `encode` and `decode` taking `detail::secret_tag` first, which the core MUST call in a secret operation, `over` included. Its errors MUST reach the caller unchanged. + +#### Scenario: A typed value round-trips +- **WHEN** a test specializes `value_codec` for a format of its own and a type holding a 16-bit number written as two big-endian bytes, then calls `codecs::encode(format, value)` and `codecs::decode(format, bytes)` +- **THEN** the encoding is `bytes<2>` (the value codec states `max_encoded_size = 2`) and the decode gives the value back + +### Requirement: Contract: concepts and the compile-time refusal +The concepts `codecs::format`, `codecs::encodable` and `codecs::decodable` SHALL hold as follows: `format` when `F` is copyable with a `static constexpr` `name` that converts to `std::string_view`; `encodable` when `V` is a byte input and `codec` is specialized, or `value_codec` is specialized with `encode`; `decodable` when `V` is a byte result the core builds and `codec` is specialized, or `value_codec` is specialized with `decode`. A call with any other pair MUST stop the build in a `static_assert` whose requirement, `detail::converts`, names the format's type in full (a C++20 message is a literal and cannot hold `F::name`) and whose message says that the format does not convert this type and to include the format's header or to specialize `value_codec`. + +#### Scenario: A pair that does not exist +- **WHEN** a program calls `codecs::decode(codecs::formats::hex, text)` +- **THEN** compilation stops with a message whose requirement names `webcpp::codecs::formats::hex_t` and which says that the format does not convert this type + +### Requirement: Operations: sizes +`codecs::encoded_size(format, input)` SHALL return the exact size of what `encode` writes for `input`, and `codecs::max_decoded_size(format, text)` a bound on what `decode` writes for `text`, computed from the text's size alone. Both MUST be constexpr where the format and the input are constant expressions, the input's bytes are `std::uint8_t` or `unsigned char` and the input is not secret; of a secret input `encoded_size` MUST hold the timing guard and run the format's secret arithmetic. + +#### Scenario: The exact size and the bound +- **WHEN** `encoded_size(formats::base64, "foob"-as-bytes)` and `max_decoded_size(formats::base64, "Zm9vYg==")` are evaluated in a `static_assert` +- **THEN** they are 8 and 6, and `decode` writes 4 bytes + +### Requirement: Operations: buffer forms +`codecs::encode(format, input, std::span output)` and `codecs::decode(format, text, std::span output)` SHALL write into the caller's buffer (a value codec of bytes encodes into a `std::span`) and return `result`, the number of elements written; an output shorter than the exact size MUST be refused with `output_too_small`, and on every error nothing MUST be written. Neither form MUST allocate, except over an `over` whose intermediate is on the heap, whose buffer forms allocate through `over`'s allocator and are not `noexcept`. + +#### Scenario: A short buffer +- **WHEN** 32 bytes are encoded in hex into a `std::span` of 63 characters +- **THEN** the result is `output_too_small` and the buffer is unchanged + +### Requirement: Operations: tokens +`codecs::encode(format, input, token = {})` and `codecs::decode(format, text, token = {})` SHALL return `result`. A text token MUST be accepted when it has `result_type`, `prepare(n)` returning `char*` and `result()`, so that Boost.URL's `string_token::return_string`, `append_to` and `assign_to` work unchanged; a byte token likewise with `prepare` returning a pointer to a one-byte element. The core MUST call `prepare` at most once, with the exact size, after every check of the input has passed, then `result` once; a token's `static constexpr std::size_t capacity` MUST be compared before `prepare` (`output_too_small`), and a token's `static constexpr bool secret` MUST make the operation secret. `codecs::tokens` MUST provide `automatic` (the default), `return_string`, `append_to(s)`, `assign_to(s)`, `fixed` and `secret`, each serving both directions. `append_to` and `assign_to` MUST accept any `std::basic_string` and, for decode, any `std::vector`, using that container's allocator; `return_string` and `secret` MUST also be callable with an allocator, whose heap result is built with it. When a value codec fails after `prepare`, or the outer link of an `over` with a heap intermediate refuses, codecs' own tokens MUST be restored: `append_to` put back as it was, `return_string` giving nothing, and `assign_to` untouched, since it MUST convert into a scratch first (in place when the static bound is at most 4096 elements, else from its container's allocator, wiped in a secret operation) and copy into its container only on success; a token of the program's own is left as `prepare` made it. + +#### Scenario: Boost.URL's token +- **WHEN** a program calls `codecs::encode(codecs::formats::hex, bytes, boost::urls::string_token::append_to(text))` +- **THEN** the hex is appended to `text`, and the same call with an invalid decode leaves `text` unchanged + +#### Scenario: A pmr string token +- **WHEN** a program encodes 32 bytes in hex with `codecs::tokens::append_to(text)` where `text` is a `std::pmr::string` over an arena resource, and with `codecs::tokens::return_string(std::pmr::polymorphic_allocator{&arena})` +- **THEN** both texts are the hex, the second is a `std::pmr::string`, and the arena records every allocation while the global `operator new` counts none + +#### Scenario: A fixed token too small +- **WHEN** 40 bytes are encoded in base64 with `tokens::fixed<54>{}` +- **THEN** the result is `output_too_small` and no `prepare` is called + +#### Scenario: assign_to keeps its target when a value codec fails +- **WHEN** a value codec that fails after its output is prepared encodes into `tokens::assign_to(text)` where `text` holds "kept" +- **THEN** the result is the value codec's error and `text` still reads "kept" + +### Requirement: Operations: the default result +With no token, `encode` SHALL return `codecs::text` (or `codecs::bytes` for a value codec of bytes) when the input's size is known at compile time (`std::array`, a byte array, `std::span`, `text`, `bytes`, a type with a static `size()` that converts to a fixed-extent span) or the value codec states `max_encoded_size`, `M` being the format's bound, and `std::string` or `std::vector` otherwise; `decode` SHALL return `bytes` for a text of static size and `std::vector` otherwise. `text` and `bytes` MUST hold their elements in place with an actual size, compare by content, convert on an lvalue to `std::string_view` and `std::span`, and refuse the conversion of an rvalue at compile time. + +#### Scenario: A digest's hex with no heap +- **WHEN** a `std::array` is encoded with `codecs::encode(codecs::formats::hex, digest)` and decoded back from the result +- **THEN** the types are `result>` and `result>`, the bytes equal the digest, and a counting `operator new` counts nothing + +#### Scenario: A run-time input +- **WHEN** a `std::vector` is encoded in base64 with no token +- **THEN** the result is `result` + +### Requirement: Operations: typed decode +`codecs::decode(format, input)` SHALL return `result` for every `Value` that is `decodable` with the format: a value codec's type, `std::string`, `std::vector`, `std::array` (exactly `N` bytes, else `invalid_length`), `bytes` and `secret_bytes` (up to `N` bytes, else `output_too_small`), `secret_byte_vector`, and a type whose `fixed_byte_storage` a library specializes. The untyped overloads MUST NOT be chosen when a type argument is given explicitly. + +#### Scenario: A key from hex into a fixed array +- **WHEN** `codecs::decode>(codecs::formats::hex, text)` is called with 64 hex digits and then with 62 +- **THEN** the first gives the 32 bytes and the second `invalid_length` + +### Requirement: Secrecy: the trait, the format and the types +`codecs::is_secret` SHALL be false unless a library specializes it, and `is_secret_v` read it through `std::remove_cvref_t`. An operation MUST be secret when the value's `is_secret_v` is true, the value codec's `secret` is true, the token's `secret` is true, or the requested type of a typed decode is secret. A secret operation MUST return `secret_text` or `secret_bytes` (in place, move-only, wiped on destruction and on move, copied only by `clone()`) when the size is bounded at compile time and `secret_string` or `secret_byte_vector` (on the heap, move-only, wiped before the memory is freed) otherwise, and MUST wipe every buffer of the library's that held its bytes, every wipe by `secure::erase_secret`; a buffer here is memory the library owns or passes by pointer, not a scalar it returns by value (a decoder's `std::optional`, a character local). A secret operation into an explicit token that is not secret (`return_string`, `fixed`, `append_to`, `assign_to`, a Boost.URL token) MUST run guarded with the format's secret arithmetic and return the token's own `result_type`, every token the core makes being wiped when abandoned and where its result is cut to the written size; only `tokens::automatic` and `tokens::secret` give the secret result types. The core MUST specialize `is_secret` and `fixed_byte_storage` for `secure::secret`. `secret_string` and `secret_byte_vector` MUST be the `std::allocator` aliases of `basic_secret_string` and `basic_secret_byte_vector`, and `codecs::pmr::secret_string` and `codecs::pmr::secret_byte_vector` their `std::pmr::polymorphic_allocator` aliases. + +#### Scenario: A secret type encodes to a wiped text +- **WHEN** a test specializes `is_secret` for a 32-byte type of its own and encodes it in hex with no token +- **THEN** the result is `secret_text<64>`, and after its destruction its storage reads zero through the test seam + +#### Scenario: secure's secret is secret +- **WHEN** a program encodes a `secure::secret<32>` in hex with no token, and decodes 64 hex digits with `codecs::decode>(codecs::formats::hex, text)` +- **THEN** the first result is `secret_text<64>`, the second a `secure::secret<32>`, both operations are secret and neither uses the heap + +#### Scenario: Decode follows the requested type +- **WHEN** a program decodes 64 hex digits with `codecs::decode>(codecs::formats::hex, text)` +- **THEN** the operation is secret, its temporaries are wiped and no heap is used + +### Requirement: Composition: over +`codecs::over` SHALL be a format whose encode encodes with `Inner` and then with `Outer`, and whose decode decodes with `Outer` and then with `Inner`; `Inner` MAY be a codec or a value codec's format, `Outer` MUST be a codec, text feeding `Outer` as bytes. Its `name` MUST be `Outer`'s, `" over "` and `Inner`'s; it MUST be constructible from values by class template argument deduction; it MUST be constant time when every link is and secret when any link's operation is; its intermediate MUST be held in place when its bound is known at compile time (with no cap; the stack it costs is documented), MUST otherwise come from `over`'s allocator (a third template parameter, `std::allocator` by default, deduced from `over{outer, inner, allocator}`), and MUST be wiped when the chain is secret, each link's secret arithmetic running in a secret chain. With a heap intermediate its exact sizes, its encode and decode and the core's buffer forms over it run the inner link into the intermediate, allocate and MUST NOT be `noexcept`; with a static bound they MUST be `noexcept` and allocate nothing. A fault of a link's configuration MUST be the chain's, the outer link's first, before any data; a fault of a link's encode MUST be the chain's before any `prepare`, the inner link's always and the outer link's on an intermediate in place (with a heap intermediate the outer link's is found by its encode, after `prepare`, codecs' tokens being restored). `over` MUST stay one-shot. + +#### Scenario: Hex over base64 +- **WHEN** 16 bytes are encoded with `codecs::over{codecs::formats::hex, codecs::formats::base64}` and decoded back +- **THEN** the text is the hex of the base64 text, the bytes come back, and nothing is allocated + +### Requirement: Format: hex +`` SHALL declare `formats::hex`, writing lower case by default and upper case with `formats::hex(formats::letter_case::upper)`. Decode MUST accept either case, mixed included, and refuse an odd length with `invalid_length` and any other character with `invalid_character`. + +#### Scenario: RFC 4648's base16 +- **WHEN** the inputs of RFC 4648 section 10 are encoded with `hex(letter_case::upper)` +- **THEN** each text is the RFC's, and each decodes back, in either case + +### Requirement: Format: base32 and base32hex +`` SHALL declare `formats::base32` (RFC 4648 section 6) and `formats::base32hex` (section 7), each writing padding by default and none with `padding::omitted`, encoding in upper case. Decode MUST accept either case, require the padding the option says (`invalid_padding`, which a text of a valid length with its `=` out of place, `MZXW6Y==`, also is), refuse a length no encoding has (`invalid_length`), any other character (`invalid_character`) and non-zero trailing bits (`invalid_padding`). + +#### Scenario: RFC 4648's vectors +- **WHEN** the inputs of RFC 4648 section 10 are encoded with `base32` and `base32hex`, padded and unpadded +- **THEN** each text is the RFC's (its padding removed for the unpadded form), and each decodes back + +### Requirement: Format: base58 +`` SHALL declare, in `codecs::formats`, `template struct basic_base58`, the concept `base58_alphabet` (a type with `static constexpr std::string_view characters`), the alphabets `bitcoin_alphabet`, `ripple_alphabet` and `flickr_alphabet`, `struct no_checksum {}`, the concept `base58_checksum` (`no_checksum`, or a type with `static constexpr std::size_t size` and `static void compute(std::span payload, std::span out) noexcept`), the types `base58_bitcoin_t`, `base58_ripple_t` and `base58_flickr_t` (each `basic_base58<100, ...>` of its alphabet, with no checksum), their objects `base58_bitcoin`, `base58_ripple` and `base58_flickr`, and `formats::base58`, which is `base58_bitcoin`. `basic_base58` MUST stop the build in a `static_assert` when its alphabet's `characters` are not 58 distinct characters. Its `maximum_bytes` MUST be `MaximumBytes`, the payload's bound without the checksum, and its `maximum_characters` MUST be derived from it, the length of the longest encoding of `maximum_bytes` plus `Checksum::size` bytes (137 for 100 bytes with no checksum). Encode MUST write each leading zero byte as the alphabet's first character. Decode MUST refuse any character outside the alphabet with `invalid_character`. An input longer than `maximum_bytes` and a text longer than `maximum_characters` MUST be refused with `input_too_long` by their length, before any read, and a decode whose payload would be longer than `maximum_bytes` MUST be refused with `input_too_long`, after the text's characters and length and before its checksum. Every instance MUST keep its scratch in place, sized by its template, so that its sizes are exact, `noexcept` and allocation-free. With a checksum, encode MUST append `Checksum::compute(payload)`, and decode MUST split the last `Checksum::size` decoded bytes off, recompute the checksum of the rest, compare the two with `secure::constant_time_equal` and give the payload without the checksum, refusing a mismatch with `checksum_mismatch` and fewer decoded bytes than `Checksum::size` with `invalid_length`. codecs MUST define no checksum algorithm. Code derived from Bitcoin Core's MUST ship with Bitcoin Core's MIT notice, `LICENSE-BITCOIN.txt`. + +#### Scenario: Bitcoin Core's vectors +- **WHEN** every pair of Bitcoin Core's `base58_encode_decode.json` of at most 100 bytes is encoded and decoded with `formats::base58`, and every pair, its 256-byte input included, with `basic_base58<256, bitcoin_alphabet>{}` +- **THEN** each text and each byte string is the file's, and the 256-byte input and its 348-character text are `input_too_long` through `formats::base58` + +#### Scenario: The default's bound and a larger instance +- **WHEN** 101 bytes are encoded with `formats::base58` and with `basic_base58<1024, bitcoin_alphabet>{}`, and 138 characters and 137 `z` characters (101 bytes) are decoded with `formats::base58` +- **THEN** `formats::base58` refuses each with `input_too_long`, and the larger instance encodes the 101 bytes and decodes its text back to them + +#### Scenario: An alphabet of the program's own +- **WHEN** a program defines a type whose `characters` are Bitcoin's alphabet reversed and encodes and decodes with `basic_base58<100, that type>{}`, and another program defines an alphabet of 58 characters with one repeated and names `basic_base58<100, that type>` +- **THEN** the first round-trips, its text being Bitcoin's with each character replaced by the character of the same digit, and the second stops the build with a message saying an alphabet is 58 distinct characters + +#### Scenario: A checksum as the third parameter +- **WHEN** a test defines a 4-byte checksum type of its own and encodes and decodes with `basic_base58<100, bitcoin_alphabet, that type>{}`, a payload as public bytes and a `secure::secret<32>` payload as a secret operation +- **THEN** each text is `formats::basic_base58<104, bitcoin_alphabet>`'s encoding of the payload followed by its checksum, each decodes back to the payload alone, a changed character is `checksum_mismatch` in both operations, and a text of fewer than 4 decoded bytes is `invalid_length` + +#### Scenario: base58 streams only through buffered +- **WHEN** a program passes `codecs::encoder(codecs::formats::base58)` to `codecs::drain`, and then streams `codecs::buffered(codecs::encoder(codecs::formats::basic_base58<256, codecs::formats::bitcoin_alphabet>{}))` over the file's inputs in chunks +- **THEN** the first stops the build with a message naming `codecs::buffered`, and the second gives the file's texts + +### Requirement: Format: base64 and base64url +`` SHALL declare `formats::base64` (RFC 4648 section 4, padding written by default) and `formats::base64url` (section 5, padding omitted by default), each taking the other padding by option. Decode MUST be canonical: it refuses whitespace, line breaks and the other alphabet's characters (`invalid_character`), padding against the option and non-zero trailing bits (`invalid_padding`), and a length no encoding has (`invalid_length`). + +#### Scenario: RFC 4648's vectors and the URL alphabet +- **WHEN** RFC 4648 section 10's inputs are encoded with `base64` and with `base64url`, and the bytes `0xfb 0xff` are encoded with both +- **THEN** the texts are the RFC's, `+/8=` and `-_8`, and each decodes back + +#### Scenario: A non-canonical text +- **WHEN** `Zh==` is decoded with `base64` +- **THEN** the result is `invalid_padding`, since its trailing bits are not zero + +### Requirement: Format: bech32 and bech32m +`` SHALL declare, in `codecs::formats`, `enum class bech32_variant : unsigned char { bech32 = 1, bech32m = 2 }` (BIP-173's and BIP-350's checksum constants), the data tags `bech32_bytes` and `bech32_words`, `template class basic_bech32`, `bech32_t` and `bech32m_t` (its instances of 90 characters over bytes) with their objects `formats::bech32` and `formats::bech32m`, `bech32_parts`, `append_words_from_bytes` and `bytes_from_words`. A format MUST be configured by a call with a human-readable part held in the format value, and `.words()` MUST give the same format over `bech32_words`. `basic_bech32` MUST stop the build in a `static_assert` when `MaximumLength` is below 8. With `bech32_bytes` the data MUST be bytes regrouped into 5-bit groups with zero padding as BIP-173's `convertbits`; with `bech32_words` each element MUST be one 5-bit value written and read as it is, a value above 31 refused on encode with `invalid_character`. Encode MUST write lower case and refuse a missing or invalid human-readable part with `invalid_prefix`, a missing part, a text past `MaximumLength` and a word above 31 being the codec's `encode_fault`, found before any token is prepared. Decode MUST refuse mixed case (`mixed_case`), a human-readable part other than the format's or outside 1 to 83 characters of 33 to 126 (`invalid_prefix`), a bad checksum (`checksum_mismatch`), a text past `MaximumLength` (`input_too_long`), a character outside the alphabet (`invalid_character`) and, over bytes, more than 4 padding bits or non-zero padding bits (`invalid_padding`). Every form of bech32 MUST allocate nothing: its scratch, its stream decoder's hold and its results are in place, sized from `MaximumLength`. `codecs::decode(format, text)` with no human-readable part in the format MUST accept any and yield `human_readable_part` and `data`. `bytes_from_words(words, out)` MUST regroup 5-bit values into bytes, refusing a value above 31 (`invalid_character`), more than 4 padding bits or a non-zero one (`invalid_padding`) and a short output (`output_too_small`). codecs MUST NOT apply segwit's rules (versions, program sizes, networks' prefixes) nor parse Lightning's fields. + +#### Scenario: BIP-173's and BIP-350's lists +- **WHEN** every valid string of BIP-173 is decoded with `bech32` and every valid string of BIP-350 with `bech32m`, and every invalid string of both with its format +- **THEN** every valid string passes the checksum and case checks; each whose data regroup into bytes with at most 4 zero padding bits decodes and encodes back to its lower-case form, the others (BIP-350's 82 `l` characters) are refused with `invalid_padding`; and every invalid one is refused with the error the test's table maps its reason to + +#### Scenario: Segwit addresses in words mode +- **WHEN** each valid segwit address of BIP-173 (version 0) and BIP-350 is encoded from its scriptPubKey as the version word followed by `append_words_from_bytes(program)`, with `formats::bech32(prefix).words()` for version 0 and `formats::bech32m(prefix).words()` above, and decoded back +- **THEN** each text is the address in lower case, its words give back the version and, through `bytes_from_words`, the program; and a word of 32 is refused with `invalid_character` + +#### Scenario: A version as a byte is another text +- **WHEN** BIP-350's Taproot address `bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0` is encoded in words mode (the word 1, then the program's words) and in bytes mode (the byte 0x01, then the program) +- **THEN** the words mode gives the address and the bytes mode a different text + +#### Scenario: The stream decoder holds until the checksum +- **WHEN** a valid bech32 text is sent to `codecs::decoder(formats::bech32("bc"))` one character at a time, receiving after each, and then the same text with its last character changed +- **THEN** every receive before `flush` gives zero bytes; after `flush` the first gives the data and the second `checksum_mismatch` with no byte ever delivered + +#### Scenario: A Lightning invoice through a larger instance +- **WHEN** BOLT 11's first example invoice is decoded by `basic_bech32{}("lnbc").words()`, one-shot and through its stream decoder, and by `formats::bech32("lnbc").words()` +- **THEN** the larger instance gives the invoice's words, the first seven reading the example's timestamp, and `formats::bech32` reports `input_too_long`, its stream having delivered nothing + +#### Scenario: A maximum length below the shortest text +- **WHEN** a program names `basic_bech32` +- **THEN** the build stops with a message saying a bech32 maximum length is at least 8 characters + +#### Scenario: A Nostr public key +- **WHEN** 32 bytes are encoded with `formats::bech32("npub")` +- **THEN** the text starts with `npub1`, is 63 characters long and decodes back with the same format + +### Requirement: Format: armor (RFC 7468) +`` SHALL declare `formats::armor`, configured by a call with a label of up to 64 characters held in the format value, whose encode writes `-----BEGIN