From bb87db9a02cafd58b220649152983706a56c7124 Mon Sep 17 00:00:00 2001 From: R Date: Thu, 26 Nov 2026 06:15:13 -0300 Subject: [PATCH 1/4] codecs: the genesis, its plan and the base commits of its implementation --- README.md | 1 + .../openspec/changes/genesis/.openspec.yaml | 11 + .../codecs/openspec/changes/genesis/design.md | 1263 +++++++++++ .../openspec/changes/genesis/proposal.md | 183 ++ .../changes/genesis/reference/STATUS.md | 35 + .../changes/genesis/reference/plan.md | 1878 +++++++++++++++++ .../changes/genesis/specs/codecs/spec.md | 338 +++ .../codecs/openspec/changes/genesis/tasks.md | 57 + libraries/codecs/openspec/config.yaml | 11 + 9 files changed, 3777 insertions(+) create mode 100644 libraries/codecs/openspec/changes/genesis/.openspec.yaml create mode 100644 libraries/codecs/openspec/changes/genesis/design.md create mode 100644 libraries/codecs/openspec/changes/genesis/proposal.md create mode 100644 libraries/codecs/openspec/changes/genesis/reference/STATUS.md create mode 100644 libraries/codecs/openspec/changes/genesis/reference/plan.md create mode 100644 libraries/codecs/openspec/changes/genesis/specs/codecs/spec.md create mode 100644 libraries/codecs/openspec/changes/genesis/tasks.md create mode 100644 libraries/codecs/openspec/config.yaml diff --git a/README.md b/README.md index dd0e79f..c6bd368 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 | accepted | | 2026-11-24 | | | 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..5ce812c --- /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: accepted + release: null + implementation: null + 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..cf1cb14 --- /dev/null +++ b/libraries/codecs/openspec/changes/genesis/design.md @@ -0,0 +1,1263 @@ +## 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; base58check and crypto's key formats, which are their libraries' follow-ups; 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). +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. +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). +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). +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. + +## 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"). + +``` +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::base58 +include/webcpp/codecs/base64.hpp formats::base64, formats::base64url +include/webcpp/codecs/bech32.hpp formats::bech32, formats::bech32m, bech32_parts +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). + +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. + +### 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. + +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. + +### 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 fails after `prepare`. 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()`, which base58's decode uses for its scratch (D13, +D22). The default token's name, `automatic`, is builder's call B7. + +### 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). + +### 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). + +### 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. `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). + +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. + +### 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`): `formats::base58`, `base58_alphabet::bitcoin` by default, `ripple` + and `flickr` by option (builder's call B14: the alphabets in use). Leading zero bytes are leading + first-alphabet characters, as Bitcoin Core's `EncodeBase58`. The conversion is quadratic in the + length; codecs sets no cap (builder's call B15), and the page says to check a length before + decoding text from outside. Decoding into a token runs the conversion twice, the first time to + count (D8's exact size), since base58's inputs are short; that decode's scratch (the limbs of a + run-time length) comes from the token's `get_allocator()` when the token has one, from + `std::allocator` otherwise, and is wiped when the operation is secret (owner decision 23, D22). + 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`): `formats::bech32` and `formats::bech32m`, configured with a + human-readable part, `formats::bech32("bc")`, held in the format value (up to 83 characters, + in place, so the format never dangles; builder's call B17), and a `maximum_length`, 90 by default + as BIP-173 says and settable for Lightning's invoices and Nostr's NIP-19 (builder's call B18). + 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`). + 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 `maximum_length` + (`input_too_long`), a human-readable part outside 1 to 83 characters of 33 to 126 + (`invalid_prefix`). Encoding writes lower case. 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 a + `std::vector`). The public name is `human_readable_part`, spelled out (BIP-173's + "hrp" is an abbreviation), builder's call B19. A witness version and a segwit address are the + caller's (or a later value codec's), not this format's. Its stream encoder writes as it goes; + its stream decoder holds the decoded bytes 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, cited, ruling R8), `test/bech32_stream_test.cpp`, the lanes' additions +(`bech32_fuzz.cpp`, `bech32m_fuzz.cpp`); modify `test/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 { +struct bech32_t { // bech32m_t the same, name "bech32m" + static constexpr std::string_view name = "bech32"; + detail::bounded_label<83> human_readable_part; + std::size_t maximum_length = 90; + [[nodiscard]] constexpr bech32_t operator()(std::string_view human_readable_part, + std::size_t maximum_length = 90) const noexcept; +}; +inline constexpr bech32_t bech32{}; +inline constexpr bech32m_t bech32m{}; +struct bech32_parts { text<83> human_readable_part; std::vector data; }; +} +// value_codec and : decode only +// (output_kind::text input), any human-readable part when the format has none. +// stream_codec: encoder writes as it goes and the checksum at flush; decoder holds raw characters +// (Options.capacity, 90 when 0, B47) and gives human_readable_part() after a successful flush. +``` + The configuration's faults, checked first (B23): a human-readable part over 83 characters + (`overflowed()`), outside 33 to 126, or empty on encode: `invalid_prefix`; `maximum_length` + below the shortest valid text (8): `invalid_prefix`. `polymod`'s conditional XOR is + `select` by a mask over the five generator words (D12); the alphabet by `lookup` over the + 32-entry table and its inverse by masks. The bound counts 83 characters of human-readable part. + Decode with no human-readable part in the format accepts any (D20's rule for the stream, the + same one-shot). + +- [ ] **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; 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"); a 300-character text with + `decoder(formats::bech32("lnbc", 1023), capacity<1023>)` gives the data and with + `decoder(formats::bech32("lnbc", 1023))` `input_too_long` at `flush`, nothing delivered (the + spec's scenario "A hold larger than the default"); 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"). +- [ ] **Steps 2 to 4** as the pattern. Expected: pass. +- [ ] **Step 5: Commit, lint.** `codecs: bech32 and bech32m, constant time, the parts, 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/base58check.hpp` (the test's own `base58check`, a codec over `formats::base58` and +a 4-byte checksum of the test's own, since codecs has no hash: a 32-bit state from 0, for each +byte `state = std::rotl(state, 5) ^ byte`, written big-endian), `test/messages/drain_of_base58/`, the lanes' additions +(`base58_fuzz.cpp`); modify `test/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 { +enum class base58_alphabet : unsigned char { bitcoin = 1, ripple = 2, flickr = 3 }; +struct base58_t { + static constexpr std::string_view name = "base58"; + static constexpr std::size_t maximum_bytes = 1024; // ruling R6 + static constexpr std::size_t maximum_characters = 1400; + base58_alphabet alphabet = base58_alphabet::bitcoin; + [[nodiscard]] constexpr base58_t operator()(base58_alphabet chosen) const noexcept; +}; +inline constexpr base58_t base58{}; +} +// codec: constant_time = false; constant_time_when_secret = true (B24); +// no stream_codec. +``` + Every operation works in an in-place scratch sized for `maximum_bytes` and + `maximum_characters` (ruling R6): an input past either is `input_too_long`, checked before any + read. 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` and its inverse by masks. + +- [ ] **Step 1: Write the failing tests:** `base58_test.cpp`: every pair of Bitcoin Core's + `base58_encode_decode.json` (read through `WEBCPP_TEST_BITCOIN_BASE58_VECTORS`, test + requirement `/webcpp/third_party//bitcoin_base58_vectors`) encoded and decoded, 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 spec's scenario "Bitcoin Core's + vectors"); the three alphabets on one input (Ripple's and Flickr's texts are Bitcoin's with each character + replaced by the character of the same digit in their alphabet); `'0'`, `'O'`, `'I'`, `'l'` and every byte + outside the alphabet `invalid_character`; 1025 bytes and 1401 characters `input_too_long`; + 1024 bytes of 0xFF round trip; Review Focus 1 to 3 (no in-place decode: the page says so). + `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` with + `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 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`: includes + `"support/base58check.hpp"`; `encode(test::base58check, payload)` and `decode` round trip, a + changed character is `checksum_mismatch` (the spec's scenario "hash's base58check"), and a + translation unit of the same program that does not include the header does not see the name + (a `requires` probe in a second source file, `interoperation_unseen.cpp`). + The constant-time lane: base58's secret encode and decode of a fixed length in `paths.hpp`, + and its dudect case (secret decode of a fixed length, two classes); the fuzz target. +- [ ] **Steps 2 to 4** as the pattern, and `python3 tools/test/third_party_test.py`. Expected: + pass. +- [ ] **Step 5: Commit, lint.** codecs: `codecs: base58, Bitcoin Core's algorithm and a constant-time one for secrets, its vectors, and a format 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 ceiling and its constant time only when + secret; bech32's maximum length and hold; 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 24, 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, R6 and R7 written into D11, D13, D22 and the requirements + they touch, once the owner has answered Q1), `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 (changes B15, and touches D13 and D22; owner question Q1):** base58 has a ceiling, + `maximum_bytes = 1024` and `maximum_characters = 1400`, past which every operation is + `input_too_long`, and works in an in-place scratch sized for it. Without a ceiling the approved + contract cannot hold for base58: `codec::encoded_size` and `decoded_size` must be exact, + `noexcept` and allocation-free (D3, the spec), and base58's exact size exists only after a + quadratic conversion that needs a working number as long as the input. The ceiling also bounds + the quadratic cost a text from outside can force. Consequence: base58's decode into a token + allocates only through the token's own `prepare`, never a scratch, so D13's and D22's "its + scratch from the token's `get_allocator()`" has nothing to apply to; 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) 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 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). + +## Owner's questions + +- **Q1 (R6):** 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 plan builds the ceiling; Task 19 + is the first to depend on it, and the delivery writes the answer into the design and the spec. + +## 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::formats::base58check` (double SHA-256) + over `formats::base58`; hash then depends on codecs. +- `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..e0b2ba4 --- /dev/null +++ b/libraries/codecs/openspec/changes/genesis/specs/codecs/spec.md @@ -0,0 +1,338 @@ +## 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`; the library MUST compile and work without exceptions, an allocator's failure then following the build's handler with no handling added by codecs. + +#### 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 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`. Every public operation of the core MUST be written over these functions alone. + +#### 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` + +### 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. 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 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`. + +#### Scenario: A pair that does not exist +- **WHEN** a program calls `codecs::decode(codecs::formats::hex, text)` +- **THEN** compilation stops with a message that names `hex` and says that it 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. + +#### 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. + +#### 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. + +#### 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 + +### 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`. 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, 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. `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`), 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 `formats::base58`, with Bitcoin's alphabet by default and `base58_alphabet::ripple` and `base58_alphabet::flickr` by option, writing each leading zero byte as the alphabet's first character. Decode MUST refuse any character outside the alphabet with `invalid_character`. + +#### Scenario: Bitcoin Core's vectors +- **WHEN** every pair of Bitcoin Core's `base58_encode_decode.json` is encoded and decoded +- **THEN** each text and each byte string is the file's + +#### 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::base58))` 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 `formats::bech32` (BIP-173) and `formats::bech32m` (BIP-350), configured by a call with a human-readable part held in the format value, and a `maximum_length` of 90 by default that a program may raise. The data MUST be bytes regrouped into 5-bit groups with zero padding as BIP-173's `convertbits`. Encode MUST write lower case and refuse a missing or invalid human-readable part with `invalid_prefix`. 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 `maximum_length` (`input_too_long`), a character outside the alphabet (`invalid_character`) and more than 4 padding bits or non-zero padding bits (`invalid_padding`). `codecs::decode(formats::bech32, text)` with no human-readable part in the format MUST accept any and yield `human_readable_part` and `data`. + +#### 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: 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 hold larger than the default +- **WHEN** a 300-character bech32 text is decoded by `codecs::decoder(formats::bech32("lnbc", 1023), codecs::capacity<1023>)` and by `codecs::decoder(formats::bech32("lnbc", 1023))` +- **THEN** the first gives the data, and the second reports `input_too_long` at `flush`, having delivered nothing + +#### 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