diff --git a/.gitattributes b/.gitattributes index cc23192..4860ac6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,6 @@ * text=auto eol=lf *.bat text eol=crlf +# The fuzz corpora are inputs byte for byte: no line ending of theirs is converted. +test/fuzz/corpus/** -text +# The armor's vectors are compared byte for byte: no line ending of theirs is converted. +test/data/armor/** -text diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..5ad6934 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,48 @@ +# Working on codecs + +webcpp's rules apply here: read the superproject's +[CODING-GUIDELINES.md](../../CODING-GUIDELINES.md) +() and its +[AGENTS.md](../../AGENTS.md) +() first. This file holds only what is +specific to codecs. + +## What codecs is + +- **webcpp's own library** (`"port-of": null`): one contract for converting bytes and typed + values to text and back, and any data through one-shot and stream transformers, with seven + formats (hex, base32, base58, base64, bech32, percent-encoding and RFC 7468's armor). +- **Header-only**, built on secure (`/webcpp/secure//secure`) and config. percent alone + depends on Boost.URL, through the target `/webcpp/codecs//percent`. + +## Cautions + +- A test is declared through `codecs-run` (or `codecs-compile`) in `test/Jamfile`, which builds it + with exceptions and without. +- A test that defines a seam includes the seam's header first, before any header of codecs. +- The core (`codecs.hpp` and `detail/core/`) includes no format and no Boost.URL: + `meta/include-boundaries.json` checks it, and checks that no header names another webcpp + library but config and secure. +- Constant-time code uses secure's building blocks alone: codecs keeps no guard, no secret value + type and no wipe primitive of its own (`secure::timing_guard`, `secure::secret`, + `secure::erase_secret`), and no constant-time primitive; its secret results (`secret_text`, + `secret_bytes` and the heap secret types) are built on them. +- `detail` is not API: another library's header never includes it. +- Every header survives a bare `` before it (CODING-GUIDELINES.md's rule): it writes + `(std::min)(...)`, `(std::max)(...)` and `(std::numeric_limits::max)()`, and names none of + ``'s other macros; `test/windows_h_before_test.cpp` and + `test/windows_h_after_test.cpp` check it on the MSVC lanes. + +## The page and the examples + +- The page is `doc/codecs.adoc`, which includes one file for each chapter (`overview`, `formats`, + `tokens`, `results`, `secrecy`, `composition`, `streams`, `allocators`, `writing_a_format`, + `writing_a_transformer`) and the changelog. A chapter that states a behaviour states what the + headers' Doc Comments state: read them when a header changes, and change the chapter with it. +- Every C++ listing of the page is a tagged region of a program of `example/`, which + `example/Jamfile` builds and runs on every target, its output compared with the `.expected` + beside it. A new example is declared there and shown in a chapter (the doc build fails on one + that is not); the percent example links `/webcpp/codecs//percent`, and the allocator example + catches `std::bad_alloc`, so it is built with exceptions on. +- A change a user sees adds its line to `doc/changelog.adoc` under "Unreleased", at most ten lines + for the library. diff --git a/LICENSE-BITCOIN.txt b/LICENSE-BITCOIN.txt new file mode 100644 index 0000000..89960cb --- /dev/null +++ b/LICENSE-BITCOIN.txt @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2009-2026 The Bitcoin Core developers +Copyright (c) 2009-2026 Bitcoin Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md index cbd547c..d89f347 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,12 @@ wasip2, wasip3 and Emscripten. Over that contract it ships seven formats: hex, b base64, bech32, percent-encoding and RFC 7468's armor, every name in `webcpp::codecs`. It is header-only and builds on webcpp::secure for its secret and constant-time operations. -The library is being built; its design is the genesis of `libraries/codecs` in +Every format is a value (`codecs::formats::hex`), an operation a function of it +(`codecs::encode(format, bytes)`), and where a result goes a token, so that a digest is a text held in +place, a key a secret that wipes itself, and a file a stream. Errors are values, and codecs throws +nothing of its own. Its page, `doc/codecs.adoc`, teaches the formats, the tokens and results, +secrecy, composition, streams, allocators and how to write a format or a transformer, with a program +of `example/` for each; its design is the genesis of `libraries/codecs` in [webcpporg/proposals](https://github.com/webcpporg/proposals). ## Build and test @@ -26,6 +31,15 @@ From the superproject's root: ./b2 toolset=clang libs/codecs/test libs/codecs/example ``` +## Documentation + +The library's page is built with `./b2 libs/codecs/doc doc` and published with webcpp's +documentation, at . + ## Licence Distributed under the Boost Software License, Version 1.0 (`LICENSE_1_0.txt`). + +base58's public conversion, in `include/webcpp/codecs/detail/formats/base58.hpp`, follows Bitcoin +Core's `EncodeBase58` and `DecodeBase58` (`src/base58.cpp`); codecs is BSL-1.0; base58's public +conversion derives from Bitcoin Core's, whose MIT notice is `LICENSE-BITCOIN.txt`. diff --git a/build.jam b/build.jam new file mode 100644 index 0000000..54b4559 --- /dev/null +++ b/build.jam @@ -0,0 +1,25 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# codecs: one contract for converting bytes and values to text and back, and +# any data through streams; a program names /webcpp/codecs//codecs, and +# /webcpp/codecs//percent for percent-encoding: +# +# exe app : app.cpp /webcpp/codecs//codecs ; + +import webcpp-target ; + +project /webcpp/codecs ; + +# tag::codecs[] +alias codecs : : : : include /boost//headers /webcpp/config//config + /webcpp/secure//secure ; +# end::codecs[] +# percent.hpp adapts Boost.URL's percent-encoding: a program that includes it +# names this target, which links Boost.URL built from Boost's sources. +# tag::percent[] +alias percent : : : : codecs /webcpp//boost_url ; +# end::percent[] diff --git a/doc/Jamfile b/doc/Jamfile new file mode 100644 index 0000000..79e00bb --- /dev/null +++ b/doc/Jamfile @@ -0,0 +1,10 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.doc codecs : codecs.adoc ; +webcpp.reference codecs ; diff --git a/doc/allocators.adoc b/doc/allocators.adoc new file mode 100644 index 0000000..2783c96 --- /dev/null +++ b/doc/allocators.adoc @@ -0,0 +1,110 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#codecs-allocators] +== Allocators + +A program that cannot call the global `operator new`, a WASI component with an +arena, a server with a request pool, tells codecs which allocator to use, and +codecs allocates through it and through nothing else. + +=== What allocates + +[cols="3,2",options="header"] +|=== +| Form | Allocates + +| the buffer forms of `encode` and `decode`, the sizes +| nothing (and `noexcept`), except `over` with a heap intermediate, whose sizes and buffer forms allocate and are not `noexcept` (<>) + +| `text`, `bytes`, `tokens::fixed`, and the secret results in place +| nothing + +| the conversion of every format, in every form: hex, base32, base58, base64, bech32, percent and the armor +| nothing: the scratch of each is in place; a result on the heap, as the default result of a run-time size or `armor_parts`, allocates through its own allocator + +| `over` with a static bound +| nothing + +| `over` with a bound that is not static +| its allocator, for the intermediate + +| the stream transformers of the native formats, `pipe`, `drain`, and `each` and `buffered` with `codecs::capacity` +| nothing, once constructed + +| the default result of a run-time size, `return_string`, `append_to`, `assign_to`, `tokens::secret` with a heap result +| the allocator of the result or the container + +| `each` and `buffered` with an allocator +| the allocator, for their storage +|=== + +base58 takes no allocator: its scratch is in place, sized by its template, so +that `buffered` over its encoder takes its storage from the allocator it is given and the +conversion itself allocates nothing. bech32's results, scratch and stream hold +are in place too, sized from `MaximumLength`. + +=== The tokens with an allocator + +`tokens::return_string(allocator)` gives a `std::basic_string` over the +allocator, which is used through `std::allocator_traits` and rebound to `char`; +`tokens::secret(allocator)` gives `basic_secret_string` or +`basic_secret_byte_vector` when the size is not known at compile time, and +the in-place result, ignoring the allocator, when it is; and `append_to` and +`assign_to` use the allocator of the container they are given, a +`std::pmr::string` among them. The decode's bytes go to a `std::vector` +the same way. + +The `std::pmr` aliases, in `codecs::pmr`, are `codecs::pmr::secret_string` and +`codecs::pmr::secret_byte_vector`, the secret heap types over +`std::pmr::polymorphic_allocator`, as the containers of `std::pmr` are over the +standard's allocators. Their `std::allocator` aliases are `codecs::secret_string` and +`codecs::secret_byte_vector`. + +[source,cpp] +---- +include::{examples}/pmr_arena.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/pmr_arena.expected[] +---- + +The arena in the program records every allocation, and the global `operator new` +sees none: codecs' tests check that for every form that takes an allocator, with +a recording memory resource and with allocators of their own that the +standard's rules are checked against. + +=== An allocator that throws + +An allocator that cannot give the memory throws, as `std::pmr::null_memory_resource` +does once the arena is full. That exception propagates unchanged out of the +allocating function, which is not `noexcept`, and codecs throws nothing of its +own (<>). What the program finds after it: + +* a token's container still holds what it held: `append_to` is put back as it + was, `assign_to` gives the container nothing before the conversion succeeds, + and in the example the string still holds `kept`; +* every buffer of a secret operation that was allocated is wiped before it is + given back, and a secret heap type whose allocation throws keeps its value; +* `each` and `buffered` with an allocator: a `send` that throws accepts nothing, + and the stream converts the same input after the exception; a `receive` + that throws leaves its item pending; a `flush` that throws leaves the stream + as it was before the flush, valid and resettable. + +Without exceptions the allocator's failure follows the build's handler: codecs +adds no handling. + +=== Pitfalls + +* The allocator of `over` is for its intermediate alone. The allocator of a + token is for its result alone. Neither is the other's. +* A `std::pmr::monotonic_buffer_resource` never gives memory back: an encode of a + megabyte through an arena of a kilobyte throws once, and a loop that reuses the + arena must release it. +* A secret result over a pmr allocator is wiped before its memory goes back to + the resource, but the resource may keep the pages: that is the resource's. diff --git a/doc/changelog.adoc b/doc/changelog.adoc new file mode 100644 index 0000000..f36b04a --- /dev/null +++ b/doc/changelog.adoc @@ -0,0 +1,29 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[appendix] +[#codecs-changelog] +== Changelog + +What changed in codecs in each version of webcpp, newest first, one line +per change. "Unreleased" is what the next version brings. The release notes +of every version are on webcpp's index page. + +[#codecs-changelog-unreleased] +=== Unreleased + +// tag::unreleased[] +* Added codecs.hpp and config.hpp: encode, decode, tokens, results, secrecy and over, errors as values. +* Added the stream contract: one-shot and stream transformers, pipe, drain, each, buffered, encoder and decoder. +* Added hex.hpp: hex, constant time, streaming natively and decoding in place. +* Added base32.hpp: base32 and base32hex of RFC 4648, padding an option, constant time, streaming natively and decoding in place. +* Added base64.hpp: base64 and base64url of RFC 4648, canonical on decode, constant time, streaming natively and decoding in place. +* Added base58.hpp: basic_base58 with a bound, an alphabet and a checksum as parameters, constant time when secret, streaming through buffered. +* Added bech32.hpp: bech32 and bech32m with a maximum length, words and bytes data, constant time and streaming natively. +* Added percent.hpp: percent-encoding over Boost.URL with any CharSet, and the target percent, streaming natively. +* Added armor.hpp: RFC 7468's strict armor, composing over any bytes format, its payload constant time, streaming natively. +* Added the guide, with its examples built and run on every target. +// end::unreleased[] diff --git a/doc/codecs.adoc b/doc/codecs.adoc new file mode 100644 index 0000000..ba67459 --- /dev/null +++ b/doc/codecs.adoc @@ -0,0 +1,68 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + += codecs: bytes and values to text and back, and streams of any data, for {cpp} +:toc: left +:toclevels: 2 +:idprefix: +:sectanchors: +:example-caption!: +:attribute-missing: warn + +codecs is the conversion library of +https://github.com/webcpporg/webcpp[webcpp], for a {cpp}20 program on every +target webcpp has: one contract for converting bytes and typed values to text +and back, and any data through one-shot and stream transformers, with hex, +base32, base58, base64, bech32, percent-encoding and RFC 7468's armor. It is +built on webcpp::secure, so that the conversions of secrets keep their timing +and their memory clean. + +The page teaches the library in the order a program meets it. <> +says what codecs is and what it is not, <> has one section for +each format, with its example and its pitfalls, and the chapters after it teach +what every format shares: <> (where a result goes), +<> (the default and fixed results and the typed decode), +<> (what a secret operation is), <> +(`over`), <> (the two transformer concepts, `pipe`, `drain`, +`each` and `buffered`) and <> (what allocates, and the +`codecs::pmr` aliases). <> and +<> are for the library that adds a format of its +own, and a transformer of data that is no text. Every program shown is in +`example/`, built and run on every target with the output it prints. The +<> that closes the page lists every name the headers +declare. + +include::overview.adoc[] + +include::formats.adoc[] + +include::tokens.adoc[] + +include::results.adoc[] + +include::secrecy.adoc[] + +include::composition.adoc[] + +include::streams.adoc[] + +include::allocators.adoc[] + +include::writing_a_format.adoc[] + +include::writing_a_transformer.adoc[] + +[#reference] +== Reference + +Every name codecs declares, in the namespace `webcpp::codecs`, from the Doc +Comments of its headers: each class, function, type and enumerator with its +declaration, what it does, what it asks of its caller and how it fails. The +other sections teach the library; this one is where a name is looked up. + +include::{reference}[leveloffset=+1] + +include::changelog.adoc[] diff --git a/doc/composition.adoc b/doc/composition.adoc new file mode 100644 index 0000000..6e92758 --- /dev/null +++ b/doc/composition.adoc @@ -0,0 +1,92 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#codecs-composition] +== Composition: over + +`codecs::over{outer, inner}` is a format made of two. Encoding encodes with the +inner format and then encodes that output, as bytes, with the outer; decoding +decodes with the outer and then with the inner. `Inner` may be the format of a `codec` +or of a value codec, whose value `over` converts to bytes first +(<>); `Outer` must be the format of a `codec`, since its input is +the inner's output read as bytes. The armor over any bytes format is the usual +use (`over{formats::armor("PUBLIC KEY"), inner}`). + +[source,cpp] +---- +include::{examples}/over_chain.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/over_chain.expected[] +---- + +The name of the chain is the outer link's name, `" over "` and the inner's, +and the chain is constructed from values by class template argument deduction, +as `over{formats::hex, formats::base64}` shows. It is constant time when +every link is, and secret when any link's operation is: the core runs the links' +secret arithmetic, and the intermediate is wiped by `secure::erase_secret`. + +=== Where the intermediate lives + +The intermediate, the bytes between the two links, is held: + +* *in place*, in the frame of each function of `over`, when its bound is known + at compile time: when the input's type states its size (a `std::array`, a + `std::span` of a static extent, a `secure::secret`, `text`, `bytes`) or + the value codec states `max_encoded_size`. There is no cap: the cost is the + stack, an array of the middle bound, the inner link's bound on the input's size + for an encode and the outer link's bound on the text's size for a decode, in + every level of a chain of chains; +* *on the heap*, from the allocator of `over`, for any other input. The third + template parameter of `over` is that allocator, `std::allocator` by default, + deduced from `over{outer, inner, allocator}`. A program that passes an input of a + static size and wants the intermediate on the heap passes it as a view of a + dynamic extent, a `std::span` or a `std::string_view`. + +The allocator of a result or a token is not the intermediate's, and the +allocator of `over` is used for nothing else. A heap intermediate makes the exact +`encoded_size` and `decoded_size`, which run the inner link into it, and +`encode` and `decode` allocate: those forms are not `noexcept`, an allocator's +exception reaches the caller, and on a secret chain every buffer is wiped +before it goes back. With a bound known at compile time they are `noexcept` and +allocate nothing, which the allocation test checks. + +=== One-shot, with a stream of links + +`over` is a format of the one-shot operations. Its transformers, +`codecs::encoder(chain)` and `codecs::decoder(chain)`, stream through a pipe of +the links' streams when both links stream natively (<>), and +are one-shot otherwise: a chain with base58 in it streams through `buffered`. + +=== Errors + +A fault of a link's configuration is the chain's, the outer link's first, and +every form reports it before it reads any data, in either link: a chain with +`formats::bech32` configured with a human-readable part of 84 characters +refuses every form with `invalid_prefix`. A data error of either link is the chain's: +the decode of `414` in the program is the outer link's, hex, odd length. + +A fault a link's encode has (bech32 with no human-readable part, the armor with +no label, the format's `encode_fault`) is the chain's too, before any token is +prepared: the inner link's in every form, and the outer link's on the +intermediate when the intermediate is in place, which the chain finds by running +the inner link into it. With a heap intermediate the outer link's is found by +its encode, after `prepare`: codecs' tokens are put back or untouched, and a +token of the program's own is left as `prepare` made it, as for a value codec's +own error. + +=== Pitfalls + +* The intermediate on the stack grows with the input's static size, and a chain + of chains has one in each level's frame. A program that puts a large array + through `over` passes a view of a dynamic extent to move the intermediate to + the heap. +* The inner link's output is bytes, and the outer reads them as bytes, whatever + the inner's text was. The armor over hex, as in the program of + <>, armors the hex text; a program that wants the armor of + the bytes themselves uses the armor alone. diff --git a/doc/formats.adoc b/doc/formats.adoc new file mode 100644 index 0000000..0c23808 --- /dev/null +++ b/doc/formats.adoc @@ -0,0 +1,400 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#codecs-formats] +== The formats + +Each section says what the format is, shows a program, and ends with what +catches a program that has not read the section. Every format is a value in +`webcpp::codecs::formats`, copyable, with a `name`; a format with options is +configured by a call that gives another value (`formats::hex(letter_case::upper)`), +so that a format is a constant a program names and never a type it builds. +The sections that follow say what every format shares: the tokens, the results, +the secret operations and the streams. + +A decode reads its whole text before it writes a byte, so that on every error +nothing is written; its buffer form leaves the bytes past the result as they +were. Which formats decode into the text's own storage, which the table in +<> lists, is a promise of the format's page and not of the +core: hex, base32 and base64 write byte `i` after the characters it comes from +are read, and base58, bech32, the armor and percent ask that the input and the +output do not overlap (percent's decode is Boost.URL's, which promises nothing +of overlapping buffers). + +[#codecs-hex] +=== hex + +hex, or base16 (RFC 4648 section 8), writes each byte as two hex digits, its +high nibble first. `formats::hex` writes lower case, and +`formats::hex(formats::letter_case::upper)` upper case, as the RFC does. +Decode takes either case, mixed included, and refuses a text of an odd length +with `invalid_length` and any character that is no hex digit with +`invalid_character`, which wins when both are found. It is constant time on +every call, one-shot and streamed, and streams natively: the encoder holds the +low digit of a byte its output had no room for, and the decoder one digit of a +pair. + +[source,cpp] +---- +include::{examples}/digest_hex.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/digest_hex.expected[] +---- + +*Pitfalls.* + +* Decode takes digits and nothing else: `0x` in front, a space between two + bytes and a trailing line feed are each `invalid_character`. Trim the text + before decoding it. +* A decode into a fixed type is exact. `decode>` + of 62 digits is `invalid_length`, not a shorter array. +* Constant time covers the data. The length of the text, the length of the + result and whether the call succeeded are public, as they are for every + format of codecs (<>). +* The bytes a stream decoder delivers before an error are no result: a caller + discards them (<>). + +[#codecs-base32] +=== base32 and base32hex + +`formats::base32` is RFC 4648 section 6's alphabet and `formats::base32hex` +section 7's. Each writes upper case and its padding, `=`, by default, and takes +the padding as an option: `formats::base32(formats::padding::omitted)`. Decode +is canonical. It takes the format's own alphabet in either case, the padding +the option says, and nothing else: a character of the other alphabet or a line +break is `invalid_character`, a length no encoding has is `invalid_length`, and +padding against the option, a `=` out of its place and non-zero bits at the end +of the last group are `invalid_padding`. + +[source,cpp] +---- +include::{examples}/rfc4648.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/rfc4648.expected[] +---- + +*Pitfalls.* + +* `MZ======` and `MZXW6Y==` have a valid length, so their error is + `invalid_padding`; `MZXW6YQ` with the padding written has none, and is + `invalid_length`. When a text has both, the lowest value wins. +* The two alphabets are not interchangeable: `base32hex` has the digits `0`, + `1`, `8` and `9`, which `base32` refuses. +* A padded stream decoder holds the bytes that the characters of a group's + fourth, fifth, seventh and eighth places give, since those places are `=` in + the last group of a short input, until the next character shows that the + group is not the last, or until `flush`. A stream that has delivered less + than the text seems to give is not stuck: it waits for the next character or + for `flush`. + +[#codecs-base64] +=== base64 and base64url + +`formats::base64` is RFC 4648 section 4's alphabet with its padding written; +`formats::base64url` is section 5's, with `-` and `_` and its padding omitted +by default, as JOSE and URLs write it. Each takes the other padding by option, +`formats::base64url(formats::padding::written)`. Decode is canonical, as base32's +is: only the format's alphabet, the padding of the option, and zero bits at the +end of the last group. `Zh==` is `invalid_padding` since `Zg==` is the +encoding of `f`, and a text with a line break or a space is `invalid_character`. Both +formats are constant time on every call, stream natively, and decode in place. +The program of the base32 section shows both alphabets of base64 beside +base32's: the default padding of each, the two symbols in which the alphabets +differ (`+/8=` and `-_8` for the bytes `fb ff`) and the canonical refusals. The +next program is the secret use, a key as base64. + +[source,cpp] +---- +include::{examples}/key_base64.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/key_base64.expected[] +---- + +*Pitfalls.* + +* PEM and MIME wrap base64 in lines; `formats::base64` refuses the line breaks. + PEM's own format is `formats::armor` (<>). +* A padded stream decoder holds the bytes that the characters of a group's + third and fourth places give, which are `=` in the last group of a short input, + until the next character or `flush`, as base32's does. +* A secret key goes through a `secure::secret`, which makes the operation + secret and the result a `secret_text`; the same call with a `std::vector` is + a public operation (<>). + +[#codecs-base58] +=== base58 + +base58 writes the bytes as one number in base 58, its digits in an alphabet of +58 characters and each leading zero byte as the alphabet's first character, as +Bitcoin Core's `EncodeBase58` does. The format is +`formats::basic_base58`, and `formats::base58` +is the one a program names for Bitcoin: 100 bytes of payload, Bitcoin's +alphabet, no checksum. The program shows each of the three parameters, and the +stream. + +[source,cpp] +---- +include::{examples}/base58_address.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/base58_address.expected[] +---- + +*The cost is quadratic, so the bound caps it.* Every digit depends on the whole +number, so the work grows with the square of the input's length; there is no +streaming form and no way around it. `MaximumBytes` is the payload's bound +without the checksum, 100 for `formats::base58`, and an input longer than it +and a text longer than `maximum_characters` (137 for 100 bytes) are +`input_too_long` by their length, before any read. A program that needs more +names a larger instance, `formats::basic_base58<1024, formats::bitcoin_alphabet>{}`; +a decode whose payload would be longer than `maximum_bytes` is +`input_too_long` too. + +*The scratch is in place, on the stack.* Every instance converts in an array +sized by its template, about one and a third bytes for each byte of the bound. +Nothing allocates, every size is exact, and the functions are `noexcept`: the +price is the stack, which a larger bound makes larger (about 1.4 KiB for 1024), +in every frame that converts. A secret conversion runs in the same scratch and +wipes it. + +*An alphabet of the program's own is a type.* It has a +`static constexpr std::string_view characters` of 58 characters, digit 0 first, +from which the tables are built at compile time. `basic_base58` stops the build +with a message that says an alphabet is 58 distinct characters when they are +not. The ones of the library are `bitcoin_alphabet`, `ripple_alphabet` and +`flickr_alphabet`, and the formats `base58_bitcoin`, `base58_ripple` and +`base58_flickr`, whose bound is 100 bytes. + +*The checksum is a parameter.* With `no_checksum`, the default, the payload is +the whole number. With a checksum type of the program's own, a +`static constexpr std::size_t size` and a `static void compute(payload, out)` +that is `noexcept`, encode appends `compute(payload)` to the payload before the +conversion, and decode splits the last `size` bytes off, recomputes the checksum +of the rest, compares the two with `secure::constant_time_equal` and gives the +payload without it. A mismatch is `checksum_mismatch`, and fewer decoded bytes +than the checksum's `size` are `invalid_length`. codecs defines no checksum +algorithm: webcpp::hash's `base58_with_checksum`, a format over its double +SHA-256, is what Bitcoin calls Base58Check, and the checksum of the program +above is a toy. A checksum's `compute` runs on secrets in a secret operation, +so it must be constant time, which the concept cannot check. + +*It is constant time only when the operation is secret.* A public operation +runs Bitcoin Core's conversion, with its early exits (`codec::constant_time` +is false). A secret one, with a `secure::secret` or a `secret_bytes` as the +input or a secret token as the destination, runs a conversion whose operations +depend on the length of the input alone, the alphabet read by +`secure::constant_time::lookup`, and the checksum compared inside the engaged +timing guard (`constant_time_when_secret` is true for every instance). The +length of the text and the success of the call are public. + +*Pitfalls.* + +* `formats::base58` refuses 101 bytes. It is a bound and not a bug; name the + larger instance. +* A secret input's result is a `secret_text` with `N` the bound for the + input's length, so that the text of a 32-byte key is held in 44 characters, + 42 of them here. +* A drain of `codecs::encoder(formats::base58)` does not compile: base58 has no + native stream, and the message names `codecs::buffered`. The program + streams through `buffered(encoder(format), codecs::capacity<100>)`, which + accumulates the input in place and converts at `flush`; an input past the + capacity is accepted and reported at `flush` as `input_too_long`. +* Input and output must not overlap. + +[#codecs-bech32] +=== bech32 and bech32m + +bech32 (BIP-173) and bech32m (BIP-350) write a human-readable part, the +separator `1`, the data in 5-bit groups and a checksum of six characters over +both, in an alphabet of 32 characters. `formats::bech32` and `formats::bech32m` +are the instances of 90 characters over bytes, and the human-readable part is +configured by a call and held in the format value: `formats::bech32("npub")`. +A format with none decodes any part, and encodes nothing: +`codecs::decode(formats::bech32, text)` gives +the part and the data of any text. Encode writes lower case; decode takes +either, not both (`mixed_case`). + +[source,cpp] +---- +include::{examples}/nostr_bech32.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/nostr_bech32.expected[] +---- + +*The maximum length is a template parameter.* `basic_bech32` +names the longest text, 90 by default, so that the scratch, the stream +decoder's hold and the results of every form are in place, sized from it, and +nothing allocates. A text past it is `input_too_long`, before it is read. A +Lightning invoice, which has no length limit of BIP-173's 90 characters, is +read by a larger instance (2048 in the program); `formats::bech32` reports +`input_too_long` for it, and its stream decoder has delivered nothing. The +shortest text is 8 characters, and a smaller `MaximumLength` stops the build. + +*A word is a 5-bit value, not a machine word.* In bytes mode, the default, the +data are bytes regrouped from 8 bits to 5 with zero padding, as BIP-173's +`convertbits` does, and decode refuses more than 4 padding bits or a non-zero +one with `invalid_padding`. In words mode, `format.words()`, each element is one +value from 0 to 31 written and read as it is, and a value above 31 is refused +on encode with `invalid_character`. `formats::append_words_from_bytes(words, bytes)` +regroups bytes into words after a word the program has put first, and +`formats::bytes_from_words(words, output)` regroups words back into bytes, in +constant time as the format is. + +*A segwit version is a word, never a byte.* This is the pitfall of the example: +BIP-350's Taproot address is the version word 1 followed by the program's +words, and the bytes mode of the same two values, the byte `0x01` and then the +program, is a different text, which is not the address. A program that builds +an address puts the version into a words-mode format first, `bech32` for +version 0 and `bech32m` above, and the same program takes the version back from +the first word of the decoded words. + +*What it leaves to webcpp::bitcoin.* codecs applies none of segwit's rules, the +versions, the sizes of the programs and the networks' prefixes, and parses none +of Lightning's fields: a segwit decoder checks the version and the program's +size, and a Lightning one reads the invoice's tagged fields from the words. A +future webcpp::bitcoin owns both. What codecs checks is the format: the +checksum, the case, the alphabet, the part, the length. + +*Pitfalls.* + +* The human-readable part of the format is a configuration, and a fault of it + (84 characters, or one outside 33 to 126) is `invalid_prefix`, reported + before any data is read, by the one-shot call and by the stream's first + call. +* A decode with a part other than the format's is `invalid_prefix` even when + the checksum is right; the format with no part is how a program reads any. +* The stream decoder holds the raw characters, up to the maximum length, and + delivers nothing before `flush` has checked the checksum: a program that + reads an invoice from a socket sees no byte until the last character. The + hold is `codecs::decoder(format, codecs::capacity)`, at most the + format's maximum length, which stops the build when it is more. +* The stream encoder writes the part and the data as it goes and the checksum at + `flush`. + +[#codecs-percent] +=== percent + +percent is percent-encoding (RFC 3986 section 2.1) over Boost.URL: each byte +outside a `CharSet` as `%` and two hex digits. `formats::percent` leaves the +unreserved characters as they are, and `formats::percent(char_set, options)` +takes any Boost.URL `CharSet`, `boost::urls::pchars` or a set of the program's +own built with `boost::urls::grammar::lut_chars`, and a +`boost::urls::encoding_opts`, which chooses the case of the digits and writes a +space as a plus sign. The sizes, encode and decode are Boost.URL's own, byte for +byte. It is the one header that includes Boost.URL, and a program that includes +it names `/webcpp/codecs//percent`, whose decode is compiled. + +[source,cpp] +---- +include::{examples}/percent_segment.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/percent_segment.expected[] +---- + +*Pitfalls.* + +* The `CharSet` is the characters left as they are, and each piece of a URL has + its own: a path segment `pchars`, a query value the same with + `+encoding_opts{true}+` for the plus sign, and a program that picks the default + `unreserved` set escapes more than a URL needs and never less. +* The percent sign is never in the set: it is written `%25` whatever the set + holds. +* Decode does not check that the characters it takes as they are belong to the + set. A text that holds a character the set would escape decodes to that + character; checking the text against a grammar is Boost.URL's parser's job. +* A `%` followed by a character that is no hex digit is `invalid_character`, + and a text that ends inside an escape is `invalid_length`; `%g` is both and + gets the lower value, `invalid_character`. +* percent is not constant time. A secret that must not leak through time is + written in a format that is. + +[#codecs-armor] +=== armor + +The armor is RFC 7468's strict textual encoding, which OpenSSL writes as PEM: +`-----BEGIN ` (`basic_secret_byte_vector` for bytes), `A` the allocator rebound to + the element; also callable with an allocator that it keeps (B40). + + @tparam Allocator The allocator of a heap result, `std::allocator` for the object `secret`. +*/ +template > +struct secret_t { + /** The operation is secret (D8). */ + static constexpr bool secret = true; + + /** The allocator a heap result is constructed with, rebound to its element. */ + Allocator allocator; + + /** + A tag that gives a heap result over `other`, which is used through `std::allocator_traits`. + + @tparam Other The type of the allocator. + @param other The allocator. + @return The tag. + */ + template + requires requires { typename std::allocator_traits::value_type; } + [[nodiscard]] constexpr secret_t operator()(Other const& other) const noexcept { + return secret_t{other}; + } +}; + +/** The tag `secret`: a secret result, or with an allocator `secret(allocator)`. */ +inline constexpr secret_t<> secret{}; + +/** + The tag that gives `N` elements in place: `text` from `encode`, `bytes` from `decode`. + + A value codec of bytes encodes into `bytes`. A result that does not fit is + @ref error::output_too_small. + + @tparam N The most elements. +*/ +template +struct fixed { + /** The most elements. */ + static constexpr std::size_t capacity = N; +}; + +} // namespace tokens + +namespace detail { + +/** + A token that appends the result to a string or a vector; its result is the container. + + `append_to` gives the token of a public operation; in a secret one the core converts through + `wiping()`, whose token wipes, by `secure::erase_secret`, the elements it takes back from the + container: all those appended when the conversion fails, the tail past the written count on + success. + + @tparam Container The string or the vector. + @tparam Wiped Whether the operation is secret. +*/ +template +class appending_token { +public: + /** The container, by reference, as Boost.URL's `append_to` gives it. */ + using result_type = Container&; + + /** Constructs a token that appends to `target`, which outlives it. */ + explicit appending_token(Container& target) noexcept : target_(&target) {} + + /** The token of a secret operation that appends to the same container. */ + [[nodiscard]] appending_token wiping() const noexcept { + return appending_token{*target_}; + } + + /** Grows the container by `size` elements and returns a pointer to the new ones. */ + [[nodiscard]] auto* prepare(std::size_t size) { + old_size_ = target_->size(); + target_->resize(saturating_add(old_size_, size)); + return target_->data() + old_size_; + } + + /** + Cuts the container to the `written` elements appended, the cut ones wiped when `Wiped`; the + core passes at most the count it prepared, so that the container only shrinks. + */ + void shrink_to(std::size_t written) noexcept { cut_to(old_size_ + written); } + + /** + Puts the container back as it was before `prepare`, the elements appended wiped when + `Wiped`. + */ + void abandon() noexcept { cut_to(old_size_); } + + /** The container. */ + [[nodiscard]] result_type result() noexcept { return *target_; } + +private: + /** + Cuts the container to `kept` elements, at most its size, wiping the others first when `Wiped`. + A string's or a vector's `resize` down to a smaller size erases the elements past it, bytes + or characters, and neither allocates nor throws. + */ + // NOLINTNEXTLINE(bugprone-exception-escape): a resize down cannot throw + void cut_to(std::size_t kept) noexcept { + BOOST_ASSERT(kept <= target_->size()); + if constexpr (Wiped) { + secure::erase_secret(std::span{*target_}.subspan(kept)); + } + target_->resize(kept); + } + + Container* target_; + std::size_t old_size_ = 0; +}; + +/** + The most elements of a scratch in place of an operation into `assign_to`: past it, or when the + bound is not known at compile time, the scratch is a container of the target's allocator (the + owner's ruling). +*/ +inline constexpr std::size_t in_place_scratch_limit = 4096; + +/** + A token that replaces the content of a string or a vector with the result, and leaves it as it + was when the operation fails (the owner's ruling): the conversion writes into a scratch, and the + container gets the result only on success, by one copy. + + Through the token contract, the scratch is a container of the target's own type and allocator, + which `prepare` allocates (an allocation that throws leaves the target untouched); `result` + copies it into the target, which keeps its buffer when it holds the result, and gives the + scratch back at once. When the bound is known at compile time and at most + `in_place_scratch_limit` elements, the core converts into a scratch in place instead and gives + the result to `assign`. `assign_to` gives the token of a public operation; in a secret one the + core converts through `wiping()`, whose token wipes the scratch, by `secure::erase_secret`, + before it gives it back, also when an allocation throws. + + @tparam Container The string or the vector. + @tparam Wiped Whether the operation is secret. +*/ +template +class assigning_token { +public: + /** The container, by reference, as Boost.URL's `assign_to` gives it. */ + using result_type = Container&; + + /** The element of the container: `char` or `std::uint8_t`. */ + using element_type = Container::value_type; + + /** Constructs a token that assigns to `target`, which outlives it. */ + explicit assigning_token(Container& target) noexcept : target_(&target) {} + + /** + A copy of a token takes its target alone and has no scratch: the scratch belongs to the + operation that prepared it, and a copy would duplicate an engaged secret one. The core copies + tokens that are not prepared yet. + */ + assigning_token(assigning_token const& other) noexcept : target_(other.target_) {} + + /** + A copy assignment takes the target of `other` and gives this token's own scratch back, + wiped when `Wiped`: it belonged to the old target's operation; `other` keeps its own. + */ + assigning_token& operator=(assigning_token const& other) noexcept { + if (this != &other) { + target_ = other.target_; + release_scratch(); + } + return *this; + } + + /** + A move takes the target alone, as a copy does: an engaged scratch stays with `other`, which + gives it back when it goes, so that none is dropped or duplicated. + */ + assigning_token(assigning_token&& other) noexcept : target_(other.target_) {} + + /** A move assignment takes the target alone, as the copy assignment does. */ + assigning_token& operator=(assigning_token&& other) noexcept { + if (this != &other) { + target_ = other.target_; + release_scratch(); + } + return *this; + } + + /** Gives the scratch back, wiped when `Wiped`, if the operation did not. */ + ~assigning_token() { release_scratch(); } + + /** The token of a secret operation that assigns to the same container. */ + [[nodiscard]] assigning_token wiping() const noexcept { + return assigning_token{*target_}; + } + + /** + Makes a scratch of `size` elements, of the target's allocator, and returns them; the target is + untouched. + */ + [[nodiscard]] element_type* prepare(std::size_t size) { + scratch_.emplace(target_->get_allocator()); + scratch_->resize(size); + return scratch_->data(); + } + + /** + Cuts the scratch to the `written` elements, the others wiped when `Wiped`; the core passes at + most the count it prepared, so that the scratch only shrinks, which neither allocates nor + throws. + */ + // NOLINTNEXTLINE(bugprone-exception-escape): a resize down cannot throw + void shrink_to(std::size_t written) noexcept { + BOOST_ASSERT(written <= scratch().size()); + if constexpr (Wiped) { + secure::erase_secret(std::span{scratch()}.subspan(written)); + } + scratch().resize(written); + } + + /** Gives the scratch back, wiped when `Wiped`: the target keeps its content. */ + void abandon() noexcept { release_scratch(); } + + /** + Copies the scratch into the target and gives it back, wiped when `Wiped`; when the copy's + allocation throws, the target is as it was. + */ + [[nodiscard]] result_type result() { + assign(std::span{scratch()}); + release_scratch(); + return *target_; + } + + /** + Replaces the content of the target with `written`, or leaves it as it was when the allocation + this needs throws: in the target's own buffer when it holds them, else in a new container of + its allocator, swapped in. + + @param written The elements of the result. + @return The target. + */ + result_type assign(std::span written) { + // Through pointers, which every standard library copies directly: an iterator of another + // type may be copied through a temporary container first (libc++ does so for a checked + // iterator), an unwiped copy of a secret. + element_type const* const first = written.data(); + element_type const* const last = first + written.size(); + if (written.size() <= target_->capacity()) { + target_->assign(first, last); + } else { + Container fresh(target_->get_allocator()); + fresh.assign(first, last); + target_->swap(fresh); + } + return *target_; + } + +private: + /** The scratch, which `prepare` made: the core calls `prepare` before every other member. */ + [[nodiscard]] Container& scratch() noexcept { + BOOST_ASSERT(scratch_.has_value()); + return *scratch_; + } + + /** Wipes the scratch's whole buffer when `Wiped` and gives it back, if there is one. */ + // NOLINTNEXTLINE(bugprone-exception-escape): a resize within the capacity cannot throw + void release_scratch() noexcept { + if constexpr (Wiped) { + if (scratch_) { + // Within the capacity: no allocation, and every element a part of the container. + scratch_->resize(scratch_->capacity()); + secure::erase_secret(*scratch_); + } + } + scratch_.reset(); + } + + Container* target_; + std::optional scratch_; +}; + +/** + The scratch in place of an operation into `assign_to` whose bound, `N`, is known at compile + time and at most `in_place_scratch_limit`: a token of `N` elements whose result is the elements + written, wiped when it goes when `Wiped`, a secret operation's. Its elements are not zeroed when + it is made: the conversion writes those it prepares before they are read. + + @tparam Element `char` or `std::uint8_t`. + @tparam N The most elements. + @tparam Wiped Whether the operation is secret. +*/ +template +class in_place_scratch { +public: + /** The elements written. */ + using result_type = std::span; + + /** The most elements. */ + static constexpr std::size_t capacity = N; + + /** An empty scratch, its elements not zeroed. */ + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read + in_place_scratch() noexcept = default; + + /** Not copyable: the elements are the operation's. */ + in_place_scratch(in_place_scratch const&) = delete; + /** Not copyable: the elements are the operation's. */ + in_place_scratch& operator=(in_place_scratch const&) = delete; + /** Not movable: the elements are the operation's. */ + in_place_scratch(in_place_scratch&&) = delete; + /** Not movable: the elements are the operation's. */ + in_place_scratch& operator=(in_place_scratch&&) = delete; + + /** Wipes the elements prepared, when `Wiped`. */ + ~in_place_scratch() { + if constexpr (Wiped) { + secure::erase_secret(std::span{elements_}.first(prepared_)); + } + } + + /** Returns `size` elements, which the core made sure fit. */ + [[nodiscard]] Element* prepare(std::size_t size) noexcept { + prepared_ = size; + written_ = size; + return elements_.data(); + } + + /** Keeps the `written` elements. */ + void shrink_to(std::size_t written) noexcept { written_ = written; } + + /** The elements written. */ + [[nodiscard]] result_type result() const noexcept { return {elements_.data(), written_}; } + +private: + std::array elements_; + std::size_t prepared_ = 0; + std::size_t written_ = 0; +}; + +/** Whether `T` is the token of `assign_to`. */ +template +inline constexpr bool is_assigning_token = false; + +/** The token of `assign_to`. */ +template +inline constexpr bool is_assigning_token> = true; + +/** Whether `T` is the token of `append_to` or `assign_to` of a public operation. */ +template +inline constexpr bool is_public_container_token = false; + +/** The token of `append_to` of a public operation. */ +template +inline constexpr bool is_public_container_token> = true; + +/** The token of `assign_to` of a public operation. */ +template +inline constexpr bool is_public_container_token> = true; + +/** + A token that gives a string of its own, made with the allocator it was constructed with. + + In a secret operation (`Wiped`) it wipes, by `secure::erase_secret`, what the caller does not get: + the characters written when the conversion fails, the tail past the written count, and what its + string still holds when it goes (a short string's characters stay in a moved-from one). + + @tparam String The string. + @tparam Wiped Whether the operation is secret. +*/ +template +class returning_token { +public: + /** The string. */ + using result_type = String; + + /** Constructs a token whose string is made with `allocator_value`. */ + explicit returning_token(String::allocator_type const& allocator_value) noexcept + : value_(allocator_value) {} + + /** Not copyable: the string is the operation's. */ + returning_token(returning_token const&) = delete; + /** Not copyable: the string is the operation's. */ + returning_token& operator=(returning_token const&) = delete; + /** Not movable: the token is the operation's. */ + returning_token(returning_token&&) = delete; + /** Not movable: the token is the operation's. */ + returning_token& operator=(returning_token&&) = delete; + + /** Wipes the whole buffer of the string, when `Wiped`. */ + // NOLINTNEXTLINE(bugprone-exception-escape): a resize within the capacity cannot throw + ~returning_token() { + if constexpr (Wiped) { + // Within the capacity: no allocation, and every character a part of the string. + value_.resize(value_.capacity()); + secure::erase_secret(value_); + } + } + + /** Resizes the string to `size` characters and returns a pointer to them. */ + [[nodiscard]] char* prepare(std::size_t size) { + value_.resize(size); + return value_.data(); + } + + /** Cuts the string to the `written` characters, the others wiped when `Wiped`. */ + void shrink_to(std::size_t written) { + if constexpr (Wiped) { + secure::erase_secret(std::span{value_}.subspan(written)); + } + value_.resize(written); + } + + /** Wipes the characters written, when `Wiped`: the caller gets none of them. */ + void abandon() noexcept { + if constexpr (Wiped) { + secure::erase_secret(value_); + } + } + + /** The string, moved out. */ + [[nodiscard]] result_type result() noexcept { return std::move(value_); } + +private: + String value_; +}; + +/** + A token that gives `text` or `bytes`: the elements in place, nothing allocated. + + The elements past the written count are zero, as the result's own are. In a secret operation + (`Wiped`) it wipes, by `secure::erase_secret`, the elements written when the conversion fails, the + tail past the written count, and its own copy of the result when it goes. + + @tparam Fixed `text` or `bytes`. + @tparam Wiped Whether the operation is secret. +*/ +template +class fixed_token { +public: + /** The fixed result. */ + using result_type = Fixed; + + /** The most elements. */ + static constexpr std::size_t capacity = Fixed::capacity(); + + /** A token of no elements. */ + fixed_token() noexcept = default; + + /** Not copyable: the elements are the operation's. */ + fixed_token(fixed_token const&) = delete; + /** Not copyable: the elements are the operation's. */ + fixed_token& operator=(fixed_token const&) = delete; + /** Not movable: the token is the operation's. */ + fixed_token(fixed_token&&) = delete; + /** Not movable: the token is the operation's. */ + fixed_token& operator=(fixed_token&&) = delete; + + /** Wipes the elements it holds, when `Wiped`. */ + ~fixed_token() { + if constexpr (Wiped) { + secure::erase_secret(fixed_access::writable(value_).first(held_)); + } + } + + /** Sets the size and returns a pointer to the elements, which the core made sure fit. */ + [[nodiscard]] auto* prepare(std::size_t size) noexcept { + held_ = size; + fixed_access::resize(value_, size); + return fixed_access::writable(value_).data(); + } + + /** Sets the size to the `written` elements, the others zeroed (wiped when `Wiped`). */ + void shrink_to(std::size_t written) noexcept { + auto const cut = fixed_access::writable(value_).subspan(written, held_ - written); + if constexpr (Wiped) { + secure::erase_secret(cut); + } else { + std::ranges::fill(cut, 0); + } + held_ = written; + fixed_access::resize(value_, written); + } + + /** Wipes the elements written, when `Wiped`: the caller gets none of them. */ + void abandon() noexcept { + if constexpr (Wiped) { + secure::erase_secret(fixed_access::writable(value_).first(held_)); + } + held_ = 0; + fixed_access::resize(value_, 0); + } + + /** The fixed result. */ + [[nodiscard]] result_type result() noexcept { return value_; } + +private: + Fixed value_{}; + std::size_t held_ = 0; +}; + +/** Whether `T` is a `return_string_t`. */ +template +inline constexpr bool is_return_string = false; + +/** A `return_string_t`. */ +template +inline constexpr bool is_return_string> = true; + +/** Whether `T` is a `tokens::fixed`. */ +template +inline constexpr bool is_fixed_tag = false; + +/** A `tokens::fixed`. */ +template +inline constexpr bool is_fixed_tag> = true; + +/** Whether `T` is a `tokens::secret_t`. */ +template +inline constexpr bool is_secret_tag = false; + +/** A `tokens::secret_t`. */ +template +inline constexpr bool is_secret_tag> = true; + +/** A tag of `codecs::tokens` that is no token of itself: the core makes the token of it. */ +template +concept token_tag = std::same_as || is_return_string || is_fixed_tag || + is_secret_tag; + +/** What `encode` and `decode` take as a token: a tag, or an object of the token contract. */ +template +concept token_argument = + token_tag> || byte_token>; + +/** + The concrete token of a `return_string`: the string made with the tag's allocator, rebound to + `char`, which wipes what the caller does not get when `Secret`. +*/ +template +[[nodiscard]] auto concrete_token(tokens::return_string_t const& tag_value) { + using string_allocator = std::allocator_traits::template rebind_alloc; + using string_type = std::basic_string, string_allocator>; + return returning_token{string_allocator{tag_value.allocator}}; +} + +/** + The concrete token of `fixed`: `text` for text, `bytes` for bytes, which wipes what the + caller does not get when `Secret`. +*/ +template +[[nodiscard]] auto concrete_token(tokens::fixed const& /*tag_value*/) noexcept { + if constexpr (Bytes) { + return fixed_token, Secret>{}; + } else { + return fixed_token, Secret>{}; + } +} + +/** + The token of `append_to` or `assign_to` in a secret operation: the one of the same container that + wipes what the container does not get. +*/ +template + requires(Secret && is_public_container_token) +[[nodiscard]] auto concrete_token(Token& token_object) noexcept { + return token_object.wiping(); +} + +/** A token that is one already: used as given. */ +template + requires(byte_token && !token_tag && + !(Secret && is_public_container_token)) +[[nodiscard]] constexpr Token& concrete_token(Token& token_object) noexcept { + return token_object; +} + +/** + The type of the concrete token of `Token`, the argument of the operation as it was passed, in an + operation that is secret when `Secret`. +*/ +template +using concrete_token_t = std::remove_cvref_t( + std::declval&>()))>; + +/** Whether using `Token`, a concrete token, cannot throw: its `prepare` and `result` do not. */ +template +inline constexpr bool token_is_noexcept = + noexcept(std::declval().prepare(std::size_t{0})) && + noexcept(std::declval().result()); + +} // namespace detail + +namespace tokens { + +/** + The tag that appends the result to `target`, a string of any traits and allocator. + + The string's own allocator is used. The operation returns `target` by reference, as Boost.URL's + does; the bytes of a decode are appended as characters. The input must not be a part of + `target`. In a secret operation the characters the string does not keep (all those appended when + the operation fails) are wiped before it is cut. + + @tparam Traits The string's character traits. + @tparam Allocator The string's allocator. + @param target The string to append to. + @return The token. +*/ +template +[[nodiscard]] auto append_to(std::basic_string& target) noexcept { + return detail::appending_token>{target}; +} + +/** + The tag that appends the bytes of a decode (or of a value codec of bytes) to `target`, a vector of + any allocator. + + The vector's own allocator is used. The operation returns `target` by reference. + + @tparam Allocator The vector's allocator. + @param target The vector to append to. + @return The token. +*/ +template +[[nodiscard]] auto append_to(std::vector& target) noexcept { + return detail::appending_token>{target}; +} + +/** + The tag that replaces the content of `target`, a string of any traits and allocator, with the + result. + + The string's own allocator is used. The operation returns `target` by reference, and leaves it as + it was when it fails, also after the conversion began (a value codec's own error) and when an + allocation throws: the conversion writes into a scratch, in place when the bound is known at + compile time and at most 4096 characters, else of the string's allocator (one allocation), and the + string gets the result only on success, by one copy, so that the input may be a part of + `target`. The string keeps its buffer when it holds the result. In a secret operation the scratch + is wiped before it is given back. + + @tparam Traits The string's character traits. + @tparam Allocator The string's allocator. + @param target The string to assign to. + @return The token. +*/ +template +[[nodiscard]] auto assign_to(std::basic_string& target) noexcept { + return detail::assigning_token>{target}; +} + +/** + The tag that replaces the content of `target`, a vector of any allocator, with the bytes of a + decode (or of a value codec of bytes). + + The vector's own allocator is used. The operation returns `target` by reference, and leaves it as + it was when it fails, as `assign_to` of a string does. + + @tparam Allocator The vector's allocator. + @param target The vector to assign to. + @return The token. +*/ +template +[[nodiscard]] auto assign_to(std::vector& target) noexcept { + return detail::assigning_token>{target}; +} + +} // namespace tokens + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_TOKENS_HPP diff --git a/include/webcpp/codecs/detail/core/transformer.hpp b/include/webcpp/codecs/detail/core/transformer.hpp new file mode 100644 index 0000000..0116630 --- /dev/null +++ b/include/webcpp/codecs/detail/core/transformer.hpp @@ -0,0 +1,254 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The conversion contract of webcpp::codecs (D17, D18): the two transformer concepts, one-shot and + stream, over elements of any type; the flow state and the step of the stream protocol; the tags + of a capacity in place and of a secret operation; and the traits the compositions read. +*/ +#ifndef WEBCPP_CODECS_DETAIL_CORE_TRANSFORMER_HPP +#define WEBCPP_CODECS_DETAIL_CORE_TRANSFORMER_HPP + +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace webcpp::codecs { + +/** + The state of a stream transformer after a call, beside its result and never an error (D18). + + "Receive again" and "send more" are the normal course of a stream, so they are not error codes: + a result's error is a real fault alone. +*/ +enum class flow : unsigned char { + /** Everything accepted is processed: send more, or flush. */ + needs_input = 1, + /** Output is waiting: receive it. */ + output_pending = 2, + /** Flushed and every output received: reset to start again. */ + finished = 3, +}; + +/** What a stream transformer's `send` or `receive` did: a count of elements and the state after. */ +struct step { + /** The elements `send` accepted, or the elements `receive` wrote. */ + std::size_t count; + /** The state after the call. */ + codecs::flow flow; +}; + +namespace detail { + +/** An element type of a transformer: a cv-unqualified object type of any kind. */ +template +concept transformer_element = std::is_object_v && std::same_as>; + +/** + The types both transformer concepts require: `T` is movable, and its `input_type` and + `output_type` are cv-unqualified object types (D17). +*/ +template +concept transformer_types = std::movable && requires { + typename T::input_type; + typename T::output_type; +} && transformer_element && transformer_element; + +} // namespace detail + +/** + A transformer that converts a whole input at once: `transform(input, output)` writes all of its + output and returns the count, or writes nothing and returns an error (D17). + + Its `input_type` and `output_type` are any cv-unqualified object types (a byte, a character, a + compressed packet, a decoded frame) and every transfer is a contiguous span of elements, read + from the caller's input and written into the caller's output. A short output is + @ref error::output_too_small, with nothing written. `transform` takes the transformer by + non-const reference, so that it may keep state between calls (a media encoder's context). A type + may add overloads of its own; the concept requires the span form alone, and assumes no bytes, + characters, constant time or secrecy. A moved-from `T` must still transform: `each` and `buffered` + move their transformer along with the rest of their state, and a moved-from one keeps calling the + `T` it was left holding, so a stateful move-only `T` has to leave its moved-from object able to + convert (the concept cannot check it). + + Optional members, read when present and never required: a static `max_output_size(std::size_t)`, + a bound on the output of that many input elements, constexpr where it can be (a bound of the + object's own, a non-static member, is not read, and `each` and `buffered` size such a + transformer's output by doubling), and `output_size(input)`, the exact size; + `static constexpr bool constant_time`, read through @ref is_constant_time_v. + + @tparam T The type to check. +*/ +template +concept one_shot_transformer = + detail::transformer_types && + requires(T& transformer, std::span input, + std::span output) { + { transformer.transform(input, output) } -> std::same_as>; + }; + +/** + A transformer that converts a stream: `send` gives it input, `receive` takes its output, `flush` + ends the input and `reset` starts again, with the protocol of D18. + + It starts in @ref flow::needs_input. `send(input)` in that state accepts a prefix of `input` and + returns how many elements it accepted with the state after; in any other state it accepts + nothing and returns `{0, state}`. The elements accepted stay the caller's, alive and unchanged, + until the transformer next reports @ref flow::needs_input or @ref flow::finished, or is reset or + destroyed: it reads them during `receive`, from the caller's input straight into the caller's + output. `receive(output)` writes up to `output.size()` elements and returns how many with the + state after; an empty span returns `{0, state}`. `flush()` ends the input and returns + @ref flow::output_pending while output remains and @ref flow::finished when none does; after it + nothing is accepted until `reset`. A fault of the data is reported once, after `flush`, by the + first call that has processed the whole input, and every call returns it until `reset`. + `reset()` returns the transformer to @ref flow::needs_input with nothing borrowed, nothing pending + and no error, and a moved-from transformer is in the state `reset` leaves, so that it converts a + new input from the start; the concept cannot check either, and every transformer of codecs keeps + both. + + The concept assumes no bytes, characters, constant time or secrecy; a type may satisfy it and + @ref one_shot_transformer both. + + @tparam T The type to check. +*/ +template +concept stream_transformer = detail::transformer_types && + requires(T& transformer, std::span input, + std::span output) { + { transformer.send(input) } -> std::same_as>; + { transformer.receive(output) } -> std::same_as>; + { transformer.flush() } -> std::same_as>; + { transformer.reset() } noexcept -> std::same_as; + }; + +/** + The tag of a capacity in place of `N` elements, which a composition takes instead of its default + (`pipe`'s intermediate, `drain`'s buffer) or of an allocator (`buffered`, `each`). + + @tparam N The capacity, in elements. +*/ +template +struct capacity_t { + /** The capacity, in elements. */ + static constexpr std::size_t value = N; +}; + +/** + A capacity in place of `N` elements: `codecs::pipe(first, second, codecs::capacity<64>)`. + + @tparam N The capacity, in elements. +*/ +template +inline constexpr capacity_t capacity{}; + +/** The tag that makes a transformer of a format secret: `encoder(format, secret_operation)`. */ +struct secret_operation_t { + /** Constructed by name only, so that `{}` never stands for it. */ + explicit secret_operation_t() = default; +}; + +/** The tag that makes a transformer of a format secret, wiped and under secure's timing guard. */ +inline constexpr secret_operation_t secret_operation{}; + +namespace detail { + +/** Whether `T` states `constant_time`, a constant. */ +template +concept states_constant_time = requires { + { std::bool_constant(T::constant_time)>{} }; +}; + +/** `T::constant_time` when `T` states it, else false. */ +template +constexpr bool constant_time_of() noexcept { + if constexpr (states_constant_time) { + return static_cast(T::constant_time); + } else { + return false; + } +} + +} // namespace detail + +/** + Whether a transformer of type `T` runs in a time that does not depend on its data: its + `static constexpr bool constant_time` when it states one, and false otherwise. + + @tparam T The transformer's type; a reference and `const` are ignored. +*/ +template +inline constexpr bool is_constant_time_v = detail::constant_time_of>(); + +/** + The default capacity in place of a composition's buffer of elements of type `Element`: 512 bytes, + at least one element (B32). + + @tparam Element The buffer's element type. +*/ +template +inline constexpr std::size_t default_capacity_v = + sizeof(Element) >= 512 ? 1 : 512 / sizeof(Element); + +namespace detail { + +/** + Whether elements of `From` are read as elements of `To` with no copy: the same type, or both + one-byte character or byte types (`char`, `unsigned char`, which is `std::uint8_t`, and + `std::byte`), as `over` reads text as bytes (D19). +*/ +template +concept compatible_elements = std::same_as || (byte_element && byte_element); + +/** + Whether `T` states a bound on its output, `T::max_output_size(std::size_t)`, a static member: a + bound of the object's own (a non-static member, which a configured format's may be) is not one. +*/ +template +concept has_max_output_size = requires(std::size_t input_size) { + { T::max_output_size(input_size) } -> std::convertible_to; +}; + +/** + Whether `T` states its bound for `InputSize` input elements as a constant expression, which an + in-place storage sizes itself by: `each` reads it at one element, `buffered` at its capacity, + where a bound constant at one element may not be. +*/ +template +concept has_constant_max_output_size = has_max_output_size && requires { + typename std::integral_constant; +}; + +/** + How a composition that holds a one-shot transformer (`buffered`, `each`) asks it for the fault of + its configuration, which it reports from its first call, before any data: none for a transformer + that has no configuration; a format's transformer gives its format's (format_transformer.hpp). + + @tparam T The transformer's type. +*/ +template +struct transformer_configuration_probe { + /** + The fault of `transformer`'s configuration. + + @return `std::nullopt`. + */ + [[nodiscard]] static constexpr std::optional fault(T const& /*transformer*/) noexcept { + return std::nullopt; + } +}; + +} // namespace detail + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_DETAIL_CORE_TRANSFORMER_HPP diff --git a/include/webcpp/codecs/detail/formats/armor.hpp b/include/webcpp/codecs/detail/formats/armor.hpp new file mode 100644 index 0000000..e2f6c8f --- /dev/null +++ b/include/webcpp/codecs/detail/formats/armor.hpp @@ -0,0 +1,602 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The arithmetic of the armor (RFC 7468's strict textual encoding), which its codec and stream codec + share (``): the label's grammar, the sizes, the writing of the boundaries + and of the base64 lines, and the reader, one character at a time, that both decode forms run, so + that the stream gives the one-shot form's bytes and error for every input. + + The armor's structure is public (B45, D12): its line endings, the optional final line ending, the + boundary lines and their positions, and the label. Its payload is base64 (RFC 4648 section 4, + padded), read and written by the arithmetic of `detail/formats/base64.hpp`, by masks alone. The + reader never decides in the open whether a character of the payload is a line ending: it takes + the boundaries from the first line and from the last, and the lines between them from their + positions, a line ending where the format writes one, after 64 symbols; a line feed where a + symbol is (a line shorter than 64 before the last) is a mask, declassified with the verdict. +*/ +#ifndef WEBCPP_CODECS_DETAIL_FORMATS_ARMOR_HPP +#define WEBCPP_CODECS_DETAIL_FORMATS_ARMOR_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs::detail { + +/** The most characters of a label the format holds (B25). */ +inline constexpr std::size_t armor_longest_label = 64; + +/** The start of the pre-encapsulation boundary, before the label. */ +inline constexpr std::string_view armor_begin_prefix = "-----BEGIN "; + +/** The start of the post-encapsulation boundary, before the label. */ +inline constexpr std::string_view armor_end_prefix = "-----END "; + +/** The end of both boundaries, after the label. */ +inline constexpr std::string_view armor_boundary_suffix = "-----"; + +/** The symbols of a whole line of the payload. */ +inline constexpr std::size_t armor_line_symbols = 64; + +/** The bytes of a whole line of the payload: 64 symbols, 16 groups of three bytes. */ +inline constexpr std::size_t armor_line_bytes = 48; + +/** + Whether a character is RFC 7468's `labelchar`: a printable character of 0x21 to 0x7E other than + `-`. + + @param character The character, which is public. + @return Whether it is one. +*/ +[[nodiscard]] constexpr bool armor_is_label_character(char character) noexcept { + auto const code = static_cast(character); + return code >= 0x21 && code <= 0x7e && character != '-'; +} + +/** + Whether `label` is a label of RFC 7468's grammar, not empty and of 64 characters at most (B25): + `labelchar`s, any two of which may be separated by one `-` or one space. + + @param label The label, which is public. + @return Whether it is one. +*/ +[[nodiscard]] constexpr bool armor_label_is_valid(std::string_view label) noexcept { + if (label.empty() || label.size() > armor_longest_label || + !armor_is_label_character(label.front()) || !armor_is_label_character(label.back())) { + return false; + } + bool after_separator = false; + for (char const character : label) { + if (armor_is_label_character(character)) { + after_separator = false; + } else if ((character == '-' || character == ' ') && !after_separator) { + after_separator = true; + } else { + return false; + } + } + return true; +} + +/** + The characters of a boundary line with a label of `label_size` characters, its line feed + included. + + @param prefix The boundary's start, `armor_begin_prefix` or `armor_end_prefix`. + @param label_size The label's characters. + @return The characters. +*/ +[[nodiscard]] constexpr std::size_t armor_boundary_size(std::string_view prefix, + std::size_t label_size) noexcept { + return prefix.size() + label_size + armor_boundary_suffix.size() + 1; +} + +/** + The exact size of the armor of `byte_count` bytes with a label of `label_size` characters: the + two boundaries, and the padded base64 of the bytes in lines of 64 characters, each ended by a line + feed. + + @param label_size The label's characters, at most 64. + @param byte_count The bytes. + @return The characters, `SIZE_MAX` when they do not fit in `std::size_t`. +*/ +[[nodiscard]] constexpr std::size_t armor_text_size(std::size_t label_size, + std::size_t byte_count) noexcept { + std::size_t const symbols = base64_text_size(byte_count, true); + if (symbols == size_maximum) { + return size_maximum; + } + std::size_t const line_feeds = (symbols / armor_line_symbols) + + static_cast(symbols % armor_line_symbols != 0); + std::size_t const boundaries = armor_boundary_size(armor_begin_prefix, label_size) + + armor_boundary_size(armor_end_prefix, label_size); + if (symbols > size_maximum - line_feeds - boundaries) { + return size_maximum; + } + return symbols + line_feeds + boundaries; +} + +/** + Writes a boundary line: its start, the label, `-----` and a line feed. + + @param prefix The boundary's start. + @param label The label. + @param output Exactly the boundary's room. +*/ +constexpr void armor_write_boundary(std::string_view prefix, std::string_view label, + std::span output) noexcept { + std::size_t position = 0; + for (std::string_view const piece : {prefix, label, armor_boundary_suffix}) { + for (char const character : piece) { + output[position++] = character; + } + } + output[position] = '\n'; +} + +/** + The character at `index` of a boundary line, its line feed last. + + @param prefix The boundary's start. + @param label The label. + @param index The place, below the boundary's size. + @return The character. +*/ +[[nodiscard]] constexpr char armor_boundary_character(std::string_view prefix, + std::string_view label, + std::size_t index) noexcept { + if (index < prefix.size()) { + return prefix[index]; + } + index -= prefix.size(); + if (index < label.size()) { + return label[index]; + } + index -= label.size(); + if (index < armor_boundary_suffix.size()) { + return armor_boundary_suffix[index]; + } + return '\n'; +} + +/** + Writes the armor of `input_bytes`: the BEGIN boundary, the padded base64 of the bytes in lines of + 64 characters, 48 bytes a line, each ended by a line feed, and the END boundary. + + @param label The label, valid and not empty. + @param input_bytes The bytes, which may be secret. + @param output_characters Exactly the armor's room, as `armor_text_size` gives it. +*/ +constexpr void armor_encode_text(std::string_view label, std::span input_bytes, + std::span output_characters) noexcept { + std::size_t const begin_size = armor_boundary_size(armor_begin_prefix, label.size()); + armor_write_boundary(armor_begin_prefix, label, output_characters.first(begin_size)); + std::size_t position = begin_size; + for (std::size_t byte_index = 0; byte_index < input_bytes.size(); + byte_index += armor_line_bytes) { + std::span const line_bytes = input_bytes.subspan( + byte_index, (std::min)(armor_line_bytes, input_bytes.size() - byte_index)); + std::size_t const line_size = base64_text_size(line_bytes.size(), true); + base64_encode_bytes(line_bytes, output_characters.subspan(position, line_size), + true); + position += line_size; + output_characters[position++] = '\n'; + } + armor_write_boundary(armor_end_prefix, label, output_characters.subspan(position)); +} + +/** + The reader of an armor, one character at a time, which the one-shot decode and the stream decoder + both run, so that they agree on every input. + + The first line, to its line feed, is the BEGIN boundary, held and checked when its line feed + comes. Every character after it enters a window of the last 82 characters, which at the end holds + the END boundary (78 characters at most), the final line ending and the one before the END line; + a character the window pushes out is the payload's, read at its place in its line: a line ending + after 64 symbols (a line feed, or a carriage return and a line feed), a symbol everywhere else, by + masks. At the end, @ref locate_end takes the END boundary from the window's last line, and the + window's characters before its line ending are read as the others were (@ref read_window); then + @ref close checks the last line, and @ref verdict gives the fault or the count of bytes. + + The faults, in their order: the boundaries' (a missing or malformed boundary, a label outside RFC + 7468's grammar or other than the format's, an END label other than the BEGIN label), each + @ref error::invalid_prefix and public; then the lines' (a line longer than 64 characters, a line + shorter than 64 before the last, an empty one), each @ref error::invalid_length and public but for + a line feed where a symbol is, a mask; then base64's own, its reader's verdict over the symbols + (@ref error::invalid_character, @ref error::invalid_length, @ref error::invalid_padding). The + armor's structure comes before its payload, as a configuration comes before data: it is public, + and a text whose structure is not the format's is not read as base64. + + The symbols reach the caller's sink with the column of their base64 group (`sink(byte, column)`, + the byte the character completes at columns 1 to 3, as base64's reader gives it), so that a stream + delivers them and the one-shot form writes them. +*/ +class armor_reader { +public: + /** The characters the window holds: the END boundary, the final line ending and the one before. + */ + static constexpr std::size_t window_size = 82; + + /** The characters of the BEGIN line held: its start, the longest label, its end, a return. */ + static constexpr std::size_t begin_hold = 81; + + /** + A reader at the start of a text, which accepts the label `expected_label`, or any when it is + empty. + + @param expected_label The format's label, valid or empty. + */ + explicit constexpr armor_reader(std::string_view expected_label) noexcept + : expected_(expected_label) {} + + /** + Reads a character of the input. + + @param character The character, which may be secret when it is a symbol of the payload. + @param sink Called with each byte a symbol pushed out of the window gives, and its column. + */ + template + void read(char character, Sink& sink) noexcept { + if (!in_body_) { + read_begin(character); + return; + } + if (window_count_ < window_size) { + state_.window[(window_start_ + window_count_) % window_size] = character; + ++window_count_; + return; + } + char const oldest = state_.window[window_start_]; + state_.window[window_start_] = character; + window_start_ = (window_start_ + 1) % window_size; + pushed_out_ = true; + read_payload(oldest, sink); + } + + /** + At the end of the input: finds the END boundary in the window's last line and checks it, and + how many of the window's characters are the payload's, before the line ending that precedes + the END line. + */ + void locate_end() noexcept { + if (!in_body_) { + prefix_fault_ = true; + return; + } + std::size_t end = window_count_; + if (end > 0 && window_at(end - 1) == '\n') { + --end; + if (end > 0 && window_at(end - 1) == '\r') { + --end; + } + } + std::size_t start = end; + while (start > 0 && window_at(start - 1) != '\n') { + --start; + } + if (start > 0) { + preceded_ = true; + std::size_t ending = start - 1; + if (ending > 0) { + // The line ending's form is public (B45): for a last line ended by a line feed + // alone, the character before it is a symbol, of which only "is it a carriage + // return" passes declassify, as one value. + auto return_mask = static_cast(secure::constant_time::is_equal_mask( + unsigned{static_cast(window_at(ending - 1))}, unsigned{'\r'})); + secure::declassify(return_mask); + if (return_mask != 0) { + --ending; + } + } + payload_in_window_ = ending; + } else if (pushed_out_) { + // The END line is longer than the window: no END boundary of the format. + prefix_fault_ = true; + } + if (!end_line_matches(start, end)) { + prefix_fault_ = true; + } + } + + /** + The window's characters that are the payload's, after @ref locate_end. + + @return Their count, which is public. + */ + [[nodiscard]] constexpr std::size_t window_payload() const noexcept { + return payload_in_window_; + } + + /** + Reads the window's payload character at `index`, after @ref locate_end. + + @param index The place, below @ref window_payload. + @param sink As for @ref read. + */ + template + void read_window(std::size_t index, Sink& sink) noexcept { + read_payload(window_at(index), sink); + } + + /** Checks the last line of the payload, after the window's payload is read. */ + constexpr void close() noexcept { + if (in_body_ && preceded_ && (column_ == 0 || after_return_)) { + length_fault_ = true; + } + } + + /** + The verdict over the whole text, once @ref close has run, which is + @ref error::invalid_prefix for a fault of the boundaries, else @ref error::invalid_length for + one of the lines, else base64's verdict over the symbols; for a valid text, the count of bytes. + + The lines' mask passes through `secure::declassify` as one value (the structure is public); + base64's reader declassifies its own verdict and, for a valid text, its count of `=`. + + @return The count of bytes, or the fault. + */ + [[nodiscard]] result verdict() const noexcept { + if (prefix_fault_) { + return error::invalid_prefix; + } + std::uint8_t line_fault = state_.line_fault; + secure::declassify(line_fault); + if (length_fault_ || line_fault != 0) { + return error::invalid_length; + } + result const padding_count = reader_.verdict(); + if (!padding_count) { + return padding_count.error(); + } + // Read unchecked: the error was returned above. + return base64_max_byte_size(symbols_) - padding_count.unsafe_value(); + } + + /** + The symbols read, which is public. + + @return Their count. + */ + [[nodiscard]] constexpr std::size_t symbols() const noexcept { return symbols_; } + + /** + The label of the BEGIN line, valid while the reader is. + + @return The label, empty when the BEGIN line has a fault or was not read. + */ + [[nodiscard]] constexpr std::string_view label() const noexcept { + return {begin_.data() + armor_begin_prefix.size(), label_size_}; + } + + /** Wipes what may be secret: the window, the masks and base64's state. */ + void wipe() noexcept { + secure::erase_secret(std::span{&state_, 1}); + reader_.wipe(); + } + + /** Back to the start of a text; the expected label stays. */ + constexpr void reset() noexcept { + in_body_ = false; + begin_ = {}; + begin_count_ = 0; + begin_overflowed_ = false; + label_size_ = 0; + prefix_fault_ = false; + length_fault_ = false; + column_ = 0; + after_return_ = false; + symbols_ = 0; + reader_.reset(); + state_ = secret_state{}; + window_start_ = 0; + window_count_ = 0; + pushed_out_ = false; + preceded_ = false; + payload_in_window_ = 0; + } + +private: + /** What the reader holds that may be secret, wiped as one. */ + struct secret_state { + /** The last characters after the BEGIN line, a ring from `window_start_`. */ + std::array window{}; + /** All ones once a line feed was read where a symbol is. */ + std::uint8_t line_fault = 0; + /** All ones when the last symbol read was a carriage return. */ + std::uint8_t return_before = 0; + }; + + /** + The window's character at `index` from its oldest. + + @param index The place, below `window_count_`. + @return The character. + */ + [[nodiscard]] constexpr char window_at(std::size_t index) const noexcept { + return state_.window[(window_start_ + index) % window_size]; + } + + /** A character of the BEGIN line, which is public; its line feed ends it. */ + constexpr void read_begin(char character) noexcept { + if (character == '\n') { + check_begin(); + in_body_ = true; + return; + } + if (begin_count_ < begin_hold) { + begin_[begin_count_++] = character; + } else { + begin_overflowed_ = true; + } + } + + /** Checks the BEGIN line: its start, a label of the grammar and the format's, its end. */ + constexpr void check_begin() noexcept { + std::string_view line{begin_.data(), begin_count_}; + if (!line.empty() && line.back() == '\r') { + line.remove_suffix(1); + } + std::size_t const frame = armor_begin_prefix.size() + armor_boundary_suffix.size(); + if (begin_overflowed_ || line.size() < frame || !line.starts_with(armor_begin_prefix) || + !line.ends_with(armor_boundary_suffix)) { + prefix_fault_ = true; + return; + } + std::string_view begin_label = line; + begin_label.remove_prefix(armor_begin_prefix.size()); + begin_label.remove_suffix(armor_boundary_suffix.size()); + if (!armor_label_is_valid(begin_label) || + (!expected_.empty() && begin_label != expected_.view())) { + prefix_fault_ = true; + return; + } + label_size_ = begin_label.size(); + } + + /** + Whether the window's characters `[start, end)` are the END boundary of the BEGIN line's label. + + @param start The END line's first place. + @param end The place after its last character. + @return Whether they are. + */ + [[nodiscard]] constexpr bool end_line_matches(std::size_t start, + std::size_t end) const noexcept { + std::string_view const begin_label = label(); + std::size_t const size = armor_boundary_size(armor_end_prefix, begin_label.size()) - 1; + if (end - start != size) { + return false; + } + for (std::size_t index = 0; index < size; ++index) { + if (window_at(start + index) != + armor_boundary_character(armor_end_prefix, begin_label, index)) { + return false; + } + } + return true; + } + + /** + A character of the payload at its place: a line ending after 64 symbols, else a symbol, read + by masks into base64's reader. + */ + template + void read_payload(char character, Sink& sink) noexcept { + if (after_return_) { + after_return_ = false; + if (character == '\n') { + column_ = 0; + return; + } + // A carriage return with no line feed after it: the line is longer than 64. + length_fault_ = true; + column_ = 0; + } else if (column_ == armor_line_symbols) { + if (character == '\n') { + // A line feed after a carriage return among the symbols: a line of 63 or fewer, + // ended by a carriage return and a line feed, before the last. + state_.line_fault = + static_cast(state_.line_fault | state_.return_before); + column_ = 0; + return; + } + if (character == '\r') { + after_return_ = true; + return; + } + // A 65th character: the line is longer than 64; the character starts the next. + length_fault_ = true; + column_ = 0; + } + auto const code = static_cast(static_cast(character)); + state_.line_fault = static_cast( + state_.line_fault | secure::constant_time::is_equal_mask(code, unsigned{'\n'})); + state_.return_before = + static_cast(secure::constant_time::is_equal_mask(code, unsigned{'\r'})); + unsigned const group_column = reader_.column(); + std::uint8_t const byte = reader_.read(character); + sink(byte, group_column); + ++column_; + ++symbols_; + } + + /** The format's label, or none. */ + bounded_label expected_; + /** Whether the BEGIN line's line feed was read. */ + bool in_body_ = false; + /** The BEGIN line, public. */ + std::array begin_{}; + /** How many characters of the BEGIN line are held. */ + std::size_t begin_count_ = 0; + /** Whether the BEGIN line was longer than its hold. */ + bool begin_overflowed_ = false; + /** The label's characters, after the BEGIN line's start; 0 for a BEGIN line with a fault. */ + std::size_t label_size_ = 0; + /** A fault of a boundary. */ + bool prefix_fault_ = false; + /** A fault of a line found at a line ending's place. */ + bool length_fault_ = false; + /** The characters of the current line read, 0 to 64: public. */ + std::size_t column_ = 0; + /** Whether a carriage return was read at a line ending's place. */ + bool after_return_ = false; + /** The symbols read: public. */ + std::size_t symbols_ = 0; + /** base64's state over the symbols. */ + base64_reader reader_{true}; + /** The window and the masks. */ + secret_state state_{}; + /** The window's oldest place. */ + std::size_t window_start_ = 0; + /** How many characters the window holds. */ + std::size_t window_count_ = 0; + /** Whether a character was pushed out of the window. */ + bool pushed_out_ = false; + /** Whether a line ending precedes the END line in the window. */ + bool preceded_ = false; + /** The window's characters that are the payload's. */ + std::size_t payload_in_window_ = 0; +}; + +/** + Reads the whole `text_characters` through `reader`, from the state `reset` leaves, and its end: + every character, the END boundary, the window's payload and the last line. + + @param reader The reader. + @param text_characters The text. + @param sink As for `armor_reader::read`. +*/ +template +void armor_read_text(armor_reader& reader, std::string_view text_characters, Sink& sink) noexcept { + for (char const text_character : text_characters) { + reader.read(text_character, sink); + } + reader.locate_end(); + for (std::size_t index = 0; index < reader.window_payload(); ++index) { + reader.read_window(index, sink); + } + reader.close(); +} + +} // namespace webcpp::codecs::detail + +#endif // WEBCPP_CODECS_DETAIL_FORMATS_ARMOR_HPP diff --git a/include/webcpp/codecs/detail/formats/base32.hpp b/include/webcpp/codecs/detail/formats/base32.hpp new file mode 100644 index 0000000..4925c1d --- /dev/null +++ b/include/webcpp/codecs/detail/formats/base32.hpp @@ -0,0 +1,463 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The arithmetic of base32 and base32hex, which their codec and stream codec share + (``): a 5-bit value to its symbol and a symbol to its 5-bit value by + webcpp::secure's constant-time blocks, as base64's 6-bit ones are, with no table indexed by a data + byte and no branch on one, the 5-byte group to its 8 symbols, and the decoder's state machine, one + character at a time, whose verdict is accumulated over the whole text and passes through + `secure::declassify` before its one branch (D12). + + The two alphabets differ in where their digits and letters lie alone, so that one template, by a + flag, is the implementation of both formats (RFC 4648's section 6 and section 7). +*/ +#ifndef WEBCPP_CODECS_DETAIL_FORMATS_BASE32_HPP +#define WEBCPP_CODECS_DETAIL_FORMATS_BASE32_HPP + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace webcpp::codecs::detail::base32_arithmetic { + +/** + The symbol of a 5-bit value: `A` to `Z` for 0 to 25 and `2` to `7` for 26 to 31, or, for the + extended hex alphabet, `0` to `9` for 0 to 9 and `A` to `V` for 10 to 31, chosen by masks with no + table and no branch. + + @tparam Hex Whether the alphabet is the extended hex one of RFC 4648 section 7. + @param five_bits A value of 0 to 31, which may be secret; a value above 31 gives the symbol `\0`. + @return The symbol. +*/ +template +[[nodiscard]] constexpr std::uint8_t symbol_of(std::uint8_t five_bits) noexcept { + // In unsigned, a mask word of secure's that no promotion turns signed. + auto const value = static_cast(five_bits); + constexpr unsigned boundary = Hex ? 10U : 26U; + // The symbol of a value is its value plus an offset, which wraps, for the run it is in. + constexpr unsigned first_offset = Hex ? unsigned{'0'} : unsigned{'A'}; + constexpr unsigned second_offset = Hex ? unsigned{'A'} - 10U : unsigned{'2'} - 26U; + auto const first_mask = secure::constant_time::is_less_mask(value, boundary); + auto const second_mask = secure::constant_time::is_in_range_mask(value, boundary, 31U); + // A run whose mask is clear contributes nothing, whatever the wrapped sum it was given. + unsigned const symbol = + (first_mask & (first_offset + value)) | (second_mask & (second_offset + value)); + return static_cast(symbol); +} + +/** + The 5-bit value of a symbol, and a mask of whether it is no symbol of the alphabet, by masks over + its byte value with no table and no branch. Either case is a symbol (B13). The byte is read as + unsigned first, so that a `char` from 0x80 up, negative where `char` is signed, lands in no range. + `=` is no symbol here: the padding is the format's to read. + + @tparam Hex Whether the alphabet is the extended hex one of RFC 4648 section 7. + @param symbol The byte of the character, which may be secret. + @param error_mask Set to all ones when `symbol` is no symbol of the alphabet; left as it was + otherwise. + @return The value, 0 for a byte that is no symbol. +*/ +template +[[nodiscard]] constexpr std::uint8_t five_bits_of(std::uint8_t symbol, + std::uint8_t& error_mask) noexcept { + auto const code = static_cast(symbol); + // The letters run from `A` to `Z` (to `V`, the 32nd symbol, in the hex alphabet); the digits + // from `2` to `7` after them (from `0` to `9` before them). + constexpr unsigned last_letter = Hex ? unsigned{'V'} : unsigned{'Z'}; + constexpr unsigned first_digit = Hex ? unsigned{'0'} : unsigned{'2'}; + constexpr unsigned last_digit = Hex ? unsigned{'9'} : unsigned{'7'}; + constexpr unsigned letter_value = Hex ? 10U : 0U; + constexpr unsigned digit_value = Hex ? 0U : 26U; + auto const upper_mask = + secure::constant_time::is_in_range_mask(code, unsigned{'A'}, last_letter); + auto const lower_mask = secure::constant_time::is_in_range_mask( + code, unsigned{'a'}, last_letter - unsigned{'A'} + unsigned{'a'}); + auto const digit_mask = secure::constant_time::is_in_range_mask(code, first_digit, last_digit); + unsigned const value = (upper_mask & (code - unsigned{'A'} + letter_value)) | + (lower_mask & (code - unsigned{'a'} + letter_value)) | + (digit_mask & (code - first_digit + digit_value)); + unsigned const symbol_mask = upper_mask | lower_mask | digit_mask; + error_mask = static_cast(error_mask | static_cast(~symbol_mask)); + return static_cast(value); +} + +} // namespace webcpp::codecs::detail::base32_arithmetic + +namespace webcpp::codecs::detail { + +/** The padding character of RFC 4648 section 3.2. */ +inline constexpr char base32_padding_character = '='; + +/** How many bytes a group holds, and how many characters it is written as. */ +inline constexpr std::size_t base32_group_bytes = 5; +/** How many characters a group of five bytes is written as. */ +inline constexpr std::size_t base32_group_characters = 8; + +/** + The symbols of a group of one to five bytes: the bytes' bits taken five at a time, the last + symbol's missing bits zero, written as `(8 * group_bytes.size() + 4) / 5` symbols (2, 4, 5, 7 or 8) + at the start of `symbols`. + + @tparam Hex Whether the alphabet is the extended hex one. + @param group_bytes One to five bytes, which may be secret; their count is public. + @param symbols Room for the symbols of the group at least; the ones past them are left as they + were. + @return The symbols written: 2, 4, 5, 7 or 8. +*/ +template +constexpr std::size_t base32_group_symbols(std::span group_bytes, + std::span symbols) noexcept { + std::uint64_t bits = 0; + for (std::size_t index = 0; index < base32_group_bytes; ++index) { + bits = (bits << 8U) | (index < group_bytes.size() ? std::uint64_t{group_bytes[index]} : 0U); + } + std::size_t const count = ((8 * group_bytes.size()) + 4) / 5; + for (std::size_t index = 0; index < count; ++index) { + auto const five_bits = static_cast((bits >> (35U - (5U * index))) & 31U); + symbols[index] = static_cast(base32_arithmetic::symbol_of(five_bits)); + } + // Nothing of the group stays in a temporary but this word, which the caller's bytes made. + return count; +} + +/** + The characters of the last group of one to four bytes, its padding `=` written when the format + writes it. + + @tparam Hex Whether the alphabet is the extended hex one. + @param group_bytes One to four bytes, which may be secret. + @param padded Whether the padding is written, which is public. + @param characters Room for the characters of the group: 8 when padded, else 2, 4, 5 or 7. + @return The characters of the group: 8 when padded, else 2, 4, 5 or 7. +*/ +template +constexpr std::size_t base32_last_group(std::span group_bytes, bool padded, + std::span characters) noexcept { + std::size_t const symbol_count = base32_group_symbols(group_bytes, characters); + if (!padded) { + return symbol_count; + } + for (std::size_t index = symbol_count; index < base32_group_characters; ++index) { + characters[index] = base32_padding_character; + } + return base32_group_characters; +} + +/** + Writes the text of `input_bytes`: eight characters for each group of five bytes, then the last + group of one to four bytes as @ref base32_last_group gives it. + + @tparam Hex Whether the alphabet is the extended hex one. + @param input_bytes The bytes, which may be secret. + @param output_characters The text, exactly as many characters as the format writes for the bytes. + @param padded Whether the padding is written. +*/ +template +constexpr void base32_encode_bytes(std::span input_bytes, + std::span output_characters, bool padded) noexcept { + std::size_t byte_index = 0; + std::size_t character_index = 0; + for (; input_bytes.size() - byte_index >= base32_group_bytes; + byte_index += base32_group_bytes, character_index += base32_group_characters) { + static_cast(base32_group_symbols( + input_bytes.subspan(byte_index, base32_group_bytes), + output_characters.subspan(character_index).template first())); + } + // The last group straight into the output, which has exactly its room: no secret symbol is + // left in a temporary. + if (byte_index != input_bytes.size()) { + static_cast(base32_last_group(input_bytes.subspan(byte_index), padded, + output_characters.subspan(character_index))); + } +} + +/** + The exact size of the text of `byte_count` bytes: eight characters a group of five bytes, and the + last group of one to four bytes completed to eight with the padding, or as short as its bytes make + it without. + + @param byte_count The bytes. + @param padded Whether the padding is written. + @return The characters, `SIZE_MAX` when they do not fit in `std::size_t`. +*/ +[[nodiscard]] constexpr std::size_t base32_text_size(std::size_t byte_count, bool padded) noexcept { + std::size_t const whole_groups = byte_count / base32_group_bytes; + std::size_t const rest = byte_count % base32_group_bytes; + std::size_t last_group = 0; + if (rest != 0) { + last_group = padded ? base32_group_characters : ((8 * rest) + 4) / 5; + } + if (whole_groups > (size_maximum - last_group) / base32_group_characters) { + return size_maximum; + } + return (whole_groups * base32_group_characters) + last_group; +} + +/** + A bound on the text of `byte_count` bytes over both options: the padded size, which is at least + the unpadded one. + + @param byte_count The bytes. + @return The characters, `SIZE_MAX` when they do not fit in `std::size_t`. +*/ +[[nodiscard]] constexpr std::size_t base32_max_text_size(std::size_t byte_count) noexcept { + return base32_text_size(byte_count, true); +} + +/** + A bound on the bytes of `character_count` characters over both options: five bytes a group of + eight characters, and of the characters of a last short group (2 to 7) 5/8 of a byte each, down. + + @param character_count The characters. + @return The bytes, which never wrap. +*/ +[[nodiscard]] constexpr std::size_t base32_max_byte_size(std::size_t character_count) noexcept { + return (character_count / base32_group_characters * base32_group_bytes) + + ((character_count % base32_group_characters) * base32_group_bytes / + base32_group_characters); +} + +/** + Whether the character at `column` of a group completes a byte of it, which is public: the bits + of the characters of a group are 5, 10, 15, ..., 40, and a byte is complete at the 10th, 20th, + 25th, 35th and 40th, the characters at columns 1, 3, 4, 6 and 7. + + @param column The place of the character in its group of eight, 0 to 7. + @return Whether it completes a byte. +*/ +[[nodiscard]] constexpr bool base32_completes_byte(unsigned column) noexcept { + // Bit `column` of 0b11011010. + return ((0xdaU >> column) & 1U) != 0; +} + +/** + The decoder's state machine, one character at a time, for the alphabet of `Hex` and the format's + padding, written or omitted. + + Each character is read by masks alone, and the reader decides nothing in the open about a + character: at the columns that complete a byte it gives the byte the character's place completes, + whatever the character is, so that a stream never holds more than the bits of a group. Which of + those bytes are the result's is the caller's to know from public facts alone: the place, which is + public, being a character's position in a text of a public length, and, for a padded text, how + many bytes of the last group the `=` drop, which @ref verdict gives once the text is valid, as + the result's length makes it public. A character that is no symbol and no `=` accumulates into a + mask of invalid characters; a `=` that is not where the padding is (not starting a run of 1, 3, 4 + or 6, which ends the group), a symbol after a `=` of its group, a character after the padding, + and non-zero bits at the end of the last group accumulate into a mask of padding faults. Neither + is branched on before @ref verdict, which gives the fault of the lowest value of @ref error over + the whole text (B23): @ref error::invalid_character, then @ref error::invalid_length, then @ref + error::invalid_padding. Nothing else passes through `secure::declassify`: for an invalid text, + where its `=` are stays secret. + + The state is what a stream decoder holds, and is wiped by a secret one and by the one-shot form. + + @tparam Hex Whether the alphabet is the extended hex one. +*/ +template +class base32_reader { +public: + /** + A reader at the start of a text. + + @param padded Whether the format writes its padding, which decides what a `=` is. + */ + explicit constexpr base32_reader(bool padded) noexcept : padded_(padded) {} + + /** + Whether the format writes its padding, which is public. + + @return Whether a `=` completes the last group. + */ + [[nodiscard]] constexpr bool padded() const noexcept { return padded_; } + + /** + The column of the next character in its group of eight: 0 to 7, which is public. + + @return The column. + */ + [[nodiscard]] constexpr unsigned column() const noexcept { return column_; } + + /** + Reads a character: accumulates its faults, by masks, and gives the byte its place completes. + + @param character The character, which may be secret. + @return At the columns that complete a byte (@ref base32_completes_byte), the byte, which is + no byte of the result when the character is a `=` or the text is invalid; 0 elsewhere. + */ + [[nodiscard]] std::uint8_t read(char character) noexcept { + auto const code = static_cast(character); + std::uint8_t symbol_error = 0; + unsigned const value = base32_arithmetic::five_bits_of(code, symbol_error); + unsigned const padding_mask = + secure::constant_time::is_equal_mask(unsigned{code}, unsigned{'='}); + unsigned const not_a_symbol = unsigned{symbol_error} & ~padding_mask; + auto const padding_in_group = static_cast(state_.padding_in_group); + // Every character after a group that ended in padding is a fault, and so is a symbol + // after the `=` of its group. + auto padding_fault = + static_cast(state_.pad_seen) | (padding_in_group & ~padding_mask); + if (!padded_) { + padding_fault |= padding_mask; + } + // A `=` that starts a run: after 2, 4, 5 or 7 symbols alone (a run of 6, 4, 3 or 1), and + // with the bits pending then zero. + unsigned const starts_run = padding_mask & ~padding_in_group; + unsigned const bits_pending = + ~secure::constant_time::is_zero_mask(unsigned{state_.leftover}); + switch (column_) { + case 0: + case 1: padding_fault |= padding_mask; break; + case 3: + case 6: padding_fault |= starts_run; break; + default: padding_fault |= starts_run & bits_pending; break; + } + state_.padding_fault = static_cast(state_.padding_fault | padding_fault); + state_.character_fault = static_cast(state_.character_fault | not_a_symbol); + std::uint8_t const byte = take(value); + state_.padding_in_group = static_cast(state_.padding_in_group | padding_mask); + state_.padding_count = + static_cast(state_.padding_count + (padding_mask & 1U)); + if (column_ == 0) { + // The group is whole: its padding, if any, ends the text, and its count is the end's. + state_.pad_seen = static_cast(state_.pad_seen | state_.padding_in_group); + state_.last_padding = state_.padding_count; + state_.padding_in_group = 0; + state_.padding_count = 0; + } + return byte; + } + + /** + The verdict over the text read so far, as a text that ends here: @ref error::invalid_character + when a character was no symbol and no `=`, else @ref error::invalid_length for a length no + encoding has (not a multiple of 8 with the padding written, a remainder of 1, 3 or 6 without + it), else @ref error::invalid_padding for a `=` out of its place, a `=` against the option, a + character after the padding or non-zero bits at the end; for a valid text, how many bytes the + `=` of its last group drop. + + The faults pass through `secure::declassify` as one value before the one branch: the result's + success is public, the place of a bad character is not. Then, for a valid text alone, the + count of `=` passes through it: the result's length, which is public. + + @return The bytes the padding of the last group drops, 0 to 4 (always 0 with the padding + omitted), or the fault. + */ + [[nodiscard]] result verdict() const noexcept { + // The bits left at the end of a last short group must be zero. + unsigned const trailing_bits = + ~secure::constant_time::is_zero_mask(unsigned{state_.leftover}); + unsigned const padding_fault = unsigned{state_.padding_fault} | trailing_bits; + auto const character_fault = static_cast(state_.character_fault); + // Bit 0: a bad character. Bit 1: a padding fault, when no character is bad. + auto faults = static_cast((character_fault & 1U) | + (~character_fault & padding_fault & 2U)); + secure::declassify(faults); + if ((faults & 1U) != 0) { + return error::invalid_character; + } + bool const no_encoding = + padded_ ? column_ != 0 : column_ == 1 || column_ == 3 || column_ == 6; + if (no_encoding) { + return error::invalid_length; + } + if ((faults & 2U) != 0) { + return error::invalid_padding; + } + std::uint8_t padding_count = state_.last_padding; + secure::declassify(padding_count); + // A run of 1, 3, 4 or 6 `=` drops 1, 2, 3 or 4 bytes: those of the characters it stands for + // that hold no bit of a byte. + return ((std::size_t{padding_count} * base32_group_bytes) + 7) / base32_group_characters; + } + + /** Wipes the state that may be secret: the bits, the masks and the padding seen. */ + void wipe() noexcept { secure::erase_secret(std::span{&state_, 1}); } + + /** Back to the start of a text; the format's padding stays. */ + constexpr void reset() noexcept { + column_ = 0; + state_ = secret_state{}; + } + +private: + /** What the reader holds that may be secret, wiped as one. */ + struct secret_state { + /** The bits of the group not yet in a byte, as a value of at most seven bits. */ + std::uint8_t leftover = 0; + /** All ones once a character was no symbol and no `=`. */ + std::uint8_t character_fault = 0; + /** All ones once a padding fault was found. */ + std::uint8_t padding_fault = 0; + /** All ones once a group ended in padding: nothing may follow. */ + std::uint8_t pad_seen = 0; + /** All ones once a `=` was read in this group. */ + std::uint8_t padding_in_group = 0; + /** The count of `=` read in this group, 0 to 8. */ + std::uint8_t padding_count = 0; + /** The count of `=` of the last whole group, 0 to 8. */ + std::uint8_t last_padding = 0; + }; + + /** + Takes the 5 bits of a character into the group: its byte when its place completes one, and + the bits that stay; the column moves on. + + @param value The five bits. + @return The byte, 0 when the place completes none. + */ + std::uint8_t take(unsigned value) noexcept { + unsigned const bits = (unsigned{state_.leftover} << 5U) | value; + std::uint8_t byte = 0; + switch (column_) { + case 0: + case 2: + case 5: state_.leftover = static_cast(bits); break; + case 1: + byte = static_cast(bits >> 2U); + state_.leftover = static_cast(bits & 3U); + break; + case 3: + byte = static_cast(bits >> 4U); + state_.leftover = static_cast(bits & 15U); + break; + case 4: + byte = static_cast(bits >> 1U); + state_.leftover = static_cast(bits & 1U); + break; + case 6: + byte = static_cast(bits >> 3U); + state_.leftover = static_cast(bits & 7U); + break; + default: + byte = static_cast(bits); + state_.leftover = 0; + break; + } + column_ = (column_ + 1) % base32_group_characters; + return byte; + } + + /** Whether the format writes its padding. */ + bool padded_; + /** The column of the next character in its group: 0 to 7, public. */ + unsigned column_ = 0; + /** The bits, the masks and the padding seen. */ + secret_state state_{}; +}; + +} // namespace webcpp::codecs::detail + +#endif // WEBCPP_CODECS_DETAIL_FORMATS_BASE32_HPP diff --git a/include/webcpp/codecs/detail/formats/base58.hpp b/include/webcpp/codecs/detail/formats/base58.hpp new file mode 100644 index 0000000..0e87699 --- /dev/null +++ b/include/webcpp/codecs/detail/formats/base58.hpp @@ -0,0 +1,416 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The arithmetic of base58, which its codec runs (``): the length of the + longest text of a number of bytes, computed at compile time in integers; an alphabet's tables, + built at compile time from its characters; the public conversions, which follow Bitcoin Core's + `EncodeBase58` and `DecodeBase58` (`src/base58.cpp`) line by line, quadratic, with their early + exits (Bitcoin Core's MIT notice is the library's `LICENSE-BITCOIN.txt`); and the secret + conversions, which process every limb of the scratch's bound for the input's length with no early + exit, count the leading zeros by a mask scan, read the alphabet by `secure::constant_time::lookup` + and its inverse by masks, so that the operations they run depend on the input's length alone + (D12). Each conversion works in the scratch its caller gives, in place, and leaves the result at + the scratch's end: the digits of a text, or the bytes of a decoded text, its leading zeros + included. +*/ +#ifndef WEBCPP_CODECS_DETAIL_FORMATS_BASE58_HPP +#define WEBCPP_CODECS_DETAIL_FORMATS_BASE58_HPP + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs::detail { + +/** The bits below the binary point of the rational bounds of log(256) / log(58). */ +inline constexpr unsigned base58_ratio_bits = 40; + +/** log(256) / log(58) from below: floor(2^40 * log(256) / log(58)), over 2^40. */ +inline constexpr std::uint64_t base58_ratio_below = 1'501'557'111'490; + +/** log(256) / log(58) from above: the bound from below plus one, over 2^40. */ +inline constexpr std::uint64_t base58_ratio_above = base58_ratio_below + 1; + +/** The most bytes whose product with a bound fits in 64 bits: 2^23. */ +inline constexpr std::uint64_t base58_largest_counted = std::uint64_t{1} << 23U; + +/** + The ceiling of `byte_count` times a bound of log(256) / log(58), in integers. + + @param byte_count The bytes, at most `base58_largest_counted`. + @param ratio `base58_ratio_below` or `base58_ratio_above`. + @return The ceiling. +*/ +[[nodiscard]] constexpr std::uint64_t base58_ceiling(std::uint64_t byte_count, + std::uint64_t ratio) noexcept { + std::uint64_t const scaled = byte_count * ratio; + std::uint64_t const fraction_mask = (std::uint64_t{1} << base58_ratio_bits) - 1U; + return (scaled >> base58_ratio_bits) + ((scaled & fraction_mask) != 0 ? 1U : 0U); +} + +/** + Whether `base58_encoded_length(byte_count)` is exact: both bounds of log(256) / log(58) give the + same ceiling, so that it is ceil(byte_count * log(256) / log(58)), the base-58 digits of + 256^byte_count - 1 (true for every count below 2038748). + + @param byte_count The bytes. + @return Whether the length is exact. +*/ +[[nodiscard]] constexpr bool base58_length_is_exact(std::size_t byte_count) noexcept { + return byte_count <= base58_largest_counted && + base58_ceiling(byte_count, base58_ratio_below) == + base58_ceiling(byte_count, base58_ratio_above); +} + +/** + The length of the longest text of `byte_count` bytes, ceil(byte_count * log(256) / log(58)), by + the bound from above: never less than the exact length, and equal to it where + @ref base58_length_is_exact holds. The leading-zero rule never gives more: k leading zero bytes + write k characters, fewer than their share of the ceiling. + + @param byte_count The bytes. + @return The characters, `SIZE_MAX` past `base58_largest_counted` bytes. +*/ +[[nodiscard]] constexpr std::size_t base58_encoded_length(std::size_t byte_count) noexcept { + if (byte_count > base58_largest_counted) { + return detail::size_maximum; + } + return static_cast(base58_ceiling(byte_count, base58_ratio_above)); +} + +/** + The limbs a decode of `character_count` characters needs: Bitcoin Core's `strlen(psz) * 733 / + 1000 + 1`, log(58) / log(256) rounded up, which bounds the bytes of 58^character_count - 1. + + @param character_count The characters. + @return The bytes. +*/ +[[nodiscard]] constexpr std::size_t base58_decoded_limbs(std::size_t character_count) noexcept { + return static_cast(std::uint64_t{character_count} * 733U / 1000U) + 1; +} + +/** + Whether `characters` are a base58 alphabet: 58 characters, no two the same. + + @param characters The alphabet's characters, digit 0 first. + @return Whether they are 58 distinct characters. +*/ +[[nodiscard]] constexpr bool is_base58_alphabet(std::string_view characters) noexcept { + if (characters.size() != 58) { + return false; + } + for (std::size_t first = 0; first < characters.size(); ++first) { + for (std::size_t second = first + 1; second < characters.size(); ++second) { + if (characters[first] == characters[second]) { + return false; + } + } + } + return true; +} + +/** The value of a byte that is no character of an alphabet, in @ref base58_values. */ +inline constexpr std::uint8_t base58_no_value = 0xff; + +/** + The characters of `Alphabet` as bytes, digit 0 first: the table encode reads. + + @tparam Alphabet A type with `static constexpr std::string_view characters`, 58 of them. + @return The table. +*/ +template +[[nodiscard]] constexpr std::array base58_symbols_of() noexcept { + std::array symbols{}; + for (std::size_t digit = 0; digit < symbols.size(); ++digit) { + symbols[digit] = static_cast(Alphabet::characters[digit]); + } + return symbols; +} + +/** The characters of `Alphabet` as bytes, built at compile time. */ +template +inline constexpr std::array base58_symbols = base58_symbols_of(); + +/** + The digit of each byte value as a character of `Alphabet`, @ref base58_no_value for a byte that is + none: Bitcoin Core's `mapBase58`, the table the public decode reads. + + @tparam Alphabet A type with `static constexpr std::string_view characters`, 58 of them. + @return The table. +*/ +template +[[nodiscard]] constexpr std::array base58_values_of() noexcept { + std::array values{}; + values.fill(base58_no_value); + for (std::size_t digit = 0; digit < 58; ++digit) { + values[static_cast(Alphabet::characters[digit])] = + static_cast(digit); + } + return values; +} + +/** The digit of each byte value as a character of `Alphabet`, built at compile time. */ +template +inline constexpr std::array base58_values = base58_values_of(); + +/** + The bytes an encode converts: the payload, then the checksum its codec computed (empty with no + checksum), read as one sequence without a copy. +*/ +struct base58_bytes { + /** The payload. */ + std::span payload; + /** The checksum of the payload. */ + std::span checksum; + + /** + The bytes of both. + + @return The count. + */ + [[nodiscard]] constexpr std::size_t size() const noexcept { + return payload.size() + checksum.size(); + } + + /** + The byte at `index`, which is public: the branch reads no data. + + @param index The place, below `size()`. + @return The byte. + */ + [[nodiscard]] constexpr std::uint8_t operator[](std::size_t index) const noexcept { + return index < payload.size() ? payload[index] : checksum[index - payload.size()]; + } +}; + +/** + `value / 58` for `value` below 58 * 256, by a multiplication and a shift, so that no division + instruction, whose time may depend on its operands, runs on a secret: floor(value * 565 / 2^15), + exact for every value below 14848 (the test checks each). + + @param value The value, below 14848. + @return Its quotient by 58. +*/ +[[nodiscard]] constexpr std::uint32_t base58_quotient(std::uint32_t value) noexcept { + return (value * 565U) >> 15U; +} + +/** + Bitcoin Core's `EncodeBase58`, its arithmetic: the leading zero bytes counted and skipped, then + `b58 = b58 * 256 + ch` for each byte after them, over the digits touched so far and no further + (its early exit), into the end of `digits`, zero before the call. + + @param input The bytes, which are public. + @param digits The scratch, at least the digits of the text long. + @return The text's length: a character a leading zero byte, and the number's digits, which are + the last of `digits` (those before them zero). +*/ +[[nodiscard]] constexpr std::size_t base58_public_digits(base58_bytes input, + std::span digits) noexcept { + // Skip & count leading zeroes. + std::size_t zeroes = 0; + while (zeroes < input.size() && input[zeroes] == 0) { + ++zeroes; + } + std::size_t length = 0; + // Process the bytes. + for (std::size_t position = zeroes; position < input.size(); ++position) { + std::uint32_t carry = input[position]; + std::size_t touched = 0; + // Apply "b58 = b58 * 256 + ch". + for (std::size_t index = digits.size(); (carry != 0 || touched < length) && index != 0; + --index, ++touched) { + carry += 256U * digits[index - 1]; + digits[index - 1] = static_cast(carry % 58U); + carry /= 58U; + } + length = touched; + } + // Skip leading zeroes in base58 result. + while (length != 0 && digits[digits.size() - length] == 0) { + --length; + } + return zeroes + length; +} + +/** + The secret encode's arithmetic: `b58 = b58 * 256 + ch` for every byte, the leading zeros + included, over every digit of `digits`, with no early exit; then the leading zero bytes and the + leading zero digits counted by mask scans. The text's length passes through + `secure::declassify`: it is public (D12), as the text's is. + + @param input The bytes, which may be secret. + @param digits The digits of the bound for the input's length, `base58_encoded_length(size)`, + zero before the call. + @return The text's length, its digits the last of `digits` (those before them zero). +*/ +[[nodiscard]] inline std::size_t base58_secret_digits(base58_bytes input, + std::span digits) noexcept { + namespace constant_time = secure::constant_time; + std::size_t leading_mask = detail::size_maximum; + std::size_t zeroes = 0; + for (std::size_t position = 0; position < input.size(); ++position) { + std::uint8_t const input_byte = input[position]; + leading_mask &= constant_time::is_zero_mask(input_byte); + zeroes += leading_mask & 1U; + std::uint32_t carry = input_byte; + for (std::size_t index = digits.size(); index != 0; --index) { + std::uint32_t const value = carry + (256U * digits[index - 1]); + carry = base58_quotient(value); + digits[index - 1] = static_cast(value - (58U * carry)); + } + } + std::size_t zero_mask = detail::size_maximum; + std::size_t zero_digits = 0; + for (std::uint8_t const digit : digits) { + zero_mask &= constant_time::is_zero_mask(digit); + zero_digits += zero_mask & 1U; + } + std::size_t text_size = zeroes + (digits.size() - zero_digits); + secure::declassify(text_size); + return text_size; +} + +/** + Writes the character of each digit: by indexing the alphabet when the operation is public, by + `secure::constant_time::lookup`, which reads the whole alphabet, when it is secret. + + @tparam Alphabet The alphabet. + @tparam Secret Whether the digits are secret. + @param digits The digits, 0 to 57. + @param output_characters The text, as long as `digits`. +*/ +template +constexpr void base58_write_text(std::span digits, + std::span output_characters) noexcept { + for (std::size_t index = 0; index < digits.size(); ++index) { + if constexpr (Secret) { + output_characters[index] = static_cast(secure::constant_time::lookup( + std::span{base58_symbols}, digits[index])); + } else { + output_characters[index] = static_cast(base58_symbols[digits[index]]); + } + } +} + +/** + Bitcoin Core's `DecodeBase58`, its arithmetic: the leading characters of digit 0 counted and + skipped, then `b256 = b256 * 58 + digit` for each character after them, over the bytes touched so + far and no further (its early exit), into the end of `bytes`, zero before the call; the first + character outside the alphabet stops it. Unlike Bitcoin Core's, it skips no space. + + @tparam Alphabet The alphabet. + @param text_characters The text, which is public. + @param bytes The scratch, at least the text long. + @return The decoded length, a zero byte a leading character of digit 0, and the number's bytes, + which are the last of `bytes` (those before them zero); `std::nullopt` for a character outside + the alphabet. +*/ +template +[[nodiscard]] constexpr std::optional base58_public_bytes( + std::string_view text_characters, std::span bytes) noexcept { + // Skip and count leading '1's. + std::size_t zeroes = 0; + while (zeroes < text_characters.size() && + static_cast(text_characters[zeroes]) == base58_symbols[0]) { + ++zeroes; + } + std::size_t length = 0; + // Process the characters. + for (std::size_t position = zeroes; position < text_characters.size(); ++position) { + // Decode base58 character + std::uint32_t carry = + base58_values[static_cast(text_characters[position])]; + if (carry == base58_no_value) { + // Invalid b58 character + return std::nullopt; + } + std::size_t touched = 0; + for (std::size_t index = bytes.size(); (carry != 0 || touched < length) && index != 0; + --index, ++touched) { + carry += 58U * bytes[index - 1]; + bytes[index - 1] = static_cast(carry & 0xffU); + carry >>= 8U; + } + length = touched; + } + return zeroes + length; +} + +/** + The secret decode's arithmetic: each character read as a digit by a mask against each of the 58 + characters, the verdict accumulated over the whole text; `b256 = b256 * 58 + digit` for every + character, the leading ones included, over every limb of `limbs`, with no early exit; the leading + characters of digit 0 and the leading zero limbs counted by mask scans. The verdict passes + through `secure::declassify` before its one branch, then the decoded length, which is public + (D12): the place of a bad character is not. + + @tparam Alphabet The alphabet. + @param text_characters The text, which may be secret. + @param limbs The bytes of the bound for the text's length, `base58_decoded_limbs(size)`, zero + before the call. + @return The decoded length, its number's bytes the last of `limbs` (those before them zero), or + `std::nullopt` for a text holding a character outside the alphabet. +*/ +template +[[nodiscard]] std::optional base58_secret_bytes( + std::string_view text_characters, std::span limbs) noexcept { + namespace constant_time = secure::constant_time; + std::uint32_t invalid_mask = 0; + std::size_t leading_mask = detail::size_maximum; + std::size_t zeroes = 0; + for (char const text_character : text_characters) { + // The byte value first, then the unsigned mask word of secure's. + auto const code = static_cast(static_cast(text_character)); + std::uint32_t const zero_match = + constant_time::is_equal_mask(code, std::uint32_t{base58_symbols[0]}); + std::uint32_t found = zero_match; + std::uint32_t value = 0; + for (std::uint32_t digit = 1; digit < 58; ++digit) { + std::uint32_t const match = + constant_time::is_equal_mask(code, std::uint32_t{base58_symbols[digit]}); + found |= match; + value |= match & digit; + } + invalid_mask |= ~found; + leading_mask &= constant_time::mask_from_bit(zero_match & 1U); + zeroes += leading_mask & 1U; + std::uint32_t carry = value; + for (std::size_t index = limbs.size(); index != 0; --index) { + carry += 58U * limbs[index - 1]; + limbs[index - 1] = static_cast(carry & 0xffU); + carry >>= 8U; + } + } + std::size_t zero_mask = detail::size_maximum; + std::size_t zero_limbs = 0; + for (std::uint8_t const limb : limbs) { + zero_mask &= constant_time::is_zero_mask(limb); + zero_limbs += zero_mask & 1U; + } + secure::declassify(invalid_mask); + if (invalid_mask != 0) { + return std::nullopt; + } + std::size_t decoded_size = zeroes + (limbs.size() - zero_limbs); + secure::declassify(decoded_size); + return decoded_size; +} + +} // namespace webcpp::codecs::detail + +#endif // WEBCPP_CODECS_DETAIL_FORMATS_BASE58_HPP diff --git a/include/webcpp/codecs/detail/formats/base64.hpp b/include/webcpp/codecs/detail/formats/base64.hpp new file mode 100644 index 0000000..d210855 --- /dev/null +++ b/include/webcpp/codecs/detail/formats/base64.hpp @@ -0,0 +1,449 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The arithmetic of base64 and base64url, which their codec and stream codec share + (``) and which the armor reuses (`base64_arithmetic`): a 6-bit value to + its symbol and a symbol to its 6-bit value by webcpp::secure's constant-time blocks, with no table + indexed by a data byte and no branch on one, the 3-byte group to its 4 symbols, and the decoder's + state machine, one character at a time, whose verdict is accumulated over the whole text and passes + through `secure::declassify` before its one branch (D12). libsodium's `sodium_bin2base64` and + `sodium_base642bin` are the reference for the method, written here over secure's masks. + + The two alphabets differ in their last two symbols alone, so that one template, by a flag, is the + implementation of both formats (RFC 4648's section 4 and section 5). +*/ +#ifndef WEBCPP_CODECS_DETAIL_FORMATS_BASE64_HPP +#define WEBCPP_CODECS_DETAIL_FORMATS_BASE64_HPP + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace webcpp::codecs::detail::base64_arithmetic { + +/** + The symbol of a 6-bit value: `A` to `Z` for 0 to 25, `a` to `z` for 26 to 51, `0` to `9` for 52 to + 61, then `+` and `/` (`-` and `_` for the URL alphabet), chosen by masks with no table and no + branch. + + @tparam Url Whether the alphabet is the URL one of RFC 4648 section 5. + @param six_bits A value of 0 to 63, which may be secret; a value above 63 gives the symbol `\0`. + @return The symbol. +*/ +template +[[nodiscard]] constexpr std::uint8_t symbol_of(std::uint8_t six_bits) noexcept { + // In unsigned, a mask word of secure's that no promotion turns signed. + auto const value = static_cast(six_bits); + auto const upper_mask = secure::constant_time::is_less_mask(value, 26U); + auto const lower_mask = secure::constant_time::is_in_range_mask(value, 26U, 51U); + auto const digit_mask = secure::constant_time::is_in_range_mask(value, 52U, 61U); + auto const sixty_two_mask = secure::constant_time::is_equal_mask(value, 62U); + auto const sixty_three_mask = secure::constant_time::is_equal_mask(value, 63U); + constexpr unsigned sixty_two_symbol = Url ? unsigned{'-'} : unsigned{'+'}; + constexpr unsigned sixty_three_symbol = Url ? unsigned{'_'} : unsigned{'/'}; + // A symbol whose mask is clear contributes nothing, whatever the wrapped sum it was given. + unsigned const symbol = + (upper_mask & (unsigned{'A'} + value)) | (lower_mask & (unsigned{'a'} - 26U + value)) | + (digit_mask & (unsigned{'0'} - 52U + value)) | (sixty_two_mask & sixty_two_symbol) | + (sixty_three_mask & sixty_three_symbol); + return static_cast(symbol); +} + +/** + The 6-bit value of a symbol, and a mask of whether it is no symbol of the alphabet, by masks over + its byte value with no table and no branch. The byte is read as unsigned first, so that a `char` + from 0x80 up, negative where `char` is signed, lands in no range. `=` is no symbol here: the + padding is the format's to read. + + @tparam Url Whether the alphabet is the URL one of RFC 4648 section 5. + @param symbol The byte of the character, which may be secret. + @param error_mask Set to all ones when `symbol` is no symbol of the alphabet; left as it was + otherwise. + @return The value, 0 for a byte that is no symbol. +*/ +template +[[nodiscard]] constexpr std::uint8_t six_bits_of(std::uint8_t symbol, + std::uint8_t& error_mask) noexcept { + auto const code = static_cast(symbol); + auto const upper_mask = + secure::constant_time::is_in_range_mask(code, unsigned{'A'}, unsigned{'Z'}); + auto const lower_mask = + secure::constant_time::is_in_range_mask(code, unsigned{'a'}, unsigned{'z'}); + auto const digit_mask = + secure::constant_time::is_in_range_mask(code, unsigned{'0'}, unsigned{'9'}); + auto const sixty_two_mask = + secure::constant_time::is_equal_mask(code, Url ? unsigned{'-'} : unsigned{'+'}); + auto const sixty_three_mask = + secure::constant_time::is_equal_mask(code, Url ? unsigned{'_'} : unsigned{'/'}); + unsigned const value = (upper_mask & (code - unsigned{'A'})) | + (lower_mask & (code - unsigned{'a'} + 26U)) | + (digit_mask & (code - unsigned{'0'} + 52U)) | (sixty_two_mask & 62U) | + (sixty_three_mask & 63U); + unsigned const symbol_mask = + upper_mask | lower_mask | digit_mask | sixty_two_mask | sixty_three_mask; + error_mask = static_cast(error_mask | static_cast(~symbol_mask)); + return static_cast(value); +} + +} // namespace webcpp::codecs::detail::base64_arithmetic + +namespace webcpp::codecs::detail { + +/** The padding character of RFC 4648 section 3.2. */ +inline constexpr char base64_padding_character = '='; + +/** + The symbols of a group of one to three bytes: the bytes' bits taken six at a time, the last + group's missing bits zero, written as `group_bytes.size() + 1` symbols at the start of + `symbols`. + + @tparam Url Whether the alphabet is the URL one. + @param group_bytes One to three bytes, which may be secret; their count is public. + @param symbols Room for `group_bytes.size() + 1` characters at least; the ones past them are left + as they were. + @return The symbols written: 2, 3 or 4. +*/ +template +constexpr std::size_t base64_group_symbols(std::span group_bytes, + std::span symbols) noexcept { + unsigned const first_byte = group_bytes[0]; + unsigned const second_byte = group_bytes.size() > 1 ? unsigned{group_bytes[1]} : 0U; + unsigned const third_byte = group_bytes.size() > 2 ? unsigned{group_bytes[2]} : 0U; + auto const symbol_at = [](unsigned six_bits) { + return static_cast( + base64_arithmetic::symbol_of(static_cast(six_bits))); + }; + symbols[0] = symbol_at(first_byte >> 2U); + symbols[1] = symbol_at(((first_byte & 3U) << 4U) | (second_byte >> 4U)); + if (group_bytes.size() > 1) { + symbols[2] = symbol_at(((second_byte & 15U) << 2U) | (third_byte >> 6U)); + } + if (group_bytes.size() > 2) { + symbols[3] = symbol_at(third_byte & 63U); + } + return group_bytes.size() + 1; +} + +/** + The characters of the last group of one or two bytes, its padding `=` written when the format + writes it. + + @tparam Url Whether the alphabet is the URL one. + @param group_bytes One or two bytes, which may be secret. + @param padded Whether the padding is written, which is public. + @param characters Room for the characters of the group: 4 when padded, else 2 or 3. + @return The characters of the group: 4 when padded, else 2 or 3. +*/ +template +constexpr std::size_t base64_last_group(std::span group_bytes, bool padded, + std::span characters) noexcept { + std::size_t const symbol_count = base64_group_symbols(group_bytes, characters); + if (!padded) { + return symbol_count; + } + for (std::size_t index = symbol_count; index < 4; ++index) { + characters[index] = base64_padding_character; + } + return 4; +} + +/** + Writes the text of `input_bytes`: four characters for each group of three bytes, then the last + group of one or two bytes as @ref base64_last_group gives it. + + @tparam Url Whether the alphabet is the URL one. + @param input_bytes The bytes, which may be secret. + @param output_characters The text, exactly as many characters as the format writes for the bytes. + @param padded Whether the padding is written. +*/ +template +constexpr void base64_encode_bytes(std::span input_bytes, + std::span output_characters, bool padded) noexcept { + std::size_t byte_index = 0; + std::size_t character_index = 0; + for (; input_bytes.size() - byte_index >= 3; byte_index += 3, character_index += 4) { + static_cast(base64_group_symbols( + input_bytes.subspan(byte_index, 3), + output_characters.subspan(character_index).template first<4>())); + } + // The last group straight into the output, which has exactly its room: no secret symbol is + // left in a temporary. + if (byte_index != input_bytes.size()) { + static_cast(base64_last_group(input_bytes.subspan(byte_index), padded, + output_characters.subspan(character_index))); + } +} + +/** + The exact size of the text of `byte_count` bytes: four characters a group of three bytes, and the + last group of one or two bytes completed to four with the padding, or as short as its bytes make + it without. + + @param byte_count The bytes. + @param padded Whether the padding is written. + @return The characters, `SIZE_MAX` when they do not fit in `std::size_t`. +*/ +[[nodiscard]] constexpr std::size_t base64_text_size(std::size_t byte_count, bool padded) noexcept { + std::size_t const whole_groups = byte_count / 3; + std::size_t const rest = byte_count % 3; + std::size_t last_group = 0; + if (rest != 0) { + last_group = padded ? 4 : rest + 1; + } + if (whole_groups > (size_maximum - last_group) / 4) { + return size_maximum; + } + return (whole_groups * 4) + last_group; +} + +/** + A bound on the text of `byte_count` bytes over both options: the padded size, which is at least + the unpadded one. + + @param byte_count The bytes. + @return The characters, `SIZE_MAX` when they do not fit in `std::size_t`. +*/ +[[nodiscard]] constexpr std::size_t base64_max_text_size(std::size_t byte_count) noexcept { + return base64_text_size(byte_count, true); +} + +/** + A bound on the bytes of `character_count` characters over both options: three bytes a group of + four characters, and of the characters of a last short group (2 or 3) one byte and two. + + @param character_count The characters. + @return The bytes, which never wrap. +*/ +[[nodiscard]] constexpr std::size_t base64_max_byte_size(std::size_t character_count) noexcept { + return (character_count / 4 * 3) + ((character_count % 4) * 3 / 4); +} + +/** + The decoder's state machine, one character at a time, for the alphabet of `Url` and the format's + padding, written or omitted. + + Each character is read by masks alone, and the reader decides nothing in the open about a + character: it gives the byte the character's place completes (the second place of a group the + first byte, the third the second, the fourth the third) whatever the character is, so that a + stream never holds more than the bits of a group. Which of those bytes are the result's is the + caller's to know from public facts alone: the place, which is public, being a character's position + in a text of a public length, and, for a padded text, the count of `=` of the last group, which + @ref verdict gives once the text is valid, as the result's length makes it public. A character + that is no symbol and no `=` accumulates into a mask of invalid characters; a `=` that is not where + the padding is, a character after the padding, and non-zero bits at the end of the last group + accumulate into a mask of padding faults. Neither is branched on before @ref verdict, which gives + the fault of the lowest value of @ref error over the whole text (B23): @ref + error::invalid_character, then @ref error::invalid_length, then @ref error::invalid_padding. + Nothing else passes through `secure::declassify`: for an invalid text, where its `=` are stays + secret. + + The state is what a stream decoder holds, and is wiped by a secret one and by the one-shot form. + + @tparam Url Whether the alphabet is the URL one. +*/ +template +class base64_reader { +public: + /** + A reader at the start of a text. + + @param padded Whether the format writes its padding, which decides what a `=` is. + */ + explicit constexpr base64_reader(bool padded) noexcept : padded_(padded) {} + + /** + Whether the format writes its padding, which is public. + + @return Whether a `=` completes the last group. + */ + [[nodiscard]] constexpr bool padded() const noexcept { return padded_; } + + /** + The column of the next character in its group of four: 0 to 3, which is public. + + @return The column. + */ + [[nodiscard]] constexpr unsigned column() const noexcept { return column_; } + + /** + Reads a character: accumulates its faults, by masks, and gives the byte its place completes. + + @param character The character, which may be secret. + @return At columns 1, 2 and 3, the group's first, second and third byte, which is no byte of + the result when the character is a `=` or the text is invalid; 0 at column 0. + */ + [[nodiscard]] std::uint8_t read(char character) noexcept { + auto const code = static_cast(character); + std::uint8_t symbol_error = 0; + unsigned const value = base64_arithmetic::six_bits_of(code, symbol_error); + unsigned const padding_mask = + secure::constant_time::is_equal_mask(unsigned{code}, unsigned{'='}); + unsigned const not_a_symbol = unsigned{symbol_error} & ~padding_mask; + // Every character after a group that ended in padding is a fault. + auto padding_fault = static_cast(state_.pad_seen); + if (!padded_) { + padding_fault |= padding_mask; + } + std::uint8_t byte = 0; + switch (column_) { + case 0: read_first(value, padding_mask, padding_fault); break; + case 1: byte = read_second(value, padding_mask, padding_fault); break; + case 2: byte = read_third(value, padding_mask, padding_fault); break; + default: byte = read_fourth(value, padding_mask, padding_fault); break; + } + state_.character_fault = static_cast(state_.character_fault | not_a_symbol); + return byte; + } + + /** + The verdict over the text read so far, as a text that ends here: @ref error::invalid_character + when a character was no symbol and no `=`, else @ref error::invalid_length for a length no + encoding has (not a multiple of 4 with the padding written, 4k + 1 without it), else + @ref error::invalid_padding for a `=` out of its place, a `=` against the option, a + character after the padding or non-zero bits at the end; for a valid text, the count of `=` + of its last group. + + The faults pass through `secure::declassify` as one value before the one branch: the result's + success is public, the place of a bad character is not. Then, for a valid text alone, the + count of `=` passes through it: the result's length, which is public. + + @return The count of `=` of the last group, 0 to 2 (always 0 with the padding omitted), or the + fault. + */ + [[nodiscard]] result verdict() const noexcept { + // The bits left at the end of a last short group must be zero. + unsigned const trailing_bits = + ~secure::constant_time::is_zero_mask(unsigned{state_.leftover}); + unsigned const padding_fault = unsigned{state_.padding_fault} | trailing_bits; + auto const character_fault = static_cast(state_.character_fault); + // Bit 0: a bad character. Bit 1: a padding fault, when no character is bad. + auto faults = static_cast((character_fault & 1U) | + (~character_fault & padding_fault & 2U)); + secure::declassify(faults); + if ((faults & 1U) != 0) { + return error::invalid_character; + } + if (padded_ ? column_ != 0 : column_ == 1) { + return error::invalid_length; + } + if ((faults & 2U) != 0) { + return error::invalid_padding; + } + std::uint8_t padding_count = state_.last_padding; + secure::declassify(padding_count); + return std::size_t{padding_count}; + } + + /** Wipes the state that may be secret: the bits, the masks and the padding seen. */ + void wipe() noexcept { secure::erase_secret(std::span{&state_, 1}); } + + /** Back to the start of a text; the format's padding stays. */ + constexpr void reset() noexcept { + column_ = 0; + state_ = secret_state{}; + } + +private: + /** What the reader holds that may be secret, wiped as one. */ + struct secret_state { + /** The bits of the group not yet in a byte: six after the first character, then four, two. + */ + std::uint8_t leftover = 0; + /** All ones once a character was no symbol and no `=`. */ + std::uint8_t character_fault = 0; + /** All ones once a padding fault was found. */ + std::uint8_t padding_fault = 0; + /** All ones once a group ended in padding: nothing may follow. */ + std::uint8_t pad_seen = 0; + /** All ones when the third character of this group was a `=`. */ + std::uint8_t padding_at_third = 0; + /** The count of `=` at the third and fourth places of the last whole group, 0 to 2. */ + std::uint8_t last_padding = 0; + }; + + /** Accumulates a mask of padding faults. */ + void add_padding_fault(unsigned padding_fault) noexcept { + state_.padding_fault = static_cast(state_.padding_fault | padding_fault); + } + + /** The first character of a group: six bits, no byte; a `=` here is a fault. */ + void read_first(unsigned value, unsigned padding_mask, unsigned padding_fault) noexcept { + add_padding_fault(padding_fault | padding_mask); + state_.leftover = static_cast(value); + // A group follows the last whole one: its padding, a fault if any, is no longer the end's. + state_.last_padding = 0; + column_ = 1; + } + + /** The second: the group's first byte, four bits left; a `=` here is a fault. */ + std::uint8_t read_second(unsigned value, unsigned padding_mask, + unsigned padding_fault) noexcept { + add_padding_fault(padding_fault | padding_mask); + unsigned const bits = (unsigned{state_.leftover} << 6U) | value; + state_.leftover = static_cast(bits & 15U); + column_ = 2; + return static_cast(bits >> 4U); + } + + /** + The third: the second byte, two bits left; or a `=`, which ends the group, whose four bits + left must be zero. + */ + std::uint8_t read_third(unsigned value, unsigned padding_mask, + unsigned padding_fault) noexcept { + unsigned const four_bits_left = + ~secure::constant_time::is_zero_mask(unsigned{state_.leftover}); + add_padding_fault(padding_fault | (padding_mask & four_bits_left)); + state_.padding_at_third = static_cast(padding_mask); + unsigned const bits = (unsigned{state_.leftover} << 6U) | value; + // A padding character leaves the bits as they were: they were checked above. + state_.leftover = static_cast( + secure::constant_time::select(padding_mask, unsigned{state_.leftover}, bits & 3U)); + column_ = 3; + return static_cast(bits >> 2U); + } + + /** + The fourth: the third byte; or a `=`, which ends the group: after a symbol its two bits left + must be zero, after a `=` there is nothing left. A symbol after a `=` is a fault. + */ + std::uint8_t read_fourth(unsigned value, unsigned padding_mask, + unsigned padding_fault) noexcept { + auto const padded_third = static_cast(state_.padding_at_third); + unsigned const two_bits_left = + ~secure::constant_time::is_zero_mask(unsigned{state_.leftover}); + add_padding_fault(padding_fault | (padding_mask & ~padded_third & two_bits_left) | + (padded_third & ~padding_mask)); + unsigned const bits = (unsigned{state_.leftover} << 6U) | value; + state_.pad_seen = static_cast(state_.pad_seen | padding_mask | padded_third); + state_.last_padding = static_cast((padded_third & 1U) + (padding_mask & 1U)); + state_.padding_at_third = 0; + state_.leftover = 0; + column_ = 0; + return static_cast(bits); + } + + /** Whether the format writes its padding. */ + bool padded_; + /** The column of the next character in its group: 0 to 3, public. */ + unsigned column_ = 0; + /** The bits, the masks and the padding seen. */ + secret_state state_{}; +}; + +} // namespace webcpp::codecs::detail + +#endif // WEBCPP_CODECS_DETAIL_FORMATS_BASE64_HPP diff --git a/include/webcpp/codecs/detail/formats/bech32.hpp b/include/webcpp/codecs/detail/formats/bech32.hpp new file mode 100644 index 0000000..d085da5 --- /dev/null +++ b/include/webcpp/codecs/detail/formats/bech32.hpp @@ -0,0 +1,585 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The arithmetic of bech32 and bech32m (BIP-173 and BIP-350), which their codec, their value codec + and their stream codec share (``): a 5-bit value to its character by + `secure::constant_time::lookup` over the 32 characters of the alphabet, a character to its value + by masks against each of them, the checksum's `polymod`, whose conditional XOR of the five + generator words is a `select` by a mask, the regrouping of 5-bit values into bytes and back, and + the verdict over a whole text, which passes through `secure::declassify` once (D12). + + What is public: the text's length, the position of its separator (the last `1`), which is the + length of its human-readable part, the format's own human-readable part, and the result's success; + the characters themselves, those of the human-readable part included, are read by masks alone, so + that no branch and no index depends on them. The two variants differ in the checksum's final + constant alone, and the two data modes in the regrouping alone, so that one set of functions + serves the four. +*/ +#ifndef WEBCPP_CODECS_DETAIL_FORMATS_BECH32_HPP +#define WEBCPP_CODECS_DETAIL_FORMATS_BECH32_HPP + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs::detail { + +/** The word of bech32's masks and checksum: 32 bits, as BIP-173's `polymod` computes. */ +using bech32_word = std::uint32_t; + +/** The 32 characters of bech32's alphabet, the character of each 5-bit value in order. */ +inline constexpr std::array bech32_alphabet{ + 'q', 'p', 'z', 'r', 'y', '9', 'x', '8', 'g', 'f', '2', 't', 'v', 'd', 'w', '0', + 's', '3', 'j', 'n', '5', '4', 'k', 'h', 'c', 'e', '6', 'm', 'u', 'a', '7', 'l', +}; + +/** The five generator words of BIP-173's `polymod`. */ +inline constexpr std::array bech32_generator{ + 0x3b6a57b2U, 0x26508e6dU, 0x1ea119faU, // XORed in for the top's bits 0 to 2 + 0x3d4233ddU, 0x2a1462b3U, // and for its bits 3 and 4 +}; + +/** The characters of the checksum, at the end of every text. */ +inline constexpr std::size_t bech32_checksum_size = 6; + +/** The longest human-readable part, in characters (BIP-173). */ +inline constexpr std::size_t bech32_longest_part = 83; + +/** + The shortest text: a human-readable part of one character, the separator and the checksum, which + is the least maximum length an instance may have. +*/ +inline constexpr std::size_t bech32_shortest_text = 1 + 1 + bech32_checksum_size; + +/** + The mask of a public condition: all ones when it holds, else zero. + + @param condition The condition, which is public. + @return The mask. +*/ +[[nodiscard]] constexpr bech32_word bech32_public_mask(bool condition) noexcept { + return bech32_word{0} - static_cast(condition); +} + +/** + The byte value of a character, read as an unsigned byte first, since a `char` from 0x80 up is + negative where `char` is signed. + + @param character The character, which may be secret. + @return Its value, 0 to 255. +*/ +[[nodiscard]] constexpr bech32_word bech32_code(char character) noexcept { + return static_cast(static_cast(character)); +} + +/** + The value of a character with an ASCII capital letter folded to small, by a mask. + + @param code A byte value, which may be secret. + @return The value folded. +*/ +[[nodiscard]] constexpr bech32_word bech32_lower(bech32_word code) noexcept { + bech32_word const capital_mask = + secure::constant_time::is_in_range_mask(code, bech32_word{'A'}, bech32_word{'Z'}); + return code | (capital_mask & bech32_word{0x20}); +} + +/** + The character of a 5-bit value, read from the whole alphabet by `lookup`. + + @param value A value of 0 to 31, which may be secret. + @return The character. +*/ +[[nodiscard]] constexpr char bech32_character(bech32_word value) noexcept { + return static_cast(secure::constant_time::lookup( + std::span{bech32_alphabet}, static_cast(value))); +} + +/** What a character of a data part reads as: its value, and the mask of whether it is none. */ +struct bech32_reading { + /** The 5-bit value, 0 for a character outside the alphabet. */ + bech32_word value; + /** All ones when the character is outside the alphabet, in either case, else zero. */ + bech32_word invalid_mask; +}; + +/** + Reads a character of a data part, either case: its byte, folded to small, against each of the 32 + characters of the alphabet by a mask, with no table indexed by it. + + @param character The character, which may be secret. + @return Its value and the mask of whether it is outside the alphabet. +*/ +[[nodiscard]] constexpr bech32_reading bech32_value(char character) noexcept { + bech32_word const lowered = bech32_lower(bech32_code(character)); + bech32_word value = 0; + bech32_word found = 0; + for (bech32_word index = 0; index < bech32_alphabet.size(); ++index) { + bech32_word const match = + secure::constant_time::is_equal_mask(lowered, bech32_word{bech32_alphabet[index]}); + value |= match & index; + found |= match; + } + return bech32_reading{.value = value, .invalid_mask = ~found}; +} + +/** + One step of BIP-173's `polymod`: the checksum times x, plus the value, the conditional XOR of each + generator word chosen by a mask of its bit. + + @param checksum The checksum so far, which may be secret. + @param value The next 5-bit value, which may be secret. + @return The checksum after it. +*/ +[[nodiscard]] constexpr bech32_word bech32_step(bech32_word checksum, bech32_word value) noexcept { + bech32_word const top = checksum >> 25U; + bech32_word next = ((checksum & 0x1ffffffU) << 5U) ^ value; + for (std::size_t index = 0; index < bech32_generator.size(); ++index) { + bech32_word const bit_mask = + secure::constant_time::mask_from_bit(static_cast((top >> index) & 1U)); + next ^= secure::constant_time::select(bit_mask, bech32_generator[index], bech32_word{0}); + } + return next; +} + +/** + The checksum after a human-readable part's expansion (BIP-173's `hrp_expand`: the high three bits + of each character, a zero, then the low five of each), its letters folded to small. + + @param part The human-readable part, whose characters may be marked secret: they are read by + masks. + @return The checksum after it. +*/ +[[nodiscard]] constexpr bech32_word bech32_part_checksum(std::string_view part) noexcept { + bech32_word checksum = 1; + for (char const character : part) { + checksum = bech32_step(checksum, bech32_lower(bech32_code(character)) >> 5U); + } + checksum = bech32_step(checksum, 0); + for (char const character : part) { + checksum = bech32_step(checksum, bech32_lower(bech32_code(character)) & 31U); + } + return checksum; +} + +/** + The checksum's final value: six steps of zero, then the variant's constant. + + @param checksum The checksum after the data. + @param final_constant 1 for bech32, 0x2bc830a3 for bech32m. + @return The value whose six 5-bit groups are the checksum's characters. +*/ +[[nodiscard]] constexpr bech32_word bech32_final(bech32_word checksum, + bech32_word final_constant) noexcept { + for (std::size_t index = 0; index < bech32_checksum_size; ++index) { + checksum = bech32_step(checksum, 0); + } + return checksum ^ final_constant; +} + +/** + The 5-bit value of the checksum's character at `index`, the first the highest. + + @param final_value The checksum's final value. + @param index 0 to 5. + @return The value. +*/ +[[nodiscard]] constexpr bech32_word bech32_checksum_value(bech32_word final_value, + std::size_t index) noexcept { + return (final_value >> (5U * (bech32_checksum_size - 1 - index))) & 31U; +} + +/** + The characters of the data of `count` elements: one a word, or one every five bits of the bytes, + the last padded. + + @param count The bytes or the words. + @param words Whether the elements are words. + @return The characters, `SIZE_MAX` when they do not fit. +*/ +[[nodiscard]] constexpr std::size_t bech32_data_characters(std::size_t count, bool words) noexcept { + if (words) { + return count; + } + if (count > detail::size_maximum / 8) { + return detail::size_maximum; + } + return ((count * 8) + 4) / 5; +} + +/** + The elements of `data_characters` characters of data: one a character in words mode, else the + whole bytes of five bits a character. + + @param data_characters The characters of the data, the checksum's not among them. + @param words Whether the elements are words. + @return The elements. +*/ +[[nodiscard]] constexpr std::size_t bech32_data_count(std::size_t data_characters, + bool words) noexcept { + if (words) { + return data_characters; + } + return (data_characters / 8 * 5) + ((data_characters % 8) * 5 / 8); +} + +/** + The characters of a text: the human-readable part, the separator, the data and the checksum. + + @param part_size The human-readable part's characters. + @param count The bytes or the words of the data. + @param words Whether the elements are words. + @return The characters, `SIZE_MAX` when they do not fit. +*/ +[[nodiscard]] constexpr std::size_t bech32_text_size(std::size_t part_size, std::size_t count, + bool words) noexcept { + return saturating_add(saturating_add(part_size, 1 + bech32_checksum_size), + bech32_data_characters(count, words)); +} + +/** + A bound on the text of `count` elements over every human-readable part of an instance of + `maximum_length` characters: `SIZE_MAX` when no text of that data fits, a one-character part's + included, so that the core refuses the input before it reads it; else the longest part's text, at + most `maximum_length`. + + @param count The bytes or the words. + @param words Whether the elements are words. + @param maximum_length The instance's longest text. + @return The bound. +*/ +[[nodiscard]] constexpr std::size_t bech32_max_text_size(std::size_t count, bool words, + std::size_t maximum_length) noexcept { + if (bech32_text_size(1, count, words) > maximum_length) { + return detail::size_maximum; + } + std::size_t const longest = bech32_text_size(bech32_longest_part, count, words); + return longest < maximum_length ? longest : maximum_length; +} + +/** + A bound on the elements of a text of `text_size` characters in an instance of `maximum_length`: + `SIZE_MAX` past it, so that the core refuses the text before it reads it; else the elements of + the data of a one-character part. + + @param text_size The characters. + @param words Whether the elements are words. + @param maximum_length The instance's longest text. + @return The bound. +*/ +[[nodiscard]] constexpr std::size_t bech32_max_data_size(std::size_t text_size, bool words, + std::size_t maximum_length) noexcept { + if (text_size > maximum_length) { + return detail::size_maximum; + } + if (text_size < bech32_shortest_text) { + return 0; + } + return bech32_data_count(text_size - bech32_shortest_text, words); +} + +/** Where a valid text's parts are, and how many elements its data gives. */ +struct bech32_layout { + /** The position of the separator: the human-readable part's length, which is public. */ + std::size_t separator; + /** The bytes or the words of the data. */ + std::size_t count; +}; + +/** What a text is checked against: the format's own part, the variant, the data mode. */ +struct bech32_expectation { + /** The format's human-readable part; empty, any part is accepted. */ + std::string_view part; + /** The checksum's final constant: 1 for bech32, 0x2bc830a3 for bech32m. */ + bech32_word final_constant; + /** Whether the data are words, whose padding is none of decode's to check. */ + bool words; +}; + +/** + The human-readable part of a text: its characters before the separator. + + @param text The text. + @param separator The separator's position, at most the text's size. + @return The part. +*/ +[[nodiscard]] constexpr std::string_view bech32_part_of(std::string_view text, + std::size_t separator) noexcept { + text.remove_suffix(text.size() - separator); + return text; +} + +/** + The data part of a text: its characters after the separator, the checksum's included. + + @param text The text. + @param separator The separator's position, below the text's size. + @return The data part. +*/ +[[nodiscard]] constexpr std::string_view bech32_data_of(std::string_view text, + std::size_t separator) noexcept { + text.remove_prefix(separator + 1); + return text; +} + +/** + The separator of a text, its last `1`, found by masks over every character and made public by + `secure::declassify`: it is the length of the human-readable part, which is public. + + @param text The text, whose characters may be secret. + @return The separator's position, or the text's size when it has none. +*/ +[[nodiscard]] inline std::size_t bech32_separator(std::string_view text) noexcept { + std::size_t separator = text.size(); + for (std::size_t index = 0; index < text.size(); ++index) { + std::size_t const separator_mask = secure::constant_time::is_equal_mask( + static_cast(bech32_code(text[index])), std::size_t{'1'}); + separator = secure::constant_time::select(separator_mask, index, separator); + } + secure::declassify(separator); + return separator; +} + +/** + The mask of a text's mixed case: a capital letter and a small one anywhere in it. + + @param text The text, whose characters may be secret. + @return All ones when it mixes case, else zero. +*/ +[[nodiscard]] constexpr bech32_word bech32_mixed_case_mask(std::string_view text) noexcept { + // Not named small: (rpcndr.h) defines it as a macro. + bech32_word capital = 0; + bech32_word lower = 0; + for (char const character : text) { + bech32_word const code = bech32_code(character); + capital |= + secure::constant_time::is_in_range_mask(code, bech32_word{'A'}, bech32_word{'Z'}); + lower |= secure::constant_time::is_in_range_mask(code, bech32_word{'a'}, bech32_word{'z'}); + } + return capital & lower; +} + +/** + The mask of the faults of a text's human-readable part: none, or longer than 83 characters (both + public), a character outside 33 to 126, or, when the format has a part of its own, another part + than it, either case (public by its length, by masks over the characters). + + @param part The text's human-readable part, whose characters may be secret. + @param expected The format's part; empty, any part is accepted. + @return All ones for a fault, else zero. +*/ +[[nodiscard]] constexpr bech32_word bech32_part_fault_mask(std::string_view part, + std::string_view expected) noexcept { + bool const compared = !expected.empty(); + bech32_word fault = bech32_public_mask(part.empty() || part.size() > bech32_longest_part || + (compared && expected.size() != part.size())); + bool const same_size = compared && expected.size() == part.size(); + for (std::size_t index = 0; index < part.size(); ++index) { + bech32_word const code = bech32_code(part[index]); + fault |= static_cast( + ~secure::constant_time::is_in_range_mask(code, bech32_word{33}, bech32_word{126})); + if (same_size) { + fault |= static_cast(~secure::constant_time::is_equal_mask( + bech32_lower(code), bech32_lower(bech32_code(expected[index])))); + } + } + return fault; +} + +/** + The verdict over a whole text, every fault found by masks and the one of the lowest value + reported (B23): @ref error::invalid_character for a character of the data outside the alphabet, + @ref error::invalid_length for a data part shorter than the checksum, @ref error::invalid_padding + over bytes for more than 4 padding bits or a non-zero one, @ref error::checksum_mismatch, + @ref error::invalid_prefix for a human-readable part none may have or other than the format's, + @ref error::mixed_case. A text with no separator has no human-readable part and no data: + @ref error::invalid_prefix. The faults pass through `secure::declassify` as one value, the error's, + before the one branch on it; the separator's position, the part's length, is the other value that + does. + + @param text The text, at most the instance's maximum length, whose characters may be secret. + @param expected The format's part, variant and data mode. + @return Where its parts are, or the error. +*/ +[[nodiscard]] inline result bech32_check( + std::string_view text, bech32_expectation const& expected) noexcept { + namespace constant_time = secure::constant_time; + std::size_t const separator = bech32_separator(text); + if (separator == text.size()) { + return error::invalid_prefix; + } + std::string_view const part = bech32_part_of(text, separator); + std::string_view const data = bech32_data_of(text, separator); + bool const too_short = data.size() < bech32_checksum_size; + std::size_t const word_count = too_short ? 0 : data.size() - bech32_checksum_size; + + bech32_word checksum = bech32_part_checksum(part); + bech32_word character_fault = 0; + bech32_word last_value = 0; + for (std::size_t index = 0; index < data.size(); ++index) { + bech32_reading const reading = bech32_value(data[index]); + character_fault |= reading.invalid_mask; + checksum = bech32_step(checksum, reading.value); + // The index is public: the value is kept, not branched on. + if (index + 1 == word_count) { + last_value = reading.value; + } + } + bech32_word padding_fault = 0; + if (!expected.words) { + std::size_t const padding_bits = (word_count * 5) % 8; + bech32_word const padding_bit_mask = (bech32_word{1} << padding_bits) - 1U; + padding_fault = + bech32_public_mask(padding_bits > 4) | + static_cast(~constant_time::is_zero_mask(last_value & padding_bit_mask)); + } + auto const checksum_fault = + static_cast(~constant_time::is_equal_mask(checksum, expected.final_constant)); + + // The fault of the lowest value wins: each select from the highest to the lowest. + auto const code_of = [](error fault) { return static_cast(fault); }; + bech32_word fault_code = 0; + fault_code = + constant_time::select(bech32_mixed_case_mask(text), code_of(error::mixed_case), fault_code); + fault_code = constant_time::select(bech32_part_fault_mask(part, expected.part), + code_of(error::invalid_prefix), fault_code); + fault_code = + constant_time::select(checksum_fault, code_of(error::checksum_mismatch), fault_code); + fault_code = constant_time::select(padding_fault, code_of(error::invalid_padding), fault_code); + fault_code = constant_time::select(bech32_public_mask(too_short), + code_of(error::invalid_length), fault_code); + fault_code = + constant_time::select(character_fault, code_of(error::invalid_character), fault_code); + secure::declassify(fault_code); + if (fault_code != 0) { + return static_cast(fault_code); + } + return bech32_layout{ + .separator = separator, + .count = bech32_data_count(word_count, expected.words), + }; +} + +/** + Writes the data of a text found valid: its words as they are, or its 5-bit values regrouped into + bytes. Element `j` is written after the characters it comes from are read, at or before the + place of the first of them, so that `output` may start at the data's first character, as the + stream decoder's hold does. + + @param text The text. + @param layout Its layout, as @ref bech32_check gave it. + @param words Whether the elements are words. + @param output The elements: exactly `layout.count`. +*/ +inline void bech32_write_data(std::string_view text, bech32_layout const& layout, bool words, + std::span output) noexcept { + std::string_view data = bech32_data_of(text, layout.separator); + data.remove_suffix(bech32_checksum_size); + bech32_word bits = 0; + std::size_t bit_count = 0; + std::size_t written = 0; + for (std::size_t index = 0; index < data.size(); ++index) { + bech32_word const value = bech32_value(data[index]).value; + if (words) { + output[index] = static_cast(value); + continue; + } + bits = ((bits << 5U) | value) & 0xfffU; + bit_count += 5; + if (bit_count >= 8) { + bit_count -= 8; + output[written++] = static_cast(bits >> bit_count); + } + } +} + +/** + Writes a human-readable part with its letters folded to small, by masks. + + @param part The part, whose characters may be secret. + @param output Its characters: exactly `part.size()`; it may be the part's own storage. +*/ +constexpr void bech32_write_part(std::string_view part, std::span output) noexcept { + for (std::size_t index = 0; index < part.size(); ++index) { + output[index] = static_cast(bech32_lower(bech32_code(part[index]))); + } +} + +/** + The mask of words above 31, accumulated over every word with no early exit. + + @param words The words, which may be secret. + @return All ones when a word is above 31, else zero. +*/ +[[nodiscard]] constexpr bech32_word bech32_words_fault_mask( + std::span words) noexcept { + bech32_word fault = 0; + for (std::uint8_t const word : words) { + fault |= static_cast( + ~secure::constant_time::is_less_mask(bech32_word{word}, bech32_word{32})); + } + return fault; +} + +/** + Writes a whole text: the human-readable part in small letters, the separator, the data's + characters and the checksum's. + + @param part The format's human-readable part, which is public. + @param input The bytes, or the words, each read through its low five bits. + @param words Whether the elements are words. + @param final_constant The checksum's final constant. + @param output The characters: exactly `bech32_text_size(part.size(), input.size(), words)`. +*/ +inline void bech32_encode_text(std::string_view part, std::span input, + bool words, bech32_word final_constant, + std::span output) noexcept { + bech32_write_part(part, output.first(part.size())); + std::size_t written = part.size(); + output[written++] = '1'; + bech32_word checksum = bech32_part_checksum(part); + auto const emit = [&](bech32_word value) noexcept { + output[written++] = bech32_character(value); + checksum = bech32_step(checksum, value); + }; + bech32_word bits = 0; + std::size_t bit_count = 0; + for (std::uint8_t const element : input) { + if (words) { + emit(element & 31U); + continue; + } + bits = ((bits << 8U) | element) & 0xfffU; + bit_count += 8; + while (bit_count >= 5) { + bit_count -= 5; + emit((bits >> bit_count) & 31U); + } + } + if (bit_count != 0) { + emit((bits << (5 - bit_count)) & 31U); + } + bech32_word const final_value = bech32_final(checksum, final_constant); + for (std::size_t index = 0; index < bech32_checksum_size; ++index) { + output[written++] = bech32_character(bech32_checksum_value(final_value, index)); + } +} + +} // namespace webcpp::codecs::detail + +#endif // WEBCPP_CODECS_DETAIL_FORMATS_BECH32_HPP diff --git a/include/webcpp/codecs/detail/formats/bounded_label.hpp b/include/webcpp/codecs/detail/formats/bounded_label.hpp new file mode 100644 index 0000000..4a8dde5 --- /dev/null +++ b/include/webcpp/codecs/detail/formats/bounded_label.hpp @@ -0,0 +1,101 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + A label held in place in a format value, so that a configured format never dangles: bech32's + human-readable part and the armor's label. A label longer than its bound is kept as the fact that + it overflowed, which the format's codec reports as a fault of its configuration. +*/ +#ifndef WEBCPP_CODECS_DETAIL_FORMATS_BOUNDED_LABEL_HPP +#define WEBCPP_CODECS_DETAIL_FORMATS_BOUNDED_LABEL_HPP + +#include + +#include +#include +#include + +namespace webcpp::codecs::detail { + +/** + Up to `N` characters held in place, copied from a `std::string_view`; a longer one holds nothing + and says that it overflowed. + + It is a regular, trivially copyable type, usable in a constant expression, so that a format value + that holds one stays a value a program writes as a constant. + + @tparam N The most characters it holds. +*/ +template +class bounded_label { +public: + /** No label: nothing held, and no overflow. */ + constexpr bounded_label() noexcept = default; + + /** + Holds a copy of `label`, or nothing and the overflow when it is longer than `N`. + + @param label The characters, which the label does not borrow. + */ + constexpr explicit bounded_label(std::string_view label) noexcept { + if (label.size() > N) { + overflowed_ = true; + return; + } + for (std::size_t index = 0; index < label.size(); ++index) { + characters_[index] = label[index]; + } + size_ = label.size(); + } + + /** + The characters held, valid while this label is. + + @return A view of them; empty when nothing is held, an overflowed label included. + */ + [[nodiscard]] constexpr std::string_view view() const noexcept { + return {characters_.data(), size_}; + } + + /** + Whether no character is held: no label was given, an empty one was, or it overflowed. + + @return Whether the view is empty. + */ + [[nodiscard]] constexpr bool empty() const noexcept { return size_ == 0; } + + /** + Whether the label given was longer than `N` characters, so that nothing is held. + + @return Whether it overflowed. + */ + [[nodiscard]] constexpr bool overflowed() const noexcept { return overflowed_; } + + /** + Whether two labels hold the same characters and the same overflow. + + @param first_label A label. + @param second_label Another label. + @return Whether they are the same. + */ + friend constexpr bool operator==(bounded_label const& first_label, + bounded_label const& second_label) noexcept { + return first_label.view() == second_label.view() && + first_label.overflowed_ == second_label.overflowed_; + } + +private: + /** The characters, those past `size_` zero. */ + std::array characters_{}; + /** How many characters are held. */ + std::size_t size_ = 0; + /** Whether the label given was longer than `N`. */ + bool overflowed_ = false; +}; + +} // namespace webcpp::codecs::detail + +#endif // WEBCPP_CODECS_DETAIL_FORMATS_BOUNDED_LABEL_HPP diff --git a/include/webcpp/codecs/detail/formats/hex.hpp b/include/webcpp/codecs/detail/formats/hex.hpp new file mode 100644 index 0000000..2d4ca3d --- /dev/null +++ b/include/webcpp/codecs/detail/formats/hex.hpp @@ -0,0 +1,161 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The arithmetic of hex, which its codec and its stream codec share (``): a + nibble to its character and a character to its nibble by webcpp::secure's constant-time blocks, + with no table indexed by a data byte and no branch on one, and the verdict over a text, which + passes through `secure::declassify` before its one branch (D12). libsodium's `sodium_bin2hex` and + `sodium_hex2bin` are the reference for the method, written here over secure's masks. +*/ +#ifndef WEBCPP_CODECS_DETAIL_FORMATS_HEX_HPP +#define WEBCPP_CODECS_DETAIL_FORMATS_HEX_HPP + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace webcpp::codecs::detail { + +/** + The character of a nibble: `0` to `9` for 0 to 9, then the letters from `letter_base`, chosen by + a mask with no branch. + + @param nibble A value of 0 to 15, which may be secret. + @param letter_base `a` or `A`, the format's case, which is public. + @return The character. +*/ +[[nodiscard]] constexpr char hex_character(std::uint8_t nibble, char letter_base) noexcept { + // In unsigned, a mask word of secure's that no promotion turns signed. + auto const value = static_cast(nibble); + auto const digit_mask = secure::constant_time::is_less_mask(value, 10U); + unsigned const digit = '0' + value; + unsigned const letter = + static_cast(static_cast(letter_base)) + value - 10U; + return static_cast(secure::constant_time::select(digit_mask, digit, letter)); +} + +/** What a character reads as: its nibble, and the mask of whether it is no hex digit. */ +struct hex_reading { + /** The nibble, 0 for a character that is no hex digit. */ + std::uint8_t value; + /** All ones when the character is no hex digit, else zero. */ + std::uint8_t invalid_mask; +}; + +/** + Reads a character as a hex digit, either case: three range masks over its byte value, read as an + unsigned byte first, since a `char` from 0x80 up is negative where `char` is signed. + + @param character The character, which may be secret. + @return Its nibble and the mask of whether it is no hex digit. +*/ +[[nodiscard]] constexpr hex_reading hex_nibble(char character) noexcept { + // The byte value first, then the unsigned mask word of secure's. + auto const code = static_cast(static_cast(character)); + auto const digit_mask = + secure::constant_time::is_in_range_mask(code, unsigned{'0'}, unsigned{'9'}); + auto const lower_mask = + secure::constant_time::is_in_range_mask(code, unsigned{'a'}, unsigned{'f'}); + auto const upper_mask = + secure::constant_time::is_in_range_mask(code, unsigned{'A'}, unsigned{'F'}); + unsigned const digit_value = code - unsigned{'0'}; + unsigned const lower_value = code - (unsigned{'a'} - 10U); + unsigned const upper_value = code - (unsigned{'A'} - 10U); + return hex_reading{ + .value = static_cast((digit_mask & digit_value) | (lower_mask & lower_value) | + (upper_mask & upper_value)), + .invalid_mask = static_cast(~(digit_mask | lower_mask | upper_mask)), + }; +} + +/** + Writes the two characters of each byte of `input_bytes`, its high nibble first. + + @param input_bytes The bytes. + @param output_characters Their characters, two a byte: exactly `2 * input_bytes.size()`. + @param letter_base `a` or `A`, the format's case. +*/ +constexpr void hex_encode_bytes(std::span input_bytes, + std::span output_characters, char letter_base) noexcept { + std::size_t character_index = 0; + for (std::uint8_t const input_byte : input_bytes) { + output_characters[character_index] = + hex_character(static_cast(input_byte >> 4U), letter_base); + output_characters[character_index + 1] = + hex_character(static_cast(input_byte & 15U), letter_base); + character_index += 2; + } +} + +/** + The mask of a text's characters that are no hex digit, accumulated over every character with no + early exit. + + @param text_characters The text. + @return Zero when every character is a hex digit, else all ones. +*/ +[[nodiscard]] constexpr std::uint8_t hex_invalid_mask(std::string_view text_characters) noexcept { + std::uint8_t invalid_mask = 0; + for (char const text_character : text_characters) { + invalid_mask |= hex_nibble(text_character).invalid_mask; + } + return invalid_mask; +} + +/** + Writes the byte of each pair of digits of a text found valid. + + Byte `i` is written after characters `2i` and `2i + 1` are read, so that `output_bytes` may be the + text's own storage. + + @param text_characters The digits, `2 * output_bytes.size()` of them at least. + @param output_bytes The bytes. +*/ +constexpr void hex_decode_pairs(std::string_view text_characters, + std::span output_bytes) noexcept { + for (std::size_t byte_index = 0; byte_index < output_bytes.size(); ++byte_index) { + unsigned const high_nibble = hex_nibble(text_characters[2 * byte_index]).value; + unsigned const low_nibble = hex_nibble(text_characters[(2 * byte_index) + 1]).value; + output_bytes[byte_index] = static_cast((high_nibble << 4U) | low_nibble); + } +} + +/** + The verdict over a whole text: @ref error::invalid_character when a character is no hex digit, + else @ref error::invalid_length for an odd count of characters (the lowest value wins, B23). + + The mask passes through `secure::declassify` before the one branch on it: the result's success is + public, the place of a bad character is not. + + @param invalid_mask The mask accumulated over the text, which is secret. + @param character_count The text's characters, which is public. + @return The fault, or `std::nullopt` for a valid text. +*/ +[[nodiscard]] inline std::optional hex_verdict(std::uint8_t invalid_mask, + std::size_t character_count) noexcept { + std::uint8_t verdict = invalid_mask; + secure::declassify(verdict); + if (verdict != 0) { + return error::invalid_character; + } + if (character_count % 2 != 0) { + return error::invalid_length; + } + return std::nullopt; +} + +} // namespace webcpp::codecs::detail + +#endif // WEBCPP_CODECS_DETAIL_FORMATS_HEX_HPP diff --git a/include/webcpp/codecs/detail/formats/options.hpp b/include/webcpp/codecs/detail/formats/options.hpp new file mode 100644 index 0000000..8d59dfc --- /dev/null +++ b/include/webcpp/codecs/detail/formats/options.hpp @@ -0,0 +1,82 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The options that more than one format takes, which each format's header brings with it: today + `formats::padding`, of base64 and base64url (``) and of base32 and + base32hex. +*/ +#ifndef WEBCPP_CODECS_DETAIL_FORMATS_OPTIONS_HPP +#define WEBCPP_CODECS_DETAIL_FORMATS_OPTIONS_HPP + +#include + +namespace webcpp::codecs::formats { + +/** + Whether a format writes its padding, `=`, which RFC 4648 section 3.2 completes the last group with. + + Decode takes the choice as the rule: a text with the padding the option does not give is refused + with @ref error::invalid_padding. A value of neither enumerator, cast from another integer + (`formats::padding{0}`), is read as `written`, RFC 4648's own form: a format omits its padding for + `padding::omitted` alone, as each format that takes the option (base64's, base32's) does. +*/ +enum class padding : unsigned char { + /** The last group is completed with `=` to a whole group: RFC 4648's own form. */ + written = 1, + /** No `=`: the last group is as short as its bytes make it (JOSE's and URLs' form). */ + omitted = 2, +}; + +} // namespace webcpp::codecs::formats + +namespace webcpp::codecs::detail { + +/** + What the formats that take the padding option have in common as values: the option and the call + that chooses it, in the type of the format that derives from it. + + @tparam Format The format's type, which derives from this one (the curiously recurring template). + @tparam OmittedByDefault Whether the format omits its padding by default (base64url does). +*/ +template +// A format is an aggregate a program value-initialises, `formats::base64_t{}`, so that the base's +// constructor must be public. +// NOLINTNEXTLINE(bugprone-crtp-constructor-accessibility): the formats are public aggregates +struct padding_options { + /** Whether the padding `=` is written; decode requires it exactly then. */ + formats::padding padding_option = + OmittedByDefault ? formats::padding::omitted : formats::padding::written; + + /** + The format with the padding `chosen`. + + @param chosen The padding. + @return The configured format. + */ + [[nodiscard]] constexpr Format operator()(formats::padding chosen) const noexcept { + Format configured{}; + configured.padding_option = chosen; + return configured; + } +}; + +/** + Whether a format that takes the padding option writes its padding: any option but + `padding::omitted`, so that a value cast into the enum is read as the RFC's own form. + + @tparam Format The format's type. + @param format_value The format. + @return Whether the padding is written. +*/ +template +[[nodiscard]] constexpr bool padding_is_written(Format const& format_value) noexcept { + return format_value.padding_option != formats::padding::omitted; +} + +} // namespace webcpp::codecs::detail + +#endif // WEBCPP_CODECS_DETAIL_FORMATS_OPTIONS_HPP diff --git a/include/webcpp/codecs/hex.hpp b/include/webcpp/codecs/hex.hpp new file mode 100644 index 0000000..dfe15ec --- /dev/null +++ b/include/webcpp/codecs/hex.hpp @@ -0,0 +1,653 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + hex, base16 (RFC 4648 section 8): each byte as two hex digits, its high nibble first. The format + `formats::hex` writes lower case, and `formats::hex(formats::letter_case::upper)` upper case, as + RFC 4648 does; decode takes either case, mixed included. It is constant time on every call, and + streams natively. +*/ +#ifndef WEBCPP_CODECS_HEX_HPP +#define WEBCPP_CODECS_HEX_HPP + +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace webcpp::codecs::formats { + +/** The case of the letters `a` to `f` a format writes. */ +enum class letter_case : unsigned char { + /** `a` to `f`. */ + lower = 1, + /** `A` to `F`. */ + upper = 2, +}; + +/** + The type of the format hex: base16, each byte as two hex digits, its high nibble first. + + Encode writes `written_case`; decode takes either case, mixed included, and refuses a text of an + odd length with @ref error::invalid_length and any character that is no hex digit with + @ref error::invalid_character, which wins when both are found. A text may be decoded into its own + storage: byte `i` is written after characters `2i` and `2i + 1` are read. Encode and decode, + one-shot and streamed, index no table by a data byte and branch on none (D12); the text's length + and the result's success are public. +*/ +struct hex_t { + /** The format's name. */ + static constexpr std::string_view name = "hex"; + + /** The case of the letters encode writes. */ + letter_case written_case = letter_case::lower; + + /** + The format writing letters in `chosen` case. + + @param chosen The case. + @return The configured format. + */ + [[nodiscard]] constexpr hex_t operator()(letter_case chosen) const noexcept { + return hex_t{.written_case = chosen}; + } +}; + +/** The format hex, writing lower case: `codecs::encode(formats::hex, digest)`. */ +inline constexpr hex_t hex{}; + +} // namespace webcpp::codecs::formats + +namespace webcpp::codecs { + +namespace detail { + +/** + The first letter hex writes in its format's case: `A` for upper case, else `a`. + + @param format_value The format, whose case is public. + @return `a` or `A`. +*/ +[[nodiscard]] constexpr char hex_letter_base(formats::hex_t const& format_value) noexcept { + return format_value.written_case == formats::letter_case::upper ? 'A' : 'a'; +} + +} // namespace detail + +/** The codec of hex: two digits a byte, in constant time. */ +template <> +struct codec { + /** hex indexes no table by a data byte and branches on none. */ + static constexpr bool constant_time = true; + + /** + Two characters a byte. + + @param input_size The bytes. + @return The characters, `SIZE_MAX` when they do not fit. + */ + static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept { + return detail::saturating_multiply(input_size, 2); + } + + /** + One byte every two characters. + + @param text_size The characters. + @return The most bytes. + */ + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { + return text_size / 2; + } + + /** + The exact size of the text of `input_bytes`: two characters a byte. + + @param format_value The format. + @param input_bytes The bytes. + @return The characters. + */ + static constexpr std::size_t encoded_size(formats::hex_t const& format_value, + std::span input_bytes) noexcept { + static_cast(format_value); + return max_encoded_size(input_bytes.size()); + } + + /** + The exact size of the bytes of `text_characters`, every character checked. + + @param format_value The format. + @param text_characters The text. + @return The bytes, or @ref error::invalid_character for a character that is no hex digit, + else @ref error::invalid_length for an odd length. + */ + [[nodiscard]] static result decoded_size( + formats::hex_t const& format_value, std::string_view text_characters) noexcept { + static_cast(format_value); + if (auto const fault = detail::hex_verdict(detail::hex_invalid_mask(text_characters), + text_characters.size())) { + return *fault; + } + return text_characters.size() / 2; + } + + /** + Writes the two digits of each byte of `input_bytes` at the start of `output_characters`. + + @param format_value The format, whose case the letters are written in. + @param input_bytes The bytes. + @param output_characters The buffer. + @return The characters written, or @ref error::output_too_small, with nothing written, when + `output_characters` cannot hold them. + */ + [[nodiscard]] static result encode(formats::hex_t const& format_value, + std::span input_bytes, + std::span output_characters) noexcept { + std::size_t const written_size = encoded_size(format_value, input_bytes); + if (output_characters.size() < written_size) { + return error::output_too_small; + } + detail::hex_encode_bytes(input_bytes, output_characters.first(written_size), + detail::hex_letter_base(format_value)); + return written_size; + } + + /** + Writes the bytes of `text_characters` at the start of `output_bytes`, after the whole text is + found valid; `output_bytes` may be the text's own storage. + + @param format_value The format. + @param text_characters The text. + @param output_bytes The buffer. + @return The bytes written, or the text's error as `decoded_size` gives it, else + @ref error::output_too_small, with nothing written. + */ + [[nodiscard]] static result decode(formats::hex_t const& format_value, + std::string_view text_characters, + std::span output_bytes) noexcept { + result const decoded_count = decoded_size(format_value, text_characters); + if (!decoded_count) { + return decoded_count; + } + // Read unchecked: the error was returned above. + std::size_t const byte_count = decoded_count.unsafe_value(); + if (output_bytes.size() < byte_count) { + return error::output_too_small; + } + detail::hex_decode_pairs(text_characters, output_bytes.first(byte_count)); + return byte_count; + } +}; + +/** + The stream codec of hex (D20): an encoder that holds one character of a pair its output had no + room for, and a decoder that holds one digit of a pair and the error mask, each in constant time. +*/ +template <> +struct stream_codec { + /** + The stream encoder: two digits a borrowed byte, written straight into the caller's span. + + The low digit of a byte whose high digit filled the span waits for the next `receive`. It + never fails. With `Options.secret` it is move-only and wipes the waiting digit by + `secure::erase_secret` on `reset`, on destruction and in the moved-from encoder. + + @tparam Options The stream's options. + */ + template + class encoder { + public: + /** Whether the stream wipes its pending state: it is secret. */ + static constexpr bool wipes = Options.secret; + + /** The bytes read. */ + using input_type = std::uint8_t; + /** The digits written. */ + using output_type = char; + + /** + An encoder in `flow::needs_input`, writing the case of `format_value`. + + @param format_value The format. + */ + explicit encoder(formats::hex_t const& format_value) noexcept + : letter_base_(detail::hex_letter_base(format_value)) {} + + /** A copy of the state, borrowing what the other borrows; a secret stream has none. */ + encoder(encoder const&) noexcept + requires(!Options.secret) + = default; + /** + A copy of the state, borrowing what the other borrows; a secret stream has none. + + @return This encoder. + */ + encoder& operator=(encoder const&) noexcept + requires(!Options.secret) + = default; + + /** + Takes `other`'s state and leaves `other` as `reset` does. + + @param other The encoder moved from. + */ + encoder(encoder&& other) noexcept + : borrowed_(other.borrowed_), + position_(other.position_), + pending_(other.pending_), + has_pending_(other.has_pending_), + flushed_(other.flushed_), + letter_base_(other.letter_base_) { + other.reset(); + } + + /** + Takes `other`'s state and leaves `other` as `reset` does. + + @param other The encoder moved from. + @return This encoder. + */ + encoder& operator=(encoder&& other) noexcept { + if (this != &other) { + borrowed_ = other.borrowed_; + position_ = other.position_; + pending_ = other.pending_; + has_pending_ = other.has_pending_; + flushed_ = other.flushed_; + letter_base_ = other.letter_base_; + other.reset(); + } + return *this; + } + + /** Wipes the waiting digit of a secret stream. */ + ~encoder() + requires wipes + { + wipe_pending(); + } + + /** A public stream wipes nothing. */ + ~encoder() = default; + + /** + Borrows all of `input` in `flow::needs_input`, and accepts nothing in another state. + + @param input The bytes to encode. + @return The bytes accepted and the state after. + */ + [[nodiscard]] result send(std::span input) noexcept { + if (state() != flow::needs_input) { + return step{.count = 0, .flow = state()}; + } + borrowed_ = input; + position_ = 0; + return step{.count = input.size(), .flow = state()}; + } + + /** + Writes the waiting digit, then two digits a borrowed byte, as `output` has room. + + @param output The span to write into. + @return The digits written and the state after. + */ + [[nodiscard]] result receive(std::span output) noexcept { + std::size_t written = 0; + if (has_pending_ && written < output.size()) { + output[written++] = pending_; + has_pending_ = false; + } + while (position_ < borrowed_.size() && written < output.size()) { + std::uint8_t const input_byte = borrowed_[position_++]; + output[written++] = detail::hex_character( + static_cast(input_byte >> 4U), letter_base_); + char const low_digit = detail::hex_character( + static_cast(input_byte & 15U), letter_base_); + if (written < output.size()) { + output[written++] = low_digit; + } else { + pending_ = low_digit; + has_pending_ = true; + } + } + if (position_ == borrowed_.size()) { + borrowed_ = {}; + position_ = 0; + } + return step{.count = written, .flow = state()}; + } + + /** + Ends the input: hex has no fault of the data to find in bytes. + + @return `flow::output_pending` while digits remain, else `flow::finished`. + */ + [[nodiscard]] result flush() noexcept { + flushed_ = true; + return state(); + } + + /** + Back to `flow::needs_input`, nothing borrowed or pending; the waiting digit of a secret + stream wiped. + */ + void reset() noexcept { + wipe_pending(); + borrowed_ = {}; + position_ = 0; + pending_ = 0; + has_pending_ = false; + flushed_ = false; + } + + private: + /** Wipes the waiting digit, a byte, when the stream is secret. */ + void wipe_pending() noexcept { + if constexpr (Options.secret) { + secure::erase_secret(std::span{&pending_, 1}); + } + } + + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (has_pending_ || position_ < borrowed_.size()) { + return flow::output_pending; + } + return flushed_ ? flow::finished : flow::needs_input; + } + + /** The bytes `send` accepted. */ + std::span borrowed_; + /** The next borrowed byte to read. */ + std::size_t position_ = 0; + /** The low digit the output had no room for. */ + char pending_ = 0; + /** Whether `pending_` waits. */ + bool has_pending_ = false; + /** Whether `flush` ended the input. */ + bool flushed_ = false; + /** `a` or `A`: the format's case, which stays across `reset`. */ + char letter_base_; + }; + + /** + The stream decoder: a byte for each pair of digits, written straight into the caller's span. + + The first digit of a pair whose second is not borrowed yet is held. Every digit's verdict is + accumulated in a mask, and reported after `flush` by the call that reads the end of the input, + which runs it over everything still borrowed before it writes, as the one-shot form reports + it (B44): @ref error::invalid_character, else @ref error::invalid_length. The bytes delivered + before `flush` may come from pairs that later fail that verdict (the error is reported after + `flush` so that the time does not depend on where the text is invalid): a caller discards what + was delivered when the stream reports an error. For "0g12", two bytes are delivered and + `flush` then reports @ref error::invalid_character. With + `Options.secret` it is move-only and wipes the held digit and the error mask by + `secure::erase_secret` on `reset`, on destruction and in the moved-from decoder. + + @tparam Options The stream's options. + */ + template + class decoder { + public: + /** Whether the stream wipes its pending state: it is secret. */ + static constexpr bool wipes = Options.secret; + + /** The digits read. */ + using input_type = char; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** + A decoder in `flow::needs_input`; it reads either case, whatever the format's. + + @param format_value The format. + */ + explicit decoder(formats::hex_t const& format_value) noexcept { + static_cast(format_value); + } + + /** A copy of the state, borrowing what the other borrows; a secret stream has none. */ + decoder(decoder const&) noexcept + requires(!Options.secret) + = default; + /** + A copy of the state, borrowing what the other borrows; a secret stream has none. + + @return This decoder. + */ + decoder& operator=(decoder const&) noexcept + requires(!Options.secret) + = default; + + /** + Takes `other`'s state and leaves `other` as `reset` does. + + @param other The decoder moved from. + */ + decoder(decoder&& other) noexcept + : borrowed_(other.borrowed_), + position_(other.position_), + held_(other.held_), + has_held_(other.has_held_), + invalid_mask_(other.invalid_mask_), + flushed_(other.flushed_), + verdict_passed_(other.verdict_passed_), + error_(other.error_) { + other.reset(); + } + + /** + Takes `other`'s state and leaves `other` as `reset` does. + + @param other The decoder moved from. + @return This decoder. + */ + decoder& operator=(decoder&& other) noexcept { + if (this != &other) { + borrowed_ = other.borrowed_; + position_ = other.position_; + held_ = other.held_; + has_held_ = other.has_held_; + invalid_mask_ = other.invalid_mask_; + flushed_ = other.flushed_; + verdict_passed_ = other.verdict_passed_; + error_ = other.error_; + other.reset(); + } + return *this; + } + + /** Wipes the held digit and the error mask of a secret stream. */ + ~decoder() + requires wipes + { + wipe_held(); + } + + /** A public stream wipes nothing. */ + ~decoder() = default; + + /** + Borrows all of `input` in `flow::needs_input`, and accepts nothing in another state; a lone + digit is held at once, which frees the input. + + @param input The digits to decode. + @return The digits accepted and the state after, or the error found after `flush`. + */ + [[nodiscard]] result send(std::span input) noexcept { + if (failed()) { + return error_; + } + if (state() != flow::needs_input) { + return step{.count = 0, .flow = state()}; + } + borrowed_ = input; + position_ = 0; + hold_lone_digit(); + return step{.count = input.size(), .flow = state()}; + } + + /** + Writes a byte for each pair of digits, as `output` has room. + + After `flush`, the first call runs the verdict over what is still borrowed and returns its + error, writing nothing. + + @param output The span to write into. + @return The bytes written and the state after, or the error. + */ + [[nodiscard]] result receive(std::span output) noexcept { + if (failed()) { + return error_; + } + if (flushed_ && !verdict_passed_ && !pass_verdict()) { + return error_; + } + std::size_t written = 0; + while (written < output.size()) { + if (!has_held_) { + if (borrowed_.size() - position_ < 2) { + break; + } + take_held(borrowed_[position_++]); + } + if (position_ == borrowed_.size()) { + break; + } + detail::hex_reading const low_digit = detail::hex_nibble(borrowed_[position_++]); + invalid_mask_ |= low_digit.invalid_mask; + output[written++] = static_cast((static_cast(held_) << 4U) | + low_digit.value); + has_held_ = false; + } + hold_lone_digit(); + if (position_ == borrowed_.size()) { + borrowed_ = {}; + position_ = 0; + } + return step{.count = written, .flow = state()}; + } + + /** + Ends the input; with nothing borrowed, it runs the verdict and reports its error itself. + + @return `flow::output_pending` while bytes remain, else `flow::finished`, or the error. + */ + [[nodiscard]] result flush() noexcept { + if (failed()) { + return error_; + } + if (!flushed_) { + flushed_ = true; + if (position_ == borrowed_.size() && !pass_verdict()) { + return error_; + } + } + return state(); + } + + /** + Back to `flow::needs_input`, nothing borrowed or held, the verdict and the error + forgotten; the held digit and the error mask of a secret stream wiped. + */ + void reset() noexcept { + wipe_held(); + borrowed_ = {}; + position_ = 0; + held_ = 0; + has_held_ = false; + invalid_mask_ = 0; + flushed_ = false; + verdict_passed_ = false; + error_.clear(); + } + + private: + /** Wipes the held digit and the error mask, a byte each, when the stream is secret. */ + void wipe_held() noexcept { + if constexpr (Options.secret) { + secure::erase_secret(std::span{&held_, 1}); + secure::erase_secret(std::span{&invalid_mask_, 1}); + } + } + + /** Holds the nibble of `digit`, the first of a pair, its verdict accumulated. */ + void take_held(char digit) noexcept { + detail::hex_reading const reading = detail::hex_nibble(digit); + invalid_mask_ |= reading.invalid_mask; + held_ = reading.value; + has_held_ = true; + } + + /** Holds the last borrowed digit when it is alone, which frees the borrow. */ + void hold_lone_digit() noexcept { + if (!has_held_ && borrowed_.size() - position_ == 1) { + take_held(borrowed_[position_++]); + } + } + + /** + The verdict over the whole input, what is still borrowed included, as `decoded_size` + gives it for the whole text: a digit read in pairs before counts in the mask, and the + held digit in the length. + + @return Whether the input is valid; the error is set when it is not. + */ + [[nodiscard]] bool pass_verdict() noexcept { + std::span const unread = borrowed_.subspan(position_); + auto const invalid_mask = + static_cast(invalid_mask_ | detail::hex_invalid_mask(std::string_view{ + unread.data(), unread.size()})); + std::size_t const character_count = + (has_held_ ? std::size_t{1} : std::size_t{0}) + unread.size(); + if (auto const fault = detail::hex_verdict(invalid_mask, character_count)) { + error_ = *fault; + } + verdict_passed_ = !error_; + return verdict_passed_; + } + + /** Whether a call reports an error, which stays until `reset`. */ + [[nodiscard]] bool failed() const noexcept { return static_cast(error_); } + + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (position_ < borrowed_.size()) { + return flow::output_pending; + } + return flushed_ ? flow::finished : flow::needs_input; + } + + /** The digits `send` accepted. */ + std::span borrowed_; + /** The next borrowed digit to read. */ + std::size_t position_ = 0; + /** The nibble of the first digit of a pair whose second is not read yet. */ + std::uint8_t held_ = 0; + /** Whether `held_` waits. */ + bool has_held_ = false; + /** All ones once a character that is no hex digit was read, else zero. */ + std::uint8_t invalid_mask_ = 0; + /** Whether `flush` ended the input. */ + bool flushed_ = false; + /** Whether the verdict over the whole input passed. */ + bool verdict_passed_ = false; + /** The error every call returns until `reset`. */ + boost::system::error_code error_; + }; +}; + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_HEX_HPP diff --git a/include/webcpp/codecs/percent.hpp b/include/webcpp/codecs/percent.hpp new file mode 100644 index 0000000..858fb85 --- /dev/null +++ b/include/webcpp/codecs/percent.hpp @@ -0,0 +1,860 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + percent, percent-encoding (RFC 3986 section 2.1) over Boost.URL: each byte outside a `CharSet` as + `%` and two hex digits. The format `formats::percent` leaves the unreserved characters of RFC 3986 + as they are, and `formats::percent(boost::urls::pchars)` or any other Boost.URL `CharSet` and + `boost::urls::encoding_opts` choose the characters left as they are, the case of the digits and a + plus sign for a space. The sizes, encode and decode are Boost.URL's own, byte for byte. It is not + constant time, and streams natively. + + This is the only header of codecs that includes Boost.URL, whose decode is compiled: a program that + includes it names the target `/webcpp/codecs//percent`. +*/ +#ifndef WEBCPP_CODECS_PERCENT_HPP +#define WEBCPP_CODECS_PERCENT_HPP + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs::formats { + +/** + The type of the format percent: percent-encoding over Boost.URL, with the `CharSet` of the + characters it leaves as they are and the options of Boost.URL's `encoding_opts`. + + Encode writes a byte of `char_set` as it is and every other byte as `%` and two hex digits, in + upper case unless `options.lower_case`; with `options.space_as_plus` a space is written as `+` + and a plus sign always as `%2B`, as `boost::urls::encode` does. The percent sign is never a + character of the set: it is written as `%25` whatever `char_set` holds, as `reserved_chars`, + which names it, would otherwise give a text no decode reads back. + + Decode reads each escape, and a `+` as a space when `options.space_as_plus`. As + `boost::urls::decode`, it does not check that the characters it takes as they are belong to the + set: a text that holds a character the set would escape decodes to that character. It refuses a + `%` followed by a character that is no hex digit with @ref error::invalid_character, and a text + that ends inside an escape with @ref error::invalid_length; a text that does both, as `"%g"`, + gets @ref error::invalid_character, the lowest value. `options.disallow_null` is Boost.URL's, + which neither its encode nor its decode reads. Input and output must not overlap: the decode is + `boost::urls::decode`'s, which promises nothing of overlapping buffers. +*/ +struct percent_t { + /** The format's name. */ + static constexpr std::string_view name = "percent"; + + /** The characters encode leaves as they are: the unreserved characters by default. */ + boost::urls::grammar::lut_chars char_set = boost::urls::unreserved_chars; + + /** Boost.URL's options of encode and decode: none by default. */ + boost::urls::encoding_opts options{}; + + /** + The format leaving the characters of `chosen` as they are and using `chosen_options`. + + @tparam CharSet The type of a Boost.URL `CharSet`: a type invocable with a `char` that gives + whether the character is in the set, as `boost::urls::pchars` and + `boost::urls::grammar::lut_chars` are. + @param chosen Any Boost.URL `CharSet`, held as `boost::urls::grammar::lut_chars`. + @param chosen_options The options of encode and decode. + @return The configured format. + */ + template + requires boost::urls::grammar::is_charset::value + [[nodiscard]] constexpr percent_t operator()( + CharSet const& chosen, boost::urls::encoding_opts chosen_options = {}) const noexcept { + return percent_t{ + .char_set = boost::urls::grammar::lut_chars(chosen), + .options = chosen_options, + }; + } +}; + +/** The format percent, leaving the unreserved characters: `codecs::encode(formats::percent, text)`. + */ +inline constexpr percent_t percent{}; + +} // namespace webcpp::codecs::formats + +namespace webcpp::codecs { + +namespace detail { + +/** The progress of an escape through the characters of a text: its stage, nibble and fault. */ +using percent_progress = std::array; + +/** The place in a @ref percent_progress of its stage: 0 outside an escape, 1 after `%`, 2 after `%` + * and a digit. */ +inline constexpr std::size_t percent_stage = 0; +/** The place in a @ref percent_progress of the first digit's value, at stage 2. */ +inline constexpr std::size_t percent_nibble = 1; +/** The place in a @ref percent_progress of whether a `%` was followed by a character that is no hex + * digit. */ +inline constexpr std::size_t percent_invalid = 2; + +/** + The characters `format_value` leaves as they are: its `char_set` less the percent sign, which + `boost::urls::encode` asks its set never to hold. + + @param format_value The format. + @return The set encode passes to Boost.URL. +*/ +[[nodiscard]] constexpr boost::urls::grammar::lut_chars percent_set( + formats::percent_t const& format_value) noexcept { + return format_value.char_set - boost::urls::grammar::lut_chars('%'); +} + +/** + The value of a hex digit. + + @param character The character. + @return 0 to 15, or -1 when it is no hex digit. +*/ +[[nodiscard]] constexpr int percent_digit(char character) noexcept { + auto const value = static_cast(character); + if (value >= '0' && value <= '9') { + return value - '0'; + } + if (value >= 'a' && value <= 'f') { + return value - 'a' + 10; + } + if (value >= 'A' && value <= 'F') { + return value - 'A' + 10; + } + return -1; +} + +/** + Whether the escape a text ends in is truncated by a character that is no hex digit: a `%` and the + last character, which is not one. Boost.URL reports such a text, `"%g"`, as an incomplete + escape, though it holds a bad digit too (pre-flight F26). + + @param text_characters The text. + @return Whether its last two characters are a `%` and a character that is no hex digit. +*/ +[[nodiscard]] constexpr bool percent_ends_in_bad_digit(std::string_view text_characters) noexcept { + return text_characters.size() >= 2 && text_characters[text_characters.size() - 2] == '%' && + percent_digit(text_characters.back()) < 0; +} + +/** + The error of codecs a Boost.URL error of the text stands for: a bad hex digit, and a truncated + escape that holds one, are @ref error::invalid_character, the lowest value of the two; a truncated + escape is @ref error::invalid_length; any other is @ref error::invalid_character (B20). + + @param failure Boost.URL's error. + @param text_characters The text Boost.URL refused. + @return The error. +*/ +[[nodiscard]] inline error percent_error(boost::system::error_code const& failure, + std::string_view text_characters) noexcept { + if (failure == boost::urls::error::incomplete_encoding && + !percent_ends_in_bad_digit(text_characters)) { + return error::invalid_length; + } + return error::invalid_character; +} + +/** + Whether reading `character` writes a byte: outside an escape any character but `%`, and the + second digit of an escape when it is a hex digit; never once a fault is known. + + @param progress The progress of the escape so far. + @param character The next character. + @return Whether `percent_read` returns a byte for it. +*/ +[[nodiscard]] constexpr bool percent_writes(percent_progress const& progress, + char character) noexcept { + if (progress[percent_invalid] != 0) { + return false; + } + if (progress[percent_stage] == 0) { + return character != '%'; + } + return progress[percent_stage] == 2 && percent_digit(character) >= 0; +} + +/** + Reads `character`, as `boost::urls::decode` does: a `%` begins an escape, two hex digits end it, + `+` is a space when `space_as_plus`, any other character is its own byte. A `%` followed by a + character that is no hex digit is a fault, kept in `progress` until the progress is rebuilt; once + it is known, no character gives a byte any more, since the text is refused whatever follows. + + @param progress The progress of the escape so far, which this updates. + @param character The next character. + @param space_as_plus Whether a `+` is a space. + @return The byte the character completes, or no byte. +*/ +[[nodiscard]] constexpr std::optional percent_read(percent_progress& progress, + char character, + bool space_as_plus) noexcept { + if (progress[percent_invalid] != 0) { + return std::nullopt; + } + if (progress[percent_stage] == 0) { + if (character == '%') { + progress[percent_stage] = 1; + return std::nullopt; + } + if (space_as_plus && character == '+') { + return std::uint8_t{' '}; + } + return static_cast(character); + } + int const digit = percent_digit(character); + if (digit < 0) { + progress[percent_stage] = 0; + progress[percent_nibble] = 0; + progress[percent_invalid] = 1; + return std::nullopt; + } + auto const digit_value = static_cast(digit); + if (progress[percent_stage] == 1) { + progress[percent_stage] = 2; + progress[percent_nibble] = digit_value; + return std::nullopt; + } + progress[percent_stage] = 0; + return static_cast((static_cast(progress[percent_nibble]) << 4U) | + digit_value); +} + +/** + The fault of a text read so far, as the one-shot form reports it for the whole text: a character + that is no hex digit after a `%` is @ref error::invalid_character, a text that ends inside an + escape @ref error::invalid_length. + + @param progress The progress after the last character. + @return The fault, or none. +*/ +[[nodiscard]] constexpr std::optional percent_fault( + percent_progress const& progress) noexcept { + if (progress[percent_invalid] != 0) { + return error::invalid_character; + } + if (progress[percent_stage] != 0) { + return error::invalid_length; + } + return std::nullopt; +} + +/** + Writes the text of one byte, as `boost::urls::encode` writes it in a text of its own: the + character, or `%` and two digits, or `+`. + + @param input_byte The byte. + @param allowed The characters left as they are, the percent sign not among them. + @param encoding_options The options. + @param escape The place for up to three characters. + @return How many characters were written, 1 to 3. + @tparam Secret Whether the byte is secret: the copy of it that is read as a character is wiped. +*/ +template +[[nodiscard]] inline std::size_t percent_encode_byte(std::uint8_t input_byte, + boost::urls::grammar::lut_chars const& allowed, + boost::urls::encoding_opts encoding_options, + std::array& escape) noexcept { + std::array byte_character{static_cast(input_byte)}; + std::size_t const count = + boost::urls::encode(escape.data(), escape.size(), + std::string_view{byte_character.data(), 1}, allowed, encoding_options); + if constexpr (Secret) { + secure::erase_secret(byte_character); + } + return count; +} + +} // namespace detail + +/** The codec of percent: Boost.URL's sizes, encode and decode, with its errors as codecs'. */ +template <> +struct codec { + /** percent takes a different time for each byte: it is not constant time. */ + static constexpr bool constant_time = false; + + /** + Three characters a byte at most, for an escape. + + @param input_size The bytes. + @return The characters, `SIZE_MAX` when they do not fit. + */ + static constexpr std::size_t max_encoded_size(std::size_t input_size) noexcept { + return detail::saturating_multiply(input_size, 3); + } + + /** + One byte a character at most, for a character that is its own byte. + + @param text_size The characters. + @return The most bytes. + */ + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { + return text_size; + } + + /** + The exact size of the text of `input_bytes`, as `boost::urls::encoded_size` gives it. + + @param format_value The format. + @param input_bytes The bytes. + @return The characters. + */ + static std::size_t encoded_size(formats::percent_t const& format_value, + std::span input_bytes) noexcept { + return boost::urls::encoded_size( + std::string_view{reinterpret_cast(input_bytes.data()), input_bytes.size()}, + detail::percent_set(format_value), format_value.options); + } + + /** + The exact size of the bytes of `text_characters`, as `boost::urls::decoded_size` gives it. + + @param format_value The format. + @param text_characters The text. + @return The bytes, or @ref error::invalid_character for a `%` followed by a character that is + no hex digit, else @ref error::invalid_length for a text that ends inside an escape. + */ + [[nodiscard]] static result decoded_size( + formats::percent_t const& format_value, std::string_view text_characters) noexcept { + static_cast(format_value); + result const counted = boost::urls::decoded_size(text_characters); + if (!counted) { + return detail::percent_error(counted.error(), text_characters); + } + // Read unchecked: the error was returned above. + return counted.unsafe_value(); + } + + /** + Writes the text of `input_bytes` at the start of `output_characters`, as `boost::urls::encode` + does. + + @param format_value The format. + @param input_bytes The bytes. + @param output_characters The buffer. + @return The characters written, or @ref error::output_too_small, with nothing written, when + `output_characters` cannot hold them. + */ + [[nodiscard]] static result encode(formats::percent_t const& format_value, + std::span input_bytes, + std::span output_characters) noexcept { + std::size_t const written_size = encoded_size(format_value, input_bytes); + if (output_characters.size() < written_size) { + return error::output_too_small; + } + return boost::urls::encode( + output_characters.data(), written_size, + std::string_view{reinterpret_cast(input_bytes.data()), input_bytes.size()}, + detail::percent_set(format_value), format_value.options); + } + + /** + Writes the bytes of `text_characters` at the start of `output_bytes`, as `boost::urls::decode` + does, after the whole text is found valid. + + @param format_value The format. + @param text_characters The text. + @param output_bytes The buffer, which must not overlap the text. + @return The bytes written, or the text's error as `decoded_size` gives it, else + @ref error::output_too_small, with nothing written. + */ + [[nodiscard]] static result decode(formats::percent_t const& format_value, + std::string_view text_characters, + std::span output_bytes) noexcept { + result const decoded_count = decoded_size(format_value, text_characters); + if (!decoded_count) { + return decoded_count; + } + // Read unchecked: the error was returned above. + std::size_t const byte_count = decoded_count.unsafe_value(); + if (output_bytes.size() < byte_count) { + return error::output_too_small; + } + result const written = + boost::urls::decode(reinterpret_cast(output_bytes.data()), byte_count, + text_characters, format_value.options); + if (!written) { + return detail::percent_error(written.error(), text_characters); + } + // Read unchecked: the error was returned above. + return written.unsafe_value(); + } +}; + +/** + The stream codec of percent (D20): an encoder that holds up to two characters of an escape its + output had no room for, and a decoder that holds the escape it has read so far and the fault it + found. Each applies the format's set and options byte by byte, which Boost.URL has no stream + function for. +*/ +template <> +struct stream_codec { + /** + The stream encoder: a character or an escape a borrowed byte, written straight into the + caller's span. + + The characters of an escape that the span had no room for, one or two, wait for the next + `receive`. It never fails. With `Options.secret` it is move-only and wipes the waiting + characters by `secure::erase_secret` on `reset`, on destruction and in the moved-from encoder. + + @tparam Options The stream's options. + */ + template + class encoder { + public: + /** Whether the stream wipes its pending state: it is secret. */ + static constexpr bool wipes = Options.secret; + + /** The bytes read. */ + using input_type = std::uint8_t; + /** The characters written. */ + using output_type = char; + + /** + An encoder in `flow::needs_input`, leaving the characters of `format_value` as they are. + + @param format_value The format. + */ + explicit encoder(formats::percent_t const& format_value) noexcept + : allowed_(detail::percent_set(format_value)), options_(format_value.options) {} + + /** A copy of the state, borrowing what the other borrows; a secret stream has none. */ + encoder(encoder const&) noexcept + requires(!Options.secret) + = default; + /** + A copy of the state, borrowing what the other borrows; a secret stream has none. + + @return This encoder. + */ + encoder& operator=(encoder const&) noexcept + requires(!Options.secret) + = default; + + /** + Takes `other`'s state and leaves `other` as `reset` does. + + @param other The encoder moved from. + */ + encoder(encoder&& other) noexcept + : allowed_(other.allowed_), + options_(other.options_), + borrowed_(other.borrowed_), + position_(other.position_), + pending_(other.pending_), + pending_count_(other.pending_count_), + flushed_(other.flushed_) { + other.reset(); + } + + /** + Takes `other`'s state and leaves `other` as `reset` does. + + @param other The encoder moved from. + @return This encoder. + */ + encoder& operator=(encoder&& other) noexcept { + if (this != &other) { + allowed_ = other.allowed_; + options_ = other.options_; + borrowed_ = other.borrowed_; + position_ = other.position_; + pending_ = other.pending_; + pending_count_ = other.pending_count_; + flushed_ = other.flushed_; + other.reset(); + } + return *this; + } + + /** Wipes the waiting characters of a secret stream. */ + ~encoder() + requires wipes + { + wipe_pending(); + } + + /** A public stream wipes nothing. */ + ~encoder() = default; + + /** + Borrows all of `input` in `flow::needs_input`, and accepts nothing in another state. + + @param input The bytes to encode. + @return The bytes accepted and the state after. + */ + [[nodiscard]] result send(std::span input) noexcept { + if (state() != flow::needs_input) { + return step{.count = 0, .flow = state()}; + } + borrowed_ = input; + position_ = 0; + return step{.count = input.size(), .flow = state()}; + } + + /** + Writes the waiting characters, then the character or the escape of each borrowed byte, as + `output` has room. + + @param output The span to write into. + @return The characters written and the state after. + */ + [[nodiscard]] result receive(std::span output) noexcept { + std::size_t written = 0; + while (pending_count_ > 0 && written < output.size()) { + output[written++] = pending_[0]; + pending_[0] = pending_[1]; + --pending_count_; + } + while (position_ < borrowed_.size() && written < output.size()) { + std::array escape{}; + std::size_t const count = detail::percent_encode_byte( + borrowed_[position_++], allowed_, options_, escape); + std::size_t const fitting = (std::min)(count, output.size() - written); + std::copy_n(escape.begin(), fitting, + output.begin() + static_cast(written)); + written += fitting; + for (std::size_t index = fitting; index < count; ++index) { + pending_[pending_count_++] = escape[index]; + } + if constexpr (Options.secret) { + secure::erase_secret(escape); + } + } + if (position_ == borrowed_.size()) { + borrowed_ = {}; + position_ = 0; + } + return step{.count = written, .flow = state()}; + } + + /** + Ends the input: percent has no fault of the data to find in bytes. + + @return `flow::output_pending` while characters remain, else `flow::finished`. + */ + [[nodiscard]] result flush() noexcept { + flushed_ = true; + return state(); + } + + /** + Back to `flow::needs_input`, nothing borrowed or pending; the waiting characters of a + secret stream wiped. + */ + void reset() noexcept { + wipe_pending(); + borrowed_ = {}; + position_ = 0; + pending_ = {}; + pending_count_ = 0; + flushed_ = false; + } + + private: + /** Wipes the waiting characters, two bytes, when the stream is secret. */ + void wipe_pending() noexcept { + if constexpr (Options.secret) { + secure::erase_secret(pending_); + } + } + + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (pending_count_ > 0 || position_ < borrowed_.size()) { + return flow::output_pending; + } + return flushed_ ? flow::finished : flow::needs_input; + } + + /** The characters that are left as they are, the percent sign not among them. */ + boost::urls::grammar::lut_chars allowed_; + /** The format's options. */ + boost::urls::encoding_opts options_; + /** The bytes `send` accepted. */ + std::span borrowed_; + /** The next borrowed byte to read. */ + std::size_t position_ = 0; + /** The characters of an escape the output had no room for, the next one first. */ + std::array pending_{}; + /** How many of `pending_` wait. */ + std::size_t pending_count_ = 0; + /** Whether `flush` ended the input. */ + bool flushed_ = false; + }; + + /** + The stream decoder: a byte for each character that is its own and each escape, written + straight into the caller's span. + + The `%` and the first digit of an escape whose second digit is not borrowed yet are held. The + fault of the text is kept, and reported after `flush` by the call that reads the end of the + input, which runs it over everything still borrowed before it writes, as the one-shot form + reports it (B44): @ref error::invalid_character for a `%` followed by a character that is no + hex digit, else @ref error::invalid_length for a text that ends inside an escape. The bytes + delivered before `flush` may come from a text that later fails: a caller discards what was + delivered when the stream reports an error. Once a fault is known, nothing more is delivered: + what was delivered is always the bytes of a valid text's prefix. For "a%g", one byte is + delivered and `flush` then reports @ref error::invalid_character; for "%g41", none is. With + `Options.secret` it is move-only and wipes the held escape and the fault by + `secure::erase_secret` on `reset`, on destruction and in the moved-from decoder. + + @tparam Options The stream's options. + */ + template + class decoder { + public: + /** Whether the stream wipes its pending state: it is secret. */ + static constexpr bool wipes = Options.secret; + + /** The characters read. */ + using input_type = char; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** + A decoder in `flow::needs_input`, reading a plus sign as a space as the format's options + say. + + @param format_value The format. + */ + explicit decoder(formats::percent_t const& format_value) noexcept + : space_as_plus_(format_value.options.space_as_plus) {} + + /** A copy of the state, borrowing what the other borrows; a secret stream has none. */ + decoder(decoder const&) noexcept + requires(!Options.secret) + = default; + /** + A copy of the state, borrowing what the other borrows; a secret stream has none. + + @return This decoder. + */ + decoder& operator=(decoder const&) noexcept + requires(!Options.secret) + = default; + + /** + Takes `other`'s state and leaves `other` as `reset` does. + + @param other The decoder moved from. + */ + decoder(decoder&& other) noexcept + : space_as_plus_(other.space_as_plus_), + borrowed_(other.borrowed_), + position_(other.position_), + progress_(other.progress_), + flushed_(other.flushed_), + verdict_passed_(other.verdict_passed_), + error_(other.error_) { + other.reset(); + } + + /** + Takes `other`'s state and leaves `other` as `reset` does. + + @param other The decoder moved from. + @return This decoder. + */ + decoder& operator=(decoder&& other) noexcept { + if (this != &other) { + space_as_plus_ = other.space_as_plus_; + borrowed_ = other.borrowed_; + position_ = other.position_; + progress_ = other.progress_; + flushed_ = other.flushed_; + verdict_passed_ = other.verdict_passed_; + error_ = other.error_; + other.reset(); + } + return *this; + } + + /** Wipes the held escape and the fault of a secret stream. */ + ~decoder() + requires wipes + { + wipe_progress(); + } + + /** A public stream wipes nothing. */ + ~decoder() = default; + + /** + Borrows all of `input` in `flow::needs_input`, and accepts nothing in another state; the + characters that write nothing, a `%` and a first digit, are held at once. + + @param input The characters to decode. + @return The characters accepted and the state after, or the error found after `flush`. + */ + [[nodiscard]] result send(std::span input) noexcept { + if (failed()) { + return error_; + } + if (state() != flow::needs_input) { + return step{.count = 0, .flow = state()}; + } + borrowed_ = input; + position_ = 0; + hold_silent_characters(); + return step{.count = input.size(), .flow = state()}; + } + + /** + Writes a byte for each character that is its own and each escape, as `output` has room. + + After `flush`, the first call runs the verdict over what is still borrowed and returns its + error, writing nothing. + + @param output The span to write into. + @return The bytes written and the state after, or the error. + */ + [[nodiscard]] result receive(std::span output) noexcept { + if (failed()) { + return error_; + } + if (flushed_ && !verdict_passed_ && !pass_verdict()) { + return error_; + } + std::size_t written = 0; + while (position_ < borrowed_.size()) { + char const character = borrowed_[position_]; + if (written == output.size() && detail::percent_writes(progress_, character)) { + break; + } + ++position_; + if (auto const decoded = + detail::percent_read(progress_, character, space_as_plus_)) { + output[written++] = *decoded; + } + } + if (position_ == borrowed_.size()) { + borrowed_ = {}; + position_ = 0; + } + return step{.count = written, .flow = state()}; + } + + /** + Ends the input; with nothing borrowed, it runs the verdict and reports its error itself. + + @return `flow::output_pending` while bytes remain, else `flow::finished`, or the error. + */ + [[nodiscard]] result flush() noexcept { + if (failed()) { + return error_; + } + if (!flushed_) { + flushed_ = true; + if (position_ == borrowed_.size() && !pass_verdict()) { + return error_; + } + } + return state(); + } + + /** + Back to `flow::needs_input`, nothing borrowed or held, the verdict and the error + forgotten; the held escape and the fault of a secret stream wiped. + */ + void reset() noexcept { + wipe_progress(); + borrowed_ = {}; + position_ = 0; + progress_ = {}; + flushed_ = false; + verdict_passed_ = false; + error_.clear(); + } + + private: + /** Wipes the held escape and the fault, three bytes, when the stream is secret. */ + void wipe_progress() noexcept { + if constexpr (Options.secret) { + secure::erase_secret(progress_); + } + } + + /** Reads the borrowed characters that write nothing, up to the first that does. */ + void hold_silent_characters() noexcept { + while (position_ < borrowed_.size() && + !detail::percent_writes(progress_, borrowed_[position_])) { + static_cast( + detail::percent_read(progress_, borrowed_[position_++], space_as_plus_)); + } + } + + /** + The verdict over the whole input, what is still borrowed included, as `decoded_size` + gives it for the whole text. + + @return Whether the input is valid; the error is set when it is not. + */ + [[nodiscard]] bool pass_verdict() noexcept { + detail::percent_progress unread_progress = progress_; + for (char const character : borrowed_.subspan(position_)) { + static_cast(detail::percent_read(unread_progress, character, space_as_plus_)); + } + if (auto const fault = detail::percent_fault(unread_progress)) { + error_ = *fault; + } + if constexpr (Options.secret) { + secure::erase_secret(unread_progress); + } + verdict_passed_ = !error_; + return verdict_passed_; + } + + /** Whether a call reports an error, which stays until `reset`. */ + [[nodiscard]] bool failed() const noexcept { return static_cast(error_); } + + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (position_ < borrowed_.size()) { + return flow::output_pending; + } + return flushed_ ? flow::finished : flow::needs_input; + } + + /** Whether a plus sign is a space. */ + bool space_as_plus_; + /** The characters `send` accepted. */ + std::span borrowed_; + /** The next borrowed character to read. */ + std::size_t position_ = 0; + /** The escape read so far and the fault found: stage, first digit, fault. */ + detail::percent_progress progress_{}; + /** Whether `flush` ended the input. */ + bool flushed_ = false; + /** Whether the verdict over the whole input passed. */ + bool verdict_passed_ = false; + /** The error every call returns until `reset`. */ + boost::system::error_code error_; + }; +}; + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_PERCENT_HPP diff --git a/meta/include-boundaries.json b/meta/include-boundaries.json new file mode 100644 index 0000000..d187245 --- /dev/null +++ b/meta/include-boundaries.json @@ -0,0 +1,79 @@ +{ + "boundaries": [ + { + "headers": [ + "include/webcpp/codecs.hpp", + "include/webcpp/codecs/detail/core/*.hpp" + ], + "must-not-include": [ + "webcpp/codecs/hex", + "webcpp/codecs/base32", + "webcpp/codecs/base58", + "webcpp/codecs/base64", + "webcpp/codecs/bech32", + "webcpp/codecs/percent", + "webcpp/codecs/armor", + "webcpp/codecs/detail/formats", + "boost/url" + ], + "why": "the core (codecs.hpp and detail/core) includes no format, no format's arithmetic and no Boost.URL" + }, + { + "headers": [ + "include/webcpp/codecs/detail/formats/*.hpp" + ], + "must-not-include": [ + "webcpp/codecs/hex", + "webcpp/codecs/base32", + "webcpp/codecs/base58", + "webcpp/codecs/base64", + "webcpp/codecs/bech32", + "webcpp/codecs/percent", + "webcpp/codecs/armor", + "boost/url" + ], + "why": "a format's arithmetic includes no public format header and no Boost.URL, but may include another format's arithmetic (armor reuses base64's, D20)" + }, + { + "headers": [ + "include/webcpp/codecs.hpp", + "include/webcpp/codecs/*.hpp", + "include/webcpp/codecs/detail/core/*.hpp", + "include/webcpp/codecs/detail/formats/*.hpp" + ], + "except": [ + "include/webcpp/codecs/percent.hpp" + ], + "must-not-include": [ + "boost/url" + ], + "why": "only percent depends on Boost.URL" + }, + { + "headers": [ + "include/webcpp/codecs.hpp", + "include/webcpp/codecs/*.hpp", + "include/webcpp/codecs/detail/core/*.hpp", + "include/webcpp/codecs/detail/formats/*.hpp" + ], + "must-not-include": [ + "webcpp/asio", + "webcpp/beast", + "webcpp/cobalt", + "webcpp/crypto", + "webcpp/document", + "webcpp/hash", + "webcpp/idna", + "webcpp/lexical", + "webcpp/pratt", + "webcpp/trystero", + "webcpp/wasi", + "webcpp/webrtc", + "webcpp/xactor", + "webcpp/xstate", + "webcpp/test" + ], + "why": "codecs depends on config and secure alone" + } + ] +} diff --git a/meta/libraries.json b/meta/libraries.json new file mode 100644 index 0000000..61e7d16 --- /dev/null +++ b/meta/libraries.json @@ -0,0 +1,10 @@ +{ + "key": "codecs", + "name": "codecs", + "authors": ["R"], + "description": "One contract for converting bytes and typed values to text and back, and any data through one-shot and stream transformers, with hex, base32, base58, base64, bech32, percent-encoding and RFC 7468's armor.", + "category": ["String", "Cryptography"], + "maintainers": ["R "], + "cxxstd": "20", + "port-of": null +} diff --git a/meta/lint.json b/meta/lint.json new file mode 100644 index 0000000..df56400 --- /dev/null +++ b/meta/lint.json @@ -0,0 +1,3 @@ +{ + "nodiscard-results": "a dropped result is a refused text or a short buffer that would pass as a conversion" +} diff --git a/test/.clang-tidy b/test/.clang-tidy new file mode 100644 index 0000000..6cca041 --- /dev/null +++ b/test/.clang-tidy @@ -0,0 +1,26 @@ +# The tests inherit the superproject's configuration and switch off one check +# and one option. +# +# bugprone-unchecked-optional-access reports an optional that a test reads +# where its value must be there. Either the test has asserted it first, with +# `if (!BOOST_TEST(x.has_value())) { return; }`, and BOOST_TEST is a call +# returning whether its condition held, which the checker does not look into; +# or the test calls value(), whose failure on an empty optional ends the +# program, with std::bad_optional_access or, built without exceptions, an +# abort, and so fails the test. The library's headers are still analysed with +# it, through the aggregate translation unit tools/lint/compile_commands.py +# writes. +# +# bugprone-exception-escape.CheckMain treats every test's main as a function +# that should not throw. A test's main lets what a failing case throws, a +# boost::system::system_error from value() on a failed result or a +# std::bad_alloc, end the process uncaught, which fails the test as it should; +# example/.clang-tidy says the same of the examples. The check stays on for +# everything else: a noexcept function, a destructor, a move or a swap. +--- +InheritParentConfig: true +Checks: > + -bugprone-unchecked-optional-access +CheckOptions: + - key: bugprone-exception-escape.CheckMain + value: 'false' diff --git a/test/Jamfile b/test/Jamfile new file mode 100644 index 0000000..b77d182 --- /dev/null +++ b/test/Jamfile @@ -0,0 +1,271 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/codecs//codecs ; + +import webcpp regex ; + +webcpp.targets native wasip2 wasip3 emscripten ; + +# Every program that runs, runs with exceptions on and off, and every check +# that compiles, compiles both ways: the second has the suffix _no_exceptions +# and is built with exception-handling=off. +rule codecs-run ( name : sources + : requirements * : targets * ) +{ + webcpp.run $(name) : $(sources) : $(requirements) : $(targets) ; + webcpp.run $(name)_no_exceptions : $(sources) + : $(requirements) off : $(targets) ; +} +rule codecs-compile ( name : sources + : requirements * : targets * ) +{ + webcpp.compile $(name) : $(sources) : $(requirements) : $(targets) ; + webcpp.compile $(name)_no_exceptions : $(sources) + : $(requirements) off : $(targets) ; +} + +webcpp.headers-alone codecs : ../include : + codecs.hpp codecs/config.hpp codecs/detail/core/*.hpp + codecs/hex.hpp codecs/base32.hpp codecs/base58.hpp codecs/base64.hpp codecs/bech32.hpp + codecs/armor.hpp + codecs/detail/formats/*.hpp ; +# percent.hpp alone includes Boost.URL, whose decode is compiled: its target. +webcpp.headers-alone codecs : ../include : codecs/percent.hpp + : /webcpp/codecs//percent ; + +# config.hpp defines WEBCPP_CODECS_NO_EXCEPTIONS exactly when webcpp has no +# exceptions, keeps it when a developer defines it, and defines it when +# WEBCPP_NO_EXCEPTIONS is; it declares webcpp::codecs::formats. +webcpp.compile config : config_test.cpp ; +webcpp.compile config_no_exceptions : config_test.cpp : off ; +webcpp.compile config_all_off : config_test.cpp + : WEBCPP_NO_EXCEPTIONS WEBCPP_TEST_CODECS_ALL_OFF ; +webcpp.compile config_developer_defined : config_test.cpp + : WEBCPP_CODECS_NO_EXCEPTIONS WEBCPP_TEST_CODECS_DEVELOPER_DEFINED ; + +# The errors: eight fixed values, the category webcpp.codecs, their messages. +codecs-run error : error_test.cpp ; + +# The concepts: formats, inputs, static sizes, the pairs that convert. +codecs-run contract : contract_test.cpp ; +# The sizes and the buffer forms: B23's order, nothing written on an error. +codecs-run sizes : sizes_test.cpp ; +# The fixed results text and bytes: regular, by content, the view of +# an lvalue only. +codecs-run results : results_test.cpp ; +# The secret results in place, secret_text and secret_bytes: move-only, +# copied by clone(), wiped on a move and on destruction, as secure's wipe seam +# records it. +codecs-run secret_fixed : secret_fixed_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# The secret results on the heap, with any allocator: every buffer wiped before +# the allocator gets it back, the old one on growth included; the propagation of +# std::allocator_traits; the approved spellings. +codecs-run secret_heap : secret_heap_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# Secret operations (D10): by the value, the value codec, the token or the +# requested type; D9's secret column; the secret_tag overloads of a codec and +# of a value codec (R7); every temporary of the core wiped, as secure's wipe +# seam records it; the fixed secret forms allocate nothing. +codecs-run secret_operation : secret_operation_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# The timing guard of a secret operation: one guard of codecs' for each, none +# for a public one, as secure's timing seam records it; DIT set inside where the +# CPU has it. +codecs-run timing : timing_test.cpp ; +# over (D11): a format of two links; its intermediate in place or from its +# allocator, wiped when the chain is secret, as secure's wipe seam records it; +# the links' secret overloads (R7) run in a secret chain. +codecs-run over : over_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# The conversion contract (D17, D18): the transformer concepts, the stream +# protocol's states over a stream transformer of the tests' own, the tags and +# the traits the compositions read. +codecs-run transformer : transformer_test.cpp ; +# The toy media types: transformers of packets, frames and images, no byte or +# character among their elements, satisfy the contract. +codecs-run toy_media : toy_media_test.cpp ; +# pipe (D19): two stream transformers composed by their element types alone, +# with an intermediate in place; the first error of either is the pipe's; a +# moved-from pipe starts again. +codecs-run pipe : pipe_test.cpp ; +# drain (D19): the pieces a sink is given, through drain's own buffer, a +# capacity or the caller's span; a sink's error stops it. +codecs-run drain : drain_test.cpp ; +# each (D19, D22): a one-shot transformer as a stream, one input element an +# item; frames to images and to bytes, in place and from an allocator; an +# item's error with its item; a moved-from each starts again. +codecs-run each : each_test.cpp ; +# buffered (D19, D22): a one-shot transformer as a stream that accumulates until +# flush, in place and from an allocator; input_too_long past the capacity; the +# heap form's sizing; a moved-from buffered starts again. +codecs-run buffered : buffered_test.cpp ; +# The formats as transformers (D20): encoder and decoder, one-shot always and +# streaming through stream_codec, on letters; every chunking equals the +# one-shot form; the protocol's error rules (D18, B23, B44); over's stream +# through a pipe of its links; a moved-from transformer restarts. +codecs-run format_transformer : format_transformer_test.cpp ; +# Secret streams (D21): a transformer made with secret_operation, or of a secret +# part (pipe, each, buffered), is move-only, enters a guard of codecs' in each +# call, as secure's timing seam records it, with DIT set inside where the CPU +# has it, and wipes its pending state on reset, on destruction and on a move, +# as secure's wipe seam records it; a drain of one wipes its buffer. +codecs-run secret_stream : secret_stream_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# hex (D13): RFC 4648's base16 vectors in either case, the spec's scenarios on +# hex, every byte value as a character at each place of a pair, the bounds at +# SIZE_MAX, empty input in every form and a text decoded into its own storage. +codecs-run hex : hex_test.cpp ; +# hex as a stream (D20): every chunking equals the one-shot form, its errors +# included; the protocol's states; a file in fixed chunks with no heap; a +# moved-from stream restarts; a secret stream's carries wiped, as secure's wipe +# seam records it. +codecs-run hex_stream : hex_stream_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# base32 and base32hex (D13): RFC 4648's vectors in both alphabets and both +# paddings, from either case, every error of the format and the lowest of two +# faults, every byte value as a character at every place of a group against a +# plain reference, a text decoded in its own storage, the bounds at SIZE_MAX. +codecs-run base32 : base32_test.cpp ; +# base32 as a stream (D20): every chunking equals the one-shot form, its errors +# come after flush, a secret stream's pending state is wiped as secure's wipe +# seam records it. +codecs-run base32_stream : base32_stream_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; + +# base64 and base64url (D13): RFC 4648's vectors in both alphabets and both +# paddings, every error of the format, every byte value as a character at each +# place of a group against a plain reference, the bounds at SIZE_MAX, empty +# input in every form and a text decoded into its own storage. +codecs-run base64 : base64_test.cpp ; +# base64 as a stream (D20): every chunking equals the one-shot form, its errors +# included; the protocol's states; a file in fixed chunks with no heap; a +# moved-from stream restarts; a secret stream's carries wiped, as secure's wipe +# seam records it. +codecs-run base64_stream : base64_stream_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# bech32 and bech32m (D13, owner decision 27): BIP-173's and BIP-350's lists in +# bytes and in words, their segwit addresses, a Nostr key, BOLT 11's first +# invoice through a larger instance, the word helpers, every error and the +# lowest of two, every byte value as a character at each place against a plain +# reference, the bounds at SIZE_MAX, empty input in every form. +codecs-run bech32 : bech32_test.cpp ; +# bech32 as a stream (D20): every chunking equals the one-shot form, its errors +# included; the decoder holds until the checksum; a configuration fault from the +# first call; a hold of a capacity; a moved-from stream restarts; a secret +# stream's state and hold wiped, as secure's wipe seam records it. +codecs-run bech32_stream : bech32_stream_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# percent (D13, the spec's "Format: percent over Boost.URL"): Boost.URL's own +# functions as the oracle in 1000 random byte strings and over every CharSet its +# headers name, its documentation's examples, every error and the lowest of two +# (F26), every byte value as a character at each place of an escape against a +# plain table, the bounds at SIZE_MAX and empty input in every form. Links +# Boost.URL's compiled library. +codecs-run percent : percent_test.cpp : /webcpp/codecs//percent ; +# percent as a stream (D20): every chunking equals the one-shot form and +# Boost.URL's functions, its errors included; the protocol's states; a file in +# fixed chunks with no heap; a moved-from stream restarts; a secret stream's +# pending state wiped, as secure's wipe seam records it. +codecs-run percent_stream : percent_stream_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD /webcpp/codecs//percent ; +# The armor's vectors, test/data/armor/ (its README.txt), read at run time from +# the directory WEBCPP_TEST_CODECS_ARMOR_DATA names, with forward slashes and +# quoted whole as the fuzz corpus is (fuzz/Jamfile), so that a path with a space +# or a backslash survives; webcpp.data gives WASI the directory. +path-constant ARMOR_DATA : data/armor ; +.armor-data = [ regex.replace $(ARMOR_DATA) "\\\\" "/" ] ; +.armor-files = [ glob data/armor/* ] ; +ARMOR_DATA_REQUIREMENTS = + "\"WEBCPP_TEST_CODECS_ARMOR_DATA=\\\"$(.armor-data)\\\"\"" + [ webcpp.data $(ARMOR_DATA) ] $(.armor-files) ; +# The armor (D13, the spec's "Format: armor (RFC 7468)"): RFC 7468's examples +# and OpenSSL's PEM files of test/data/armor/ on every lane, decoded to their +# DER and encoded back byte for byte, the spec's scenario of the wrong label, +# both line endings, every error and the format's order of two, a configuration +# fault first, every byte value as a character at each place against a plain +# reference, the bounds at SIZE_MAX, empty input in every form, over the armor. +codecs-run armor : armor_test.cpp : $(ARMOR_DATA_REQUIREMENTS) ; +# The armor as a stream (D20): every file of test/data/armor/, with both line +# endings, and 1000 random inputs equal the one-shot form for every chunking; +# its errors after flush; the spec's "Armor as a stream"; a configuration fault +# from the first call; a moved-from stream restarts; a secret stream's window, +# masks and held bytes wiped, as secure's wipe seam records it. +codecs-run armor_stream : armor_stream_test.cpp + : $(ARMOR_DATA_REQUIREMENTS) WEBCPP_SECURE_TEST_WIPE_RECORD ; +# OpenSSL as the armor's oracle (ruling R8, the spec's "OpenSSL's PEM"): a P-256 +# key's SPKI and DERs of 1, 48 and 1000 bytes encode to PEM_write_bio's text and +# decode back. Native, with the superproject's OpenSSL, which the MSVC lane does +# not build. +codecs-run armor_openssl : armor_openssl_test.cpp + : /webcpp/third_party//openssl msvc:no : native ; +# base58 (D13, owner decisions 25 and 26): Bitcoin Core's vectors, read at run +# time from third_party/libs/bitcoin (ruling R8), through formats::base58 and a +# larger instance, public and secret; the named alphabets and one of the +# test's own; each instance's bounds and the decoded payload's (F12); every +# byte value as a character at each place against a plain table, the bounds at +# SIZE_MAX, empty input in every form; the public and the secret conversions +# equal. +codecs-run base58 : base58_test.cpp + : /webcpp/third_party//bitcoin_base58_vectors ; +# base58 through buffered (D19, D20): accumulating with no heap, every vector +# of the file through the heap and the in-place forms, public and secret, for +# every chunking; the refusals at flush. +codecs-run base58_buffered : base58_buffered_test.cpp + : /webcpp/third_party//bitcoin_base58_vectors ; +# A format registered outside codecs: a base58 checksum of the tests' own and +# its format, as webcpp::hash's base58_with_checksum would be, public and +# secret, the checksum compared inside the guard, as secure's seam records it. +codecs-run interoperation : interoperation_test.cpp ; +# The default result of encode and decode without a token (D9). +codecs-run default_result : default_result_test.cpp ; +# The typed decode into fixed byte types, the heap and a value codec's value. +codecs-run typed_decode : typed_decode_test.cpp ; +# Value codecs: the concepts, the default result, the buffer forms. +codecs-run value_codec : value_codec_test.cpp ; +# The tokens: codecs' own tags in both directions, a token of the test's own, +# capacities, a value codec through a token. +codecs-run tokens : tokens_test.cpp ; +# Boost.URL's string tokens work as given; the program links Boost.URL, which +# percent's target brings. +codecs-run tokens_boost_url : tokens_boost_url_test.cpp + : /webcpp/codecs//percent ; +# A codec's encode_fault (D3): an encode the format refuses (bech32's missing +# part, a text past its longest, a word above 31; the armor's missing label) is +# refused before any token is prepared, in every form and through over, the +# error not depending on the input's size; the one rule of every size (SIZE_MAX +# refused for size, 0 for a fault). Boost.URL's tokens among them: the program +# links Boost.URL, which percent's target brings. +codecs-run encode_fault : encode_fault_test.cpp : /webcpp/codecs//percent ; +# Allocators: every allocation of a form that takes one goes through it, and the +# global operator new sees none. +codecs-run allocator : allocator_test.cpp ; +# An allocator that throws on its Nth allocation: its exception reaches the +# caller and the token's container is as it was. A program that needs +# exceptions, so with no _no_exceptions twin. +webcpp.run allocator_throw : allocator_throw_test.cpp : on ; +# The forms that allocate nothing leave a counting operator new where it was. +codecs-run allocation : allocation_test.cpp ; +# percent's forms that allocate nothing, in a program of its own: it links +# Boost.URL, which allocation's program does not. +codecs-run allocation_percent : allocation_percent_test.cpp + : /webcpp/codecs//percent ; +# before and after every public header (CODING-GUIDELINES.md's +# rule): on MSVC the headers beside a bare , whose min and max macros +# every header survives by (std::min)(...), (std::max)(...) and +# (std::numeric_limits::max)(); elsewhere the headers alone. Native; links +# Boost.URL, which percent's target brings. +codecs-run windows_h_before : windows_h_before_test.cpp + : /webcpp/codecs//percent : native ; +codecs-run windows_h_after : windows_h_after_test.cpp + : /webcpp/codecs//percent : native ; +# Every form that allocates nothing is noexcept, and one that allocates is not. +codecs-compile noexcept : noexcept_test.cpp ; + +# The refusals and a forgotten format header stop the build with their messages. +build-project messages ; + +# The own lane constant-time: memcheck, MemorySanitizer and dudect over every +# constant-time format, with planted leaks that must fail. +build-project constant_time ; + +# The own lane fuzz: libFuzzer on Linux over every decoder and over, and each +# target replayed here on every lane, over its corpus and a fixed stream. +build-project fuzz ; diff --git a/test/allocation_percent_test.cpp b/test/allocation_percent_test.cpp new file mode 100644 index 0000000..0c279f1 --- /dev/null +++ b/test/allocation_percent_test.cpp @@ -0,0 +1,224 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// percent's forms that allocate nothing leave the count where it was (the spec's "Streams allocate +// nothing" and the allocation requirement, on percent): the buffer forms, the fixed results, the +// typed decodes into fixed types, the tokens of a static bound and the secret fixed results; its +// stream encoder and decoder over 1 MiB of random bytes or of their text in random chunks, public +// and secret, and each and buffered in place over its encoder; every call made under +// support/counting.hpp's replacement of every form of operator new, after its control. Boost.URL's +// compiled decode and encode are called inside the windows: they allocate nothing. This is a +// program of its own, with the percent target, so that allocation_test.cpp links no Boost.URL. + +#include "support/counting.hpp" + +#include "support/allocation_checks.hpp" +#include "support/samples.hpp" + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; +namespace urls = boost::urls; + +/** + percent's buffer forms, fixed results, typed decodes into fixed types, tokens of a static bound and + secret fixed results allocate nothing, on every path: with the default set and with pchars and a + plus for a space, accepted and refused. +*/ +void check_one_shot_forms() { + std::array digest = test::digest_bytes(); + digest[0] = ' '; + digest[1] = '~'; + digest[2] = 0xff; + webcpp::secure::secret<32> const key; + auto const query = formats::percent(urls::pchars, urls::encoding_opts(true)); + std::array text{}; + std::array decoded{}; + auto const fixed_text = codecs::encode(formats::percent, digest); // built before the windows + std::size_t volatile sink = 0; + bool volatile verdict = false; + test::expect_no_allocation("percent's buffer forms and sizes", [&] { + sink = codecs::encoded_size(formats::percent, digest); + sink = codecs::max_decoded_size(formats::percent, fixed_text.value().view()); + std::size_t const size = codecs::encoded_size(formats::percent, digest); + std::size_t const query_size = codecs::encoded_size(query, digest); + verdict = + codecs::encode(formats::percent, digest, text).has_value() && + codecs::decode(formats::percent, std::string_view{text.data(), size}, decoded) + .has_value() && + std::ranges::equal(std::span{decoded}.first(32), digest) && + codecs::encode(query, digest, text).has_value() && + codecs::decode(query, std::string_view{text.data(), query_size}, decoded).has_value() && + std::ranges::equal(std::span{decoded}.first(32), digest); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("percent's refused buffer forms", [&] { + verdict = + codecs::encode(formats::percent, digest, std::span{text}.first(10)).has_value() || + codecs::decode(formats::percent, std::string_view{"abc%4"}, decoded).has_value() || + codecs::decode(formats::percent, std::string_view{"a%g"}, decoded).has_value() || + codecs::decode(formats::percent, std::string_view{"%41%42"}, + std::span{decoded}.first(1)) + .has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("percent's fixed results and tokens", [&] { + auto const encoded = codecs::encode(formats::percent, digest); + auto const back = codecs::decode(formats::percent, encoded.value()); + auto const into_array = codecs::decode>( + formats::percent, std::string_view{"a%20%7e%FF"}); + auto const into_bytes = + codecs::decode>(formats::percent, fixed_text.value().view()); + auto const through_fixed = + codecs::encode(formats::percent, digest, codecs::tokens::fixed<96>{}); + auto const fixed_back = + codecs::decode(formats::percent, fixed_text.value(), codecs::tokens::fixed<96>{}); + verdict = encoded.has_value() && back.has_value() && into_array.has_value() && + into_bytes.has_value() && through_fixed.has_value() && fixed_back.has_value() && + back.value().size() == 32; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("percent's secret fixed results", [&] { + auto const from_key = codecs::encode(formats::percent, key); + auto const through_token = codecs::encode(formats::percent, digest, codecs::tokens::secret); + auto const into_secret = codecs::decode>( + formats::percent, std::string_view{"%01%02%03%04"}); + auto const into_secret_bytes = + codecs::decode>(formats::percent, fixed_text.value().view()); + auto const secret_back = + codecs::decode(formats::percent, fixed_text.value(), codecs::tokens::secret); + std::array secret_text{}; + auto const secret_buffer = codecs::encode(formats::percent, key, std::span{secret_text}); + verdict = from_key.has_value() && through_token.has_value() && into_secret.has_value() && + into_secret_bytes.has_value() && secret_back.has_value() && + secret_buffer.has_value() && codecs::encoded_size(formats::percent, key) > 0; + }); + BOOST_TEST(verdict); + static_cast(sink); +} + +/** + percent's streams of 1 MiB allocate nothing (the spec's "Streams allocate nothing", on percent): + random bytes in random chunks through encoder(percent) piped into decoder(percent), drained into a + fixed span and compared as it goes; the text of the bytes decoded by a secret decoder likewise, and + the bytes through a secret encoder into the same text. +*/ +void check_mebibyte() { + std::vector input(std::size_t{1024} * 1024); + // A fixed seed, so that every lane and every run sees the same bytes. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) + std::mt19937_64 generator{20261126}; + std::ranges::generate(input, [&] { return static_cast(generator()); }); + std::string const text = codecs::encode(formats::percent, input).value(); + bool volatile verdict = false; + test::expect_no_allocation("1 MiB through pipe(encoder(percent), decoder(percent))", [&] { + auto piped = + codecs::pipe(codecs::encoder(formats::percent), codecs::decoder(formats::percent)); + verdict = + test::stream_in_random_chunks<777>(piped, std::span{input}, + std::span{input}, generator); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("1 MiB of percent text through a secret decoder(percent)", [&] { + auto decoder = codecs::decoder(formats::percent, codecs::secret_operation); + verdict = test::stream_in_random_chunks<555>( + decoder, test::characters_of(text), std::span{input}, generator); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("1 MiB through a secret encoder(percent)", [&] { + auto encoder = codecs::encoder(formats::percent, codecs::secret_operation); + verdict = test::stream_in_random_chunks<333>(encoder, std::span{input}, + test::characters_of(text), generator); + }); + BOOST_TEST(verdict); +} + +/** + percent's small streams allocate nothing once made: encoder(percent) in a configuration, a secret + decoder and a secret encoder, streamed, moved and reset; and each and buffered in place over + encoder(percent). +*/ +void check_small_streams() { + bool volatile verdict = false; + std::array const bytes{0x01, ' ', 0x45, '~', 0x89, 0xab}; + std::array text{}; + std::array decoded{}; + auto const query = formats::percent(urls::pchars, urls::encoding_opts(true)); + test::expect_no_allocation("encoder(percent), a secret decoder and a secret encoder", [&] { + auto encoder = codecs::encoder(query); + bool streamed = encoder.send(bytes).has_value() && + encoder.receive(std::span{text}.first(3)).has_value() && + encoder.receive(std::span{text}.subspan(3, 4)).has_value() && + encoder.flush().has_value() && + encoder.receive(std::span{text}.subspan(7)).has_value(); + auto moved{std::move(encoder)}; + moved.reset(); + auto secret_decoder = codecs::decoder(query, codecs::secret_operation); + streamed = streamed && + secret_decoder.send(std::span{text}.first(6)).has_value() && + secret_decoder.receive(decoded).has_value() && + secret_decoder.send(std::span{text}.subspan(6, 11)).has_value() && + secret_decoder.flush().has_value() && + secret_decoder.receive(std::span{decoded}.subspan(2)).has_value(); + auto moved_decoder{std::move(secret_decoder)}; + moved_decoder.reset(); + auto secret_encoder = codecs::encoder(formats::percent, codecs::secret_operation); + streamed = streamed && secret_encoder.send(bytes).has_value() && + secret_encoder.receive(std::span{text}.first(1)).has_value(); + auto moved_secret{std::move(secret_encoder)}; + moved_secret.reset(); + verdict = streamed && text[0] == '%'; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("each and buffered in place over encoder(percent)", [&] { + auto each = codecs::each(codecs::encoder(formats::percent), codecs::capacity<3>); + bool streamed = each.send(bytes).has_value() && + each.receive(std::span{text}.first(1)).has_value() && + each.receive(std::span{text}.subspan(1, 1)).has_value(); + auto buffered = codecs::buffered( + codecs::encoder(formats::percent, codecs::secret_operation), codecs::capacity<6>); + std::array text_buffer{}; + streamed = streamed && buffered.send(bytes).has_value() && buffered.flush().has_value() && + buffered.receive(text_buffer).has_value(); + auto moved_buffered{std::move(buffered)}; + moved_buffered.reset(); + verdict = streamed && text_buffer[0] == '%' && text_buffer[1] == '0'; + }); + BOOST_TEST(verdict); +} + +} // namespace + +int main() { + std::printf("c_allocations_counted=%d\n", test::c_allocations_counted ? 1 : 0); + test::control_counts_every_form(); + check_one_shot_forms(); + check_mebibyte(); + check_small_streams(); + return boost::report_errors(); +} diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp new file mode 100644 index 0000000..cf02560 --- /dev/null +++ b/test/allocation_test.cpp @@ -0,0 +1,1664 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The forms of codecs that allocate nothing leave the count where it was: every call is made +// under support/counting.hpp's replacement of every form of operator new (and the C library's +// allocator where a program can count it). A control first calls each form of operator new once +// and checks that each is counted, so a zero is not a replacement that never ran. Later tasks +// add their rows, except percent's, whose program links Boost.URL: allocation_percent_test.cpp. + +#include "support/counting.hpp" + +#include "support/allocation_checks.hpp" +#include "support/be16.hpp" +#include "support/bookkeeping.hpp" +#include "support/doubler.hpp" +#include "support/letters.hpp" +#include "support/samples.hpp" +#include "support/saturating.hpp" +#include "support/toy_media.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +/** A library's fixed type of two bytes, a typed decode's target. */ +struct key_pair { + /** The bytes. */ + std::array held_bytes{}; +}; +} // namespace + +namespace webcpp::codecs { + +/** key_pair is a decode's target of exactly two bytes. */ +template <> +struct fixed_byte_storage<::key_pair> { + /** The size. */ + static constexpr std::size_t size = 2; + + /** The bytes a decode fills. */ + static std::span writable(::key_pair& target_key) noexcept { + return target_key.held_bytes; + } +}; + +} // namespace webcpp::codecs + +namespace { + +/** The sizes and the buffer forms (Task 2): each call of sizes_test, on every path. */ +void check_buffer_forms() { + std::array const input{0x01, 0xff}; + std::array const wide_input{}; + std::vector const heap_input(3); // built before the window + std::array output{}; + std::array decoded{}; + std::size_t volatile sink = 0; + bool volatile verdict = false; + test::expect_no_allocation("encoded_size", [&] { + sink = codecs::encoded_size(test::letters, input); + sink = codecs::encoded_size(test::letters, heap_input); + }); + test::expect_no_allocation("max_decoded_size", [&] { + sink = codecs::max_decoded_size(test::letters, std::string_view{"abpp"}); + sink = codecs::max_decoded_size(test::letters, "abpp"); + }); + test::expect_no_allocation("encode into a buffer", [&] { + verdict = codecs::encode(test::letters, input, output).has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("decode into a buffer", [&] { + verdict = codecs::decode(test::letters, std::string_view{"abpp"}, decoded).has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("encode into a short buffer", [&] { + verdict = codecs::encode(test::letters, wide_input, std::span{output}.first(63)) + .has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("decode into a short buffer", [&] { + verdict = codecs::decode(test::letters, std::string_view{"abab"}, + std::span{decoded}.first(1)) + .has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("decode of a refused text", [&] { + verdict = codecs::decode(test::letters, std::string_view{"abq"}, decoded).has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("empty inputs", [&] { + verdict = codecs::encode(test::letters, std::span{}, std::span{}) + .has_value() && + codecs::decode(test::letters, std::string_view{}, std::span{}) + .has_value(); + }); + BOOST_TEST(verdict); + std::array const long_input{}; + std::array long_text{}; + long_text.fill('a'); + test::expect_no_allocation("an input whose bound saturates", [&] { + sink = codecs::encoded_size(test::saturating, long_input); + sink = codecs::max_decoded_size(test::saturating, long_text); + verdict = codecs::encode(test::saturating, long_input, output).has_value() || + codecs::decode(test::saturating, long_text, decoded).has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("input_size_fault", [&] { + verdict = codecs::detail::input_size_fault(test::letters, SIZE_MAX).has_value(); + }); + BOOST_TEST(verdict); + static_cast(sink); +} + +/** The fixed results, the default results that are fixed, and the typed decodes into fixed types + (Task 3): nothing is allocated, on any path. */ +void check_fixed_results() { + std::array const wide_input{}; + std::array const input{0x01, 0xff}; + std::array output_bytes{}; + std::size_t volatile sink = 0; + bool volatile verdict = false; + test::expect_no_allocation("encode to a fixed text", [&] { + auto const encoded = codecs::encode(test::letters, wide_input); + verdict = encoded.has_value(); + sink = encoded.value().size(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("the fixed results", [&] { + codecs::text<8> const first_text; + codecs::text<8> const second_text = first_text; + codecs::bytes<4> const first_bytes; + verdict = first_text == second_text && first_bytes == codecs::bytes<4>{} && + first_text.view().empty() && first_bytes.view().empty(); + }); + BOOST_TEST(verdict); + auto const fixed_text = codecs::encode(test::letters, input); // built before the window + BOOST_TEST(fixed_text.has_value()); + test::expect_no_allocation("decode of a fixed text", [&] { + auto const decoded = codecs::decode(test::letters, fixed_text.value()); + verdict = decoded.has_value(); + sink = decoded.value().size(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("typed decode into an array", [&] { + verdict = codecs::decode>(test::letters, "abpp").has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("typed decode into fixed bytes", [&] { + verdict = codecs::decode>(test::letters, "abpp").has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("typed decode into a library's fixed type", [&] { + verdict = codecs::decode(test::letters, "abpp").has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("typed decodes that are refused", [&] { + verdict = codecs::decode>(test::letters, "ab").has_value() || + codecs::decode>(test::letters, "abpp").has_value() || + codecs::decode(test::letters, "abpq").has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("a value codec's default result and buffer forms", [&] { + auto const encoded = codecs::encode(test::be16, test::number{0x1234}); + verdict = encoded.has_value() && + codecs::encode(test::be16, test::number{0x1234}, output_bytes).has_value() && + codecs::decode(test::be16, input).has_value(); + sink = encoded.value().size(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("a value codec's refused buffer", [&] { + verdict = + codecs::encode(test::be16, test::number{0x1234}, + std::span{output_bytes}.first(1)) + .has_value() || + codecs::decode(test::be16, std::array{}).has_value(); + }); + BOOST_TEST(!verdict); + // The buffer form of a value codec of text (F16): characters, nothing allocated. + std::array output_characters{}; + test::expect_no_allocation("a value codec of text's buffer form", [&] { + verdict = + codecs::encode(test::be16, test::hex_number{0x1234}, output_characters).has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("a value codec of text's refused buffer", [&] { + verdict = codecs::encode(test::be16, test::hex_number{0x1234}, + std::span{output_characters}.first(3)) + .has_value(); + }); + BOOST_TEST(!verdict); + static_cast(sink); +} + +/** The token forms that hold their result in place (Task 4): `tokens::fixed` allocates nothing, + on every path. */ +void check_fixed_tokens() { + std::array const input{0x01, 0xff}; + std::vector const heap_input{0x01, 0xff}; // built before the window + bool volatile verdict = false; + test::expect_no_allocation("encode into fixed", [&] { + auto const from_array = codecs::encode(test::letters, input, codecs::tokens::fixed<8>{}); + auto const from_heap = + codecs::encode(test::letters, heap_input, codecs::tokens::fixed<8>{}); + verdict = from_array.has_value() && from_heap.has_value() && + from_array.value() == from_heap.value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("decode into fixed", [&] { + auto const decoded = codecs::decode(test::letters, "abpp", codecs::tokens::fixed<8>{}); + verdict = decoded.has_value() && decoded.value().size() == 2; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("a value codec into fixed", [&] { + auto const encoded = + codecs::encode(test::be16, test::number{0x1234}, codecs::tokens::fixed<2>{}); + auto const text_encoded = + codecs::encode(test::be16, test::hex_number{0x1234}, codecs::tokens::fixed<4>{}); + verdict = encoded.has_value() && text_encoded.has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("fixed too small, and refused", [&] { + verdict = codecs::encode(test::letters, input, codecs::tokens::fixed<3>{}).has_value() || + codecs::decode(test::letters, "abpp", codecs::tokens::fixed<1>{}).has_value() || + codecs::decode(test::letters, "abpq", codecs::tokens::fixed<8>{}).has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("the default token of a fixed result", [&] { + verdict = codecs::encode(test::letters, input, codecs::tokens::automatic{}).has_value() && + codecs::decode(test::letters, codecs::text<4>{}, codecs::tokens::automatic{}) + .has_value(); + }); + BOOST_TEST(verdict); +} + +/** The secret results in place (Task 5) allocate nothing, nor does a heap one that holds nothing. + */ +void check_secret_results() { + bool volatile verdict = false; + test::expect_no_allocation("the fixed secret results", [&] { + codecs::secret_text<64> held_text; + codecs::detail::fixed_access::writable(held_text)[0] = 's'; + codecs::detail::fixed_access::resize(held_text, 1); + codecs::secret_text<64> const moved_text{std::move(held_text)}; + codecs::secret_text<64> const cloned_text = moved_text.clone(); + codecs::secret_bytes<32> held_bytes; + codecs::detail::fixed_access::writable(held_bytes)[0] = 0x5a; + codecs::detail::fixed_access::resize(held_bytes, 1); + codecs::secret_bytes<32> moved_bytes; + moved_bytes = std::move(held_bytes); + codecs::secret_bytes<32> const cloned_bytes = moved_bytes.clone(); + verdict = cloned_text.view() == "s" && cloned_bytes.view()[0] == 0x5a; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("an empty secret on the heap", [&] { + codecs::secret_byte_vector empty_bytes; + empty_bytes.append(std::span{}); + codecs::secret_string empty_text; + empty_text.clear(); + codecs::secret_string const moved_text{std::move(empty_text)}; + verdict = empty_bytes.empty() && moved_text.empty() && empty_bytes.clone().empty(); + }); + BOOST_TEST(verdict); +} + +/** The fixed secret operations (Task 6) allocate nothing: the secret results in place, secure's + secret as a decode's target, tokens::secret of a static bound. */ +void check_secret_operations() { + webcpp::secure::secret<2> const key; + std::array const input{0x01, 0xff}; + bool volatile verdict = false; + test::expect_no_allocation("the fixed secret operations", [&] { + auto const encoded = codecs::encode(test::letters, key); + auto const through_token = codecs::encode(test::letters, input, codecs::tokens::secret); + auto const decoded = codecs::decode>(test::letters, "abpp"); + auto const into_bytes = codecs::decode>(test::letters, "abpp"); + auto const fixed_back = + codecs::decode(test::letters, codecs::text<4>{}, codecs::tokens::secret); + std::array buffer{}; + auto const buffered = codecs::encode(test::letters, key, std::span{buffer}); + verdict = encoded.has_value() && through_token.has_value() && decoded.has_value() && + into_bytes.has_value() && fixed_back.has_value() && buffered.has_value() && + codecs::encoded_size(test::letters, key) == 4; + }); + BOOST_TEST(verdict); +} + +/** Runs `body` and returns how many times operator new was called in it. */ +template +std::size_t allocations_of(Body body) { + std::size_t const before = test::counted_new.load(); + body(); + return test::counted_new.load() - before; +} + +/** assign_to (the owner's ruling): a scratch in place when the bound is known at compile time and + at most 4096 elements, else a scratch of the target's allocator, one allocation; the result is + copied into the target, which keeps its buffer when it holds the result. */ +void check_assign_to_scratch() { + std::array const at_the_limit{}; // 4096 letters + std::array const past_the_limit{}; // 4098 letters + std::vector const heap_input(100); // a size known at run time + std::array at_the_limit_text{}; // 4096 bytes + std::array past_the_limit_text{}; // 4097 bytes + at_the_limit_text.fill('a'); + past_the_limit_text.fill('a'); + std::string text_target; + text_target.reserve(8192); + char const* const text_buffer = text_target.data(); + std::vector byte_target; + byte_target.reserve(8192); + std::uint8_t const* const byte_buffer = byte_target.data(); + // The scratch container's own bookkeeping block (support/bookkeeping.hpp) is one more where + // the standard library allocates one: the MSVC STL's debug proxy. + std::size_t const one_scratch = test::bookkeeping().bytes != 0 ? 2U : 1U; + bool volatile verdict = false; + test::expect_no_allocation("assign_to of a static bound of 4096, in place", [&] { + verdict = + codecs::encode(test::letters, at_the_limit, codecs::tokens::assign_to(text_target)) + .has_value() && + codecs::decode(test::letters, at_the_limit_text, codecs::tokens::assign_to(byte_target)) + .has_value(); + }); + BOOST_TEST(verdict); + BOOST_TEST_EQ(text_target.size(), 4096U); + BOOST_TEST_EQ(byte_target.size(), 4096U); + // Past it, and of a size known at run time: one allocation each, the heap scratch. + BOOST_TEST_EQ(allocations_of([&] { + verdict = codecs::encode(test::letters, past_the_limit, + codecs::tokens::assign_to(text_target)) + .has_value(); + }), + one_scratch); + BOOST_TEST(verdict); + BOOST_TEST_EQ(text_target.size(), 4098U); + BOOST_TEST_EQ(allocations_of([&] { + verdict = codecs::decode(test::letters, past_the_limit_text, + codecs::tokens::assign_to(byte_target)) + .has_value(); + }), + one_scratch); + BOOST_TEST(verdict); + BOOST_TEST_EQ(byte_target.size(), 4097U); + BOOST_TEST_EQ(allocations_of([&] { + verdict = codecs::encode(test::letters, heap_input, + codecs::tokens::assign_to(text_target)) + .has_value(); + }), + one_scratch); + BOOST_TEST(verdict); + BOOST_TEST_EQ(text_target.size(), 200U); + // Each time the target kept its buffer. + BOOST_TEST(text_target.data() == text_buffer); + BOOST_TEST(byte_target.data() == byte_buffer); +} + +/** over with a bound known at compile time (Task 7, spec "Allocation"): its intermediate is in + place, so every form allocates nothing, a secret chain and a value codec's included; with a heap + intermediate the exact sizes, encode and decode allocate (ruling R3, finding F17), the buffer forms + among them, which the control below counts. */ +void check_over() { + constexpr codecs::over chain{test::letters, test::letters}; + constexpr codecs::over value_chain{test::letters, test::be16}; + std::array const input{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; + std::vector const heap_input(input.begin(), input.end()); + webcpp::secure::secret<32> key; + std::array output{}; + std::array decoded{}; + std::size_t volatile sink = 0; + bool volatile verdict = false; + test::expect_no_allocation("over, the default results", [&] { + auto const encoded = codecs::encode(chain, input); + auto const bytes_back = codecs::decode(chain, encoded.value()); + verdict = encoded.has_value() && bytes_back.has_value() && + std::ranges::equal(bytes_back.value().view(), input); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("over, the sizes", [&] { + sink = codecs::encoded_size(chain, input); + sink = codecs::encoded_size(chain, key); + }); + test::expect_no_allocation("over, the buffer forms", [&] { + // The decode reads the 64 letters of the input, a text<64>: its intermediate is in place. + auto const written = codecs::decode(chain, codecs::encode(chain, input).value(), decoded); + verdict = codecs::encode(chain, input, output).has_value() && written.has_value() && + written.value() == input.size() && + std::ranges::equal(std::span{decoded}.first(input.size()), input); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("over, a typed decode and the tokens", [&] { + auto const text_value = codecs::encode(chain, input); + auto const as_array = + codecs::decode>(chain, text_value.value()); + auto const fixed = codecs::encode(chain, input, codecs::tokens::fixed<64>{}); + verdict = as_array.has_value() && fixed.has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("over, a secret chain", [&] { + auto const secret_text = codecs::encode(chain, key); + // The text's size is known at compile time: a text of 128 characters in an array. + std::array text_array{}; + std::ranges::copy(secret_text.value().view(), text_array.begin()); + auto const secret_back = codecs::decode>(chain, text_array); + verdict = secret_text.has_value() && secret_back.has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("over, a value codec", [&] { + auto const encoded = codecs::encode(value_chain, test::number{0x1234}); + auto const number_back = codecs::decode(value_chain, encoded.value()); + // Made secret by its token: the intermediate in place, wiped, the result a secret_text<4>. + auto const secret_text = + codecs::encode(value_chain, test::number{0x1234}, codecs::tokens::secret); + verdict = encoded.has_value() && number_back.has_value() && secret_text.has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("over, an input whose bound saturates and the empty input", [&] { + constexpr codecs::over saturating_chain{test::letters, test::saturating}; + std::array const long_input{}; + verdict = codecs::encode(saturating_chain, long_input).has_value() || + codecs::encode(chain, std::array{}).value().size() != 0; + }); + BOOST_TEST(!verdict); + // The heap intermediate allocates, in the sizes and in the buffer forms: the form that counts. + BOOST_TEST_GE(allocations_of([&] { sink = codecs::encoded_size(chain, heap_input); }), 1U); + BOOST_TEST_GE( + allocations_of([&] { verdict = codecs::encode(chain, heap_input, output).has_value(); }), + 2U); + BOOST_TEST(verdict); + std::string const heap_text = + codecs::encode(chain, heap_input, codecs::tokens::return_string).value(); + std::array wide_decoded{}; + BOOST_TEST_GE(allocations_of([&] { + verdict = codecs::decode(chain, heap_text, wide_decoded).has_value(); + }), + 2U); + BOOST_TEST(verdict); + static_cast(sink); +} + +/** The transformers of the tests' own, a stream and the one-shots of the toy media, convert in the + caller's spans and allocate nothing (D17, D18). */ +void check_transformers() { + std::array const packets{ + test::packet{.index = 0, .frames = 1}, + test::packet{.index = 1, .frames = 2}, + test::packet{.index = 2, .frames = 0}, + }; + std::array frames{}; + std::array frame_bytes{}; + std::array images{}; + std::array doubled{}; + std::size_t volatile sink = 0; + bool volatile verdict = false; + test::expect_no_allocation("doubler, a stream", [&] { + test::doubler transformer; + bool streamed = transformer.send(std::string_view{"abc"}).has_value(); + auto const received = transformer.receive(doubled); + streamed = streamed && received.has_value() && received->count == 6 && + transformer.flush().has_value(); + test::doubler moved{std::move(transformer)}; + moved.reset(); + verdict = streamed && std::string_view{doubled.data(), 6} == "aabbcc"; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("packets_to_frames, a stream", [&] { + test::packets_to_frames decoder; + std::size_t received_count = 0; + for (test::packet const& input_packet : packets) { + auto const sent = decoder.send(std::span{&input_packet, 1}); + auto const received = decoder.receive(std::span{frames}.subspan(received_count)); + received_count += sent.has_value() && received.has_value() ? received->count : 0; + } + auto const flushed = decoder.flush(); + auto const tail = decoder.receive(std::span{frames}.subspan(received_count)); + received_count += flushed.has_value() && tail.has_value() ? tail->count : 0; + test::packets_to_frames moved{std::move(decoder)}; + moved.reset(); + verdict = received_count == 3 && frames[0].index == 0 && frames[1].index == 2 && + frames[2].index == 3; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("frame_to_bytes and frame_to_image, one-shot", [&] { + auto const written = + test::frame_to_bytes::transform(std::span{frames}.first(3), frame_bytes); + auto const bounded = + test::frame_to_bytes_bounded::transform(std::span{frames}.first(3), frame_bytes); + auto const imaged = test::frame_to_image::transform(std::span{frames}.first(3), images); + sink = written.has_value() ? written.value() : 0; + verdict = + written.has_value() && bounded.has_value() && imaged.has_value() && imaged.value() == 3; + }); + BOOST_TEST(verdict); + static_cast(sink); +} + +/** + pipe and drain allocate nothing (D21): a pipe made, streamed, flushed, moved and reset, and + drains through drain's own buffer, a capacity and the caller's span. +*/ +void check_pipe_and_drain() { + std::array piped_output{}; + std::array drain_buffer{}; + bool volatile verdict = false; + test::expect_no_allocation("pipe of two doublers", [&] { + auto piped = codecs::pipe(test::doubler{}, test::doubler{}, codecs::capacity<3>); + bool streamed = piped.send(std::string_view{"abc"}).has_value(); + auto const received = piped.receive(piped_output); + streamed = + streamed && received.has_value() && received->count == 12 && piped.flush().has_value(); + auto moved{std::move(piped)}; + moved.reset(); + verdict = streamed && std::string_view{piped_output.data(), 12} == "aaaabbbbcccc"; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("drain of a pipe of three doublers", [&] { + auto piped = codecs::pipe(test::doubler{}, test::doubler{}, test::doubler{}); + std::size_t total = 0; + auto sink = [&total](std::span piece) noexcept { total += piece.size(); }; + bool drained = piped.send(std::string_view{"abc"}).has_value() && + codecs::drain(piped, sink).has_value(); + drained = drained && piped.send(std::string_view{"de"}).has_value() && + codecs::drain(piped, sink, codecs::capacity<3>).has_value(); + drained = + drained && piped.send(std::string_view{"f"}).has_value() && piped.flush().has_value(); + auto const last = codecs::drain(piped, sink, std::span{drain_buffer}); + verdict = + drained && last.has_value() && last.value() == codecs::flow::finished && total == 48; + }); + BOOST_TEST(verdict); +} + +/** + A format's transformers allocate nothing in a stream call (D21): letters' encoder and decoder, + sent in chunks, received into short spans, flushed, drained, moved and reset, their one-shot + transform, and over's stream, a pipe of its links' streams. +*/ +void check_format_transformers() { + std::array const bytes{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}; + std::array text{}; + std::array decoded{}; + bool volatile verdict = false; + test::expect_no_allocation("encoder(letters) and decoder(letters)", [&] { + auto encoder = codecs::encoder(test::letters); + bool streamed = encoder.send(std::span{bytes}.first(2)).has_value(); + auto const first = encoder.receive(std::span{text}.first(3)); + auto const second = encoder.receive(std::span{text}.subspan(3, 1)); + streamed = streamed && first.has_value() && second.has_value() && + encoder.send(std::span{bytes}.subspan(2)).has_value() && + encoder.flush().has_value(); + std::size_t written = 4; + auto sink = [&](std::span piece) noexcept { + std::ranges::copy(piece, text.begin() + static_cast(written)); + written += piece.size(); + }; + streamed = streamed && codecs::drain(encoder, sink, codecs::capacity<5>).has_value(); + auto moved{std::move(encoder)}; + moved.reset(); + auto decoder = codecs::decoder(test::letters); + streamed = streamed && written == text.size() && + decoder.send(std::span{text}.first(5)).has_value() && + decoder.receive(decoded).has_value() && + decoder.send(std::span{text}.subspan(5)).has_value() && + decoder.flush().has_value(); + auto const last = decoder.receive(std::span{decoded}.subspan(2)); + auto moved_decoder{std::move(decoder)}; + moved_decoder.reset(); + auto const transformed = moved.transform(bytes, text); + verdict = streamed && last.has_value() && last->flow == codecs::flow::finished && + decoded == bytes && transformed.has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("encoder(over{letters, letters}) as a stream", [&] { + std::array chain_text{}; + auto encoder = codecs::encoder(codecs::over{test::letters, test::letters}); + bool streamed = encoder.send(bytes).has_value() && encoder.flush().has_value(); + auto const received = encoder.receive(chain_text); + auto decoder = codecs::decoder(codecs::over{test::letters, test::letters}); + streamed = streamed && received.has_value() && received->count == chain_text.size() && + decoder.send(std::span{chain_text}).has_value() && + decoder.flush().has_value(); + auto const decoded_chain = decoder.receive(decoded); + auto moved{std::move(decoder)}; + moved.reset(); + verdict = streamed && decoded_chain.has_value() && + decoded_chain->flow == codecs::flow::finished && decoded == bytes; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("a fault of the configuration, in every stream call", [&] { + auto encoder = codecs::encoder(codecs::over{test::letters, test::letters(true)}); + bool faulted = !encoder.send(bytes).has_value() && !encoder.receive(text).has_value() && + !encoder.flush().has_value(); + encoder.reset(); + auto decoder = codecs::decoder(test::letters(true)); + faulted = faulted && !decoder.send(std::span{text}).has_value() && + !decoder.receive(decoded).has_value() && !decoder.flush().has_value() && + !decoder.transform(std::span{text}, decoded).has_value(); + verdict = faulted; + }); + BOOST_TEST(verdict); +} + +/** + Receives the item `adapter` holds into spans of `span_size` of `output` from `total` on, adding + what it receives to `total`; false when a call fails. +*/ +template +bool receive_item(Adapter& adapter, std::span output, std::size_t span_size, + std::size_t& total) { + for (;;) { + auto const received = adapter.receive(output.subspan(total, span_size)); + if (!received.has_value()) { + return false; + } + total += received->count; + if (received->flow != codecs::flow::output_pending) { + return true; + } + } +} + +/** + each and buffered in place allocate nothing (D21): each made, streamed into spans shorter than an + item's output and into spans that take it whole, flushed, moved and reset; buffered made, sent in + chunks, flushed, received, moved and reset. +*/ +void check_each_and_buffered() { + std::array const frames = test::five_frames(); + std::array frame_bytes{}; + std::array images{}; + bool volatile verdict = false; + test::expect_no_allocation("each(frame_to_bytes_bounded, capacity<4>)", [&] { + auto adapter = codecs::each(test::frame_to_bytes_bounded(), codecs::capacity<4>); + std::size_t total = 0; + bool streamed = true; + for (std::size_t index = 0; index < frames.size(); ++index) { + // Spans of 3, then 4: through the storage, then straight into the span. + streamed = streamed && adapter.send(std::span{frames}.subspan(index)).has_value() && + receive_item(adapter, frame_bytes, index % 2 == 0 ? 3 : 4, total); + } + streamed = streamed && adapter.flush().has_value(); + auto moved{std::move(adapter)}; + moved.reset(); + verdict = streamed && total == 14 && moved.completed_items() == 0; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("buffered(frame_to_image, capacity<8>)", [&] { + auto adapter = codecs::buffered(test::frame_to_image{}, codecs::capacity<8>); + bool streamed = adapter.send(std::span{frames}.first(2)).has_value() && + adapter.send(std::span{frames}.subspan(2)).has_value() && + adapter.flush().has_value(); + auto const received = adapter.receive(images); + streamed = streamed && received.has_value() && received->count == 5; + auto moved{std::move(adapter)}; + moved.reset(); + verdict = streamed && images[4].index == 4; + }); + BOOST_TEST(verdict); +} + +/** + A secret stream allocates nothing either (D21): its guard and its wipes are in place. A secret + encoder and decoder of letters, sent, received into short spans, drained, moved, reset and + destroyed; a pipe of two secret encoders and over's secret stream; each and buffered in place + over a secret encoder. +*/ +void check_secret_streams() { + std::array const bytes{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}; + std::array text{}; + std::array decoded{}; + bool volatile verdict = false; + test::expect_no_allocation("encoder(letters, secret_operation) and its decoder", [&] { + auto encoder = codecs::encoder(test::letters, codecs::secret_operation); + bool streamed = encoder.send(bytes).has_value() && + encoder.receive(std::span{text}.first(3)).has_value(); + auto moved{std::move(encoder)}; + std::size_t written = 3; + auto sink = [&](std::span piece) noexcept { + std::ranges::copy(piece, text.begin() + static_cast(written)); + written += piece.size(); + }; + streamed = streamed && moved.flush().has_value() && + codecs::drain(moved, sink, codecs::capacity<5>).has_value() && written == 12; + moved.reset(); + auto decoder = codecs::decoder(test::letters, codecs::secret_operation); + streamed = streamed && decoder.send(std::span{text}.first(12)).has_value() && + decoder.flush().has_value() && decoder.receive(decoded).has_value(); + auto moved_decoder{std::move(decoder)}; + moved_decoder.reset(); + verdict = streamed && decoded == bytes; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("pipe of two secret encoders, and over's secret stream", [&] { + auto piped = codecs::pipe(codecs::encoder(test::letters, codecs::secret_operation), + codecs::encoder(test::letters, codecs::secret_operation)); + bool streamed = piped.send(bytes).has_value() && piped.flush().has_value(); + auto const received = piped.receive(text); + auto moved{std::move(piped)}; + moved.reset(); + auto chain = + codecs::encoder(codecs::over{test::letters, test::letters}, codecs::secret_operation); + std::array chain_text{}; + streamed = streamed && received.has_value() && received->count == text.size() && + chain.send(bytes).has_value() && chain.flush().has_value() && + chain.receive(chain_text).has_value(); + chain.reset(); + verdict = streamed && chain_text == text; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("each and buffered in place over a secret encoder", [&] { + auto each = codecs::each(codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<2>); + bool streamed = each.send(bytes).has_value() && + each.receive(std::span{text}.first(1)).has_value() && + each.receive(std::span{text}.subspan(1, 1)).has_value(); + auto moved_each{std::move(each)}; + moved_each.reset(); + auto buffered = codecs::buffered(codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<6>); + streamed = streamed && buffered.send(bytes).has_value() && buffered.flush().has_value() && + buffered.receive(text).has_value(); + auto moved_buffered{std::move(buffered)}; + moved_buffered.reset(); + verdict = streamed && text[0] == 'a' && text[11] == 'l'; + }); + BOOST_TEST(verdict); +} + +/** A pipe of packets_to_frames into each(frame_to_image, capacity<1>) allocates nothing (D21). */ +void check_pipe_of_packets_into_each() { + std::array images{}; + bool volatile verdict = false; + std::array const packets{ + test::packet{.index = 0, .frames = 1}, + test::packet{.index = 1, .frames = 2}, + }; + test::expect_no_allocation("pipe(packets_to_frames, each(frame_to_image, capacity<1>))", [&] { + auto piped = codecs::pipe(test::packets_to_frames{}, + codecs::each(test::frame_to_image{}, codecs::capacity<1>)); + std::size_t total = 0; + bool streamed = true; + for (test::packet const& input_packet : packets) { + streamed = streamed && piped.send(std::span{&input_packet, 1}).has_value(); + auto const received = piped.receive(std::span{images}.subspan(total)); + streamed = streamed && received.has_value(); + total += received.has_value() ? received->count : 0; + } + streamed = streamed && piped.flush().has_value(); + auto const last = piped.receive(std::span{images}.subspan(total)); + total += last.has_value() ? last->count : 0; + verdict = streamed && total == 3 && images[2].index == 3; + }); + BOOST_TEST(verdict); +} + +/** The default and typed forms refuse an input whose bound saturates (Review Focus 2) before they + allocate anything: the heap results are never built. */ +void check_saturating_refusals() { + std::vector const long_bytes(test::saturating_t::most_bytes + 1); + std::string const long_text(test::saturating_t::most_characters + 1, 'a'); + std::array const long_array{}; + std::array long_characters{}; + long_characters.fill('a'); + bool volatile verdict = true; + test::expect_no_allocation("default encode of an input whose bound saturates", [&] { + verdict = codecs::encode(test::saturating, long_bytes).has_value() || + codecs::encode(test::saturating, long_array).has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("default decode of a text whose bound saturates", [&] { + verdict = codecs::decode(test::saturating, long_text).has_value() || + codecs::decode(test::saturating, long_characters).has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("typed decode of a text whose bound saturates", [&] { + verdict = + codecs::decode>(test::saturating, long_text).has_value() || + codecs::decode(test::saturating, long_text).has_value() || + codecs::decode>(test::saturating, long_text).has_value() || + codecs::decode>(test::saturating, long_text).has_value() || + codecs::decode(test::saturating, long_text).has_value(); + }); + BOOST_TEST(!verdict); + // The refusals are input_too_long, so that none of the format's own functions ran. + BOOST_TEST(codecs::encode(test::saturating, long_bytes).error() == + codecs::error::input_too_long); + BOOST_TEST(codecs::decode(test::saturating, long_text).error() == + codecs::error::input_too_long); + BOOST_TEST(codecs::decode(test::saturating, long_text).error() == + codecs::error::input_too_long); +} + +/** hex's buffer forms, fixed results, typed decodes into fixed types and secret fixed results + (Task 13) allocate nothing, on every path. */ +void check_hex_one_shot_forms() { + namespace formats = codecs::formats; + std::array const digest = test::digest_bytes(); + webcpp::secure::secret<32> const key; + std::array text{}; + std::array decoded{}; + auto const fixed_text = codecs::encode(formats::hex, digest); // built before the windows + std::size_t volatile sink = 0; + bool volatile verdict = false; + test::expect_no_allocation("hex's buffer forms and sizes", [&] { + sink = codecs::encoded_size(formats::hex, digest); + sink = codecs::max_decoded_size(formats::hex, fixed_text.value().view()); + verdict = + codecs::encode(formats::hex, digest, text).has_value() && + codecs::decode(formats::hex, std::string_view{text.data(), text.size()}, decoded) + .has_value() && + codecs::encode(formats::hex(formats::letter_case::upper), digest, text).has_value() && + codecs::decode(formats::hex, std::string_view{text.data(), text.size()}, decoded) + .has_value() && + decoded == digest; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("hex's refused buffer forms", [&] { + verdict = + codecs::encode(formats::hex, digest, std::span{text}.first(63)).has_value() || + codecs::decode(formats::hex, std::string_view{"abc"}, decoded).has_value() || + codecs::decode(formats::hex, std::string_view{"ag"}, decoded).has_value() || + codecs::decode(formats::hex, std::string_view{"abcd"}, std::span{decoded}.first(1)) + .has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("hex's fixed results and tokens", [&] { + auto const encoded = codecs::encode(formats::hex, digest); + auto const back = codecs::decode(formats::hex, encoded.value()); + auto const into_array = + codecs::decode>(formats::hex, fixed_text.value().view()); + auto const into_bytes = + codecs::decode>(formats::hex, fixed_text.value().view()); + auto const into_key = codecs::decode(formats::hex, "abcd"); + auto const through_fixed = + codecs::encode(formats::hex, digest, codecs::tokens::fixed<64>{}); + auto const fixed_back = + codecs::decode(formats::hex, fixed_text.value(), codecs::tokens::fixed<32>{}); + verdict = encoded.has_value() && back.has_value() && into_array.has_value() && + into_bytes.has_value() && into_key.has_value() && through_fixed.has_value() && + fixed_back.has_value() && back.value().size() == 32; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("hex's secret fixed results", [&] { + auto const from_key = codecs::encode(formats::hex, key); + auto const through_token = codecs::encode(formats::hex, digest, codecs::tokens::secret); + auto const into_secret = + codecs::decode>(formats::hex, fixed_text.value().view()); + auto const into_secret_bytes = + codecs::decode>(formats::hex, fixed_text.value().view()); + auto const secret_back = + codecs::decode(formats::hex, fixed_text.value(), codecs::tokens::secret); + std::array secret_text{}; + auto const secret_buffer = codecs::encode(formats::hex, key, std::span{secret_text}); + verdict = from_key.has_value() && through_token.has_value() && into_secret.has_value() && + into_secret_bytes.has_value() && secret_back.has_value() && + secret_buffer.has_value() && codecs::encoded_size(formats::hex, key) == 64; + }); + BOOST_TEST(verdict); + static_cast(sink); +} + +/** + hex's streams allocate nothing once made (the spec's "Streams allocate nothing", on hex): 1 MiB of + random bytes in random chunks through encoder(hex) piped into decoder(hex), drained into a fixed + span and compared as it goes; encoder(hex) and decoder(hex), public and secret, streamed, moved + and reset; and each and buffered in place over encoder(hex). +*/ +void check_hex_streams() { + namespace formats = codecs::formats; + std::vector input(std::size_t{1024} * 1024); + // A fixed seed, so that every lane and every run sees the same bytes. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) + std::mt19937_64 generator{20261126}; + std::ranges::generate(input, [&] { return static_cast(generator()); }); + bool volatile verdict = false; + test::expect_no_allocation( + "1 MiB through pipe(encoder(hex), decoder(hex)) in random chunks", [&] { + auto piped = codecs::pipe(codecs::encoder(formats::hex), codecs::decoder(formats::hex)); + verdict = + test::stream_in_random_chunks<777>(piped, std::span{input}, + std::span{input}, generator); + }); + BOOST_TEST(verdict); + + std::array const bytes{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}; + std::array text{}; + std::array decoded{}; + test::expect_no_allocation("encoder(hex) and decoder(hex), public and secret", [&] { + auto encoder = codecs::encoder(formats::hex(formats::letter_case::upper)); + bool streamed = encoder.send(bytes).has_value() && + encoder.receive(std::span{text}.first(3)).has_value() && + encoder.receive(std::span{text}.subspan(3)).has_value() && + encoder.flush().has_value(); + auto moved{std::move(encoder)}; + moved.reset(); + auto secret_decoder = codecs::decoder(formats::hex, codecs::secret_operation); + streamed = streamed && + secret_decoder.send(std::span{text}.first(5)).has_value() && + secret_decoder.receive(decoded).has_value() && + secret_decoder.send(std::span{text}.subspan(5)).has_value() && + secret_decoder.flush().has_value() && + secret_decoder.receive(std::span{decoded}.subspan(2)).has_value(); + auto moved_decoder{std::move(secret_decoder)}; + moved_decoder.reset(); + auto secret_encoder = codecs::encoder(formats::hex, codecs::secret_operation); + streamed = streamed && secret_encoder.send(bytes).has_value() && + secret_encoder.receive(std::span{text}.first(1)).has_value(); + auto moved_secret{std::move(secret_encoder)}; + moved_secret.reset(); + verdict = streamed && decoded == bytes && text[0] == '0' && text[11] == 'B'; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("each and buffered in place over encoder(hex)", [&] { + auto each = codecs::each(codecs::encoder(formats::hex), codecs::capacity<2>); + bool streamed = each.send(bytes).has_value() && + each.receive(std::span{text}.first(1)).has_value() && + each.receive(std::span{text}.subspan(1, 1)).has_value(); + auto buffered = codecs::buffered(codecs::encoder(formats::hex, codecs::secret_operation), + codecs::capacity<6>); + streamed = streamed && buffered.send(bytes).has_value() && buffered.flush().has_value() && + buffered.receive(text).has_value(); + auto moved_buffered{std::move(buffered)}; + moved_buffered.reset(); + verdict = streamed && text[0] == '0' && text[11] == 'b'; + }); + BOOST_TEST(verdict); +} + +/** + base64's and base64url's buffer forms, fixed results, typed decodes into fixed types and secret + fixed results allocate nothing, in the window of each. +*/ +void check_base64_one_shot_forms() { + namespace formats = codecs::formats; + std::array const digest = test::digest_bytes(); + webcpp::secure::secret<32> const key; + std::array text{}; + std::array decoded{}; + auto const fixed_text = codecs::encode(formats::base64, digest); // built before the windows + auto const url_text = codecs::encode(formats::base64url, digest); + std::size_t volatile sink = 0; + bool volatile verdict = false; + test::expect_no_allocation("base64's buffer forms and sizes", [&] { + sink = codecs::encoded_size(formats::base64, digest); + sink = codecs::max_decoded_size(formats::base64, fixed_text.value().view()); + auto const written = codecs::encode(formats::base64, digest, text); + auto const back = codecs::decode(formats::base64, + std::string_view{text.data(), written.value()}, decoded); + auto const url_written = + codecs::encode(formats::base64url(formats::padding::written), digest, text); + auto const url_back = + codecs::decode(formats::base64url(formats::padding::written), + std::string_view{text.data(), url_written.value()}, decoded); + verdict = written.has_value() && written.value() == 44 && back.has_value() && + back.value() == 32 && url_written.has_value() && url_back.has_value() && + std::ranges::equal(std::span{decoded}.first(32), digest); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("base64's refused buffer forms", [&] { + verdict = codecs::encode(formats::base64, digest, std::span{text}.first(43)).has_value() || + codecs::decode(formats::base64, std::string_view{"Zm9"}, decoded).has_value() || + codecs::decode(formats::base64, std::string_view{"Zh=="}, decoded).has_value() || + codecs::decode(formats::base64, std::string_view{"Zm9\n"}, decoded).has_value() || + codecs::decode(formats::base64, std::string_view{"Zm9vYmFy"}, + std::span{decoded}.first(1)) + .has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("base64's fixed results and tokens", [&] { + auto const encoded = codecs::encode(formats::base64, digest); + auto const back = codecs::decode(formats::base64, encoded.value()); + auto const into_array = codecs::decode>( + formats::base64, fixed_text.value().view()); + auto const into_bytes = + codecs::decode>(formats::base64url, url_text.value().view()); + auto const into_key = codecs::decode(formats::base64, "AQI="); + auto const through_fixed = + codecs::encode(formats::base64, digest, codecs::tokens::fixed<44>{}); + auto const fixed_back = + codecs::decode(formats::base64, fixed_text.value(), codecs::tokens::fixed<33>{}); + verdict = encoded.has_value() && back.has_value() && into_array.has_value() && + into_bytes.has_value() && into_key.has_value() && through_fixed.has_value() && + fixed_back.has_value() && back.value().size() == 32; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("base64's secret fixed results", [&] { + auto const from_key = codecs::encode(formats::base64, key); + auto const through_token = codecs::encode(formats::base64, digest, codecs::tokens::secret); + auto const into_secret = + codecs::decode>(formats::base64, fixed_text.value().view()); + auto const into_secret_bytes = + codecs::decode>(formats::base64, fixed_text.value().view()); + auto const secret_back = + codecs::decode(formats::base64, fixed_text.value(), codecs::tokens::secret); + std::array secret_text{}; + auto const secret_buffer = codecs::encode(formats::base64, key, std::span{secret_text}); + verdict = from_key.has_value() && through_token.has_value() && into_secret.has_value() && + into_secret_bytes.has_value() && secret_back.has_value() && + secret_buffer.has_value() && codecs::encoded_size(formats::base64, key) == 44; + }); + BOOST_TEST(verdict); + static_cast(sink); +} + +/** + base64's streams of 1 MiB allocate nothing (the spec's "Streams allocate nothing", on base64): + random bytes in random chunks through encoder(base64) piped into decoder(base64) and through + base64url's, drained into a fixed span and compared as it goes; the text of the bytes decoded by + a secret decoder likewise. +*/ +void check_base64_mebibyte() { + namespace formats = codecs::formats; + std::vector input(std::size_t{1024} * 1024); + // A fixed seed, so that every lane and every run sees the same bytes. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) + std::mt19937_64 generator{20261126}; + std::ranges::generate(input, [&] { return static_cast(generator()); }); + std::string const text = codecs::encode(formats::base64, input).value(); + bool volatile verdict = false; + test::expect_no_allocation("1 MiB through pipe(encoder(base64), decoder(base64))", [&] { + auto piped = + codecs::pipe(codecs::encoder(formats::base64), codecs::decoder(formats::base64)); + verdict = + test::stream_in_random_chunks<777>(piped, std::span{input}, + std::span{input}, generator); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("1 MiB through pipe(encoder(base64url), decoder(base64url))", [&] { + auto piped = + codecs::pipe(codecs::encoder(formats::base64url), codecs::decoder(formats::base64url)); + verdict = + test::stream_in_random_chunks<777>(piped, std::span{input}, + std::span{input}, generator); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("1 MiB of base64 text through decoder(base64)", [&] { + auto decoder = codecs::decoder(formats::base64, codecs::secret_operation); + verdict = test::stream_in_random_chunks<555>( + decoder, test::characters_of(text), std::span{input}, generator); + }); + BOOST_TEST(verdict); +} + +/** + base64's small streams allocate nothing once made: encoder(base64url), a secret + decoder(base64url) and a secret encoder(base64), streamed, moved and reset; and each and buffered + in place over encoder(base64). +*/ +void check_base64_streams() { + namespace formats = codecs::formats; + bool volatile verdict = false; + std::array const bytes{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd}; + std::array characters{}; + std::array decoded{}; + test::expect_no_allocation( + "encoder(base64url), a secret decoder(base64url) and a secret encoder(base64)", [&] { + auto encoder = codecs::encoder(formats::base64url); + bool streamed = encoder.send(bytes).has_value() && + encoder.receive(std::span{characters}.first(3)).has_value() && + encoder.receive(std::span{characters}.subspan(3)).has_value() && + encoder.flush().has_value() && + encoder.receive(std::span{characters}.subspan(8)).has_value(); + auto moved{std::move(encoder)}; + moved.reset(); + auto secret_decoder = codecs::decoder(formats::base64url, codecs::secret_operation); + streamed = + streamed && + secret_decoder.send(std::span{characters}.first(5)).has_value() && + secret_decoder.receive(decoded).has_value() && + secret_decoder.send(std::span{characters}.subspan(5, 5)).has_value() && + secret_decoder.receive(std::span{decoded}.subspan(3)).has_value() && + secret_decoder.flush().has_value(); + auto moved_decoder{std::move(secret_decoder)}; + moved_decoder.reset(); + auto secret_encoder = codecs::encoder(formats::base64, codecs::secret_operation); + streamed = streamed && secret_encoder.send(bytes).has_value() && + secret_encoder.receive(std::span{characters}.first(1)).has_value(); + auto moved_secret{std::move(secret_encoder)}; + moved_secret.reset(); + verdict = streamed && characters[0] == 'A' && characters[1] == 'S'; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("each and buffered in place over encoder(base64)", [&] { + auto each = codecs::each(codecs::encoder(formats::base64), codecs::capacity<4>); + bool streamed = each.send(bytes).has_value() && + each.receive(std::span{characters}.first(1)).has_value() && + each.receive(std::span{characters}.subspan(1, 1)).has_value(); + auto buffered = codecs::buffered(codecs::encoder(formats::base64, codecs::secret_operation), + codecs::capacity<7>); + std::array text_buffer{}; + streamed = streamed && buffered.send(bytes).has_value() && buffered.flush().has_value() && + buffered.receive(text_buffer).has_value(); + auto moved_buffered{std::move(buffered)}; + moved_buffered.reset(); + verdict = streamed && text_buffer[0] == 'A' && text_buffer[1] == 'S'; + }); + BOOST_TEST(verdict); +} + +/** + base32's and base32hex's buffer forms, fixed results, typed decodes into fixed types and secret + fixed results allocate nothing, in the window of each. +*/ +void check_base32_one_shot_forms() { + namespace formats = codecs::formats; + std::array const digest = test::digest_bytes(); + webcpp::secure::secret<32> const key; + std::array text{}; + std::array decoded{}; + auto const fixed_text = codecs::encode(formats::base32, digest); // built before the windows + auto const hex_text = codecs::encode(formats::base32hex, digest); + std::size_t volatile sink = 0; + bool volatile verdict = false; + test::expect_no_allocation("base32's buffer forms and sizes", [&] { + sink = codecs::encoded_size(formats::base32, digest); + sink = codecs::max_decoded_size(formats::base32, fixed_text.value().view()); + auto const written = codecs::encode(formats::base32, digest, text); + auto const back = codecs::decode(formats::base32, + std::string_view{text.data(), written.value()}, decoded); + auto const hex_written = codecs::encode(formats::base32hex, digest, text); + auto const hex_back = codecs::decode( + formats::base32hex, std::string_view{text.data(), hex_written.value()}, decoded); + verdict = written.has_value() && written.value() == 56 && back.has_value() && + back.value() == 32 && hex_written.has_value() && hex_back.has_value() && + std::ranges::equal(std::span{decoded}.first(32), digest); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("base32's refused buffer forms", [&] { + verdict = + codecs::encode(formats::base32, digest, std::span{text}.first(55)).has_value() || + codecs::decode(formats::base32, std::string_view{"MZXW6YQ"}, decoded).has_value() || + codecs::decode(formats::base32, std::string_view{"MZ======"}, decoded).has_value() || + codecs::decode(formats::base32, std::string_view{"MZXW6YT\n"}, decoded).has_value() || + codecs::decode(formats::base32, std::string_view{"MZXW6YTB"}, + std::span{decoded}.first(1)) + .has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("base32's fixed results and tokens", [&] { + auto const encoded = codecs::encode(formats::base32, digest); + auto const back = codecs::decode(formats::base32, encoded.value()); + auto const into_array = codecs::decode>( + formats::base32, fixed_text.value().view()); + auto const into_bytes = + codecs::decode>(formats::base32hex, hex_text.value().view()); + auto const into_key = codecs::decode(formats::base32, "AEBA===="); + auto const through_fixed = + codecs::encode(formats::base32, digest, codecs::tokens::fixed<56>{}); + auto const fixed_back = + codecs::decode(formats::base32, fixed_text.value(), codecs::tokens::fixed<35>{}); + verdict = encoded.has_value() && back.has_value() && into_array.has_value() && + into_bytes.has_value() && into_key.has_value() && through_fixed.has_value() && + fixed_back.has_value() && back.value().size() == 32; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("base32's secret fixed results", [&] { + auto const from_key = codecs::encode(formats::base32, key); + auto const through_token = codecs::encode(formats::base32, digest, codecs::tokens::secret); + auto const into_secret = + codecs::decode>(formats::base32, fixed_text.value().view()); + auto const into_secret_bytes = + codecs::decode>(formats::base32, fixed_text.value().view()); + auto const secret_back = + codecs::decode(formats::base32, fixed_text.value(), codecs::tokens::secret); + std::array secret_text{}; + auto const secret_buffer = codecs::encode(formats::base32, key, std::span{secret_text}); + verdict = from_key.has_value() && through_token.has_value() && into_secret.has_value() && + into_secret_bytes.has_value() && secret_back.has_value() && + secret_buffer.has_value() && codecs::encoded_size(formats::base32, key) == 56; + }); + BOOST_TEST(verdict); + static_cast(sink); +} + +/** + base32's streams of 1 MiB allocate nothing (the spec's "Streams allocate nothing", on base32): + random bytes in random chunks through encoder(base32) piped into decoder(base32) and through + base32hex's, drained into a fixed span and compared as it goes; the text of the bytes decoded by + a secret decoder likewise. +*/ +void check_base32_mebibyte() { + namespace formats = codecs::formats; + std::vector input(std::size_t{1024} * 1024); + // A fixed seed, so that every lane and every run sees the same bytes. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) + std::mt19937_64 generator{20261126}; + std::ranges::generate(input, [&] { return static_cast(generator()); }); + std::string const text = codecs::encode(formats::base32, input).value(); + bool volatile verdict = false; + test::expect_no_allocation("1 MiB through pipe(encoder(base32), decoder(base32))", [&] { + auto piped = + codecs::pipe(codecs::encoder(formats::base32), codecs::decoder(formats::base32)); + verdict = + test::stream_in_random_chunks<777>(piped, std::span{input}, + std::span{input}, generator); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("1 MiB through pipe(encoder(base32hex), decoder(base32hex))", [&] { + auto piped = + codecs::pipe(codecs::encoder(formats::base32hex), codecs::decoder(formats::base32hex)); + verdict = + test::stream_in_random_chunks<777>(piped, std::span{input}, + std::span{input}, generator); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("1 MiB of base32 text through a secret decoder(base32)", [&] { + auto decoder = codecs::decoder(formats::base32, codecs::secret_operation); + verdict = test::stream_in_random_chunks<555>( + decoder, test::characters_of(text), std::span{input}, generator); + }); + BOOST_TEST(verdict); +} + +/** + base32's small streams allocate nothing once made: encoder(base32hex), a secret + decoder(base32hex) and a secret encoder(base32), streamed, moved and reset; and each and buffered + in place over encoder(base32). +*/ +void check_base32_streams() { + namespace formats = codecs::formats; + bool volatile verdict = false; + std::array const bytes{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd}; + std::array characters{}; + std::array decoded{}; + test::expect_no_allocation( + "encoder(base32hex), a secret decoder(base32hex) and a secret encoder(base32)", [&] { + auto encoder = codecs::encoder(formats::base32hex); + bool streamed = encoder.send(bytes).has_value() && + encoder.receive(std::span{characters}.first(3)).has_value() && + encoder.receive(std::span{characters}.subspan(3, 5)).has_value() && + encoder.flush().has_value() && + encoder.receive(std::span{characters}.subspan(8)).has_value(); + auto moved{std::move(encoder)}; + moved.reset(); + auto secret_decoder = codecs::decoder(formats::base32hex, codecs::secret_operation); + streamed = + streamed && + secret_decoder.send(std::span{characters}.first(5)).has_value() && + secret_decoder.receive(decoded).has_value() && + secret_decoder.send(std::span{characters}.subspan(5, 11)).has_value() && + secret_decoder.receive(std::span{decoded}.subspan(3)).has_value() && + secret_decoder.flush().has_value(); + auto moved_decoder{std::move(secret_decoder)}; + moved_decoder.reset(); + auto secret_encoder = codecs::encoder(formats::base32, codecs::secret_operation); + streamed = streamed && secret_encoder.send(bytes).has_value() && + secret_encoder.receive(std::span{characters}.first(1)).has_value(); + auto moved_secret{std::move(secret_encoder)}; + moved_secret.reset(); + verdict = streamed && characters[0] == 'A' && characters[1] == '4'; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("each and buffered in place over encoder(base32)", [&] { + auto each = codecs::each(codecs::encoder(formats::base32), codecs::capacity<8>); + bool streamed = each.send(bytes).has_value() && + each.receive(std::span{characters}.first(1)).has_value() && + each.receive(std::span{characters}.subspan(1, 1)).has_value(); + auto buffered = codecs::buffered(codecs::encoder(formats::base32, codecs::secret_operation), + codecs::capacity<7>); + std::array text_buffer{}; + streamed = streamed && buffered.send(bytes).has_value() && buffered.flush().has_value() && + buffered.receive(text_buffer).has_value(); + auto moved_buffered{std::move(buffered)}; + moved_buffered.reset(); + verdict = streamed && text_buffer[0] == 'A' && text_buffer[1] == 'E'; + }); + BOOST_TEST(verdict); +} + +/** + bech32's buffer forms, fixed results, typed decodes into fixed types and into its parts, and + secret fixed results allocate nothing, in the window of each: every form of bech32 is in place + (owner decision 27). +*/ +void check_bech32_one_shot_forms() { + namespace formats = codecs::formats; + std::array const digest = test::digest_bytes(); + webcpp::secure::secret<32> const key; + std::array text{}; + std::array decoded{}; + std::array words{}; + std::ranges::transform(std::span{digest}.first(20), words.begin(), + [](std::uint8_t byte) { return static_cast(byte & 31U); }); + auto const npub = formats::bech32("npub"); + auto const fixed_text = codecs::encode(npub, digest); // built before the windows + std::size_t volatile sink = 0; + bool volatile verdict = false; + test::expect_no_allocation("bech32's buffer forms and sizes", [&] { + sink = codecs::encoded_size(npub, digest); + sink = codecs::max_decoded_size(formats::bech32, fixed_text.value().view()); + auto const written = codecs::encode(npub, digest, text); + auto const back = codecs::decode(formats::bech32, + std::string_view{text.data(), written.value()}, decoded); + auto const words_written = codecs::encode(npub.words(), words, text); + auto const words_back = codecs::decode( + formats::bech32.words(), std::string_view{text.data(), words_written.value()}, decoded); + verdict = written.has_value() && written.value() == 63 && back.has_value() && + back.value() == 32 && words_written.has_value() && words_back.has_value() && + std::ranges::equal(std::span{decoded}.first(words.size()), words); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("bech32's refused buffer forms", [&] { + verdict = + codecs::encode(npub, digest, std::span{text}.first(62)).has_value() || + codecs::encode(formats::bech32, digest, text).has_value() || + codecs::decode(formats::bech32, std::string_view{"a12uel5m"}, decoded).has_value() || + codecs::decode(formats::bech32, std::string_view{"x1b4n0q5v"}, decoded).has_value() || + codecs::decode(formats::bech32, fixed_text.value().view(), std::span{decoded}.first(1)) + .has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("bech32's fixed results, tokens and parts", [&] { + auto const encoded = codecs::encode(npub, digest); + auto const back = codecs::decode(npub, encoded.value()); + auto const into_array = + codecs::decode>(npub, fixed_text.value().view()); + auto const into_bytes = + codecs::decode>(formats::bech32, fixed_text.value().view()); + auto const parts = codecs::decode(formats::bech32, + fixed_text.value().view()); + auto const through_fixed = codecs::encode(npub, digest, codecs::tokens::fixed<90>{}); + auto const fixed_back = + codecs::decode(npub, fixed_text.value(), codecs::tokens::fixed<51>{}); + verdict = encoded.has_value() && back.has_value() && into_array.has_value() && + into_bytes.has_value() && parts.has_value() && + parts->human_readable_part.view() == "npub" && through_fixed.has_value() && + fixed_back.has_value() && back.value().size() == 32; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("bech32's secret fixed results", [&] { + auto const from_key = codecs::encode(npub, key); + auto const through_token = codecs::encode(npub, digest, codecs::tokens::secret); + auto const into_secret = + codecs::decode>(npub, fixed_text.value().view()); + auto const into_secret_bytes = + codecs::decode>(npub, fixed_text.value().view()); + auto const secret_back = codecs::decode(npub, fixed_text.value(), codecs::tokens::secret); + std::array secret_text{}; + auto const secret_buffer = codecs::encode(npub, key, std::span{secret_text}); + verdict = from_key.has_value() && through_token.has_value() && into_secret.has_value() && + into_secret_bytes.has_value() && secret_back.has_value() && + secret_buffer.has_value() && codecs::encoded_size(npub, key) == 63; + }); + BOOST_TEST(verdict); + static_cast(sink); +} + +/** + bech32's streams over 1 MiB of random bytes allocate nothing (the spec's "Streams allocate + nothing", on bech32): a text holds at most 50 bytes under "bc", so that the bytes are cut into + texts of 50, each encoded by encoder(bech32("bc")) in random chunks, its text decoded by + decoder(bech32("bc")) and by a secret decoder in random chunks, the streams reset between texts, + drained into fixed spans and compared as they go. +*/ +void check_bech32_mebibyte() { + namespace formats = codecs::formats; + constexpr std::size_t text_bytes = 50; + std::vector input(std::size_t{1024} * 1024); + // A fixed seed, so that every lane and every run sees the same bytes. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) + std::mt19937_64 generator{20261127}; + std::ranges::generate(input, [&] { return static_cast(generator()); }); + auto const format = formats::bech32("bc"); + std::vector texts; // made before the window + for (std::size_t offset = 0; offset < input.size(); offset += text_bytes) { + std::size_t const size = std::min(text_bytes, input.size() - offset); + texts.push_back(codecs::encode(format, std::span{input}.subspan(offset, size)).value()); + } + bool volatile verdict = false; + test::expect_no_allocation("1 MiB of bech32 texts through its encoder and decoders", [&] { + auto encoder = codecs::encoder(format); + auto decoder = codecs::decoder(format); + auto secret_decoder = codecs::decoder(format, codecs::secret_operation); + bool streamed = true; + for (std::size_t index = 0; index < texts.size() && streamed; ++index) { + std::span const bytes = std::span{input}.subspan( + index * text_bytes, std::min(text_bytes, input.size() - (index * text_bytes))); + std::span const characters{texts[index].data(), texts[index].size()}; + encoder.reset(); + decoder.reset(); + secret_decoder.reset(); + streamed = + test::stream_in_random_chunks<17>(encoder, bytes, characters, generator) && + test::stream_in_random_chunks<13>(decoder, characters, bytes, generator) && + test::stream_in_random_chunks<7>(secret_decoder, characters, bytes, generator); + } + verdict = streamed; + }); + BOOST_TEST(verdict); +} + +/** + base58's buffer forms, fixed results, typed decodes into fixed types and secret fixed results + allocate nothing, public and secret, its scratch in place (owner decision 25), in the window of + each, as do its refusals past the bound. +*/ +void check_base58_one_shot_forms() { + namespace formats = codecs::formats; + std::array const digest = test::digest_bytes(); + webcpp::secure::secret<32> key; + std::ranges::copy(digest, key.writable().begin()); + std::array const past_bound{}; + std::array text{}; + std::array decoded{}; + auto const fixed_text = codecs::encode(formats::base58, digest); // built before the windows + std::string_view const fixed_view = fixed_text.value().view(); + std::size_t volatile sink = 0; + bool volatile verdict = false; + test::expect_no_allocation("base58's buffer forms and sizes", [&] { + sink = codecs::encoded_size(formats::base58, digest); + sink = codecs::max_decoded_size(formats::base58, fixed_view); + auto const written = codecs::encode(formats::base58, digest, text); + auto const back = codecs::decode(formats::base58, + std::string_view{text.data(), written.value()}, decoded); + verdict = written.has_value() && written.value() == fixed_view.size() && back.has_value() && + back.value() == 32 && std::ranges::equal(std::span{decoded}.first(32), digest); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("base58's refused buffer forms", [&] { + verdict = + codecs::encode(formats::base58, digest, std::span{text}.first(10)).has_value() || + codecs::encode(formats::base58, past_bound, text).has_value() || + codecs::decode(formats::base58, std::string_view{"2g0"}, decoded).has_value() || + codecs::decode(formats::base58, fixed_view, std::span{decoded}.first(1)).has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("base58's fixed results and tokens", [&] { + auto const encoded = codecs::encode(formats::base58, digest); + auto const back = codecs::decode(formats::base58, encoded.value()); + auto const into_array = + codecs::decode>(formats::base58, fixed_view); + auto const into_bytes = codecs::decode>(formats::base58, fixed_view); + auto const into_key = codecs::decode(formats::base58, "2gb"); + auto const through_fixed = + codecs::encode(formats::base58, digest, codecs::tokens::fixed<44>{}); + auto const fixed_back = + codecs::decode(formats::base58, fixed_text.value(), codecs::tokens::fixed<44>{}); + verdict = encoded.has_value() && back.has_value() && into_array.has_value() && + into_bytes.has_value() && into_key.has_value() && through_fixed.has_value() && + fixed_back.has_value() && back.value().size() == 32; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("base58's secret fixed results", [&] { + auto const from_key = codecs::encode(formats::base58, key); + auto const through_token = codecs::encode(formats::base58, digest, codecs::tokens::secret); + auto const into_secret = + codecs::decode>(formats::base58, fixed_view); + auto const into_secret_bytes = + codecs::decode>(formats::base58, fixed_view); + auto const secret_back = + codecs::decode(formats::base58, fixed_text.value(), codecs::tokens::secret); + std::array secret_text{}; + auto const secret_buffer = codecs::encode(formats::base58, key, std::span{secret_text}); + verdict = from_key.has_value() && through_token.has_value() && into_secret.has_value() && + into_secret_bytes.has_value() && secret_back.has_value() && + secret_buffer.has_value() && + codecs::encoded_size(formats::base58, key) == fixed_view.size(); + }); + BOOST_TEST(verdict); + static_cast(sink); +} + +/** + base58 through buffered in place allocates nothing: 64 KiB of random bytes, cut into inputs of + 100 bytes, each sent in random chunks to buffered(encoder(base58), capacity<100>) and its text to + buffered(decoder(base58), capacity<137>), public and secret, the streams reset between inputs, + drained into fixed spans and compared as they go. +*/ +void check_base58_buffered() { + namespace formats = codecs::formats; + constexpr std::size_t piece_bytes = 100; + std::vector input(std::size_t{64} * 1024); + // A fixed seed, so that every lane and every run sees the same bytes. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) + std::mt19937_64 generator{20261127}; + std::ranges::generate(input, [&] { return static_cast(generator()); }); + std::vector texts; // made before the window + for (std::size_t offset = 0; offset < input.size(); offset += piece_bytes) { + std::size_t const size = std::min(piece_bytes, input.size() - offset); + texts.push_back( + codecs::encode(formats::base58, std::span{input}.subspan(offset, size)).value()); + } + bool volatile verdict = false; + test::expect_no_allocation("64 KiB of base58 texts through buffered in place", [&] { + auto encoder = codecs::buffered(codecs::encoder(formats::base58), codecs::capacity<100>); + auto decoder = codecs::buffered(codecs::decoder(formats::base58), codecs::capacity<137>); + auto secret_encoder = codecs::buffered( + codecs::encoder(formats::base58, codecs::secret_operation), codecs::capacity<100>); + auto secret_decoder = codecs::buffered( + codecs::decoder(formats::base58, codecs::secret_operation), codecs::capacity<137>); + bool streamed = true; + for (std::size_t index = 0; index < texts.size() && streamed; ++index) { + std::span const bytes = std::span{input}.subspan( + index * piece_bytes, std::min(piece_bytes, input.size() - (index * piece_bytes))); + std::span const characters{texts[index].data(), texts[index].size()}; + encoder.reset(); + decoder.reset(); + secret_encoder.reset(); + secret_decoder.reset(); + streamed = + test::stream_in_random_chunks<17>(encoder, bytes, characters, generator) && + test::stream_in_random_chunks<13>(decoder, characters, bytes, generator) && + test::stream_in_random_chunks<11>(secret_encoder, bytes, characters, generator) && + test::stream_in_random_chunks<7>(secret_decoder, characters, bytes, generator); + } + verdict = streamed; + }); + BOOST_TEST(verdict); +} + +/** + The armor's buffer forms, fixed results, typed decodes into fixed types and secret fixed results + allocate nothing, in the window of each, its refusals included. +*/ +void check_armor_one_shot_forms() { + namespace formats = codecs::formats; + std::array const digest = test::digest_bytes(); + webcpp::secure::secret<32> const key; + auto const label = formats::armor("PUBLIC KEY"); + auto const fixed_text = codecs::encode(label, digest); // built before the windows + std::array text{}; + std::array decoded{}; + std::size_t volatile sink = 0; + bool volatile verdict = false; + test::expect_no_allocation("the armor's buffer forms and sizes", [&] { + sink = codecs::encoded_size(label, digest); + sink = codecs::max_decoded_size(formats::armor, fixed_text.value().view()); + auto const written = codecs::encode(label, digest, text); + auto const back = + codecs::decode(formats::armor, std::string_view{text.data(), written.value()}, decoded); + verdict = written.has_value() && written.value() == 97 && back.has_value() && + back.value() == 32 && std::ranges::equal(std::span{decoded}.first(32), digest); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("the armor's refused buffer forms", [&] { + verdict = + codecs::encode(label, digest, std::span{text}.first(96)).has_value() || + codecs::encode(formats::armor, digest, text).has_value() || + codecs::decode(label, std::string_view{"-----BEGIN A-----\n"}, decoded).has_value() || + codecs::decode(formats::armor("A"), fixed_text.value().view(), decoded).has_value() || + codecs::decode(label, fixed_text.value().view(), std::span{decoded}.first(31)) + .has_value(); + }); + BOOST_TEST(!verdict); + test::expect_no_allocation("the armor's fixed results and tokens", [&] { + auto const encoded = codecs::encode(label, digest); + auto const back = codecs::decode(formats::armor, encoded.value()); + auto const into_array = + codecs::decode>(label, fixed_text.value().view()); + auto const through_fixed = codecs::encode(label, digest, codecs::tokens::fixed<97>{}); + verdict = encoded.has_value() && back.has_value() && into_array.has_value() && + through_fixed.has_value() && back.value().size() == 32; + }); + BOOST_TEST(verdict); + test::expect_no_allocation("the armor's secret fixed results", [&] { + auto const from_key = codecs::encode(label, key); + auto const into_secret = + codecs::decode>(formats::armor, fixed_text.value().view()); + auto const secret_back = codecs::decode(label, fixed_text.value(), codecs::tokens::secret); + verdict = from_key.has_value() && into_secret.has_value() && secret_back.has_value(); + }); + BOOST_TEST(verdict); + static_cast(sink); +} + +/** + The armor's streams of 1 MiB allocate nothing (the spec's "Streams allocate nothing", on the + armor): random bytes in random chunks through encoder(armor("PUBLIC KEY")) piped into + decoder(armor), drained into a fixed span and compared as it goes; the armor of the bytes decoded + by a secret decoder likewise, and encoded by a secret encoder. +*/ +void check_armor_mebibyte() { + namespace formats = codecs::formats; + std::vector input(std::size_t{1024} * 1024); + // A fixed seed, so that every lane and every run sees the same bytes. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) + std::mt19937_64 generator{20261129}; + std::ranges::generate(input, [&] { return static_cast(generator()); }); + auto const label = formats::armor("PUBLIC KEY"); + std::string const text = codecs::encode(label, input).value(); + bool volatile verdict = false; + test::expect_no_allocation("1 MiB through pipe(encoder(armor), decoder(armor))", [&] { + auto piped = codecs::pipe(codecs::encoder(label), codecs::decoder(formats::armor)); + verdict = + test::stream_in_random_chunks<777>(piped, std::span{input}, + std::span{input}, generator); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("1 MiB of armor through a secret decoder(armor)", [&] { + auto decoder = codecs::decoder(formats::armor, codecs::secret_operation); + verdict = test::stream_in_random_chunks<555>( + decoder, test::characters_of(text), std::span{input}, generator); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("1 MiB through a secret encoder(armor)", [&] { + auto encoder = codecs::encoder(label, codecs::secret_operation); + verdict = test::stream_in_random_chunks<333>(encoder, std::span{input}, + test::characters_of(text), generator); + }); + BOOST_TEST(verdict); +} + +} // namespace + +int main() { + std::printf("c_allocations_counted=%d\n", test::c_allocations_counted ? 1 : 0); + test::control_counts_every_form(); + check_buffer_forms(); + check_fixed_results(); + check_fixed_tokens(); + check_secret_results(); + check_secret_operations(); + check_assign_to_scratch(); + check_over(); + check_transformers(); + check_pipe_and_drain(); + check_format_transformers(); + check_each_and_buffered(); + check_secret_streams(); + check_pipe_of_packets_into_each(); + check_saturating_refusals(); + check_hex_one_shot_forms(); + check_hex_streams(); + check_base64_one_shot_forms(); + check_base64_mebibyte(); + check_base64_streams(); + check_base32_one_shot_forms(); + check_base32_mebibyte(); + check_base32_streams(); + check_bech32_one_shot_forms(); + check_bech32_mebibyte(); + check_base58_one_shot_forms(); + check_base58_buffered(); + check_armor_one_shot_forms(); + check_armor_mebibyte(); + return boost::report_errors(); +} diff --git a/test/allocator_test.cpp b/test/allocator_test.cpp new file mode 100644 index 0000000..e79ca68 --- /dev/null +++ b/test/allocator_test.cpp @@ -0,0 +1,632 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The allocator rows of codecs (owner decision 23): every allocation of a form that takes an +// allocator, or whose token holds a container with one, goes through that allocator, and the +// global operator new, counted by support/counting.hpp, sees none. A recording memory resource is +// the arena; the allocators of the tests' own are checked against the standard's rules, too. A +// standard container's own block, which the MSVC STL's debug containers allocate through their +// allocator, is no allocation of an operation: the arena leaves it out (support/bookkeeping.hpp), +// as document's and trystero's tests do, and it reaches the global operator new never. The secret +// heap types over the arena, and tokens::secret with the arena's allocator, give it back every +// buffer wiped. each and buffered with the arena's allocator take their storage from it. base58 +// takes no allocator, its scratch in place (owner decision 25): buffered over its encoder takes its +// storage from the arena, its decode into a pmr token allocates the token's buffer alone, and over +// with base58 takes its intermediate from its allocator. Later tasks add their rows. + +#include "support/counting.hpp" + +#include "support/allocators.hpp" +#include "support/arena.hpp" +#include "support/be16.hpp" +#include "support/letters.hpp" +#include "support/toy_media.hpp" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +/** The allocations of the whole program so far: operator new's and the C library's. */ +std::size_t global_allocations() { + return test::counted_new.load() + test::counted_c.load(); +} + +/** Runs `body`, and checks that the global operator new saw nothing of it. */ +template +void expect_no_global_allocation(char const* what, Body body) { + std::size_t const before = global_allocations(); + body(); + std::size_t const after = global_allocations(); + if (after != before) { + std::printf("allocated globally: %s\n", what); + } + BOOST_TEST_EQ(after - before, 0U); +} + +/** 32 bytes, and the text the format letters gives for them. */ +std::array bytes_32() { + std::array held_bytes{}; + for (std::size_t index = 0; index < held_bytes.size(); ++index) { + held_bytes[index] = static_cast((index * 37U) + 1U); + } + return held_bytes; +} + +void return_string_over_an_arena() { + test::recording_resource arena; + auto const input = bytes_32(); + std::string const expected = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::pmr::polymorphic_allocator const allocator{&arena}; + expect_no_global_allocation("return_string over an arena, encode", [&] { + auto const encoded = codecs::encode(test::letters, input, tokens::return_string(allocator)); + static_assert(std::is_same_v const>); + BOOST_TEST(encoded.has_value()); + BOOST_TEST(std::string_view{encoded.value()} == expected); + BOOST_TEST(arena.owns(encoded.value().data())); + auto const& encoded_string = encoded.value(); + BOOST_TEST(encoded_string.get_allocator().resource() == &arena); + }); + BOOST_TEST_EQ(arena.allocation_count(), 1U); + BOOST_TEST_GE(arena.allocation(0).size, expected.size() + 1); + // The decode gives the bytes as a string of the same kind. + std::size_t const before = arena.allocation_count(); + expect_no_global_allocation("return_string over an arena, decode", [&] { + auto const decoded = + codecs::decode(test::letters, expected, tokens::return_string(allocator)); + static_assert(std::is_same_v const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), input.size()); + BOOST_TEST(arena.owns(decoded.value().data())); + }); + BOOST_TEST_EQ(arena.allocation_count() - before, 1U); +} + +void append_to_a_pmr_string() { + test::recording_resource arena; + auto const input = bytes_32(); + std::string const expected = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::pmr::string target{&arena}; + target = "kept"; + BOOST_TEST_EQ(arena.allocation_count(), 0U); // four characters stay in the string + expect_no_global_allocation("append_to a pmr string", [&] { + auto const encoded = codecs::encode(test::letters, input, tokens::append_to(target)); + static_assert(std::is_same_v const>); + BOOST_TEST(encoded.has_value()); + BOOST_TEST_EQ(&encoded.value(), &target); + }); + BOOST_TEST(std::string_view{target} == "kept" + expected); + BOOST_TEST(arena.allocation_count() >= 1U); + BOOST_TEST(arena.owns(target.data())); +} + +void assign_to_a_pmr_vector() { + test::recording_resource arena; + auto const input = bytes_32(); + std::string const text_value = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::pmr::vector target{&arena}; + expect_no_global_allocation("assign_to a pmr vector", [&] { + auto const decoded = codecs::decode(test::letters, text_value, tokens::assign_to(target)); + static_assert(std::is_same_v&> const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(&decoded.value(), &target); + }); + BOOST_TEST_EQ(target.size(), input.size()); + BOOST_TEST(std::equal(input.begin(), input.end(), target.begin())); + // The scratch (a text of a size known at run time), then the vector's own buffer, which it + // lacked: the scratch is copied into the vector and given back. + BOOST_TEST_EQ(arena.allocation_count(), 2U); + BOOST_TEST(arena.owns(target.data())); + // A vector that holds the result keeps its buffer: the scratch alone is allocated. + std::uint8_t const* const kept_buffer = target.data(); + std::size_t const before_kept = arena.allocation_count(); + BOOST_TEST(codecs::decode(test::letters, text_value, tokens::assign_to(target)).has_value()); + BOOST_TEST_EQ(arena.allocation_count(), before_kept + 1); + BOOST_TEST(target.data() == kept_buffer); + // The same for append_to. + std::pmr::vector appended{&arena}; + std::size_t const before = arena.allocation_count(); + expect_no_global_allocation("append_to a pmr vector", [&] { + BOOST_TEST( + codecs::decode(test::letters, text_value, tokens::append_to(appended)).has_value()); + }); + BOOST_TEST_EQ(appended.size(), input.size()); + BOOST_TEST(arena.allocation_count() > before); +} + +void a_typed_decode_with_an_allocator() { + test::recording_resource arena; + auto const input = bytes_32(); + std::string const text_value = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::pmr::polymorphic_allocator const allocator{&arena}; + expect_no_global_allocation("a typed decode into a pmr vector", [&] { + auto const decoded = + codecs::decode>(test::letters, text_value, allocator); + static_assert(std::is_same_v> const>); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), input.size()); + auto const& decoded_vector = decoded.value(); + BOOST_TEST(decoded_vector.get_allocator().resource() == &arena); + BOOST_TEST(arena.owns(decoded.value().data())); + }); + BOOST_TEST_EQ(arena.allocation_count(), 1U); + // A string takes an allocator too, and a heap type of std::allocator takes its own. + std::pmr::polymorphic_allocator const char_allocator{&arena}; + auto const as_string = + codecs::decode(test::letters, text_value, char_allocator); + BOOST_TEST(as_string.has_value()); + BOOST_TEST_EQ(as_string.value().size(), input.size()); + BOOST_TEST(arena.owns(as_string.value().data())); + auto const plain = codecs::decode>(test::letters, text_value, + std::allocator{}); + BOOST_TEST(plain.has_value()); + BOOST_TEST_EQ(plain.value().size(), input.size()); + // The errors reach the caller, and the arena was given nothing. + std::size_t const before = arena.allocation_count(); + auto const refused = codecs::decode>( + test::letters, std::string_view{"abq"}, allocator); + BOOST_TEST(refused.error() == codecs::error::invalid_character); + BOOST_TEST_EQ(arena.allocation_count(), before); +} + +/** + The spec's "An arena receives every allocation", on base64's typed decode: a text decoded with + `codecs::decode>(formats::base64, text, allocator)` lands in the + arena, which records its one allocation, and the global operator new counts none; base64url + likewise, and an error gives the arena nothing. +*/ +void base64_typed_decode_into_an_arena() { + namespace formats = webcpp::codecs::formats; + test::recording_resource arena; + auto const input = bytes_32(); + std::string const text_value = + codecs::encode(formats::base64, input, tokens::return_string).value(); + std::string const url_text = + codecs::encode(formats::base64url, input, tokens::return_string).value(); + std::pmr::polymorphic_allocator const allocator{&arena}; + std::pmr::polymorphic_allocator const char_allocator{&arena}; + std::optional>> decoded; + std::optional>> url_decoded; + std::optional> encoded; + expect_no_global_allocation("base64's typed decode into a pmr vector", [&] { + decoded.emplace( + codecs::decode>(formats::base64, text_value, allocator)); + }); + BOOST_TEST_EQ(arena.allocation_count(), 1U); + expect_no_global_allocation("base64url's typed decode into a pmr vector", [&] { + url_decoded.emplace(codecs::decode>(formats::base64url, + url_text, allocator)); + }); + BOOST_TEST_EQ(arena.allocation_count(), 2U); + expect_no_global_allocation("base64's return_string over an arena", [&] { + encoded.emplace( + codecs::encode(formats::base64, input, tokens::return_string(char_allocator))); + }); + BOOST_TEST_EQ(arena.allocation_count(), 3U); + BOOST_TEST(decoded->has_value() && std::ranges::equal(decoded->value(), input)); + BOOST_TEST(decoded->has_value() && arena.owns(decoded->value().data())); + BOOST_TEST(decoded->has_value() && decoded->value().get_allocator().resource() == &arena); + BOOST_TEST(url_decoded->has_value() && std::ranges::equal(url_decoded->value(), input)); + BOOST_TEST(url_decoded->has_value() && arena.owns(url_decoded->value().data())); + BOOST_TEST(encoded->has_value() && std::string_view{encoded->value()} == text_value); + BOOST_TEST(encoded->has_value() && arena.owns(encoded->value().data())); + // An error reaches the caller and the arena is given nothing. + auto const refused = codecs::decode>( + formats::base64, std::string_view{"Zh=="}, allocator); + BOOST_TEST(refused.error() == codecs::error::invalid_padding); + BOOST_TEST_EQ(arena.allocation_count(), 3U); +} + +/** Checks that every block the arena gave out reads zero in it now. */ +void expect_every_block_zero(test::recording_resource const& arena) { + for (std::size_t index = 0; index < arena.allocation_count(); ++index) { + auto const& block = arena.allocation(index); + auto const* const first_byte = static_cast(block.pointer); + BOOST_TEST(std::all_of(first_byte, first_byte + block.size, + [](unsigned char byte_value) { return byte_value == 0; })); + } +} + +/** The secret heap types over the arena (Task 5): every buffer, the old ones of a growth too, comes + from the arena and goes back to it wiped, and the global operator new sees none. */ +void secret_types_over_an_arena() { + test::recording_resource arena; + auto const input = bytes_32(); + expect_no_global_allocation("pmr::secret_byte_vector", [&] { + codecs::pmr::secret_byte_vector secret{&arena}; + secret.append(input); + BOOST_TEST_EQ(arena.allocation_count(), 1U); + BOOST_TEST(arena.owns(secret.data())); + secret.append(input); // past the capacity: a second buffer of the arena's + BOOST_TEST_EQ(arena.allocation_count(), 2U); + BOOST_TEST(arena.owns(secret.data())); + BOOST_TEST_EQ(arena.deallocation_count(), 1U); + BOOST_TEST_EQ(secret.size(), 2 * input.size()); + // A clone takes the allocator std::allocator_traits gives a copy: for a + // polymorphic_allocator, the default memory resource, as a std::pmr container's copy. + std::array copy_storage{}; + std::pmr::monotonic_buffer_resource copies{copy_storage.data(), copy_storage.size(), + std::pmr::null_memory_resource()}; + std::pmr::memory_resource* const previous = std::pmr::set_default_resource(&copies); + auto const copy = secret.clone(); + std::pmr::set_default_resource(previous); + BOOST_TEST(copy.get_allocator().resource() == &copies); + BOOST_TEST(std::ranges::equal(copy.view(), secret.view())); + }); + BOOST_TEST_EQ(arena.allocation_count(), 2U); + BOOST_TEST_EQ(arena.deallocation_count(), 2U); + // A monotonic arena never reuses what it is given back: each buffer still reads zero in it. + expect_every_block_zero(arena); + std::string const characters(40, 's'); + expect_no_global_allocation("pmr::secret_string", [&] { + codecs::pmr::secret_string secret{&arena}; + secret.append(characters); + BOOST_TEST(arena.owns(secret.data())); + BOOST_TEST(secret.view() == characters); + BOOST_TEST(secret.get_allocator().resource() == &arena); + // A move assignment between two strings of the same arena takes the buffer. + codecs::pmr::secret_string target{&arena}; + target = std::move(secret); + BOOST_TEST(target.view() == characters); + }); + BOOST_TEST_EQ(arena.allocation_count(), 3U); + BOOST_TEST_EQ(arena.deallocation_count(), 3U); + // The string's buffer, the third block, reads zero too. + expect_every_block_zero(arena); + // With no allocator, the default memory resource, as std::pmr's containers. + codecs::pmr::secret_byte_vector const defaulted; + BOOST_TEST(defaulted.get_allocator().resource() == std::pmr::get_default_resource()); +} + +/** tokens::secret with an allocator (Task 6): a secret result on the arena, both ways, its buffers + given back wiped, and a typed decode into a pmr secret type likewise. */ +void the_secret_token_over_an_arena() { + test::recording_resource arena; + std::vector const input(40, 0x5a); // a size known at run time: the heap + std::string const text_value = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::pmr::polymorphic_allocator const allocator{&arena}; + expect_no_global_allocation("tokens::secret over an arena, encode", [&] { + auto const encoded = codecs::encode(test::letters, input, tokens::secret(allocator)); + static_assert( + std::is_same_v const>); + BOOST_TEST(encoded.value().view() == text_value); + BOOST_TEST(arena.owns(encoded.value().data())); + auto const& encoded_secret = encoded.value(); + BOOST_TEST(encoded_secret.get_allocator().resource() == &arena); + }); + BOOST_TEST_EQ(arena.allocation_count(), 1U); + BOOST_TEST_EQ(arena.deallocation_count(), 1U); + // The decode rebinds the allocator to the bytes. + expect_no_global_allocation("tokens::secret over an arena, decode", [&] { + auto const decoded = codecs::decode(test::letters, text_value, tokens::secret(allocator)); + static_assert(std::is_same_v const>); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + BOOST_TEST(arena.owns(decoded.value().data())); + }); + BOOST_TEST_EQ(arena.allocation_count(), 2U); + expect_no_global_allocation("a typed decode into a pmr secret", [&] { + auto const decoded = codecs::decode( + test::letters, text_value, std::pmr::polymorphic_allocator{&arena}); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + BOOST_TEST(arena.owns(decoded.value().data())); + }); + BOOST_TEST_EQ(arena.allocation_count(), 3U); + BOOST_TEST_EQ(arena.deallocation_count(), 3U); + expect_every_block_zero(arena); +} + +/** over with its own allocator (Task 7, owner decision 23): the heap intermediate of a chain on a + vector input comes from the arena, one block for each time a link runs into it (the exact size, + then the encode), and the global operator new sees none; in place, with a size known at compile + time, the allocator is not asked at all. A secret chain gives its intermediates back wiped. */ +void over_takes_its_intermediate_from_its_allocator() { + test::recording_resource arena; + std::pmr::polymorphic_allocator const allocator{&arena}; + auto const chain = codecs::over{test::letters, test::letters, allocator}; + static_assert(std::is_same_v, + codecs::over>>); + std::vector const input(40, 0x5a); + std::string const inner_text = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::string const expected = + codecs::encode(test::letters, inner_text, tokens::return_string).value(); + // The result goes to the arena too, so that the global operator new sees nothing. + std::pmr::polymorphic_allocator const char_allocator{&arena}; + expect_no_global_allocation("over over an arena, encode", [&] { + auto const encoded = codecs::encode(chain, input, tokens::return_string(char_allocator)); + BOOST_TEST(encoded.has_value()); + BOOST_TEST(std::string_view{encoded.value()} == expected); + BOOST_TEST(arena.owns(encoded.value().data())); + }); + // The exact size's intermediate, the encode's, and the string. + BOOST_TEST_EQ(arena.allocation_count(), 3U); + BOOST_TEST_GE(arena.allocation(0).size, inner_text.size()); + BOOST_TEST_GE(arena.allocation(1).size, inner_text.size()); + for (std::size_t index = 0; index < 2; ++index) { + BOOST_TEST(arena.owns(arena.allocation(index).pointer)); + } + std::size_t const before = arena.allocation_count(); + expect_no_global_allocation("over over an arena, decode", [&] { + auto const decoded = codecs::decode(chain, expected, tokens::return_string(char_allocator)); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), input.size()); + }); + // The exact size's intermediate, the decode's, and the string. + BOOST_TEST_EQ(arena.allocation_count() - before, 3U); + // With a size known at compile time, the allocator is not asked. + std::array const known{}; + std::size_t const before_known = arena.allocation_count(); + BOOST_TEST(codecs::encode(chain, known).has_value()); + BOOST_TEST_EQ(arena.allocation_count(), before_known); + // A value codec of text with no stated bound takes the arena too. + test::recording_resource value_arena; + auto const value_chain = codecs::over{ + test::letters, test::be16, std::pmr::polymorphic_allocator{&value_arena}}; + BOOST_TEST( + codecs::encode(value_chain, test::hex_number{0x1234}, + tokens::return_string(std::pmr::polymorphic_allocator{&value_arena})) + .has_value()); + // The exact size's intermediate and the encode's; the eight characters stay in the string. + BOOST_TEST_GE(value_arena.allocation_count(), 2U); +} + +/** A secret chain over an arena (Task 7): each intermediate comes from the arena and goes back to + it wiped, with the secret result on the arena too. */ +void a_secret_over_gives_its_intermediates_back_wiped() { + test::recording_resource arena; + std::pmr::polymorphic_allocator const allocator{&arena}; + auto const chain = codecs::over{test::letters, test::letters, allocator}; + std::vector const input(40, 0x5a); + std::pmr::polymorphic_allocator const char_allocator{&arena}; + expect_no_global_allocation("a secret over over an arena, encode", [&] { + auto const encoded = codecs::encode(chain, input, tokens::secret(char_allocator)); + BOOST_TEST(encoded.has_value()); + auto const& secret_text = encoded.value(); + BOOST_TEST_EQ(secret_text.view().size(), 160U); + }); + // The exact size's intermediate, the encode's, and the secret text. + BOOST_TEST_EQ(arena.allocation_count(), 3U); + BOOST_TEST_EQ(arena.deallocation_count(), 3U); + expect_every_block_zero(arena); + // The decode: the outer link's intermediates, and the secret bytes, wiped likewise. + std::string const inner_text = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::string const text_value = + codecs::encode(test::letters, inner_text, tokens::return_string).value(); + std::size_t const before = arena.allocation_count(); + expect_no_global_allocation("a secret over over an arena, decode", [&] { + auto const decoded = codecs::decode(chain, text_value, tokens::secret(char_allocator)); + static_assert(std::is_same_v const>); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + }); + BOOST_TEST_EQ(arena.allocation_count() - before, 3U); + BOOST_TEST_EQ(arena.deallocation_count(), arena.allocation_count()); + expect_every_block_zero(arena); +} + +/** Frames 0 to `Count - 1`. */ +template +std::array frames_from_zero() { + std::array frames{}; + for (std::size_t index = 0; index < Count; ++index) { + frames[index] = test::make_frame(static_cast(index)); + } + return frames; +} + +/** + Streams `frames` through `adapter`, receiving into `output` after each send and after flush, and + returns the bytes received, or 0 when a call fails; it allocates nothing of its own. +*/ +template +std::size_t frames_through(Adapter& adapter, std::span frames, + std::span output) { + std::size_t total = 0; + auto const receive_all = [&]() -> bool { + for (;;) { + auto const received = adapter.receive(output); + if (!received.has_value()) { + return false; + } + total += received->count; + if (received->flow != codecs::flow::output_pending) { + return true; + } + } + }; + std::span rest = frames; + while (!rest.empty()) { + auto const sent = adapter.send(rest.first(std::min(rest.size(), 2))); + if (!sent.has_value() || sent->count == 0 || !receive_all()) { + return 0; + } + rest = rest.subspan(sent->count); + } + if (!adapter.flush().has_value() || !receive_all()) { + return 0; + } + return total; +} + +/** + each and buffered with an allocator (Task 10): each over a frame-to-bytes transformer with no + constant bound (the spec's scenario "An arena receives every allocation") and buffered over the + bounded one take their storage from the arena, rebound to their elements, and the global + operator new sees none of it. +*/ +void each_and_buffered_over_an_arena() { + auto const frames = frames_from_zero<5>(); + std::array small_output{}; + std::array output{}; + test::recording_resource each_arena; + std::pmr::polymorphic_allocator const each_allocator{&each_arena}; + std::size_t total = 0; + expect_no_global_allocation("each(frame_to_bytes) over an arena", [&] { + auto adapter = codecs::each(test::frame_to_bytes{}, each_allocator); + total = frames_through(adapter, frames, small_output); + }); + // Frames 0 to 4 are 2, 3, 4, 2 and 3 bytes. + BOOST_TEST_EQ(total, 14U); + BOOST_TEST_GE(each_arena.allocation_count(), 1U); + for (std::size_t index = 0; + index < std::min(each_arena.allocation_count(), test::recording_resource::most_records); + ++index) { + BOOST_TEST(each_arena.owns(each_arena.allocation(index).pointer)); + } + test::recording_resource buffered_arena; + std::pmr::polymorphic_allocator const buffered_allocator{&buffered_arena}; + expect_no_global_allocation("buffered(frame_to_bytes_bounded) over an arena", [&] { + auto adapter = codecs::buffered(test::frame_to_bytes_bounded(), buffered_allocator); + total = frames_through(adapter, frames, output); + }); + BOOST_TEST_EQ(total, 14U); + // The frames and the bytes, at least one block each. + BOOST_TEST_GE(buffered_arena.allocation_count(), 2U); + for (std::size_t index = 0; index < std::min(buffered_arena.allocation_count(), + test::recording_resource::most_records); + ++index) { + BOOST_TEST(buffered_arena.owns(buffered_arena.allocation(index).pointer)); + } +} + +/** + base58 over an arena (owner decision 25, the spec's "An arena receives every allocation"): + buffered(encoder(base58)) with the arena's allocator takes its storage, the input and the text, + from it; a decode into a std::pmr::vector token allocates the token's own buffer alone, its scratch + in place, one block of the arena; over{hex, base58} with the arena's allocator takes base58's text, + its intermediate, from it; and the global operator new sees none of them. +*/ +void base58_over_an_arena() { + namespace formats = webcpp::codecs::formats; + auto const input = bytes_32(); + std::string const text_value = + codecs::encode(formats::base58, input, tokens::return_string).value(); + test::recording_resource buffered_arena; + std::pmr::polymorphic_allocator const buffered_allocator{&buffered_arena}; + std::array streamed{}; + std::size_t streamed_count = 0; + expect_no_global_allocation("buffered(encoder(base58)) over an arena", [&] { + auto adapter = codecs::buffered(codecs::encoder(formats::base58), buffered_allocator); + BOOST_TEST(adapter.send(std::span{input}).has_value()); + BOOST_TEST(adapter.flush().has_value()); + auto const received = adapter.receive(std::span{streamed}); + BOOST_TEST(received.has_value() && received->flow == codecs::flow::finished); + streamed_count = received.has_value() ? received->count : 0; + }); + BOOST_TEST(std::string_view(streamed.data(), streamed_count) == text_value); + // The input and the text, at least one block each. + BOOST_TEST_GE(buffered_arena.allocation_count(), 2U); + + test::recording_resource token_arena; + std::pmr::vector target{&token_arena}; + expect_no_global_allocation("base58's decode into a pmr vector token", [&] { + auto const decoded = codecs::decode(formats::base58, text_value, tokens::append_to(target)); + BOOST_TEST(decoded.has_value()); + }); + BOOST_TEST(std::ranges::equal(target, input)); + BOOST_TEST(token_arena.owns(target.data())); + BOOST_TEST_EQ(token_arena.allocation_count(), 1U); + BOOST_TEST_EQ(token_arena.allocation(0).size, input.size()); + + test::recording_resource chain_arena; + auto const chain = codecs::over{formats::hex, formats::base58, + std::pmr::polymorphic_allocator{&chain_arena}}; + std::vector const heap_input(input.begin(), input.end()); + std::string const expected = codecs::encode(formats::hex, text_value).value(); + std::pmr::polymorphic_allocator const char_allocator{&chain_arena}; + expect_no_global_allocation("over{hex, base58} over an arena", [&] { + auto const encoded = + codecs::encode(chain, heap_input, tokens::return_string(char_allocator)); + BOOST_TEST(encoded.has_value() && std::string_view{encoded.value()} == expected); + auto const decoded = codecs::decode(chain, expected, tokens::return_string(char_allocator)); + BOOST_TEST(decoded.has_value() && decoded.value().size() == input.size()); + }); + // The exact size's intermediate, the operation's and the string, in each direction. + BOOST_TEST_EQ(chain_arena.allocation_count(), 6U); +} + +void the_allocators_of_the_tests_own() { + // non_propagating_allocator: equal only to a copy. + test::non_propagating_allocator const first_allocator{1}; + test::non_propagating_allocator const second_allocator{2}; + BOOST_TEST(first_allocator == test::non_propagating_allocator{1}); + BOOST_TEST(!(first_allocator == second_allocator)); + static_assert( + !std::allocator_traits< + test::non_propagating_allocator>::propagate_on_container_move_assignment::value); + // wipe_checking_allocator: a block is counted, and a zero one is told from a written one. + test::wipe_checking_allocator checking; + std::uint8_t* const zeros = checking.allocate(16); + std::fill(zeros, zeros + 16, std::uint8_t{0}); + checking.deallocate(zeros, 16); + std::uint8_t* const written = checking.allocate(16); + std::fill(written, written + 16, std::uint8_t{0x5a}); + checking.deallocate(written, 16); + BOOST_TEST_EQ(checking.state()->allocations, 2U); + BOOST_TEST_EQ(checking.state()->deallocations, 2U); + BOOST_TEST_EQ(checking.state()->wiped_deallocations, 1U); + // The arena records sizes and pointers, and refuses past its buffer. + test::recording_resource arena; + void* const block = arena.allocate(100, 8); + BOOST_TEST_EQ(arena.allocation_count(), 1U); + BOOST_TEST_EQ(arena.allocation(0).size, 100U); + BOOST_TEST(arena.allocation(0).pointer == block); + BOOST_TEST(arena.owns(block)); + int on_the_stack = 0; + BOOST_TEST(!arena.owns(&on_the_stack)); + arena.deallocate(block, 100, 8); + BOOST_TEST_EQ(arena.deallocation_count(), 1U); +} + +} // namespace + +int main() { + return_string_over_an_arena(); + append_to_a_pmr_string(); + assign_to_a_pmr_vector(); + a_typed_decode_with_an_allocator(); + base64_typed_decode_into_an_arena(); + secret_types_over_an_arena(); + the_secret_token_over_an_arena(); + over_takes_its_intermediate_from_its_allocator(); + a_secret_over_gives_its_intermediates_back_wiped(); + each_and_buffered_over_an_arena(); + base58_over_an_arena(); + the_allocators_of_the_tests_own(); + return boost::report_errors(); +} diff --git a/test/allocator_throw_test.cpp b/test/allocator_throw_test.cpp new file mode 100644 index 0000000..a86c644 --- /dev/null +++ b/test/allocator_throw_test.cpp @@ -0,0 +1,710 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// An allocator that fails (owner decision 24): for every N, the Nth allocation of the operation +// throws std::bad_alloc, which reaches the caller unchanged; the token's container still holds +// what it held; and the first N that does not throw gives the right result. A program that needs +// exceptions, built with them on in every lane (the Jamfile). A standard container's own block +// (the MSVC STL's debug proxy, allocated in noexcept constructors) is neither counted nor failed by +// throwing_allocator (support/bookkeeping.hpp, as document's tests leave it out). A secret heap +// type whose allocation throws keeps its value, and every buffer it gives back reads zero; so does +// every buffer of a secret operation through tokens::secret(allocator), and assign_to's scratch +// of a secret operation. buffered and each with the allocator: a send that throws accepts nothing, +// and the stream converts the same input after the exception; a receive that throws leaves its +// item pending; a flush that throws leaves the stream resettable. base58's decode into +// tokens::secret(allocator) allocates the token's buffer alone, its scratch in place (owner +// decision 25), and over's heap intermediate with base58 as its inner link throws through and, on a +// secret chain, gives back every buffer wiped. Later tasks add their rows. + +#include "support/allocators.hpp" +#include "support/letters.hpp" +#include "support/toy_media.hpp" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +using throwing_string = + std::basic_string, test::throwing_allocator>; +using throwing_bytes = std::vector>; +using throwing_secret = codecs::basic_secret_byte_vector>; + +/** More than a small string holds: the allocation cannot be avoided. */ +constexpr std::size_t held_size = 24; + +std::array input_bytes() { + std::array held_bytes{}; + for (std::size_t index = 0; index < held_bytes.size(); ++index) { + held_bytes[index] = static_cast((index * 11U) + 3U); + } + return held_bytes; +} + +/** The text letters gives for `input_bytes()`. */ +std::string expected_text() { + auto const held_bytes = input_bytes(); + return codecs::encode(test::letters, held_bytes, tokens::return_string).value(); +} + +void return_string_throws_through() { + auto const held_bytes = input_bytes(); + std::string const expected = expected_text(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + try { + auto const encoded = + codecs::encode(test::letters, held_bytes, tokens::return_string(allocator)); + BOOST_TEST(encoded.has_value()); + BOOST_TEST(std::string_view{encoded.value()} == expected); + } catch (std::bad_alloc const&) { + thrown = true; + } + if (!thrown) { + // Past the last allocation of the operation: it needed fewer than fail_at - 1 + 1. + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + BOOST_TEST_EQ(allocator.allocations(), fail_at); + ++attempts; + } + BOOST_TEST(attempts >= 1U); + // The same for a decode, which gives the bytes in a string. + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + try { + auto const decoded = + codecs::decode(test::letters, expected, tokens::return_string(allocator)); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), held_size); + } catch (std::bad_alloc const&) { + thrown = true; + } + if (!thrown) { + break; + } + } +} + +/** Whether `target` holds the characters of `expected`. */ +bool holds(throwing_string const& target, std::string_view expected) { + return std::string_view{target.data(), target.size()} == expected; +} + +void append_to_keeps_the_string() { + auto const held_bytes = input_bytes(); + std::string const expected = "kept" + expected_text(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{0}; + throwing_string target{"kept", allocator}; + allocator.arm(fail_at); + bool thrown = false; + try { + auto const encoded = + codecs::encode(test::letters, held_bytes, tokens::append_to(target)); + BOOST_TEST(encoded.has_value()); + BOOST_TEST_EQ(&encoded.value(), &target); + BOOST_TEST(holds(target, expected)); + } catch (std::bad_alloc const&) { + thrown = true; + // The failed append left the string as it was. + BOOST_TEST(holds(target, "kept")); + } + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + BOOST_TEST(attempts >= 1U); +} + +void assign_to_keeps_the_string() { + auto const held_bytes = input_bytes(); + std::string const expected = expected_text(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{0}; + throwing_string target{"kept", allocator}; + allocator.arm(fail_at); + bool thrown = false; + try { + BOOST_TEST( + codecs::encode(test::letters, held_bytes, tokens::assign_to(target)).has_value()); + BOOST_TEST(holds(target, expected)); + } catch (std::bad_alloc const&) { + thrown = true; + BOOST_TEST(holds(target, "kept")); + } + if (!thrown) { + break; + } + ++attempts; + } + BOOST_TEST(attempts >= 1U); +} + +void decode_into_a_vector_keeps_it() { + std::string const expected = expected_text(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{0}; + throwing_bytes target{{9, 9}, allocator}; + allocator.arm(fail_at); + bool thrown = false; + try { + BOOST_TEST( + codecs::decode(test::letters, expected, tokens::append_to(target)).has_value()); + BOOST_TEST_EQ(target.size(), 2 + held_size); + } catch (std::bad_alloc const&) { + thrown = true; + BOOST_TEST_EQ(target.size(), 2U); + BOOST_TEST_EQ(target[0], 9); + BOOST_TEST_EQ(target[1], 9); + } + if (!thrown) { + break; + } + ++attempts; + } + BOOST_TEST(attempts >= 1U); +} + +void assign_to_a_vector_keeps_it() { + // A text of a size known at run time: assign_to's scratch comes from the vector's allocator, + // and when that allocation throws the vector holds what it held. + std::string const expected = expected_text(); + auto const held_bytes = input_bytes(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{0}; + throwing_bytes target{{9, 9}, allocator}; + allocator.arm(fail_at); + bool thrown = false; + try { + BOOST_TEST( + codecs::decode(test::letters, expected, tokens::assign_to(target)).has_value()); + BOOST_TEST(std::ranges::equal(target, held_bytes)); + } catch (std::bad_alloc const&) { + thrown = true; + BOOST_TEST((target == throwing_bytes{{9, 9}, allocator})); + } + if (!thrown) { + break; + } + ++attempts; + } + BOOST_TEST(attempts >= 1U); +} + +void a_typed_decode_throws_through() { + std::string const expected = expected_text(); + auto const held_bytes = input_bytes(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + try { + auto const decoded = codecs::decode(test::letters, expected, allocator); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(decoded.value().size(), held_size); + BOOST_TEST(std::equal(held_bytes.begin(), held_bytes.end(), decoded.value().begin())); + } catch (std::bad_alloc const&) { + thrown = true; + } + if (!thrown) { + break; + } + ++attempts; + } + BOOST_TEST(attempts >= 1U); +} + +/** Whether `secret` holds `expected`. */ +bool holds(throwing_secret const& secret, std::span expected) { + return std::ranges::equal(secret.view(), expected); +} + +void a_secret_growth_keeps_its_bytes() { + auto const all_bytes = input_bytes(); + auto const held = std::span{all_bytes}.first(16); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{0}; + std::vector expected(held.begin(), held.end()); + bool thrown = false; + { + throwing_secret secret{allocator}; + secret.append(held); + allocator.arm(fail_at); + try { + // Each call allocates once: a growth past the capacity, a larger capacity, a + // buffer of the size, a copy. + secret.append(all_bytes); + expected.insert(expected.end(), all_bytes.begin(), all_bytes.end()); + secret.reserve(secret.capacity() + 1); + secret.shrink_to_fit(); + auto const copy = secret.clone(); + BOOST_TEST(holds(copy, expected)); + } catch (std::bad_alloc const&) { + thrown = true; + } + // The value is the one before the call that threw. + BOOST_TEST(holds(secret, expected)); + } + // Every buffer came back, and none of them held a byte. + BOOST_TEST(allocator.state()->deallocations >= 1U); + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + BOOST_TEST_EQ(attempts, 4U); +} + +void a_secret_move_between_unequal_allocators_keeps_both() { + auto const all_bytes = input_bytes(); + auto const target_bytes = std::span{all_bytes}.first(4); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const target_allocator{0}; + test::throwing_allocator const source_allocator{0}; + bool thrown = false; + { + throwing_secret target{target_allocator}; + target.append(target_bytes); + throwing_secret source{source_allocator}; + source.append(all_bytes); + target_allocator.arm(fail_at); + try { + // Unequal and not propagating: a copy into a buffer of the target's allocator. + target = std::move(source); + BOOST_TEST(holds(target, all_bytes)); + } catch (std::bad_alloc const&) { + thrown = true; + BOOST_TEST(holds(target, target_bytes)); + // NOLINTNEXTLINE(bugprone-use-after-move): a move that threw left it whole + BOOST_TEST(holds(source, all_bytes)); + } + } + BOOST_TEST_EQ(target_allocator.state()->unwiped_deallocations, 0U); + BOOST_TEST_EQ(source_allocator.state()->unwiped_deallocations, 0U); + if (!thrown) { + break; + } + ++attempts; + } + BOOST_TEST_EQ(attempts, 1U); +} + +void the_secret_token_throws_through() { + // A secret encode through tokens::secret(allocator), then a clone of its result: two + // allocations, so that the second fails after the first gave a buffer that held the secret + // text. The allocator's exception reaches the caller, and every buffer allocated before it was + // given back zero. + std::vector const held_bytes(held_size, 0x5a); // the heap: not a static size + std::string const expected = + codecs::encode(test::letters, held_bytes, tokens::return_string).value(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + try { + auto const encoded = + codecs::encode(test::letters, held_bytes, tokens::secret(allocator)); + BOOST_TEST(encoded.value().view() == expected); + auto const copy = encoded.value().clone(); + BOOST_TEST(copy.view() == expected); + } catch (std::bad_alloc const&) { + thrown = true; + } + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.allocations() - (thrown ? 1 : 0)); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + // From the second on, a buffer of the secret text was allocated before the throw. + BOOST_TEST_EQ(allocator.state()->deallocations, fail_at - 1); + ++attempts; + } + BOOST_TEST_EQ(attempts, 2U); + // The same for a decode, and a typed decode into a secret vector of the allocator: the second + // allocation fails after the decode's buffer held the secret bytes. + attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + try { + auto const decoded = codecs::decode(test::letters, expected, tokens::secret(allocator)); + BOOST_TEST(holds(decoded.value(), held_bytes)); + auto const typed = codecs::decode(test::letters, expected, allocator); + BOOST_TEST(holds(typed.value(), held_bytes)); + } catch (std::bad_alloc const&) { + thrown = true; + } + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.allocations() - (thrown ? 1 : 0)); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + BOOST_TEST_EQ(allocator.state()->deallocations, fail_at - 1); + ++attempts; + } + BOOST_TEST_EQ(attempts, 2U); +} + +void a_secret_assign_to_wipes_its_scratch_when_the_target_throws() { + // A secret input whose encoding (4200 letters) is past the bound of a scratch in place: + // assign_to's scratch comes from the string's allocator (the first allocation), and the copy + // into a string too short for it allocates the second. When the second throws, the string holds + // what it held and the scratch, which held the secret text, was given back zero. + webcpp::secure::secret<2100> key; + std::ranges::fill(key.writable(), std::uint8_t{0x5a}); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{0}; + throwing_string target{"kept", allocator}; + allocator.arm(fail_at); + bool thrown = false; + try { + BOOST_TEST(codecs::encode(test::letters, key, tokens::assign_to(target)).has_value()); + BOOST_TEST_EQ(target.size(), 4200U); + } catch (std::bad_alloc const&) { + thrown = true; + BOOST_TEST(holds(target, "kept")); + } + // Read before the string, which holds the text when the operation succeeded, goes. + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + BOOST_TEST_EQ(allocator.state()->deallocations, fail_at == 1 ? 0U : 1U); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + BOOST_TEST_EQ(attempts, 2U); +} + +/** Runs `operation`, which is given the chain `make_chain` makes of an allocator that throws on its + `fail_at`th allocation, for every `fail_at` until it does not: an exception reaches the caller + from the first and the second allocation (the exact size's intermediate and the operation's), + every buffer is given back, and on a secret chain every one reads zero. */ +template +void for_each_failing_chain_allocation(bool secret, MakeChain make_chain, Operation operation) { + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + auto const chain = make_chain(allocator); + bool thrown = false; + try { + operation(chain); + } catch (std::bad_alloc const&) { + thrown = true; + } + if (secret) { + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + } + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.allocations() - (thrown ? 1 : 0)); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + BOOST_TEST_EQ(attempts, 2U); +} + +/** for_each_failing_chain_allocation over a chain of letters over letters. */ +template +void for_each_failing_allocation(bool secret, Operation operation) { + for_each_failing_chain_allocation( + secret, + [](test::throwing_allocator const& allocator) { + return codecs::over{test::letters, test::letters, allocator}; + }, + operation); +} + +void an_over_throws_through_and_wipes_when_secret() { + // over's heap intermediate (Task 7): the exact size's intermediate is the first allocation and + // the operation's the second; on a secret chain every buffer the allocator was given back + // reads zero. + std::vector const input(held_size, 0x5a); + std::string const inner_text = + codecs::encode(test::letters, input, tokens::return_string).value(); + std::string const expected = + codecs::encode(test::letters, inner_text, tokens::return_string).value(); + for_each_failing_allocation(false, [&](auto const& chain) { + BOOST_TEST(codecs::encode(chain, input).value() == expected); + }); + for_each_failing_allocation(true, [&](auto const& chain) { + auto const encoded = codecs::encode(chain, input, tokens::secret); + BOOST_TEST(encoded.value().view() == expected); + }); + for_each_failing_allocation(false, [&](auto const& chain) { + BOOST_TEST((codecs::decode(chain, expected).value() == input)); + }); + for_each_failing_allocation(true, [&](auto const& chain) { + auto const decoded = codecs::decode(chain, expected, tokens::secret); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + }); + // The buffer form allocates, too (finding F17), and the exception reaches the caller. + test::throwing_allocator const allocator{1}; + auto const chain = codecs::over{test::letters, test::letters, allocator}; + std::array buffer{}; + bool thrown = false; + try { + BOOST_TEST(codecs::encode(chain, input, std::span{buffer}).has_value()); + } catch (std::bad_alloc const&) { + thrown = true; + } + BOOST_TEST(thrown); +} + +/** + base58's decode of a secret text into tokens::secret(allocator), for every failing allocation + (owner decision 25): its scratch is in place, so that the token's buffer is the one allocation; + when it throws, the exception reaches the caller, and every buffer given back reads zero. +*/ +void a_base58_decode_throws_through() { + namespace formats = codecs::formats; + std::vector const held_bytes(held_size, 0x5a); + std::string const text = codecs::encode(formats::base58, held_bytes).value(); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + try { + auto const decoded = codecs::decode(formats::base58, text, tokens::secret(allocator)); + BOOST_TEST(holds(decoded.value(), held_bytes)); + } catch (std::bad_alloc const&) { + thrown = true; + } + BOOST_TEST_EQ(allocator.state()->unwiped_deallocations, 0U); + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.allocations() - (thrown ? 1 : 0)); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + BOOST_TEST_EQ(attempts, 1U); +} + +/** + over{hex, base58} with an allocator that throws on its fail_at-th allocation, for every fail_at + until it does not: base58's text is the heap intermediate, of the exact size's run and of the + operation's, and the exception reaches the caller from each; every buffer is given back, and on a + secret chain each reads zero. +*/ +void an_over_of_base58_throws_through() { + namespace formats = codecs::formats; + std::vector const input(held_size, 0x5a); + std::string const inner_text = codecs::encode(formats::base58, input).value(); + std::string const expected = codecs::encode(formats::hex, inner_text).value(); + auto const make_chain = [](test::throwing_allocator const& allocator) { + return codecs::over{formats::hex, formats::base58, allocator}; + }; + for_each_failing_chain_allocation(false, make_chain, [&](auto const& chain) { + BOOST_TEST(codecs::encode(chain, input).value() == expected); + }); + for_each_failing_chain_allocation(true, make_chain, [&](auto const& chain) { + auto const decoded = codecs::decode(chain, expected, tokens::secret); + BOOST_TEST(std::ranges::equal(decoded.value().view(), input)); + }); +} + +/** Frames 0 to 19, whose bytes frame_to_bytes writes 2 + index % 3 a frame. */ +std::array twenty_frames() { + std::array frames{}; + for (std::size_t index = 0; index < frames.size(); ++index) { + frames[index] = test::make_frame(static_cast(index)); + } + return frames; +} + +/** The bytes of `frames`, the one-shot form. */ +std::vector bytes_of_frames(std::span frames) { + std::vector bytes(4 * frames.size()); + bytes.resize(test::frame_to_bytes::transform(frames, bytes).value()); + return bytes; +} + +/** + Receives everything `adapter` holds into `received`, one span of up to 5 bytes at a time, while + it reports output_pending; a receive that throws is called again, and true is returned when one + did: the item stays pending, and the stream delivers it. +*/ +template +bool receive_all(Adapter& adapter, std::vector& received) { + std::array output{}; + bool thrown = false; + for (;;) { + codecs::result step_taken = + codecs::step{.count = 0, .flow = codecs::flow::needs_input}; + try { + step_taken = adapter.receive(output); + } catch (std::bad_alloc const&) { + thrown = true; + continue; + } + if (!BOOST_TEST(step_taken.has_value())) { + return thrown; + } + received.insert(received.end(), output.begin(), + output.begin() + static_cast(step_taken->count)); + if (step_taken->flow != codecs::flow::output_pending) { + return thrown; + } + } +} + +/** + buffered with an allocator that throws on its fail_at-th allocation, for every fail_at until the + stream needs fewer (Task 10): the frames go in chunks of 3, growing the input, and flush sizes the + output. A send that throws accepts nothing: the same chunk sent again gives the right bytes, with + no frame twice. A flush that throws leaves the stream resettable: reset, the same frames give the + right bytes. Every block is given back. +*/ +void buffered_throws_through() { + auto const frames = twenty_frames(); + std::vector const expected = bytes_of_frames(frames); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + { + codecs::buffered adapter{test::frame_to_bytes_bounded(), allocator}; + auto const send_all = [&] { + for (std::size_t first = 0; first < frames.size(); first += 3) { + std::span const chunk = + std::span{frames}.subspan(first, std::min(3, 20 - first)); + codecs::result sent = + codecs::step{.count = 0, .flow = codecs::flow::needs_input}; + try { + sent = adapter.send(chunk); + } catch (std::bad_alloc const&) { + thrown = true; + sent = adapter.send(chunk); + } + BOOST_TEST(sent.has_value() && sent->count == chunk.size()); + } + }; + send_all(); + codecs::result flushed = codecs::flow::needs_input; + try { + flushed = adapter.flush(); + } catch (std::bad_alloc const&) { + thrown = true; + adapter.reset(); + send_all(); + flushed = adapter.flush(); + } + BOOST_TEST(flushed.has_value()); + std::vector received; + static_cast(receive_all(adapter, received)); + BOOST_TEST(received == expected); + } + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.allocations() - (thrown ? 1 : 0)); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + // The input's growths and the output. + BOOST_TEST_GE(attempts, 2U); +} + +/** + each with an allocator that throws on its fail_at-th allocation, for every fail_at until the + stream needs fewer (Task 10): frame_to_bytes states no bound, so that receive grows the item + storage by doubling. A receive that throws leaves the item pending: receiving again delivers it, + and the stream gives the right bytes; reset, it converts the frames again. Every block is given + back. +*/ +void each_throws_through() { + auto const frames = twenty_frames(); + std::vector const expected = bytes_of_frames(frames); + std::size_t attempts = 0; + for (std::size_t fail_at = 1;; ++fail_at) { + test::throwing_allocator const allocator{fail_at}; + bool thrown = false; + { + codecs::each adapter{test::frame_to_bytes{}, allocator}; + std::vector received; + for (std::size_t index = 0; index < frames.size(); ++index) { + auto const sent = adapter.send(std::span{frames}.subspan(index)); + BOOST_TEST(sent.has_value() && sent->count == 1); + thrown = receive_all(adapter, received) || thrown; + } + BOOST_TEST(received == expected); + BOOST_TEST_EQ(adapter.completed_items(), frames.size()); + adapter.reset(); + received.clear(); + for (std::size_t index = 0; index < frames.size(); ++index) { + BOOST_TEST(adapter.send(std::span{frames}.subspan(index)).has_value()); + static_cast(receive_all(adapter, received)); + } + BOOST_TEST(received == expected); + } + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.allocations() - (thrown ? 1 : 0)); + if (!thrown) { + BOOST_TEST_EQ(allocator.allocations(), fail_at - 1); + break; + } + ++attempts; + } + // The storage's doublings. + BOOST_TEST_GE(attempts, 2U); +} + +} // namespace + +int main() { + return_string_throws_through(); + append_to_keeps_the_string(); + assign_to_keeps_the_string(); + decode_into_a_vector_keeps_it(); + assign_to_a_vector_keeps_it(); + a_typed_decode_throws_through(); + a_secret_growth_keeps_its_bytes(); + a_secret_move_between_unequal_allocators_keeps_both(); + the_secret_token_throws_through(); + a_secret_assign_to_wipes_its_scratch_when_the_target_throws(); + an_over_throws_through_and_wipes_when_secret(); + a_base58_decode_throws_through(); + an_over_of_base58_throws_through(); + buffered_throws_through(); + each_throws_through(); + return boost::report_errors(); +} diff --git a/test/armor_openssl_test.cpp b/test/armor_openssl_test.cpp new file mode 100644 index 0000000..c8541a4 --- /dev/null +++ b/test/armor_openssl_test.cpp @@ -0,0 +1,193 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// OpenSSL as the armor's oracle (ruling R8, the spec's scenario "OpenSSL's PEM"): a P-256 public +// key's SubjectPublicKeyInfo, generated by OpenSSL and written by i2d_PUBKEY, and three other DERs +// of 1, 48 and 1000 bytes, encoded with formats::armor and each label equal, byte for +// byte, what PEM_write_bio writes for the same bytes and label, and decode back to them, as +// PEM_read_bio reads ours; through the stream encoder and decoder too. OpenSSL, the superproject's +// source-built library, is linked in this test alone, natively. PEM_write_bio of no bytes writes +// the two boundary lines and returns 0, the count of base64 characters, so it is not a failure: the +// armor of no bytes equals that text too. + +#include "support/samples.hpp" + +#include +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; + +/** Frees a BIO. */ +struct bio_free { + void operator()(BIO* bio) const noexcept { BIO_free(bio); } +}; + +/** Frees an EVP_PKEY. */ +struct key_free { + void operator()(EVP_PKEY* key) const noexcept { EVP_PKEY_free(key); } +}; + +/** Frees what OpenSSL allocated. */ +struct openssl_free { + void operator()(void* block) const noexcept { OPENSSL_free(block); } +}; + +/** + What PEM_write_bio writes for `der` under `label`, or nothing when it fails. It returns the count + of base64 characters written, which is 0 for no bytes, so only a negative value is a failure. +*/ +std::string openssl_pem(std::string const& label, std::span der) { + std::unique_ptr const bio{BIO_new(BIO_s_mem())}; + if (bio == nullptr || PEM_write_bio(bio.get(), label.c_str(), "", der.data(), + static_cast(der.size())) < 0) { + return {}; + } + char* data = nullptr; + // BIO_get_mem_data's own call, with no cast of the macro's. + long const size = BIO_ctrl(bio.get(), BIO_CTRL_INFO, 0, static_cast(&data)); + return {data, static_cast(size)}; +} + +/** What PEM_read_bio reads in `text`: its label and its bytes, empty when it fails. */ +std::pair> openssl_read(std::string_view text) { + std::unique_ptr const bio{ + BIO_new_mem_buf(text.data(), static_cast(text.size()))}; + char* name = nullptr; + char* header = nullptr; + unsigned char* data = nullptr; + long size = 0; + if (bio == nullptr || PEM_read_bio(bio.get(), &name, &header, &data, &size) <= 0) { + return {}; + } + std::unique_ptr const owned_name{name}; + std::unique_ptr const owned_header{header}; + std::unique_ptr const owned_data{data}; + return {std::string{name}, std::vector(data, data + size)}; +} + +/** A P-256 public key's SubjectPublicKeyInfo, OpenSSL's i2d_PUBKEY of a key it generates. */ +std::vector p256_spki() { + std::unique_ptr const key{ + EVP_PKEY_Q_keygen(nullptr, nullptr, "EC", "P-256")}; + if (key == nullptr) { + return {}; + } + unsigned char* der = nullptr; + int const size = i2d_PUBKEY(key.get(), &der); + if (size <= 0) { + return {}; + } + std::unique_ptr const owned{der}; + return {der, der + size}; +} + +/** + Receives from `decoder` into `output` after `received` bytes until it reports another state than + `flow::output_pending`. + + @return The bytes received in all, or nothing when a call fails. +*/ +template +std::optional receive_into(Decoder& decoder, std::span output, + std::size_t received) { + for (;;) { + auto const step = decoder.receive(output.subspan(received)); + if (!step) { + return std::nullopt; + } + received += step->count; + if (step->flow != codecs::flow::output_pending) { + return received; + } + } +} + +/** + Checks that the secret stream encoder writes `expected`, PEM_write_bio's text of `der` under + `label`, and that the stream decoder reads it back to `der` and its label. +*/ +void expect_the_streams(std::string const& label, std::vector const& der, + std::string const& expected) { + auto const encoder = codecs::encoder(formats::armor(label), codecs::secret_operation); + std::string streamed(expected.size(), '\0'); + auto const written = encoder.transform(der, std::span{streamed}); + BOOST_TEST(written.has_value() && streamed == expected); + auto decoder = codecs::decoder(formats::armor); + BOOST_TEST(decoder.send(test::characters_of(expected)).has_value()); + std::vector output(der.size() + 1); + auto const before_flush = receive_into(decoder, std::span{output}, 0); + BOOST_TEST(before_flush.has_value() && decoder.flush().has_value()); + auto const received = receive_into(decoder, std::span{output}, before_flush.value_or(0)); + BOOST_TEST(received.has_value()); + output.resize(received.value_or(0)); + BOOST_TEST(output == der); + BOOST_TEST(decoder.label() == label); +} + +/** + Checks that `der` under `label` encodes to PEM_write_bio's text, one-shot and through the stream + encoder, and that the text decodes back to `der`, one-shot and through the stream decoder, as + PEM_read_bio reads it. +*/ +void expect_openssls_pem(std::string const& label, std::span der) { + std::string const expected = openssl_pem(label, der); + BOOST_TEST(!expected.empty()); + auto const encoded = codecs::encode(formats::armor(label), der); + if (!BOOST_TEST(encoded.has_value() && encoded.value() == expected)) { + std::printf("OpenSSL:\n%s\ncodecs:\n%s\n", expected.c_str(), + encoded.has_value() ? encoded->c_str() : "(error)"); + } + std::vector const der_bytes(der.begin(), der.end()); + auto const decoded = codecs::decode(formats::armor(label), expected); + BOOST_TEST(decoded.has_value() && decoded.value() == der_bytes); + auto const parts = codecs::decode(formats::armor, expected); + BOOST_TEST(parts.has_value() && parts->label.view() == label && parts->data == der_bytes); + // PEM_read_bio reads no PEM of no bytes (it writes one, which is the oracle's text above). + if (!der_bytes.empty()) { + auto const read = openssl_read(encoded.has_value() ? encoded.value() : std::string{}); + BOOST_TEST(read.first == label && read.second == der_bytes); + } + expect_the_streams(label, der_bytes, expected); +} + +} // namespace + +int main() { + std::vector const spki = p256_spki(); + BOOST_TEST_EQ(spki.size(), 91U); + expect_openssls_pem("PUBLIC KEY", spki); + for (std::size_t const size : {std::size_t{1}, std::size_t{48}, std::size_t{1000}}) { + std::vector const der = test::random_bytes(size); + for (std::string const label : {"CERTIFICATE", "PRIVATE KEY", "X509 CRL"}) { + expect_openssls_pem(label, der); + } + } + // No bytes: the two boundary lines, as OpenSSL writes them. + expect_openssls_pem("PUBLIC KEY", {}); + return boost::report_errors(); +} diff --git a/test/armor_stream_test.cpp b/test/armor_stream_test.cpp new file mode 100644 index 0000000..7649afd --- /dev/null +++ b/test/armor_stream_test.cpp @@ -0,0 +1,630 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The armor as a stream (D20): encoder(armor("PUBLIC KEY")) writes the BEGIN boundary with its +// first input, the base64 lines as it goes and the END boundary at flush; decoder(armor) reads the +// BEGIN line, the payload as it comes and the END boundary at flush, and gives the label it read by +// label() after it. RFC 7468's examples and OpenSSL's PEM files of test/data/armor/, their lines +// ended by a line feed, by a carriage return and a line feed, with and without the final one, and +// 1000 random inputs (the first 40 over every chunking, the others over random ones) equal the +// one-shot forms for every chunking (support/chunkings.hpp) and output spans of one and 1024, +// public and secret; every invalid text of the one-shot test's kinds, and every byte value as a +// character at each place of a short text, give the one-shot form's error after flush, writing +// nothing (B44). The spec's scenario "Armor as a stream" (a DER in chunks of 5 bytes); a +// configuration fault by the first call, also after reset (B23), and the encoder of a format with +// no label; the protocol's states; empty input (Review Focus 3); a moved-from stream converts from +// the start (Review Focus 5); a secret stream wipes its pending state, as secure's wipe seam +// records it. + +#include "support/wipe_recorder.hpp" + +#include "support/armor_files.hpp" +#include "support/armor_reference.hpp" +#include "support/chunkings.hpp" +#include "support/samples.hpp" +#include "support/steps.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; + +using armor_encoder = decltype(codecs::encoder(formats::armor("PUBLIC KEY"))); +using armor_decoder = decltype(codecs::decoder(formats::armor)); +using secret_armor_encoder = decltype(codecs::encoder(formats::armor, codecs::secret_operation)); +using secret_armor_decoder = decltype(codecs::decoder(formats::armor, codecs::secret_operation)); +using stream_encoder = codecs::stream_codec::encoder; +using stream_decoder = codecs::stream_codec::decoder; +using secret_stream_encoder = + codecs::stream_codec::encoder; +using secret_stream_decoder = + codecs::stream_codec::decoder; + +// The armor streams natively: one-shot and stream transformers, constant time as its codec is. +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(codecs::is_constant_time_v); +static_assert(codecs::is_constant_time_v); +static_assert(armor_encoder::max_output_size(0) == 160); +static_assert(armor_decoder::max_output_size(52) == 39); +// The decoder gives the label it read (B39). +static_assert( + std::is_same_v().label()), std::string_view>); +static_assert(noexcept(std::declval().label())); +// A public stream is copyable and trivially destructible, a secret one move-only and wiping. +static_assert(std::is_trivially_destructible_v); +static_assert(std::is_trivially_destructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(!std::is_trivially_destructible_v); +static_assert(!std::is_trivially_destructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(codecs::is_secret_v); +static_assert(codecs::is_secret_v); + +/** + A valid `text` of `bytes` under `label`, through every chunking of the decoder of a format with no + label and of one with its label, and of the secret one when `with_secret`, equal to the bytes, the + label read given by label(); when `text` is what the format writes, the bytes through every + chunking of the encoder, and of the secret one likewise, equal to it. +*/ +void expect_every_chunking_of(std::string_view text, std::span bytes, + std::string_view label, bool with_secret = true) { + auto decoder = codecs::decoder(formats::armor); + test::expect_every_chunking(decoder, test::characters_of(text), bytes); + BOOST_TEST(decoder.label() == label); + auto labelled = codecs::decoder(formats::armor(label)); + test::expect_every_chunking(labelled, test::characters_of(text), bytes); + bool const written_form = test::reference_armor_encode(label, bytes) == text; + auto encoder = codecs::encoder(formats::armor(label)); + if (written_form) { + test::expect_every_chunking(encoder, bytes, text); + } + if (!with_secret) { + return; + } + auto secret_decoder = codecs::decoder(formats::armor, codecs::secret_operation); + test::expect_every_chunking(secret_decoder, test::characters_of(text), bytes); + BOOST_TEST(secret_decoder.label() == label); + if (written_form) { + auto secret_encoder = codecs::encoder(formats::armor(label), codecs::secret_operation); + test::expect_every_chunking(secret_encoder, bytes, text); + } +} + +/** + A valid `text` of `bytes` under `label` through `chunkings` random chunkings of the decoder of a + format with no label, public and secret, equal to the bytes. +*/ +void expect_random_chunkings_of(std::string_view text, std::span bytes, + std::string_view label, std::mt19937_64& generator, int chunkings) { + auto decoder = codecs::decoder(formats::armor); + test::expect_random_chunkings(decoder, test::characters_of(text), bytes, generator, chunkings); + BOOST_TEST(decoder.label() == label); + auto secret_decoder = codecs::decoder(formats::armor(label), codecs::secret_operation); + test::expect_random_chunkings(secret_decoder, test::characters_of(text), bytes, generator, + chunkings); +} + +/** + Every file of test/data/armor/ through every chunking, the secret streams over the first three; + its lines ended by a carriage return and a line feed, and with no final line ending, through 16 + random chunkings. +*/ +void every_file_through_every_chunking() { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): a fixed seed + std::mt19937_64 generator{20261130}; + std::vector const vectors = test::read_armor_vectors(); + BOOST_TEST_EQ(vectors.size(), test::armor_files.size()); + for (std::size_t index = 0; index < vectors.size(); ++index) { + test::armor_vector const& vector = vectors[index]; + expect_every_chunking_of(vector.text, vector.der, vector.file.label, index < 3); + std::string const crlf = test::with_carriage_returns(vector.text); + for (std::string_view const variant : { + std::string_view{crlf}, + std::string_view{crlf}.substr(0, crlf.size() - 2), + std::string_view{vector.text}.substr(0, vector.text.size() - 1), + }) { + expect_random_chunkings_of(variant, vector.der, vector.file.label, generator, 16); + } + } +} + +/** + 1000 random inputs of 0 to 96 bytes under a label of the grammar: the first 40 through every + chunking, the others through 4 random chunkings, public and secret, each line ending in turn. +*/ +void a_thousand_random_inputs() { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): a fixed seed + std::mt19937_64 generator{20261129}; + constexpr std::array labels{"PUBLIC KEY", "A", "x-y z", "PRIVATE KEY"}; + for (int iteration = 0; iteration < 1000; ++iteration) { + std::vector bytes(generator() % 97); + for (std::uint8_t& byte : bytes) { + byte = static_cast(generator()); + } + std::string_view const label = labels[generator() % labels.size()]; + std::string text = test::reference_armor_encode(label, bytes); + bool const crlf = iteration % 3 == 1; + if (crlf) { + text = test::with_carriage_returns(text); + } + if (iteration % 5 == 2) { + text.resize(text.size() - (crlf ? 2 : 1)); + } + if (iteration < 40) { + expect_every_chunking_of(text, bytes, label, iteration % 4 == 0); + continue; + } + auto decoder = codecs::decoder(formats::armor); + test::expect_random_chunkings(decoder, test::characters_of(text), + std::span{bytes}, generator, 4); + auto secret_decoder = codecs::decoder(formats::armor(label), codecs::secret_operation); + test::expect_random_chunkings(secret_decoder, test::characters_of(text), + std::span{bytes}, generator, 4); + std::string const written = test::reference_armor_encode(label, bytes); + auto encoder = codecs::encoder(formats::armor(label)); + test::expect_random_chunkings(encoder, std::span{bytes}, + std::string_view{written}, generator, 4); + auto secret_encoder = codecs::encoder(formats::armor(label), codecs::secret_operation); + test::expect_random_chunkings(secret_encoder, std::span{bytes}, + std::string_view{written}, generator, 4); + } +} + +/** + Every chunking of `text` decodes in `format` as the one-shot form does: the same bytes, or the + same error, reported after flush by the call that reads the end, which writes nothing (B44); + public and, when `with_secret`, secret decoders alike. +*/ +void expect_the_one_shot_verdict(formats::armor_t const& format, std::string_view text, + bool with_secret = true) { + test::expect_the_one_shot_verdict(format, text, with_secret, [](auto const& decoder) { + BOOST_TEST(decoder.label().empty()); + }); +} + +/** + `text` decodes in `format` as the one-shot form does, through the stream whole and one character + at a time, into spans of one and of 1024: the same bytes, or the same error after flush, which the + call that reports it writes nothing for (B44). +*/ +void expect_the_one_shot_verdict_lightly(formats::armor_t const& format, std::string_view text) { + auto const one_shot = codecs::decode(format, text); + auto decoder = codecs::decoder(format); + std::vector> const whole{test::characters_of(text)}; + std::vector> singles_storage; + singles_storage.reserve(text.size()); + for (std::size_t index = 0; index < text.size(); ++index) { + singles_storage.push_back(test::characters_of(text).subspan(index, 1)); + } + std::vector> const& singles = singles_storage; + for (std::vector> const* const chunks : {&whole, &singles}) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { + decoder.reset(); + auto const streamed = test::stream_whole( + decoder, std::span const>{*chunks}, span_size); + if (one_shot.has_value()) { + BOOST_TEST(streamed.has_value() && streamed.value() == one_shot.value()); + } else { + BOOST_TEST(!streamed.has_value() && streamed.error() == one_shot.error()); + decoder.reset(); + BOOST_TEST(test::error_after_flush(decoder, + std::span const>{*chunks}, + span_size) == one_shot.error()); + } + } + } +} + +/** + The one-shot test's invalid texts give the one-shot form's error after flush, for every chunking; + every byte value as a character at each place of a short text and inserted there, the one-shot + form's bytes or error, whole and one character at a time, and for every chunking two values at + each place. +*/ +void invalid_texts_give_the_one_shot_error_after_flush() { + std::vector const bytes = test::random_bytes(100); + std::string const text = test::reference_armor_encode("PUBLIC KEY", bytes); + auto const format = formats::armor("PUBLIC KEY"); + std::size_t const payload = text.find('\n') + 1; + std::size_t const end_line = text.rfind("-----END"); + std::string bad_symbol = text; + bad_symbol[payload + 5] = '*'; + std::string padding_inside = text; + padding_inside[payload + 3] = '='; + for (std::string const& invalid : { + std::string{}, + text.substr(0, payload), + text.substr(0, end_line), + text.substr(payload), + "Subject: CN=Atlantis\n" + text, + text + "Subject: CN=Atlantis\n", + text + "\n", + text + text, + text.substr(0, end_line) + "-----END PRIVATE KEY-----\n", + text.substr(0, payload + 10) + "A" + text.substr(payload + 10), + text.substr(0, payload + 10) + "\n" + text.substr(payload + 10), + text.substr(0, payload + 10) + " " + text.substr(payload + 10), + text.substr(0, payload) + "Proc-Type: 4,ENCRYPTED\n\n" + text.substr(payload), + text.substr(0, end_line) + "\n" + text.substr(end_line), + bad_symbol, + padding_inside, + std::string{"-----BEGIN A-----\nZh==\n-----END A-----\n"}, + std::string{"-----BEGIN A-----\nZm9vY\n-----END A-----\n"}, + }) { + expect_the_one_shot_verdict(format, invalid); + expect_the_one_shot_verdict_lightly(formats::armor, invalid); + } + expect_the_one_shot_verdict(formats::armor("PRIVATE KEY"), text); + std::string const base = test::reference_armor_encode("A B", std::span{bytes}.first(4)); + for (std::size_t place = 0; place <= base.size(); ++place) { + for (unsigned value = 0; value < 256; ++value) { + auto const character = static_cast(static_cast(value)); + std::string replaced = base; + if (place == base.size()) { + replaced.push_back(character); + } else { + replaced[place] = character; + } + expect_the_one_shot_verdict_lightly(formats::armor, replaced); + std::string inserted = base; + inserted.insert(place, 1, character); + expect_the_one_shot_verdict_lightly(formats::armor("A B"), inserted); + // Every chunking for two values at each place, public and secret. + if (value % 128 == place % 128) { + expect_the_one_shot_verdict(formats::armor, replaced); + } + } + } +} + +/** + The spec's "Armor as a stream": a DER streamed through encoder(armor("PUBLIC KEY")) in chunks of 5 + bytes equals the one-shot armor, byte for byte, and the result streamed through decoder(armor) + gives the DER and label() "PUBLIC KEY" after flush. +*/ +void an_armor_as_a_stream() { + auto const spki = test::read_armor_data("openssl-p256-spki.der"); + BOOST_TEST(spki.has_value()); + if (!spki) { + return; + } + std::vector const der{spki->begin(), spki->end()}; + std::vector> chunks; + for (std::size_t position = 0; position < der.size(); position += 5) { + chunks.push_back( + std::span{der}.subspan(position, std::min(5, der.size() - position))); + } + auto encoder = codecs::encoder(formats::armor("PUBLIC KEY")); + auto const text = + test::stream_whole(encoder, std::span const>{chunks}, 16); + auto const one_shot = codecs::encode(formats::armor("PUBLIC KEY"), der); + BOOST_TEST(text.has_value() && one_shot.has_value() && + std::string(text->begin(), text->end()) == one_shot.value()); + BOOST_TEST(one_shot.value() == test::read_armor_data("openssl-p256-spki.pem").value_or("")); + auto decoder = codecs::decoder(formats::armor); + std::vector> const whole{test::characters_of(one_shot.value())}; + auto const decoded = + test::stream_whole(decoder, std::span const>{whole}, 7); + BOOST_TEST(decoded.has_value() && decoded.value() == der); + BOOST_TEST(decoder.label() == "PUBLIC KEY"); +} + +/** + A configuration fault by the first call (B23): a label of 65 characters, or outside the grammar, + is invalid_prefix from the decoder's first call, whatever it is, and every call after, also after + reset. +*/ +void a_configuration_fault_by_the_first_call() { + std::string const label_65(65, 'A'); + std::string const text = test::reference_armor_encode("A", test::random_bytes(10)); + std::array span{}; + for (formats::armor_t const& faulty : {formats::armor(label_65), formats::armor("A--B")}) { + auto decoder = codecs::decoder(faulty); + BOOST_TEST(test::failed_with(decoder.receive(span), codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(decoder.send(test::characters_of(text)), + codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_prefix)); + decoder.reset(); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(decoder.transform(test::characters_of(text), span), + codecs::error::invalid_prefix)); + BOOST_TEST_EQ(decoder.output_size(test::characters_of(text)), 0U); + auto first_flush = codecs::decoder(faulty, codecs::secret_operation); + BOOST_TEST(test::failed_with(first_flush.flush(), codecs::error::invalid_prefix)); + } +} + +/** + The encoder's configuration fault by its first call (B23), and the encoder of a format with no + label, which has nothing to write: invalid_prefix from every call, also after reset. +*/ +void an_encoders_configuration_fault_by_the_first_call() { + std::string const label_65(65, 'A'); + std::array characters{}; + std::array const bytes{1, 2}; + for (auto encoder : { + codecs::encoder(formats::armor(label_65)), + codecs::encoder(formats::armor), + codecs::encoder(formats::armor("A--B")), + }) { + BOOST_TEST(test::failed_with(encoder.send(bytes), codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(encoder.receive(characters), codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(encoder.flush(), codecs::error::invalid_prefix)); + encoder.reset(); + BOOST_TEST(test::failed_with(encoder.flush(), codecs::error::invalid_prefix)); + BOOST_TEST( + test::failed_with(encoder.transform(bytes, characters), codecs::error::invalid_prefix)); + BOOST_TEST_EQ(encoder.output_size(bytes), 0U); + } + auto no_label = codecs::encoder(formats::armor, codecs::secret_operation); + BOOST_TEST(test::failed_with(no_label.receive(characters), codecs::error::invalid_prefix)); + stream_encoder direct{formats::armor}; + BOOST_TEST(test::failed_with(direct.send(bytes), codecs::error::invalid_prefix)); +} + +/** + The encoder's protocol: the BEGIN boundary is written with the first input, not before; a send + while output is pending accepts nothing; a line feed every 64 characters; a finished encoder's + send is {0, finished}. +*/ +void the_encoders_protocol() { + auto encoder = codecs::encoder(formats::armor("A")); + std::array four{}; + BOOST_TEST(test::is_step(encoder.receive(four), 0, codecs::flow::needs_input)); + BOOST_TEST(test::is_step(encoder.send({}), 0, codecs::flow::needs_input)); + BOOST_TEST(test::is_step(encoder.receive(four), 0, codecs::flow::needs_input)); + std::vector const bytes = test::random_bytes(50); + BOOST_TEST(test::is_step(encoder.send(bytes), 50, codecs::flow::output_pending)); + BOOST_TEST(test::is_step(encoder.send(bytes), 0, codecs::flow::output_pending)); + BOOST_TEST(test::is_step(encoder.receive(four), 4, codecs::flow::output_pending)); + BOOST_TEST(std::string_view(four.data(), 4) == "----"); + std::array rest{}; + // The BEGIN line's 14 other characters and a line of 64, the 48 bytes of the line; its line + // feed comes with what follows it, and the 49th and 50th bytes wait for a third or flush. + auto const received = encoder.receive(rest); + BOOST_TEST(test::is_step(received, 14 + 64, codecs::flow::needs_input)); + std::size_t const before_flush = received.has_value() ? received->count : 0; + auto const flushed = encoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + auto const tail = encoder.receive(std::span{rest}.subspan(before_flush)); + BOOST_TEST(tail.has_value() && tail->flow == codecs::flow::finished); + std::string const text = std::string(four.data(), 4) + + std::string(rest.data(), before_flush + (tail ? tail->count : 0)); + BOOST_TEST(text == codecs::encode(formats::armor("A"), bytes).value()); + BOOST_TEST(test::is_step(encoder.send(bytes), 0, codecs::flow::finished)); + BOOST_TEST(test::is_step(encoder.receive(rest), 0, codecs::flow::finished)); +} + +/** + The decoder's protocol: nothing is delivered before 82 characters follow the BEGIN line (the + window that holds the END boundary), then a byte as each group's place gives it; the label is + empty before a successful flush; a send after flush accepts nothing; after an error every call + returns it until reset. +*/ +void the_decoders_protocol() { + std::vector const bytes = test::random_bytes(90); + std::string const text = test::reference_armor_encode("A", bytes); + std::size_t const payload = text.find('\n') + 1; + auto decoder = codecs::decoder(formats::armor("A")); + std::array span{}; + BOOST_TEST(test::is_step(decoder.send(test::characters_of(text).first(payload + 82)), + payload + 82, codecs::flow::output_pending)); + BOOST_TEST(test::is_step(decoder.receive(span), 0, codecs::flow::needs_input)); + BOOST_TEST(decoder.label().empty()); + BOOST_TEST(test::is_step(decoder.send(test::characters_of(text).subspan(payload + 82, 2)), 2, + codecs::flow::output_pending)); + // The first two characters of the payload leave the window: one byte, at the second. + BOOST_TEST(test::is_step(decoder.receive(span), 1, codecs::flow::needs_input)); + BOOST_TEST_EQ(span[0], bytes[0]); + BOOST_TEST(decoder.send(test::characters_of(text).subspan(payload + 84)).has_value()); + std::size_t delivered = 1 + test::receive_until_done(decoder, 3); + auto const flushed = decoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + BOOST_TEST(decoder.label() == "A"); + delivered += test::receive_until_done(decoder, 5); + BOOST_TEST_EQ(delivered, bytes.size()); + BOOST_TEST(test::is_step(decoder.send(test::characters_of("x")), 0, codecs::flow::finished)); + BOOST_TEST(test::is_step(decoder.receive(span), 0, codecs::flow::finished)); + + decoder.reset(); + BOOST_TEST(decoder.label().empty()); + BOOST_TEST(decoder.send(test::characters_of(text + "x")).has_value()); + BOOST_TEST(test::is_flow(decoder.flush(), codecs::flow::output_pending)); + span.fill(0x5a); + BOOST_TEST(test::failed_with(decoder.receive(span), codecs::error::invalid_prefix)); + BOOST_TEST(std::ranges::all_of(span, [](std::uint8_t byte) { return byte == 0x5a; })); + BOOST_TEST( + test::failed_with(decoder.send(test::characters_of("x")), codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_prefix)); + BOOST_TEST(decoder.label().empty()); + decoder.reset(); + std::vector> const whole{test::characters_of(text)}; + auto const again = + test::stream_whole(decoder, std::span const>{whole}, 1); + BOOST_TEST(again.has_value() && again.value() == bytes); +} + +/** + Review Focus 3: an encoder flushed with nothing sent writes the two boundary lines; a decoder + flushed with nothing sent has no BEGIN line, invalid_prefix; the two boundary lines decode to no + bytes, flush finishing at once; transform of empty spans gives the one-shot forms' errors. +*/ +void empty_input() { + std::string_view const empty_armor = "-----BEGIN A-----\n-----END A-----\n"; + auto encoder = codecs::encoder(formats::armor("A")); + std::vector> const no_chunk; + auto const encoded = test::stream_whole(encoder, no_chunk, 1); + BOOST_TEST(encoded.has_value() && std::string(encoded->begin(), encoded->end()) == empty_armor); + auto decoder = codecs::decoder(formats::armor("A")); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_prefix)); + BOOST_TEST( + test::failed_with(encoder.transform(std::span{}, std::span{}), + codecs::error::output_too_small)); + BOOST_TEST( + test::failed_with(decoder.transform(std::span{}, std::span{}), + codecs::error::invalid_prefix)); + decoder.reset(); + BOOST_TEST(decoder.send(test::characters_of(empty_armor)).has_value()); + BOOST_TEST(test::receive_until_done(decoder, 4) == 0); + BOOST_TEST(test::is_flow(decoder.flush(), codecs::flow::finished)); + std::array one{}; + BOOST_TEST(test::is_step(decoder.receive(one), 0, codecs::flow::finished)); + BOOST_TEST(decoder.label() == "A"); +} + +/** + Review Focus 5: a moved-from encoder and decoder, public and secret, convert an input from the + start, and the moved-to one finishes what the source had begun. +*/ +template +void a_moved_from_stream_converts_from_the_start(Encoder encoder, Decoder decoder) { + std::vector const bytes = test::random_bytes(130); + std::string const text = codecs::encode(formats::armor("A"), bytes).value(); + BOOST_TEST(encoder.send(bytes).has_value()); + std::array thirty{}; + BOOST_TEST(test::is_step(encoder.receive(thirty), 30, codecs::flow::output_pending)); + Encoder moved_encoder{std::move(encoder)}; + std::vector> const no_chunk; + auto const rest = test::stream_whole(moved_encoder, no_chunk, 3); + BOOST_TEST(rest.has_value() && + std::string(thirty.data(), 30) + std::string(rest->begin(), rest->end()) == text); + std::vector> const whole{bytes}; + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): Review Focus 5 + auto const again = test::stream_whole(encoder, whole, 7); + BOOST_TEST(again.has_value() && std::string(again->begin(), again->end()) == text); + + std::array first{}; + BOOST_TEST(decoder.send(test::characters_of(text).first(150)).has_value()); + std::size_t const before = decoder.receive(first).value().count; + Decoder moved_decoder{std::move(decoder)}; + std::vector> const tail{test::characters_of(text).subspan(150)}; + auto const decoded_rest = test::stream_whole(moved_decoder, tail, 4); + BOOST_TEST(decoded_rest.has_value()); + if (decoded_rest) { + std::vector joined(first.begin(), + first.begin() + static_cast(before)); + joined.insert(joined.end(), decoded_rest->begin(), decoded_rest->end()); + BOOST_TEST(joined == bytes); + } + BOOST_TEST(moved_decoder.label() == "A"); + std::vector> const whole_text{test::characters_of(text)}; + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): Review Focus 5 + auto const decoded_again = test::stream_whole(decoder, whole_text, 3); + BOOST_TEST(decoded_again.has_value() && *decoded_again == bytes); +} + +/** + A secret stream wipes its pending state (D21): the encoder's 3 bytes of a group and 4 characters, + and the decoder's window and masks (84 bytes), base64's state (6 bytes) and its held and waiting + bytes (2 each), in the source after a move, at reset and at destruction; a public stream wipes + nothing. +*/ +void a_secret_streams_state_is_wiped() { + std::vector const bytes = test::random_bytes(130); + std::string const text = codecs::encode(formats::armor("A"), bytes).value(); + std::array characters{}; + std::optional encoder; + encoder.emplace(formats::armor("A")); + BOOST_TEST(encoder->send(bytes).has_value()); + BOOST_TEST(encoder->receive(std::span{characters}.first(30)).has_value()); + test::clear_wipes(); + secret_stream_encoder moved_encoder{std::move(*encoder)}; + BOOST_TEST_EQ(test::wipes_in(*encoder, 3), 1U); + BOOST_TEST_EQ(test::wipes_in(*encoder, 4), 1U); + test::clear_wipes(); + moved_encoder.reset(); + BOOST_TEST_EQ(test::wipes_in(moved_encoder, 3), 1U); + BOOST_TEST_EQ(test::wipes_in(moved_encoder, 4), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(encoder, 4), 1U); + + std::optional decoder; + decoder.emplace(formats::armor("A")); + BOOST_TEST(decoder->send(test::characters_of(text)).has_value()); + BOOST_TEST(decoder->flush().has_value()); + test::clear_wipes(); + secret_stream_decoder moved_decoder{std::move(*decoder)}; + BOOST_TEST_EQ(test::wipes_in(*decoder, 84), 1U); + BOOST_TEST_EQ(test::wipes_in(*decoder, 6), 1U); + BOOST_TEST_EQ(test::wipes_in(*decoder, 2), 2U); + test::clear_wipes(); + moved_decoder.reset(); + BOOST_TEST_EQ(test::wipes_in(moved_decoder, 84), 1U); + BOOST_TEST_EQ(test::wipes_in(moved_decoder, 6), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(decoder, 84), 1U); + // The verdict's copy of the reader is wiped too: the one-shot reading of the rest at flush. + decoder.emplace(formats::armor("A")); + BOOST_TEST(decoder->send(test::characters_of(text)).has_value()); + BOOST_TEST(decoder->flush().has_value()); + test::clear_wipes(); + std::array span{}; + BOOST_TEST(decoder->receive(span).has_value()); + BOOST_TEST_EQ(test::wipes.count, 2U); + + test::clear_wipes(); + { + stream_encoder public_encoder{formats::armor("A")}; + BOOST_TEST(public_encoder.send(bytes).has_value()); + BOOST_TEST(public_encoder.receive(characters).has_value()); + public_encoder.reset(); + stream_decoder public_decoder{formats::armor("A")}; + BOOST_TEST(public_decoder.send(test::characters_of(text)).has_value()); + BOOST_TEST(public_decoder.flush().has_value()); + public_decoder.reset(); + } + BOOST_TEST_EQ(test::wipes.count, 0U); +} + +} // namespace + +int main() { + every_file_through_every_chunking(); + a_thousand_random_inputs(); + invalid_texts_give_the_one_shot_error_after_flush(); + an_armor_as_a_stream(); + a_configuration_fault_by_the_first_call(); + an_encoders_configuration_fault_by_the_first_call(); + the_encoders_protocol(); + the_decoders_protocol(); + empty_input(); + a_moved_from_stream_converts_from_the_start(codecs::encoder(formats::armor("A")), + codecs::decoder(formats::armor("A"))); + a_moved_from_stream_converts_from_the_start( + codecs::encoder(formats::armor("A"), codecs::secret_operation), + codecs::decoder(formats::armor("A"), codecs::secret_operation)); + a_secret_streams_state_is_wiped(); + return boost::report_errors(); +} diff --git a/test/armor_test.cpp b/test/armor_test.cpp new file mode 100644 index 0000000..a95258e --- /dev/null +++ b/test/armor_test.cpp @@ -0,0 +1,702 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The armor, RFC 7468's strict textual encoding (D13, the spec's "Format: armor (RFC 7468)"): +// RFC 7468's examples and OpenSSL's PEM files of test/data/armor/, read at run time on every lane +// (support/armor_files.hpp), each decoded with the format configured with its label and with none, +// to its DER, through the buffer, token, default and typed forms (its parts among them), and +// encoded back to its text byte for byte; the spec's scenario "RFC 7468's examples and the wrong +// label"; lines ended by a carriage return and a line feed, and no final line ending; every error +// of the format, one input each (explanatory text before the BEGIN line and after the END line, an +// RFC 1421 header, a space in a line, a 65-character line, a short line before the last, an END +// label under another BEGIN label among them), and inputs of two faults giving the format's order +// (the boundaries, the lines, then base64's lowest value, B23); a configuration fault first; every +// byte value as a character at every place of a text against the plain reference of +// support/armor_reference.hpp, `char` signed (Review Focus 1); random armors against the +// reference; empty input in every form (Review Focus 3: the armor of no bytes is the two boundary +// lines); the bounds saturating at SIZE_MAX (Review Focus 2); over{armor("PUBLIC KEY"), hex}. +// Input and output must not overlap (Review Focus 4 does not apply). + +#include "support/counting.hpp" + +#include "support/armor_files.hpp" +#include "support/armor_reference.hpp" +#include "support/samples.hpp" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace detail = webcpp::codecs::detail; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +using armor_codec = codecs::codec; + +constexpr std::size_t size_maximum = std::numeric_limits::max(); + +// The format: a label held in place, configured by a call; with none it decodes any. +static_assert(codecs::format); +static_assert(formats::armor_t::name == "armor"); +static_assert(std::is_trivially_copyable_v); +static_assert(formats::armor.label().empty()); +static_assert(formats::armor("PUBLIC KEY").label() == "PUBLIC KEY"); +static_assert(std::is_same_v); + +// Its codec: constant time, with a configuration to check (B23): a label over 64 characters or +// outside RFC 7468's grammar. +static_assert(armor_codec::constant_time); +static_assert(codecs::detail::has_configuration_fault); +static_assert(!codecs::detail::configuration_fault_of(formats::armor).has_value()); +static_assert(!codecs::detail::configuration_fault_of(formats::armor("PUBLIC KEY")).has_value()); +static_assert(!codecs::detail::configuration_fault_of(formats::armor("X.509 A-B C")).has_value()); +constexpr std::array label_65_characters = [] { + std::array characters{}; + characters.fill('A'); + return characters; +}(); +constexpr std::string_view label_65{label_65_characters.data(), label_65_characters.size()}; +static_assert(!codecs::detail::configuration_fault_of(formats::armor(label_65.substr(1)))); +static_assert(codecs::detail::configuration_fault_of(formats::armor(label_65)) == + codecs::error::invalid_prefix); +// An overflowed label holds nothing: its accessor is empty, and the fault is the configuration's. +static_assert(formats::armor(label_65).label().empty()); +static_assert(codecs::detail::configuration_fault_of(formats::armor("A--B")) == + codecs::error::invalid_prefix); +static_assert(codecs::detail::configuration_fault_of(formats::armor("A B")) == + codecs::error::invalid_prefix); +static_assert(codecs::detail::configuration_fault_of(formats::armor(" A")) == + codecs::error::invalid_prefix); +static_assert(codecs::detail::configuration_fault_of(formats::armor("A-")) == + codecs::error::invalid_prefix); +static_assert(codecs::detail::configuration_fault_of(formats::armor("A\tB")) == + codecs::error::invalid_prefix); +static_assert(codecs::detail::configuration_fault_of(formats::armor(std::string_view{"\x7f"})) == + codecs::error::invalid_prefix); +static_assert(detail::armor_label_is_valid("A") && detail::armor_label_is_valid("A-B C!~")); +static_assert(!detail::armor_label_is_valid("") && !detail::armor_label_is_valid("-A") && + !detail::armor_label_is_valid("A -B")); + +// The sizes: "-----BEGIN PUBLIC KEY-----\n" is 27 characters, "-----END PUBLIC KEY-----\n" 25, +// and the 124 symbols of 91 bytes two lines, each with its line feed. +constexpr std::array spki_size_bytes{}; +static_assert(codecs::encoded_size(formats::armor("PUBLIC KEY"), std::span{}) == + 52); +static_assert(codecs::encoded_size(formats::armor("PUBLIC KEY"), spki_size_bytes) == 178); +// No label, nothing to encode: 0, which every encode refuses with invalid_prefix; a configuration +// fault is 0 too (B23). +static_assert(codecs::encoded_size(formats::armor, spki_size_bytes) == 0); +static_assert(codecs::encoded_size(formats::armor(label_65), spki_size_bytes) == 0); +// The bound counts the longest label: 160 characters of boundaries. +static_assert(armor_codec::max_encoded_size(0) == 160); +static_assert(armor_codec::max_encoded_size(1) == 165); +static_assert(armor_codec::max_encoded_size(48) == 225); +static_assert(armor_codec::max_encoded_size(49) == 230); +static_assert(armor_codec::max_encoded_size(91) == 286); + +// Review Focus 2: the bound saturates at SIZE_MAX where base64's does, and past it where the line +// feeds and the boundaries no longer fit, near SIZE_MAX / 65 * 48 bytes (65 characters a line of 48 +// bytes); the core then refuses the input before reading it. +/** The most bytes whose armor's bound fits in `std::size_t`, by bisection. */ +constexpr std::size_t largest_bounded_input() { + std::size_t low = 0; + std::size_t high = size_maximum; + while (high - low > 1) { + std::size_t const middle = low + ((high - low) / 2); + if (armor_codec::max_encoded_size(middle) == size_maximum) { + high = middle; + } else { + low = middle; + } + } + return low; +} + +constexpr std::size_t bounded = largest_bounded_input(); +static_assert(armor_codec::max_encoded_size(bounded) < size_maximum); +static_assert(armor_codec::max_encoded_size(bounded + 1) == size_maximum); +static_assert(armor_codec::max_encoded_size(size_maximum) == size_maximum); +static_assert(bounded > (size_maximum / 65 * 48) - 1024 && + bounded < (size_maximum / 65 * 48) + 1024); +static_assert(armor_codec::max_encoded_size(bounded) > size_maximum - 256); +static_assert(!codecs::detail::input_size_fault(formats::armor("A"), bounded).has_value()); +static_assert(codecs::detail::input_size_fault(formats::armor("A"), bounded + 1) == + codecs::error::input_too_long); +static_assert(armor_codec::max_decoded_size(0) == 0); +static_assert(armor_codec::max_decoded_size(52) == 39); +static_assert(armor_codec::max_decoded_size(size_maximum) == (size_maximum / 4 * 3) + 2); + +// The default results (D9): in place for a size known at compile time, the heap otherwise; the +// parts decode only. +static_assert( + std::is_same_v{})), + codecs::result>>); +static_assert(std::is_same_v const&>())), + codecs::result>>); +static_assert(std::is_same_v>>); +static_assert(std::is_same_v(formats::armor, + std::string_view{})), + codecs::result>); +static_assert(codecs::decodable); +static_assert(!codecs::encodable); +static_assert(decltype(formats::armor_parts{}.label)::capacity() == 64); + +/** `text` with `inserted` at `place`. */ +std::string inserted_at(std::string_view text, std::size_t place, std::string_view inserted) { + std::string changed{text}; + changed.insert(place, inserted); + return changed; +} + +/** + Checks that `format` refuses `text` with `expected` in every form of decode, writing nothing, and, + unless `configured_fault`, that the plain reference agrees. +*/ +void expect_refusal(formats::armor_t const& format, std::string_view text, codecs::error expected, + bool configured_fault = false) { + auto const defaulted = codecs::decode(format, text); + BOOST_TEST(!defaulted.has_value() && defaulted.error() == expected); + if (!configured_fault) { + auto const size = armor_codec::decoded_size(format, text); + BOOST_TEST(!size.has_value() && size.error() == expected); + std::array codec_buffer{}; + auto const codec_written = armor_codec::decode(format, text, std::span{codec_buffer}); + BOOST_TEST(!codec_written.has_value() && codec_written.error() == expected); + } + std::array buffer{}; + buffer.fill(0x5a); + auto const written = codecs::decode(format, text, std::span{buffer}); + BOOST_TEST(!written.has_value() && written.error() == expected); + BOOST_TEST(std::ranges::all_of(buffer, [](std::uint8_t byte) { return byte == 0x5a; })); + std::vector appended{0x5a}; + auto const token = codecs::decode(format, text, tokens::append_to(appended)); + BOOST_TEST(!token.has_value() && token.error() == expected); + BOOST_TEST(appended == std::vector{0x5a}); + auto const typed = codecs::decode>(format, text); + BOOST_TEST(!typed.has_value() && typed.error() == expected); + auto const parts = codecs::decode(format, text); + BOOST_TEST(!parts.has_value() && parts.error() == expected); + if (!configured_fault) { + auto const reference = test::reference_armor_decode(text, format.label()); + if (!BOOST_TEST(reference.fault == std::optional{expected})) { + std::printf("refused text: [%.*s]\n", static_cast(text.size()), text.data()); + } + } +} + +/** + Checks that `format` decodes `text` to `expected` in the buffer, token, default and typed forms, + its parts giving `label`, and that the reference agrees. +*/ +void expect_decodes(formats::armor_t const& format, std::string_view text, + std::span expected, std::string_view label) { + auto const defaulted = codecs::decode(format, text); + if (!BOOST_TEST(defaulted.has_value() && std::ranges::equal(defaulted.value(), expected))) { + std::printf("not decoded: [%.*s]\n", static_cast(text.size()), text.data()); + return; + } + auto const size = armor_codec::decoded_size(format, text); + BOOST_TEST(size.has_value() && size.value() == expected.size()); + BOOST_TEST(codecs::max_decoded_size(format, text) >= expected.size()); + std::vector buffer(expected.size() + 1, 0x5a); + auto const written = codecs::decode(format, text, std::span{buffer}); + BOOST_TEST(written.has_value() && written.value() == expected.size()); + BOOST_TEST(std::ranges::equal(std::span{buffer}.first(expected.size()), expected)); + BOOST_TEST_EQ(buffer.back(), 0x5a); + if (!expected.empty()) { + auto const short_buffer = + codecs::decode(format, text, std::span{buffer}.first(expected.size() - 1)); + BOOST_TEST(!short_buffer.has_value() && + short_buffer.error() == codecs::error::output_too_small); + } + std::vector appended{0x5a}; + BOOST_TEST(codecs::decode(format, text, tokens::append_to(appended)).has_value()); + BOOST_TEST_EQ(appended.size(), expected.size() + 1); + auto const typed = codecs::decode(format, text); + BOOST_TEST(typed.has_value() && typed->size() == expected.size()); + auto const parts = codecs::decode(format, text); + BOOST_TEST(parts.has_value() && parts->label.view() == label && + std::ranges::equal(parts->data, expected)); + auto const reference = test::reference_armor_decode(text, format.label()); + BOOST_TEST(!reference.fault.has_value() && reference.label == label && + std::ranges::equal(reference.bytes, expected)); +} + +/** + Checks that `bytes` encode under `label` to `text` in every form of encode, and that the + reference writes the same text. +*/ +void expect_encodes(std::string_view label, std::span bytes, + std::string_view text) { + auto const format = formats::armor(label); + auto const encoded = + codecs::encode(format, std::vector(bytes.begin(), bytes.end())); + BOOST_TEST(encoded.has_value() && encoded.value() == text); + BOOST_TEST_EQ(codecs::encoded_size(format, bytes), text.size()); + std::vector buffer(text.size() + 1, '~'); + auto const written = codecs::encode(format, bytes, std::span{buffer}); + BOOST_TEST(written.has_value() && written.value() == text.size()); + BOOST_TEST(std::string_view(buffer.data(), text.size()) == text && buffer.back() == '~'); + auto const short_buffer = + codecs::encode(format, bytes, std::span{buffer}.first(text.size() - 1)); + BOOST_TEST(!short_buffer.has_value() && + short_buffer.error() == codecs::error::output_too_small); + auto const returned = codecs::encode(format, bytes, tokens::return_string); + BOOST_TEST(returned.has_value() && returned.value() == text); + std::string appended{"x"}; + BOOST_TEST(codecs::encode(format, bytes, tokens::append_to(appended)).has_value()); + BOOST_TEST(appended == "x" + std::string{text}); + BOOST_TEST(test::reference_armor_encode(label, bytes) == text); +} + +/** + The vector of the file called `name`; the process stops with a failure when there is none, so a + renamed file is not a silent pass. +*/ +test::armor_vector const& named_vector(std::vector const& vectors, + std::string_view name) { + auto const found = std::ranges::find_if( + vectors, [&](test::armor_vector const& vector) { return vector.file.name == name; }); + if (found == vectors.end()) { + std::printf("no armor vector named %.*s\n", static_cast(name.size()), name.data()); + std::abort(); + } + return *found; +} + +/** + The spec's "RFC 7468's examples and the wrong label", and "OpenSSL's PEM" on OpenSSL's files: + every file of test/data/armor/ decodes, with the format of its label and with none, to its DER in + every form and encodes back to its text, byte for byte; the certificate with armor("PUBLIC KEY") + is invalid_prefix, and Figure 7, explanatory text before the BEGIN line, is refused. +*/ +void rfc7468_examples_and_openssl_files() { + std::vector const vectors = test::read_armor_vectors(); + BOOST_TEST_EQ(vectors.size(), test::armor_files.size()); + for (test::armor_vector const& vector : vectors) { + expect_decodes(formats::armor(vector.file.label), vector.text, vector.der, + vector.file.label); + expect_decodes(formats::armor, vector.text, vector.der, vector.file.label); + expect_encodes(vector.file.label, vector.der, vector.text); + if (vector.file.label != "PUBLIC KEY") { + expect_refusal(formats::armor("PUBLIC KEY"), vector.text, + codecs::error::invalid_prefix); + } + // A secret result and a typed decode into a secure type of the DER's size. + auto const secret = codecs::decode(formats::armor, vector.text, tokens::secret); + BOOST_TEST(secret.has_value() && std::ranges::equal(secret->view(), vector.der)); + } + // OpenSSL's x509 writes Figure 6 again, byte for byte, and its P-256 key is 91 bytes, 178 + // characters. + test::armor_vector const& certificate = named_vector(vectors, "rfc7468-figure-06-certificate"); + test::armor_vector const& openssl_certificate = + named_vector(vectors, "openssl-x509-certificate"); + test::armor_vector const& openssl_key = named_vector(vectors, "openssl-p256-spki"); + BOOST_TEST(certificate.text == openssl_certificate.text); + BOOST_TEST_EQ(openssl_key.der.size(), 91U); + BOOST_TEST_EQ(openssl_key.text.size(), 178U); + auto const key = + codecs::decode>(formats::armor("PUBLIC KEY"), openssl_key.text); + BOOST_TEST(key.has_value() && std::ranges::equal(key->bytes(), openssl_key.der)); + // The spec's scenario: the certificate example with armor("PUBLIC KEY"). + expect_refusal(formats::armor("PUBLIC KEY"), certificate.text, codecs::error::invalid_prefix); + auto const explanatory = + test::read_armor_data(std::string{test::armor_explanatory_file} + ".pem"); + BOOST_TEST(explanatory.has_value()); + if (explanatory) { + BOOST_TEST(explanatory->starts_with("Subject: CN=Atlantis\n")); + expect_refusal(formats::armor, *explanatory, codecs::error::invalid_prefix); + expect_refusal(formats::armor("CERTIFICATE"), *explanatory, codecs::error::invalid_prefix); + // From its BEGIN line on, it is a strict certificate. + std::size_t const begin = explanatory->find("-----BEGIN"); + auto const strict = codecs::decode(formats::armor("CERTIFICATE"), + std::string_view{*explanatory}.substr(begin)); + BOOST_TEST(strict.has_value()); + } +} + +/** + Lines ended by a carriage return and a line feed, each or some, and no final line ending, with or + without a carriage return before it: the same bytes (B26). +*/ +void the_line_endings() { + std::vector const bytes = test::random_bytes(100); + std::string const text = test::reference_armor_encode("PUBLIC KEY", bytes); + std::string const crlf = test::with_carriage_returns(text); + auto const format = formats::armor("PUBLIC KEY"); + expect_decodes(format, crlf, bytes, "PUBLIC KEY"); + expect_decodes(format, std::string_view{text}.substr(0, text.size() - 1), bytes, "PUBLIC KEY"); + expect_decodes(format, std::string_view{crlf}.substr(0, crlf.size() - 2), bytes, "PUBLIC KEY"); + // A carriage return on the BEGIN line, on one line of the payload, on the END line alone. + std::size_t const first_line = text.find('\n'); + expect_decodes(format, inserted_at(text, first_line, "\r"), bytes, "PUBLIC KEY"); + expect_decodes(format, inserted_at(text, first_line + 65, "\r"), bytes, "PUBLIC KEY"); + expect_decodes(format, inserted_at(text, text.size() - 1, "\r"), bytes, "PUBLIC KEY"); + // The last line of the payload ended by a carriage return and a line feed, the others not. + std::size_t const end_line = text.rfind("-----END"); + expect_decodes(format, inserted_at(text, end_line - 1, "\r"), bytes, "PUBLIC KEY"); + // A carriage return with no line feed after it is no line ending. + expect_refusal(format, std::string_view{crlf}.substr(0, crlf.size() - 1), + codecs::error::invalid_prefix); +} + +/** + Every error of the format, one input each, and inputs of two faults: the boundaries' first, then + the lines', then base64's lowest value (B23); a configuration fault before them all. +*/ +void every_error_and_the_order() { + constexpr auto prefix = codecs::error::invalid_prefix; + constexpr auto length = codecs::error::invalid_length; + constexpr auto character = codecs::error::invalid_character; + constexpr auto padding = codecs::error::invalid_padding; + std::vector const bytes = test::random_bytes(100); + std::string const text = test::reference_armor_encode("PUBLIC KEY", bytes); + auto const format = formats::armor("PUBLIC KEY"); + std::size_t const payload = text.find('\n') + 1; + std::size_t const end_line = text.rfind("-----END"); + // The boundaries. + expect_refusal(format, "", prefix); + expect_refusal(formats::armor, "", prefix); + expect_refusal(format, text.substr(0, payload), prefix); + expect_refusal(format, text.substr(0, payload - 1), prefix); + expect_refusal(format, text.substr(0, end_line), prefix); + expect_refusal(format, text.substr(payload), prefix); + expect_refusal(format, "-----BEGIN PUBLIC KEY----\n" + text.substr(payload), prefix); + expect_refusal(format, "-----begin PUBLIC KEY-----\n" + text.substr(payload), prefix); + expect_refusal(format, "-----BEGIN PUBLIC KEY-----\n" + text.substr(payload), prefix); + expect_refusal(format, "-----BEGIN PUBLIC KEY----- \n" + text.substr(payload), prefix); + expect_refusal(formats::armor("PRIVATE KEY"), text, prefix); + // The spec's END label under another BEGIN label. + expect_refusal(format, text.substr(0, end_line) + "-----END PRIVATE KEY-----\n", prefix); + expect_refusal(formats::armor, text.substr(0, end_line) + "-----END PRIVATE KEY-----\n", + prefix); + expect_refusal(format, text.substr(0, end_line) + "-----END PUBLIC KEY----\n", prefix); + expect_refusal(format, text.substr(0, end_line) + "-----END PUBLIC KEY-----X\n", prefix); + // Labels outside the grammar, or empty, in the text of a format with none. + std::string const no_label = test::reference_armor_encode("", bytes); + expect_refusal(formats::armor, no_label, prefix); + expect_refusal(formats::armor, test::reference_armor_encode("A--B", bytes), prefix); + expect_refusal(formats::armor, test::reference_armor_encode(" A", bytes), prefix); + expect_refusal(formats::armor, test::reference_armor_encode(label_65, bytes), prefix); + expect_decodes(formats::armor, test::reference_armor_encode(label_65.substr(1), bytes), bytes, + label_65.substr(1)); + // Explanatory text before the BEGIN line and after the END line; lines after the END line. + expect_refusal(format, "Subject: CN=Atlantis\n" + text, prefix); + expect_refusal(format, text + "Subject: CN=Atlantis\n", prefix); + expect_refusal(format, text + "\n", prefix); + expect_refusal(format, text + " ", prefix); + // Two armors: the first's END and the second's BEGIN line are short lines of the payload. + expect_refusal(format, text + text, length); + // The lines: 65 characters, a short line before the last, an empty line, an RFC 1421 header, + // a space added to a line, the last line of 65. + std::string const long_text = + test::reference_armor_encode("PUBLIC KEY", test::random_bytes(200)); + std::size_t const long_payload = long_text.find('\n') + 1; + expect_refusal(format, inserted_at(long_text, long_payload + 10, "A"), length); + expect_refusal(format, inserted_at(long_text, long_payload + 64, "AAAA"), length); + expect_refusal(format, inserted_at(long_text, long_payload + 10, "\n"), length); + expect_refusal(format, inserted_at(long_text, long_payload + 10, "\r\n"), length); + expect_refusal(format, inserted_at(long_text, long_payload + 65, "\n"), length); + expect_refusal(format, inserted_at(long_text, long_payload, "\n"), length); + expect_refusal(format, inserted_at(text, end_line, "\n"), length); + expect_refusal(format, inserted_at(text, end_line - 1, "A"), length); + expect_refusal( + format, + inserted_at(text, payload, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,F8B1C1E5\n\n"), + length); + expect_refusal(format, inserted_at(long_text, long_payload + 30, " "), length); + expect_refusal(format, inserted_at(long_text, long_payload + 30, "\t"), length); + // A line feed after a carriage return among the symbols: a line of 63, then the line ending. + std::string short_crlf = long_text; + short_crlf[long_payload + 63] = '\r'; + expect_refusal(format, short_crlf, length); + // A space, a tab or a carriage return in place of a symbol: base64's invalid_character. + for (char const replacement : {' ', '\t', '\r', '*', '-', ':', '\0', static_cast(0xc1)}) { + std::string replaced = long_text; + replaced[long_payload + 30] = replacement; + expect_refusal(format, replaced, character); + } + // base64's own: a count of symbols that is no multiple of 4, `=` out of place, trailing bits. + auto const one_line = [](std::string_view symbols) { + return "-----BEGIN A-----\n" + std::string{symbols} + "\n-----END A-----\n"; + }; + expect_refusal(formats::armor("A"), one_line("Zm9vY"), length); + expect_refusal(formats::armor("A"), one_line("Zm9"), length); + expect_refusal(formats::armor("A"), one_line("Zh=="), padding); + expect_refusal(formats::armor("A"), one_line("Zg==Zg=="), padding); + expect_decodes(formats::armor("A"), one_line("Zm9vYmFy"), test::bytes_of("foobar"), "A"); + // Two faults: the boundaries before the lines, the lines before base64, base64's lowest. + std::string bad_symbol = long_text; + bad_symbol[long_payload + 5] = '*'; + expect_refusal(formats::armor("PRIVATE KEY"), inserted_at(long_text, long_payload + 10, "A"), + prefix); + expect_refusal(format, inserted_at(bad_symbol, long_payload + 64, "A"), length); + expect_refusal(format, "Subject: x\n" + bad_symbol, prefix); + expect_refusal(formats::armor("A"), one_line("Zh=*"), character); + expect_refusal(formats::armor("A"), one_line("Zh="), length); + expect_refusal(formats::armor("A"), one_line("Zg==Zh="), length); + // A configuration fault before them all (B23), in every form. + expect_refusal(formats::armor(label_65), bad_symbol, prefix, true); + expect_refusal(formats::armor("A--B"), "", prefix, true); + expect_refusal(formats::armor("A--B"), test::reference_armor_encode("A--B", bytes), prefix, + true); +} + +/** + Encode refuses a format with no label and a configuration fault with invalid_prefix, in every + form, writing nothing; its size is 0. +*/ +void encode_with_no_label() { + std::vector const bytes = test::random_bytes(10); + for (formats::armor_t const& format : + {formats::armor, formats::armor(label_65), formats::armor("A--B")}) { + auto const defaulted = codecs::encode(format, bytes); + BOOST_TEST(!defaulted.has_value() && defaulted.error() == codecs::error::invalid_prefix); + std::array buffer{}; + buffer.fill('~'); + auto const written = codecs::encode(format, bytes, std::span{buffer}); + BOOST_TEST(!written.has_value() && written.error() == codecs::error::invalid_prefix); + BOOST_TEST(std::ranges::all_of(buffer, [](char character) { return character == '~'; })); + std::string appended{"x"}; + auto const token = codecs::encode(format, bytes, tokens::append_to(appended)); + BOOST_TEST(!token.has_value() && token.error() == codecs::error::invalid_prefix); + BOOST_TEST(appended == "x"); + auto const fixed = codecs::encode(format, std::array{1, 2, 3}); + BOOST_TEST(!fixed.has_value() && fixed.error() == codecs::error::invalid_prefix); + BOOST_TEST_EQ(codecs::encoded_size(format, bytes), 0U); + } + std::array buffer{}; + auto const codec_written = armor_codec::encode(formats::armor, bytes, std::span{buffer}); + BOOST_TEST(!codec_written.has_value() && + codec_written.error() == codecs::error::invalid_prefix); +} + +/** + Checks the reading of `text` by `format` against the plain reference: the same fault, or the same + bytes, through decode and decoded_size. +*/ +void expect_the_reference_reading(formats::armor_t const& format, std::string_view text) { + test::armor_reference_reading const reference = + test::reference_armor_decode(text, format.label()); + auto const size = armor_codec::decoded_size(format, text); + std::vector buffer(codecs::max_decoded_size(format, text)); + auto const written = codecs::decode(format, text, std::span{buffer}); + if (reference.fault) { + bool const same = !size.has_value() && size.error() == *reference.fault && + !written.has_value() && written.error() == *reference.fault; + if (!BOOST_TEST(same)) { + std::printf("reference %d: [%.*s]\n", static_cast(*reference.fault), + static_cast(text.size()), text.data()); + } + return; + } + BOOST_TEST(size.has_value() && size.value() == reference.bytes.size()); + BOOST_TEST(written.has_value() && written.value() == reference.bytes.size()); + BOOST_TEST( + std::ranges::equal(std::span{buffer}.first(reference.bytes.size()), reference.bytes)); +} + +/** + Review Focus 1: each of the 256 byte values as a character, `char` signed, at each place of a + text and inserted there, with no label in the format and with its own: the verdict and the bytes + equal the plain reference's. NUL, 0x80 to 0xff, the characters one past each range (the slash, + the colon, the at sign, `[`, the backquote, `{`), `=`, `-`, the space, the carriage return and the + line feed are among them. The places are every one of a text of two lines, its padding written + and not, and of a text of no bytes. +*/ +void every_byte_value_as_a_character() { + std::vector const bytes = test::random_bytes(52); + for (std::string const& base : { + test::reference_armor_encode("A B", bytes), + test::reference_armor_encode("A B", std::span{bytes}.first(49)), + test::reference_armor_encode("A B", {}), + }) { + for (std::size_t place = 0; place <= base.size(); ++place) { + for (unsigned value = 0; value < 256; ++value) { + auto const character = static_cast(static_cast(value)); + std::string replaced = base; + if (place == base.size()) { + replaced.push_back(character); + } else { + replaced[place] = character; + } + expect_the_reference_reading(formats::armor, replaced); + // Every value at every place for the format with no label; one in eight inserted, + // and for the format with its label. + if (value % 8 == place % 8) { + expect_the_reference_reading(formats::armor("A B"), replaced); + expect_the_reference_reading(formats::armor, + inserted_at(base, place, {&character, 1})); + } + } + } + } +} + +/** + Random armors against the reference: the bytes of 0 to 300 bytes under a label of the grammar, + encoded and decoded back in every form, and texts near them (characters replaced, inserted or + removed, line endings changed) read as the reference reads them. +*/ +void random_armors() { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): a fixed seed + std::mt19937_64 generator{20261129}; + constexpr std::array labels{"PUBLIC KEY", "X509 CRL", "A", "a-b c", "!~"}; + constexpr std::string_view pool = "\n\r -=A/+aZ9:*"; + for (int iteration = 0; iteration < 600; ++iteration) { + std::vector bytes(generator() % 301); + for (std::uint8_t& byte : bytes) { + byte = static_cast(generator()); + } + std::string_view const label = labels[generator() % labels.size()]; + std::string const text = test::reference_armor_encode(label, bytes); + if (iteration % 8 == 0) { + expect_encodes(label, bytes, text); + expect_decodes(formats::armor(label), text, bytes, label); + } + expect_decodes(formats::armor, text, bytes, label); + std::string near = iteration % 2 == 0 ? text : test::with_carriage_returns(text); + for (std::size_t change = generator() % 4; change > 0; --change) { + std::size_t const place = generator() % (near.size() + 1); + char const character = pool[generator() % pool.size()]; + switch (generator() % 3) { + case 0: near.insert(place, 1, character); break; + case 1: + if (place < near.size()) { + near.erase(place, 1); + } + break; + default: + if (place < near.size()) { + near[place] = character; + } + break; + } + } + expect_the_reference_reading(formats::armor, near); + expect_the_reference_reading(formats::armor(label), near); + } +} + +/** + Review Focus 3: the armor of no bytes is the two boundary lines, in every form of encode; an empty + text is invalid_prefix in every form of decode; the two boundary lines decode to no bytes. +*/ +void empty_input_in_every_form() { + std::string_view const empty_armor = "-----BEGIN A B-----\n-----END A B-----\n"; + expect_encodes("A B", {}, empty_armor); + std::array const nothing{}; + auto const fixed = codecs::encode(formats::armor("A B"), nothing); + static_assert(std::is_same_v> const>); + BOOST_TEST(fixed.has_value() && fixed->view() == empty_armor); + auto const secret = codecs::encode(formats::armor("A B"), nothing, tokens::secret); + BOOST_TEST(secret.has_value() && secret->view() == empty_armor); + expect_decodes(formats::armor("A B"), empty_armor, {}, "A B"); + expect_decodes(formats::armor, empty_armor, {}, "A B"); + expect_decodes(formats::armor, test::with_carriage_returns(empty_armor), {}, "A B"); + expect_decodes(formats::armor, empty_armor.substr(0, empty_armor.size() - 1), {}, "A B"); + auto const fixed_back = codecs::decode(formats::armor, fixed.value()); + BOOST_TEST(fixed_back.has_value() && fixed_back->size() == 0); + auto const into_array = + codecs::decode>(formats::armor, empty_armor); + BOOST_TEST(into_array.has_value()); + expect_refusal(formats::armor, "", codecs::error::invalid_prefix); + expect_refusal(formats::armor("A B"), "", codecs::error::invalid_prefix); + auto const empty_buffer = + codecs::decode(formats::armor, std::string_view{}, std::span{}); + BOOST_TEST(!empty_buffer.has_value() && empty_buffer.error() == codecs::error::invalid_prefix); + BOOST_TEST_EQ(codecs::max_decoded_size(formats::armor, std::string_view{}), 0U); +} + +/** The forms of the armor that hold their results in place allocate nothing. */ +void the_fixed_forms_allocate_nothing() { + std::array const digest = test::digest_bytes(); + auto const encoded = codecs::encode(formats::armor("PUBLIC KEY"), digest); + bool volatile verdict = false; + test::expect_no_allocation("the armor's fixed forms", [&] { + auto const text = codecs::encode(formats::armor("PUBLIC KEY"), digest); + auto const back = codecs::decode(formats::armor, text.value()); + auto const into_array = + codecs::decode>(formats::armor, encoded.value().view()); + std::size_t const back_size = back.has_value() ? back->size() : 0; + verdict = back_size == 32 && into_array.has_value() && into_array.value() == digest; + }); + BOOST_TEST(verdict); +} + +/** The armor composes: over{armor("PUBLIC KEY"), hex} armors hex's text, and decodes back. */ +void over_the_armor() { + std::vector const bytes = test::random_bytes(40); + auto const chain = codecs::over{formats::armor("PUBLIC KEY"), formats::hex}; + auto const text = codecs::encode(chain, bytes); + std::string const hex_text = codecs::encode(formats::hex, bytes).value(); + BOOST_TEST(text.has_value() && text.value() == test::reference_armor_encode( + "PUBLIC KEY", test::bytes_of(hex_text))); + auto const back = codecs::decode(chain, text.value()); + BOOST_TEST(back.has_value() && back.value() == bytes); + auto const refused = + codecs::decode(codecs::over{formats::armor("PRIVATE KEY"), formats::hex}, text.value()); + BOOST_TEST(!refused.has_value() && refused.error() == codecs::error::invalid_prefix); + auto const unlabelled = codecs::encode(codecs::over{formats::armor, formats::hex}, bytes); + BOOST_TEST(!unlabelled.has_value() && unlabelled.error() == codecs::error::invalid_prefix); +} + +/** + armor_parts is public: a PRIVATE KEY payload goes to a secret type with the label in the format, + and the format gives its label back. +*/ +void a_private_key_into_a_secret_type() { + std::vector const key{0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03}; + auto const format = formats::armor("PRIVATE KEY"); + BOOST_TEST(format.label() == "PRIVATE KEY"); + auto const text = codecs::encode(format, key); + BOOST_TEST(text.has_value()); + auto const secret = codecs::decode(format, text.value()); + BOOST_TEST(secret.has_value() && std::ranges::equal(secret->view(), key)); + BOOST_TEST( + codecs::decode(formats::armor("PUBLIC KEY"), text.value()) + .error() == codecs::error::invalid_prefix); +} + +} // namespace + +int main() { + rfc7468_examples_and_openssl_files(); + a_private_key_into_a_secret_type(); + the_line_endings(); + every_error_and_the_order(); + encode_with_no_label(); + every_byte_value_as_a_character(); + random_armors(); + empty_input_in_every_form(); + the_fixed_forms_allocate_nothing(); + over_the_armor(); + return boost::report_errors(); +} diff --git a/test/base32_stream_test.cpp b/test/base32_stream_test.cpp new file mode 100644 index 0000000..10d1d0f --- /dev/null +++ b/test/base32_stream_test.cpp @@ -0,0 +1,766 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// base32 and base32hex as streams (D20): encoder(base32) and decoder(base32) are its one-shot +// transformers always and its stream transformers through stream_codec, whose encoder holds the up +// to four bytes of a group and the characters its output had no room for, and whose decoder the +// bits of a group, the padding seen and the fault masks (D20's table), and with the padding written +// the bytes of a group from its fourth place on until the next character or the flush. RFC 4648's +// vectors, bytes of 0 to 1000, and 1000 random inputs, in both alphabets and both paddings, equal +// the one-shot forms for every chunking (support/chunkings.hpp) and output spans of one and 1024, +// and every invalid text gives the one-shot form's error after flush, every byte value as a +// character at each place of a group among them (Review Focus 1); the spec's "Send while output is +// pending", "After the end and after an error", "The call that fails writes nothing" (B44) and "A +// file in base32 with no heap"; empty input (Review Focus 3); a moved-from stream converts from the +// start (Review Focus 5); a secret stream wipes its pending state, as secure's wipe seam records +// it. base32 has no configuration to be at fault, so no stream call reports one. + +#include "support/wipe_recorder.hpp" + +#include "support/counting.hpp" + +#include "support/base32_reference.hpp" +#include "support/chunkings.hpp" +#include "support/samples.hpp" +#include "support/steps.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; + +using base32_encoder = decltype(codecs::encoder(formats::base32)); +using base32_decoder = decltype(codecs::decoder(formats::base32)); +using base32hex_encoder = decltype(codecs::encoder(formats::base32hex)); +using base32hex_decoder = decltype(codecs::decoder(formats::base32hex)); +using secret_base32_encoder = decltype(codecs::encoder(formats::base32, codecs::secret_operation)); +using secret_base32_decoder = decltype(codecs::decoder(formats::base32, codecs::secret_operation)); +using stream_encoder = codecs::stream_codec::encoder; +using stream_decoder = codecs::stream_codec::decoder; +using secret_stream_encoder = + codecs::stream_codec::encoder; +using secret_stream_decoder = + codecs::stream_codec::decoder; + +// base32 and base32hex stream natively: their transformers are one-shot and stream transformers, +// of bytes to characters and back, constant time as their codec is. +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(codecs::is_constant_time_v); +static_assert(codecs::is_constant_time_v); +static_assert(codecs::is_constant_time_v); +static_assert(base32_encoder::max_output_size(5) == 8); +static_assert(base32_encoder::max_output_size(6) == 16); +static_assert(base32_decoder::max_output_size(8) == 5); +// The stream codec's own streams: a public one is copyable and trivially destructible, a secret +// one move-only, with a destructor that wipes (D21). +static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); +static_assert(std::is_trivially_destructible_v); +static_assert(std::is_trivially_destructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(!std::is_trivially_destructible_v); +static_assert(!std::is_trivially_destructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(codecs::is_secret_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); +// One implementation: the stream codecs of the two formats are the same templates. +static_assert(std::is_base_of_v, + codecs::stream_codec>); +static_assert(std::is_base_of_v, + codecs::stream_codec>); + +/** Whether a format of the pair is the extended hex one, which the reference reads. */ +template +constexpr bool is_hex = std::is_same_v; + +/** + The encoder, the decoder and the secret ones of `format` over every chunking of `bytes` equal the + one-shot forms: the text the reference writes, and the bytes back. +*/ +template +void expect_every_chunking_of(Format const& format, std::span bytes) { + bool const padded = format.padding_option == formats::padding::written; + std::string const text = test::reference_base32_encode(bytes, is_hex, padded); + BOOST_TEST(codecs::encode(format, bytes).value() == text); + auto encoder = codecs::encoder(format); + auto decoder = codecs::decoder(format); + test::expect_every_chunking(encoder, bytes, text); + test::expect_every_chunking(decoder, test::characters_of(text), bytes); + auto secret_encoder = codecs::encoder(format, codecs::secret_operation); + auto secret_decoder = codecs::decoder(format, codecs::secret_operation); + test::expect_every_chunking(secret_encoder, bytes, text); + test::expect_every_chunking(secret_decoder, test::characters_of(text), bytes); +} + +/** `expect_every_chunking_of` in the four configurations: both alphabets, both paddings. */ +void expect_every_chunking_everywhere(std::span bytes) { + expect_every_chunking_of(formats::base32, bytes); + expect_every_chunking_of(formats::base32(formats::padding::omitted), bytes); + expect_every_chunking_of(formats::base32hex, bytes); + expect_every_chunking_of(formats::base32hex(formats::padding::omitted), bytes); +} + +/** + RFC 4648 section 10's inputs, and bytes of every length from 0 to 11, in the four configurations, + and 31, 32 and 33 random bytes in the two defaults and 200 (past the exhaustive splits' limit, so + on the grid of cuts) in base32 and base32hex, over every chunking. +*/ +void every_chunking_equals_the_one_shot_form() { + for (std::string_view const input : {"", "f", "fo", "foo", "foob", "fooba", "foobar"}) { + expect_every_chunking_everywhere(test::bytes_of(input)); + } + for (std::size_t size = 0; size < 12; ++size) { + expect_every_chunking_everywhere(test::random_bytes(size)); + } + for (std::size_t const size : std::array{31, 32, 33}) { + std::vector const bytes = test::random_bytes(size); + expect_every_chunking_of(formats::base32, bytes); + expect_every_chunking_of(formats::base32hex, bytes); + } + expect_every_chunking_of(formats::base32, test::random_bytes(200)); + expect_every_chunking_of(formats::base32hex(formats::padding::omitted), + test::random_bytes(200)); + // The bytes 0xff 0x00 0xab 0xcd 0x01, whose symbols the alphabets give differently. + std::array const bytes{0xff, 0x00, 0xab, 0xcd, 0x01}; + auto standard = codecs::encoder(formats::base32); + auto extended = codecs::encoder(formats::base32hex); + test::expect_every_chunking(standard, std::span{bytes}, + std::string_view{"74AKXTIB"}); + test::expect_every_chunking(extended, std::span{bytes}, + std::string_view{"VS0ANJ81"}); +} + +/** + `bytes` and their text in `format` through `chunkings` random chunkings (a cut at each position + with the chance of one in three, drawn from `generator`), both output span sizes, the encoder, the + decoder and the secret ones: the same checks as `expect_every_chunking_of`, over a sample. +*/ +template +void expect_random_chunkings_of(Format const& format, std::span bytes, + std::mt19937_64& generator, int chunkings) { + bool const padded = format.padding_option == formats::padding::written; + std::string const text = test::reference_base32_encode(bytes, is_hex, padded); + BOOST_TEST(codecs::encode(format, bytes).value() == text); + std::span const characters = test::characters_of(text); + auto encoder = codecs::encoder(format); + auto decoder = codecs::decoder(format); + auto secret_encoder = codecs::encoder(format, codecs::secret_operation); + auto secret_decoder = codecs::decoder(format, codecs::secret_operation); + test::expect_random_chunkings(encoder, bytes, text, generator, chunkings); + test::expect_random_chunkings(secret_encoder, bytes, text, generator, chunkings); + test::expect_random_chunkings(decoder, characters, bytes, generator, chunkings); + test::expect_random_chunkings(secret_decoder, characters, bytes, generator, chunkings); +} + +/** + 1000 random inputs of 0 to 13 bytes, each in a configuration of the four and as public and as + secret streams alternately. The product with every chunking is what made this test slow, so the + first 40 inputs go over every chunking and the other 960 over 6 random chunkings each: the stream + equals the one-shot form and decodes back. Every vector of the test, valid and invalid, is + exhaustive over every chunking. +*/ +void a_thousand_random_inputs() { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): a fixed seed + std::mt19937_64 generator{20261129}; + for (int iteration = 0; iteration < 1000; ++iteration) { + std::vector bytes(generator() % 14); + for (std::uint8_t& byte : bytes) { + byte = static_cast(generator()); + } + auto const check = [&](auto const& format) { + if (iteration < 40) { + expect_every_chunking_of(format, bytes); + } else { + expect_random_chunkings_of(format, bytes, generator, 6); + } + }; + switch (iteration % 4) { + case 0: check(formats::base32); break; + case 1: check(formats::base32(formats::padding::omitted)); break; + case 2: check(formats::base32hex); break; + default: check(formats::base32hex(formats::padding::omitted)); break; + } + } +} + +/** + Every chunking of `text` decodes as the one-shot form does: the same bytes, or the same error, + reported after flush by the call that reads the end, which writes nothing (B44); public and secret + decoders alike. +*/ +template +void expect_the_one_shot_verdict(Format const& format, std::string_view text) { + auto const one_shot = codecs::decode(format, text); + bool const padded = format.padding_option == formats::padding::written; + test::base32_reading const reference = + test::reference_base32_decode(text, is_hex, padded); + BOOST_TEST_EQ(one_shot.has_value(), !reference.fault.has_value()); + if (!one_shot.has_value()) { + BOOST_TEST(one_shot.error() == *reference.fault); + } + test::expect_the_one_shot_verdict(format, text); +} + +/** `expect_the_one_shot_verdict` in the four configurations. */ +void expect_the_one_shot_verdict_everywhere(std::string_view text) { + expect_the_one_shot_verdict(formats::base32, text); + expect_the_one_shot_verdict(formats::base32(formats::padding::omitted), text); + expect_the_one_shot_verdict(formats::base32hex, text); + expect_the_one_shot_verdict(formats::base32hex(formats::padding::omitted), text); +} + +/** + Invalid texts give the one-shot form's error after flush, for every chunking: a character that is + no symbol is invalid_character wherever it is, a length no encoding has invalid_length, a `=` out + of place or non-zero trailing bits invalid_padding, and faults of two kinds the lowest value + (B23). +*/ +void invalid_texts_give_the_one_shot_error_after_flush() { + std::string const high_character{'M', 'Z', static_cast(0xc1), 'W'}; + for (std::string_view const text : { + std::string_view{"MZ======"}, + std::string_view{"MZXW6YTB\n"}, + std::string_view{"MZXW6YTB MZXW6YTB"}, + std::string_view{"MZXW6YQ"}, + std::string_view{"MZXW6=="}, + std::string_view{"MZXW6"}, + std::string_view{"M"}, + std::string_view{"MZX"}, + std::string_view{"MZXW6Y"}, + std::string_view{"MZXW6YT1"}, + std::string_view{"MZXW6YT-"}, + std::string_view{"CPNMUOJ1"}, + std::string_view{"MZXW6Y=="}, + std::string_view{"MZXW===="}, + std::string_view{"MZX====="}, + std::string_view{"M======="}, + std::string_view{"========"}, + std::string_view{"MY======MY======"}, + std::string_view{"MY======MZXW6YTB"}, + std::string_view{"MZXW6YTB========"}, + std::string_view{"MZ=W6YTB"}, + std::string_view{"MZXW6=TB"}, + std::string_view{"MY=====A"}, + std::string_view{"MZXR===="}, + std::string_view{"MZXW7==="}, + std::string_view{"MZXW6YR="}, + std::string_view{"MZ======\n"}, + std::string_view{"MZ====="}, + std::string_view{"MZ=====\n"}, + std::string_view{"MY======MZXW6YT\n"}, + std::string_view{"MZXW6YTBMZ"}, + std::string_view{"MZXW6YTBMZX"}, + std::string_view{high_character}, + }) { + expect_the_one_shot_verdict_everywhere(text); + } + // Each byte value as a character at each place of a group and as the lone last character: the + // stream's verdict is the one-shot form's, which the plain reference confirms. A padded group, + // and short unpadded ones. One value in five at each place: the exhaustive plain checks of + // the one-shot form are in base32_test. + for (std::string_view const base : {"MZXW6===", "MY======", "MZXW6YQ"}) { + for (std::size_t place = 0; place <= base.size(); ++place) { + for (unsigned value = 0; value < 256; ++value) { + // One value in five, and the `=`, `a`, `2` and 0xc1 that matter most. + if (value % 5 != 0 && value != '=' && value != 'a' && value != '2' && + value != 0xc1) { + continue; + } + auto const character = static_cast(static_cast(value)); + std::string text{base}; + if (place == base.size()) { + text.push_back(character); + } else { + text[place] = character; + } + if (base.size() == 8) { + expect_the_one_shot_verdict(formats::base32, text); + } else { + expect_the_one_shot_verdict(formats::base32(formats::padding::omitted), text); + } + } + } + } +} + +/** + The spec's "Send while output is pending": 64 bytes then 4 more before any receive give {64, + output_pending} then {0, output_pending}, and the second send is accepted once the output is + received until needs_input. A group not whole waits: 96 characters of the first 64 bytes, 8 of + the next 4 (a group is whole with the fifth byte of the held four), and `flush` completes the + last group with its padding. +*/ +void send_while_output_is_pending_to_the_encoder() { + std::vector const bytes = test::random_bytes(68); + auto encoder = codecs::encoder(formats::base32); + BOOST_TEST( + test::is_step(encoder.send(std::span{bytes}.first(64)), 64, codecs::flow::output_pending)); + BOOST_TEST( + test::is_step(encoder.send(std::span{bytes}.subspan(64)), 0, codecs::flow::output_pending)); + BOOST_TEST_EQ(test::receive_until_done(encoder, 100), 96U); + BOOST_TEST( + test::is_step(encoder.send(std::span{bytes}.subspan(64)), 4, codecs::flow::output_pending)); + BOOST_TEST_EQ(test::receive_until_done(encoder, 3), 8U); + // The last group, of three bytes, waits for the flush, which completes it with its padding. + auto const flushed = encoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + BOOST_TEST_EQ(test::receive_until_done(encoder, 2), 8U); + auto const second_flush = encoder.flush(); + BOOST_TEST(second_flush.has_value() && second_flush.value() == codecs::flow::finished); + // A send of nothing is accepted whole and absorbed. + encoder.reset(); + BOOST_TEST(test::is_step(encoder.send({}), 0, codecs::flow::needs_input)); +} + +/** + The decoder's half of "Send while output is pending": the first character of a group is absorbed + into its state and the held bytes are delivered by the next group's first character, or by the + flush, as a span of one byte takes them. +*/ +void send_while_output_is_pending_to_the_decoder() { + // The first character of a group is absorbed into the decoder's state, which frees the input + // at once; the rest of the group is read by the receive. With the padding written, the bytes + // of a group's fourth, fifth, seventh and eighth places are held until the group is known not + // to be the last, which a `=` there would make it: the next character delivers them, or the + // flush. + auto decoder = codecs::decoder(formats::base32); + BOOST_TEST(test::is_step(decoder.send(test::characters_of("M")), 1, codecs::flow::needs_input)); + BOOST_TEST(test::is_step(decoder.send(test::characters_of("ZXW6YTB")), 7, + codecs::flow::output_pending)); + std::array decoded{}; + BOOST_TEST(test::is_step(decoder.receive(decoded), 1, codecs::flow::needs_input)); + BOOST_TEST_EQ(decoded[0], 'f'); + // A span of one byte takes one byte at a time: the next group's first character delivers the + // four held bytes, then its second character the group's first byte. + BOOST_TEST(test::is_step(decoder.send(test::characters_of("MZXW6YTB")), 8, + codecs::flow::output_pending)); + std::array one_byte{}; + for (char const expected : std::string_view{"oob"}) { + BOOST_TEST(test::is_step(decoder.receive(one_byte), 1, codecs::flow::output_pending)); + BOOST_TEST_EQ(one_byte[0], static_cast(expected)); + } + BOOST_TEST(test::is_step(decoder.receive(one_byte), 1, codecs::flow::output_pending)); + BOOST_TEST_EQ(one_byte[0], 'a'); + BOOST_TEST(test::is_step(decoder.receive(one_byte), 1, codecs::flow::needs_input)); + BOOST_TEST_EQ(one_byte[0], 'f'); + // The flush delivers the last group's held bytes, its `=` none. + auto const decoder_flushed = decoder.flush(); + BOOST_TEST(decoder_flushed.has_value() && + decoder_flushed.value() == codecs::flow::output_pending); + for (char const expected : std::string_view{"oob"}) { + BOOST_TEST(test::is_step(decoder.receive(one_byte), 1, codecs::flow::output_pending)); + BOOST_TEST_EQ(one_byte[0], static_cast(expected)); + } + BOOST_TEST(test::is_step(decoder.receive(one_byte), 1, codecs::flow::finished)); + BOOST_TEST_EQ(one_byte[0], 'a'); + // With the padding omitted, every byte is delivered as its character is read. + auto unpadded_decoder = codecs::decoder(formats::base32(formats::padding::omitted)); + BOOST_TEST(test::is_step(unpadded_decoder.send(test::characters_of("MZXW6YTB")), 8, + codecs::flow::output_pending)); + BOOST_TEST(test::is_step(unpadded_decoder.receive(decoded), 5, codecs::flow::needs_input)); + BOOST_TEST((decoded == std::array{'f', 'o', 'o', 'b', 'a'})); +} + +/** + A decoder given a span of exactly the room the bytes of `text` need reads the padding as well: the + characters that deliver no byte are read with or without room, so that the stream reaches + needs_input with `held` bytes of the last group still held (its fourth, fifth, seventh and eighth + places' but those of its `=`), and finished after the flush and the receive of those into the + rest of the span; a caller with a fixed buffer never waits for room that no byte needs. +*/ +template +void expect_exact_room_reads_the_padding(Decoder& decoder, std::string_view text, + std::size_t held) { + auto const bytes = codecs::decode(formats::base32, text).value(); + decoder.reset(); + std::vector exact(bytes.size()); + BOOST_TEST(decoder.send(test::characters_of(text)).has_value()); + BOOST_TEST( + test::is_step(decoder.receive(exact), exact.size() - held, codecs::flow::needs_input)); + auto const flushed = decoder.flush(); + codecs::flow const after_flush = + held == 0 ? codecs::flow::finished : codecs::flow::output_pending; + BOOST_TEST(flushed.has_value() && flushed.value() == after_flush); + if (held != 0) { + BOOST_TEST(test::is_step(decoder.receive(std::span{exact}.last(held)), held, + codecs::flow::finished)); + } + BOOST_TEST(exact == bytes); + // A span of nothing: what delivers no byte is read, and a byte with no room waits. + decoder.reset(); + BOOST_TEST(decoder.send(test::characters_of(text)).has_value()); + auto const empty_receive = decoder.receive(std::span{}); + BOOST_TEST(empty_receive.has_value() && empty_receive->count == 0); + std::vector> const no_chunk; + auto const drained = test::stream_whole(decoder, no_chunk, 1); + BOOST_TEST(drained.has_value() && drained->size() == bytes.size()); +} + +/** `expect_exact_room_reads_the_padding` over texts of each count of `=`. */ +template +void expect_exact_room_reads_the_padding(Decoder decoder) { + expect_exact_room_reads_the_padding(decoder, "MY======", 0); + expect_exact_room_reads_the_padding(decoder, "MZXQ====", 1); + expect_exact_room_reads_the_padding(decoder, "MZXW6===", 2); + expect_exact_room_reads_the_padding(decoder, "MZXW6YQ=", 3); + expect_exact_room_reads_the_padding(decoder, "MZXW6YTB", 4); + expect_exact_room_reads_the_padding(decoder, "MZXW6YTBOI======", 0); + expect_exact_room_reads_the_padding(decoder, "MZXW6YTBMZXW6YQ=", 3); +} + +/** A public and a secret decoder, as @ref expect_exact_room_reads_the_padding checks them. */ +void exact_room_reads_the_padding() { + expect_exact_room_reads_the_padding(codecs::decoder(formats::base32)); + expect_exact_room_reads_the_padding(codecs::decoder(formats::base32, codecs::secret_operation)); +} + +/** + The spec's "After the end and after an error", its first half: a finished encoder's send is {0, + finished}, and so is every call after. +*/ +void after_the_end() { + std::array const bytes{0x12, 0x34}; + auto encoder = codecs::encoder(formats::base32); + BOOST_TEST(encoder.send(bytes).has_value()); + BOOST_TEST_EQ(test::receive_until_done(encoder, 16), 0U); + auto const flushed = encoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + BOOST_TEST_EQ(test::receive_until_done(encoder, 16), 8U); + BOOST_TEST(test::is_step(encoder.send(bytes), 0, codecs::flow::finished)); + auto const second_flush = encoder.flush(); + BOOST_TEST(second_flush.has_value() && second_flush.value() == codecs::flow::finished); + std::array text{}; + BOOST_TEST(test::is_step(encoder.receive(text), 0, codecs::flow::finished)); +} + +/** + The spec's "After the end and after an error", its second half: a decoder whose flush reported + invalid_character returns it from both receives after, writing nothing, and from every call, and + decodes a valid text after reset; a length no encoding has is invalid_length from flush when + nothing is still borrowed, and a `=` out of place invalid_padding. +*/ +void after_an_error() { + auto decoder = codecs::decoder(formats::base32); + std::array decoded{}; + BOOST_TEST(decoder.send(test::characters_of("MZXW6YTB*ZXW6YTB")).has_value()); + BOOST_TEST(test::is_step(decoder.receive(std::span{decoded}.first(5)), 5, + codecs::flow::output_pending)); + auto const flushed = decoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + decoded.fill(0x5a); + BOOST_TEST(test::failed_with(decoder.receive(decoded), codecs::error::invalid_character)); + BOOST_TEST(test::failed_with(decoder.receive(decoded), codecs::error::invalid_character)); + BOOST_TEST(std::ranges::all_of(decoded, [](std::uint8_t byte) { return byte == 0x5a; })); + BOOST_TEST(test::failed_with(decoder.send(test::characters_of("MZXW6YTB")), + codecs::error::invalid_character)); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_character)); + decoder.reset(); + BOOST_TEST(test::is_step(decoder.send(test::characters_of("INXWMZTFMU======")), 16, + codecs::flow::output_pending)); + BOOST_TEST(decoder.flush().has_value()); + BOOST_TEST(test::is_step(decoder.receive(decoded), 6, codecs::flow::finished)); + BOOST_TEST(std::string_view(reinterpret_cast(decoded.data()), 6) == "Coffee"); + + decoder.reset(); + BOOST_TEST(decoder.send(test::characters_of("MZXW6YT")).has_value()); + // The fourth place's byte is held: the group may be the last, and its fourth character a `=`. + BOOST_TEST(test::is_step(decoder.receive(decoded), 1, codecs::flow::needs_input)); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_length)); + decoder.reset(); + BOOST_TEST(decoder.send(test::characters_of("MZ======")).has_value()); + BOOST_TEST(test::is_step(decoder.receive(decoded), 1, codecs::flow::needs_input)); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_padding)); + // An error is the lowest value: the character, over the length and the padding. + decoder.reset(); + BOOST_TEST(decoder.send(test::characters_of("MZ=====\n")).has_value()); + BOOST_TEST(decoder.receive(decoded).has_value()); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_character)); +} + +/** + The spec's "The call that fails writes nothing" (B44), on base32: 4000 valid characters drained, + then 96 characters whose last is `*`, flushed and received into a span of 1024, which the receive + that reports invalid_character leaves unchanged; the earlier receives delivered the valid bytes. +*/ +void the_call_that_fails_writes_nothing() { + std::vector const bytes = test::random_bytes(3000); + std::string const text = codecs::encode(formats::base32, bytes).value(); + BOOST_TEST_EQ(text.size(), 4800U); + auto decoder = codecs::decoder(formats::base32); + std::vector delivered; + auto sink = [&delivered](std::span piece) { + delivered.insert(delivered.end(), piece.begin(), piece.end()); + }; + BOOST_TEST( + decoder.send(test::characters_of(std::string_view{text}.substr(0, 4000))).has_value()); + auto const drained = codecs::drain(decoder, sink); + BOOST_TEST(drained.has_value() && drained.value() == codecs::flow::needs_input); + // The last group's four bytes after the first are held until the group is known not to be the + // last, which the next character, never delivered here, would make it. + BOOST_TEST(std::ranges::equal(delivered, std::span{bytes}.first(2496))); + + std::string tail = text.substr(4000, 96); + tail.back() = '*'; + BOOST_TEST(decoder.send(test::characters_of(tail)).has_value()); + auto const flushed = decoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + std::array span{}; + span.fill(0x5a); + auto const received = decoder.receive(span); + BOOST_TEST(test::failed_with(received, codecs::error::invalid_character)); + BOOST_TEST(std::ranges::all_of(span, [](std::uint8_t byte) { return byte == 0x5a; })); + // The same with a secret decoder. + auto secret_decoder = codecs::decoder(formats::base32, codecs::secret_operation); + BOOST_TEST(secret_decoder.send(test::characters_of(tail)).has_value()); + BOOST_TEST(secret_decoder.flush().has_value()); + span.fill(0x5a); + BOOST_TEST(test::failed_with(secret_decoder.receive(span), codecs::error::invalid_character)); + BOOST_TEST(std::ranges::all_of(span, [](std::uint8_t byte) { return byte == 0x5a; })); +} + +/** A stream of `format` flushed with nothing sent finishes at once with nothing written. */ +template +void expect_empty_streams_finish(Format const& format) { + auto encoder = codecs::encoder(format); + auto const flushed = encoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::finished); + std::array text{}; + BOOST_TEST(test::is_step(encoder.receive(text), 0, codecs::flow::finished)); + auto decoder = codecs::decoder(format); + auto const decoder_flushed = decoder.flush(); + BOOST_TEST(decoder_flushed.has_value() && decoder_flushed.value() == codecs::flow::finished); + std::array decoded{}; + BOOST_TEST(test::is_step(decoder.receive(decoded), 0, codecs::flow::finished)); + auto const encoded_nothing = + encoder.transform(std::span{}, std::span{}); + BOOST_TEST(encoded_nothing.has_value() && encoded_nothing.value() == 0); + auto const decoded_nothing = + decoder.transform(std::span{}, std::span{}); + BOOST_TEST(decoded_nothing.has_value() && decoded_nothing.value() == 0); +} + +/** + Review Focus 3: a stream flushed with nothing sent finishes at once with nothing written, and + transform of empty spans writes nothing and returns 0. +*/ +void empty_input() { + for (formats::padding const option : {formats::padding::written, formats::padding::omitted}) { + expect_empty_streams_finish(formats::base32(option)); + expect_empty_streams_finish(formats::base32hex(option)); + } +} + +/** + Review Focus 5: a moved-from encoder and decoder, public and secret, convert an input from the + start, and the moved-to one finishes what the source had begun. +*/ +template +void a_moved_from_stream_converts_from_the_start(Encoder encoder, Decoder decoder) { + std::vector const bytes = test::random_bytes(31); + std::string const text = codecs::encode(formats::base32, bytes).value(); + BOOST_TEST(encoder.send(bytes).has_value()); + std::array one_character{}; + BOOST_TEST(test::is_step(encoder.receive(one_character), 1, codecs::flow::output_pending)); + Encoder moved_encoder{std::move(encoder)}; + std::vector> const no_chunk; + auto const rest = test::stream_whole(moved_encoder, no_chunk, 5); + BOOST_TEST(rest.has_value() && + std::string(1, one_character[0]) + std::string(rest->begin(), rest->end()) == text); + std::vector> const whole{bytes}; + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): Review Focus 5 + auto const again = test::stream_whole(encoder, whole, 7); + BOOST_TEST(again.has_value() && std::string(again->begin(), again->end()) == text); + + BOOST_TEST(decoder.send(test::characters_of(text).first(9)).has_value()); + std::array one_byte{}; + BOOST_TEST(test::is_step(decoder.receive(one_byte), 1, codecs::flow::output_pending)); + Decoder moved_decoder{std::move(decoder)}; + std::vector> const tail{test::characters_of(text).subspan(9)}; + auto const decoded_rest = test::stream_whole(moved_decoder, tail, 4); + // The moved-to decoder reads the characters the source still borrowed, then the rest. + BOOST_TEST(decoded_rest.has_value() && one_byte[0] == bytes[0] && + std::ranges::equal(*decoded_rest, std::span{bytes}.subspan(1))); + std::vector> const whole_text{test::characters_of(text)}; + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): Review Focus 5 + auto const decoded_again = test::stream_whole(decoder, whole_text, 3); + BOOST_TEST(decoded_again.has_value() && *decoded_again == bytes); +} + +/** + The spec's "A file in base32 with no heap": a file of 64 KiB is read in 4096-byte chunks into one + buffer, each sent to encoder(base32) and drained into a fixed span before the next chunk is read; + the text equals the one-shot encoding of the whole file, and decodes back the same way, with no + allocation counted. +*/ +void a_file_with_no_heap() { + std::vector const file = test::random_bytes(std::size_t{64} * 1024); + std::string const expected = codecs::encode(formats::base32, file).value(); + std::string text(expected.size(), ' '); // the output, made before the window + std::vector decoded(file.size()); + bool volatile verdict = false; + test::expect_no_allocation("a file through encoder(base32) and decoder(base32)", [&] { + std::array chunk{}; + std::array fixed_span{}; + std::size_t written = 0; + auto const text_sink = [&](std::span piece) noexcept { + std::ranges::copy(piece, text.begin() + static_cast(written)); + written += piece.size(); + }; + auto encoder = codecs::encoder(formats::base32); + bool streamed = true; + for (std::size_t offset = 0; offset < file.size(); offset += chunk.size()) { + // The "read": the next chunk of the file into the one buffer. + std::ranges::copy(std::span{file}.subspan(offset, chunk.size()), chunk.begin()); + streamed = streamed && encoder.send(chunk).has_value() && + codecs::drain(encoder, text_sink, std::span{fixed_span}).has_value(); + } + streamed = streamed && encoder.flush().has_value() && + codecs::drain(encoder, text_sink, std::span{fixed_span}).has_value(); + + std::array fixed_bytes{}; + std::size_t decoded_count = 0; + auto const byte_sink = [&](std::span piece) noexcept { + std::ranges::copy(piece, decoded.begin() + static_cast(decoded_count)); + decoded_count += piece.size(); + }; + auto decoder = codecs::decoder(formats::base32); + std::array text_chunk{}; + for (std::size_t offset = 0; offset < text.size(); offset += text_chunk.size()) { + std::size_t const size = std::min(text_chunk.size(), text.size() - offset); + std::ranges::copy(std::string_view{text}.substr(offset, size), text_chunk.begin()); + streamed = streamed && + decoder.send(std::span{text_chunk}.first(size)).has_value() && + codecs::drain(decoder, byte_sink, std::span{fixed_bytes}).has_value(); + } + streamed = streamed && decoder.flush().has_value() && + codecs::drain(decoder, byte_sink, std::span{fixed_bytes}).has_value(); + verdict = streamed && written == expected.size() && decoded_count == file.size(); + }); + BOOST_TEST(verdict); + BOOST_TEST(text == expected); + BOOST_TEST(decoded == file); +} + +/** + A secret stream wipes its pending state (D21): the encoder's waiting bytes (5) and characters + (8), and the decoder's seven bytes of bits and masks, its four held bytes and its four waiting + bytes, in the source after a move, at reset and at destruction; a public stream wipes nothing. The + encoder is given 31 bytes, which leaves one byte pending, the spec's scenario "A secret stream's + state is wiped". +*/ +void a_secret_streams_state_is_wiped() { + std::vector const bytes = test::random_bytes(31); + std::array text{}; + std::optional encoder; + encoder.emplace(formats::base32); + BOOST_TEST(encoder->send(bytes).has_value()); + BOOST_TEST(test::is_step(encoder->receive(text), 48, codecs::flow::needs_input)); + test::clear_wipes(); + secret_stream_encoder moved_encoder{std::move(*encoder)}; + BOOST_TEST_EQ(test::wipes_in(*encoder, 5), 1U); + BOOST_TEST_EQ(test::wipes_in(*encoder, 8), 1U); + BOOST_TEST(moved_encoder.flush().has_value()); + BOOST_TEST(test::is_step(moved_encoder.receive(text), 8, codecs::flow::finished)); + // The moved-to encoder holds the byte again: its reset and destruction wipe it. + moved_encoder.reset(); + BOOST_TEST(moved_encoder.send(bytes).has_value()); + BOOST_TEST(moved_encoder.receive(text).has_value()); + test::clear_wipes(); + moved_encoder.reset(); + BOOST_TEST_EQ(test::wipes_in(moved_encoder, 5), 1U); + BOOST_TEST_EQ(test::wipes_in(moved_encoder, 8), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(encoder, 5), 1U); + + std::optional decoder; + decoder.emplace(formats::base32); + BOOST_TEST(decoder->send(test::characters_of("MZXW6YTBMZXW6Y")).has_value()); + std::array decoded{}; + BOOST_TEST(test::is_step(decoder->receive(decoded), 6, codecs::flow::needs_input)); + test::clear_wipes(); + secret_stream_decoder moved_decoder{std::move(*decoder)}; + BOOST_TEST_EQ(test::wipes_in(*decoder, 7), 1U); + BOOST_TEST_EQ(test::wipes_in(*decoder, 4), 2U); + test::clear_wipes(); + moved_decoder.reset(); + BOOST_TEST_EQ(test::wipes_in(moved_decoder, 7), 1U); + BOOST_TEST_EQ(test::wipes_in(moved_decoder, 4), 2U); + BOOST_TEST_EQ(test::wipes_at_destruction(decoder, 7), 1U); + BOOST_TEST_EQ(test::wipes.count, 3U); + + // A public stream wipes nothing. + test::clear_wipes(); + { + stream_encoder public_encoder{formats::base32}; + BOOST_TEST(public_encoder.send(bytes).has_value()); + BOOST_TEST(public_encoder.receive(text).has_value()); + public_encoder.reset(); + stream_decoder public_decoder{formats::base32}; + BOOST_TEST(public_decoder.send(test::characters_of("MZXW6YQ=")).has_value()); + BOOST_TEST(public_decoder.receive(decoded).has_value()); + BOOST_TEST(public_decoder.flush().has_value()); + public_decoder.reset(); + } + BOOST_TEST_EQ(test::wipes.count, 0U); +} + +} // namespace + +int main() { + every_chunking_equals_the_one_shot_form(); + a_thousand_random_inputs(); + invalid_texts_give_the_one_shot_error_after_flush(); + send_while_output_is_pending_to_the_encoder(); + send_while_output_is_pending_to_the_decoder(); + exact_room_reads_the_padding(); + after_the_end(); + after_an_error(); + the_call_that_fails_writes_nothing(); + empty_input(); + a_moved_from_stream_converts_from_the_start(codecs::encoder(formats::base32), + codecs::decoder(formats::base32)); + a_moved_from_stream_converts_from_the_start( + codecs::encoder(formats::base32, codecs::secret_operation), + codecs::decoder(formats::base32, codecs::secret_operation)); + a_file_with_no_heap(); + a_secret_streams_state_is_wiped(); + return boost::report_errors(); +} diff --git a/test/base32_test.cpp b/test/base32_test.cpp new file mode 100644 index 0000000..2738405 --- /dev/null +++ b/test/base32_test.cpp @@ -0,0 +1,815 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// base32 and base32hex, the formats (D13, the spec's "Format: base32 and base32hex"): RFC 4648 +// section 10's vectors with either padding and either alphabet, through the buffer, token, default +// and typed forms, each decoding back from lower case and from mixed case (B13); every error of the +// format, one input each, and an input of two faults giving the lowest value (B23), among them +// "MZXW6===" with the padding omitted (invalid_padding), "MZXW6YQ" with the padding written +// (invalid_length), "MY======" (the byte "f") and "MZ======" (a non-zero trailing bit); every byte +// value as a character at every place of a group against a plain reference, `char` signed (Review +// Focus 1), and 5000 texts near the valid ones (each in four +// configurations); a text decoded into its own storage (Review Focus 4); empty input in every form +// (Review Focus 3); the bounds saturating at SIZE_MAX with an input of 5 * (SIZE_MAX / 8) + 1 bytes +// refused (Review Focus 2); the spec's "The exact size and the bound" on base32 (the others, with +// the token, over and stream forms, are in tokens_test, over_test, format_transformer_test and +// base32_stream_test). The one implementation of the pair is run through both formats and both +// paddings: base32 and base32hex differ in their alphabet alone. + +#include "support/counting.hpp" + +#include "support/base32_reference.hpp" +#include "support/decode_checks.hpp" +#include "support/letter_cases.hpp" +#include "support/samples.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace detail = webcpp::codecs::detail; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +using base32_codec = codecs::codec; +using base32hex_codec = codecs::codec; + +constexpr std::size_t size_maximum = std::numeric_limits::max(); + +// The formats: values whose call configures the padding (D2); both write it by default. +static_assert(codecs::format && codecs::format); +static_assert(!std::is_same_v); +static_assert(formats::base32_t::name == "base32"); +static_assert(formats::base32hex_t::name == "base32hex"); +static_assert(formats::base32.padding_option == formats::padding::written); +static_assert(formats::base32hex.padding_option == formats::padding::written); +static_assert(formats::base32(formats::padding::omitted).padding_option == + formats::padding::omitted); +static_assert(formats::base32hex(formats::padding::omitted).padding_option == + formats::padding::omitted); +static_assert( + std::is_same_v); +static_assert( + std::is_same_v); +// A value of neither enumerator, cast from another integer, is read as written, RFC 4648's own +// form: the padding is omitted for padding::omitted alone (formats::padding's rule), here too. +static_assert(codecs::detail::padding_is_written(formats::base32(formats::padding{0}))); +static_assert(codecs::detail::padding_is_written(formats::base32hex(formats::padding{3}))); +static_assert(!codecs::detail::padding_is_written(formats::base32(formats::padding::omitted))); +static_assert(codecs::encoded_size(formats::base32(formats::padding{0}), + std::array{}) == 8); +static_assert(codecs::encoded_size(formats::base32hex(formats::padding{9}), + std::array{}) == 8); + +// Their codecs: constant time; one implementation, the same functions under both names. +static_assert(base32_codec::constant_time && base32hex_codec::constant_time); +static_assert(std::is_base_of_v, base32_codec>); +static_assert(std::is_base_of_v, base32hex_codec>); + +// The spec's "The exact size and the bound": "foob" is 8 characters and "MZXW6YQ=" holds at most 5 +// bytes, in a static_assert, and decode writes 4 (below). +constexpr std::array foob{'f', 'o', 'o', 'b'}; +static_assert(codecs::encoded_size(formats::base32, foob) == 8); +static_assert(codecs::max_decoded_size(formats::base32, std::string_view{"MZXW6YQ="}) == 5); +static_assert(codecs::max_decoded_size(formats::base32, "MZXW6YQ=") == 5); +// The exact size follows the padding, the bound is over both. +static_assert(codecs::encoded_size(formats::base32(formats::padding::omitted), foob) == 7); +static_assert(codecs::encoded_size(formats::base32hex(formats::padding::omitted), foob) == 7); +static_assert(codecs::encoded_size(formats::base32, std::array{}) == 0); +static_assert(codecs::encoded_size(formats::base32, std::array{}) == 8); +static_assert(codecs::encoded_size(formats::base32(formats::padding::omitted), + std::array{}) == 8); +static_assert(codecs::encoded_size(formats::base32(formats::padding::omitted), + std::array{}) == 2); +static_assert(codecs::encoded_size(formats::base32(formats::padding::omitted), + std::array{}) == 4); +static_assert(codecs::encoded_size(formats::base32(formats::padding::omitted), + std::array{}) == 5); +static_assert(codecs::encoded_size(formats::base32(formats::padding::omitted), + std::array{}) == 10); +static_assert(base32_codec::max_encoded_size(0) == 0); +static_assert(base32_codec::max_encoded_size(1) == 8); +static_assert(base32_codec::max_encoded_size(5) == 8); +static_assert(base32_codec::max_encoded_size(6) == 16); +static_assert(base32_codec::max_encoded_size(32) == 56); +static_assert(base32_codec::max_decoded_size(0) == 0); +static_assert(base32_codec::max_decoded_size(1) == 0); +static_assert(base32_codec::max_decoded_size(2) == 1); +static_assert(base32_codec::max_decoded_size(3) == 1); +static_assert(base32_codec::max_decoded_size(4) == 2); +static_assert(base32_codec::max_decoded_size(5) == 3); +static_assert(base32_codec::max_decoded_size(6) == 3); +static_assert(base32_codec::max_decoded_size(7) == 4); +static_assert(base32_codec::max_decoded_size(8) == 5); +static_assert(base32_codec::max_decoded_size(52) == 32); +static_assert(base32_codec::max_decoded_size(56) == 35); + +// Review Focus 2: the bound is 8 * ceil(n / 5), which saturates past 5 * (SIZE_MAX / 8) bytes, on a +// 32-bit std::size_t too; the core refuses such an input before it reads it. A text's bound never +// saturates. +constexpr std::size_t longest_input = 5 * (size_maximum / 8); +static_assert(base32_codec::max_encoded_size(longest_input) == 8 * (size_maximum / 8)); +static_assert(base32_codec::max_encoded_size(longest_input + 1) == size_maximum); +static_assert(base32_codec::max_encoded_size(size_maximum) == size_maximum); +static_assert(base32hex_codec::max_encoded_size(longest_input + 1) == size_maximum); +static_assert(!codecs::detail::input_size_fault(formats::base32, longest_input).has_value()); +static_assert(codecs::detail::input_size_fault(formats::base32, longest_input + 1) == + codecs::error::input_too_long); +static_assert(codecs::detail::input_size_fault(formats::base32hex, longest_input + 1) == + codecs::error::input_too_long); +static_assert(codecs::detail::input_size_fault(formats::base32, size_maximum) == + codecs::error::input_too_long); +static_assert(base32_codec::max_decoded_size(size_maximum) == (size_maximum / 8 * 5) + 4); +static_assert(!codecs::detail::text_size_fault(formats::base32, size_maximum).has_value()); +// The padded bound is the unpadded size's bound; the sizes of the lengths of the last group. +static_assert(detail::base32_text_size(1, false) == 2 && detail::base32_text_size(2, false) == 4); +static_assert(detail::base32_text_size(3, false) == 5 && detail::base32_text_size(4, false) == 7); +static_assert(detail::base32_text_size(1, true) == 8 && detail::base32_text_size(5, false) == 8); +static_assert(detail::base32_text_size(longest_input, true) == 8 * (size_maximum / 8)); +static_assert(detail::base32_text_size(longest_input + 1, false) == (8 * (size_maximum / 8)) + 2); +static_assert(detail::base32_text_size(longest_input + 4, false) == (8 * (size_maximum / 8)) + 7); + +// base32 has no configuration to be at fault. +static_assert(!codecs::detail::takes_configuration_fault); +static_assert(!codecs::detail::configuration_fault_of(formats::base32).has_value()); +static_assert(!codecs::detail::configuration_fault_of(formats::base32hex).has_value()); + +// The default results (D9): in place for a size known at compile time, the heap otherwise. +static_assert( + std::is_same_v const&>())), + codecs::result>>); +static_assert(std::is_same_v const&>())), + codecs::result>>); +static_assert( + std::is_same_v const&>())), + codecs::result>); +static_assert(std::is_same_v>>); + +// The arithmetic, as constant expressions: a value's symbol in either alphabet, and a symbol's +// value and verdict, in either case. +static_assert(detail::base32_arithmetic::symbol_of(0) == 'A'); +static_assert(detail::base32_arithmetic::symbol_of(25) == 'Z'); +static_assert(detail::base32_arithmetic::symbol_of(26) == '2'); +static_assert(detail::base32_arithmetic::symbol_of(31) == '7'); +static_assert(detail::base32_arithmetic::symbol_of(0) == '0'); +static_assert(detail::base32_arithmetic::symbol_of(9) == '9'); +static_assert(detail::base32_arithmetic::symbol_of(10) == 'A'); +static_assert(detail::base32_arithmetic::symbol_of(31) == 'V'); + +/** The value of `symbol` in an alphabet as the arithmetic gives it, and whether it is no symbol. */ +template +constexpr std::pair read_symbol(char symbol) { + std::uint8_t mask = 0; + unsigned const value = + detail::base32_arithmetic::five_bits_of(static_cast(symbol), mask); + return {value, mask != 0}; +} + +static_assert(read_symbol('A') == std::pair{0U, false}); +static_assert(read_symbol('a') == std::pair{0U, false}); +static_assert(read_symbol('z') == std::pair{25U, false}); +static_assert(read_symbol('2') == std::pair{26U, false}); +static_assert(read_symbol('7') == std::pair{31U, false}); +static_assert(read_symbol('0').second && read_symbol('1').second); +static_assert(read_symbol('8').second && read_symbol('9').second); +static_assert(read_symbol('0') == std::pair{0U, false}); +static_assert(read_symbol('9') == std::pair{9U, false}); +static_assert(read_symbol('A') == std::pair{10U, false}); +static_assert(read_symbol('v') == std::pair{31U, false}); +static_assert(read_symbol('W').second && read_symbol('z').second); +static_assert(read_symbol('=').second && read_symbol('=').second); +static_assert(read_symbol(static_cast(0xc1)).second); + +/** RFC 4648 section 10's test vectors: the input, and its base32 and base32hex as the RFC writes. + */ +struct rfc_vector { + /** The input. */ + std::string_view input; + /** Its base32, with the padding. */ + std::string_view padded; + /** Its base32hex, with the padding. */ + std::string_view padded_hex; +}; + +/** RFC 4648 section 10's test vectors. */ +constexpr std::array rfc4648_vectors{ + rfc_vector{.input = "", .padded = "", .padded_hex = ""}, + rfc_vector{.input = "f", .padded = "MY======", .padded_hex = "CO======"}, + rfc_vector{.input = "fo", .padded = "MZXQ====", .padded_hex = "CPNG===="}, + rfc_vector{.input = "foo", .padded = "MZXW6===", .padded_hex = "CPNMU==="}, + rfc_vector{.input = "foob", .padded = "MZXW6YQ=", .padded_hex = "CPNMUOG="}, + rfc_vector{.input = "fooba", .padded = "MZXW6YTB", .padded_hex = "CPNMUOJ1"}, + rfc_vector{.input = "foobar", .padded = "MZXW6YTBOI======", .padded_hex = "CPNMUOJ1E8======"}, +}; + +/** + One vector's encode through the forms of one configuration: the default form, the buffer form + (the characters past the text unchanged, a short buffer refused) and the tokens. + + @return The text the default form gave. +*/ +template +std::string expect_encodes(Format const& format, bool hex, rfc_vector const& vector, bool padded) { + std::string const written_text{hex ? vector.padded_hex : vector.padded}; + std::string const expected = padded ? written_text : test::without_padding(written_text); + // The reference agrees with the RFC. + BOOST_TEST(test::reference_base32_encode(test::bytes_of(vector.input), hex, padded) == + expected); + auto const defaulted = codecs::encode(format, vector.input); + BOOST_TEST(defaulted.has_value() && defaulted.value() == expected); + BOOST_TEST_EQ(codecs::encoded_size(format, vector.input), expected.size()); + + std::array buffer{}; + buffer.fill('x'); + auto const written = codecs::encode(format, vector.input, std::span{buffer}); + BOOST_TEST(written.has_value() && written.value() == expected.size()); + BOOST_TEST(std::string_view(buffer.data(), expected.size()) == expected); + // The characters past the text are unchanged. + BOOST_TEST(std::all_of(buffer.begin() + static_cast(expected.size()), + buffer.end(), [](char character) { return character == 'x'; })); + if (!expected.empty()) { + auto const short_buffer = + codecs::encode(format, vector.input, std::span{buffer}.first(expected.size() - 1)); + BOOST_TEST(!short_buffer.has_value() && + short_buffer.error() == codecs::error::output_too_small); + } + + auto const returned = codecs::encode(format, vector.input, tokens::return_string); + BOOST_TEST(returned.has_value() && returned.value() == expected); + std::string appended{"<"}; + BOOST_TEST(codecs::encode(format, vector.input, tokens::append_to(appended)).has_value()); + BOOST_TEST(appended == "<" + expected); + auto const fixed = codecs::encode(format, vector.input, tokens::fixed<16>{}); + BOOST_TEST(fixed.has_value() && fixed.value().view() == expected); + return expected; +} + +/** + One vector's decode through the forms of one configuration: the default form, the typed forms, + the tokens and the buffer form, and the sizes. +*/ +template +void expect_decodes(Format const& format, rfc_vector const& vector, std::string const& text) { + BOOST_TEST_EQ(codecs::max_decoded_size(format, text) >= vector.input.size(), true); + auto const decoded = codecs::decode(format, text); + BOOST_TEST(test::decodes_to(decoded, vector.input)); + auto const typed = codecs::decode>(format, text); + BOOST_TEST(test::decodes_to(typed, vector.input)); + auto const fixed_bytes = codecs::decode(format, text, tokens::fixed<10>{}); + BOOST_TEST(fixed_bytes.has_value() && + std::ranges::equal(fixed_bytes.value().view(), test::bytes_of(vector.input))); + std::vector appended_bytes{0x5a}; + BOOST_TEST(codecs::decode(format, text, tokens::append_to(appended_bytes)).has_value()); + BOOST_TEST_EQ(appended_bytes.size(), vector.input.size() + 1); + std::array byte_buffer{}; + auto const decoded_count = codecs::decode(format, text, std::span{byte_buffer}); + BOOST_TEST(decoded_count.has_value() && decoded_count.value() == vector.input.size()); + BOOST_TEST(std::ranges::equal(std::span{byte_buffer}.first(vector.input.size()), + test::bytes_of(vector.input))); + auto const size = codecs::codec::decoded_size(format, text); + BOOST_TEST(size.has_value() && size.value() == vector.input.size()); + // A buffer larger than the result, filled with a sentinel, given to the core and to the + // codec's own decode: the bytes past the count are unchanged. + test::expect_tail_unchanged<16>( + [&](std::span output) { return codecs::decode(format, text, output); }, + test::bytes_of(vector.input)); + test::expect_tail_unchanged<16>( + [&](std::span output) { + return codecs::codec::decode(format, text, output); + }, + test::bytes_of(vector.input)); +} + +/** + One vector through every form of one configuration, from the upper case the RFC writes, from lower + case and from mixed case (B13), and the other padding refused, whichever the format writes (a + fault of the text, not of the format): the unpadded form where the padding is written is + invalid_length, and the padded one where it is not invalid_padding. The unpadded texts of + lengths 1, 3 and 6 have no vector, so the refusal is the vector's own text. +*/ +template +void expect_vector(Format const& format, bool hex, rfc_vector const& vector, bool padded) { + std::string const text = expect_encodes(format, hex, vector, padded); + expect_decodes(format, vector, text); + expect_decodes(format, vector, test::ascii_lower_case(text)); + expect_decodes(format, vector, test::ascii_mixed_case(text)); + std::string_view const written_text = hex ? vector.padded_hex : vector.padded; + if (!written_text.empty() && written_text.back() == '=') { + auto const other = padded ? test::without_padding(written_text) : std::string{written_text}; + auto const refused = codecs::decode(format, other); + BOOST_TEST(!refused.has_value()); + // "MY" is a length of an unpadded text: written, it is a length of no padded one; "MZXW6YQ" + // (7 characters), and the others, likewise, the padded text of 8 being refused for its `=`. + BOOST_TEST(refused.error() == + (padded ? codecs::error::invalid_length : codecs::error::invalid_padding)); + } +} + +/** RFC 4648 section 10's vectors through one configuration. */ +template +void expect_every_vector(Format const& format, bool hex, bool padded) { + for (rfc_vector const& vector : rfc4648_vectors) { + expect_vector(format, hex, vector, padded); + } +} + +/** + The spec's "RFC 4648's vectors": section 10's inputs with base32 and with base32hex, padded and + unpadded, each decoding back. +*/ +void rfc4648_vectors_in_both_alphabets() { + expect_every_vector(formats::base32, false, true); + expect_every_vector(formats::base32(formats::padding::omitted), false, false); + expect_every_vector(formats::base32hex, true, true); + expect_every_vector(formats::base32hex(formats::padding::omitted), true, false); + + // A character of the other alphabet is no character of this one. + BOOST_TEST(codecs::decode(formats::base32, std::string_view{"CPNMUOJ1"}).error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(formats::base32hex, std::string_view{"MZXW6YTB"}).error() == + codecs::error::invalid_character); + // The same eight characters of both alphabets are the same bytes under a different symbol. + std::array const bytes{0xff, 0x00, 0xab, 0xcd, 0x01}; + auto const standard = codecs::encode(formats::base32, bytes); + auto const extended = codecs::encode(formats::base32hex, bytes); + BOOST_TEST(standard.has_value() && standard.value().view() == "74AKXTIB"); + BOOST_TEST(extended.has_value() && extended.value().view() == "VS0ANJ81"); + auto const standard_back = codecs::decode(formats::base32, standard.value()); + auto const extended_back = codecs::decode(formats::base32hex, extended.value()); + BOOST_TEST(standard_back.has_value() && + std::ranges::equal(standard_back.value().view(), bytes)); + BOOST_TEST(extended_back.has_value() && + std::ranges::equal(extended_back.value().view(), bytes)); +} + +/** The spec's "The exact size and the bound", at run time as well: decode writes 4 bytes. */ +void the_exact_size_and_the_bound() { + std::string_view const text = "MZXW6YQ="; + BOOST_TEST_EQ(codecs::encoded_size(formats::base32, foob), 8U); + BOOST_TEST_EQ(codecs::max_decoded_size(formats::base32, text), 5U); + auto const decoded = codecs::decode(formats::base32, text); + BOOST_TEST(decoded.has_value() && decoded.value().size() == 4); + BOOST_TEST_EQ(base32_codec::decoded_size(formats::base32, text).value(), 4U); + std::array buffer{}; + auto const written = codecs::decode(formats::base32, text, std::span{buffer}); + BOOST_TEST(written.has_value() && written.value() == 4); + // The buffer of the bound is enough, the one of the exact size is as well, one less is not. + BOOST_TEST(codecs::decode(formats::base32, text, std::span{buffer}.first(4)).has_value()); + BOOST_TEST(codecs::decode(formats::base32, text, std::span{buffer}.first(3)).error() == + codecs::error::output_too_small); +} + +/** Checks that `format` refuses `text` with `expected` in every form, writing nothing. */ +template +void expect_refusal(Format const& format, std::string_view text, codecs::error expected) { + auto const defaulted = codecs::decode(format, text); + BOOST_TEST(!defaulted.has_value() && defaulted.error() == expected); + auto const size = codecs::codec::decoded_size(format, text); + BOOST_TEST(!size.has_value() && size.error() == expected); + std::array buffer{}; + buffer.fill(0x5a); + auto const written = codecs::decode(format, text, std::span{buffer}); + BOOST_TEST(!written.has_value() && written.error() == expected); + BOOST_TEST(std::ranges::all_of(buffer, [](std::uint8_t byte) { return byte == 0x5a; })); + std::vector appended{0x5a}; + auto const token = codecs::decode(format, text, tokens::append_to(appended)); + BOOST_TEST(!token.has_value() && token.error() == expected); + BOOST_TEST(appended == std::vector{0x5a}); + auto const typed = codecs::decode>(format, text); + BOOST_TEST(!typed.has_value() && typed.error() == expected); + // The reference gives the same verdict. + auto const reference = + test::reference_base32_decode(text, std::is_same_v, + format.padding_option == formats::padding::written); + BOOST_TEST(reference.fault == std::optional{expected}); +} + +/** + Every error of the format, one input each, with the padding written (the default): a character + outside the alphabet, whitespace and a line break (invalid_character), a length that is no + multiple of 8 (invalid_length), a `=` against the rules and non-zero trailing bits + (invalid_padding); the spec's "MZXW6YQ" with the padding written, "MY======" and "MZ======". +*/ +void every_error_with_the_padding_written() { + auto const& base32 = formats::base32; + constexpr auto character = codecs::error::invalid_character; + constexpr auto length = codecs::error::invalid_length; + constexpr auto padding = codecs::error::invalid_padding; + // The spec's scenarios: the byte "f", and the text of a non-zero trailing bit. + BOOST_TEST(codecs::decode(base32, std::string_view{"MY======"}).has_value()); + expect_refusal(base32, "MZ======", padding); + // B23: the lowest value of two faults, "MZXW6YQ" with the padding written is a length. + expect_refusal(base32, "MZXW6YQ", length); + expect_refusal(base32, "MZXW6YTB\n", character); + expect_refusal(base32, "MZXW6YTB MZXW6YTB", character); + expect_refusal(base32, "\nMZXW6YTB", character); + expect_refusal(base32, "MZXW6YT\r\n", character); + expect_refusal(base32, "MZXW 6YT", character); + // A length that is no multiple of 8: every remainder. + for (std::size_t size = 1; size < 8; ++size) { + expect_refusal(base32, std::string_view{"MZXW6YTB"}.substr(0, size), length); + expect_refusal(base32, std::string{"MZXW6YTBMZXW6YTB"}.substr(0, 8 + size), length); + } + expect_refusal(base32, "MY=====", length); + expect_refusal(base32, "MY=======", length); + expect_refusal(base32, "MZXW6YQ==", length); + // The characters outside the alphabet: the digits of base32hex that base32 lacks, a character + // of the other alphabet, the NUL, the bytes with the high bit, and the ones past each range. + expect_refusal(base32, "MZXW6YT0", character); + expect_refusal(base32, "MZXW6YT1", character); + expect_refusal(base32, "MZXW6YT8", character); + expect_refusal(base32, "MZXW6YT9", character); + expect_refusal(base32, "MZXW6YT-", character); + expect_refusal(base32, "MZXW6YT_", character); + expect_refusal(base32, "MZXW6YT@", character); + expect_refusal(base32, "MZXW6YT[", character); + expect_refusal(base32, "MZXW6YT`", character); + expect_refusal(base32, "MZXW6YT{", character); + expect_refusal(base32, "MZXW6YT/", character); + expect_refusal(base32, "MZXW6YT:", character); + expect_refusal(base32, std::string_view{"MZXW6YT\0", 8}, character); + expect_refusal(base32, "MZXW6YT\xc1", character); + expect_refusal(base32, "MZXW6YT\xff", character); + expect_refusal(base32, "MZXW6YT\x80", character); + expect_refusal(base32, "MZXW6YT*", character); + // Padding where it is not: a run of other than 1, 3, 4 or 6, a run in the middle of a group + // or of the text, after the padding, alone, and a run before a symbol. + expect_refusal(base32, "MZXW6Y==", padding); + expect_refusal(base32, "MZXW====", padding); + expect_refusal(base32, "MZX=====", padding); + expect_refusal(base32, "MZ=W6YTB", padding); + expect_refusal(base32, "MZXW6=TB", padding); + expect_refusal(base32, "M=======", padding); + expect_refusal(base32, "========", padding); + expect_refusal(base32, "=ZXW6YTB", padding); + expect_refusal(base32, "=Y======", padding); + expect_refusal(base32, "MY======MY======", padding); + expect_refusal(base32, "MY======MZXW6YTB", padding); + expect_refusal(base32, "MZXW6YTB========", padding); + expect_refusal(base32, "MZXW6YT=MZXW6YTB", padding); + expect_refusal(base32, "MY=====A", padding); + expect_refusal(base32, "MY====A=", padding); + expect_refusal(base32, "MZXW6=A=", padding); + // Non-zero trailing bits: one byte ends in 2 bits, two in 4, three in 1, four in 3. + expect_refusal(base32, "MZ======", padding); + expect_refusal(base32, "MZXR====", padding); + expect_refusal(base32, "MZXW7===", padding); + expect_refusal(base32, "MZXW6YR=", padding); + expect_refusal(base32, "MZXW6YTBMZ======", padding); + // Two faults give the lowest value (B23): an invalid character before the length, which comes + // before the padding. + expect_refusal(base32, "MZ======\n", character); + expect_refusal(base32, "MZ=====\n", character); + expect_refusal(base32, "MZ=====", length); + expect_refusal(base32, "MZXW6Y==M", length); + expect_refusal(base32, "MY======MZXW6YT\n", character); + expect_refusal(base32, "MZ==\n===", character); + // The valid texts of the same shapes. + BOOST_TEST(codecs::decode(base32, std::string_view{"MY======"}).has_value()); + BOOST_TEST(codecs::decode(base32, std::string_view{"MZXQ===="}).has_value()); + BOOST_TEST(codecs::decode(base32, std::string_view{"MZXW6==="}).has_value()); + BOOST_TEST(codecs::decode(base32, std::string_view{"MZXW6YQ="}).has_value()); + BOOST_TEST(codecs::decode(base32, std::string_view{"MZXW6YTB"}).has_value()); + BOOST_TEST(codecs::decode(base32, std::string_view{"MZXW6YTBMZXW6YQ="}).has_value()); +} + +/** + Every error with the padding omitted (by option): a `=` anywhere is padding against the option + (invalid_padding, "MZXW6===" the spec's), a length of remainder 1, 3 or 6 has no encoding + (invalid_length, "MZXW6YQ" valid), non-zero trailing bits are invalid_padding, and the faults of + two kinds give the lowest value. +*/ +void every_error_with_the_padding_omitted() { + auto const base32 = formats::base32(formats::padding::omitted); + constexpr auto character = codecs::error::invalid_character; + constexpr auto length = codecs::error::invalid_length; + constexpr auto padding = codecs::error::invalid_padding; + // The spec's scenarios: "MZXW6===" with the padding omitted, "MZXW6YQ" unpadded. + expect_refusal(base32, "MZXW6===", padding); + BOOST_TEST(codecs::decode(base32, std::string_view{"MZXW6YQ"}).has_value()); + expect_refusal(base32, "MY======", padding); + expect_refusal(base32, "MZXW6YQ=", padding); + expect_refusal(base32, "MZXW6YTB========", padding); + expect_refusal(base32, "MZXW6YTB=", length); + expect_refusal(base32, "M=", padding); + expect_refusal(base32, "MZXW6=", length); + expect_refusal(base32, "MZXW6Y=", padding); + expect_refusal(base32, "========", padding); + // Non-zero trailing bits. + expect_refusal(base32, "MZ", padding); + expect_refusal(base32, "MZXR", padding); + expect_refusal(base32, "MZXW7", padding); + expect_refusal(base32, "MZXW6YR", padding); + expect_refusal(base32, "MZXW6YTBMZ", padding); + // The remainders that have no encoding: 1, 3 and 6. + expect_refusal(base32, "M", length); + expect_refusal(base32, "MZX", length); + expect_refusal(base32, "MZXW6Y", length); + expect_refusal(base32, "MZXW6YTBM", length); + expect_refusal(base32, "MZXW6YTBMZX", length); + expect_refusal(base32, "MZXW6YTBMZXW6Y", length); + expect_refusal(base32, "MZXW6YTB\n", character); + expect_refusal(base32, "MZXW6YT\xc1", character); + expect_refusal(base32, "MZXW6Y 8", character); + // Two faults: the lowest value of error. + expect_refusal(base32, "MZ=\n", character); + expect_refusal(base32, "MZ======\n", character); + expect_refusal(base32, "MZX=", padding); + BOOST_TEST(codecs::decode(base32, std::string_view{"MY"}).has_value()); + BOOST_TEST(codecs::decode(base32, std::string_view{"MZXQ"}).has_value()); + BOOST_TEST(codecs::decode(base32, std::string_view{"MZXW6"}).has_value()); + BOOST_TEST(codecs::decode(base32, std::string_view{"MZXW6YTBMZXW6YQ"}).has_value()); + // base32hex, in both paddings, is the same format of the other alphabet. + auto const hex_unpadded = formats::base32hex(formats::padding::omitted); + expect_refusal(hex_unpadded, "CPNMU===", padding); + expect_refusal(hex_unpadded, "CPNMUO", length); + expect_refusal(hex_unpadded, "CPNMUOW", character); + expect_refusal(hex_unpadded, "MZXW6YQ", character); + BOOST_TEST(codecs::decode(hex_unpadded, std::string_view{"CPNMUOG"}).has_value()); + auto const hex_padded = formats::base32hex; + expect_refusal(hex_padded, "CPNMUOG", length); + expect_refusal(hex_padded, "CPNMUOH=", padding); + expect_refusal(hex_padded, "CO======W", character); + expect_refusal(hex_padded, "CO======0", length); + expect_refusal(hex_padded, "CP======", padding); + expect_refusal(hex_padded, "MZXW6YQ=", character); + expect_refusal(hex_padded, "cpnmuogw", character); + BOOST_TEST(codecs::decode(hex_padded, std::string_view{"CPNMUOG="}).has_value()); + BOOST_TEST(codecs::decode(hex_padded, std::string_view{"cpnmuog="}).has_value()); +} + +/** + The plain reading of `text`, compared with the library's decode and decoded_size for a + configuration: the same bytes, or the same error. +*/ +template +void expect_the_reference_reading(Format const& format, bool hex, bool padded, + std::string_view text) { + test::base32_reading const reference = test::reference_base32_decode(text, hex, padded); + auto const size = codecs::codec::decoded_size(format, text); + std::array buffer{}; + std::span const output = std::span{buffer}.first( + std::min(buffer.size(), codecs::max_decoded_size(format, text))); + auto const written = codecs::decode(format, text, output); + if (reference.fault) { + BOOST_TEST(!size.has_value() && size.error() == *reference.fault); + BOOST_TEST(!written.has_value() && written.error() == *reference.fault); + return; + } + BOOST_TEST(size.has_value() && size.value() == reference.bytes.size()); + BOOST_TEST(written.has_value() && written.value() == reference.bytes.size()); + BOOST_TEST(std::ranges::equal(output.first(reference.bytes.size()), reference.bytes)); +} + +/** Runs @ref expect_the_reference_reading in every configuration: both alphabets and paddings. */ +void expect_the_reference_reading_everywhere(std::string_view text) { + expect_the_reference_reading(formats::base32, false, true, text); + expect_the_reference_reading(formats::base32(formats::padding::omitted), false, false, text); + expect_the_reference_reading(formats::base32hex, true, true, text); + expect_the_reference_reading(formats::base32hex(formats::padding::omitted), true, false, text); +} + +/** + Review Focus 1: each of the 256 byte values as a character, `char` signed, at each place of a + text, in every configuration: the verdict and the bytes equal a plain reference's. NUL, 0x80 to + 0xff, the characters one past each range (the slash, the colon, the at sign, `[`, the backquote, + `{`), `=`, and the symbols of the other alphabet are among them. The places are the eight of a + group, in the first group and in the last, with the padding written and with it omitted, and as the + lone last character of a text of every remainder. +*/ +void every_byte_value_as_a_character() { + for (std::string_view const base : { + "MZXW6YTBOI======", + "MZXW6YTB", + "MY======", + "MZXQ====", + "MZXW6===", + "MZXW6YQ=", + "AAAAAAAAAAAAAAAA", + "MY", + "MZXQ", + "MZXW6", + "MZXW6YQ", + "MZXW6YTBMZ", + "cpnmuoj1e8======", + "CPNMUOG=", + "CPNMUOJ1", + "VVVVVV", + }) { + std::string const text{base}; + for (std::size_t place = 0; place <= base.size(); ++place) { + for (unsigned value = 0; value < 256; ++value) { + auto const character = static_cast(static_cast(value)); + std::string replaced = text; + if (place == base.size()) { + replaced.push_back(character); + } else { + replaced[place] = character; + } + expect_the_reference_reading_everywhere(replaced); + } + } + } + // The arithmetic alone: every byte against the plain table, in both alphabets and both cases. + for (bool const hex : {false, true}) { + std::string_view const symbols = test::base32_symbols(hex); + for (unsigned value = 0; value < 256; ++value) { + auto const character = static_cast(static_cast(value)); + std::size_t const at = symbols.find(test::base32_folded(character)); + auto const [five_bits, invalid] = + hex ? read_symbol(character) : read_symbol(character); + BOOST_TEST_EQ(invalid, at == std::string_view::npos); + BOOST_TEST_EQ(five_bits, at == std::string_view::npos ? 0U : static_cast(at)); + } + for (unsigned value = 0; value < 32; ++value) { + std::uint8_t const symbol = + hex ? detail::base32_arithmetic::symbol_of(static_cast(value)) + : detail::base32_arithmetic::symbol_of(static_cast(value)); + BOOST_TEST_EQ(static_cast(symbol), symbols[value]); + } + } +} + +/** + Texts near the valid ones, against the plain reference in every configuration: the base32 of + random bytes, from 0 to 40, with up to three characters replaced by a symbol of either alphabet, + `=`, a line feed or any byte, and cut or lengthened by up to two characters; decode and + decoded_size give the reference's bytes or error. +*/ +void texts_near_the_valid_ones() { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): a fixed seed + std::mt19937_64 generator{20261128}; + constexpr std::string_view odd_characters = "=01689 \n*\x7f\x80\xc1\xff-_azAZ"; + for (int iteration = 0; iteration < 5000; ++iteration) { + std::size_t const size = generator() % 41; + std::vector bytes(size); + for (std::uint8_t& byte : bytes) { + byte = static_cast(generator()); + } + bool const hex = (generator() & 1U) != 0; + bool const padded = (generator() & 1U) != 0; + std::string text = test::reference_base32_encode(bytes, hex, padded); + if ((generator() & 3U) == 0) { + text = test::ascii_lower_case(text); + } + for (std::size_t edits = generator() % 4; edits > 0 && !text.empty(); --edits) { + std::size_t const at = generator() % text.size(); + std::size_t const kind = generator() % 4; + if (kind == 0) { + text[at] = odd_characters[generator() % odd_characters.size()]; + } else if (kind == 1) { + text[at] = test::base32_symbols((generator() & 1U) != 0)[generator() % 32]; + } else if (kind == 2) { + text[at] = static_cast(generator()); + } else { + text[at] = '='; + } + } + if (generator() % 4 == 0 && !text.empty()) { + text.resize(text.size() - (generator() % std::min(3, text.size() + 1))); + } else if (generator() % 8 == 0) { + text.append(generator() % 3, 'A'); + } + expect_the_reference_reading_everywhere(text); + } +} + +/** + Review Focus 4: a text decoded into its own storage gives the right bytes, byte `i` written after + the characters it comes from are read; an invalid one leaves the storage as it was. Both + alphabets, both paddings, each length of the last group. +*/ +void decoding_in_place() { + for (std::size_t const size : + {0U, 1U, 2U, 3U, 4U, 5U, 6U, 7U, 8U, 9U, 10U, 31U, 32U, 33U, 100U}) { + std::vector const bytes = test::random_bytes(size); + test::expect_in_place(formats::base32, test::reference_base32_encode(bytes, false, true), + bytes); + test::expect_in_place(formats::base32(formats::padding::omitted), + test::reference_base32_encode(bytes, false, false), bytes); + test::expect_in_place(formats::base32hex, test::reference_base32_encode(bytes, true, true), + bytes); + test::expect_in_place(formats::base32hex(formats::padding::omitted), + test::reference_base32_encode(bytes, true, false), bytes); + } +} + +/** + Review Focus 3, the encodes: empty input in every form gives an empty result: the default results + in place and on the heap, the buffer form (0 written), the tokens, the secret token and the size. +*/ +void empty_input_in_every_encode() { + std::array const nothing{}; + auto const fixed = codecs::encode(formats::base32, nothing); + static_assert(std::is_same_v> const>); + BOOST_TEST(fixed.has_value() && fixed.value().size() == 0); + auto const heap = codecs::encode(formats::base32, std::vector{}); + BOOST_TEST(heap.has_value() && heap.value().empty()); + auto const hex = codecs::encode(formats::base32hex, std::string{}); + BOOST_TEST(hex.has_value() && hex.value().empty()); + auto const unpadded = codecs::encode(formats::base32(formats::padding::omitted), std::string{}); + BOOST_TEST(unpadded.has_value() && unpadded.value().empty()); + auto const unpadded_hex = + codecs::encode(formats::base32hex(formats::padding::omitted), std::string{}); + BOOST_TEST(unpadded_hex.has_value() && unpadded_hex.value().empty()); + auto const buffer_written = + codecs::encode(formats::base32, std::span{}, std::span{}); + BOOST_TEST(buffer_written.has_value() && buffer_written.value() == 0); + auto const returned = codecs::encode(formats::base32, nothing, tokens::return_string); + BOOST_TEST(returned.has_value() && returned.value().empty()); + std::string kept{"kept"}; + BOOST_TEST(codecs::encode(formats::base32, nothing, tokens::append_to(kept)).has_value()); + BOOST_TEST(kept == "kept"); + auto const secret_empty = codecs::encode(formats::base32, nothing, tokens::secret); + BOOST_TEST(secret_empty.has_value() && secret_empty.value().size() == 0); + BOOST_TEST_EQ(codecs::encoded_size(formats::base32, std::vector{}), 0U); + BOOST_TEST_EQ(codecs::encoded_size(formats::base32hex, std::vector{}), 0U); +} + +/** Review Focus 3, the decodes: an empty text gives an empty result in every form. */ +void empty_text_in_every_decode() { + for (formats::padding const option : {formats::padding::written, formats::padding::omitted}) { + test::expect_empty_text_decodes(formats::base32(option)); + test::expect_empty_text_decodes(formats::base32hex(option)); + } +} + +/** + The typed decodes: into an array of exactly N bytes (invalid_length otherwise), into bytes (up + to N, output_too_small otherwise), the heap, and a secret type, with no heap for the fixed ones. +*/ +void the_typed_decodes() { + std::array const digest = test::digest_bytes(); + auto const text = codecs::encode(formats::base32, digest); + BOOST_TEST(text.has_value() && text.value().size() == 56); + bool volatile verdict = false; + test::expect_no_allocation("typed decodes into fixed arrays", [&] { + auto const key = + codecs::decode>(formats::base32, text.value()); + auto const short_key = + codecs::decode>(formats::base32, text.value()); + auto const fixed = codecs::decode>(formats::base32, text.value()); + auto const too_small = codecs::decode>(formats::base32, text.value()); + verdict = key.has_value() && key.value() == digest && !short_key.has_value() && + short_key.error() == codecs::error::invalid_length && fixed.has_value() && + fixed.value().size() == 32 && !too_small.has_value() && + too_small.error() == codecs::error::output_too_small; + }); + BOOST_TEST(verdict); + // The text of 32 bytes without its padding. + auto const unpadded_text = codecs::encode(formats::base32(formats::padding::omitted), digest); + BOOST_TEST(unpadded_text.has_value() && unpadded_text.value().size() == 52); + auto const unpadded_key = codecs::decode>( + formats::base32(formats::padding::omitted), unpadded_text.value()); + BOOST_TEST(unpadded_key.has_value() && unpadded_key.value() == digest); + auto const hex_text = codecs::encode(formats::base32hex, digest); + auto const hex_key = + codecs::decode>(formats::base32hex, hex_text.value()); + BOOST_TEST(hex_key.has_value() && hex_key.value() == digest); + auto const heap = codecs::decode>(formats::base32, text.value()); + BOOST_TEST(heap.has_value() && std::ranges::equal(heap.value(), digest)); + auto const as_string = codecs::decode(formats::base32, text.value()); + BOOST_TEST(as_string.has_value() && as_string.value().size() == 32); +} + +} // namespace + +int main() { + rfc4648_vectors_in_both_alphabets(); + the_exact_size_and_the_bound(); + every_error_with_the_padding_written(); + every_error_with_the_padding_omitted(); + every_byte_value_as_a_character(); + texts_near_the_valid_ones(); + decoding_in_place(); + empty_input_in_every_encode(); + empty_text_in_every_decode(); + the_typed_decodes(); + return boost::report_errors(); +} diff --git a/test/base58_buffered_test.cpp b/test/base58_buffered_test.cpp new file mode 100644 index 0000000..9fdbecd --- /dev/null +++ b/test/base58_buffered_test.cpp @@ -0,0 +1,163 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// base58 as a stream (D19, D20, owner decision 19): base58 does not stream natively, and streams +// through codecs::buffered, which accumulates the input and converts it whole at flush. The spec's +// "Accumulating: base58 over byte chunks": 40 bytes sent to buffered(encoder(formats::base58), +// capacity<64>) in chunks of 7 give nothing before flush and the one-shot text after it, with +// nothing allocated. The spec's "base58 streams only through buffered", its second half: every pair +// of Bitcoin Core's base58_encode_decode.json through buffered(encoder(basic_base58<256, +// bitcoin_alphabet>{})), on the heap as the spec writes it and in place with a capacity of the +// instance's 256 bytes, and every text back through buffered(decoder(...)), for every chunking, +// public and secret (a secret encoder's buffered runs base58's secret conversion at flush, D21); +// its first half, drain refusing the one-shot encoder, is the message case drain_of_base58. A +// capacity past the instance's bound has no in-place output: the bound of an input past +// `maximum_bytes` saturates, as the core refuses such an input before it reads it, so that the +// in-place form takes a capacity of at most `maximum_bytes` bytes, and an input past its capacity +// or past the bound is input_too_long at flush. + +#include "support/counting.hpp" + +#include "support/bitcoin_base58_vectors.hpp" +#include "support/chunkings.hpp" +#include "support/samples.hpp" +#include "support/steps.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; + +using base58_256_t = formats::basic_base58<256, formats::bitcoin_alphabet>; +constexpr base58_256_t base58_256{}; + +/** + The spec's "Accumulating: base58 over byte chunks": 40 bytes in chunks of 7 to + buffered(encoder(formats::base58), capacity<64>); every receive before flush gives nothing, the + text after flush equals the one-shot base58, and nothing is allocated. +*/ +void accumulating_base58_over_byte_chunks() { + std::vector const input = test::random_bytes(40); + std::string const expected = codecs::encode(formats::base58, input).value(); + std::array text{}; + bool volatile verdict = true; + std::size_t received_count = 0; + test::expect_no_allocation("buffered(encoder(base58), capacity<64>)", [&] { + auto adapter = codecs::buffered(codecs::encoder(formats::base58), codecs::capacity<64>); + bool steps_hold = true; + for (std::size_t offset = 0; offset < input.size(); offset += 7) { + std::span const chunk = + std::span{input}.subspan(offset, std::min(7, input.size() - offset)); + steps_hold = + steps_hold && + test::is_step(adapter.send(chunk), chunk.size(), codecs::flow::needs_input) && + test::is_step(adapter.receive(std::span{text}), 0, codecs::flow::needs_input); + } + steps_hold = steps_hold && test::is_flow(adapter.flush(), codecs::flow::output_pending); + auto const received = adapter.receive(std::span{text}); + steps_hold = steps_hold && received.has_value() && received->flow == codecs::flow::finished; + received_count = received.has_value() ? received->count : 0; + verdict = steps_hold; + }); + BOOST_TEST(verdict); + BOOST_TEST(std::string_view(text.data(), received_count) == expected); +} + +/** Streams every vector's bytes through `encoder` and its text through `decoder`, every chunking. + */ +template +void every_vector_through(Encoder& encoder, Decoder& decoder, + std::vector const& vectors) { + for (test::bitcoin_base58_vector const& vector : vectors) { + test::expect_every_chunking(encoder, std::span{vector.bytes}, + test::characters_of(vector.text)); + test::expect_every_chunking(decoder, test::characters_of(vector.text), + std::span{vector.bytes}); + } +} + +/** + The spec's "base58 streams only through buffered", its second half: every pair of the file + through buffered over basic_base58<256>'s encoder and decoder, for every chunking and output spans + of 1 and 1024, gives the file's text and bytes: on the heap, as the spec writes it, in place, and + secret in both. +*/ +void every_vector_through_buffered() { + std::vector const vectors = test::read_bitcoin_base58_vectors(); + BOOST_TEST_EQ(vectors.size(), 21U); + auto heap_encoder = codecs::buffered(codecs::encoder(base58_256)); + auto heap_decoder = codecs::buffered(codecs::decoder(base58_256)); + every_vector_through(heap_encoder, heap_decoder, vectors); + auto encoder = codecs::buffered(codecs::encoder(base58_256), codecs::capacity<256>); + auto decoder = codecs::buffered(codecs::decoder(base58_256), + codecs::capacity); + every_vector_through(encoder, decoder, vectors); + auto secret_encoder = codecs::buffered(codecs::encoder(base58_256, codecs::secret_operation), + codecs::capacity<256>); + auto secret_decoder = codecs::buffered(codecs::decoder(base58_256, codecs::secret_operation), + codecs::capacity); + static_assert(codecs::is_secret_v); + every_vector_through(secret_encoder, secret_decoder, vectors); + auto secret_heap_encoder = + codecs::buffered(codecs::encoder(base58_256, codecs::secret_operation)); + auto secret_heap_decoder = + codecs::buffered(codecs::decoder(base58_256, codecs::secret_operation)); + every_vector_through(secret_heap_encoder, secret_heap_decoder, vectors); +} + +/** + The refusals at flush: an input past the capacity, an input past formats::base58's 100 bytes on + the heap and a text that decodes to more than 100 bytes are input_too_long, a character outside + the alphabet invalid_character, each reported at flush, writing nothing (B44). +*/ +void the_refusals_at_flush() { + std::vector const past_capacity = test::random_bytes(65); + auto in_place = codecs::buffered(codecs::encoder(formats::base58), codecs::capacity<64>); + std::array, 1> const capacity_chunks{std::span{past_capacity}}; + BOOST_TEST(test::error_after_flush(in_place, capacity_chunks, 8) == + codecs::error::input_too_long); + std::vector const past_bound = test::random_bytes(101); + auto heap = codecs::buffered(codecs::encoder(formats::base58)); + std::array, 2> const bound_chunks{ + std::span{past_bound}.first(50), + std::span{past_bound}.subspan(50), + }; + BOOST_TEST(test::error_after_flush(heap, bound_chunks, 8) == codecs::error::input_too_long); + std::string const too_many_bytes(137, 'z'); + auto decoder = + codecs::buffered(codecs::decoder(formats::base58), + codecs::capacity); + std::array, 1> const text_chunks{test::characters_of(too_many_bytes)}; + BOOST_TEST(test::error_after_flush(decoder, text_chunks, 8) == codecs::error::input_too_long); + decoder.reset(); + std::array, 1> const invalid_chunks{test::characters_of("2g0")}; + BOOST_TEST(test::error_after_flush(decoder, invalid_chunks, 8) == + codecs::error::invalid_character); +} + +} // namespace + +int main() { + accumulating_base58_over_byte_chunks(); + every_vector_through_buffered(); + the_refusals_at_flush(); + return boost::report_errors(); +} diff --git a/test/base58_test.cpp b/test/base58_test.cpp new file mode 100644 index 0000000..e82280c --- /dev/null +++ b/test/base58_test.cpp @@ -0,0 +1,817 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// base58, the format (D13, owner decisions 25 and 26, the spec's "Format: base58"): Bitcoin Core's +// base58_encode_decode.json, read at run time (ruling R8), its 20 pairs of at most 100 bytes +// through formats::base58 and all 21 through basic_base58<256, bitcoin_alphabet>, each public and +// secret (a secret type of the test's own of each length the file holds, through tokens::secret), +// and its 256-byte pair refused by formats::base58 (the spec's "Bitcoin Core's vectors"); the three +// named alphabets on one input, and an alphabet of the test's own, Bitcoin's reversed (the spec's +// "An alphabet of the program's own", its first half); each instance's bounds, the default's 100 +// bytes and 137 characters and a larger instance's (the spec's "The default's bound and a larger +// instance"), with the decoded payload's bound (pre-flight F12); every byte value as a character at +// each place of a text, against a plain table, public and secret, with `char` signed (Review Focus +// 1); the bounds saturating at SIZE_MAX past each instance's bound (Review Focus 2); empty input in +// every form (Review Focus 3); the public and the secret conversions equal over random inputs. A +// text is never decoded into its own storage: the format's page says input and output must not +// overlap (Review Focus 4). basic_base58<16384, bitcoin_alphabet>'s sizes and buffer forms are +// checked at compile time alone: its scratch of 22375 bytes on the stack is too large for the +// WebAssembly lanes' stacks. + +#include "support/base58_checksum.hpp" +#include "support/bitcoin_base58_vectors.hpp" +#include "support/samples.hpp" +#include "support/steps.hpp" + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +/** A secret type of the test's own: `N` bytes of a constant size, a byte input, as key32. */ +template +class secret_key { +public: + /** The size. */ + static constexpr std::size_t size() noexcept { return N; } + + /** The bytes. */ + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) + operator std::span() const& noexcept { return held_bytes; } + + /** The bytes, written by the test. */ + std::array held_bytes{}; +}; + +} // namespace + +namespace webcpp::codecs::test { +namespace { + +/** An alphabet of the test's own: Bitcoin's characters reversed. */ +struct reversed_alphabet { + /** The characters, digit 0 first. */ + static constexpr std::string_view characters = + "zyxwvutsrqponmkjihgfedcbaZYXWVUTSRQPNMLKJHGFEDCBA987654321"; +}; + +} // namespace + +} // namespace webcpp::codecs::test + +namespace webcpp::codecs { + +/** secret_key is secret. */ +template +struct is_secret<::secret_key> : std::true_type {}; + +} // namespace webcpp::codecs + +namespace { + +namespace codecs = webcpp::codecs; +namespace detail = webcpp::codecs::detail; +namespace formats = webcpp::codecs::formats; +namespace secure = webcpp::secure; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +constexpr std::size_t size_maximum = std::numeric_limits::max(); + +using base58_codec = codecs::codec; +using base58_256_t = formats::basic_base58<256, formats::bitcoin_alphabet>; +using base58_1024_t = formats::basic_base58<1024, formats::bitcoin_alphabet>; +using base58_16384_t = formats::basic_base58<16384, formats::bitcoin_alphabet>; +using reversed_t = formats::basic_base58<100, test::reversed_alphabet>; + +constexpr base58_256_t base58_256{}; +constexpr base58_1024_t base58_1024{}; +constexpr reversed_t base58_reversed{}; + +/** Bitcoin's characters, digit 0 first, for the test's plain tables. */ +constexpr std::string_view bitcoin_characters = + "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + +// The format (owner decisions 25 and 26): a type over its bound, its alphabet and its checksum. +static_assert(codecs::format); +static_assert(formats::base58_bitcoin_t::name == "base58"); +static_assert(formats::base58_ripple_t::name == "base58"); +static_assert(std::is_same_v); +static_assert(std::is_same_v>); +static_assert( + std::is_same_v>); +static_assert( + std::is_same_v>); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(formats::base58_alphabet); +static_assert(formats::base58_alphabet); +static_assert(!formats::base58_alphabet); +static_assert(formats::base58_checksum); +static_assert(!formats::base58_checksum); +static_assert(formats::bitcoin_alphabet::characters == bitcoin_characters); + +// The bounds of each instance (owner decision 25, F12): maximum_characters derived from the payload +// and the checksum, the number of base-58 digits of 256^n - 1. +static_assert(formats::base58_bitcoin_t::maximum_bytes == 100); +static_assert(formats::base58_bitcoin_t::checksum_size == 0); +static_assert(formats::base58_bitcoin_t::maximum_characters == 137); +static_assert(formats::base58_ripple_t::maximum_characters == 137); +static_assert(formats::base58_flickr_t::maximum_characters == 137); +static_assert(base58_256_t::maximum_characters == 350); +static_assert(base58_1024_t::maximum_characters == 1399); +static_assert(base58_16384_t::maximum_characters == 22375); +static_assert(test::base58_with_checksum_t::maximum_bytes == 100); +static_assert(test::base58_with_checksum_t::checksum_size == 4); +static_assert(test::base58_with_checksum_t::maximum_characters == 143); +static_assert(detail::base58_encoded_length(0) == 0); +static_assert(detail::base58_encoded_length(1) == 2); +static_assert(detail::base58_encoded_length(104) == 143); +static_assert(detail::base58_encoded_length(256) == 350); +static_assert(detail::base58_length_is_exact(16384)); +static_assert(detail::base58_length_is_exact(2'038'747)); +static_assert(!detail::base58_length_is_exact(2'038'748)); +static_assert(detail::base58_encoded_length(size_maximum) == size_maximum); +static_assert(detail::is_base58_alphabet(bitcoin_characters)); +static_assert(!detail::is_base58_alphabet(bitcoin_characters.substr(1))); +static_assert( + !detail::is_base58_alphabet("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxy1")); + +// Its codec: constant time only when secret (B24), with the secret overloads the core calls (R7). +static_assert(!base58_codec::constant_time); +static_assert(base58_codec::constant_time_when_secret); +static_assert(!codecs::codec::constant_time); +static_assert(codecs::codec::constant_time_when_secret); +static_assert(codecs::codec::constant_time_when_secret); +static_assert(!codecs::is_constant_time_v); +static_assert(detail::has_secret_encoded_size); +static_assert(detail::has_secret_decoded_size); +static_assert(detail::has_secret_encode); +static_assert(detail::has_secret_decode); +static_assert(detail::secret_overloads_match); +static_assert(!detail::takes_configuration_fault); + +// The bounds saturate past each instance's (Review Focus 2): the core refuses an input past 100 +// bytes and a text past 137 characters before it reads them; on a 32-bit std::size_t too. +static_assert(base58_codec::max_encoded_size(0) == 0); +static_assert(base58_codec::max_encoded_size(32) == 44); +static_assert(base58_codec::max_encoded_size(100) == 137); +static_assert(base58_codec::max_encoded_size(101) == size_maximum); +static_assert(base58_codec::max_encoded_size(size_maximum) == size_maximum); +static_assert(base58_codec::max_decoded_size(0) == 0); +static_assert(base58_codec::max_decoded_size(44) == 44); +static_assert(base58_codec::max_decoded_size(137) == 100); +static_assert(base58_codec::max_decoded_size(138) == size_maximum); +static_assert(base58_codec::max_decoded_size(size_maximum) == size_maximum); +static_assert(codecs::codec::max_encoded_size(0) == 6); +static_assert(codecs::codec::max_decoded_size(3) == 0); +static_assert(codecs::codec::max_decoded_size(143) == 100); +static_assert(codecs::codec::max_encoded_size(1024) == 1399); +static_assert(codecs::codec::max_encoded_size(1025) == size_maximum); +static_assert(codecs::detail::input_size_fault(formats::base58, 101) == + codecs::error::input_too_long); +static_assert(!codecs::detail::input_size_fault(formats::base58, 100).has_value()); +static_assert(codecs::detail::text_size_fault(formats::base58, 138) == + codecs::error::input_too_long); +static_assert(!codecs::detail::text_size_fault(formats::base58, 137).has_value()); +// The exact size is a constant expression, by Bitcoin Core's conversion. +static_assert(codecs::encoded_size(formats::base58, std::array{0x61}) == 2); +static_assert(codecs::encoded_size(formats::base58, std::array{0, 0, 1}) == 3); +static_assert(codecs::encoded_size(formats::base58, std::array{}) == 0); +static_assert(codecs::max_decoded_size(formats::base58, std::string_view{"2g"}) == 2); + +// The default results (D9): in place for a size known at compile time, the heap otherwise. +static_assert( + std::is_same_v const&>())), + codecs::result>>); +static_assert(std::is_same_v const&>())), + codecs::result>>); +static_assert(std::is_same_v>())), + codecs::result>); +static_assert(std::is_same_v>>); + +// Every function of the codec allocates nothing and is noexcept, for every instance, its scratch in +// place (owner decision 25): basic_base58<16384>'s are checked here alone, never run. +using codec_16384 = codecs::codec; +static_assert(noexcept(codec_16384::max_encoded_size(0))); +static_assert(noexcept(codec_16384::max_decoded_size(0))); +static_assert(noexcept(codec_16384::encoded_size(base58_16384_t{}, + std::span{}))); +static_assert(noexcept(codec_16384::decoded_size(base58_16384_t{}, std::string_view{}))); +static_assert(noexcept(codec_16384::encode(base58_16384_t{}, std::span{}, + std::span{}))); +static_assert(noexcept(codec_16384::decode(base58_16384_t{}, std::string_view{}, + std::span{}))); +static_assert(noexcept(codecs::encode(base58_16384_t{}, std::span{}, + std::span{}))); +static_assert(noexcept(codecs::decode(base58_16384_t{}, std::string_view{}, + std::span{}))); +static_assert(noexcept(codecs::encoded_size(base58_16384_t{}, std::array{}))); +static_assert(noexcept(codecs::encoded_size(base58_16384_t{}, std::declval>()))); +static_assert(noexcept(codecs::encode(base58_16384_t{}, std::declval>(), + std::span{}))); + +/** Whether `decoded` holds `expected`. */ +template +bool decodes_to(Result const& decoded, std::span expected) { + return decoded.has_value() && std::ranges::equal(test::bytes_in(decoded.value()), expected); +} + +/** `count` bytes of `value`. */ +std::vector repeated_bytes(std::size_t count, std::uint8_t value) { + std::vector bytes(count, value); + return bytes; +} + +/** + Checks one pair of the file through `format` publicly, in every form: the default result, the + buffer form, a token, the exact sizes. +*/ +template +void expect_public_pair(Format const& format, test::bitcoin_base58_vector const& vector) { + auto const encoded = codecs::encode(format, vector.bytes); + BOOST_TEST(encoded.has_value() && encoded.value() == vector.text); + BOOST_TEST_EQ(codecs::encoded_size(format, vector.bytes), vector.text.size()); + std::vector buffer(vector.text.size() + 1, '~'); + auto const written = codecs::encode(format, vector.bytes, std::span{buffer}); + BOOST_TEST(written.has_value() && written.value() == vector.text.size()); + BOOST_TEST(std::string_view(buffer.data(), vector.text.size()) == vector.text); + BOOST_TEST_EQ(buffer.back(), '~'); + BOOST_TEST(decodes_to(codecs::decode(format, vector.text), vector.bytes)); + std::vector decoded(vector.bytes.size() + 1, 0x5a); + auto const decoded_count = codecs::decode(format, vector.text, std::span{decoded}); + BOOST_TEST(decoded_count.has_value() && decoded_count.value() == vector.bytes.size()); + BOOST_TEST(std::ranges::equal(std::span{decoded}.first(vector.bytes.size()), vector.bytes)); + BOOST_TEST_EQ(decoded.back(), 0x5aU); + // The typed form: the bytes as the type of the program's choice. + auto const typed = codecs::decode>(format, vector.text); + BOOST_TEST(typed.has_value() && std::ranges::equal(typed.value(), vector.bytes)); + std::vector appended{0x01}; + BOOST_TEST(codecs::decode(format, vector.text, tokens::append_to(appended)).has_value()); + BOOST_TEST_EQ(appended.size(), vector.bytes.size() + 1); + auto const size = codecs::codec::decoded_size(format, vector.text); + BOOST_TEST(size.has_value() && size.value() == vector.bytes.size()); +} + +/** Checks one pair of the file through `format` as secret operations, from a secret_key. */ +template +void expect_secret_pair(Format const& format, secret_key const& key, + test::bitcoin_base58_vector const& vector) { + auto const encoded = codecs::encode(format, key, tokens::secret); + BOOST_TEST(encoded.has_value() && test::text_of(encoded.value()) == vector.text); + BOOST_TEST_EQ(codecs::encoded_size(format, key), vector.text.size()); + auto const decoded = codecs::decode(format, vector.text, tokens::secret); + BOOST_TEST(decodes_to(decoded, vector.bytes)); + auto const secret_size = + codecs::codec::decoded_size(detail::secret_tag{}, format, vector.text); + BOOST_TEST(secret_size.has_value() && secret_size.value() == vector.bytes.size()); +} + +/** + The pairs of `N` bytes, public and secret: through formats::base58 up to 100 bytes and refused + past them, and through basic_base58<256> each. Returns the pairs checked. +*/ +template +std::size_t check_pairs_of_length(std::vector const& vectors) { + std::size_t checked = 0; + for (test::bitcoin_base58_vector const& vector : vectors) { + if (vector.bytes.size() != N) { + continue; + } + ++checked; + secret_key key; + std::ranges::copy(vector.bytes, key.held_bytes.begin()); + expect_public_pair(base58_256, vector); + expect_secret_pair(base58_256, key, vector); + if constexpr (N <= 100) { + expect_public_pair(formats::base58, vector); + expect_secret_pair(formats::base58, key, vector); + } else { + BOOST_TEST(test::failed_with(codecs::encode(formats::base58, vector.bytes), + codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(codecs::encode(formats::base58, key, tokens::secret), + codecs::error::input_too_long)); + BOOST_TEST_EQ(codecs::encoded_size(formats::base58, vector.bytes), size_maximum); + BOOST_TEST(test::failed_with(codecs::decode(formats::base58, vector.text), + codecs::error::input_too_long)); + BOOST_TEST( + test::failed_with(codecs::decode(formats::base58, vector.text, tokens::secret), + codecs::error::input_too_long)); + } + } + return checked; +} + +/** The pairs of each length the file holds. */ +template +std::size_t check_pairs(std::vector const& vectors, + std::index_sequence /*lengths*/) { + return (check_pairs_of_length(vectors) + ...); +} + +/** + The spec's "Bitcoin Core's vectors": the file's 21 pairs, of 0 to 256 bytes, each text and byte + string the file's, through formats::base58 the 20 of at most 100 bytes and through + basic_base58<256> all, public and secret; the 256-byte input, 0x00 to 0xff, and its 348-character + text are input_too_long through formats::base58. +*/ +void bitcoin_cores_vectors() { + std::vector const vectors = test::read_bitcoin_base58_vectors(); + BOOST_TEST_EQ(vectors.size(), 21U); + std::size_t at_most_100 = 0; + std::size_t largest = 0; + for (test::bitcoin_base58_vector const& vector : vectors) { + at_most_100 += vector.bytes.size() <= 100 ? 1 : 0; + largest = std::max(largest, vector.bytes.size()); + } + BOOST_TEST_EQ(at_most_100, 20U); + BOOST_TEST_EQ(largest, 256U); + std::size_t const checked = + check_pairs(vectors, std::index_sequence<0, 1, 3, 4, 5, 9, 10, 20, 25, 40, 43, 98, 256>{}); + BOOST_TEST_EQ(checked, vectors.size()); + // The largest is the bytes 0x00 to 0xff. + auto const all_bytes = std::ranges::find_if( + vectors, + [](test::bitcoin_base58_vector const& vector) { return vector.bytes.size() == 256; }); + if (BOOST_TEST(all_bytes != vectors.end())) { + BOOST_TEST_EQ(all_bytes->text.size(), 348U); + for (std::size_t index = 0; index < all_bytes->bytes.size(); ++index) { + BOOST_TEST_EQ(static_cast(all_bytes->bytes[index]), index); + } + } +} + +/** The text of `bitcoin_text` with each character replaced by the character of its digit in `to`. + */ +std::string translated(std::string_view bitcoin_text, std::string_view to) { + std::string text; + for (char const character : bitcoin_text) { + text += to[bitcoin_characters.find(character)]; + } + return text; +} + +/** The input the alphabets are compared on: two leading zero bytes, then bytes of every range. */ +std::vector alphabets_input() { + return { + 0x00, 0x00, 0x01, 0x02, 0x03, 0xfe, 0xff, 0x7f, 0x80, + 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x99, + }; +} + +/** + The three named alphabets on one input, and the spec's "An alphabet of the program's own", its + first half: Ripple's, Flickr's and the test's reversed alphabet's texts are Bitcoin's with each + character replaced by the character of the same digit, and each round trips. +*/ +void the_alphabets() { + std::vector const input = alphabets_input(); + auto const bitcoin = codecs::encode(formats::base58_bitcoin, input); + BOOST_TEST(bitcoin.has_value()); + BOOST_TEST(codecs::encode(formats::base58, input).value() == bitcoin.value()); + BOOST_TEST(bitcoin.value().starts_with("11")); + auto const ripple = codecs::encode(formats::base58_ripple, input); + BOOST_TEST(ripple.has_value() && + ripple.value() == translated(bitcoin.value(), formats::ripple_alphabet::characters)); + BOOST_TEST(ripple.value().starts_with("rr")); + auto const flickr = codecs::encode(formats::base58_flickr, input); + BOOST_TEST(flickr.has_value() && + flickr.value() == translated(bitcoin.value(), formats::flickr_alphabet::characters)); + auto const reversed = codecs::encode(base58_reversed, input); + BOOST_TEST(reversed.has_value() && + reversed.value() == + translated(bitcoin.value(), test::reversed_alphabet::characters)); + BOOST_TEST(reversed.value().starts_with("zz")); + BOOST_TEST(decodes_to(codecs::decode(formats::base58_ripple, ripple.value()), input)); + BOOST_TEST(decodes_to(codecs::decode(formats::base58_flickr, flickr.value()), input)); + BOOST_TEST(decodes_to(codecs::decode(base58_reversed, reversed.value()), input)); + // The secret conversions read each alphabet too. + secret_key<17> key; + std::ranges::copy(input, key.held_bytes.begin()); + BOOST_TEST(test::text_of(codecs::encode(formats::base58_ripple, key).value()) == + ripple.value()); + BOOST_TEST(test::text_of(codecs::encode(base58_reversed, key).value()) == reversed.value()); + BOOST_TEST( + decodes_to(codecs::decode(base58_reversed, reversed.value(), tokens::secret), input)); + BOOST_TEST( + decodes_to(codecs::decode(formats::base58_flickr, flickr.value(), tokens::secret), input)); +} + +/** + The alphabets' refusals: `0`, absent from Ripple's and from the test's reversed alphabet, is + invalid_character in each, public and secret, and Bitcoin's text is no Ripple text of the input. +*/ +void the_alphabets_refusals() { + std::vector const input = alphabets_input(); + auto const bitcoin = codecs::encode(formats::base58_bitcoin, input); + for (std::string_view const zero : {"0", "z0", "10"}) { + BOOST_TEST(test::failed_with(codecs::decode(base58_reversed, zero), + codecs::error::invalid_character)); + BOOST_TEST(test::failed_with(codecs::decode(formats::base58_ripple, zero), + codecs::error::invalid_character)); + BOOST_TEST(test::failed_with(codecs::decode(base58_reversed, zero, tokens::secret), + codecs::error::invalid_character)); + } + BOOST_TEST(!decodes_to(codecs::decode(formats::base58_ripple, bitcoin.value()), input)); +} + +/** + The refusals of the spec's "Format: base58": `0`, `O`, `I` and `l`, which Bitcoin's alphabet + leaves out, a space, a line feed and a NUL are invalid_character in every form, public and + secret; a short buffer is output_too_small with nothing written; within the bounds, the + character's fault wins over the decoded payload's length (B23). +*/ +void the_refusals() { + for (std::string_view const text : { + std::string_view{"0"}, + std::string_view{"O"}, + std::string_view{"I"}, + std::string_view{"l"}, + std::string_view{"2g0"}, + std::string_view{"1O"}, + std::string_view{" 2g"}, + std::string_view{"2g\n"}, + std::string_view{"2\0g", 3}, + }) { + BOOST_TEST(test::failed_with(codecs::decode(formats::base58, text), + codecs::error::invalid_character)); + BOOST_TEST(test::failed_with(codecs::decode(formats::base58, text, tokens::secret), + codecs::error::invalid_character)); + BOOST_TEST(test::failed_with(base58_codec::decoded_size(formats::base58, text), + codecs::error::invalid_character)); + } + // A short buffer: nothing is written. + std::vector const input{0x00, 0x61, 0x62}; + std::array buffer{}; + buffer.fill('~'); + BOOST_TEST(test::failed_with(codecs::encode(formats::base58, input, std::span{buffer}.first(3)), + codecs::error::output_too_small)); + BOOST_TEST( + test::failed_with(base58_codec::encode(formats::base58, input, std::span{buffer}.first(3)), + codecs::error::output_too_small)); + BOOST_TEST(std::ranges::all_of(buffer, [](char character) { return character == '~'; })); + std::array bytes{}; + bytes.fill(0x5a); + BOOST_TEST(test::failed_with( + codecs::decode(formats::base58, std::string_view{"1a3gV"}, std::span{bytes}.first(3)), + codecs::error::output_too_small)); + BOOST_TEST(test::failed_with( + base58_codec::decode(formats::base58, std::string_view{"1a3gV"}, std::span{bytes}.first(3)), + codecs::error::output_too_small)); + BOOST_TEST(test::failed_with( + base58_codec::decode(detail::secret_tag{}, formats::base58, std::string_view{"1a3gV"}, + std::span{bytes}.first(3)), + codecs::error::output_too_small)); + BOOST_TEST(std::ranges::all_of(bytes, [](std::uint8_t byte) { return byte == 0x5a; })); + // 137 characters whose payload would be 101 bytes, with a character outside the alphabet: + // invalid_character, the lowest value. + std::string with_fault(137, 'z'); + with_fault[70] = '0'; + BOOST_TEST(test::failed_with(codecs::decode(formats::base58, with_fault), + codecs::error::invalid_character)); + BOOST_TEST(test::failed_with(codecs::decode(formats::base58, with_fault, tokens::secret), + codecs::error::invalid_character)); + // A text past the bound is refused by its length before it is read: input_too_long, the only + // fault reported. + std::string past_bound(138, '2'); + past_bound[0] = '0'; + BOOST_TEST(test::failed_with(codecs::decode(formats::base58, past_bound), + codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(base58_codec::decoded_size(formats::base58, past_bound), + codecs::error::input_too_long)); + // Every form gives the error, and a token is left as it was. + std::vector appended{0x5a}; + BOOST_TEST( + test::failed_with(codecs::decode(formats::base58, "2gO", tokens::append_to(appended)), + codecs::error::invalid_character)); + BOOST_TEST(appended == std::vector{0x5a}); + BOOST_TEST(test::failed_with(codecs::decode>(formats::base58, "zl"), + codecs::error::invalid_character)); +} + +/** + Decodes the text `text` publicly and secretly, in the buffer form and through the size, and checks + the verdict against `valid`, the plain table's; a valid text decodes alike in both and encodes + back to itself. +*/ +void expect_text_verdict(std::string_view text, bool valid) { + std::array decoded{}; + decoded.fill(0x5a); + auto const written = codecs::decode(formats::base58, text, std::span{decoded}); + auto const secret_written = + base58_codec::decode(detail::secret_tag{}, formats::base58, text, std::span{decoded}); + auto const size = base58_codec::decoded_size(formats::base58, text); + auto const secret_size = + base58_codec::decoded_size(detail::secret_tag{}, formats::base58, text); + if (!valid) { + BOOST_TEST(test::failed_with(written, codecs::error::invalid_character)); + BOOST_TEST(test::failed_with(secret_written, codecs::error::invalid_character)); + BOOST_TEST(test::failed_with(size, codecs::error::invalid_character)); + BOOST_TEST(test::failed_with(secret_size, codecs::error::invalid_character)); + BOOST_TEST(std::ranges::all_of(decoded, [](std::uint8_t byte) { return byte == 0x5a; })); + return; + } + BOOST_TEST(written.has_value() && secret_written.has_value() && + written.value() == secret_written.value()); + BOOST_TEST(size.has_value() && secret_size.has_value() && size.value() == written.value() && + secret_size.value() == written.value()); + if (written.has_value()) { + auto const encoded = + codecs::encode(formats::base58, std::span{decoded}.first(written.value())); + BOOST_TEST(encoded.has_value() && encoded.value() == text); + } +} + +/** + Review Focus 1: each of the 256 byte values as a character, `char` signed, at the first place, in + a run of leading `1`s, after one, in the middle of a number and last: the verdict equals the + plain table's (Bitcoin's characters), public and secret. NUL, 0x80 to 0xff, `0`, `O`, `I`, `l` + and the characters one past each range of the alphabet (the slash, the colon, the at sign, the + opening bracket, the backquote and the opening brace) are invalid_character. +*/ +void every_byte_value_as_a_character() { + for (unsigned value = 0; value < 256; ++value) { + auto const character = static_cast(static_cast(value)); + bool const valid = bitcoin_characters.find(character) != std::string_view::npos; + for (std::string text : { + std::string{"X"}, + std::string{"11X"}, + std::string{"1X1"}, + std::string{"2gX2"}, + std::string{"zX"}, + std::string{"2gaX"}, + }) { + text[text.find('X')] = character; + expect_text_verdict(text, valid); + } + } + // The table holds 58 characters and none of the four Bitcoin leaves out. + std::size_t valid_count = 0; + for (unsigned value = 0; value < 256; ++value) { + valid_count += + bitcoin_characters.find(static_cast(static_cast(value))) != + std::string_view::npos + ? 1 + : 0; + } + BOOST_TEST_EQ(valid_count, 58U); + for (char const left_out : {'0', 'O', 'I', 'l', '/', ':', '@', '[', '`', '{'}) { + BOOST_TEST(bitcoin_characters.find(left_out) == std::string_view::npos); + } +} + +/** + The default's bound (owner decision 25, F12): through formats::base58, 100 bytes of 0xff round + trip in 137 characters, public and secret, and 100 `1`s are 100 zero bytes both ways. +*/ +void the_default_bound() { + std::vector const hundred = repeated_bytes(100, 0xff); + auto const hundred_text = codecs::encode(formats::base58, hundred); + BOOST_TEST(hundred_text.has_value() && hundred_text.value().size() == 137); + BOOST_TEST(decodes_to(codecs::decode(formats::base58, hundred_text.value()), hundred)); + BOOST_TEST( + decodes_to(codecs::decode(formats::base58, hundred_text.value(), tokens::secret), hundred)); + secret_key<100> hundred_key; + std::ranges::copy(hundred, hundred_key.held_bytes.begin()); + BOOST_TEST(test::text_of(codecs::encode(formats::base58, hundred_key).value()) == + hundred_text.value()); + + // 100 `1`s decode to 100 zero bytes, and 100 zero bytes encode to them. + std::string const hundred_ones(100, '1'); + BOOST_TEST(decodes_to(codecs::decode(formats::base58, hundred_ones), repeated_bytes(100, 0))); + BOOST_TEST(codecs::encode(formats::base58, repeated_bytes(100, 0)).value() == hundred_ones); +} + +/** + The spec's "The default's bound and a larger instance", the default's half: through + formats::base58, 101 bytes are input_too_long from encode, encoded_size and the buffer form, and + 138 characters, 137 `1`s (137 zero bytes) and 137 `z`s (101 bytes) from decode, public and secret. +*/ +void past_the_default_bound() { + std::vector const past = repeated_bytes(101, 0xff); + BOOST_TEST( + test::failed_with(codecs::encode(formats::base58, past), codecs::error::input_too_long)); + BOOST_TEST_EQ(codecs::encoded_size(formats::base58, past), size_maximum); + BOOST_TEST_EQ(base58_codec::encoded_size(formats::base58, past), size_maximum); + BOOST_TEST_EQ(base58_codec::encoded_size(detail::secret_tag{}, formats::base58, past), + size_maximum); + std::array buffer{}; + BOOST_TEST(test::failed_with(codecs::encode(formats::base58, past, std::span{buffer}), + codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(base58_codec::encode(formats::base58, past, std::span{buffer}), + codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(codecs::encode(formats::base58, past, tokens::return_string), + codecs::error::input_too_long)); + secret_key<101> past_key; + past_key.held_bytes.fill(0xff); + BOOST_TEST(test::failed_with(codecs::encode(formats::base58, past_key, tokens::secret), + codecs::error::input_too_long)); + BOOST_TEST_EQ(codecs::encoded_size(formats::base58, past_key), size_maximum); + std::array bytes{}; + for (std::string const& text : + {std::string(138, '2'), std::string(137, '1'), std::string(137, 'z')}) { + BOOST_TEST(test::failed_with(codecs::decode(formats::base58, text), + codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(codecs::decode(formats::base58, text, std::span{bytes}), + codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(codecs::decode(formats::base58, text, tokens::secret), + codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(base58_codec::decoded_size(formats::base58, text), + codecs::error::input_too_long)); + } +} + +/** + The spec's "The default's bound and a larger instance", the larger instance's half: through + basic_base58<1024, bitcoin_alphabet>, the same 101 bytes round trip, 1024 bytes of 0xff round trip + in 1399 characters, and 1025 bytes, 1400 characters, 1399 `1`s and 1399 `z`s (1025 bytes) are + input_too_long, public and secret. +*/ +void a_larger_instance() { + std::vector const past = repeated_bytes(101, 0xff); + secret_key<101> past_key; + past_key.held_bytes.fill(0xff); + auto const past_text = codecs::encode(base58_1024, past); + BOOST_TEST(past_text.has_value() && past_text.value().size() == 138); + BOOST_TEST(decodes_to(codecs::decode(base58_1024, past_text.value()), past)); + BOOST_TEST( + test::text_of(codecs::encode(base58_1024, past_key, tokens::secret).value()).size() == 138); + std::vector const most = repeated_bytes(1024, 0xff); + auto const most_text = codecs::encode(base58_1024, most); + BOOST_TEST(most_text.has_value() && most_text.value().size() == 1399); + BOOST_TEST(decodes_to(codecs::decode(base58_1024, most_text.value()), most)); + BOOST_TEST(decodes_to(codecs::decode(base58_1024, most_text.value(), tokens::secret), most)); + BOOST_TEST(test::text_of(codecs::encode(base58_1024, most, tokens::secret).value()) == + most_text.value()); + std::vector const too_many = repeated_bytes(1025, 0xff); + BOOST_TEST( + test::failed_with(codecs::encode(base58_1024, too_many), codecs::error::input_too_long)); + BOOST_TEST_EQ(codecs::encoded_size(base58_1024, too_many), size_maximum); + for (std::string const& text : + {std::string(1400, '2'), std::string(1399, '1'), std::string(1399, 'z')}) { + BOOST_TEST( + test::failed_with(codecs::decode(base58_1024, text), codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(codecs::decode(base58_1024, text, tokens::secret), + codecs::error::input_too_long)); + } +} + +/** + Review Focus 3: zero bytes encode to an empty text and an empty text decodes to zero bytes, in + every form: the default results in place and on the heap, the buffer forms, the tokens, the + secret operations and the sizes. +*/ +void empty_input_in_every_form() { + std::array const nothing{}; + auto const fixed = codecs::encode(formats::base58, nothing); + static_assert(std::is_same_v> const>); + BOOST_TEST(fixed.has_value() && fixed.value().size() == 0); + auto const heap = codecs::encode(formats::base58, std::vector{}); + BOOST_TEST(heap.has_value() && heap.value().empty()); + auto const buffer_written = + codecs::encode(formats::base58, std::span{}, std::span{}); + BOOST_TEST(buffer_written.has_value() && buffer_written.value() == 0); + std::string kept{"kept"}; + BOOST_TEST(codecs::encode(formats::base58, nothing, tokens::append_to(kept)).has_value()); + BOOST_TEST(kept == "kept"); + auto const secret_empty = codecs::encode(formats::base58, secret_key<0>{}); + BOOST_TEST(secret_empty.has_value() && secret_empty.value().size() == 0); + BOOST_TEST_EQ(codecs::encoded_size(formats::base58, std::vector{}), 0U); + BOOST_TEST_EQ(codecs::encoded_size(formats::base58, secret_key<0>{}), 0U); + auto const decoded = codecs::decode(formats::base58, std::string_view{}); + BOOST_TEST(decoded.has_value() && decoded.value().empty()); + auto const literal_decoded = codecs::decode(formats::base58, ""); + BOOST_TEST(literal_decoded.has_value() && literal_decoded.value().empty()); + auto const buffer_decoded = + codecs::decode(formats::base58, std::string_view{}, std::span{}); + BOOST_TEST(buffer_decoded.has_value() && buffer_decoded.value() == 0); + auto const into_secret = codecs::decode(formats::base58, std::string_view{}, tokens::secret); + BOOST_TEST(into_secret.has_value() && into_secret.value().empty()); + auto const typed_array = codecs::decode>(formats::base58, ""); + BOOST_TEST(typed_array.has_value()); + auto const size = base58_codec::decoded_size(formats::base58, std::string_view{}); + BOOST_TEST(size.has_value() && size.value() == 0); + BOOST_TEST_EQ(codecs::max_decoded_size(formats::base58, std::string_view{}), 0U); +} + +/** + A secret decode into a typed result and the secret forms of the buffer: a Bitcoin address's 25 + bytes into secure::secret<25>, 24 refused as invalid_length; the secret encode into a buffer. +*/ +void the_secret_forms() { + std::string_view const address = "1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L"; + auto const key = codecs::decode>(formats::base58, address); + BOOST_TEST(key.has_value()); + if (key) { + BOOST_TEST_EQ(key->bytes()[0], 0x00U); + BOOST_TEST_EQ(key->bytes()[1], 0xebU); + std::array buffer{}; + auto const written = codecs::encode(formats::base58, key.value(), std::span{buffer}); + BOOST_TEST(written.has_value() && + std::string_view(buffer.data(), written.value()) == address); + auto const text = codecs::encode(formats::base58, key.value()); + BOOST_TEST(text.has_value() && test::text_of(text.value()) == address); + } + BOOST_TEST(test::failed_with(codecs::decode>(formats::base58, address), + codecs::error::invalid_length)); +} + +/** + The division of the secret encode by 58, a multiplication and a shift, equals the quotient for + every value it is given, 0 to 58 * 256 - 1. +*/ +void the_quotient_by_58() { + std::size_t wrong = 0; + for (std::uint32_t value = 0; value < 58U * 256U; ++value) { + wrong += detail::base58_quotient(value) == value / 58U ? 0 : 1; + } + BOOST_TEST_EQ(wrong, 0U); +} + +/** + The public and the secret conversions agree: 1000 inputs of a fixed seed, of 0 to 100 bytes, each + starting with 0 to 3 zero bytes, encode to the same text both ways, which decodes back to them + both ways. +*/ +void public_and_secret_agree() { + // A fixed seed, so that every lane and every run sees the same inputs. + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp) + std::mt19937_64 generator{20261127}; + std::array public_text{}; + std::array secret_text{}; + std::array decoded{}; + std::size_t disagreements = 0; + for (int round = 0; round < 1000; ++round) { + auto const size = static_cast(generator() % 101U); + std::size_t const zeros = std::min(size, static_cast(generator() % 4U)); + std::vector input(size); + for (std::size_t index = zeros; index < size; ++index) { + input[index] = static_cast(generator()); + } + auto const written = base58_codec::encode(formats::base58, input, public_text); + auto const secret_written = + base58_codec::encode(detail::secret_tag{}, formats::base58, input, secret_text); + std::size_t const exact = base58_codec::encoded_size(formats::base58, input); + std::size_t const secret_exact = + base58_codec::encoded_size(detail::secret_tag{}, formats::base58, input); + bool agree = written.has_value() && secret_written.has_value() && + written.value() == secret_written.value() && exact == written.value() && + secret_exact == written.value() && + std::ranges::equal(std::span{public_text}.first(written.value()), + std::span{secret_text}.first(written.value())); + if (agree) { + std::string_view const text{public_text.data(), written.value()}; + auto const back = base58_codec::decode(formats::base58, text, decoded); + agree = back.has_value() && + std::ranges::equal(std::span{decoded}.first(back.value()), input); + auto const secret_back = + base58_codec::decode(detail::secret_tag{}, formats::base58, text, decoded); + agree = agree && secret_back.has_value() && + std::ranges::equal(std::span{decoded}.first(secret_back.value()), input); + } + disagreements += agree ? 0 : 1; + } + BOOST_TEST_EQ(disagreements, 0U); +} + +} // namespace + +int main() { + bitcoin_cores_vectors(); + the_alphabets(); + the_alphabets_refusals(); + the_refusals(); + every_byte_value_as_a_character(); + the_default_bound(); + past_the_default_bound(); + a_larger_instance(); + empty_input_in_every_form(); + the_secret_forms(); + the_quotient_by_58(); + public_and_secret_agree(); + return boost::report_errors(); +} diff --git a/test/base64_stream_test.cpp b/test/base64_stream_test.cpp new file mode 100644 index 0000000..5cd56ee --- /dev/null +++ b/test/base64_stream_test.cpp @@ -0,0 +1,708 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// base64 and base64url as streams (D20): encoder(base64) and decoder(base64) are its one-shot +// transformers always and its stream transformers through stream_codec, whose encoder holds the up +// to two bytes of a group and the characters its output had no room for, and whose decoder the bits +// of a group, the padding seen and the fault masks (D20's table), and with the padding written the +// third and fourth bytes of a group until the next character or the flush. RFC 4648's vectors, +// bytes of 0 to 1000, and 1000 random inputs, in both alphabets and both paddings, equal the +// one-shot forms for every chunking (support/chunkings.hpp) and output spans of one and 1024, and +// every invalid text gives the one-shot form's error after flush, every byte value as a character +// at each place of a group among them (Review Focus 1); the spec's "Send while output is pending", +// "After the end and after an error", "The call that fails writes nothing" (B44) and "A file in +// base64 with no heap"; empty input (Review Focus 3); a moved-from stream converts from the start +// (Review Focus 5); a secret stream wipes its pending state, as secure's wipe seam records it. +// base64 has no configuration to be at fault, so no stream call reports one. + +#include "support/wipe_recorder.hpp" + +#include "support/counting.hpp" + +#include "support/base64_reference.hpp" +#include "support/chunkings.hpp" +#include "support/samples.hpp" +#include "support/steps.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; + +using base64_encoder = decltype(codecs::encoder(formats::base64)); +using base64_decoder = decltype(codecs::decoder(formats::base64)); +using base64url_encoder = decltype(codecs::encoder(formats::base64url)); +using base64url_decoder = decltype(codecs::decoder(formats::base64url)); +using secret_base64_encoder = decltype(codecs::encoder(formats::base64, codecs::secret_operation)); +using secret_base64_decoder = decltype(codecs::decoder(formats::base64, codecs::secret_operation)); +using stream_encoder = codecs::stream_codec::encoder; +using stream_decoder = codecs::stream_codec::decoder; +using secret_stream_encoder = + codecs::stream_codec::encoder; +using secret_stream_decoder = + codecs::stream_codec::decoder; + +// base64 and base64url stream natively: their transformers are one-shot and stream transformers, +// of bytes to characters and back, constant time as their codec is. +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(codecs::is_constant_time_v); +static_assert(codecs::is_constant_time_v); +static_assert(codecs::is_constant_time_v); +static_assert(base64_encoder::max_output_size(3) == 4); +static_assert(base64_encoder::max_output_size(4) == 8); +static_assert(base64_decoder::max_output_size(8) == 6); +// The stream codec's own streams: a public one is copyable and trivially destructible, a secret +// one move-only, with a destructor that wipes (D21). +static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); +static_assert(std::is_trivially_destructible_v); +static_assert(std::is_trivially_destructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(!std::is_trivially_destructible_v); +static_assert(!std::is_trivially_destructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(codecs::is_secret_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); +// One implementation: the stream codecs of the two formats are the same templates. +static_assert(std::is_base_of_v, + codecs::stream_codec>); +static_assert(std::is_base_of_v, + codecs::stream_codec>); + +/** Whether a format of the pair is the URL one, which the reference reads. */ +template +constexpr bool is_url = std::is_same_v; + +/** + The encoder, the decoder and the secret ones of `format` over every chunking of `bytes` equal the + one-shot forms: the text the reference writes, and the bytes back. +*/ +template +void expect_every_chunking_of(Format const& format, std::span bytes) { + bool const padded = format.padding_option == formats::padding::written; + std::string const text = test::reference_base64_encode(bytes, is_url, padded); + BOOST_TEST(codecs::encode(format, bytes).value() == text); + auto encoder = codecs::encoder(format); + auto decoder = codecs::decoder(format); + test::expect_every_chunking(encoder, bytes, text); + test::expect_every_chunking(decoder, test::characters_of(text), bytes); + auto secret_encoder = codecs::encoder(format, codecs::secret_operation); + auto secret_decoder = codecs::decoder(format, codecs::secret_operation); + test::expect_every_chunking(secret_encoder, bytes, text); + test::expect_every_chunking(secret_decoder, test::characters_of(text), bytes); +} + +/** `expect_every_chunking_of` in the four configurations: both alphabets, both paddings. */ +void expect_every_chunking_everywhere(std::span bytes) { + expect_every_chunking_of(formats::base64, bytes); + expect_every_chunking_of(formats::base64(formats::padding::omitted), bytes); + expect_every_chunking_of(formats::base64url, bytes); + expect_every_chunking_of(formats::base64url(formats::padding::written), bytes); +} + +/** + RFC 4648 section 10's inputs, and bytes of every length from 0 to 7, in the four configurations, + and 31, 32 and 33 random bytes in the two defaults and 1000 in base64's, over every chunking. +*/ +void every_chunking_equals_the_one_shot_form() { + for (std::string_view const input : {"", "f", "fo", "foo", "foob", "fooba", "foobar"}) { + expect_every_chunking_everywhere(test::bytes_of(input)); + } + for (std::size_t size = 0; size < 8; ++size) { + expect_every_chunking_everywhere(test::random_bytes(size)); + } + for (std::size_t const size : std::array{31, 32, 33}) { + std::vector const bytes = test::random_bytes(size); + expect_every_chunking_of(formats::base64, bytes); + expect_every_chunking_of(formats::base64url, bytes); + } + expect_every_chunking_of(formats::base64, test::random_bytes(1000)); + // The bytes 0xfb 0xff, whose symbols are the two that differ between the alphabets. + std::array const plus_slash{0xfb, 0xff}; + auto standard = codecs::encoder(formats::base64); + auto url = codecs::encoder(formats::base64url); + test::expect_every_chunking(standard, std::span{plus_slash}, + std::string_view{"+/8="}); + test::expect_every_chunking(url, std::span{plus_slash}, + std::string_view{"-_8"}); +} + +/** + 1000 random inputs of 0 to 12 bytes, each in a configuration of the four and as public and as + secret streams alternately, over every chunking: the stream equals the one-shot form and decodes + back. +*/ +void a_thousand_random_inputs() { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): a fixed seed + std::mt19937_64 generator{20261127}; + for (int iteration = 0; iteration < 1000; ++iteration) { + std::vector bytes(generator() % 13); + for (std::uint8_t& byte : bytes) { + byte = static_cast(generator()); + } + switch (iteration % 4) { + case 0: expect_every_chunking_of(formats::base64, bytes); break; + case 1: + expect_every_chunking_of(formats::base64(formats::padding::omitted), bytes); + break; + case 2: expect_every_chunking_of(formats::base64url, bytes); break; + default: + expect_every_chunking_of(formats::base64url(formats::padding::written), bytes); + break; + } + } +} + +/** + Every chunking of `text` decodes as the one-shot form does: the same bytes, or the same error, + reported after flush by the call that reads the end, which writes nothing (B44); public and secret + decoders alike. +*/ +template +void expect_the_one_shot_verdict(Format const& format, std::string_view text) { + auto const one_shot = codecs::decode(format, text); + bool const padded = format.padding_option == formats::padding::written; + test::reference_reading const reference = + test::reference_base64_decode(text, is_url, padded); + BOOST_TEST_EQ(one_shot.has_value(), !reference.fault.has_value()); + if (!one_shot.has_value()) { + BOOST_TEST(one_shot.error() == *reference.fault); + } + test::expect_the_one_shot_verdict(format, text); +} + +/** `expect_the_one_shot_verdict` in the four configurations. */ +void expect_the_one_shot_verdict_everywhere(std::string_view text) { + expect_the_one_shot_verdict(formats::base64, text); + expect_the_one_shot_verdict(formats::base64(formats::padding::omitted), text); + expect_the_one_shot_verdict(formats::base64url, text); + expect_the_one_shot_verdict(formats::base64url(formats::padding::written), text); +} + +/** + Invalid texts give the one-shot form's error after flush, for every chunking: a character that is + no symbol is invalid_character wherever it is, a length no encoding has invalid_length, a `=` out + of place or non-zero trailing bits invalid_padding, and faults of two kinds the lowest value + (B23). +*/ +void invalid_texts_give_the_one_shot_error_after_flush() { + std::string const high_character{'Z', 'm', static_cast(0xc1), 'v'}; + for (std::string_view const text : { + std::string_view{"Zh=="}, std::string_view{"Zm9v\n"}, + std::string_view{"Zm9v Zm9v"}, std::string_view{"Zm9"}, + std::string_view{"Zg="}, std::string_view{"Zg"}, + std::string_view{"Z"}, std::string_view{"Zm9vY"}, + std::string_view{"Zm9-"}, std::string_view{"Zm+/"}, + std::string_view{"Zg==Zm9v"}, std::string_view{"Zg==Zg=="}, + std::string_view{"Z==="}, std::string_view{"Zm=9"}, + std::string_view{"Zm9="}, std::string_view{"Zh==\n"}, + std::string_view{"Zh="}, std::string_view{"Zh=\n"}, + std::string_view{"Zm9v===="}, std::string_view{high_character}, + }) { + expect_the_one_shot_verdict_everywhere(text); + } + // Each byte value as a character at each place of a group and as the lone last character: the + // stream's verdict is the one-shot form's, which the plain reference confirms. The first group + // of a padded and of an unpadded text, the last group of a padded one and a short unpadded one. + for (std::string_view const base : {"Zm9v", "Zg==", "Zg"}) { + for (std::size_t place = 0; place <= base.size(); ++place) { + for (unsigned value = 0; value < 256; ++value) { + auto const character = static_cast(static_cast(value)); + std::string text{base}; + if (place == base.size()) { + text.push_back(character); + } else { + text[place] = character; + } + if (base.size() == 4 && base != "Zg==") { + expect_the_one_shot_verdict(formats::base64, text); + expect_the_one_shot_verdict(formats::base64url, text); + } else if (base == "Zg==") { + expect_the_one_shot_verdict(formats::base64, text); + } else { + expect_the_one_shot_verdict(formats::base64url, text); + } + } + } + } +} + +/** + The spec's "Send while output is pending": 64 bytes then 4 more before any receive give {64, + output_pending} then {0, output_pending}, and the second send is accepted once the output is + received until needs_input. A group not whole waits: 84 characters of the first 64 bytes, 4 of + the next 4, and `flush` completes the last group with its padding. +*/ +void send_while_output_is_pending() { + std::vector const bytes = test::random_bytes(68); + auto encoder = codecs::encoder(formats::base64); + BOOST_TEST( + test::is_step(encoder.send(std::span{bytes}.first(64)), 64, codecs::flow::output_pending)); + BOOST_TEST( + test::is_step(encoder.send(std::span{bytes}.subspan(64)), 0, codecs::flow::output_pending)); + BOOST_TEST_EQ(test::receive_until_done(encoder, 100), 84U); + BOOST_TEST( + test::is_step(encoder.send(std::span{bytes}.subspan(64)), 4, codecs::flow::output_pending)); + BOOST_TEST_EQ(test::receive_until_done(encoder, 3), 4U); + // The last group, of two bytes, waits for the flush, which completes it with its padding. + auto const flushed = encoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + BOOST_TEST_EQ(test::receive_until_done(encoder, 2), 4U); + auto const second_flush = encoder.flush(); + BOOST_TEST(second_flush.has_value() && second_flush.value() == codecs::flow::finished); + // A send of nothing is accepted whole and absorbed. + encoder.reset(); + BOOST_TEST(test::is_step(encoder.send({}), 0, codecs::flow::needs_input)); + // The first character of a group is absorbed into the decoder's state, which frees the input + // at once; the rest of the group is read by the receive. With the padding written, the bytes + // of a group's third and fourth places are held until the group is known not to be the last, + // which a `=` there would make it: the next character delivers them, or the flush. + auto decoder = codecs::decoder(formats::base64); + BOOST_TEST(test::is_step(decoder.send(test::characters_of("Z")), 1, codecs::flow::needs_input)); + BOOST_TEST( + test::is_step(decoder.send(test::characters_of("m9v")), 3, codecs::flow::output_pending)); + std::array decoded{}; + BOOST_TEST(test::is_step(decoder.receive(decoded), 1, codecs::flow::needs_input)); + BOOST_TEST_EQ(decoded[0], 'f'); + // A span of one byte takes one byte at a time: the next group's first character delivers the + // two held bytes, then its second character the group's first byte. + BOOST_TEST( + test::is_step(decoder.send(test::characters_of("Zm9v")), 4, codecs::flow::output_pending)); + std::array one_byte{}; + BOOST_TEST(test::is_step(decoder.receive(one_byte), 1, codecs::flow::output_pending)); + BOOST_TEST_EQ(one_byte[0], 'o'); + BOOST_TEST(test::is_step(decoder.receive(one_byte), 1, codecs::flow::output_pending)); + BOOST_TEST_EQ(one_byte[0], 'o'); + BOOST_TEST(test::is_step(decoder.receive(one_byte), 1, codecs::flow::needs_input)); + BOOST_TEST_EQ(one_byte[0], 'f'); + // The flush delivers the last group's held bytes, its `=` none. + auto const decoder_flushed = decoder.flush(); + BOOST_TEST(decoder_flushed.has_value() && + decoder_flushed.value() == codecs::flow::output_pending); + BOOST_TEST(test::is_step(decoder.receive(one_byte), 1, codecs::flow::output_pending)); + BOOST_TEST_EQ(one_byte[0], 'o'); + BOOST_TEST(test::is_step(decoder.receive(one_byte), 1, codecs::flow::finished)); + BOOST_TEST_EQ(one_byte[0], 'o'); + // With the padding omitted, every byte is delivered as its character is read. + auto url_decoder = codecs::decoder(formats::base64url); + BOOST_TEST(test::is_step(url_decoder.send(test::characters_of("Zm9v")), 4, + codecs::flow::output_pending)); + BOOST_TEST(test::is_step(url_decoder.receive(decoded), 3, codecs::flow::needs_input)); + BOOST_TEST((decoded == std::array{'f', 'o', 'o'})); +} + +/** + A decoder given a span of exactly the room the bytes of `text` need reads the padding as well: the + characters that deliver no byte are read with or without room, so that the stream reaches + needs_input with `held` bytes of the last group still held (its third and fourth places' but those + of its `=`), and finished after the flush and the receive of those into the rest of the span; a + caller with a fixed buffer never waits for room that no byte needs. +*/ +template +void expect_exact_room_reads_the_padding(Decoder& decoder, std::string_view text, + std::size_t held) { + auto const bytes = codecs::decode(formats::base64, text).value(); + decoder.reset(); + std::vector exact(bytes.size()); + BOOST_TEST(decoder.send(test::characters_of(text)).has_value()); + BOOST_TEST( + test::is_step(decoder.receive(exact), exact.size() - held, codecs::flow::needs_input)); + auto const flushed = decoder.flush(); + codecs::flow const after_flush = + held == 0 ? codecs::flow::finished : codecs::flow::output_pending; + BOOST_TEST(flushed.has_value() && flushed.value() == after_flush); + if (held != 0) { + BOOST_TEST(test::is_step(decoder.receive(std::span{exact}.last(held)), held, + codecs::flow::finished)); + } + BOOST_TEST(exact == bytes); + // A span of nothing: what delivers no byte is read, and a byte with no room waits. + decoder.reset(); + BOOST_TEST(decoder.send(test::characters_of(text)).has_value()); + auto const empty_receive = decoder.receive(std::span{}); + BOOST_TEST(empty_receive.has_value() && empty_receive->count == 0); + std::vector> const no_chunk; + auto const drained = test::stream_whole(decoder, no_chunk, 1); + BOOST_TEST(drained.has_value() && drained->size() == bytes.size()); +} + +/** `expect_exact_room_reads_the_padding` over texts of each count of `=`. */ +template +void expect_exact_room_reads_the_padding(Decoder decoder) { + expect_exact_room_reads_the_padding(decoder, "Zg==", 0); + expect_exact_room_reads_the_padding(decoder, "Zm8=", 1); + expect_exact_room_reads_the_padding(decoder, "Zm9vYg==", 0); + expect_exact_room_reads_the_padding(decoder, "Zm9vYmE=", 1); + expect_exact_room_reads_the_padding(decoder, "Zm9vYmFy", 2); +} + +/** A public and a secret decoder, as @ref expect_exact_room_reads_the_padding checks them. */ +void exact_room_reads_the_padding() { + expect_exact_room_reads_the_padding(codecs::decoder(formats::base64)); + expect_exact_room_reads_the_padding(codecs::decoder(formats::base64, codecs::secret_operation)); +} + +/** + The spec's "After the end and after an error", its first half: a finished encoder's send is {0, + finished}, and so is every call after. +*/ +void after_the_end() { + std::array const bytes{0x12, 0x34}; + auto encoder = codecs::encoder(formats::base64); + BOOST_TEST(encoder.send(bytes).has_value()); + BOOST_TEST_EQ(test::receive_until_done(encoder, 16), 0U); + auto const flushed = encoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + BOOST_TEST_EQ(test::receive_until_done(encoder, 16), 4U); + BOOST_TEST(test::is_step(encoder.send(bytes), 0, codecs::flow::finished)); + auto const second_flush = encoder.flush(); + BOOST_TEST(second_flush.has_value() && second_flush.value() == codecs::flow::finished); + std::array text{}; + BOOST_TEST(test::is_step(encoder.receive(text), 0, codecs::flow::finished)); +} + +/** + The spec's "After the end and after an error", its second half: a decoder whose flush reported + invalid_character returns it from both receives after, writing nothing, and from every call, and + decodes a valid text after reset; a length no encoding has is invalid_length from flush when + nothing is still borrowed, and a `=` out of place invalid_padding. +*/ +void after_an_error() { + auto decoder = codecs::decoder(formats::base64); + std::array decoded{}; + BOOST_TEST(decoder.send(test::characters_of("Zm9v*A==")).has_value()); + BOOST_TEST(test::is_step(decoder.receive(std::span{decoded}.first(3)), 3, + codecs::flow::output_pending)); + auto const flushed = decoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + decoded.fill(0x5a); + BOOST_TEST(test::failed_with(decoder.receive(decoded), codecs::error::invalid_character)); + BOOST_TEST(test::failed_with(decoder.receive(decoded), codecs::error::invalid_character)); + BOOST_TEST(std::ranges::all_of(decoded, [](std::uint8_t byte) { return byte == 0x5a; })); + BOOST_TEST(test::failed_with(decoder.send(test::characters_of("Zm9v")), + codecs::error::invalid_character)); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_character)); + decoder.reset(); + BOOST_TEST(test::is_step(decoder.send(test::characters_of("Q29mZmVl")), 8, + codecs::flow::output_pending)); + BOOST_TEST(decoder.flush().has_value()); + BOOST_TEST(test::is_step(decoder.receive(decoded), 6, codecs::flow::finished)); + BOOST_TEST(std::string_view(reinterpret_cast(decoded.data()), 6) == "Coffee"); + + decoder.reset(); + BOOST_TEST(decoder.send(test::characters_of("Zm9")).has_value()); + // The third place's byte is held: the group may be the last, and its third character a `=`. + BOOST_TEST(test::is_step(decoder.receive(decoded), 1, codecs::flow::needs_input)); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_length)); + decoder.reset(); + BOOST_TEST(decoder.send(test::characters_of("Zh==")).has_value()); + BOOST_TEST(test::is_step(decoder.receive(decoded), 1, codecs::flow::needs_input)); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_padding)); + // An error is the lowest value: the character, over the length and the padding. + decoder.reset(); + BOOST_TEST(decoder.send(test::characters_of("Zh=\n")).has_value()); + BOOST_TEST(decoder.receive(decoded).has_value()); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_character)); +} + +/** + The spec's "The call that fails writes nothing" (B44), on base64: 4000 valid characters drained, + then 96 characters whose last is `*`, flushed and received into a span of 1024, which the receive + that reports invalid_character leaves unchanged; the earlier receives delivered the valid bytes. +*/ +void the_call_that_fails_writes_nothing() { + std::vector const bytes = test::random_bytes(3072); + std::string const text = codecs::encode(formats::base64, bytes).value(); + BOOST_TEST_EQ(text.size(), 4096U); + auto decoder = codecs::decoder(formats::base64); + std::vector delivered; + auto sink = [&delivered](std::span piece) { + delivered.insert(delivered.end(), piece.begin(), piece.end()); + }; + BOOST_TEST( + decoder.send(test::characters_of(std::string_view{text}.substr(0, 4000))).has_value()); + auto const drained = codecs::drain(decoder, sink); + BOOST_TEST(drained.has_value() && drained.value() == codecs::flow::needs_input); + // The last group's third and fourth bytes are held until the group is known not to be the + // last, which the next character, never delivered here, would make it. + BOOST_TEST(std::ranges::equal(delivered, std::span{bytes}.first(2998))); + + std::string tail = text.substr(4000, 96); + tail.back() = '*'; + BOOST_TEST(decoder.send(test::characters_of(tail)).has_value()); + auto const flushed = decoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + std::array span{}; + span.fill(0x5a); + auto const received = decoder.receive(span); + BOOST_TEST(test::failed_with(received, codecs::error::invalid_character)); + BOOST_TEST(std::ranges::all_of(span, [](std::uint8_t byte) { return byte == 0x5a; })); + // The same with a secret decoder, and with every other character of the tail at fault. + auto secret_decoder = codecs::decoder(formats::base64, codecs::secret_operation); + BOOST_TEST(secret_decoder.send(test::characters_of(tail)).has_value()); + BOOST_TEST(secret_decoder.flush().has_value()); + span.fill(0x5a); + BOOST_TEST(test::failed_with(secret_decoder.receive(span), codecs::error::invalid_character)); + BOOST_TEST(std::ranges::all_of(span, [](std::uint8_t byte) { return byte == 0x5a; })); + std::string alternating = tail; + for (std::size_t index = 0; index < alternating.size(); index += 2) { + alternating[index] = '*'; + } + secret_decoder.reset(); + BOOST_TEST(secret_decoder.send(test::characters_of(alternating)).has_value()); + auto const alternating_flushed = secret_decoder.flush(); + span.fill(0x5a); + // The verdict comes at flush, or with the receive after it; either way nothing is written. + if (alternating_flushed.has_value()) { + BOOST_TEST( + test::failed_with(secret_decoder.receive(span), codecs::error::invalid_character)); + } else { + BOOST_TEST(test::failed_with(alternating_flushed, codecs::error::invalid_character)); + } + BOOST_TEST(std::ranges::all_of(span, [](std::uint8_t byte) { return byte == 0x5a; })); +} + +/** A stream of `format` flushed with nothing sent finishes at once with nothing written. */ +template +void expect_empty_streams_finish(Format const& format) { + auto encoder = codecs::encoder(format); + auto const flushed = encoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::finished); + std::array text{}; + BOOST_TEST(test::is_step(encoder.receive(text), 0, codecs::flow::finished)); + auto decoder = codecs::decoder(format); + auto const decoder_flushed = decoder.flush(); + BOOST_TEST(decoder_flushed.has_value() && decoder_flushed.value() == codecs::flow::finished); + std::array decoded{}; + BOOST_TEST(test::is_step(decoder.receive(decoded), 0, codecs::flow::finished)); + auto const encoded_nothing = + encoder.transform(std::span{}, std::span{}); + BOOST_TEST(encoded_nothing.has_value() && encoded_nothing.value() == 0); + auto const decoded_nothing = + decoder.transform(std::span{}, std::span{}); + BOOST_TEST(decoded_nothing.has_value() && decoded_nothing.value() == 0); +} + +/** + Review Focus 3: a stream flushed with nothing sent finishes at once with nothing written, and + transform of empty spans writes nothing and returns 0. +*/ +void empty_input() { + for (formats::padding const option : {formats::padding::written, formats::padding::omitted}) { + expect_empty_streams_finish(formats::base64(option)); + expect_empty_streams_finish(formats::base64url(option)); + } +} + +/** + Review Focus 5: a moved-from encoder and decoder, public and secret, convert an input from the + start, and the moved-to one finishes what the source had begun. +*/ +template +void a_moved_from_stream_converts_from_the_start(Encoder encoder, Decoder decoder) { + std::vector const bytes = test::random_bytes(31); + std::string const text = codecs::encode(formats::base64, bytes).value(); + BOOST_TEST(encoder.send(bytes).has_value()); + std::array one_character{}; + BOOST_TEST(test::is_step(encoder.receive(one_character), 1, codecs::flow::output_pending)); + Encoder moved_encoder{std::move(encoder)}; + std::vector> const no_chunk; + auto const rest = test::stream_whole(moved_encoder, no_chunk, 5); + BOOST_TEST(rest.has_value() && + std::string(1, one_character[0]) + std::string(rest->begin(), rest->end()) == text); + std::vector> const whole{bytes}; + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): Review Focus 5 + auto const again = test::stream_whole(encoder, whole, 7); + BOOST_TEST(again.has_value() && std::string(again->begin(), again->end()) == text); + + BOOST_TEST(decoder.send(test::characters_of(text).first(6)).has_value()); + std::array one_byte{}; + BOOST_TEST(test::is_step(decoder.receive(one_byte), 1, codecs::flow::output_pending)); + Decoder moved_decoder{std::move(decoder)}; + std::vector> const tail{test::characters_of(text).subspan(6)}; + auto const decoded_rest = test::stream_whole(moved_decoder, tail, 4); + // The moved-to decoder reads the characters the source still borrowed, then the rest. + BOOST_TEST(decoded_rest.has_value() && one_byte[0] == bytes[0] && + std::ranges::equal(*decoded_rest, std::span{bytes}.subspan(1))); + std::vector> const whole_text{test::characters_of(text)}; + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): Review Focus 5 + auto const decoded_again = test::stream_whole(decoder, whole_text, 3); + BOOST_TEST(decoded_again.has_value() && *decoded_again == bytes); +} + +/** + The spec's "A file in base64 with no heap": a file of 64 KiB is read in 4096-byte chunks into one + buffer, each sent to encoder(base64) and drained into a fixed span before the next chunk is read; + the text equals the one-shot encoding of the whole file, and decodes back the same way, with no + allocation counted. +*/ +void a_file_with_no_heap() { + std::vector const file = test::random_bytes(std::size_t{64} * 1024); + std::string const expected = codecs::encode(formats::base64, file).value(); + std::string text(expected.size(), ' '); // the output, made before the window + std::vector decoded(file.size()); + bool volatile verdict = false; + test::expect_no_allocation("a file through encoder(base64) and decoder(base64)", [&] { + std::array chunk{}; + std::array fixed_span{}; + std::size_t written = 0; + auto const text_sink = [&](std::span piece) noexcept { + std::ranges::copy(piece, text.begin() + static_cast(written)); + written += piece.size(); + }; + auto encoder = codecs::encoder(formats::base64); + bool streamed = true; + for (std::size_t offset = 0; offset < file.size(); offset += chunk.size()) { + // The "read": the next chunk of the file into the one buffer. + std::ranges::copy(std::span{file}.subspan(offset, chunk.size()), chunk.begin()); + streamed = streamed && encoder.send(chunk).has_value() && + codecs::drain(encoder, text_sink, std::span{fixed_span}).has_value(); + } + streamed = streamed && encoder.flush().has_value() && + codecs::drain(encoder, text_sink, std::span{fixed_span}).has_value(); + + std::array fixed_bytes{}; + std::size_t decoded_count = 0; + auto const byte_sink = [&](std::span piece) noexcept { + std::ranges::copy(piece, decoded.begin() + static_cast(decoded_count)); + decoded_count += piece.size(); + }; + auto decoder = codecs::decoder(formats::base64); + std::array text_chunk{}; + for (std::size_t offset = 0; offset < text.size(); offset += text_chunk.size()) { + std::size_t const size = std::min(text_chunk.size(), text.size() - offset); + std::ranges::copy(std::string_view{text}.substr(offset, size), text_chunk.begin()); + streamed = streamed && + decoder.send(std::span{text_chunk}.first(size)).has_value() && + codecs::drain(decoder, byte_sink, std::span{fixed_bytes}).has_value(); + } + streamed = streamed && decoder.flush().has_value() && + codecs::drain(decoder, byte_sink, std::span{fixed_bytes}).has_value(); + verdict = streamed && written == expected.size() && decoded_count == file.size(); + }); + BOOST_TEST(verdict); + BOOST_TEST(text == expected); + BOOST_TEST(decoded == file); +} + +/** + A secret stream wipes its pending state (D21): the encoder's waiting bytes (3) and characters + (4), and the decoder's six bytes of bits and masks, its two held bytes and its two waiting bytes, + in the source after a move, at reset and at destruction; a public stream wipes nothing. The encoder + is given 31 bytes, which leaves one byte pending, the spec's scenario "A secret stream's state is + wiped". +*/ +void a_secret_streams_state_is_wiped() { + std::vector const bytes = test::random_bytes(31); + std::array text{}; + std::optional encoder; + encoder.emplace(formats::base64); + BOOST_TEST(encoder->send(bytes).has_value()); + BOOST_TEST(test::is_step(encoder->receive(text), 40, codecs::flow::needs_input)); + test::clear_wipes(); + secret_stream_encoder moved_encoder{std::move(*encoder)}; + BOOST_TEST_EQ(test::wipes_in(*encoder, 3), 1U); + BOOST_TEST_EQ(test::wipes_in(*encoder, 4), 1U); + BOOST_TEST(moved_encoder.flush().has_value()); + BOOST_TEST(test::is_step(moved_encoder.receive(text), 4, codecs::flow::finished)); + // The moved-to encoder holds the byte again: its reset and destruction wipe it. + moved_encoder.reset(); + BOOST_TEST(moved_encoder.send(bytes).has_value()); + BOOST_TEST(moved_encoder.receive(text).has_value()); + test::clear_wipes(); + moved_encoder.reset(); + BOOST_TEST_EQ(test::wipes_in(moved_encoder, 3), 1U); + BOOST_TEST_EQ(test::wipes_in(moved_encoder, 4), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(encoder, 3), 1U); + + std::optional decoder; + decoder.emplace(formats::base64); + BOOST_TEST(decoder->send(test::characters_of("Zm9vYg")).has_value()); + std::array decoded{}; + BOOST_TEST(test::is_step(decoder->receive(decoded), 4, codecs::flow::needs_input)); + test::clear_wipes(); + secret_stream_decoder moved_decoder{std::move(*decoder)}; + BOOST_TEST_EQ(test::wipes_in(*decoder, 6), 1U); + BOOST_TEST_EQ(test::wipes_in(*decoder, 2), 2U); + test::clear_wipes(); + moved_decoder.reset(); + BOOST_TEST_EQ(test::wipes_in(moved_decoder, 6), 1U); + BOOST_TEST_EQ(test::wipes_in(moved_decoder, 2), 2U); + BOOST_TEST_EQ(test::wipes_at_destruction(decoder, 6), 1U); + BOOST_TEST_EQ(test::wipes.count, 3U); + + // A public stream wipes nothing. + test::clear_wipes(); + { + stream_encoder public_encoder{formats::base64}; + BOOST_TEST(public_encoder.send(bytes).has_value()); + BOOST_TEST(public_encoder.receive(text).has_value()); + public_encoder.reset(); + stream_decoder public_decoder{formats::base64}; + BOOST_TEST(public_decoder.send(test::characters_of("Zm9vYg==")).has_value()); + BOOST_TEST(public_decoder.receive(decoded).has_value()); + BOOST_TEST(public_decoder.flush().has_value()); + public_decoder.reset(); + } + BOOST_TEST_EQ(test::wipes.count, 0U); +} + +} // namespace + +int main() { + every_chunking_equals_the_one_shot_form(); + a_thousand_random_inputs(); + invalid_texts_give_the_one_shot_error_after_flush(); + send_while_output_is_pending(); + exact_room_reads_the_padding(); + after_the_end(); + after_an_error(); + the_call_that_fails_writes_nothing(); + empty_input(); + a_moved_from_stream_converts_from_the_start(codecs::encoder(formats::base64), + codecs::decoder(formats::base64)); + a_moved_from_stream_converts_from_the_start( + codecs::encoder(formats::base64, codecs::secret_operation), + codecs::decoder(formats::base64, codecs::secret_operation)); + a_file_with_no_heap(); + a_secret_streams_state_is_wiped(); + return boost::report_errors(); +} diff --git a/test/base64_test.cpp b/test/base64_test.cpp new file mode 100644 index 0000000..902e58c --- /dev/null +++ b/test/base64_test.cpp @@ -0,0 +1,746 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// base64 and base64url, the formats (D13, the spec's "Format: base64 and base64url"): RFC 4648 +// section 10's vectors with either padding and either alphabet, through the buffer, token, default +// and typed forms; the bytes 0xfb 0xff as "+/8=" and "-_8"; every error of the format, one input +// each, and an input of two faults giving the lowest value (B23); every byte value as a character +// at every place of a group against a plain reference, `char` signed (Review Focus 1), and 20000 +// texts near the valid ones; a text decoded into its own storage (Review Focus 4); empty input in +// every form (Review Focus 3); the bounds saturating at SIZE_MAX with an input of 3 * (SIZE_MAX / +// 4) + 1 bytes refused (Review Focus 2); the spec's scenarios "The exact size and the bound" and +// "A run-time input" (the others, with the token, over and stream forms, are in tokens_test, +// over_test, format_transformer_test and base64_stream_test). The one implementation of the pair +// is run through both formats and both paddings: base64 and base64url differ in the two last +// symbols, and in the padding they default to, alone. + +#include "support/counting.hpp" + +#include "support/base64_reference.hpp" +#include "support/decode_checks.hpp" +#include "support/samples.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace detail = webcpp::codecs::detail; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +using base64_codec = codecs::codec; +using base64url_codec = codecs::codec; + +constexpr std::size_t size_maximum = std::numeric_limits::max(); + +// The formats: values whose call configures the padding (D2); base64 writes it, base64url omits it. +static_assert(codecs::format && codecs::format); +static_assert(!std::is_same_v); +static_assert(formats::base64_t::name == "base64"); +static_assert(formats::base64url_t::name == "base64url"); +static_assert(formats::base64.padding_option == formats::padding::written); +static_assert(formats::base64url.padding_option == formats::padding::omitted); +static_assert(formats::base64(formats::padding::omitted).padding_option == + formats::padding::omitted); +static_assert(formats::base64url(formats::padding::written).padding_option == + formats::padding::written); +static_assert( + std::is_same_v); +static_assert( + std::is_same_v); +static_assert(static_cast(formats::padding::written) == 1U); +static_assert(static_cast(formats::padding::omitted) == 2U); +static_assert(std::is_same_v, unsigned char>); +// A value of neither enumerator, cast from another integer, is read as written, RFC 4648's own +// form: the padding is omitted for padding::omitted alone (formats::padding's rule). +static_assert(codecs::detail::padding_is_written(formats::base64(formats::padding{0}))); +static_assert(codecs::detail::padding_is_written(formats::base64url(formats::padding{3}))); +static_assert(!codecs::detail::padding_is_written(formats::base64(formats::padding::omitted))); +static_assert(codecs::encoded_size(formats::base64url(formats::padding{0}), + std::array{}) == 4); + +// Their codecs: constant time; one implementation, the same functions under both names. +static_assert(base64_codec::constant_time && base64url_codec::constant_time); +static_assert(std::is_base_of_v, base64_codec>); +static_assert(std::is_base_of_v, base64url_codec>); + +// The spec's "The exact size and the bound": "foob" is 8 characters and "Zm9vYg==" holds at most 6 +// bytes, in a static_assert, and decode writes 4 (below). +constexpr std::array foob{'f', 'o', 'o', 'b'}; +static_assert(codecs::encoded_size(formats::base64, foob) == 8); +static_assert(codecs::max_decoded_size(formats::base64, std::string_view{"Zm9vYg=="}) == 6); +static_assert(codecs::max_decoded_size(formats::base64, "Zm9vYg==") == 6); +// The exact size follows the padding, the bound is over both. +static_assert(codecs::encoded_size(formats::base64(formats::padding::omitted), foob) == 6); +static_assert(codecs::encoded_size(formats::base64url, foob) == 6); +static_assert(codecs::encoded_size(formats::base64url(formats::padding::written), foob) == 8); +static_assert(codecs::encoded_size(formats::base64, std::array{}) == 0); +static_assert(codecs::encoded_size(formats::base64, std::array{}) == 4); +static_assert(codecs::encoded_size(formats::base64(formats::padding::omitted), + std::array{}) == 4); +static_assert(codecs::encoded_size(formats::base64(formats::padding::omitted), + std::array{}) == 7); +static_assert(base64_codec::max_encoded_size(0) == 0); +static_assert(base64_codec::max_encoded_size(1) == 4); +static_assert(base64_codec::max_encoded_size(32) == 44); +static_assert(base64_codec::max_decoded_size(0) == 0); +static_assert(base64_codec::max_decoded_size(1) == 0); +static_assert(base64_codec::max_decoded_size(2) == 1); +static_assert(base64_codec::max_decoded_size(3) == 2); +static_assert(base64_codec::max_decoded_size(4) == 3); +static_assert(base64_codec::max_decoded_size(43) == 32); +static_assert(base64_codec::max_decoded_size(44) == 33); + +// Review Focus 2: the bound is 4 * ceil(n / 3), which saturates past 3 * (SIZE_MAX / 4) bytes, on a +// 32-bit std::size_t too; the core refuses such an input before it reads it. A text's bound never +// saturates. +constexpr std::size_t longest_input = 3 * (size_maximum / 4); +static_assert(base64_codec::max_encoded_size(longest_input) == 4 * (size_maximum / 4)); +static_assert(base64_codec::max_encoded_size(longest_input + 1) == size_maximum); +static_assert(base64_codec::max_encoded_size(size_maximum) == size_maximum); +static_assert(base64url_codec::max_encoded_size(longest_input + 1) == size_maximum); +static_assert(!codecs::detail::input_size_fault(formats::base64, longest_input).has_value()); +static_assert(codecs::detail::input_size_fault(formats::base64, longest_input + 1) == + codecs::error::input_too_long); +static_assert(codecs::detail::input_size_fault(formats::base64url, longest_input + 1) == + codecs::error::input_too_long); +static_assert(codecs::detail::input_size_fault(formats::base64, size_maximum) == + codecs::error::input_too_long); +static_assert(base64_codec::max_decoded_size(size_maximum) == (size_maximum / 4 * 3) + 2); +static_assert(!codecs::detail::text_size_fault(formats::base64, size_maximum).has_value()); +// The padded bound is the unpadded size's bound. +static_assert(detail::base64_text_size(1, false) == 2 && detail::base64_text_size(2, false) == 3); +static_assert(detail::base64_text_size(1, true) == 4 && detail::base64_text_size(3, false) == 4); + +// base64 has no configuration to be at fault. +static_assert(!codecs::detail::takes_configuration_fault); +static_assert(!codecs::detail::configuration_fault_of(formats::base64).has_value()); +static_assert(!codecs::detail::configuration_fault_of(formats::base64url).has_value()); + +// The default results (D9): in place for a size known at compile time, the heap otherwise. The +// spec's "A run-time input": a std::vector of bytes gives a std::string. +static_assert( + std::is_same_v const&>())), + codecs::result>>); +static_assert( + std::is_same_v const&>())), + codecs::result>>); +static_assert(std::is_same_v const&>())), + codecs::result>>); +static_assert( + std::is_same_v const&>())), + codecs::result>); +static_assert(std::is_same_v>>); + +// The arithmetic, as constant expressions: a value's symbol in either alphabet, and a symbol's +// value and verdict. +static_assert(detail::base64_arithmetic::symbol_of(0) == 'A'); +static_assert(detail::base64_arithmetic::symbol_of(25) == 'Z'); +static_assert(detail::base64_arithmetic::symbol_of(26) == 'a'); +static_assert(detail::base64_arithmetic::symbol_of(51) == 'z'); +static_assert(detail::base64_arithmetic::symbol_of(52) == '0'); +static_assert(detail::base64_arithmetic::symbol_of(61) == '9'); +static_assert(detail::base64_arithmetic::symbol_of(62) == '+'); +static_assert(detail::base64_arithmetic::symbol_of(63) == '/'); +static_assert(detail::base64_arithmetic::symbol_of(62) == '-'); +static_assert(detail::base64_arithmetic::symbol_of(63) == '_'); +static_assert(detail::base64_arithmetic::symbol_of(51) == 'z'); + +/** The value of `symbol` in an alphabet as the arithmetic gives it, and whether it is no symbol. */ +template +constexpr std::pair read_symbol(char symbol) { + std::uint8_t mask = 0; + unsigned const value = + detail::base64_arithmetic::six_bits_of(static_cast(symbol), mask); + return {value, mask != 0}; +} + +static_assert(read_symbol('A') == std::pair{0U, false}); +static_assert(read_symbol('z') == std::pair{51U, false}); +static_assert(read_symbol('9') == std::pair{61U, false}); +static_assert(read_symbol('+') == std::pair{62U, false}); +static_assert(read_symbol('/') == std::pair{63U, false}); +static_assert(read_symbol('-').second && read_symbol('_').second); +static_assert(read_symbol('-') == std::pair{62U, false}); +static_assert(read_symbol('_') == std::pair{63U, false}); +static_assert(read_symbol('+').second && read_symbol('/').second); +static_assert(read_symbol('=').second); +static_assert(read_symbol(static_cast(0xc1)).second); + +/** RFC 4648 section 10's vectors: the input, and its base64 as the RFC writes it. */ +struct rfc_vector { + /** The input. */ + std::string_view input; + /** Its base64, with the padding. */ + std::string_view padded; +}; + +/** RFC 4648 section 10's test vectors. */ +constexpr std::array rfc4648_vectors{ + rfc_vector{.input = "", .padded = ""}, + rfc_vector{.input = "f", .padded = "Zg=="}, + rfc_vector{.input = "fo", .padded = "Zm8="}, + rfc_vector{.input = "foo", .padded = "Zm9v"}, + rfc_vector{.input = "foob", .padded = "Zm9vYg=="}, + rfc_vector{.input = "fooba", .padded = "Zm9vYmE="}, + rfc_vector{.input = "foobar", .padded = "Zm9vYmFy"}, +}; + +/** + One vector's encode through the forms of one configuration: the default form, the buffer form + (the characters past the text unchanged, a short buffer refused) and the tokens. + + @return The text the default form gave. +*/ +template +std::string expect_encodes(Format const& format, bool url, rfc_vector const& vector, bool padded) { + std::string const expected = + padded ? std::string{vector.padded} : test::without_padding(vector.padded); + // The reference agrees with the RFC. + BOOST_TEST(test::reference_base64_encode(test::bytes_of(vector.input), false, padded) == + expected); + auto const defaulted = codecs::encode(format, vector.input); + BOOST_TEST(defaulted.has_value() && + defaulted.value() == + test::reference_base64_encode(test::bytes_of(vector.input), url, padded)); + BOOST_TEST_EQ(codecs::encoded_size(format, vector.input), expected.size()); + + std::array buffer{}; + buffer.fill('x'); + auto const written = codecs::encode(format, vector.input, std::span{buffer}); + BOOST_TEST(written.has_value() && written.value() == expected.size()); + BOOST_TEST(std::string_view(buffer.data(), expected.size()) == expected); + // The characters past the text are unchanged. + BOOST_TEST(std::all_of(buffer.begin() + static_cast(expected.size()), + buffer.end(), [](char character) { return character == 'x'; })); + if (!expected.empty()) { + auto const short_buffer = + codecs::encode(format, vector.input, std::span{buffer}.first(expected.size() - 1)); + BOOST_TEST(!short_buffer.has_value() && + short_buffer.error() == codecs::error::output_too_small); + } + + auto const returned = codecs::encode(format, vector.input, tokens::return_string); + BOOST_TEST(returned.has_value() && returned.value() == expected); + std::string appended{"<"}; + BOOST_TEST(codecs::encode(format, vector.input, tokens::append_to(appended)).has_value()); + BOOST_TEST(appended == "<" + expected); + auto const fixed = codecs::encode(format, vector.input, tokens::fixed<8>{}); + BOOST_TEST(fixed.has_value() && fixed.value().view() == expected); + return expected; +} + +/** + One vector's decode through the forms of one configuration: the default form, the typed forms, + the tokens and the buffer form, and the sizes. +*/ +template +void expect_decodes(Format const& format, rfc_vector const& vector, std::string const& text) { + BOOST_TEST_EQ(codecs::max_decoded_size(format, text) >= vector.input.size(), true); + auto const decoded = codecs::decode(format, text); + BOOST_TEST(test::decodes_to(decoded, vector.input)); + auto const typed = codecs::decode>(format, text); + BOOST_TEST(test::decodes_to(typed, vector.input)); + auto const fixed_bytes = codecs::decode(format, text, tokens::fixed<6>{}); + BOOST_TEST(fixed_bytes.has_value() && + std::ranges::equal(fixed_bytes.value().view(), test::bytes_of(vector.input))); + std::vector appended_bytes{0x5a}; + BOOST_TEST(codecs::decode(format, text, tokens::append_to(appended_bytes)).has_value()); + BOOST_TEST_EQ(appended_bytes.size(), vector.input.size() + 1); + std::array byte_buffer{}; + auto const decoded_count = codecs::decode(format, text, std::span{byte_buffer}); + BOOST_TEST(decoded_count.has_value() && decoded_count.value() == vector.input.size()); + BOOST_TEST(std::ranges::equal(std::span{byte_buffer}.first(vector.input.size()), + test::bytes_of(vector.input))); + auto const size = codecs::codec::decoded_size(format, text); + BOOST_TEST(size.has_value() && size.value() == vector.input.size()); + // A buffer larger than the result, filled with a sentinel, given to the core and to the + // codec's own decode: the bytes past the count are unchanged. + test::expect_tail_unchanged<12>( + [&](std::span output) { return codecs::decode(format, text, output); }, + test::bytes_of(vector.input)); + test::expect_tail_unchanged<12>( + [&](std::span output) { + return codecs::codec::decode(format, text, output); + }, + test::bytes_of(vector.input)); +} + +/** + One vector through every form of one configuration, and the other padding refused, whichever the + format writes (a fault of the text, not of the format): the unpadded form where the padding is + written is invalid_length, and the padded one where it is not invalid_padding. +*/ +template +void expect_vector(Format const& format, bool url, rfc_vector const& vector, bool padded) { + std::string const text = expect_encodes(format, url, vector, padded); + expect_decodes(format, vector, text); + if (!vector.padded.empty() && vector.padded.back() == '=') { + auto const other = + padded ? test::without_padding(vector.padded) : std::string{vector.padded}; + auto const refused = codecs::decode(format, other); + BOOST_TEST(!refused.has_value()); + BOOST_TEST(refused.error() == + (padded ? codecs::error::invalid_length : codecs::error::invalid_padding)); + } +} + +/** RFC 4648 section 10's vectors through one configuration. */ +template +void expect_every_vector(Format const& format, bool url, bool padded) { + for (rfc_vector const& vector : rfc4648_vectors) { + expect_vector(format, url, vector, padded); + } +} + +/** + The spec's "RFC 4648's vectors and the URL alphabet": section 10's inputs with base64 and with + base64url, in both paddings, and the bytes 0xfb 0xff as "+/8=" and "-_8", each decoding back. +*/ +void rfc4648_vectors_and_the_url_alphabet() { + expect_every_vector(formats::base64, false, true); + expect_every_vector(formats::base64(formats::padding::omitted), false, false); + expect_every_vector(formats::base64url, true, false); + expect_every_vector(formats::base64url(formats::padding::written), true, true); + + std::array const bytes{0xfb, 0xff}; + auto const standard = codecs::encode(formats::base64, bytes); + auto const url = codecs::encode(formats::base64url, bytes); + BOOST_TEST(standard.has_value() && standard.value().view() == "+/8="); + BOOST_TEST(url.has_value() && url.value().view() == "-_8"); + auto const unpadded = codecs::encode(formats::base64(formats::padding::omitted), bytes); + auto const padded_url = codecs::encode(formats::base64url(formats::padding::written), bytes); + BOOST_TEST(unpadded.has_value() && unpadded.value().view() == "+/8"); + BOOST_TEST(padded_url.has_value() && padded_url.value().view() == "-_8="); + auto const standard_back = codecs::decode(formats::base64, standard.value()); + auto const url_back = codecs::decode(formats::base64url, url.value()); + BOOST_TEST(standard_back.has_value() && + std::ranges::equal(standard_back.value().view(), bytes)); + BOOST_TEST(url_back.has_value() && std::ranges::equal(url_back.value().view(), bytes)); + // A character of the other alphabet is no character of this one. + BOOST_TEST(codecs::decode(formats::base64, url.value().view()).error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(formats::base64url, std::string_view{"+/8"}).error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(formats::base64url, std::string_view{"-_8="}).error() == + codecs::error::invalid_padding); +} + +/** The spec's "The exact size and the bound", at run time as well: decode writes 4 bytes. */ +void the_exact_size_and_the_bound() { + std::string_view const text = "Zm9vYg=="; + BOOST_TEST_EQ(codecs::encoded_size(formats::base64, foob), 8U); + BOOST_TEST_EQ(codecs::max_decoded_size(formats::base64, text), 6U); + auto const decoded = codecs::decode(formats::base64, text); + BOOST_TEST(decoded.has_value() && decoded.value().size() == 4); + BOOST_TEST_EQ(base64_codec::decoded_size(formats::base64, text).value(), 4U); + std::array buffer{}; + auto const written = codecs::decode(formats::base64, text, std::span{buffer}); + BOOST_TEST(written.has_value() && written.value() == 4); + // The buffer of the bound is enough, the one of the exact size is as well, one less is not. + BOOST_TEST(codecs::decode(formats::base64, text, std::span{buffer}.first(4)).has_value()); + BOOST_TEST(codecs::decode(formats::base64, text, std::span{buffer}.first(3)).error() == + codecs::error::output_too_small); +} + +/** An input and the text base64 refuses it with, in the configurations the entry names. */ +struct refusal { + /** The text. */ + std::string_view text; + /** The format's configuration it is read with: padding written or omitted. */ + bool padded; + /** The error. */ + codecs::error expected; +}; + +/** Checks that `format` refuses `text` with `expected` in every form, writing nothing. */ +template +void expect_refusal(Format const& format, std::string_view text, codecs::error expected) { + auto const defaulted = codecs::decode(format, text); + BOOST_TEST(!defaulted.has_value() && defaulted.error() == expected); + auto const size = codecs::codec::decoded_size(format, text); + BOOST_TEST(!size.has_value() && size.error() == expected); + std::array buffer{}; + buffer.fill(0x5a); + auto const written = codecs::decode(format, text, std::span{buffer}); + BOOST_TEST(!written.has_value() && written.error() == expected); + BOOST_TEST(std::ranges::all_of(buffer, [](std::uint8_t byte) { return byte == 0x5a; })); + std::vector appended{0x5a}; + auto const token = codecs::decode(format, text, tokens::append_to(appended)); + BOOST_TEST(!token.has_value() && token.error() == expected); + BOOST_TEST(appended == std::vector{0x5a}); + auto const typed = codecs::decode>(format, text); + BOOST_TEST(!typed.has_value() && typed.error() == expected); + // The reference gives the same verdict. + auto const reference = + test::reference_base64_decode(text, std::is_same_v, + format.padding_option == formats::padding::written); + BOOST_TEST(reference.fault == std::optional{expected}); +} + +/** + Every error of the format, one input each, with the padding written (base64's default): a + character outside the alphabet, whitespace and a line break (invalid_character), a length that is + no multiple of 4 (invalid_length), a `=` against the rules and non-zero trailing bits + (invalid_padding); the spec's "Zh==", "Zm9v" and a line feed, "Zm9v Zm9v", "Zm9" and a base64url + character. +*/ +void every_error_with_the_padding_written() { + auto const& base64 = formats::base64; + constexpr auto character = codecs::error::invalid_character; + constexpr auto length = codecs::error::invalid_length; + constexpr auto padding = codecs::error::invalid_padding; + // The spec's scenario "A non-canonical text": the trailing bits of "Zh==" are not zero. + expect_refusal(base64, "Zh==", padding); + expect_refusal(base64, "Zm9v\n", character); + expect_refusal(base64, "Zm9v Zm9v", character); + expect_refusal(base64, "\nZm9v", character); + expect_refusal(base64, "Zm9v\r\n", character); + expect_refusal(base64, "Zm9 v", character); + expect_refusal(base64, "Zm9", length); + expect_refusal(base64, "Zg", length); + expect_refusal(base64, "Z", length); + expect_refusal(base64, "Zg=", length); + expect_refusal(base64, "Zm9vYg=", length); + expect_refusal(base64, "Zm9vY", length); + // A character of base64url in base64, and the other way. + expect_refusal(base64, "Zm9-", character); + expect_refusal(base64, "Zm9_", character); + expect_refusal(base64, std::string_view{"Zm9\0", 4}, character); + expect_refusal(base64, "Zm9\xc1", character); + expect_refusal(base64, "Zm9\xff", character); + expect_refusal(base64, "Zm9*", character); + expect_refusal(base64, "Zm9v====", padding); + // Padding where it is not: before the last group, in the middle of one, alone, and the third + // character padded with a fourth that is not. + expect_refusal(base64, "Zg==Zm9v", padding); + expect_refusal(base64, "Zg==Zg==", padding); + expect_refusal(base64, "Zm9v=Zm9", padding); + expect_refusal(base64, "Z===", padding); + expect_refusal(base64, "====", padding); + expect_refusal(base64, "=Zg=", padding); + expect_refusal(base64, "Zg=a", padding); + expect_refusal(base64, "Zm=9", padding); + // Non-zero trailing bits: one byte ends in four bits, two in two. + expect_refusal(base64, "Zm9=", padding); + expect_refusal(base64, "Zh==", padding); + expect_refusal(base64, "Zm9vZh==", padding); + // Two faults give the lowest value (B23): an invalid character before the length, which comes + // before the padding. + expect_refusal(base64, "Zh==\n", character); + expect_refusal(base64, "Zh=\n", character); + expect_refusal(base64, "Zh=", length); + expect_refusal(base64, "Zm9=Zm9", length); + expect_refusal(base64, "Zg==Zm9\n", character); + expect_refusal(base64, "Zm9=\n", character); + // The valid texts of the same shapes. + BOOST_TEST(codecs::decode(base64, std::string_view{"Zg=="}).has_value()); + BOOST_TEST(codecs::decode(base64, std::string_view{"Zm8="}).has_value()); +} + +/** + Every error with the padding omitted (base64url's default, base64's by option): a `=` anywhere is + padding against the option (invalid_padding), a length of 4k + 1 has no encoding (invalid_length), + non-zero trailing bits are invalid_padding, and the faults of two kinds give the lowest value. +*/ +void every_error_with_the_padding_omitted() { + auto const& base64url = formats::base64url; + constexpr auto character = codecs::error::invalid_character; + constexpr auto length = codecs::error::invalid_length; + constexpr auto padding = codecs::error::invalid_padding; + expect_refusal(base64url, "Zg==", padding); + expect_refusal(base64url, "Zg=", padding); + expect_refusal(base64url, "Zm8=", padding); + expect_refusal(base64url, "Zm9v=", length); + expect_refusal(base64url, "Zm9vYg==", padding); + expect_refusal(base64url, "Z=", padding); + expect_refusal(base64url, "Zh", padding); + expect_refusal(base64url, "Zm9", padding); + expect_refusal(base64url, "Zm9vZh", padding); + expect_refusal(base64url, "Z", length); + expect_refusal(base64url, "Zm9vY", length); + expect_refusal(base64url, "Zm9vYmFyZ", length); + expect_refusal(base64url, "Zm9v\n", character); + expect_refusal(base64url, "Zm9v Zm9v", character); + expect_refusal(base64url, "Zm+/", character); + expect_refusal(base64url, "Zm9v\xc1", character); + // Two faults: the lowest value of error. + expect_refusal(base64url, "Zh=\n", character); + expect_refusal(base64url, "Zh==\n", character); + expect_refusal(base64url, "Zm9v=", length); + expect_refusal(base64url, "Zh=Zm", length); + BOOST_TEST(codecs::decode(base64url, std::string_view{"Zg"}).has_value()); + BOOST_TEST(codecs::decode(base64url, std::string_view{"Zm8"}).has_value()); + // base64 with its padding omitted is the same format of the other alphabet. + auto const unpadded = formats::base64(formats::padding::omitted); + expect_refusal(unpadded, "Zg==", padding); + expect_refusal(unpadded, "Zm9v-", character); + expect_refusal(unpadded, "Zm9vY", length); + BOOST_TEST(codecs::decode(unpadded, std::string_view{"+/8"}).has_value()); + // base64url with its padding written. + auto const padded_url = formats::base64url(formats::padding::written); + expect_refusal(padded_url, "-_8", length); + expect_refusal(padded_url, "-_9=", padding); + expect_refusal(padded_url, "+/8=", character); + BOOST_TEST(codecs::decode(padded_url, std::string_view{"-_8="}).has_value()); +} + +/** + The plain reading of `text`, compared with the library's decode and decoded_size for a + configuration: the same bytes, or the same error. +*/ +template +void expect_the_reference_reading(Format const& format, bool url, bool padded, + std::string_view text) { + test::reference_reading const reference = test::reference_base64_decode(text, url, padded); + auto const size = codecs::codec::decoded_size(format, text); + std::array buffer{}; + std::span const output = std::span{buffer}.first( + std::min(buffer.size(), codecs::max_decoded_size(format, text))); + auto const written = codecs::decode(format, text, output); + if (reference.fault) { + BOOST_TEST(!size.has_value() && size.error() == *reference.fault); + BOOST_TEST(!written.has_value() && written.error() == *reference.fault); + return; + } + BOOST_TEST(size.has_value() && size.value() == reference.bytes.size()); + BOOST_TEST(written.has_value() && written.value() == reference.bytes.size()); + BOOST_TEST(std::ranges::equal(output.first(reference.bytes.size()), reference.bytes)); +} + +/** Runs @ref expect_the_reference_reading in every configuration: both alphabets and paddings. */ +void expect_the_reference_reading_everywhere(std::string_view text) { + expect_the_reference_reading(formats::base64, false, true, text); + expect_the_reference_reading(formats::base64(formats::padding::omitted), false, false, text); + expect_the_reference_reading(formats::base64url, true, false, text); + expect_the_reference_reading(formats::base64url(formats::padding::written), true, true, text); +} + +/** + Review Focus 1: each of the 256 byte values as a character, `char` signed, at each place of a + text, in every configuration: the verdict and the bytes equal a plain reference's. NUL, 0x80 to + 0xff, the characters one past each range (the slash, the colon, the at sign, `[`, the backquote, + `{`), `=`, and the symbols of the other alphabet are among them. The places are the four of a + group, in the first group and in the last, with the padding written and with it omitted, and as the + lone last character of a text of 4k + 1 characters. +*/ +void every_byte_value_as_a_character() { + for (std::string_view const base : { + "Zm9vYmFy", + "Zm9vYg==", + "Zm9vYmE=", + "Zm9vYg", + "Zm9vYmE", + "AAAAAAAA", + "Zg==", + "Zm9v", + "Zg", + "Zm8", + "Zm9vY", + }) { + std::string const text{base}; + for (std::size_t place = 0; place <= base.size(); ++place) { + for (unsigned value = 0; value < 256; ++value) { + auto const character = static_cast(static_cast(value)); + std::string replaced = text; + if (place == base.size()) { + replaced.push_back(character); + } else { + replaced[place] = character; + } + expect_the_reference_reading_everywhere(replaced); + } + } + } + // The arithmetic alone: every byte against the plain table, in both alphabets. + for (bool const url : {false, true}) { + std::string_view const symbols = test::base64_symbols(url); + for (unsigned value = 0; value < 256; ++value) { + auto const character = static_cast(static_cast(value)); + std::size_t const at = symbols.find(character); + auto const [six_bits, invalid] = + url ? read_symbol(character) : read_symbol(character); + BOOST_TEST_EQ(invalid, at == std::string_view::npos); + BOOST_TEST_EQ(six_bits, at == std::string_view::npos ? 0U : static_cast(at)); + } + for (unsigned value = 0; value < 64; ++value) { + std::uint8_t const symbol = + url ? detail::base64_arithmetic::symbol_of(static_cast(value)) + : detail::base64_arithmetic::symbol_of(static_cast(value)); + BOOST_TEST_EQ(static_cast(symbol), symbols[value]); + } + } +} + +/** + Texts near the valid ones, against the plain reference in every configuration: the base64 of + random bytes, from 0 to 40, with up to three characters replaced by a symbol of either alphabet, + `=`, a line feed or any byte, and cut or lengthened by up to two characters; decode and + decoded_size give the reference's bytes or error. +*/ +void texts_near_the_valid_ones() { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): a fixed seed + std::mt19937_64 generator{20261126}; + constexpr std::string_view odd_characters = "=+/-_ \n*\x7f\x80\xc1\xff"; + for (int iteration = 0; iteration < 5000; ++iteration) { + std::size_t const size = generator() % 41; + std::vector bytes(size); + for (std::uint8_t& byte : bytes) { + byte = static_cast(generator()); + } + bool const url = (generator() & 1U) != 0; + bool const padded = (generator() & 1U) != 0; + std::string text = test::reference_base64_encode(bytes, url, padded); + for (std::size_t edits = generator() % 4; edits > 0 && !text.empty(); --edits) { + std::size_t const at = generator() % text.size(); + std::size_t const kind = generator() % 4; + if (kind == 0) { + text[at] = odd_characters[generator() % odd_characters.size()]; + } else if (kind == 1) { + text[at] = test::base64_symbols(false)[generator() % 64]; + } else if (kind == 2) { + text[at] = static_cast(generator()); + } else { + text[at] = '='; + } + } + if (generator() % 4 == 0 && !text.empty()) { + text.resize(text.size() - (generator() % std::min(3, text.size() + 1))); + } else if (generator() % 8 == 0) { + text.append(generator() % 3, 'A'); + } + expect_the_reference_reading_everywhere(text); + } +} + +/** + Review Focus 4: a text decoded into its own storage gives the right bytes, byte `i` written after + the characters it comes from are read; an invalid one leaves the storage as it was. Both + paddings, each length of the last group. +*/ +void decoding_in_place() { + for (std::size_t const size : {0U, 1U, 2U, 3U, 4U, 5U, 6U, 31U, 32U, 33U, 100U}) { + std::vector const bytes = test::random_bytes(size); + test::expect_in_place(formats::base64, test::reference_base64_encode(bytes, false, true), + bytes); + test::expect_in_place(formats::base64(formats::padding::omitted), + test::reference_base64_encode(bytes, false, false), bytes); + } +} + +/** + Review Focus 3, the encodes: empty input in every form gives an empty result: the default results + in place and on the heap, the buffer form (0 written), the tokens, the secret token and the size. +*/ +void empty_input_in_every_encode() { + std::array const nothing{}; + auto const fixed = codecs::encode(formats::base64, nothing); + static_assert(std::is_same_v> const>); + BOOST_TEST(fixed.has_value() && fixed.value().size() == 0); + auto const heap = codecs::encode(formats::base64, std::vector{}); + BOOST_TEST(heap.has_value() && heap.value().empty()); + auto const url = codecs::encode(formats::base64url, std::string{}); + BOOST_TEST(url.has_value() && url.value().empty()); + auto const unpadded = codecs::encode(formats::base64(formats::padding::omitted), std::string{}); + BOOST_TEST(unpadded.has_value() && unpadded.value().empty()); + auto const padded_url = + codecs::encode(formats::base64url(formats::padding::written), std::string{}); + BOOST_TEST(padded_url.has_value() && padded_url.value().empty()); + auto const buffer_written = + codecs::encode(formats::base64, std::span{}, std::span{}); + BOOST_TEST(buffer_written.has_value() && buffer_written.value() == 0); + auto const returned = codecs::encode(formats::base64, nothing, tokens::return_string); + BOOST_TEST(returned.has_value() && returned.value().empty()); + std::string kept{"kept"}; + BOOST_TEST(codecs::encode(formats::base64, nothing, tokens::append_to(kept)).has_value()); + BOOST_TEST(kept == "kept"); + auto const secret_empty = codecs::encode(formats::base64, nothing, tokens::secret); + BOOST_TEST(secret_empty.has_value() && secret_empty.value().size() == 0); + BOOST_TEST_EQ(codecs::encoded_size(formats::base64, std::vector{}), 0U); + BOOST_TEST_EQ(codecs::encoded_size(formats::base64url, std::vector{}), 0U); +} + +/** Review Focus 3, the decodes: an empty text gives an empty result in every form. */ +void empty_text_in_every_decode() { + for (formats::padding const option : {formats::padding::written, formats::padding::omitted}) { + test::expect_empty_text_decodes(formats::base64(option)); + test::expect_empty_text_decodes(formats::base64url(option)); + } +} + +/** + The typed decodes: into an array of exactly N bytes (invalid_length otherwise), into bytes (up + to N, output_too_small otherwise), the heap, and a secret type, with no heap for the fixed ones. +*/ +void the_typed_decodes() { + std::array const digest = test::digest_bytes(); + auto const text = codecs::encode(formats::base64, digest); + BOOST_TEST(text.has_value()); + bool volatile verdict = false; + test::expect_no_allocation("typed decodes into fixed arrays", [&] { + auto const key = + codecs::decode>(formats::base64, text.value()); + auto const short_key = + codecs::decode>(formats::base64, text.value()); + auto const fixed = codecs::decode>(formats::base64, text.value()); + auto const too_small = codecs::decode>(formats::base64, text.value()); + verdict = key.has_value() && key.value() == digest && !short_key.has_value() && + short_key.error() == codecs::error::invalid_length && fixed.has_value() && + fixed.value().size() == 32 && !too_small.has_value() && + too_small.error() == codecs::error::output_too_small; + }); + BOOST_TEST(verdict); + // The text of 32 bytes without its padding, in base64url's default. + auto const url_text = codecs::encode(formats::base64url, digest); + BOOST_TEST(url_text.has_value() && url_text.value().size() == 43); + auto const url_key = + codecs::decode>(formats::base64url, url_text.value()); + BOOST_TEST(url_key.has_value() && url_key.value() == digest); + auto const heap = codecs::decode>(formats::base64, text.value()); + BOOST_TEST(heap.has_value() && std::ranges::equal(heap.value(), digest)); + auto const as_string = codecs::decode(formats::base64, text.value()); + BOOST_TEST(as_string.has_value() && as_string.value().size() == 32); +} + +} // namespace + +int main() { + rfc4648_vectors_and_the_url_alphabet(); + the_exact_size_and_the_bound(); + every_error_with_the_padding_written(); + every_error_with_the_padding_omitted(); + every_byte_value_as_a_character(); + texts_near_the_valid_ones(); + decoding_in_place(); + empty_input_in_every_encode(); + empty_text_in_every_decode(); + the_typed_decodes(); + return boost::report_errors(); +} diff --git a/test/bech32_stream_test.cpp b/test/bech32_stream_test.cpp new file mode 100644 index 0000000..7cecd39 --- /dev/null +++ b/test/bech32_stream_test.cpp @@ -0,0 +1,635 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// bech32 and bech32m as streams (D20, owner decision 27): encoder(bech32("bc")) writes the +// human-readable part and the data as the input comes and the checksum at flush; decoder(bech32) +// holds the raw characters in place and delivers nothing before flush has verified the checksum, +// and gives the part it read by human_readable_part() after it. BIP-173's and BIP-350's valid +// strings, in bytes and in words, and 1000 random inputs, equal the one-shot forms for every +// chunking (support/chunkings.hpp) and output spans of one and 1024; every invalid string, and +// every byte value as a character at each place of a text, gives the one-shot form's error after +// flush, writing nothing (B44); the encoder's own faults (a word above 31, a text past the +// maximum) after flush too. The spec's scenarios "The stream decoder holds until the checksum", +// "A Lightning invoice through a larger instance" (its stream), "A configuration fault wins" (by +// the stream's first call, also after reset) and the hold of a capacity (B47); empty input (Review +// Focus 3); a moved-from stream converts from the start (Review Focus 5); a secret stream wipes +// its pending state and its hold, as secure's wipe seam records it. + +#include "support/wipe_recorder.hpp" + +#include "bech32_vectors.hpp" +#include "support/bech32_reference.hpp" +#include "support/chunkings.hpp" +#include "support/samples.hpp" +#include "support/steps.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; + +using lightning_t = formats::basic_bech32; +using long_t = formats::basic_bech32; +using bech32_encoder = decltype(codecs::encoder(formats::bech32)); +using bech32_decoder = decltype(codecs::decoder(formats::bech32)); +using held_decoder = decltype(codecs::decoder(long_t{}, codecs::capacity<128>)); +using stream_encoder = codecs::stream_codec::encoder; +using stream_decoder = codecs::stream_codec::decoder; +using secret_stream_encoder = + codecs::stream_codec::encoder; +using secret_stream_decoder = + codecs::stream_codec::decoder; + +// bech32 streams natively: one-shot and stream transformers, constant time as its codec is. +static_assert(codecs::one_shot_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); +static_assert(codecs::stream_transformer); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(codecs::is_constant_time_v); +static_assert(codecs::is_constant_time_v); +static_assert(bech32_encoder::max_output_size(32) == 90); +static_assert(bech32_decoder::max_output_size(90) == 51); +// The decoder holds its input (B47): the format's maximum by default, a capacity's otherwise, +// never more than the maximum, and it gives the part it read. +static_assert(stream_decoder::holds); +static_assert(stream_decoder::hold_size == 90); +static_assert(codecs::stream_codec::decoder::hold_size == + 2048); +static_assert(held_decoder::max_output_size(1023) == 634); +static_assert( + codecs::stream_codec::decoder::hold_size == + 128); +static_assert(std::is_same_v().human_readable_part()), + std::string_view>); +static_assert(noexcept(std::declval().human_readable_part())); +// A public stream is copyable and trivially destructible, a secret one move-only and wiping. +static_assert(std::is_trivially_destructible_v); +static_assert(std::is_trivially_destructible_v); +static_assert(std::is_copy_constructible_v); +static_assert(!std::is_trivially_destructible_v); +static_assert(!std::is_trivially_destructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); + +/** + A valid `text` through every chunking of `format`'s decoder, and of the secret one when + `with_secret`, equal to the one-shot decode; its data through every chunking of the encoder of + the part read, and of the secret one likewise, equal to the text in small letters; the part read + given by human_readable_part() after the last flush. +*/ +template +void expect_every_chunking_of(Format const& format, std::string_view text, + bool with_secret = true) { + auto const data = codecs::decode(format, text); + if (!BOOST_TEST(data.has_value())) { + std::printf("not decoded: %.*s\n", static_cast(text.size()), text.data()); + return; + } + auto const parts = codecs::decode(format, text); + auto decoder = codecs::decoder(format); + test::expect_every_chunking(decoder, test::characters_of(text), data.value()); + BOOST_TEST(decoder.human_readable_part() == parts->human_readable_part.view()); + auto const configured = format(parts->human_readable_part.view()); + std::string const lowered = test::ascii_lower(text); + auto encoder = codecs::encoder(configured); + test::expect_every_chunking(encoder, std::span{data.value()}, + std::string_view{lowered}); + if (!with_secret) { + return; + } + auto secret_decoder = codecs::decoder(format, codecs::secret_operation); + test::expect_every_chunking(secret_decoder, test::characters_of(text), data.value()); + auto secret_encoder = codecs::encoder(configured, codecs::secret_operation); + test::expect_every_chunking(secret_encoder, std::span{data.value()}, + std::string_view{lowered}); +} + +/** + Every chunking of `text` decodes as the one-shot form does: the same data, or the same error, + reported after flush by the call that reads the end, which writes nothing (B44); public and, + when `with_secret`, secret decoders alike. +*/ +template +void expect_the_one_shot_verdict(Format const& format, std::string_view text, + bool with_secret = true) { + test::expect_the_one_shot_verdict(format, text, with_secret, [](auto const& decoder) { + BOOST_TEST(decoder.human_readable_part().empty()); + }); +} + +/** + BIP-173's and BIP-350's valid strings, in their variant, over bytes where they regroup and over + words always, through every chunking of the decoder and the encoder. +*/ +void every_valid_string_through_every_chunking() { + // The secret streams run the same arithmetic: they take the words, the public ones both modes. + for (test::valid_string const& entry : test::bip173_valid_strings) { + if (!entry.bytes_fault) { + expect_every_chunking_of(formats::bech32, entry.text, false); + } + expect_every_chunking_of(formats::bech32.words(), entry.text); + } + for (test::valid_string const& entry : test::bip350_valid_strings) { + if (!entry.bytes_fault) { + expect_every_chunking_of(formats::bech32m, entry.text, false); + } else { + expect_the_one_shot_verdict(formats::bech32m, entry.text); + } + expect_every_chunking_of(formats::bech32m.words(), entry.text); + } + // The segwit addresses, in words mode: version 0 in bech32, the others in bech32m. + for (test::segwit_address const& entry : test::bip350_segwit_addresses) { + if (entry.script.starts_with("00")) { + expect_every_chunking_of(formats::bech32.words(), entry.address, false); + } else { + expect_every_chunking_of(formats::bech32m.words(), entry.address, false); + } + } +} + +/** + 1000 random inputs: a part of 1 to 4 characters of 33 to 126 and 0 to 8 bytes, or words, in + either variant, encoded and decoded through every chunking, equal to the one-shot forms; one in + eight through the secret streams too. +*/ +void a_thousand_random_inputs() { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): a fixed seed + std::mt19937_64 generator{20261127}; + for (int iteration = 0; iteration < 1000; ++iteration) { + std::string part; + for (std::size_t size = 1 + (generator() % 4); size > 0; --size) { + part.push_back(static_cast(33 + (generator() % 94))); + } + bool const words = iteration % 4 >= 2; + std::vector data(generator() % 9); + for (std::uint8_t& element : data) { + element = static_cast(generator() & (words ? 31U : 255U)); + } + bool const with_secret = iteration % 32 < 4; + switch (iteration % 4) { + case 0: + expect_every_chunking_of(formats::bech32, + test::reference_bech32_encode(part, data, false, false), + with_secret); + break; + case 1: + expect_every_chunking_of(formats::bech32m, + test::reference_bech32_encode(part, data, true, false), + with_secret); + break; + case 2: + expect_every_chunking_of(formats::bech32.words(), + test::reference_bech32_encode(part, data, false, true), + with_secret); + break; + default: + expect_every_chunking_of(formats::bech32m.words(), + test::reference_bech32_encode(part, data, true, true), + with_secret); + break; + } + } +} + +/** + Every invalid string of the BIPs' lists, in both modes, and each byte value as a character at + each place of a short text and appended to it, give the one-shot form's error after flush, for + every chunking. +*/ +void invalid_texts_give_the_one_shot_error_after_flush() { + for (test::invalid_string const& entry : test::bip173_invalid_strings) { + expect_the_one_shot_verdict(formats::bech32, entry.text); + expect_the_one_shot_verdict(formats::bech32.words(), entry.text); + } + for (test::invalid_string const& entry : test::bip350_invalid_strings) { + expect_the_one_shot_verdict(formats::bech32m, entry.text); + expect_the_one_shot_verdict(formats::bech32m.words(), entry.text); + } + std::string_view const base = "a12uel5l"; + for (std::size_t place = 0; place <= base.size(); ++place) { + for (unsigned value = 0; value < 256; ++value) { + auto const character = static_cast(static_cast(value)); + std::string text{base}; + if (place == base.size()) { + text.push_back(character); + } else { + text[place] = character; + } + // The secret decoder runs the same verdict: one value in sixteen is enough for it. + expect_the_one_shot_verdict(formats::bech32, text, value % 16 == 0); + } + } + // A part other than the format's, and a mixed case. + expect_the_one_shot_verdict(formats::bech32("b"), "a12uel5l"); + expect_the_one_shot_verdict(formats::bech32, "A12uel5l"); +} + +/** + Sends `text` to `decoder` one character at a time, receiving after each, and checks that each + send takes its character and each receive delivers nothing, writing nothing. +*/ +template +void send_one_at_a_time(Decoder& decoder, std::string_view text) { + std::array span{}; + span.fill(0x5a); + std::size_t delivered = 0; + for (char const character : text) { + std::array const one{character}; + BOOST_TEST(test::is_step(decoder.send(one), 1, codecs::flow::needs_input)); + auto const received = decoder.receive(span); + BOOST_TEST(test::is_step(received, 0, codecs::flow::needs_input)); + delivered += received.has_value() ? received->count : 0; + } + BOOST_TEST_EQ(delivered, 0U); + BOOST_TEST(std::ranges::all_of(span, [](std::uint8_t byte) { return byte == 0x5a; })); +} + +/** + The spec's "The stream decoder holds until the checksum": a valid text sent to + decoder(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. +*/ +void the_decoder_holds_until_the_checksum() { + std::array const digest = test::digest_bytes(); + std::span const digest_prefix = std::span{digest}.first<20>(); + auto const encoded = codecs::encode(formats::bech32("bc"), digest_prefix); + std::string_view const address = encoded.value().view(); + auto const expected = codecs::decode(formats::bech32("bc"), address); + BOOST_TEST(expected.has_value()); + auto decoder = codecs::decoder(formats::bech32("bc")); + send_one_at_a_time(decoder, address); + BOOST_TEST(decoder.human_readable_part().empty()); + auto const flushed = decoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + BOOST_TEST(decoder.human_readable_part() == "bc"); + std::array data{}; + auto const received = decoder.receive(data); + BOOST_TEST(test::is_step(received, expected->size(), codecs::flow::finished)); + BOOST_TEST(std::ranges::equal(std::span{data}.first(expected->size()), expected.value())); + + std::string changed{address}; + changed.back() = changed.back() == 'q' ? 'p' : 'q'; + decoder.reset(); + send_one_at_a_time(decoder, changed); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::checksum_mismatch)); + data.fill(0x5a); + BOOST_TEST(test::failed_with(decoder.receive(data), codecs::error::checksum_mismatch)); + BOOST_TEST(std::ranges::all_of(data, [](std::uint8_t byte) { return byte == 0x5a; })); + BOOST_TEST(decoder.human_readable_part().empty()); + // A send after flush accepts nothing; after the error it returns it. + BOOST_TEST(test::failed_with(decoder.send(test::characters_of("q")), + codecs::error::checksum_mismatch)); + decoder.reset(); + BOOST_TEST(decoder.send(test::characters_of(address)).has_value()); + BOOST_TEST(decoder.flush().has_value()); + BOOST_TEST( + test::is_step(decoder.send(test::characters_of("q")), 0, codecs::flow::output_pending)); +} + +/** + The spec's "A Lightning invoice through a larger instance", its stream: BOLT 11's first invoice + through decoder(basic_bech32("lnbc").words()) gives the one-shot words, for spans + of one and more; through decoder(bech32("lnbc").words()), input_too_long at flush, nothing ever + delivered. +*/ +void a_lightning_invoice_through_a_stream() { + std::string_view const invoice = test::bolt11_donation_invoice; + auto const lightning = lightning_t{}("lnbc").words(); + auto const words = codecs::decode(lightning, invoice).value(); + auto decoder = codecs::decoder(lightning); + std::vector> const whole{test::characters_of(invoice)}; + for (std::size_t const span_size : {std::size_t{1}, std::size_t{7}, std::size_t{1024}}) { + decoder.reset(); + auto const streamed = test::stream_whole(decoder, whole, span_size); + BOOST_TEST(streamed.has_value() && streamed.value() == words); + BOOST_TEST(decoder.human_readable_part() == "lnbc"); + } + std::uint64_t timestamp = 0; + for (std::size_t index = 0; index < 7; ++index) { + timestamp = (timestamp * 32) + words[index]; + } + BOOST_TEST_EQ(timestamp, test::bolt11_donation_timestamp); + auto encoder = codecs::encoder(lightning); + test::expect_every_chunking(encoder, std::span{words}, invoice); + + auto short_decoder = codecs::decoder(formats::bech32("lnbc").words()); + std::array span{}; + std::size_t delivered = 0; + for (std::size_t position = 0; position < invoice.size(); position += 16) { + auto const sent = short_decoder.send(test::characters_of(invoice.substr(position, 16))); + BOOST_TEST(sent.has_value()); + auto const received = short_decoder.receive(span); + BOOST_TEST(received.has_value()); + delivered += received ? received->count : 0; + } + BOOST_TEST(test::failed_with(short_decoder.flush(), codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(short_decoder.receive(span), codecs::error::input_too_long)); + BOOST_TEST_EQ(delivered, 0U); +} + +/** + The hold of a capacity (B47): decoder(basic_bech32("lnbc"), capacity<128>) holds + 128 characters: a text of 128 (73 bytes) decodes as the one-shot form does, one of 130 (74 + bytes) and one of 300 (289 words), which the format's own maximum takes, are input_too_long at + flush. +*/ +void the_hold_of_a_capacity() { + auto const format = long_t{}("lnbc"); + std::string const fits = + test::reference_bech32_encode("lnbc", test::random_bytes(73), false, false); + BOOST_TEST_EQ(fits.size(), 128U); + std::string const just_past = + test::reference_bech32_encode("lnbc", test::random_bytes(74), false, false); + BOOST_TEST_EQ(just_past.size(), 130U); + std::vector const words(289, 17); + std::string const long_text = test::reference_bech32_encode("lnbc", words, false, true); + BOOST_TEST_EQ(long_text.size(), 300U); + BOOST_TEST(codecs::decode(format.words(), long_text).has_value()); + BOOST_TEST(codecs::decode(format, just_past).has_value()); + auto decoder = codecs::decoder(format, codecs::capacity<128>); + std::vector> chunks{test::characters_of(fits)}; + auto const streamed = test::stream_whole(decoder, chunks, 50); + BOOST_TEST(streamed.has_value() && streamed.value() == codecs::decode(format, fits).value()); + for (std::string const* const text : {&just_past, &long_text}) { + decoder.reset(); + BOOST_TEST(test::is_step(decoder.send(test::characters_of(*text)), text->size(), + codecs::flow::needs_input)); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::input_too_long)); + } + auto secret_held = codecs::decoder(format, codecs::secret_operation, codecs::capacity<128>); + BOOST_TEST(secret_held.send(test::characters_of(long_text)).has_value()); + BOOST_TEST(test::failed_with(secret_held.flush(), codecs::error::input_too_long)); + auto other_order = codecs::decoder(format, codecs::capacity<128>, codecs::secret_operation); + auto const streamed_secret = test::stream_whole(other_order, chunks, 1); + BOOST_TEST(streamed_secret.has_value() && streamed_secret.value() == streamed.value()); +} + +/** + The spec's "A configuration fault wins", as streams: a text with an invalid character and a bad + checksum, with a format whose part is 84 characters, is invalid_prefix from the decoder's first + call, whatever it is, and every call after, also after reset; the same for the encoder, and for + an encoder with no part at all, which has nothing to write. +*/ +void a_configuration_fault_by_the_first_call() { + std::string const part_84(84, 'a'); + auto const overflowed = formats::bech32(part_84); + std::array span{}; + std::array characters{}; + auto decoder = codecs::decoder(overflowed); + BOOST_TEST(test::failed_with(decoder.receive(span), codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(decoder.send(test::characters_of("x1b4n0q5v")), + codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_prefix)); + decoder.reset(); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(decoder.transform(test::characters_of("x1b4n0q5v"), span), + codecs::error::invalid_prefix)); + BOOST_TEST_EQ(decoder.output_size(test::characters_of("a12uel5l")), 0U); + auto first_flush = codecs::decoder(overflowed, codecs::secret_operation); + BOOST_TEST(test::failed_with(first_flush.flush(), codecs::error::invalid_prefix)); + + std::array const bytes{1, 2}; + for (auto encoder : {codecs::encoder(overflowed), codecs::encoder(formats::bech32)}) { + BOOST_TEST(test::failed_with(encoder.send(bytes), codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(encoder.receive(characters), codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(encoder.flush(), codecs::error::invalid_prefix)); + encoder.reset(); + BOOST_TEST(test::failed_with(encoder.flush(), codecs::error::invalid_prefix)); + BOOST_TEST( + test::failed_with(encoder.transform(bytes, characters), codecs::error::invalid_prefix)); + BOOST_TEST_EQ(encoder.output_size(bytes), 0U); + } + auto no_part = codecs::encoder(formats::bech32m.words(), codecs::secret_operation); + BOOST_TEST(test::failed_with(no_part.receive(characters), codecs::error::invalid_prefix)); +} + +/** + The encoder's own faults, after flush, by the call that reaches the end, which writes nothing + (B44): a word above 31 is invalid_character, a text past the maximum input_too_long, for every + chunking; the one-shot form's errors. +*/ +void the_encoders_faults_after_flush() { + std::vector words(20, 7); + words[13] = 32; + std::vector const long_bytes = test::random_bytes(60); + auto const format = formats::bech32("bc"); + BOOST_TEST(codecs::encode(format.words(), words).error() == codecs::error::invalid_character); + BOOST_TEST(codecs::encode(format, long_bytes).error() == codecs::error::input_too_long); + auto words_encoder = codecs::encoder(format.words()); + auto bytes_encoder = codecs::encoder(format, codecs::secret_operation); + for (std::size_t const span_size : {std::size_t{1}, std::size_t{1024}}) { + test::for_each_chunking( + std::span{words}, + [&](std::span const> chunks) { + words_encoder.reset(); + BOOST_TEST(test::error_after_flush(words_encoder, chunks, span_size) == + codecs::error::invalid_character); + }); + test::for_each_chunking( + std::span{long_bytes}, + [&](std::span const> chunks) { + bytes_encoder.reset(); + BOOST_TEST(test::error_after_flush(bytes_encoder, chunks, span_size) == + codecs::error::input_too_long); + }); + } + // After the error, every call returns it until reset, which converts a valid input. + BOOST_TEST(test::failed_with(bytes_encoder.send(long_bytes), codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(bytes_encoder.flush(), codecs::error::input_too_long)); + bytes_encoder.reset(); + std::vector> const short_input{ + std::span{long_bytes}.first(32), + }; + auto const again = test::stream_whole(bytes_encoder, short_input, 5); + auto const short_text = codecs::encode(format, std::span{long_bytes}.first(32)); + BOOST_TEST(again.has_value() && + std::string(again->begin(), again->end()) == short_text.value()); +} + +/** + The encoder's protocol: the part is written with the first input, not before; a send while + output is pending accepts nothing; a finished encoder's send is {0, finished}. +*/ +void the_encoders_protocol() { + auto encoder = codecs::encoder(formats::bech32("bc")); + std::array four{}; + BOOST_TEST(test::is_step(encoder.receive(four), 0, codecs::flow::needs_input)); + BOOST_TEST(test::is_step(encoder.send({}), 0, codecs::flow::needs_input)); + std::array const bytes{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + BOOST_TEST(test::is_step(encoder.send(bytes), 10, codecs::flow::output_pending)); + BOOST_TEST(test::is_step(encoder.send(bytes), 0, codecs::flow::output_pending)); + BOOST_TEST(test::is_step(encoder.receive(four), 4, codecs::flow::output_pending)); + BOOST_TEST(std::string_view(four.data(), 4).starts_with("bc1")); + std::array rest{}; + BOOST_TEST(test::is_step(encoder.receive(rest), 15, codecs::flow::needs_input)); + auto const flushed = encoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::output_pending); + BOOST_TEST( + test::is_step(encoder.receive(std::span{rest}.subspan(15)), 6, codecs::flow::finished)); + std::string const text = std::string(four.data(), 4) + std::string(rest.data(), 21); + auto const one_shot = codecs::encode(formats::bech32("bc"), bytes); + BOOST_TEST(text == one_shot.value().view()); + BOOST_TEST(test::is_step(encoder.send(bytes), 0, codecs::flow::finished)); + BOOST_TEST(test::is_step(encoder.receive(rest), 0, codecs::flow::finished)); +} + +/** + Review Focus 3: an encoder flushed with nothing sent writes the part, `1` and the checksum; a + decoder flushed with nothing sent has no part, invalid_prefix; transform of empty spans gives the + one-shot forms' errors, an output too small for the part and the checksum, and no part. +*/ +void empty_input() { + auto encoder = codecs::encoder(formats::bech32("bc")); + std::vector> const no_chunk; + auto const encoded = test::stream_whole(encoder, no_chunk, 1); + BOOST_TEST(encoded.has_value() && std::string(encoded->begin(), encoded->end()) == + test::reference_bech32_encode("bc", {}, false, false)); + auto decoder = codecs::decoder(formats::bech32("bc")); + BOOST_TEST(test::failed_with(decoder.flush(), codecs::error::invalid_prefix)); + BOOST_TEST( + test::failed_with(encoder.transform(std::span{}, std::span{}), + codecs::error::output_too_small)); + BOOST_TEST( + test::failed_with(decoder.transform(std::span{}, std::span{}), + codecs::error::invalid_prefix)); + // The text of no data decodes to no data: flush finishes at once. + std::string const empty_text = test::reference_bech32_encode("bc", {}, false, false); + decoder.reset(); + BOOST_TEST(decoder.send(test::characters_of(empty_text)).has_value()); + auto const flushed = decoder.flush(); + BOOST_TEST(flushed.has_value() && flushed.value() == codecs::flow::finished); + std::array one{}; + BOOST_TEST(test::is_step(decoder.receive(one), 0, codecs::flow::finished)); + BOOST_TEST(decoder.human_readable_part() == "bc"); +} + +/** + Review Focus 5: a moved-from encoder and decoder, public and secret, convert an input from the + start, and the moved-to one finishes what the source had begun. +*/ +template +void a_moved_from_stream_converts_from_the_start(Encoder encoder, Decoder decoder) { + std::vector const bytes = test::random_bytes(31); + std::string const text = codecs::encode(formats::bech32("bc"), bytes).value(); + BOOST_TEST(encoder.send(bytes).has_value()); + std::array five{}; + BOOST_TEST(test::is_step(encoder.receive(five), 5, codecs::flow::output_pending)); + Encoder moved_encoder{std::move(encoder)}; + std::vector> const no_chunk; + auto const rest = test::stream_whole(moved_encoder, no_chunk, 3); + BOOST_TEST(rest.has_value() && + std::string(five.data(), 5) + std::string(rest->begin(), rest->end()) == text); + std::vector> const whole{bytes}; + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): Review Focus 5 + auto const again = test::stream_whole(encoder, whole, 7); + BOOST_TEST(again.has_value() && std::string(again->begin(), again->end()) == text); + + BOOST_TEST(decoder.send(test::characters_of(text).first(20)).has_value()); + Decoder moved_decoder{std::move(decoder)}; + std::vector> const tail{test::characters_of(text).subspan(20)}; + auto const decoded_rest = test::stream_whole(moved_decoder, tail, 4); + BOOST_TEST(decoded_rest.has_value() && *decoded_rest == bytes); + BOOST_TEST(moved_decoder.human_readable_part() == "bc"); + std::vector> const whole_text{test::characters_of(text)}; + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): Review Focus 5 + auto const decoded_again = test::stream_whole(decoder, whole_text, 3); + BOOST_TEST(decoded_again.has_value() && *decoded_again == bytes); +} + +/** + A secret stream wipes its pending state (D21): the encoder's 12 bytes of bits, checksum and mask, + and the decoder's hold of 90 characters, in the source after a move, at reset and at destruction; + a public stream wipes nothing. +*/ +void a_secret_streams_state_is_wiped() { + std::vector const bytes = test::random_bytes(31); + std::string const text = codecs::encode(formats::bech32("bc"), bytes).value(); + std::array characters{}; + std::optional encoder; + encoder.emplace(formats::bech32("bc")); + BOOST_TEST(encoder->send(bytes).has_value()); + BOOST_TEST(encoder->receive(std::span{characters}.first(10)).has_value()); + test::clear_wipes(); + secret_stream_encoder moved_encoder{std::move(*encoder)}; + BOOST_TEST_EQ(test::wipes_in(*encoder, 12), 1U); + test::clear_wipes(); + moved_encoder.reset(); + BOOST_TEST_EQ(test::wipes_in(moved_encoder, 12), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(encoder, 12), 1U); + + std::optional decoder; + decoder.emplace(formats::bech32("bc")); + BOOST_TEST(decoder->send(test::characters_of(text)).has_value()); + BOOST_TEST(decoder->flush().has_value()); + test::clear_wipes(); + secret_stream_decoder moved_decoder{std::move(*decoder)}; + BOOST_TEST_EQ(test::wipes_in(*decoder, 90), 1U); + BOOST_TEST(moved_decoder.human_readable_part() == "bc"); + test::clear_wipes(); + moved_decoder.reset(); + BOOST_TEST_EQ(test::wipes_in(moved_decoder, 90), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(decoder, 90), 1U); + + test::clear_wipes(); + { + stream_encoder public_encoder{formats::bech32("bc")}; + BOOST_TEST(public_encoder.send(bytes).has_value()); + BOOST_TEST(public_encoder.receive(characters).has_value()); + public_encoder.reset(); + stream_decoder public_decoder{formats::bech32("bc")}; + BOOST_TEST(public_decoder.send(test::characters_of(text)).has_value()); + BOOST_TEST(public_decoder.flush().has_value()); + public_decoder.reset(); + } + BOOST_TEST_EQ(test::wipes.count, 0U); +} + +} // namespace + +int main() { + every_valid_string_through_every_chunking(); + a_thousand_random_inputs(); + invalid_texts_give_the_one_shot_error_after_flush(); + the_decoder_holds_until_the_checksum(); + a_lightning_invoice_through_a_stream(); + the_hold_of_a_capacity(); + a_configuration_fault_by_the_first_call(); + the_encoders_faults_after_flush(); + the_encoders_protocol(); + empty_input(); + a_moved_from_stream_converts_from_the_start(codecs::encoder(formats::bech32("bc")), + codecs::decoder(formats::bech32("bc"))); + a_moved_from_stream_converts_from_the_start( + codecs::encoder(formats::bech32("bc"), codecs::secret_operation), + codecs::decoder(formats::bech32("bc"), codecs::secret_operation)); + a_secret_streams_state_is_wiped(); + return boost::report_errors(); +} diff --git a/test/bech32_test.cpp b/test/bech32_test.cpp new file mode 100644 index 0000000..0125e00 --- /dev/null +++ b/test/bech32_test.cpp @@ -0,0 +1,944 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// bech32 and bech32m, the formats (D13, owner decision 27, the spec's "Format: bech32 and +// bech32m"): BIP-173's and BIP-350's lists, every valid string decoded and encoded back to its +// small letters, or refused with invalid_padding when its data do not regroup into bytes, in +// bytes mode and in words mode, every invalid string refused with the error the table of +// bech32_vectors.hpp maps it to, through the buffer, token, default and typed forms (the parts +// among them); the spec's scenarios "A Nostr public key", "Segwit addresses in words mode", "A +// version as a byte is another text", "A Lightning invoice through a larger instance" (one-shot; +// its stream is bech32_stream_test's) and "A configuration fault wins" (one-shot); the word +// helpers; every error of the format, one input each, and inputs of two faults giving the lowest +// value (B23); every byte value as a character at every place of a text against the plain +// reference of support/bech32_reference.hpp, `char` signed (Review Focus 1), and texts near the +// valid ones; the bounds saturating at SIZE_MAX (Review Focus 2); empty input in every form +// (Review Focus 3: the text of no data is the part, `1` and the checksum; an empty text has no +// part). Input and output must not overlap (Review Focus 4 does not apply). One implementation +// serves both variants and both data modes: every check runs through more than one of them. + +#include "support/counting.hpp" + +#include "bech32_vectors.hpp" +#include "support/bech32_reference.hpp" +#include "support/samples.hpp" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace detail = webcpp::codecs::detail; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +using bech32_codec = codecs::codec; +using bech32_words_t = + formats::basic_bech32; +using lightning_t = formats::basic_bech32; + +constexpr std::size_t size_maximum = std::numeric_limits::max(); + +// The formats: templates over the variant, the maximum length and the data (owner decision 27), +// whose call holds a human-readable part and whose words() changes the data mode alone. +static_assert(codecs::format && codecs::format); +static_assert(codecs::format && codecs::format); +static_assert( + std::is_same_v>); +static_assert( + std::is_same_v>); +static_assert(formats::bech32_t::name == "bech32" && formats::bech32m_t::name == "bech32m"); +static_assert(formats::bech32_t::maximum_length == 90 && lightning_t::maximum_length == 2048); +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert( + std::is_same_v); +static_assert(std::is_same_v>); +static_assert(static_cast(formats::bech32_variant::bech32) == 1U); +static_assert(static_cast(formats::bech32_variant::bech32m) == 2U); +static_assert(std::is_same_v, unsigned char>); +static_assert(formats::bech32.human_readable_part().empty()); +static_assert(formats::bech32("bc").human_readable_part() == "bc"); +static_assert(formats::bech32("BC").words().human_readable_part() == "BC"); +// The part is held in place: the format outlives the string it was configured from. +static_assert(std::is_trivially_copyable_v); +// The parts hold a text of 83 and the data of the maximum length's longest data, in place. +static_assert(decltype(formats::bech32_t::parts_type{}.human_readable_part)::capacity() == 83); +static_assert(decltype(formats::bech32_t::parts_type{}.data)::capacity() == 51); +static_assert(decltype(bech32_words_t::parts_type{}.data)::capacity() == 82); +static_assert(decltype(lightning_t::parts_type{}.data)::capacity() == 1275); +static_assert(detail::bech32_data_capacity(7) == 0); +static_assert(detail::bech32_data_capacity(8) == 0); + +// Their codec: constant time, one template for every instance, with a configuration to check. +static_assert(bech32_codec::constant_time && codecs::codec::constant_time); +static_assert(codecs::detail::takes_configuration_fault); +static_assert(codecs::detail::has_configuration_fault); +static_assert(!codecs::detail::configuration_fault_of(formats::bech32).has_value()); +static_assert(!codecs::detail::configuration_fault_of(formats::bech32("bc")).has_value()); +static_assert(codecs::detail::configuration_fault_of(formats::bech32("a b")) == + codecs::error::invalid_prefix); +static_assert(codecs::detail::configuration_fault_of(formats::bech32m(std::string_view{"\x7f"})) == + codecs::error::invalid_prefix); +static_assert(detail::bech32_final_constant(formats::bech32_variant::bech32) == 1U); +static_assert(detail::bech32_final_constant(formats::bech32_variant::bech32m) == 0x2bc830a3U); + +// The spec's "A Nostr public key", as constant expressions: 32 bytes are 52 characters, with +// "npub", the separator and the checksum 63. +constexpr std::array nostr_key{}; +static_assert(codecs::encoded_size(formats::bech32("npub"), nostr_key) == 63); +// No part, nothing to encode: 0, which every encode refuses with invalid_prefix. +static_assert(codecs::encoded_size(formats::bech32, nostr_key) == 0); +// A part of 84 characters is a fault of the configuration: 0 (B23). +constexpr std::array part_84_characters = [] { + std::array characters{}; + characters.fill('a'); + return characters; +}(); +constexpr std::string_view part_84{part_84_characters.data(), part_84_characters.size()}; +static_assert(codecs::encoded_size(formats::bech32(part_84), nostr_key) == 0); +static_assert(codecs::detail::configuration_fault_of(formats::bech32(part_84)) == + codecs::error::invalid_prefix); +static_assert(!codecs::detail::configuration_fault_of(formats::bech32(part_84.substr(1)))); + +// Review Focus 2: the bounds come from the maximum length. A text of data no one-character part's +// text fits in is SIZE_MAX, which the core refuses before it reads the input: 51 bytes are 82 +// characters (90 with the shortest part), 52 are 84 (92). Any other is at most the maximum. +static_assert(bech32_codec::max_encoded_size(0) == 90); +static_assert(bech32_codec::max_encoded_size(32) == 90); +static_assert(bech32_codec::max_encoded_size(51) == 90); +static_assert(bech32_codec::max_encoded_size(52) == size_maximum); +static_assert(codecs::codec::max_encoded_size(82) == 90); +static_assert(codecs::codec::max_encoded_size(83) == size_maximum); +static_assert(bech32_codec::max_encoded_size((size_maximum / 8) + 1) == size_maximum); +static_assert(bech32_codec::max_encoded_size(size_maximum) == size_maximum); +static_assert(codecs::codec::max_encoded_size(size_maximum) == size_maximum); +static_assert(codecs::codec::max_encoded_size(32) == 142); +static_assert(detail::bech32_data_characters((size_maximum / 8) + 1, false) == size_maximum); +static_assert(detail::bech32_text_size(size_maximum, 1, true) == size_maximum); +static_assert(!codecs::detail::input_size_fault(formats::bech32, 51).has_value()); +static_assert(codecs::detail::input_size_fault(formats::bech32, 52) == + codecs::error::input_too_long); +static_assert(codecs::detail::input_size_fault(formats::bech32m, size_maximum) == + codecs::error::input_too_long); +// A text past the maximum is SIZE_MAX, refused before it is read; below the shortest text, 0. +static_assert(bech32_codec::max_decoded_size(0) == 0); +static_assert(bech32_codec::max_decoded_size(8) == 0); +static_assert(bech32_codec::max_decoded_size(45) == 23); +static_assert(bech32_codec::max_decoded_size(90) == 51); +static_assert(bech32_codec::max_decoded_size(91) == size_maximum); +static_assert(bech32_codec::max_decoded_size(size_maximum) == size_maximum); +static_assert(codecs::codec::max_decoded_size(90) == 82); +static_assert(codecs::codec::max_decoded_size(2048) == 1275); +static_assert(!codecs::detail::text_size_fault(formats::bech32, 90).has_value()); +static_assert(codecs::detail::text_size_fault(formats::bech32, 91) == + codecs::error::input_too_long); +static_assert(codecs::max_decoded_size(formats::bech32, "a12uel5l") == 0); + +// The default results (D9): in place for a size known at compile time, the heap otherwise. +static_assert(std::is_same_v>>); +static_assert(std::is_same_v const&>())), + codecs::result>>); +static_assert( + std::is_same_v const&>())), + codecs::result>); +static_assert(std::is_same_v>>); +static_assert(std::is_same_v( + formats::bech32, std::string_view{})), + codecs::result>); +static_assert(codecs::decodable); +static_assert(codecs::decodable); +// The parts of one instance are not another's. +static_assert(!codecs::decodable); +static_assert(!codecs::encodable); + +// The arithmetic, as constant expressions: a value's character and a character's value. +static_assert(detail::bech32_character(0) == 'q' && detail::bech32_character(31) == 'l'); +static_assert(detail::bech32_value('q').value == 0 && detail::bech32_value('L').value == 31); +static_assert(detail::bech32_value('b').invalid_mask != 0); +static_assert(detail::bech32_value('1').invalid_mask != 0); +static_assert(detail::bech32_value(static_cast(0xd1)).invalid_mask != 0); + +/** The bytes of a text of hex digits. */ +std::vector from_hex(std::string_view digits) { + return codecs::decode(formats::hex, digits).value(); +} + +/** The human-readable part of a text: what is before its last `1`. */ +std::string_view part_of(std::string_view text) { + return text.substr(0, text.rfind('1')); +} + +/** Whether `Format` is in words mode. */ +template +constexpr bool is_words = std::is_same_v; + +/** Whether `Format` is bech32m. */ +template +constexpr bool is_bech32m = Format::name == "bech32m"; + +/** + Checks that `format` refuses `text` with `expected` in every form of decode, writing nothing, and + that the plain reference agrees. +*/ +template +void expect_refusal(Format const& format, std::string_view text, codecs::error expected) { + auto const defaulted = codecs::decode(format, text); + BOOST_TEST(!defaulted.has_value() && defaulted.error() == expected); + auto const size = codecs::codec::decoded_size(format, text); + BOOST_TEST(!size.has_value() && size.error() == expected); + std::array buffer{}; + buffer.fill(0x5a); + auto const written = codecs::decode(format, text, std::span{buffer}); + BOOST_TEST(!written.has_value() && written.error() == expected); + auto const codec_written = codecs::codec::decode(format, text, std::span{buffer}); + BOOST_TEST(!codec_written.has_value() && codec_written.error() == expected); + BOOST_TEST(std::ranges::all_of(buffer, [](std::uint8_t byte) { return byte == 0x5a; })); + std::vector appended{0x5a}; + auto const token = codecs::decode(format, text, tokens::append_to(appended)); + BOOST_TEST(!token.has_value() && token.error() == expected); + BOOST_TEST(appended == std::vector{0x5a}); + auto const typed = codecs::decode>(format, text); + BOOST_TEST(!typed.has_value() && typed.error() == expected); + auto const parts = codecs::decode(format, text); + BOOST_TEST(!parts.has_value() && parts.error() == expected); + auto const reference = + test::reference_bech32_decode(text, format.human_readable_part(), is_bech32m, + is_words, Format::maximum_length); + if (!BOOST_TEST(reference.fault == std::optional{expected})) { + std::printf("refused text: %.*s\n", static_cast(text.size()), text.data()); + } +} + +/** Checks that `format` decodes `text` to `reference`'s data in the buffer and default forms. */ +template +void expect_buffer_decodes(Format const& format, std::string_view text, + test::bech32_reference_reading const& reference) { + auto const defaulted = codecs::decode(format, text); + BOOST_TEST(defaulted.has_value() && defaulted.value() == reference.data); + auto const size = codecs::codec::decoded_size(format, text); + BOOST_TEST(size.has_value() && size.value() == reference.data.size()); + std::array buffer{}; + buffer.fill(0x5a); + auto const written = codecs::decode(format, text, std::span{buffer}); + BOOST_TEST(written.has_value() && written.value() == reference.data.size()); + BOOST_TEST(std::ranges::equal(std::span{buffer}.first(reference.data.size()), reference.data)); + BOOST_TEST(std::ranges::all_of(std::span{buffer}.subspan(reference.data.size()), + [](std::uint8_t byte) { return byte == 0x5a; })); + if (!reference.data.empty()) { + auto const short_buffer = + codecs::decode(format, text, std::span{buffer}.first(reference.data.size() - 1)); + BOOST_TEST(!short_buffer.has_value() && + short_buffer.error() == codecs::error::output_too_small); + } +} + +/** + Checks that `format` decodes `text` in every form to the reference's data and part, and that the + data encode back, under the part read, to the text in small letters. +*/ +template +void expect_decodes_back(Format const& format, std::string_view text) { + auto const reference = + test::reference_bech32_decode(text, format.human_readable_part(), is_bech32m, + is_words, Format::maximum_length); + BOOST_TEST(!reference.fault.has_value()); + expect_buffer_decodes(format, text, reference); + std::vector appended{0x5a}; + BOOST_TEST(codecs::decode(format, text, tokens::append_to(appended)).has_value()); + BOOST_TEST_EQ(appended.size(), reference.data.size() + 1); + auto const parts = codecs::decode(format, text); + BOOST_TEST(parts.has_value() && parts->human_readable_part.view() == reference.part && + std::ranges::equal(parts->data.view(), reference.data)); + // The data encode back to the small letters, under the part read (pre-flight F8). + auto const configured = format(parts->human_readable_part.view()); + auto const encoded = codecs::encode(configured, reference.data); + BOOST_TEST(encoded.has_value() && encoded.value() == test::ascii_lower(text)); + BOOST_TEST_EQ(codecs::encoded_size(configured, reference.data), text.size()); + auto const returned = codecs::encode(configured, reference.data, tokens::return_string); + BOOST_TEST(returned.has_value() && returned.value() == test::ascii_lower(text)); + auto const fixed = codecs::encode(configured, reference.data, tokens::fixed<90>{}); + BOOST_TEST(fixed.has_value() && fixed.value().view() == test::ascii_lower(text)); + BOOST_TEST(test::reference_bech32_encode(reference.part, reference.data, is_bech32m, + is_words) == test::ascii_lower(text)); + // The format of the part read decodes the text too, and another part is refused. + BOOST_TEST(codecs::decode(configured, text).has_value()); + if (reference.part != "other") { + BOOST_TEST(codecs::decode(format("other"), text).error() == codecs::error::invalid_prefix); + } +} + +/** + One valid string of a BIP's list in its variant `format`: over bytes it decodes back, or is + refused with the table's error; over words it decodes back; in the other variant it fails the + checksum, unless a lower fault comes first, as the reference says. +*/ +template +void expect_valid_string(Format const& format, Other const& other, + test::valid_string const& entry) { + if (entry.bytes_fault) { + expect_refusal(format, entry.text, *entry.bytes_fault); + } else { + expect_decodes_back(format, entry.text); + } + expect_decodes_back(format.words(), entry.text); + // No string is valid in both variants (BIP-350). + auto const in_other = codecs::decode(other.words(), entry.text); + BOOST_TEST(!in_other.has_value() && in_other.error() == codecs::error::checksum_mismatch); + auto const other_reference = + test::reference_bech32_decode(entry.text, "", is_bech32m, false); + BOOST_TEST(other_reference.fault.has_value()); + expect_refusal(other, entry.text, other_reference.fault.value()); +} + +/** + The spec's "BIP-173's and BIP-350's lists": every valid string passes the checksum and case + checks, decodes and encodes back to its small letters, or is invalid_padding over bytes (BIP-350's + 82 `l`); every invalid one is refused with the error the table maps it to, in both data modes. +*/ +void bip_lists() { + for (test::valid_string const& entry : test::bip173_valid_strings) { + expect_valid_string(formats::bech32, formats::bech32m, entry); + } + for (test::valid_string const& entry : test::bip350_valid_strings) { + expect_valid_string(formats::bech32m, formats::bech32, entry); + } + for (test::invalid_string const& entry : test::bip173_invalid_strings) { + expect_refusal(formats::bech32, entry.text, entry.bytes_error); + expect_refusal(formats::bech32.words(), entry.text, entry.words_error); + } + for (test::invalid_string const& entry : test::bip350_invalid_strings) { + expect_refusal(formats::bech32m, entry.text, entry.bytes_error); + expect_refusal(formats::bech32m.words(), entry.text, entry.words_error); + } + // A valid string in a format of its part, and of another: either case of the part. + expect_decodes_back(formats::bech32("abcdef"), "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw"); + expect_decodes_back(formats::bech32("ABCDEF"), "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw"); + expect_decodes_back(formats::bech32m("a"), "A1LQFN3A"); + expect_refusal(formats::bech32("abcde"), "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw", + codecs::error::invalid_prefix); + expect_refusal(formats::bech32("abcdeg"), "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw", + codecs::error::invalid_prefix); +} + +/** + The spec's "A Nostr public key": 32 bytes encoded with bech32("npub") are a text of 63 + characters that starts with "npub1" and decodes back with the same format, in every form. +*/ +void a_nostr_public_key() { + std::array const key = test::digest_bytes(); + auto const npub = codecs::encode(formats::bech32("npub"), key); + BOOST_TEST(npub.has_value() && npub->size() == 63 && npub->view().starts_with("npub1")); + BOOST_TEST(npub->view() == test::reference_bech32_encode("npub", key, false, false)); + auto const back = codecs::decode(formats::bech32("npub"), npub.value()); + BOOST_TEST(back.has_value() && std::ranges::equal(back->view(), key)); + auto const typed = + codecs::decode>(formats::bech32("npub"), npub->view()); + BOOST_TEST(typed.has_value() && typed.value() == key); + auto const secret_key = + codecs::decode>(formats::bech32("npub"), npub->view()); + BOOST_TEST(secret_key.has_value() && std::ranges::equal(secret_key->bytes(), key)); + auto const short_array = + codecs::decode>(formats::bech32("npub"), npub->view()); + BOOST_TEST(!short_array.has_value() && short_array.error() == codecs::error::invalid_length); + auto const into_bytes = codecs::decode>(formats::bech32, npub->view()); + BOOST_TEST(into_bytes.has_value() && std::ranges::equal(into_bytes->view(), key)); + auto const too_small = codecs::decode>(formats::bech32, npub->view()); + BOOST_TEST(!too_small.has_value() && too_small.error() == codecs::error::output_too_small); + // A buffer encode: the exact size, and one less refused with nothing written. + std::array buffer{}; + buffer.fill('~'); + auto const short_buffer = + codecs::encode(formats::bech32("npub"), key, std::span{buffer}.first(62)); + BOOST_TEST(!short_buffer.has_value() && + short_buffer.error() == codecs::error::output_too_small); + BOOST_TEST(std::ranges::all_of(buffer, [](char character) { return character == '~'; })); + auto const written = codecs::encode(formats::bech32("npub"), key, std::span{buffer}); + BOOST_TEST(written.has_value() && written.value() == 63 && buffer[63] == '~'); + BOOST_TEST(std::string_view(buffer.data(), 63) == npub->view()); + // A secret input is a secret operation: its result is a secret_text. + webcpp::secure::secret<32> secret_input; + std::ranges::copy(key, secret_input.writable().begin()); + auto const secret_text = codecs::encode(formats::bech32("npub"), secret_input); + static_assert( + std::is_same_v> const>); + BOOST_TEST(secret_text.has_value() && secret_text->view() == npub->view()); +} + +/** + The typed decode into the parts with no human-readable part in the format accepts any and gives + the part and the data, in place, with no allocation counted (R12). +*/ +void the_parts_with_no_allocation() { + std::array const key = test::digest_bytes(); + auto const encoded = codecs::encode(formats::bech32("npub"), key); + std::string const text{encoded.value().view()}; + bool volatile verdict = false; + test::expect_no_allocation("decode(formats::bech32, text)", [&] { + auto const parts = codecs::decode( + formats::bech32, std::string_view{text.data(), 63}); + auto const words = codecs::decode( + formats::bech32.words(), std::string_view{text.data(), 63}); + verdict = parts.has_value() && parts->human_readable_part.view() == "npub" && + std::ranges::equal(parts->data.view(), key) && words.has_value() && + words->data.size() == 52; + }); + BOOST_TEST(verdict); + // Upper case: the part comes in small letters. + auto const raised = codecs::decode( + formats::bech32, test::ascii_upper(std::string_view{text.data(), 63})); + BOOST_TEST(raised.has_value() && raised->human_readable_part.view() == "npub"); + // Two parts compare by content. + auto const again = codecs::decode( + formats::bech32, std::string_view{text.data(), 63}); + BOOST_TEST(raised.value() == again.value()); +} + +/** The version word of a scriptPubKey: `OP_0` is 0, `OP_1` to `OP_16` (0x51 to 0x60) 1 to 16. */ +std::uint8_t version_of(std::span script) { + return script[0] == 0 ? std::uint8_t{0} : static_cast(script[0] - 0x50U); +} + +/** + One segwit address in words mode, in the variant `format`: the version word and the program's + words give the address in small letters, and its decode gives the words back, the program through + bytes_from_words. +*/ +template +void expect_segwit_address(Format const& format, test::segwit_address const& entry) { + std::vector const script = from_hex(entry.script); + std::span const program = std::span{script}.subspan(2); + BOOST_TEST_EQ(program.size(), script[1]); + std::vector words{version_of(script)}; + formats::append_words_from_bytes(words, program); + std::string const prefix = test::ascii_lower(part_of(entry.address)); + auto const in_words = format(prefix).words(); + auto const encoded = codecs::encode(in_words, words); + BOOST_TEST(encoded.has_value() && encoded.value() == test::ascii_lower(entry.address)); + auto const decoded = codecs::decode(in_words, entry.address); + BOOST_TEST(decoded.has_value() && decoded.value() == words); + std::array program_bytes{}; + auto const regrouped = + formats::bytes_from_words(std::span{decoded.value()}.subspan(1), std::span{program_bytes}); + BOOST_TEST(regrouped.has_value() && regrouped.value() == program.size()); + BOOST_TEST(std::ranges::equal(std::span{program_bytes}.first(program.size()), program)); +} + +/** + The spec's "Segwit addresses in words mode": each valid address of BIP-173 of version 0 with + bech32, each of BIP-350 with bech32 for version 0 and bech32m above; BIP-173's addresses of + version 1 and above, written before BIP-350, with bech32 too, since codecs applies none of + segwit's rules; and a word of 32 refused on encode with invalid_character, nothing written. +*/ +void segwit_addresses_in_words_mode() { + for (test::segwit_address const& entry : test::bip173_segwit_addresses) { + expect_segwit_address(formats::bech32, entry); + } + for (test::segwit_address const& entry : test::bip350_segwit_addresses) { + if (from_hex(entry.script)[0] == 0) { + expect_segwit_address(formats::bech32, entry); + } else { + expect_segwit_address(formats::bech32m, entry); + } + } + std::vector const bad_words{0, 1, 2, 32, 4}; + std::array buffer{}; + buffer.fill('~'); + auto const refused = + codecs::encode(formats::bech32("bc").words(), bad_words, std::span{buffer}); + BOOST_TEST(!refused.has_value() && refused.error() == codecs::error::invalid_character); + BOOST_TEST(std::ranges::all_of(buffer, [](char character) { return character == '~'; })); + auto const defaulted = codecs::encode(formats::bech32m("bc").words(), bad_words); + BOOST_TEST(!defaulted.has_value() && defaulted.error() == codecs::error::invalid_character); + std::vector const top_word{255}; + BOOST_TEST(codecs::encode(formats::bech32("bc").words(), top_word).error() == + codecs::error::invalid_character); + // A word of 31 is the last valid one. + std::vector const last_word{31}; + BOOST_TEST(codecs::encode(formats::bech32("bc").words(), last_word).has_value()); +} + +/** + The spec's "A version as a byte is another text": BIP-350's Taproot address from its program in + words mode, the word 1 then the program's words, and a different text from the byte 0x01 then the + program in bytes mode, which decodes back to those 33 bytes and not to the words. +*/ +void a_version_as_a_byte_is_another_text() { + std::string_view const address = + "bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0"; + std::vector const program = + from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"); + std::vector words{1}; + formats::append_words_from_bytes(words, program); + auto const in_words = codecs::encode(formats::bech32m("bc").words(), words); + BOOST_TEST(in_words.has_value() && in_words.value() == address); + std::vector version_byte{0x01}; + version_byte.insert(version_byte.end(), program.begin(), program.end()); + auto const in_bytes = codecs::encode(formats::bech32m("bc"), version_byte); + BOOST_TEST(in_bytes.has_value() && in_bytes.value() != address); + BOOST_TEST(in_bytes.value() == test::reference_bech32_encode("bc", version_byte, true, false)); + auto const bytes_back = codecs::decode(formats::bech32m("bc"), in_bytes.value()); + BOOST_TEST(bytes_back.has_value() && bytes_back.value() == version_byte); + // The address in bytes mode: its 53 words of five bits regroup into 33 bytes that are not the + // version byte and the program. + auto const address_bytes = codecs::decode(formats::bech32m("bc"), address); + BOOST_TEST(address_bytes.has_value() && address_bytes->size() == 33 && + address_bytes.value() != version_byte); +} + +/** + The word helpers: append_words_from_bytes is BIP-173's convertbits from 8 to 5 with zero padding; + bytes_from_words regroups 8 words into 5 bytes, 2 words (2 padding bits, zero) into 1, refuses 3 + words (7 padding bits) and a non-zero padding bit with invalid_padding, a value of 32 with + invalid_character (the lowest), and an output one byte short with output_too_small, writing + nothing on an error. +*/ +void the_word_helpers() { + std::vector words; + std::array const five{0xff, 0x00, 0xa5, 0x5a, 0x01}; + formats::append_words_from_bytes(words, five); + BOOST_TEST_EQ(words.size(), 8U); + std::array back{}; + auto const regrouped = formats::bytes_from_words(words, back); + BOOST_TEST(regrouped.has_value() && regrouped.value() == 5 && back == five); + std::vector one_byte; + formats::append_words_from_bytes(one_byte, std::array{0xa7}); + BOOST_TEST((one_byte == std::vector{20, 28})); + std::array output{}; + output.fill(0x5a); + auto const from_two = formats::bytes_from_words(one_byte, output); + BOOST_TEST(from_two.has_value() && from_two.value() == 1 && output[0] == 0xa7 && + output[1] == 0x5a); + auto const untouched = [&] { + return std::ranges::all_of(output, [](std::uint8_t byte) { return byte == 0x5a; }); + }; + output.fill(0x5a); + std::array const three_words{1, 2, 0}; + BOOST_TEST(formats::bytes_from_words(three_words, output).error() == + codecs::error::invalid_padding); + std::array const set_padding{20, 29}; + BOOST_TEST(formats::bytes_from_words(set_padding, output).error() == + codecs::error::invalid_padding); + std::array const value_of_32{20, 32}; + BOOST_TEST(formats::bytes_from_words(value_of_32, output).error() == + codecs::error::invalid_character); + // Two faults: the value above 31 comes first. + std::array const both{32, 2, 1}; + BOOST_TEST(formats::bytes_from_words(both, output).error() == codecs::error::invalid_character); + BOOST_TEST(formats::bytes_from_words(words, std::span{output}).error() == + codecs::error::output_too_small); + BOOST_TEST(untouched()); + auto const nothing = formats::bytes_from_words({}, std::span{}); + BOOST_TEST(nothing.has_value() && nothing.value() == 0); + std::vector none; + formats::append_words_from_bytes(none, std::span{}); + BOOST_TEST(none.empty()); + // Every length from 0 to 40 bytes goes there and back. + for (std::size_t size = 0; size <= 40; ++size) { + std::vector const bytes = test::random_bytes(size); + std::vector grouped; + formats::append_words_from_bytes(grouped, bytes); + BOOST_TEST_EQ(grouped.size(), ((size * 8) + 4) / 5); + std::vector regrouped_bytes(size); + auto const count = formats::bytes_from_words(grouped, regrouped_bytes); + BOOST_TEST(count.has_value() && count.value() == size && regrouped_bytes == bytes); + } +} + +/** + The spec's "A Lightning invoice through a larger instance", one-shot: BOLT 11's first example + invoice, 304 characters, decoded by basic_bech32("lnbc").words() to its words, the + first seven reading the example's timestamp, and by formats::bech32("lnbc").words(), whose 90 + characters it passes, refused with input_too_long in every form. +*/ +void a_lightning_invoice_through_a_larger_instance() { + std::string_view const invoice = test::bolt11_donation_invoice; + BOOST_TEST_EQ(invoice.size(), 304U); + auto const lightning = lightning_t{}("lnbc").words(); + auto const words = codecs::decode(lightning, invoice); + BOOST_TEST(words.has_value() && words->size() == 304 - 5 - 6); + unsigned long long timestamp = 0; + for (std::size_t index = 0; index < 7 && words.has_value(); ++index) { + timestamp = (timestamp * 32) + words.value()[index]; + } + BOOST_TEST_EQ(timestamp, test::bolt11_donation_timestamp); + auto const parts = codecs::decode(lightning, invoice); + BOOST_TEST(parts.has_value() && parts->human_readable_part.view() == "lnbc" && + std::ranges::equal(parts->data.view(), words.value())); + // Encoded back from its words, it is the invoice. + auto const encoded = codecs::encode(lightning, words.value()); + BOOST_TEST(encoded.has_value() && encoded.value() == invoice); + // The 90 characters of formats::bech32: input_too_long, before the text is read. + expect_refusal(formats::bech32("lnbc").words(), invoice, codecs::error::input_too_long); + expect_refusal(formats::bech32.words(), invoice, codecs::error::input_too_long); + BOOST_TEST(codecs::encode(formats::bech32("lnbc").words(), words.value()).error() == + codecs::error::input_too_long); +} + +/** + Every error of the format, one input each, and inputs of two faults giving the lowest value + (B23): the data's characters, the data's length, the padding, the checksum, the part (none, + empty, too long, out of range, another than the format's), mixed case, a text past the maximum. +*/ +void every_error_and_the_lowest() { + constexpr auto character = codecs::error::invalid_character; + constexpr auto length = codecs::error::invalid_length; + constexpr auto padding = codecs::error::invalid_padding; + constexpr auto checksum = codecs::error::checksum_mismatch; + constexpr auto prefix = codecs::error::invalid_prefix; + constexpr auto mixed = codecs::error::mixed_case; + expect_refusal(formats::bech32, "a1b2uel5l", character); + expect_refusal(formats::bech32, "a1i2uel5l", character); + expect_refusal(formats::bech32, "a1o2uel5l", character); + expect_refusal(formats::bech32, "a12uel5", length); + expect_refusal(formats::bech32, "a1", length); + // An empty part and no data: the length, the lower value, wins. + expect_refusal(formats::bech32, "1", length); + expect_refusal(formats::bech32, "", prefix); + expect_refusal(formats::bech32, "a12uel5m", checksum); + expect_refusal(formats::bech32, "b12uel5l", checksum); + expect_refusal(formats::bech32, "A12uel5l", mixed); + expect_refusal(formats::bech32, "a12UEL5L", mixed); + expect_refusal(formats::bech32("b"), "a12uel5l", prefix); + expect_refusal(formats::bech32("aa"), "a12uel5l", prefix); + expect_refusal(formats::bech32, std::string(91, 'q'), codecs::error::input_too_long); + // Over bytes: one word is 5 bits, no byte and more than 4 padding bits; two words are a byte + // and 2 padding bits, which must be zero. The texts are made with valid checksums. + std::array const one_word{3}; + std::string const one = test::reference_bech32_encode("a", one_word, false, true); + expect_refusal(formats::bech32, one, padding); + expect_decodes_back(formats::bech32.words(), one); + std::array const set_bit{20, 29}; + std::string const set = test::reference_bech32_encode("a", set_bit, false, true); + expect_refusal(formats::bech32, set, padding); + expect_decodes_back(formats::bech32.words(), set); + // Two faults and more: the lowest value. + expect_refusal(formats::bech32, "a1b", character); + expect_refusal(formats::bech32, "A1b2UEL5L", character); + expect_refusal(formats::bech32("x"), "A12uel5m", checksum); + expect_refusal(formats::bech32("x"), "A12uel5l", prefix); + expect_refusal(formats::bech32, "A12uel5", length); + expect_refusal(formats::bech32, "1qzzfhee", padding); + expect_refusal(formats::bech32.words(), "1qzzfhee", prefix); + std::string const set_and_mixed = test::ascii_upper(set.substr(0, 3)) + set.substr(3); + expect_refusal(formats::bech32, set_and_mixed, padding); + std::string set_and_checksum = set; + set_and_checksum.back() = set_and_checksum.back() == 'q' ? 'p' : 'q'; + expect_refusal(formats::bech32, set_and_checksum, padding); + expect_refusal(formats::bech32.words(), set_and_checksum, checksum); + // A part of 83 characters is the longest; 84 cannot be one, whatever the text's length. + std::string const part_83(83, 'a'); + std::string const longest = test::reference_bech32_encode(part_83, {}, false, false); + BOOST_TEST_EQ(longest.size(), 90U); + expect_decodes_back(formats::bech32, longest); + std::string const text_of_84 = test::reference_bech32_encode(part_84, {}, false, false); + expect_refusal(lightning_t{}, text_of_84, prefix); +} + +/** + The spec's "A configuration fault wins", one-shot: a text with an invalid character and a bad + checksum, decoded with formats::bech32 configured with a part of 84 characters, is invalid_prefix + in every form, before any data; so is a part with a character outside 33 to 126. Encoding with no + part is invalid_prefix too, and its size 0. +*/ +void a_configuration_fault_wins() { + auto const overflowed = formats::bech32(part_84); + BOOST_TEST(overflowed.human_readable_part().empty()); + for (std::string_view const text : {"x1b4n0q5v", "a12uel5m", "a12uel5l", ""}) { + BOOST_TEST(codecs::decode(overflowed, text).error() == codecs::error::invalid_prefix); + std::array buffer{}; + BOOST_TEST(codecs::decode(overflowed, text, std::span{buffer}).error() == + codecs::error::invalid_prefix); + BOOST_TEST(codecs::decode(overflowed, text).error() == + codecs::error::invalid_prefix); + BOOST_TEST(codecs::decode(formats::bech32m("a\x7f"), text).error() == + codecs::error::invalid_prefix); + BOOST_TEST( + codecs::decode(formats::bech32(std::string_view{"\0", 1}).words(), text).error() == + codecs::error::invalid_prefix); + } + std::string const too_long(200, 'q'); + BOOST_TEST(codecs::decode(overflowed, too_long).error() == codecs::error::invalid_prefix); + std::array const bytes{1, 2, 3, 4}; + BOOST_TEST(codecs::encode(overflowed, bytes).error() == codecs::error::invalid_prefix); + BOOST_TEST(codecs::encode(formats::bech32, bytes).error() == codecs::error::invalid_prefix); + BOOST_TEST(codecs::encode(formats::bech32m.words(), std::vector{}).error() == + codecs::error::invalid_prefix); + std::array buffer{}; + BOOST_TEST(codecs::encode(formats::bech32, bytes, std::span{buffer}).error() == + codecs::error::invalid_prefix); + BOOST_TEST_EQ(codecs::encoded_size(formats::bech32, bytes), 0U); + BOOST_TEST_EQ(codecs::encoded_size(overflowed, bytes), 0U); + // A text past the maximum through a buffer: input_too_long, nothing written. + std::array const long_input{}; + BOOST_TEST(codecs::encode(formats::bech32("bc"), long_input).error() == + codecs::error::input_too_long); + std::array const fits_short_part{}; + BOOST_TEST(codecs::encode(formats::bech32("a"), fits_short_part).has_value()); + // 51 bytes are 82 characters: 90 with "a", 91 with "ab"; the fixed default result of 90 is + // not too small, the text too long. + BOOST_TEST(codecs::encode(formats::bech32("ab"), fits_short_part).error() == + codecs::error::input_too_long); + // Refused for its size: SIZE_MAX, the one rule of every size. + BOOST_TEST_EQ(codecs::encoded_size(formats::bech32("ab"), fits_short_part), + std::numeric_limits::max()); + std::array wide{}; + wide.fill('~'); + BOOST_TEST(codecs::encode(formats::bech32("ab"), fits_short_part, std::span{wide}).error() == + codecs::error::input_too_long); + BOOST_TEST(std::ranges::all_of(wide, [](char c) { return c == '~'; })); +} + +/** The plain reading of `text`, compared with the library's in a configuration. */ +template +void expect_the_reference_reading(Format const& format, std::string_view text) { + auto const reference = + test::reference_bech32_decode(text, format.human_readable_part(), is_bech32m, + is_words, Format::maximum_length); + auto const size = codecs::codec::decoded_size(format, text); + std::array buffer{}; + auto const written = codecs::decode(format, text, std::span{buffer}); + if (reference.fault) { + BOOST_TEST(!size.has_value() && size.error() == *reference.fault); + BOOST_TEST(!written.has_value() && written.error() == *reference.fault); + return; + } + BOOST_TEST(size.has_value() && size.value() == reference.data.size()); + BOOST_TEST(written.has_value() && written.value() == reference.data.size()); + BOOST_TEST(std::ranges::equal(std::span{buffer}.first(reference.data.size()), reference.data)); +} + +/** Runs @ref expect_the_reference_reading in each variant and data mode, and with a part. */ +void expect_the_reference_reading_everywhere(std::string_view text) { + expect_the_reference_reading(formats::bech32, text); + expect_the_reference_reading(formats::bech32.words(), text); + expect_the_reference_reading(formats::bech32m, text); + expect_the_reference_reading(formats::bech32("abcdef"), text); +} + +/** + Review Focus 1: each of the 256 byte values as a character, `char` signed, at every place of a + text: in its human-readable part (where a `1` moves the separator), at the separator, in its data + and in its checksum, and appended; the verdict and the data equal the plain reference's in each + variant and mode. NUL, 0x80 to 0xff, the characters one past each range (`/`, `:`, `\@`, `[`, + the backquote, `{`) and the excluded `1`, `b`, `i` and `o` are among them. +*/ +void every_byte_value_as_a_character() { + for (std::string_view const base : { + "a12uel5l", + "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw", + "?1ezyfcl", + "abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx", + }) { + for (std::size_t place = 0; place <= base.size(); ++place) { + for (unsigned value = 0; value < 256; ++value) { + auto const replacement = static_cast(static_cast(value)); + std::string text{base}; + if (place == base.size()) { + text.push_back(replacement); + } else { + text[place] = replacement; + } + expect_the_reference_reading_everywhere(text); + } + } + } + // The arithmetic alone: every byte against the plain table, either case. + for (unsigned value = 0; value < 256; ++value) { + auto const character = static_cast(static_cast(value)); + std::size_t const at = test::bech32_characters.find(test::ascii_lower({&character, 1})[0]); + detail::bech32_reading const reading = detail::bech32_value(character); + bool const in_alphabet = at != std::string_view::npos && value != 0; + BOOST_TEST_EQ(reading.invalid_mask == 0, in_alphabet); + BOOST_TEST_EQ(reading.value, in_alphabet ? static_cast(at) : 0U); + } + for (std::uint32_t value = 0; value < 32; ++value) { + BOOST_TEST_EQ(detail::bech32_character(value), test::bech32_characters[value]); + } +} + +/** + Texts near the valid ones, against the plain reference in every configuration: the texts of + random parts and data in both variants and modes, with up to three characters replaced by any + byte, a character of the alphabet, a `1` or a case change, and cut or lengthened. +*/ +void texts_near_the_valid_ones() { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): a fixed seed + std::mt19937_64 generator{20261127}; + for (int iteration = 0; iteration < 3000; ++iteration) { + std::string part; + for (std::size_t size = 1 + (generator() % 6); size > 0; --size) { + part.push_back(static_cast(33 + (generator() % 94))); + } + bool const words = (generator() & 1U) != 0; + bool const bech32m = (generator() & 1U) != 0; + std::vector data(generator() % 40); + for (std::uint8_t& element : data) { + element = static_cast(generator() & (words ? 31U : 255U)); + } + std::string text = test::reference_bech32_encode(part, data, bech32m, words); + if (generator() % 3 == 0) { + text = test::ascii_upper(text); + } + for (std::size_t edits = generator() % 4; edits > 0 && !text.empty(); --edits) { + std::size_t const at = generator() % text.size(); + switch (generator() % 4) { + case 0: text[at] = static_cast(generator()); break; + case 1: text[at] = test::bech32_characters[generator() % 32]; break; + case 2: text[at] = '1'; break; + default: + text[at] = static_cast(static_cast(text[at]) ^ 0x20U); + break; + } + } + if (generator() % 6 == 0 && !text.empty()) { + text.resize(text.size() - 1 - (generator() % std::min(3, text.size()))); + } else if (generator() % 8 == 0) { + text.append(1 + (generator() % 3), 'q'); + } + expect_the_reference_reading_everywhere(text); + } +} + +/** + Review Focus 3, the encodes: no data give the human-readable part, `1` and the checksum, in + every form, in both variants and modes; the decodes: that text gives no data, and an empty text, + which has no part, is invalid_prefix in every form. +*/ +void empty_input_in_every_form() { + std::array const nothing{}; + std::string const empty_text = test::reference_bech32_encode("bc", {}, false, false); + BOOST_TEST_EQ(empty_text.size(), 9U); + auto const fixed = codecs::encode(formats::bech32("bc"), nothing); + BOOST_TEST(fixed.has_value() && fixed->view() == empty_text); + auto const heap = codecs::encode(formats::bech32("bc"), std::vector{}); + BOOST_TEST(heap.has_value() && heap.value() == empty_text); + auto const words = codecs::encode(formats::bech32("bc").words(), std::string{}); + BOOST_TEST(words.has_value() && words.value() == empty_text); + auto const in_m = codecs::encode(formats::bech32m("bc"), std::string{}); + BOOST_TEST(in_m.has_value() && + in_m.value() == test::reference_bech32_encode("bc", {}, true, false)); + std::array buffer{}; + auto const buffer_written = codecs::encode(formats::bech32("bc"), nothing, std::span{buffer}); + BOOST_TEST(buffer_written.has_value() && buffer_written.value() == 9 && + std::string_view(buffer.data(), 9) == empty_text); + BOOST_TEST(codecs::encode(formats::bech32("bc"), nothing, std::span{}).error() == + codecs::error::output_too_small); + auto const returned = codecs::encode(formats::bech32("bc"), nothing, tokens::return_string); + BOOST_TEST(returned.has_value() && returned.value() == empty_text); + auto const secret_empty = codecs::encode(formats::bech32("bc"), nothing, tokens::secret); + BOOST_TEST(secret_empty.has_value() && secret_empty->view() == empty_text); + BOOST_TEST_EQ(codecs::encoded_size(formats::bech32("bc"), nothing), 9U); + + auto const decoded = codecs::decode(formats::bech32("bc"), empty_text); + BOOST_TEST(decoded.has_value() && decoded->empty()); + auto const buffer_decoded = + codecs::decode(formats::bech32, empty_text, std::span{}); + BOOST_TEST(buffer_decoded.has_value() && buffer_decoded.value() == 0); + auto const parts = codecs::decode(formats::bech32, empty_text); + BOOST_TEST(parts.has_value() && parts->human_readable_part.view() == "bc" && + parts->data.size() == 0); + auto const typed_array = + codecs::decode>(formats::bech32, empty_text); + BOOST_TEST(typed_array.has_value()); + expect_refusal(formats::bech32, "", codecs::error::invalid_prefix); + expect_refusal(formats::bech32m.words(), "", codecs::error::invalid_prefix); + BOOST_TEST(codecs::decode(formats::bech32, codecs::text<0>{}).error() == + codecs::error::invalid_prefix); + BOOST_TEST_EQ(codecs::max_decoded_size(formats::bech32, std::string_view{}), 0U); +} + +/** A run-time instance of another maximum: bech32m of 20 characters, the bounds of its own. */ +void another_maximum_length() { + using short_t = formats::basic_bech32; + static_assert(codecs::codec::max_encoded_size(7) == 20); + static_assert(codecs::codec::max_encoded_size(8) == size_maximum); + std::array const seven{1, 2, 3, 4, 5, 6, 7}; + auto const text = codecs::encode(short_t{}("a"), seven); + BOOST_TEST(text.has_value() && text->size() == 20); + BOOST_TEST(codecs::encode(short_t{}("ab"), seven).error() == codecs::error::input_too_long); + auto const back = codecs::decode(short_t{}, text.value()); + BOOST_TEST(back.has_value() && std::ranges::equal(back->view(), seven)); + std::string const longer = test::reference_bech32_encode("abc", seven, true, false); + BOOST_TEST(codecs::decode(short_t{}, longer).error() == codecs::error::input_too_long); + BOOST_TEST(codecs::decode(formats::bech32m, longer).has_value()); +} + +/** + bech32_parts is public: a secret payload, a Nostr nsec, goes to a secret type with the + human-readable part in the format, or through the secret stream decoder, which gives the part it + read. +*/ +void a_secret_key_into_a_secret_type() { + std::array key{}; + for (std::size_t index = 0; index < key.size(); ++index) { + key[index] = static_cast((index * 37U) + 5U); + } + auto const nsec = codecs::encode(formats::bech32("nsec"), key); + BOOST_TEST(nsec.has_value()); + auto const secret = + codecs::decode>(formats::bech32("nsec"), nsec->view()); + BOOST_TEST(secret.has_value() && std::ranges::equal(secret->view(), key)); + BOOST_TEST( + codecs::decode>(formats::bech32("npub"), nsec->view()).error() == + codecs::error::invalid_prefix); + auto decoder = codecs::decoder(formats::bech32, codecs::secret_operation); + auto const characters = nsec->view(); + BOOST_TEST(decoder.send(std::span{characters.data(), characters.size()}).has_value()); + BOOST_TEST(decoder.flush().has_value()); + std::array received{}; + auto const step = decoder.receive(received); + BOOST_TEST(step.has_value() && step->count == 32); + BOOST_TEST(received == key); + BOOST_TEST(decoder.human_readable_part() == "nsec"); +} + +} // namespace + +int main() { + bip_lists(); + a_secret_key_into_a_secret_type(); + a_nostr_public_key(); + the_parts_with_no_allocation(); + segwit_addresses_in_words_mode(); + a_version_as_a_byte_is_another_text(); + the_word_helpers(); + a_lightning_invoice_through_a_larger_instance(); + every_error_and_the_lowest(); + a_configuration_fault_wins(); + every_byte_value_as_a_character(); + texts_near_the_valid_ones(); + empty_input_in_every_form(); + another_maximum_length(); + return boost::report_errors(); +} diff --git a/test/bech32_vectors.hpp b/test/bech32_vectors.hpp new file mode 100644 index 0000000..5510aab --- /dev/null +++ b/test/bech32_vectors.hpp @@ -0,0 +1,402 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The test vectors of bech32 and bech32m, each copied as its source writes it (ruling R8: no file +// of third_party/libs holds a BOLT 11 invoice, and the BIPs' lists are read here as the tests' +// table): BIP-173's and BIP-350's lists of valid and invalid strings, with each invalid string's +// reason as the BIP gives it and the error codecs reports for it, in bytes mode and in words mode, +// and their valid segwit addresses with the scriptPubKey each translates to, from +// third_party/libs/bips at 927b6de (bip-0173.mediawiki, "Test vectors"; bip-0350.mediawiki, "Test +// vectors for Bech32m" and "Test vectors for v0-v16 native segregated witness addresses"); and +// BOLT 11's first example invoice, from lightning/bolts' 11-payment-encoding.md at 1914628, +// "Examples". An invalid string's error is the lowest value of its faults (B23): an empty +// human-readable part is invalid_prefix, but with bytes the data of "1pzry9x0s0muk" also leave +// more than 4 padding bits, invalid_padding, which is lower; in words mode there is no padding to +// check. A string with no separator has no human-readable part: invalid_prefix. + +#ifndef WEBCPP_CODECS_TEST_BECH32_VECTORS_HPP +#define WEBCPP_CODECS_TEST_BECH32_VECTORS_HPP + +#include + +#include +#include +#include + +namespace webcpp::codecs::test { + +/** A valid string of a BIP's list, and what its data give over bytes. */ +struct valid_string { + /** The string. */ + std::string_view text; + /** std::nullopt when its data regroup into bytes, else the error: BIP-350's 82 `l`. */ + std::optional bytes_fault; +}; + +/** An invalid string of a BIP's list, its reason, and the error codecs reports for it. */ +struct invalid_string { + /** The string. */ + std::string_view text; + /** Why it is invalid, as the BIP says. */ + std::string_view reason; + /** The error in bytes mode. */ + codecs::error bytes_error; + /** The error in words mode. */ + codecs::error words_error; +}; + +/** A valid segwit address and the scriptPubKey it translates to, in hex. */ +struct segwit_address { + /** The address. */ + std::string_view address; + /** The scriptPubKey: the version's opcode, the program's size, the program. */ + std::string_view script; +}; + +/** BIP-173's valid strings, of bech32. */ +inline constexpr std::array bip173_valid_strings{ + valid_string{ + .text = "A12UEL5L", + .bytes_fault = std::nullopt, + }, + valid_string{ + .text = "a12uel5l", + .bytes_fault = std::nullopt, + }, + valid_string{ + .text = "an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcha" + "ractersbio1tt5tgs", + .bytes_fault = std::nullopt, + }, + valid_string{ + .text = "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw", + .bytes_fault = std::nullopt, + }, + valid_string{ + .text = "11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq" + "qqqqqqqqqqqc8247j", + .bytes_fault = std::nullopt, + }, + valid_string{ + .text = "split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w", + .bytes_fault = std::nullopt, + }, + valid_string{ + .text = "?1ezyfcl", + .bytes_fault = std::nullopt, + }, +}; + +/** BIP-350's valid strings, of bech32m. */ +inline constexpr std::array bip350_valid_strings{ + valid_string{ + .text = "A1LQFN3A", + .bytes_fault = std::nullopt, + }, + valid_string{ + .text = "a1lqfn3a", + .bytes_fault = std::nullopt, + }, + valid_string{ + .text = "an83characterlonghumanreadablepartthatcontainsthetheexcludedcharactersbio" + "andnumber11sg7hg6", + .bytes_fault = std::nullopt, + }, + valid_string{ + .text = "abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx", + .bytes_fault = std::nullopt, + }, + valid_string{ + .text = "11lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll" + "lllllllllllludsr8", + .bytes_fault = codecs::error::invalid_padding, + }, + valid_string{ + .text = "split1checkupstagehandshakeupstreamerranterredcaperredlc445v", + .bytes_fault = std::nullopt, + }, + valid_string{ + .text = "?1v759aa", + .bytes_fault = std::nullopt, + }, +}; + +/** BIP-173's invalid strings, of bech32. */ +inline constexpr std::array bip173_invalid_strings{ + invalid_string{ + .text = "\x20" + "1nwldj5", + .reason = "HRP character out of range", + .bytes_error = codecs::error::invalid_prefix, + .words_error = codecs::error::invalid_prefix, + }, + invalid_string{ + .text = "\x7f" + "1axkwrx", + .reason = "HRP character out of range", + .bytes_error = codecs::error::invalid_prefix, + .words_error = codecs::error::invalid_prefix, + }, + invalid_string{ + .text = "\x80" + "1eym55h", + .reason = "HRP character out of range", + .bytes_error = codecs::error::invalid_prefix, + .words_error = codecs::error::invalid_prefix, + }, + invalid_string{ + .text = "an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcluded" + "charactersbio1569pvx", + .reason = "overall max length exceeded", + .bytes_error = codecs::error::input_too_long, + .words_error = codecs::error::input_too_long, + }, + invalid_string{ + .text = "pzry9x0s0muk", + .reason = "No separator character", + .bytes_error = codecs::error::invalid_prefix, + .words_error = codecs::error::invalid_prefix, + }, + invalid_string{ + .text = "1pzry9x0s0muk", + .reason = "Empty HRP", + .bytes_error = codecs::error::invalid_padding, + .words_error = codecs::error::invalid_prefix, + }, + invalid_string{ + .text = "x1b4n0q5v", + .reason = "Invalid data character", + .bytes_error = codecs::error::invalid_character, + .words_error = codecs::error::invalid_character, + }, + invalid_string{ + .text = "li1dgmt3", + .reason = "Too short checksum", + .bytes_error = codecs::error::invalid_length, + .words_error = codecs::error::invalid_length, + }, + invalid_string{ + .text = "de1lg7wt" + "\xff", + .reason = "Invalid character in checksum", + .bytes_error = codecs::error::invalid_character, + .words_error = codecs::error::invalid_character, + }, + invalid_string{ + .text = "A1G7SGD8", + .reason = "checksum calculated with uppercase form of HRP", + .bytes_error = codecs::error::checksum_mismatch, + .words_error = codecs::error::checksum_mismatch, + }, + invalid_string{ + .text = "10a06t8", + .reason = "empty HRP", + .bytes_error = codecs::error::invalid_prefix, + .words_error = codecs::error::invalid_prefix, + }, + invalid_string{ + .text = "1qzzfhee", + .reason = "empty HRP", + .bytes_error = codecs::error::invalid_padding, + .words_error = codecs::error::invalid_prefix, + }, + // BIP-173's invalid segwit addresses that are faults of the bech32 text itself; the others + // (an unknown witness version, a program of another length, more than 4 padding bits in the + // program, empty data) are valid bech32 texts, whose fault is segwit's. Over bytes the data of + // the first also leave more than 4 padding bits: invalid_padding, the lowest value (B23). + invalid_string{ + .text = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t5", + .reason = "Invalid checksum", + .bytes_error = codecs::error::invalid_padding, + .words_error = codecs::error::checksum_mismatch, + }, + invalid_string{ + .text = "tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7", + .reason = "Mixed case", + .bytes_error = codecs::error::mixed_case, + .words_error = codecs::error::mixed_case, + }, +}; + +/** BIP-350's invalid strings, of bech32m. */ +inline constexpr std::array bip350_invalid_strings{ + invalid_string{ + .text = "\x20" + "1xj0phk", + .reason = "HRP character out of range", + .bytes_error = codecs::error::invalid_prefix, + .words_error = codecs::error::invalid_prefix, + }, + invalid_string{ + .text = "\x7f" + "1g6xzxy", + .reason = "HRP character out of range", + .bytes_error = codecs::error::invalid_prefix, + .words_error = codecs::error::invalid_prefix, + }, + invalid_string{ + .text = "\x80" + "1vctc34", + .reason = "HRP character out of range", + .bytes_error = codecs::error::invalid_prefix, + .words_error = codecs::error::invalid_prefix, + }, + invalid_string{ + .text = "an84characterslonghumanreadablepartthatcontainsthetheexcludedcharacters" + "bioandnumber11d6pts4", + .reason = "overall max length exceeded", + .bytes_error = codecs::error::input_too_long, + .words_error = codecs::error::input_too_long, + }, + invalid_string{ + .text = "qyrz8wqd2c9m", + .reason = "No separator character", + .bytes_error = codecs::error::invalid_prefix, + .words_error = codecs::error::invalid_prefix, + }, + invalid_string{ + .text = "1qyrz8wqd2c9m", + .reason = "Empty HRP", + .bytes_error = codecs::error::invalid_padding, + .words_error = codecs::error::invalid_prefix, + }, + invalid_string{ + .text = "y1b0jsk6g", + .reason = "Invalid data character", + .bytes_error = codecs::error::invalid_character, + .words_error = codecs::error::invalid_character, + }, + invalid_string{ + .text = "lt1igcx5c0", + .reason = "Invalid data character", + .bytes_error = codecs::error::invalid_character, + .words_error = codecs::error::invalid_character, + }, + invalid_string{ + .text = "in1muywd", + .reason = "Too short checksum", + .bytes_error = codecs::error::invalid_length, + .words_error = codecs::error::invalid_length, + }, + invalid_string{ + .text = "mm1crxm3i", + .reason = "Invalid character in checksum", + .bytes_error = codecs::error::invalid_character, + .words_error = codecs::error::invalid_character, + }, + invalid_string{ + .text = "au1s5cgom", + .reason = "Invalid character in checksum", + .bytes_error = codecs::error::invalid_character, + .words_error = codecs::error::invalid_character, + }, + invalid_string{ + .text = "M1VUXWEZ", + .reason = "checksum calculated with uppercase form of HRP", + .bytes_error = codecs::error::checksum_mismatch, + .words_error = codecs::error::checksum_mismatch, + }, + invalid_string{ + .text = "16plkw9", + .reason = "empty HRP", + .bytes_error = codecs::error::invalid_prefix, + .words_error = codecs::error::invalid_prefix, + }, + invalid_string{ + .text = "1p2gdwpf", + .reason = "empty HRP", + .bytes_error = codecs::error::invalid_padding, + .words_error = codecs::error::invalid_prefix, + }, +}; + +/** + BIP-173's valid segwit addresses: those of version 0 are segwit's in bech32; those of version 1 + and above were written in bech32 before BIP-350, and are still valid bech32 texts. +*/ +inline constexpr std::array bip173_segwit_addresses{ + segwit_address{ + .address = "BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4", + .script = "0014751e76e8199196d454941c45d1b3a323f1433bd6", + }, + segwit_address{ + .address = "tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7", + .script = "00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262", + }, + segwit_address{ + .address = "bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7k7grplx", + .script = + "5128751e76e8199196d454941c45d1b3a323f1433bd6751e76e8199196d454941c45d1b3a323f1433bd6", + }, + segwit_address{ + .address = "BC1SW50QA3JX3S", + .script = "6002751e", + }, + segwit_address{ + .address = "bc1zw508d6qejxtdg4y5r3zarvaryvg6kdaj", + .script = "5210751e76e8199196d454941c45d1b3a323", + }, + segwit_address{ + .address = "tb1qqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesrxh6hy", + .script = "0020000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433", + }, +}; + +/** BIP-350's valid segwit addresses: version 0 in bech32, version 1 and above in bech32m. */ +inline constexpr std::array bip350_segwit_addresses{ + segwit_address{ + .address = "BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4", + .script = "0014751e76e8199196d454941c45d1b3a323f1433bd6", + }, + segwit_address{ + .address = "tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7", + .script = "00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262", + }, + segwit_address{ + .address = "bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kt5nd6y", + .script = + "5128751e76e8199196d454941c45d1b3a323f1433bd6751e76e8199196d454941c45d1b3a323f1433bd6", + }, + segwit_address{ + .address = "BC1SW50QGDZ25J", + .script = "6002751e", + }, + segwit_address{ + .address = "bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs", + .script = "5210751e76e8199196d454941c45d1b3a323", + }, + segwit_address{ + .address = "tb1qqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesrxh6hy", + .script = "0020000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433", + }, + segwit_address{ + .address = "tb1pqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesf3hn0c", + .script = "5120000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433", + }, + segwit_address{ + .address = "bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0", + .script = "512079be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + }, +}; + +/** + BOLT 11's first example invoice, "Please make a donation of any amount using payment_hash + 0001...0102 to me \@03e7...d9ad" (the example's title, its hashes cut here): 304 characters, read + by an instance of more than 90. +*/ +inline constexpr std::string_view bolt11_donation_invoice = + "lnbc1pvjluezsp5zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygspp5qqqsyqcyq5rqwzqfqqqsyqcy" + "q5rqwzqfqqqsyqcyq5rqwzqfqypqdpl2pkx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6twvus8g6rfwvs8qun0dfjkxa" + "q9qrsgq357wnc5r2ueh7ck6q93dj32dlqnls087fxdwk8qakdyafkq3yap9us6v52vjjsrvywa6rt52cm9r9zqt8r2t7" + "mlcwspyetp5h2tztugp9lfyql"; + +/** The invoice's timestamp, its first seven words read as one number, as BOLT 11's breakdown says. + */ +inline constexpr unsigned long long bolt11_donation_timestamp = 1496314658ULL; + +} // namespace webcpp::codecs::test + +#endif diff --git a/test/buffered_test.cpp b/test/buffered_test.cpp new file mode 100644 index 0000000..0ff6557 --- /dev/null +++ b/test/buffered_test.cpp @@ -0,0 +1,566 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// buffered (D19, D22): a one-shot transformer as a stream that accumulates the whole input and +// converts it at flush. 40 bytes through buffered(letters_one_shot, capacity<64>) in chunks of 7 +// give nothing before flush and the one-shot text after, with no allocation (the spec's scenario +// "Accumulating", on letters; Task 19 adds base58's); an input past the capacity is +// input_too_long at flush; the heap form takes its storage from its allocator and sizes its output +// by output_size, then max_output_size, then doubling; a transformer's error is reported at flush; +// a moved-from buffered converts from the start (Review Focus 5). + +#include "support/counting.hpp" + +#include "support/arena.hpp" +#include "support/letters.hpp" +#include "support/limits.hpp" +#include "support/steps.hpp" +#include "support/toy_media.hpp" + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +/** The bytes of the format letters' text, as a one-shot transformer: letters' codec, forwarded. */ +struct letters_one_shot { + /** The bytes read. */ + using input_type = std::uint8_t; + /** The letters written. */ + using output_type = char; + + /** Two letters a byte: letters' bound. */ + static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return codecs::codec::max_encoded_size(input_size); + } + + /** letters' encode. */ + static codecs::result transform(std::span input, + std::span output) noexcept { + return codecs::codec::encode(test::letters, input, output); + } +}; + +/** + letters' encode with no static bound, counting its calls: its bound is the object's (as a + configured format's may depend on its label or its part), or it states the exact size, or + nothing, by `Sizing`. +*/ +enum class sizing : unsigned char { exact, object_bound, static_bound, none }; + +/** letters' encode, sized as `Sizing` says, counting the calls of `transform` in `*calls`. */ +template +struct counted_letters { + /** The bytes read. */ + using input_type = std::uint8_t; + /** The letters written. */ + using output_type = char; + + /** Where the calls of `transform` are counted. */ + std::size_t* calls; + + /** The exact size of `input`'s text, when `Sizing` is `exact`. */ + [[nodiscard]] std::size_t output_size(std::span input) const noexcept + requires(Sizing == sizing::exact) + { + return codecs::codec::encoded_size(test::letters, input); + } + + /** A bound of this object's, which a static check does not see, when `Sizing` says so. */ + [[nodiscard]] std::size_t max_output_size(std::size_t input_size) const noexcept + requires(Sizing == sizing::object_bound) + { + return codecs::codec::max_encoded_size(input_size); + } + + /** A static bound, the heap form's second choice, when `Sizing` is `static_bound`. */ + [[nodiscard]] static constexpr std::size_t max_output_size(std::size_t input_size) noexcept + requires(Sizing == sizing::static_bound) + { + return codecs::codec::max_encoded_size(input_size); + } + + /** letters' encode, counted. */ + [[nodiscard]] codecs::result transform(std::span input, + std::span output) const noexcept { + ++*calls; + return codecs::codec::encode(test::letters, input, output); + } +}; + +/** letters' encode that refuses a byte 0xFF with `invalid_character`, writing nothing. */ +struct refusing_letters : letters_one_shot { + /** letters' encode, or the refusal. */ + static codecs::result transform(std::span input, + std::span output) noexcept { + if (std::ranges::find(input, std::uint8_t{0xFF}) != input.end()) { + return codecs::error::invalid_character; + } + return letters_one_shot::transform(input, output); + } +}; + +static_assert(codecs::one_shot_transformer); +static_assert(codecs::one_shot_transformer>); +static_assert(codecs::one_shot_transformer>); +static_assert(codecs::one_shot_transformer>); +static_assert(codecs::one_shot_transformer>); +static_assert(codecs::one_shot_transformer); +// The object's bound is not a static one: buffered's heap form sizes such a transformer by +// doubling (review note (a) of Task 8). +static_assert(!codecs::detail::has_max_output_size>); +static_assert(codecs::detail::has_max_output_size>); + +/** `count` bytes, each its index times 37 plus 1. */ +std::vector bytes_of(std::size_t count) { + std::vector held_bytes(count); + for (std::size_t index = 0; index < count; ++index) { + held_bytes[index] = static_cast((index * 37U) + 1U); + } + return held_bytes; +} + +/** What stream_into returns when a call fails or a state is not the protocol's. */ +constexpr std::size_t stream_failed = static_cast(-1); + +/** + Sends `input` to `adapter` in chunks of `chunk_size`, each accepted whole with needs_input and + every receive before flush giving nothing; flushes, and receives into spans of `span_size` of + `text` until finished. Returns the characters written into `text`, or stream_failed when a call + fails, a state is not the protocol's or `text` is full; it allocates nothing of its own. +*/ +template +std::size_t stream_into(Adapter& adapter, std::span input, + std::size_t chunk_size, std::size_t span_size, std::span text) { + std::span rest = input; + while (!rest.empty()) { + std::span const chunk = rest.first(std::min(chunk_size, rest.size())); + if (!test::is_step(adapter.send(chunk), chunk.size(), codecs::flow::needs_input) || + !test::is_step(adapter.receive(text.first(std::min(span_size, text.size()))), 0, + codecs::flow::needs_input)) { + return stream_failed; + } + rest = rest.subspan(chunk.size()); + } + auto const flushed = adapter.flush(); + if (!flushed.has_value()) { + return stream_failed; + } + std::size_t written = 0; + codecs::flow state = *flushed; + while (state == codecs::flow::output_pending) { + std::span const room = text.subspan(written); + auto const received = adapter.receive(room.first(std::min(span_size, room.size()))); + if (!received.has_value() || received->count == 0) { + return stream_failed; + } + written += received->count; + state = received->flow; + } + return state == codecs::flow::finished ? written : stream_failed; +} + +/** stream_into a text of its own, returned, or "". */ +template +std::string stream(Adapter& adapter, std::span input, std::size_t chunk_size, + std::size_t span_size) { + std::vector text(4096); + std::size_t const written = stream_into(adapter, input, chunk_size, span_size, text); + if (written == stream_failed) { + return ""; + } + return {text.data(), written}; +} + +/** The deduction guides and the types: the heap form by default, in place with a capacity. */ +void types() { + using heap_form = decltype(codecs::buffered(letters_one_shot{})); + static_assert(std::is_same_v>); + static_assert(std::is_same_v>>); + static_assert(codecs::stream_transformer); + static_assert(std::is_same_v); + static_assert(std::is_same_v); + using in_place = decltype(codecs::buffered(letters_one_shot{}, codecs::capacity<64>)); + static_assert( + std::is_same_v>>); + static_assert(codecs::stream_transformer); + using pmr_form = decltype(codecs::buffered(letters_one_shot{}, + std::pmr::polymorphic_allocator{})); + static_assert( + std::is_same_v>>); + static_assert(!codecs::is_constant_time_v); + // The bound is read at the capacity, constant there. + static_assert(codecs::detail::has_constant_max_output_size); +} + +/** + The spec's scenario "Accumulating", on letters: 40 bytes sent to buffered(letters_one_shot, + capacity<64>) in chunks of 7, then flushed and received: every receive before flush gives + nothing, the text after flush equals the one-shot form, and no allocation is counted. +*/ +void accumulating() { + std::vector const input = bytes_of(40); + std::string const expected = test::letters_of(input); + std::array first_text{}; + std::array second_text{}; + std::size_t first_size = 0; + std::size_t second_size = 0; + std::size_t const before = test::allocations(); + { + auto adapter = codecs::buffered(letters_one_shot{}, codecs::capacity<64>); + first_size = stream_into(adapter, input, 7, 16, first_text); + adapter.reset(); + second_size = stream_into(adapter, input, 7, 1024, second_text); + } + std::size_t const allocated = test::allocations() - before; + if (allocated != 0) { + std::printf("allocated: buffered(letters_one_shot, capacity<64>)\n"); + } + BOOST_TEST_EQ(allocated, 0U); + BOOST_TEST_EQ(first_size, expected.size()); + BOOST_TEST_EQ(second_size, expected.size()); + BOOST_TEST_EQ((std::string{first_text.data(), first_text.size()}), expected); + BOOST_TEST_EQ((std::string{second_text.data(), second_text.size()}), expected); + // Every chunking and every span size gives the same. + for (std::size_t const chunk_size : {std::size_t{1}, std::size_t{3}, std::size_t{40}}) { + for (std::size_t const span_size : {std::size_t{1}, std::size_t{5}, std::size_t{80}}) { + auto adapter = codecs::buffered(letters_one_shot{}, codecs::capacity<64>); + BOOST_TEST_EQ(stream(adapter, input, chunk_size, span_size), expected); + } + } + // Frames to images, elements of no byte: five frames, five images at flush. + auto images = codecs::buffered(test::frame_to_image{}, codecs::capacity<8>); + std::array frames{}; + for (std::size_t index = 0; index < frames.size(); ++index) { + frames[index] = test::make_frame(static_cast(index)); + } + BOOST_TEST( + test::is_step(images.send(std::span{frames}.first(2)), 2, codecs::flow::needs_input)); + BOOST_TEST( + test::is_step(images.send(std::span{frames}.subspan(2)), 3, codecs::flow::needs_input)); + BOOST_TEST(test::is_flow(images.flush(), codecs::flow::output_pending)); + std::array received{}; + BOOST_TEST(test::is_step(images.receive(received), 5, codecs::flow::finished)); + BOOST_TEST_EQ(received[4].index, 4U); +} + +/** + An input past the capacity is accepted and counted, and flush reports input_too_long, as does + every call after it until reset; the capacity itself is accepted. +*/ +void past_the_capacity() { + std::vector const input = bytes_of(65); + auto adapter = codecs::buffered(letters_one_shot{}, codecs::capacity<64>); + BOOST_TEST( + test::is_step(adapter.send(std::span{input}.first(60)), 60, codecs::flow::needs_input)); + BOOST_TEST( + test::is_step(adapter.send(std::span{input}.subspan(60)), 5, codecs::flow::needs_input)); + BOOST_TEST( + test::is_step(adapter.send(std::span{input}.subspan(60)), 5, codecs::flow::needs_input)); + BOOST_TEST(test::failed_with(adapter.flush(), codecs::error::input_too_long)); + std::array output{}; + BOOST_TEST(test::failed_with(adapter.receive(output), codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(adapter.send(input), codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(adapter.flush(), codecs::error::input_too_long)); + adapter.reset(); + BOOST_TEST_EQ(stream(adapter, std::span{input}.first(64), 7, 32), + test::letters_of(std::span{input}.first(64))); + // 65 bytes in one send. + adapter.reset(); + BOOST_TEST(test::is_step(adapter.send(input), 65, codecs::flow::needs_input)); + BOOST_TEST(test::failed_with(adapter.flush(), codecs::error::input_too_long)); +} + +/** + The protocol's edges: flush with nothing sent finishes at once, with the empty text (Review Focus + 3); an empty send accepts nothing; after flush nothing is accepted, and an empty receive returns + the state. +*/ +void protocol_edges() { + auto adapter = codecs::buffered(letters_one_shot{}, codecs::capacity<8>); + std::array output{}; + BOOST_TEST( + test::is_step(adapter.send(std::span{}), 0, codecs::flow::needs_input)); + BOOST_TEST(test::is_flow(adapter.flush(), codecs::flow::finished)); + BOOST_TEST(test::is_step(adapter.receive(output), 0, codecs::flow::finished)); + adapter.reset(); + std::vector const input = bytes_of(3); + BOOST_TEST(test::is_step(adapter.send(input), 3, codecs::flow::needs_input)); + BOOST_TEST(test::is_flow(adapter.flush(), codecs::flow::output_pending)); + BOOST_TEST(test::is_flow(adapter.flush(), codecs::flow::output_pending)); + BOOST_TEST(test::is_step(adapter.send(input), 0, codecs::flow::output_pending)); + BOOST_TEST(test::is_step(adapter.receive(std::span{}), 0, codecs::flow::output_pending)); + BOOST_TEST(test::is_step(adapter.receive(std::span{output}.first(4)), 4, + codecs::flow::output_pending)); + BOOST_TEST(test::is_step(adapter.receive(output), 2, codecs::flow::finished)); + BOOST_TEST_EQ((std::string{output.data(), 2}), test::letters_of(input).substr(4)); + BOOST_TEST(test::is_step(adapter.send(input), 0, codecs::flow::finished)); + BOOST_TEST(test::is_flow(adapter.flush(), codecs::flow::finished)); +} + +/** A transformer's error is reported at flush, and by every call after it until reset. */ +void transformer_error() { + std::vector input = bytes_of(10); + input[6] = 0xFF; + auto adapter = codecs::buffered(refusing_letters(), codecs::capacity<16>); + BOOST_TEST(test::is_step(adapter.send(input), 10, codecs::flow::needs_input)); + BOOST_TEST(test::failed_with(adapter.flush(), codecs::error::invalid_character)); + std::array output{}; + output.fill('-'); + BOOST_TEST(test::failed_with(adapter.receive(output), codecs::error::invalid_character)); + BOOST_TEST_EQ(output[0], '-'); + BOOST_TEST(test::failed_with(adapter.send(input), codecs::error::invalid_character)); + adapter.reset(); + input[6] = 0; + BOOST_TEST_EQ(stream(adapter, input, 3, 4), test::letters_of(input)); +} + +/** + A fault of the configuration of a format's transformer is reported by buffered's first call, + whatever it is, and by every call after, also after reset and in a moved stream, before any input + is accepted; a format with no fault converts. +*/ +void configuration_fault_first() { + namespace formats = codecs::formats; + std::array const input{1, 2, 3}; + std::array output{}; + output.fill('-'); + auto by_receive = codecs::buffered(codecs::encoder(formats::armor("BAD\x01"))); + BOOST_TEST(test::failed_with(by_receive.receive(output), codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(by_receive.send(input), codecs::error::invalid_prefix)); + BOOST_TEST(test::failed_with(by_receive.flush(), codecs::error::invalid_prefix)); + by_receive.reset(); + BOOST_TEST(test::failed_with(by_receive.send(input), codecs::error::invalid_prefix)); + BOOST_TEST_EQ(output[0], '-'); + auto moved = std::move(by_receive); + BOOST_TEST(test::failed_with(moved.send(input), codecs::error::invalid_prefix)); + // The moved-from stream keeps the fault, as its transformer does (Review Focus 5). + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): Review Focus 5 + BOOST_TEST(test::failed_with(by_receive.send(input), codecs::error::invalid_prefix)); + // By send, by flush, in place, secret, and a decoder. + auto by_send = codecs::buffered(codecs::encoder(formats::armor(std::string(65, 'A'))), + codecs::capacity<8>); + BOOST_TEST(test::failed_with(by_send.send(input), codecs::error::invalid_prefix)); + auto by_flush = codecs::buffered(codecs::decoder(formats::bech32(std::string(84, 'a')))); + BOOST_TEST(test::failed_with(by_flush.flush(), codecs::error::invalid_prefix)); + auto secret = codecs::buffered( + codecs::encoder(formats::bech32m("a\x7f"), codecs::secret_operation), codecs::capacity<8>); + BOOST_TEST(test::failed_with(secret.send(input), codecs::error::invalid_prefix)); + // A chain's configuration is its links': base58 over a bad armor, through buffered. + auto chain = + codecs::buffered(codecs::encoder(codecs::over{formats::armor("BAD\x01"), formats::base58})); + BOOST_TEST(test::failed_with(chain.send(input), codecs::error::invalid_prefix)); + // A good configuration converts. + auto good = codecs::buffered(codecs::encoder(formats::armor("X"))); + BOOST_TEST(test::is_step(good.send(input), 3, codecs::flow::needs_input)); + BOOST_TEST(test::is_flow(good.flush(), codecs::flow::output_pending)); +} + +/** + The heap form: every allocation goes to the arena, the output sized by the transformer's bound; + reset keeps the storage, so that the same input again allocates nothing more. +*/ +void heap_form() { + std::vector const input = bytes_of(1000); + std::string const expected = test::letters_of(input); + test::recording_resource arena; + std::pmr::polymorphic_allocator const allocator{&arena}; + auto adapter = codecs::buffered(letters_one_shot{}, allocator); + BOOST_TEST(adapter.get_allocator() == allocator); + BOOST_TEST_EQ(stream(adapter, input, 7, 64), expected); + std::size_t const allocated = arena.allocation_count(); + BOOST_TEST_GE(allocated, 2U); + for (std::size_t index = 0; index < std::min(allocated, test::recording_resource::most_records); + ++index) { + BOOST_TEST(arena.owns(arena.allocation(index).pointer)); + } + adapter.reset(); + BOOST_TEST_EQ(stream(adapter, input, 7, 64), expected); + BOOST_TEST_EQ(arena.allocation_count(), allocated); + // With std::allocator, by default. + auto by_default = codecs::buffered(letters_one_shot{}); + static_assert( + std::is_same_v>); + BOOST_TEST_EQ(stream(by_default, input, 13, 1024), expected); +} + +/** + The heap form sizes its output by the exact size when the transformer states one, then by its + static bound, then by doubling while transform reports output_too_small: one call of transform + for the first two, more for the last. A bound of the object's own is not a static one, and is + sized by doubling (D19 allows it; review note (a) of Task 8). +*/ +void heap_growth() { + std::vector const input = bytes_of(100); + std::string const expected = test::letters_of(input); + { + std::size_t calls = 0; + auto adapter = codecs::buffered(counted_letters{.calls = &calls}); + BOOST_TEST_EQ(stream(adapter, input, 9, 1024), expected); + BOOST_TEST_EQ(calls, 1U); + } + { + std::size_t calls = 0; + auto adapter = codecs::buffered(counted_letters{.calls = &calls}); + BOOST_TEST_EQ(stream(adapter, input, 9, 1024), expected); + BOOST_TEST_EQ(calls, 1U); + } + { + std::size_t calls = 0; + auto adapter = codecs::buffered(counted_letters{.calls = &calls}); + BOOST_TEST_EQ(stream(adapter, input, 9, 1024), expected); + BOOST_TEST_GT(calls, 1U); + // The storage is kept: the same input again needs one call. + calls = 0; + adapter.reset(); + BOOST_TEST_EQ(stream(adapter, input, 9, 1024), expected); + BOOST_TEST_EQ(calls, 1U); + } + { + std::size_t calls = 0; + auto adapter = codecs::buffered(counted_letters{.calls = &calls}); + BOOST_TEST_EQ(stream(adapter, input, 9, 1024), expected); + BOOST_TEST_GT(calls, 1U); + } +} + +/** + The heap form's limits (Review Focus 2): an output wanted past what the allocator holds is + input_too_long at flush, with nothing allocated for it, and a doubling that reaches the most the + allocator holds tries that most before giving up. +*/ +void heap_limits() { + std::array const input{1, 2, 3, 4, 5}; + std::array output{}; + { + // A static bound saturated past 4 input elements: wanted exceeds max_size(). + auto adapter = codecs::buffered(test::saturated_bound<4>{}); + BOOST_TEST(test::is_step(adapter.send(input), 5, codecs::flow::needs_input)); + test::expect_no_allocation("a flush past max_size", [&] { + BOOST_TEST(test::failed_with(adapter.flush(), codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(adapter.receive(output), codecs::error::input_too_long)); + }); + // Within the bound the same transformer converts. + adapter.reset(); + BOOST_TEST( + test::is_step(adapter.send(std::span{input}.first(4)), 4, codecs::flow::needs_input)); + BOOST_TEST(test::is_flow(adapter.flush(), codecs::flow::output_pending)); + BOOST_TEST(test::is_step(adapter.receive(output), 4, codecs::flow::finished)); + } + // An allocator that holds 10 elements, a transformer with no bound that writes `Need` bytes: + // doubling goes 1, 2, 4, 8 and is then clamped to the 10 that fit. + using ten = test::limited_allocator; + { + auto adapter = codecs::buffered(test::needs_bytes<9>{}, ten{}); + BOOST_TEST( + test::is_step(adapter.send(std::span{input}.first(1)), 1, codecs::flow::needs_input)); + std::array wide{}; + BOOST_TEST(test::is_flow(adapter.flush(), codecs::flow::output_pending)); + BOOST_TEST(test::is_step(adapter.receive(wide), 9, codecs::flow::finished)); + } + { + auto adapter = codecs::buffered(test::needs_bytes<10>{}, ten{}); + BOOST_TEST( + test::is_step(adapter.send(std::span{input}.first(1)), 1, codecs::flow::needs_input)); + BOOST_TEST(test::is_flow(adapter.flush(), codecs::flow::output_pending)); + } + { + auto adapter = codecs::buffered(test::needs_bytes<11>{}, ten{}); + BOOST_TEST( + test::is_step(adapter.send(std::span{input}.first(1)), 1, codecs::flow::needs_input)); + BOOST_TEST(test::failed_with(adapter.flush(), codecs::error::input_too_long)); + BOOST_TEST(test::failed_with(adapter.receive(output), codecs::error::input_too_long)); + } +} + +/** + A moved-from buffered is in reset's state and converts from the start (Review Focus 5), moved by + construction mid-input or by assignment mid-output; the moved-to one carries on. +*/ +template +void moved_mid_stream(Adapter source, Adapter target) { + std::vector const input = bytes_of(40); + std::string const expected = test::letters_of(input); + BOOST_TEST( + test::is_step(source.send(std::span{input}.first(20)), 20, codecs::flow::needs_input)); + Adapter moved{std::move(source)}; + BOOST_TEST( + test::is_step(moved.send(std::span{input}.subspan(20)), 20, codecs::flow::needs_input)); + BOOST_TEST(test::is_flow(moved.flush(), codecs::flow::output_pending)); + std::array output{}; + BOOST_TEST(test::is_step(moved.receive(output), 80, codecs::flow::finished)); + BOOST_TEST_EQ((std::string{output.data(), output.size()}), expected); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST(test::is_step(source.receive(output), 0, codecs::flow::needs_input)); + BOOST_TEST_EQ(stream(source, input, 7, 16), expected); + // By assignment, mid-output. + source.reset(); + BOOST_TEST(test::is_step(source.send(input), 40, codecs::flow::needs_input)); + BOOST_TEST(test::is_flow(source.flush(), codecs::flow::output_pending)); + BOOST_TEST(test::is_step(source.receive(std::span{output}.first(30)), 30, + codecs::flow::output_pending)); + target = std::move(source); + BOOST_TEST(test::is_step(target.receive(output), 50, codecs::flow::finished)); + BOOST_TEST_EQ((std::string{output.data(), 50}), expected.substr(30)); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST_EQ(stream(source, input, 40, 3), expected); +} + +void moved_from() { + moved_mid_stream(codecs::buffered(letters_one_shot{}, codecs::capacity<64>), + codecs::buffered(letters_one_shot{}, codecs::capacity<64>)); + moved_mid_stream(codecs::buffered(letters_one_shot{}), codecs::buffered(letters_one_shot{})); + // A buffered that has reported an error: the moved-to one keeps it, the moved-from starts + // again. + std::vector const input = bytes_of(65); + auto too_long = codecs::buffered(letters_one_shot{}, codecs::capacity<64>); + BOOST_TEST(test::is_step(too_long.send(input), 65, codecs::flow::needs_input)); + BOOST_TEST(test::failed_with(too_long.flush(), codecs::error::input_too_long)); + auto moved{std::move(too_long)}; + BOOST_TEST(test::failed_with(moved.flush(), codecs::error::input_too_long)); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST_EQ(stream(too_long, std::span{input}.first(10), 3, 7), + test::letters_of(std::span{input}.first(10))); +} + +} // namespace + +int main() { + types(); + accumulating(); + past_the_capacity(); + protocol_edges(); + transformer_error(); + configuration_fault_first(); + heap_form(); + heap_growth(); + heap_limits(); + moved_from(); + return boost::report_errors(); +} diff --git a/test/config_test.cpp b/test/config_test.cpp new file mode 100644 index 0000000..0823155 --- /dev/null +++ b/test/config_test.cpp @@ -0,0 +1,47 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// defines WEBCPP_CODECS_NO_EXCEPTIONS exactly when +// webcpp has no exceptions, and keeps the developer's own definition in a build +// that has them. test/Jamfile builds this file four ways: +// - as the build asks; +// - without exceptions; +// - with WEBCPP_NO_EXCEPTIONS defined, as a developer defines it for every +// webcpp library, which WEBCPP_TEST_CODECS_ALL_OFF tells this file; +// - with the macro itself defined on the command line, which +// WEBCPP_TEST_CODECS_DEVELOPER_DEFINED tells this file. + +#include + +// webcpp's configuration, which config.hpp includes, has said whether webcpp +// has exceptions and which target the program is for. +#ifndef WEBCPP_CONFIG_HPP +#error "config.hpp does not include " +#endif + +#ifndef WEBCPP_VERSION +#error "webcpp's configuration does not define WEBCPP_VERSION" +#endif + +#ifdef WEBCPP_TEST_CODECS_ALL_OFF +#ifndef WEBCPP_CODECS_NO_EXCEPTIONS +#error "WEBCPP_NO_EXCEPTIONS does not define WEBCPP_CODECS_NO_EXCEPTIONS" +#endif +#elif defined(WEBCPP_TEST_CODECS_DEVELOPER_DEFINED) +#ifndef WEBCPP_CODECS_NO_EXCEPTIONS +#error "config.hpp drops WEBCPP_CODECS_NO_EXCEPTIONS, which the developer defined" +#endif +#elif defined(WEBCPP_HAS_EXCEPTIONS) == defined(WEBCPP_CODECS_NO_EXCEPTIONS) +#error "WEBCPP_CODECS_NO_EXCEPTIONS is not defined exactly when webcpp has no exceptions" +#endif + +// The namespace of the formats is declared by the configuration alone. +// NOLINTNEXTLINE(misc-unused-alias-decls): the name is the check. +namespace probe = webcpp::codecs::formats; + +int main() { + return 0; +} diff --git a/test/constant_time/Jamfile b/test/constant_time/Jamfile new file mode 100644 index 0000000..21c9d95 --- /dev/null +++ b/test/constant_time/Jamfile @@ -0,0 +1,108 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# Constant time: Valgrind's memcheck and MemorySanitizer on Linux, and dudect's +# statistics natively, as the own lane constant-time, outside the ordinary +# lanes; secure's test/constant_time/Jamfile at 951401a, with codecs' names, is +# the model (pre-flight F27). Both checkers run the same paths, paths.hpp: +# every format's encode and decode, one-shot, in the buffer form, to a secret +# result and streamed in fixed chunks through encoder(format, secret_operation) +# and decoder(format, secret_operation), their input marked secret (each +# format's task adds its block; hex's first). Each checker is shown to fail on +# a planted leak in a function of its own that the report must name, a hex +# encode that indexes its digits by each nibble (planted_hex); dudect to find +# one, a hex validation that exits at the first character that is no hex +# digit (dudect_planted). WEBCPP_SECURE_CT_VALGRIND and WEBCPP_SECURE_CT_MSAN +# are the checkers' defines, which secure's declassify reads, so that the +# library's own branch on a verdict is not reported. +# +# The lane's programs are native only, each one build of its checker: they are +# not declared through test/Jamfile's codecs-run, and have no _no_exceptions +# twins (this is a project of its own, where that rule is not visible, and a +# checker's build is a release build of one configuration). +project : requirements /webcpp/codecs//codecs ; + +import webcpp os ; + +webcpp.targets native ; + +webcpp.original node ; + +# Valgrind and MemorySanitizer run on Linux alone: elsewhere their programs +# are not built, and the lane runs dudect alone. +rule linux-only ( properties * ) +{ + if ! linux in $(properties) + { + return no ; + } +} + +# MemorySanitizer is clang's alone: its programs are built with clang on +# Linux, and not with GCC (-fsanitize=memory is no option of GCC's). +rule clang-on-linux ( properties * ) +{ + if ! linux in $(properties) || ! clang in $(properties) + { + return no ; + } +} + +CTGRIND = release on @linux-only + WEBCPP_SECURE_CT_VALGRIND 300 ; + +webcpp.drive ctgrind : ctgrind_test.cpp : $(CTGRIND) : valgrind.mjs : : native ; +# The formats compile in the user's translation unit, so they are checked at +# both optimisations: ctgrind is release, which is +# speed in b2, and ctgrind_space the other, a program of its +# own, where an optimiser may if-convert a mask differently. +webcpp.drive ctgrind_space : ctgrind_test.cpp : $(CTGRIND) space + : valgrind.mjs : : native ; +# The planted leak, run before every path: memcheck must report it in its own +# function (valgrind.mjs --in). The same source, its own define. +webcpp.drive ctgrind_planted_hex : ctgrind_planted_test.cpp + : $(CTGRIND) WEBCPP_TEST_CODECS_PLANTED_HEX + : valgrind.mjs : --expect-leak --in planted_hex : native ; + +# MemorySanitizer's checking of what a function is passed and returns, eager +# since clang 16, is off: a value derived from a secret is passed and returned +# by design, and only a branch or an index on one is a leak. +MSAN_FLAGS = -fsanitize=memory -fno-sanitize-memory-param-retval ; +MSAN = WEBCPP_SECURE_CT_MSAN $(MSAN_FLAGS) -fsanitize=memory + release on @clang-on-linux ; + +webcpp.run msan : msan_test.cpp : $(MSAN) : native ; +# The planted leak under MemorySanitizer: it passes only on its report whose +# first frame is the planted function (msan_report.mjs --in). +webcpp.drive msan_planted_hex : msan_planted_test.cpp + : $(MSAN) WEBCPP_TEST_CODECS_PLANTED_HEX + : msan_report.mjs : --in planted_hex : native ; + +# dudect's statistics on every format's secret operations, each with its A/A +# control, natively: each operation holds secure's guard, which sets DIT in +# each call on arm64 where the CPU has it, and the program fails if DIT is set +# outside the calls, or not set inside a guard (dudect.hpp). On a runner GitHub +# hosts each |t| is printed and the program does not judge it (secure's +# Jamfile says why), and the CI's dudect_judge.py warns at 10 and measures a +# case over 10 again in two fresh processes, failing when two of the three are +# 10 or more. dudect_planted is judged everywhere. +DUDECT = release ; +if [ os.environ RUNNER_ENVIRONMENT ] = github-hosted +{ + DUDECT += WEBCPP_TEST_DUDECT_UNJUDGED ; +} +# Named dudect_formats, not dudect: the CI's judge reads every dudect_*.output +# (pre-flight F10). +webcpp.run dudect_formats : dudect_test.cpp : $(DUDECT) : native ; +webcpp.run dudect_planted : dudect_planted_test.cpp : release : native ; + +# dudect.hpp itself, on synthetic data and without timing: the statistics, the +# A/A control's preparation, --case and the lines the CI's judge reads. +webcpp.run dudect_harness : dudect_harness_test.cpp : : native ; + +webcpp.lane constant-time : ctgrind ctgrind_space ctgrind_planted_hex msan + msan_planted_hex dudect_formats dudect_planted dudect_harness + : native ; diff --git a/test/constant_time/ctgrind_planted_test.cpp b/test/constant_time/ctgrind_planted_test.cpp new file mode 100644 index 0000000..7b27175 --- /dev/null +++ b/test/constant_time/ctgrind_planted_test.cpp @@ -0,0 +1,11 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// ctgrind_test.cpp with a planted leak, a source of its own so that b2 compiles it with its own +// define: the build the lane expects memcheck to fail, in its planted function (paths.hpp), run +// before every path. With WEBCPP_TEST_CODECS_PLANTED_HEX, a hex encode that indexes its digits by +// each secret nibble. +#include "ctgrind_test.cpp" // NOLINT(bugprone-suspicious-include) diff --git a/test/constant_time/ctgrind_test.cpp b/test/constant_time/ctgrind_test.cpp new file mode 100644 index 0000000..42f09ab --- /dev/null +++ b/test/constant_time/ctgrind_test.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Under Valgrind's memcheck, the input of every format's encode and decode, one-shot, in the +// buffer form, to a secret result and streamed in fixed chunks, is marked undefined (paths.hpp, +// shared with msan_test.cpp): a branch or a memory index that depends on it is an error, and the +// run fails (valgrind.mjs's --error-exitcode). memcheck follows a subtraction's carry, so each +// output is also checked to be undefined until it is marked public: the mark reaches it, so the +// path is traced. A planted program (ctgrind_planted_test.cpp) runs its planted leak first, which +// memcheck must report. secure's ctgrind_test.cpp at 951401a is the model (pre-flight F27). + +#include "paths.hpp" + +#include + +int main() { + using checker = webcpp::codecs::test::memcheck; + webcpp::codecs::test::run_planted(); + int const failures = webcpp::codecs::test::format_paths(); + std::printf("constant time under memcheck: %s\n", failures == 0 ? "ok" : "FAILED"); + return failures == 0 ? 0 : 1; +} diff --git a/test/constant_time/dudect.hpp b/test/constant_time/dudect.hpp new file mode 100644 index 0000000..dd0434b --- /dev/null +++ b/test/constant_time/dudect.hpp @@ -0,0 +1,706 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Copied from webcpp::secure's test/constant_time/dudect.hpp at 951401a (pre-flight F27, the +// design's O5: codecs keeps its own constant-time support, as secure does, until webcpp::core holds +// it), with its namespace webcpp::secure::test renamed webcpp::codecs::test and its include guard +// renamed; nothing else differs. Its comments are secure's: "the blocks" and dudect_blocks are +// secure's, whose cases codecs' dudect_formats follows with hex's secret operations, each holding +// its own guard as constant_time_equal does. +// +// Welch's t-test over two classes of timings, with dudect's cropping. Copied from crypto's +// test/constant_time/dudect.hpp, which keeps its own (secure's tests keep their own support): the +// measurements its comments cite were made on crypto's lane, whose cases the reasons were found on. + +#ifndef WEBCPP_TEST_CODECS_DUDECT_HPP +#define WEBCPP_TEST_CODECS_DUDECT_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +#include +#endif + +#ifdef __APPLE__ +#include +#endif + +namespace webcpp::codecs::test { + +/** + * Waits until every instruction before it has completed, so that a clock read after it does + * not start while the preparation's last instructions still run: `isb` on 64-bit ARM, `lfence` + * on x86. Without it the clock is read out of order, and what the preparation does by class + * (it copies the fixed input or just-drawn bytes) leaks into the measured time (measured + * natively on an Apple M5, 2026-11-18: |t| 25 to 35 on a ChaCha20-Poly1305 decryption that + * never reads the classes' input, below 2 with the barriers; an early-exit comparison's |t| + * rose from 18 to 42). WebAssembly has no such instruction: there the clock is a host call. + */ +inline void serialise() noexcept { +#ifdef __aarch64__ + __asm__ volatile("isb" ::: "memory"); +#elif defined(__x86_64__) || defined(__i386__) + __asm__ volatile("lfence" ::: "memory"); +#elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) + _mm_lfence(); +#elif defined(_MSC_VER) && defined(_M_ARM64) + __isb(_ARM64_BARRIER_SY); +#endif +} + +/** + * Prints, in one line, what the program finds of 64-bit ARM's DIT (Data Independent Timing) bit, + * PSTATE.DIT, and whether the measurements may go on. The harness never sets DIT for the + * measurements: `constant_time_equal` sets it in each call through secure's guard + * (`secure::timing_guard`), and the lane measures that, what a program gets; the blocks hold no + * guard, and dudect_blocks measures each inside one, as the guarded functions that call them run + * them. Where the CPU has DIT, the line + * also shows the guard at work, once, before any measurement: DIT set inside a guard's scope and + * clear again after it. It must be clear on this thread outside the calls, or the timings would + * be those of a DIT the program set itself, not the guard's. + * @return false where the CPU has DIT and it is set on this thread outside a guard, or not set + * inside one, so that the program fails rather than measure it; true otherwise: where the CPU has + * DIT and the guard sets and clears it, where the CPU has none, and where the guard does not + * apply (not arm64 under macOS, Linux or Windows: x86 and WebAssembly, where the engine decides). + */ +inline bool report_data_independent_timing() noexcept { +#ifdef WEBCPP_SECURE_TIMING_COVERED + if (!secure::cpu_has_dit()) { + std::printf("DIT (data-independent timing): not on this CPU\n"); + return true; + } + bool const set_before = secure::dit_is_set(); + bool set_inside = false; + { + secure::timing_guard const timing_scope; + set_inside = secure::dit_is_set(); + } + bool const set_after = secure::dit_is_set(); + bool const outside_set = set_before || set_after; + std::printf( + "DIT (data-independent timing): the CPU has it; secure's guard sets it in each measured " + "call, the harness does not (%s inside a guard; %s)\n", + set_inside ? "set" : "NOT set", + outside_set ? "set on this thread outside the calls: not measured" + : "clear on this thread outside the calls"); + return set_inside && !outside_set; +#else + std::printf( + "DIT (data-independent timing): not applicable here (not arm64 under macOS, Linux or " + "Windows)\n"); + return true; +#endif +} + +/** Online mean and variance of one class, Welford's. */ +struct moments { + /** The number of values pushed. */ + double n = 0; + /** Their mean. */ + double mean = 0; + /** The sum of squared differences from the mean. */ + double m2 = 0; + + /** + * Adds a value. + * @param x The value. + */ + void push(double x) { + n += 1; + double const delta = x - mean; + mean += delta / n; + m2 += delta * (x - mean); + } + + /** + * The sample variance. + * @return The variance, 0 below two values. + */ + [[nodiscard]] double variance() const { return n > 1 ? m2 / (n - 1) : 0; } +}; + +/** + * Welch's t of two classes. + * @param a The first class. + * @param b The second class. + * @return t, 0 when both variances are 0. + */ +inline double welch(moments const& a, moments const& b) { + double const denominator = std::sqrt((a.variance() / a.n) + (b.variance() / b.n)); + return denominator == 0 ? 0 : (a.mean - b.mean) / denominator; +} + +/** One class's count and mean at a cropping. */ +struct class_summary { + /** The number of its timings kept. */ + std::size_t count; + /** Their mean, in nanoseconds. */ + double mean_ns; +}; + +/** The largest |t| of a set of timings, with what gave it. */ +struct t_statistic { + /** The largest |t| over the whole set and dudect's 100 croppings. */ + double t; + /** The cropping that gave it: -1 for the whole set, else 0 to 99. */ + int crop; + /** The largest timing that cropping kept, in nanoseconds. */ + double limit_ns; + /** Each class's count and mean at that cropping. */ + std::array classes; +}; + +/** + * A |t| as the lines print it, rounded to two decimals: every decision reads this value (the + * evidence's condition, a case's pass, `twice`'s second run, the planted leak's verdict), so that + * a |t| of 9.996 prints 10.00, with its evidence, and fails as 10.00 does, and the CI's judge, + * which reads the printed value, agrees with the program. + * @param t The |t|. + * @return It rounded to two decimals. + */ +inline double printed(double t) { + return std::round(t * 100) / 100; +} + +/** + * The largest |t| over the whole set and dudect's 100 croppings, each of which keeps the timings + * at or below a percentile, with the cropping that gave it and each class's count and mean there. + * A cropping that leaves a class empty has no t and is skipped; of equal values the first, the + * whole set before the croppings, is kept. + * @param timings The measurements, at least one. + * @param classes The class, 0 or 1, of each. + * @return The largest |t| and what gave it. + */ +inline t_statistic largest_t(std::vector const& timings, std::vector const& classes) { + std::vector sorted = timings; + std::ranges::sort(sorted); + t_statistic largest{.t = 0, .crop = -1, .limit_ns = sorted.back(), .classes = {}}; + for (int k = -1; k < 100; ++k) { + double const keep = k < 0 ? 1.0 : 1.0 - std::pow(0.5, 10.0 * (k + 1) / 100.0); + double const limit = + sorted[static_cast(keep * static_cast(sorted.size() - 1))]; + std::array m{}; + for (std::size_t i = 0; i < timings.size(); ++i) { + if (timings[i] <= limit) { + m[static_cast(classes[i])].push(timings[i]); + } + } + double const t = std::fabs(welch(m[0], m[1])); + if (!std::isfinite(t) || (k >= 0 && !(t > largest.t))) { + continue; + } + largest = { + .t = t, + .crop = k, + .limit_ns = limit, + .classes = + { + class_summary{.count = static_cast(m[0].n), .mean_ns = m[0].mean}, + class_summary{.count = static_cast(m[1].n), .mean_ns = m[1].mean}, + }, + }; + } + return largest; +} + +/** + * Draws `Size` bytes, then writes into `input` either `fixed`, for class 0, or the drawn bytes, + * for class 1, so that the two classes differ in the bytes written and in nothing else. Both + * classes draw the same bytes, read both `fixed` and the drawn bytes, and write `input` with the + * same instructions: each byte is blended through a mask read from a volatile, which the + * compiler cannot see through, so that it can neither split the work by class nor read one + * source alone. Whatever a class does differently before the measured call leaks the class into + * it. A copy from a volatile pointer to the chosen source (until 2026-11-20) read the fixed + * input for class 0 and the bytes just drawn, still in the store buffer, for class 1: on the + * CI's x86-64 runners the measured call then differed by class whatever it computed (measured + * on GitHub's ubuntu-24.04 runners, 2026-11-20: equal at |t| 31 to 56 on an Intel Xeon 6975P-C + * and ChaCha20-Poly1305's seal at 28 to 85 on AMD EPYC 9V45 and 9V74; through this blend, on + * the Xeon, the EPYC 9V74 and an AMD EPYC 7763, idle and with every processor busy, every case + * of 23 runs of 24 stayed below 4.4, the 24th is in `judged`). Before it, + * a choice the optimiser made of `which == 0 ? 0 : drawn` split the copy into a store of + * constants and a store of drawn bytes (measured natively on an Apple M5, 2026-11-18: |t| 16 to + * 18 on equal and 9 to 26 on open with the split, below 3 for both without it). + * With `Control`, the A/A control: the bytes are drawn, then overwritten with `fixed`, and blended + * through the same volatile mask, so that both classes write the fixed value with the same + * instructions as a case's and the generator advances as it does; its |t| shows what the + * measurement on that machine finds where nothing differs. + * @tparam Control Whether both classes write `fixed`. + * @param which The class, 0 or 1. + * @param generator The seeded generator. + * @param fixed The class 0 input. + * @param input Where the input of the class is written. + */ +template +void choose(int which, Generator& generator, std::array const& fixed, + std::array& input) { + std::array drawn{}; + for (auto& byte : drawn) { + byte = static_cast(generator()); + } + if constexpr (Control) { + // Read through a volatile, so that the compiler cannot know the two sources of the blend + // below equal and fold it into a copy: the control blends as every case does. + for (std::size_t index = 0; index < Size; ++index) { + drawn[index] = static_cast(fixed[index]); + } + } + std::uint8_t volatile const chosen = which == 0 ? 0xFFU : 0x00U; + unsigned const keep = chosen; + unsigned const drop = keep ^ 0xFFU; + for (std::size_t index = 0; index < Size; ++index) { + input[index] = static_cast((unsigned{fixed[index]} & keep) | + (unsigned{drawn[index]} & drop)); + } +} + +/** + * The largest |t| of `count` measurements of `run`, each after `prepare(class, generator)` + * with a class drawn at random from the seeded generator, prepare unmeasured; each clock read + * is fenced by `serialise`. + * @param seed The generator's seed. + * @param count The number of measurements. + * @param prepare Sets up the class's input, unmeasured. + * @param run The operation measured. + * @return The largest |t|, with what gave it. + */ +template +t_statistic measure(std::uint64_t seed, std::size_t count, Prepare&& prepare, Run&& run) { + std::mt19937_64 generator(seed); + std::vector timings; + std::vector classes; + timings.reserve(count); + classes.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + int const which = static_cast(generator() & 1U); + prepare(which, generator); + serialise(); + auto const start = std::chrono::steady_clock::now(); + serialise(); + run(); + serialise(); + auto const end = std::chrono::steady_clock::now(); + timings.push_back(std::chrono::duration(end - start).count()); + classes.push_back(which); + } + return largest_t(timings, classes); +} + +/** + * The largest |t| of a first run, and of a second with another seed when the first, as printed, + * is at least 10. + * @param count The number of measurements of each run. + * @param prepare Sets up the class's input, unmeasured. + * @param run The operation measured. + * @return The first run's statistic when its |t|, as printed, is below 10, else that of the run + * with the smaller |t|. + */ +template +t_statistic twice(std::size_t count, Prepare&& prepare, Run&& run) { + t_statistic const first = measure(20261011, count, prepare, run); + if (printed(first.t) < 10) { + return first; + } + t_statistic const second = measure(20261012, count, prepare, run); + return second.t < first.t ? second : first; +} + +/** A buffer a case measures, named in its addresses line. */ +struct address { + /** + * Names a buffer, as `{"data", data.data()}` does in a case's list. + * @param name Its name in the line, as `data` or `object`. + * @param buffer Where it is. + */ + constexpr address(char const* name, void const* buffer) noexcept : label(name), where(buffer) {} + + /** Its name in the line, as `data` or `object`. */ + char const* label; + /** Where it is. */ + void const* where; +}; + +/** + * The lines of a case, which the CI's judge reads (design D6 of the change api-gaps): `dudect + * case= t=<|t|> threshold=10 judged=`, and, when |t| is at least 10, `dudect + * evidence case= crop= limit_ns= class0_n= class0_mean_ns= class1_n= + * class1_mean_ns=`, the cropping that gave |t| and each class there, and `dudect addresses + * case=
buffers) { + std::array line{}; + double const t = printed(result.t); + static_cast(std::snprintf(line.data(), line.size(), + "dudect case=%s t=%.2f threshold=10 judged=%s\n", name, t, + judged_case ? "yes" : "no")); + std::string text = line.data(); + if (!(t >= 10)) { + return text; + } + static_cast(std::snprintf( + line.data(), line.size(), + "dudect evidence case=%s crop=%d limit_ns=%.2f class0_n=%zu class0_mean_ns=%.2f " + "class1_n=%zu class1_mean_ns=%.2f\n", + name, result.crop, result.limit_ns, result.classes[0].count, result.classes[0].mean_ns, + result.classes[1].count, result.classes[1].mean_ns)); + text += line.data(); + text += "dudect addresses case="; + text += name; + for (address const& buffer : buffers) { + static_cast(std::snprintf( + line.data(), line.size(), " %s=0x%03x", buffer.label, + static_cast(reinterpret_cast(buffer.where) & 0xFFFU))); + text += line.data(); + } + text += '\n'; + return text; +} + +/** + * Prints a case's lines (`case_lines`) to `out`, stdout by default, and flushes them. + * @param name The case's name, as `--case` takes it. + * @param result Its statistic. + * @param judged_case Whether its |t| counts in the program's verdict. + * @param buffers The buffers it measures: its input, its output and its object. + * @param out Where: `std::cout`, the program's stdout, whose other lines (`std::printf`) it keeps + * in order, since the standard streams are synchronised with C's; a test's string stream. + */ +inline void report_case(char const* name, t_statistic const& result, bool judged_case, + std::initializer_list
buffers, std::ostream& out = std::cout) { + out << case_lines(name, result, judged_case, buffers) << std::flush; +} + +/** + * The smallest nonzero difference of 10,000 pairs of `steady_clock::now()` read back to back, + * each read fenced by `serialise`. + * @return The clock's resolution in nanoseconds, 0 when every pair read the same time. + */ +inline double clock_resolution_ns() { + double smallest = 0; + for (int pair = 0; pair < 10'000; ++pair) { + serialise(); + auto const first = std::chrono::steady_clock::now(); + serialise(); + auto const second = std::chrono::steady_clock::now(); + serialise(); + double const difference = std::chrono::duration(second - first).count(); + if (difference > 0 && (smallest == 0 || difference < smallest)) { + smallest = difference; + } + } + return smallest; +} + +/** What the machine line says of the CPU. */ +struct cpu_identity { + /** The model, with no double quote in it. */ + std::string cpu = "unavailable"; + /** The microcode's version, with no space or double quote in it. */ + std::string microcode = "unavailable"; +}; + +/** + * Makes a CPU's identity fit the machine line: a double quote in the model becomes a single one, + * so that the quoted value does not end early, and a space or double quote in the microcode an + * underscore. + * @param identity The identity as the system gave it. + * @return The identity to print. + */ +inline cpu_identity printable(cpu_identity identity) { + std::ranges::replace(identity.cpu, '"', '\''); + for (char& character : identity.microcode) { + if (character == ' ' || character == '"') { + character = '_'; + } + } + return identity; +} + +/** + * Reads the CPU's identity from the text of Linux's /proc/cpuinfo: the first `model name` and + * `microcode` (x86); where there is no `model name` (arm64), the first `CPU implementer`, `CPU + * part`, `CPU variant` and `CPU revision`, as `arm64 implementer= part= variant= + * revision=` with the fields found. What the text does not hold stays `unavailable`. + * @param text The file's text. + * @return The identity, `printable`. + */ +inline cpu_identity parse_cpuinfo(std::string_view text) { + using field = std::pair; + std::array fields{ + field{"model name", {}}, field{"microcode", {}}, field{"CPU implementer", {}}, + field{"CPU part", {}}, field{"CPU variant", {}}, field{"CPU revision", {}}, + }; + constexpr std::string_view blank = " \t\r"; + while (!text.empty()) { + auto const end = text.find('\n'); + std::string_view const line = text.substr(0, end); + text = end == std::string_view::npos ? std::string_view{} : text.substr(end + 1); + auto const colon = line.find(':'); + if (colon == std::string_view::npos) { + continue; + } + std::string_view key = line.substr(0, colon); + std::string_view value = line.substr(colon + 1); + auto const key_end = key.find_last_not_of(blank); + key = key_end == std::string_view::npos ? std::string_view{} : key.substr(0, key_end + 1); + auto const value_start = value.find_first_not_of(blank); + value = + value_start == std::string_view::npos ? std::string_view{} : value.substr(value_start); + value = value.substr(0, value.find_last_not_of(blank) + 1); + for (auto& [name, found] : fields) { + if (key == name && found.empty()) { + found = value; + } + } + } + cpu_identity identity; + if (!fields[0].second.empty()) { + identity.cpu = fields[0].second; + } else if (!fields[2].second.empty()) { + identity.cpu = "arm64"; + constexpr std::array labels{"implementer", "part", "variant", "revision"}; + for (std::size_t index = 0; index < labels.size(); ++index) { + if (!fields[index + 2].second.empty()) { + identity.cpu += ' '; + identity.cpu += labels[index]; + identity.cpu += '='; + identity.cpu += fields[index + 2].second; + } + } + } + if (!fields[1].second.empty()) { + identity.microcode = fields[1].second; + } + return printable(identity); +} + +/** + * The CPU a measurement runs on: /proc/cpuinfo's model and microcode (`parse_cpuinfo`) on Linux, + * `machdep.cpu.brand_string` on macOS with the microcode `unavailable`, and `unavailable` + * elsewhere, WebAssembly included, as where the system does not tell them. + * @return The identity, `printable`. + */ +inline cpu_identity machine_identity() { + cpu_identity identity; +#ifdef __linux__ + if (std::FILE* const file = std::fopen("/proc/cpuinfo", "r")) { + std::string text; + std::array buffer{}; + std::size_t read = 0; + while ((read = std::fread(buffer.data(), 1, buffer.size(), file)) > 0) { + text.append(buffer.data(), read); + } + static_cast(std::fclose(file)); + identity = parse_cpuinfo(text); + } +#elif defined(__APPLE__) + std::array brand{}; + std::size_t size = brand.size(); + if (sysctlbyname("machdep.cpu.brand_string", brand.data(), &size, nullptr, 0) == 0 && + brand[0] != '\0') { + brand.back() = '\0'; + identity.cpu = brand.data(); + } + identity = printable(identity); +#endif + return identity; +} + +/** + * Prints, once per program, the machine a measurement ran on: `dudect machine cpu="" + * microcode= clock_resolution_ns=`, the CPU's `machine_identity`; the resolution is + * `clock_resolution_ns`'s, with two decimals, or `below_resolution` when it measured none. + */ +inline void report_machine() { + static bool printed_once = false; + if (printed_once) { + return; + } + printed_once = true; + cpu_identity const identity = machine_identity(); + double const resolution = clock_resolution_ns(); + std::array written{}; + if (resolution > 0) { + static_cast(std::snprintf(written.data(), written.size(), "%.2f", resolution)); + } else { + static_cast(std::snprintf(written.data(), written.size(), "below_resolution")); + } + std::printf("dudect machine cpu=\"%s\" microcode=%s clock_resolution_ns=%s\n", + identity.cpu.c_str(), identity.microcode.c_str(), written.data()); + static_cast(std::fflush(stdout)); +} + +/** The case a program measures: every one, or the one `--case` names. */ +struct case_selection { + /** The one case to measure, or none for every case. */ + char const* only = nullptr; + + /** + * Whether a case is measured. + * @param name The case's name. + * @return true when no case was named or this one was. + */ + [[nodiscard]] bool runs(char const* name) const { + return only == nullptr || std::strcmp(only, name) == 0; + } +}; + +/** + * Reads a dudect program's arguments: none, to measure every case, or `--case `, to measure + * that case alone, so that the CI measures a case again in a fresh process. + * @param argc main's argc. + * @param argv main's argv. + * @param names The program's cases. + * @return The selection; empty, after a line on stderr that lists the cases (`unknown case ; + * the cases: ` for a name not among them), when the arguments are neither. + */ +inline std::optional select_case(int argc, char const* const* argv, + std::initializer_list names) { + std::string list; + for (char const* const name : names) { + list += list.empty() ? "" : ", "; + list += name; + } + if (argc <= 1) { + return case_selection{}; + } + if (argc == 3 && std::strcmp(argv[1], "--case") == 0) { + for (char const* const name : names) { + if (std::strcmp(argv[2], name) == 0) { + return case_selection{name}; + } + } + static_cast( + std::fprintf(stderr, "unknown case %s; the cases: %s\n", argv[2], list.c_str())); + return std::nullopt; + } + static_cast(std::fprintf(stderr, "usage: %s [--case ]; the cases: %s\n", + argc > 0 ? argv[0] : "dudect", list.c_str())); + return std::nullopt; +} + +/** + * The cases a program measured: each one's lines printed as it is recorded, the human line that + * lists them, and whether every judged one passes. + */ +class case_results { +public: + /** + * Prints a case's lines (`report_case`) and adds it to the human line and to the verdict. + * @param name The case's name, as `--case` takes it. + * @param label Its name in the human line. + * @param result Its statistic. + * @param judged_case Whether its |t| counts in the verdict. + * @param buffers The buffers it measures: its input, its output and its object. + * @param note Printed after its value in the human line. + */ + void record(char const* name, char const* label, t_statistic const& result, bool judged_case, + std::initializer_list
buffers, char const* note = "") { + report_case(name, result, judged_case, buffers); + std::array value{}; + static_cast(std::snprintf(value.data(), value.size(), "%s%s %.2f%s", + human_.empty() ? "" : ", ", label, printed(result.t), + note)); + human_ += value.data(); + passes_ = passes_ && (!judged_case || printed(result.t) < 10); + } + + /** Prints the human line: `|t| and +// basic_secret_string wipe every buffer by secure::erase_secret, its whole capacity, before the +// allocator gets it back: on destruction, on shrink_to_fit, and the old buffer when they grow, +// one allocation for each growth past the capacity. A wipe-checking counting allocator sees every +// buffer zero at deallocate (the spec's scenario "A secret type's buffers are wiped before +// deallocate, also on growth", given 32 bytes and decoded from 64 hex digits, as the spec writes +// it), and secure's test seam (support/wipe_recorder.hpp) sees the wipes the allocator cannot: +// clear(), a cut, and the source's buffer of a move between unequal allocators that do not +// propagate, which copies the bytes into the target's memory. The propagation follows +// std::allocator_traits, and the approved spellings are the std::allocator aliases. + +#include "support/wipe_recorder.hpp" + +#include "support/allocators.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; +namespace test = webcpp::codecs::test; + +using checked_bytes = codecs::basic_secret_byte_vector>; +using checked_string = codecs::basic_secret_string>; +using separate_bytes = + codecs::basic_secret_byte_vector>; + +// The approved spellings are unchanged (the spec's scenario "The approved spelling is +// unchanged"), and the pmr aliases are over std::pmr::polymorphic_allocator. +static_assert( + std::is_same_v>>); +static_assert(std::is_same_v>>); +static_assert(std::is_same_v, codecs::secret_string>); +static_assert(std::is_same_v, codecs::secret_byte_vector>); +static_assert(std::is_same_v>>); +static_assert(std::is_same_v< + codecs::pmr::secret_byte_vector, + codecs::basic_secret_byte_vector>>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v>); + +// Move-only, and a move construction never allocates; a move assignment cannot throw when the +// allocator propagates or is always equal, and may copy, so allocate, when it is neither. +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(!std::is_nothrow_move_assignable_v); +static_assert(!std::is_nothrow_move_assignable_v); +static_assert(std::is_move_assignable_v); + +// No comparison, and the view of an lvalue only. +static_assert(!std::equality_comparable); +static_assert(!std::equality_comparable); +template +concept has_view = requires { std::declval().view(); }; +static_assert(has_view); +static_assert(!has_view); +static_assert(has_view); +static_assert(!has_view); +static_assert(std::is_same_v().view()), + std::string_view>); +static_assert(std::is_same_v().view()), + std::span>); + +// The default constructor is not explicit (LWG 2193), as the standard containers': `return {};` +// and a member initialized by `{}` make an empty one, and it is noexcept when the allocator's +// default construction is. +static_assert(std::is_nothrow_default_constructible_v); +static_assert(std::is_nothrow_default_constructible_v); +static_assert(!std::is_convertible_v, codecs::secret_string>); +static_assert(!std::is_convertible_v, codecs::secret_byte_vector>); +// An allocator that has no default constructor gives none. +static_assert(!std::is_default_constructible_v); + +/** An aggregate whose members are made by `{}`, a copy-list-initialization. */ +struct secret_pair { + /** Characters. */ + codecs::secret_string characters; + /** Bytes. */ + codecs::pmr::secret_byte_vector held_bytes; +}; + +/** An empty string, by `return {};`. */ +codecs::secret_string empty_string() { + return {}; +} + +/** An allocator that propagates on swap, numbered so that a swap of two of them shows. */ +template +class swapping_allocator { +public: + /** The element type. */ + using value_type = T; + /** The allocator goes with its buffer on a swap. */ + using propagate_on_container_swap = std::true_type; + + /** Constructs the allocator numbered `identity`. */ + explicit swapping_allocator(int identity) noexcept : identity_(identity) {} + + /** Constructs the allocator of another element type with this one's number. */ + template + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) + swapping_allocator(swapping_allocator const& other) noexcept + : identity_(other.identity()) {} + + /** Allocates `count` elements. */ + [[nodiscard]] T* allocate(std::size_t count) { return std::allocator{}.allocate(count); } + + /** Returns the elements. */ + void deallocate(T* pointer, std::size_t count) noexcept { + std::allocator{}.deallocate(pointer, count); + } + + /** The number. */ + [[nodiscard]] int identity() const noexcept { return identity_; } + + /** Any two give back each other's memory: std::allocator's. */ + template + [[nodiscard]] bool operator==(swapping_allocator const& /*other*/) const noexcept { + return true; + } + +private: + int identity_; +}; + +/** `count` bytes from `first_value` up, wrapping. */ +std::vector byte_run(std::size_t count, unsigned first_value) { + std::vector run(count); + for (std::size_t index = 0; index < count; ++index) { + run[index] = static_cast(first_value + index); + } + return run; +} + +/** `count` characters, letters from `first_letter` on, wrapping. */ +std::string letter_run(std::size_t count, char first_letter) { + std::string run(count, ' '); + for (std::size_t index = 0; index < count; ++index) { + run[index] = static_cast('a' + ((first_letter - 'a' + index) % 26)); + } + return run; +} + +/** Whether `secret` holds `expected`, by its view. */ +template +bool holds(Secret const& secret, Expected const& expected) { + return std::ranges::equal(secret.view(), expected); +} + +void the_buffers_of_a_byte_vector_are_wiped_on_growth_and_destruction() { + test::wipe_checking_allocator const allocator; + auto const& counts = *allocator.state(); + std::vector expected = byte_run(32, 1); + { + checked_bytes secret{allocator}; + BOOST_TEST_EQ(counts.allocations, 0U); // nothing allocated before a byte is held + secret.append(expected); + BOOST_TEST_EQ(counts.allocations, 1U); + BOOST_TEST_EQ(secret.capacity(), 32U); + // Past the capacity: one allocation, and the old buffer comes back wiped. + auto const one_more = byte_run(1, 0xa0); + secret.append(one_more); + expected.insert(expected.end(), one_more.begin(), one_more.end()); + BOOST_TEST_EQ(counts.allocations, 2U); + BOOST_TEST_EQ(counts.deallocations, 1U); + BOOST_TEST(secret.capacity() > 32U); + // Past the capacity again. + auto const many_more = byte_run(secret.capacity(), 0x40); + secret.append(many_more); + expected.insert(expected.end(), many_more.begin(), many_more.end()); + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST_EQ(counts.deallocations, 2U); + BOOST_TEST(holds(secret, expected)); + BOOST_TEST_EQ(secret.size(), expected.size()); + } + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST_EQ(counts.deallocations, 3U); + BOOST_TEST_EQ(counts.wiped_deallocations, 3U); +} + +void the_buffers_of_a_string_are_wiped_on_growth_and_destruction() { + test::wipe_checking_allocator const allocator; + auto const& counts = *allocator.state(); + std::string expected = letter_run(32, 'a'); + { + checked_string secret{allocator}; + secret.append(expected); + BOOST_TEST_EQ(counts.allocations, 1U); + secret.append("z"); + expected += 'z'; + BOOST_TEST_EQ(counts.allocations, 2U); + std::string const many_more = letter_run(secret.capacity(), 'k'); + secret.append(many_more); + expected += many_more; + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST(secret.view() == expected); + } + BOOST_TEST_EQ(counts.deallocations, 3U); + BOOST_TEST_EQ(counts.wiped_deallocations, 3U); +} + +/** + The spec's scenario, as it writes it: a basic_secret_byte_vector decoded from 64 hex digits with + a wipe-checking allocator, then appended to past its capacity twice, then destroyed, gives back + three buffers, each read zero at deallocate; a basic_secret_string decoded likewise. +*/ +void a_vector_decoded_from_hex_is_wiped_on_growth_and_destruction() { + std::vector expected = byte_run(32, 1); + std::string const text = codecs::encode(formats::hex, expected).value(); + BOOST_TEST_EQ(text.size(), 64U); + test::wipe_checking_allocator const allocator; + auto const& counts = *allocator.state(); + { + auto decoded = codecs::decode(formats::hex, text, allocator); + BOOST_TEST(decoded.has_value()); + checked_bytes& secret = decoded.value(); + BOOST_TEST_EQ(counts.allocations, 1U); + BOOST_TEST(holds(secret, expected)); + auto const one_more = byte_run(secret.capacity() - secret.size() + 1, 0xa0); + secret.append(one_more); + expected.insert(expected.end(), one_more.begin(), one_more.end()); + BOOST_TEST_EQ(counts.allocations, 2U); + BOOST_TEST_EQ(counts.deallocations, 1U); + auto const many_more = byte_run(secret.capacity() - secret.size() + 1, 0x40); + secret.append(many_more); + expected.insert(expected.end(), many_more.begin(), many_more.end()); + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST_EQ(counts.deallocations, 2U); + BOOST_TEST(holds(secret, expected)); + } + BOOST_TEST_EQ(counts.deallocations, 3U); + BOOST_TEST_EQ(counts.wiped_deallocations, 3U); + + std::string expected_text = letter_run(32, 'a'); + std::string const letters_hex = codecs::encode(formats::hex, expected_text).value(); + test::wipe_checking_allocator const character_allocator; + auto const& character_counts = *character_allocator.state(); + { + auto decoded = + codecs::decode(formats::hex, letters_hex, character_allocator); + BOOST_TEST(decoded.has_value()); + checked_string& secret = decoded.value(); + BOOST_TEST_EQ(character_counts.allocations, 1U); + BOOST_TEST(secret.view() == expected_text); + std::string const one_more = letter_run(secret.capacity() - secret.size() + 1, 'k'); + secret.append(one_more); + expected_text += one_more; + BOOST_TEST_EQ(character_counts.allocations, 2U); + std::string const many_more = letter_run(secret.capacity() - secret.size() + 1, 'q'); + secret.append(many_more); + expected_text += many_more; + BOOST_TEST_EQ(character_counts.allocations, 3U); + BOOST_TEST(secret.view() == expected_text); + } + BOOST_TEST_EQ(character_counts.deallocations, 3U); + BOOST_TEST_EQ(character_counts.wiped_deallocations, 3U); +} + +void every_wipe_covers_the_whole_capacity() { + test::wipe_checking_allocator const allocator; + checked_bytes secret{allocator}; + secret.reserve(48); + BOOST_TEST_EQ(secret.capacity(), 48U); + secret.append(byte_run(10, 1)); + void const* const buffer = secret.data(); + test::clear_wipes(); + { + checked_bytes const ending{std::move(secret)}; + BOOST_TEST(ending.data() == buffer); // a move construction takes the buffer + BOOST_TEST_EQ(test::wipes.count, 0U); + } + BOOST_TEST_EQ(test::wipes.count, 1U); + BOOST_TEST(test::wiped(buffer, 48)); + BOOST_TEST_EQ(allocator.state()->wiped_deallocations, allocator.state()->deallocations); +} + +void reserve_and_shrink_to_fit_wipe_the_old_buffer() { + test::wipe_checking_allocator const allocator; + auto const& counts = *allocator.state(); + auto const held = byte_run(20, 7); + checked_bytes secret{allocator}; + secret.append(held); + secret.reserve(10); // no smaller: nothing happens + BOOST_TEST_EQ(counts.allocations, 1U); + secret.reserve(100); + BOOST_TEST_EQ(secret.capacity(), 100U); + BOOST_TEST_EQ(counts.allocations, 2U); + BOOST_TEST_EQ(counts.deallocations, 1U); + BOOST_TEST(holds(secret, held)); + secret.shrink_to_fit(); + BOOST_TEST_EQ(secret.capacity(), 20U); + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST_EQ(counts.deallocations, 2U); + BOOST_TEST(holds(secret, held)); + secret.shrink_to_fit(); // it fits: nothing happens + BOOST_TEST_EQ(counts.allocations, 3U); + // Emptied, shrink_to_fit gives the buffer back, wiped. + secret.clear(); + secret.shrink_to_fit(); + BOOST_TEST_EQ(secret.capacity(), 0U); + BOOST_TEST(secret.data() == nullptr); + BOOST_TEST_EQ(counts.allocations, 3U); + BOOST_TEST_EQ(counts.deallocations, 3U); + BOOST_TEST_EQ(counts.wiped_deallocations, 3U); +} + +void clear_and_a_cut_wipe_the_bytes() { + test::wipe_checking_allocator const allocator; + checked_string secret{allocator}; + secret.append(letter_run(30, 'c')); + void const* const buffer = secret.data(); + std::size_t const capacity = secret.capacity(); + // A cut by resize_for_overwrite wipes the characters cut off. + test::clear_wipes(); + secret.resize_for_overwrite(12); + BOOST_TEST_EQ(secret.size(), 12U); + BOOST_TEST(secret.view() == letter_run(12, 'c')); + BOOST_TEST(test::wiped(secret.data() + 12, 18)); + // clear wipes the characters and keeps the buffer. + test::clear_wipes(); + secret.clear(); + BOOST_TEST(secret.empty()); + BOOST_TEST_EQ(secret.size(), 0U); + BOOST_TEST_EQ(secret.capacity(), capacity); + BOOST_TEST(secret.data() == buffer); + BOOST_TEST(test::wiped(buffer, 12)); + BOOST_TEST_EQ(allocator.state()->deallocations, 0U); +} + +void resize_for_overwrite_gives_room_to_write() { + test::wipe_checking_allocator const allocator; + checked_bytes secret{allocator}; + secret.append(byte_run(4, 1)); + secret.resize_for_overwrite(40); // past the capacity: one allocation, the bytes kept + BOOST_TEST_EQ(secret.size(), 40U); + BOOST_TEST(secret.capacity() >= 40U); + BOOST_TEST_EQ(allocator.state()->allocations, 2U); + BOOST_TEST_EQ(allocator.state()->wiped_deallocations, 1U); + auto const kept = byte_run(4, 1); + BOOST_TEST(std::equal(kept.begin(), kept.end(), secret.data())); + std::fill(secret.data() + 4, secret.data() + 40, std::uint8_t{0x77}); + BOOST_TEST_EQ(secret.view()[39], 0x77); + secret.resize_for_overwrite(40); // the same size: nothing happens + BOOST_TEST_EQ(allocator.state()->allocations, 2U); +} + +void an_append_of_its_own_bytes() { + test::wipe_checking_allocator const allocator; + checked_bytes secret{allocator}; + auto const held = byte_run(16, 3); + secret.append(held); + BOOST_TEST_EQ(secret.capacity(), 16U); + // Its own view, appended past its capacity: read before the old buffer goes. + secret.append(secret.view()); + std::vector twice = held; + twice.insert(twice.end(), held.begin(), held.end()); + BOOST_TEST(holds(secret, twice)); + // And within its capacity. + secret.reserve(64); + secret.append(secret.view().first(4)); + twice.insert(twice.end(), held.begin(), held.begin() + 4); + BOOST_TEST(holds(secret, twice)); + // Nothing appended, nothing allocated. + checked_bytes empty_secret{allocator}; + std::size_t const before = allocator.state()->allocations; + empty_secret.append(std::span{}); + BOOST_TEST_EQ(allocator.state()->allocations, before); + BOOST_TEST(empty_secret.empty()); + BOOST_TEST(empty_secret.view().empty()); +} + +void a_move_takes_the_buffer() { + test::wipe_checking_allocator const allocator; + auto const held = byte_run(24, 9); + checked_bytes source{allocator}; + source.append(held); + void const* const buffer = source.data(); + checked_bytes taken{std::move(source)}; + BOOST_TEST(taken.data() == buffer); + BOOST_TEST(holds(taken, held)); + // NOLINTBEGIN(bugprone-use-after-move): the moved-from state is what is checked + BOOST_TEST_EQ(source.size(), 0U); + BOOST_TEST_EQ(source.capacity(), 0U); + BOOST_TEST(source.data() == nullptr); + // NOLINTEND(bugprone-use-after-move) + BOOST_TEST_EQ(allocator.state()->allocations, 1U); + // A move assignment between equal allocators takes the buffer, and wipes the target's own. + checked_bytes target{allocator}; + target.append(byte_run(8, 1)); + target = std::move(taken); + BOOST_TEST(target.data() == buffer); + BOOST_TEST(holds(target, held)); + BOOST_TEST_EQ(allocator.state()->deallocations, 1U); + BOOST_TEST_EQ(allocator.state()->wiped_deallocations, 1U); + // std::allocator propagates: the buffer is taken. + codecs::secret_byte_vector standard_source; + standard_source.append(held); + void const* const standard_buffer = standard_source.data(); + codecs::secret_byte_vector standard_target; + standard_target.append(byte_run(100, 1)); + standard_target = std::move(standard_source); + BOOST_TEST(standard_target.data() == standard_buffer); + BOOST_TEST(holds(standard_target, held)); +} + +void a_move_between_unequal_allocators_copies_and_wipes_the_source() { + test::non_propagating_allocator const first_allocator{1}; + test::non_propagating_allocator const second_allocator{2}; + auto const held = byte_run(40, 5); + // A target too small for the bytes: a buffer of its allocator's. + { + separate_bytes source{second_allocator}; + source.append(held); + void const* const source_buffer = source.data(); + std::size_t const source_capacity = source.capacity(); + separate_bytes target{first_allocator}; + target.append(byte_run(3, 1)); + test::clear_wipes(); + target = std::move(source); + BOOST_TEST_EQ(target.get_allocator().identity(), 1); + BOOST_TEST(target.data() != source_buffer); + BOOST_TEST(holds(target, held)); + BOOST_TEST(test::wiped(source_buffer, source_capacity)); + // NOLINTBEGIN(bugprone-use-after-move): the moved-from state is what is checked + BOOST_TEST_EQ(source.size(), 0U); + BOOST_TEST_EQ(source.capacity(), 0U); + BOOST_TEST_EQ(source.get_allocator().identity(), 2); + // NOLINTEND(bugprone-use-after-move) + } + // A target with room: the bytes are copied into its buffer, the rest of its bytes wiped. + { + separate_bytes source{second_allocator}; + source.append(std::span{held}.first(10)); + void const* const source_buffer = source.data(); + std::size_t const source_capacity = source.capacity(); + separate_bytes target{first_allocator}; + target.append(byte_run(60, 1)); + void const* const target_buffer = target.data(); + test::clear_wipes(); + target = std::move(source); + BOOST_TEST(target.data() == target_buffer); + BOOST_TEST(holds(target, std::span{held}.first(10))); + BOOST_TEST(test::wiped(target.data() + 10, 50)); + BOOST_TEST(test::wiped(source_buffer, source_capacity)); + } + // Equal allocators that do not propagate: the buffer is taken. + { + separate_bytes source{first_allocator}; + source.append(held); + void const* const source_buffer = source.data(); + separate_bytes target{first_allocator}; + target = std::move(source); + BOOST_TEST(target.data() == source_buffer); + BOOST_TEST(holds(target, held)); + } +} + +void clone_copies_with_the_allocator() { + test::wipe_checking_allocator const allocator; + checked_string original{allocator}; + original.append("a string longer than any small buffer would hold"); + std::size_t const before = allocator.state()->allocations; + checked_string const copy = original.clone(); + BOOST_TEST(copy.view() == original.view()); + BOOST_TEST(copy.data() != original.data()); + BOOST_TEST(copy.get_allocator() == allocator); + BOOST_TEST_EQ(copy.capacity(), copy.size()); + BOOST_TEST_EQ(allocator.state()->allocations - before, 1U); + // An empty one allocates nothing. + checked_string const empty_secret{allocator}; + checked_string const empty_copy = empty_secret.clone(); + BOOST_TEST(empty_copy.empty()); + BOOST_TEST_EQ(allocator.state()->allocations - before, 1U); +} + +void the_default_constructor_is_not_explicit() { + codecs::secret_string const made = empty_string(); + BOOST_TEST(made.empty()); + secret_pair const pair{}; + BOOST_TEST(pair.characters.empty()); + BOOST_TEST(pair.held_bytes.empty()); + BOOST_TEST(pair.held_bytes.get_allocator().resource() == std::pmr::get_default_resource()); +} + +void swap_exchanges_the_buffers() { + // Equal allocators that do not propagate: the buffers change hands, nothing is copied. + test::wipe_checking_allocator const allocator; + checked_string first_string{allocator}; + first_string.append(letter_run(40, 'a')); + checked_string second_string{allocator}; + second_string.append(letter_run(3, 'x')); + char const* const first_buffer = first_string.data(); + char const* const second_buffer = second_string.data(); + std::size_t const allocations = allocator.state()->allocations; + test::clear_wipes(); + first_string.swap(second_string); + BOOST_TEST(first_string.view() == letter_run(3, 'x')); + BOOST_TEST(second_string.view() == letter_run(40, 'a')); + BOOST_TEST(first_string.data() == second_buffer); + BOOST_TEST(second_string.data() == first_buffer); + BOOST_TEST_EQ(allocator.state()->allocations, allocations); + BOOST_TEST_EQ(test::wipes.count, 0U); + // The free swap, found by argument-dependent lookup. + using std::swap; + swap(first_string, second_string); + BOOST_TEST(first_string.view() == letter_run(40, 'a')); + // An allocator that propagates on swap goes with its buffer. + using swapping_bytes = codecs::basic_secret_byte_vector>; + swapping_bytes first_bytes{swapping_allocator{1}}; + first_bytes.append(byte_run(5, 1)); + swapping_bytes second_bytes{swapping_allocator{2}}; + swap(first_bytes, second_bytes); + BOOST_TEST(first_bytes.empty()); + BOOST_TEST(holds(second_bytes, byte_run(5, 1))); + BOOST_TEST_EQ(first_bytes.get_allocator().identity(), 2); + BOOST_TEST_EQ(second_bytes.get_allocator().identity(), 1); + // Equal non-propagating allocators keep their places. + separate_bytes kept_first{test::non_propagating_allocator{7}}; + kept_first.append(byte_run(2, 9)); + separate_bytes kept_second{test::non_propagating_allocator{7}}; + kept_first.swap(kept_second); + BOOST_TEST(holds(kept_second, byte_run(2, 9))); + BOOST_TEST(kept_first.empty()); + static_assert(noexcept( + std::declval().swap(std::declval()))); + static_assert(noexcept(swap(std::declval(), std::declval()))); + static_assert( + !noexcept(swap(std::declval(), std::declval()))); +} + +void a_moved_allocator_stays_equal() { + // The allocator requirements: a move leaves the source equal to what it was. + test::wipe_checking_allocator const original; + test::wipe_checking_allocator source{original}; + test::wipe_checking_allocator const moved{std::move(source)}; + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from allocator is what is checked + BOOST_TEST(source == original); + BOOST_TEST(moved == original); + test::wipe_checking_allocator assigned; + test::wipe_checking_allocator assigned_source{original}; + assigned = std::move(assigned_source); + BOOST_TEST(assigned == original); + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from allocator is what is checked + BOOST_TEST(assigned_source == original); + // A secret string moved with its allocator keeps a source that can still allocate. + checked_string string_source{original}; + string_source.append("kept"); + checked_string const string_target{std::move(string_source)}; + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from string is reused + string_source.append("again"); + BOOST_TEST(string_source.view() == "again"); + BOOST_TEST(string_target.view() == "kept"); +#ifndef WEBCPP_CODECS_NO_EXCEPTIONS + test::throwing_allocator const throwing{0}; + test::throwing_allocator throwing_source{throwing}; + test::throwing_allocator const throwing_moved{std::move(throwing_source)}; + // NOLINTNEXTLINE(bugprone-use-after-move): the moved-from allocator is what is checked + BOOST_TEST(throwing_source == throwing); + BOOST_TEST(throwing_moved == throwing); +#endif +} + +void the_default_allocator() { + codecs::secret_string secret; + BOOST_TEST(secret.empty()); + BOOST_TEST(secret.get_allocator() == std::allocator{}); + secret.append("kept"); + BOOST_TEST(secret.view() == "kept"); + codecs::secret_byte_vector bytes; + bytes.append(byte_run(3, 1)); + BOOST_TEST_EQ(bytes.size(), 3U); +} + +} // namespace + +int main() { + the_buffers_of_a_byte_vector_are_wiped_on_growth_and_destruction(); + the_buffers_of_a_string_are_wiped_on_growth_and_destruction(); + a_vector_decoded_from_hex_is_wiped_on_growth_and_destruction(); + every_wipe_covers_the_whole_capacity(); + reserve_and_shrink_to_fit_wipe_the_old_buffer(); + clear_and_a_cut_wipe_the_bytes(); + resize_for_overwrite_gives_room_to_write(); + an_append_of_its_own_bytes(); + a_move_takes_the_buffer(); + a_move_between_unequal_allocators_copies_and_wipes_the_source(); + clone_copies_with_the_allocator(); + the_default_constructor_is_not_explicit(); + swap_exchanges_the_buffers(); + a_moved_allocator_stays_equal(); + the_default_allocator(); + return boost::report_errors(); +} diff --git a/test/secret_operation_test.cpp b/test/secret_operation_test.cpp new file mode 100644 index 0000000..2568fcc --- /dev/null +++ b/test/secret_operation_test.cpp @@ -0,0 +1,1048 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Secret operations (D10): an operation is secret by the value's is_secret, the value codec's +// secret, the token's secret or the requested type of a typed decode, and then returns D9's secret +// column, runs the secret_tag overloads of a format's codec or value codec where it has them +// (ruling R7), and wipes every temporary of the core, as secure's wipe seam +// (support/wipe_recorder.hpp) records it. The fixed secret forms allocate nothing, as +// support/counting.hpp's operator new sees. The spec's scenarios +// "A secret type encodes to a wiped text", "secure's secret is secret" and "A secret result type +// is secret", on the format letters, and the first two and "Decode follows the requested type" on +// hex. A token of the program's own whose secret is true makes the operation secret and keeps its +// result type; every token the core makes (return_string's, fixed's, and append_to's and +// assign_to's in a secret operation) wipes what it wrote and does not give, on a failure and in +// the tail a shrink cuts. + +#include "support/wipe_recorder.hpp" + +#include "support/counting.hpp" + +#include "support/be16.hpp" +#include "support/key32.hpp" +#include "support/letters.hpp" +#include "support/secret_tokens.hpp" +#include "support/shrinking.hpp" +#include "support/tagged_letters.hpp" + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; +namespace secure = webcpp::secure; +namespace test = webcpp::codecs::test; +namespace tokens = webcpp::codecs::tokens; + +namespace secret_operation { +namespace { + +/** The tests' secret type of 32 bytes. */ +using test::key32; + +/** A library's fixed secret type whose move does not wipe: a typed decode's target. */ +struct plain_key { + /** The bytes. */ + std::array held_bytes{}; +}; + +/** A secret run of bytes of a size known at run time, a contiguous range. */ +struct secret_run { + /** The bytes. */ + std::vector held_bytes; + + /** The first byte. */ + [[nodiscard]] std::uint8_t const* begin() const noexcept { return held_bytes.data(); } + + /** Past the last byte. */ + [[nodiscard]] std::uint8_t const* end() const noexcept { + return held_bytes.data() + held_bytes.size(); + } +}; + +/** A value of a secret value codec of bytes, with a stated bound: sixteen bits. */ +struct secret_number { + /** The bits. */ + std::uint16_t value; + + /** Equal when the bits are. */ + bool operator==(secret_number const&) const = default; +}; + +/** A secret value whose value codec writes its bytes and then fails, with no stated bound. */ +struct secret_failing_number { + /** The bits. */ + std::uint16_t value; +}; + +/** A secret_failing_number whose value codec states its bound: its scratch is in place. */ +struct bounded_secret_failing_number { + /** The bits. */ + std::uint16_t value; +}; + +/** A secret value whose value codec of text writes its characters and then fails. */ +struct secret_failing_word { + /** The characters. */ + std::string characters; +}; + +/** A value of a secret value codec of text with no stated bound. */ +struct secret_word { + /** The characters. */ + std::string characters; +}; + +/** The format of the secret value codecs. */ +struct secret_values_t { + /** The format's name. */ + static constexpr std::string_view name = "secret values"; +}; + +/** The format of the secret value codecs. */ +inline constexpr secret_values_t secret_values{}; + +/** The secret value codec that fails after writing: two bytes, then checksum_mismatch. */ +template +struct failing_value_codec { + /** Bytes. */ + static constexpr codecs::output_kind output = codecs::output_kind::bytes; + /** The value is secret. */ + static constexpr bool secret = true; + + /** Two bytes. */ + static std::size_t encoded_size(secret_values_t const& /*format*/, + Failing const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the two bytes, then reports checksum_mismatch. */ + static codecs::result encode(secret_values_t const& /*format*/, + Failing const& held_value, + std::span output_bytes) noexcept { + static_cast(test::write_be16(held_value.value, output_bytes)); + return codecs::error::checksum_mismatch; + } +}; + +/** The calls of the tagged value codec's overloads that take `detail::secret_tag` first. */ +struct tagged_value_counts { + /** The calls of `encoded_size`. */ + std::size_t encoded_size = 0; + /** The calls of `encode`. */ + std::size_t encode = 0; + /** The calls of `decode`. */ + std::size_t decode = 0; + + /** Every call. */ + [[nodiscard]] std::size_t total() const noexcept { return encoded_size + encode + decode; } +}; + +/** The calls of the tagged value codec's secret overloads. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the test's record +tagged_value_counts tagged_value_calls; + +/** A public value of the tagged value codec: sixteen bits. */ +struct tagged_number { + /** The bits. */ + std::uint16_t value; + + /** Equal when the bits are. */ + bool operator==(tagged_number const&) const = default; +}; + +/** A value of the tagged value codec that is secret (`is_secret`): sixteen bits. */ +struct tagged_secret_number { + /** The bits. */ + std::uint16_t value; + + /** Equal when the bits are. */ + bool operator==(tagged_secret_number const&) const = default; +}; + +/** A value whose value codec's secret decode takes parameters the core does not give. */ +struct misread_number { + /** The bits. */ + std::uint16_t value; +}; + +/** The format of the tagged value codec. */ +struct tagged_values_t { + /** The format's name. */ + static constexpr std::string_view name = "tagged values"; +}; + +/** The format of the tagged value codec. */ +inline constexpr tagged_values_t tagged_values{}; + +/** + A value codec of bytes whose arithmetic differs when the operation is secret (ruling R7): two + bytes, big endian, and the overloads that take `detail::secret_tag` first, which count their calls + and then convert as the others do. +*/ +template +struct tagged_value_codec { + /** Bytes. */ + static constexpr codecs::output_kind output = codecs::output_kind::bytes; + /** Two bytes, always. */ + static constexpr std::size_t max_encoded_size = 2; + + /** Two bytes. */ + static std::size_t encoded_size(tagged_values_t const& /*format*/, + Number const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the high byte then the low byte. */ + static codecs::result encode(tagged_values_t const& /*format*/, + Number const& held_value, + std::span output_bytes) noexcept { + return test::write_be16(held_value.value, output_bytes); + } + + /** Reads two bytes, big endian. */ + static codecs::result decode(tagged_values_t const& /*format*/, + std::span input_bytes) noexcept { + if (input_bytes.size() != 2) { + return codecs::error::invalid_length; + } + return Number{test::read_be16(input_bytes)}; + } + + /** The secret operation's `encoded_size`: counted, then the public one. */ + static std::size_t encoded_size(codecs::detail::secret_tag /*secret*/, + tagged_values_t const& format_value, + Number const& held_value) noexcept { + ++tagged_value_calls.encoded_size; + return encoded_size(format_value, held_value); + } + + /** The secret operation's `encode`: counted, then the public one. */ + static codecs::result encode(codecs::detail::secret_tag /*secret*/, + tagged_values_t const& format_value, + Number const& held_value, + std::span output_bytes) noexcept { + ++tagged_value_calls.encode; + return encode(format_value, held_value, output_bytes); + } + + /** The secret operation's `decode`: counted, then the public one. */ + static codecs::result decode(codecs::detail::secret_tag /*secret*/, + tagged_values_t const& format_value, + std::span input_bytes) noexcept { + ++tagged_value_calls.decode; + return decode(format_value, input_bytes); + } +}; + +} // namespace +} // namespace secret_operation + +namespace webcpp::codecs { + +/** The tagged value codec of a public number. */ +template <> +struct value_codec + : secret_operation::tagged_value_codec {}; + +/** The tagged value codec of a secret number. */ +template <> +struct value_codec + : secret_operation::tagged_value_codec {}; + +/** A value codec whose secret decode reads mutable bytes, which the core's view does not convert + to. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + + /** Reads nothing. */ + static result decode( + secret_operation::tagged_values_t const& /*format*/, + std::span /*input_bytes*/) noexcept { + return error::invalid_length; + } + + /** The secret decode, of mutable bytes. */ + static result decode( + detail::secret_tag /*secret*/, secret_operation::tagged_values_t const& /*format*/, + std::span /*input_bytes*/) noexcept { + return error::invalid_length; + } +}; + +/** tagged_secret_number is secret. */ +template <> +struct is_secret : std::true_type {}; + +/** plain_key is secret. */ +template <> +struct is_secret : std::true_type {}; + +/** plain_key is a decode's target of exactly 32 bytes. */ +template <> +struct fixed_byte_storage { + /** The size. */ + static constexpr std::size_t size = 32; + + /** The bytes a decode fills. */ + static std::span writable( + secret_operation::plain_key& target_key) noexcept { + return target_key.held_bytes; + } +}; + +/** secret_run is secret. */ +template <> +struct is_secret : std::true_type {}; + +/** The secret value codec of bytes: two bytes, big endian. */ +template <> +struct value_codec { + /** Bytes. */ + static constexpr output_kind output = output_kind::bytes; + /** The value is secret. */ + static constexpr bool secret = true; + /** Two bytes, always. */ + static constexpr std::size_t max_encoded_size = 2; + + /** Two bytes. */ + static std::size_t encoded_size( + secret_operation::secret_values_t const& /*format*/, + secret_operation::secret_number const& /*held_value*/) noexcept { + return 2; + } + + /** Writes the high byte then the low byte. */ + static result encode(secret_operation::secret_values_t const& /*format*/, + secret_operation::secret_number const& held_value, + std::span output_bytes) noexcept { + return test::write_be16(held_value.value, output_bytes); + } + + /** Reads two bytes, big endian. */ + static result decode( + secret_operation::secret_values_t const& /*format*/, + std::span input_bytes) noexcept { + if (input_bytes.size() != 2) { + return error::invalid_length; + } + return secret_operation::secret_number{test::read_be16(input_bytes)}; + } +}; + +/** The failing secret value codec with no stated bound. */ +template <> +struct value_codec + : secret_operation::failing_value_codec {}; + +/** The failing secret value codec with a stated bound. */ +template <> +struct value_codec + : secret_operation::failing_value_codec { + /** Two bytes, always. */ + static constexpr std::size_t max_encoded_size = 2; +}; + +/** The secret value codec of text: the characters as they are. */ +template <> +struct value_codec { + /** Text. */ + static constexpr output_kind output = output_kind::text; + /** The value is secret. */ + static constexpr bool secret = true; + + /** The characters. */ + static std::size_t encoded_size(secret_operation::secret_values_t const& /*format*/, + secret_operation::secret_word const& held_value) noexcept { + return held_value.characters.size(); + } + + /** Writes the characters. */ + static result encode(secret_operation::secret_values_t const& /*format*/, + secret_operation::secret_word const& held_value, + std::span output_characters) noexcept { + std::ranges::copy(held_value.characters, output_characters.begin()); + return held_value.characters.size(); + } +}; + +/** The secret value codec of text that fails after writing: the characters, then + checksum_mismatch. */ +template <> +struct value_codec { + /** Text. */ + static constexpr output_kind output = output_kind::text; + /** The value is secret. */ + static constexpr bool secret = true; + + /** The characters. */ + static std::size_t encoded_size( + secret_operation::secret_values_t const& /*format*/, + secret_operation::secret_failing_word const& held_value) noexcept { + return held_value.characters.size(); + } + + /** Writes the characters, then reports checksum_mismatch. */ + static result encode(secret_operation::secret_values_t const& /*format*/, + secret_operation::secret_failing_word const& held_value, + std::span output_characters) noexcept { + std::ranges::copy(held_value.characters, output_characters.begin()); + return error::checksum_mismatch; + } +}; + +} // namespace webcpp::codecs + +namespace secret_operation { +namespace { + +using codecs::detail::secret_operation_v; + +// is_secret: false by default, true for secure's secret and the secret results, read through +// std::remove_cvref_t. +static_assert(!codecs::is_secret_v>); +static_assert(!codecs::is_secret_v>); +static_assert(codecs::is_secret_v>); +static_assert(codecs::is_secret_v const&>); +static_assert(codecs::is_secret_v>); +static_assert(codecs::is_secret_v>); +static_assert(codecs::is_secret_v); +static_assert(codecs::is_secret_v); +static_assert(codecs::is_secret_v); + +// The operation is secret by the value, the value codec, the token or the requested type (D10). +static_assert( + !secret_operation_v, tokens::automatic>); +static_assert(secret_operation_v); +static_assert(secret_operation_v const&, tokens::automatic>); +static_assert(secret_operation_v); +static_assert( + secret_operation_v, tokens::secret_t<> const&>); +static_assert(secret_operation_v, tokens::automatic>); +static_assert( + !secret_operation_v, tokens::return_string_t<>>); + +// A token of the program's own whose secret is true makes the operation secret, its result the +// token's own. +static_assert(secret_operation_v, + test::secret_text_token&>); +static_assert(secret_operation_v); +static_assert(std::is_same_v>(), + std::declval())), + codecs::result>); +static_assert(std::is_same_v())), + codecs::result>>); + +// tokens::secret: a tag of both directions, also callable with an allocator, that it keeps. +static_assert(tokens::secret_t<>::secret); +static_assert(std::is_same_v const>); +static_assert( + std::is_same_v{})), + tokens::secret_t>>); + +// D9's secret column. +static_assert(std::is_same_v())), + codecs::result>>); +static_assert( + std::is_same_v>())), + codecs::result>>); +static_assert(std::is_same_v>>); +static_assert(std::is_same_v())), + codecs::result>); +static_assert(std::is_same_v())), + codecs::result>); +static_assert( + std::is_same_v>(), + tokens::secret)), + codecs::result>); +static_assert(std::is_same_v>(), + tokens::secret)), + codecs::result>>); +// A static bound gives the fixed form and ignores the allocator. +static_assert(std::is_same_v< + decltype(codecs::encode(test::letters, std::declval>(), + tokens::secret(std::pmr::polymorphic_allocator{}))), + codecs::result>>); +static_assert(std::is_same_v>(), + tokens::secret(std::pmr::polymorphic_allocator{}))), + codecs::result>); +static_assert( + std::is_same_v>); +static_assert(std::is_same_v>(), tokens::secret)), + codecs::result>>); +static_assert(std::is_same_v< + decltype(codecs::decode(test::letters, std::string_view{}, + tokens::secret(std::pmr::polymorphic_allocator{}))), + codecs::result>); +// A typed decode into a secret type, and the value codec's own type. +static_assert(std::is_same_v>(test::letters, "ab")), + codecs::result>>); +static_assert(codecs::decodable, test::letters_t>); +static_assert(codecs::decodable, test::letters_t>); +static_assert(codecs::decodable); +static_assert(codecs::decodable); +static_assert(codecs::decodable); +// The text of a secret encoding is no text input: its view is passed by name. +static_assert(!codecs::detail::text_input>); + +/** The 32 bytes the tests encode, 0x00 to 0xff by steps of 8 (every letter appears). */ +std::array key_bytes() { + std::array held_bytes{}; + for (std::size_t index = 0; index < held_bytes.size(); ++index) { + held_bytes[index] = static_cast(index * 8U); + } + return held_bytes; +} + +/** The letters of `key_bytes()`. */ +std::string key_text() { + return codecs::encode(test::letters, key_bytes(), tokens::return_string).value(); +} + +/** A key32 of `key_bytes()`. */ +key32 make_key32() { + key32 made; + made.held_bytes = key_bytes(); + return made; +} + +/** A secure::secret<32> of `key_bytes()`. */ +secure::secret<32> make_secret() { + secure::secret<32> made; + std::ranges::copy(key_bytes(), made.writable().begin()); + return made; +} + +void a_secret_type_encodes_to_a_wiped_text() { + key32 const key = make_key32(); + void const* storage = nullptr; + { + auto const encoded = codecs::encode(test::letters, key); + BOOST_TEST(encoded.has_value()); + BOOST_TEST(encoded.value().view() == key_text()); + storage = encoded.value().data(); + test::clear_wipes(); + } + // After its destruction its storage read zero through the seam. + BOOST_TEST(test::wiped(storage, 64)); +} + +void secures_secret_is_secret() { + secure::secret<32> const key = make_secret(); + auto const encoded = codecs::encode(test::letters, key); + BOOST_TEST(encoded.value().view() == key_text()); + // The decode into secure's secret: no heap, its temporary wiped. + test::clear_wipes(); + auto const decoded = codecs::decode>(test::letters, encoded.value().view()); + BOOST_TEST(decoded.has_value()); + auto const& decoded_secret = decoded.value(); + BOOST_TEST(std::ranges::equal(decoded_secret.bytes(), key_bytes())); + BOOST_TEST(test::wiped_elsewhere(decoded_secret.bytes().data(), 32)); + // The errors reach the caller. + BOOST_TEST(codecs::decode>(test::letters, "abq").error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode>(test::letters, "abab").error() == + codecs::error::invalid_length); +} + +void a_libraries_secret_type_has_its_temporary_wiped() { + // plain_key's move copies its bytes and wipes nothing: the core's scope guard wipes the + // temporary it decoded into. + std::string const text_value = key_text(); + test::clear_wipes(); + auto const decoded = codecs::decode(test::letters, text_value); + BOOST_TEST(decoded.has_value()); + BOOST_TEST(decoded.value().held_bytes == key_bytes()); + BOOST_TEST(test::wiped_elsewhere(decoded.value().held_bytes.data(), 32)); + // Also when the decode fails after the temporary is made. + test::clear_wipes(); + BOOST_TEST(codecs::decode(test::letters, "abab").error() == + codecs::error::invalid_length); + BOOST_TEST(test::wiped_of_size(32)); +} + +void a_secret_result_type_is_secret() { + std::string const text_value = key_text(); + test::tagged_calls.reset(); + test::clear_wipes(); + auto const decoded = codecs::decode>(test::tagged_letters, text_value); + BOOST_TEST(decoded.has_value()); + BOOST_TEST(std::ranges::equal(decoded.value().view(), key_bytes())); + // A secret operation: the format's secret arithmetic ran, and the temporary was wiped. + BOOST_TEST_EQ(test::tagged_calls.decoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.decode, 1U); + BOOST_TEST(test::wiped_elsewhere(decoded.value().data(), 32)); + // Up to N bytes, as bytes. + auto const too_small = codecs::decode>(test::letters, text_value); + BOOST_TEST(too_small.error() == codecs::error::output_too_small); + auto const heap = codecs::decode(test::letters, text_value); + BOOST_TEST(std::ranges::equal(heap.value().view(), key_bytes())); + auto const characters = codecs::decode(test::letters, "gbgc"); + BOOST_TEST(characters.value().view() == "ab"); +} + +void the_secret_token_both_ways() { + std::string const text_value = key_text(); + // A text of a size known at run time: the heap. + auto const decoded = codecs::decode(test::letters, text_value, tokens::secret); + BOOST_TEST(std::ranges::equal(decoded.value().view(), key_bytes())); + // A text<64>: the fixed form. + auto const fixed_text = codecs::encode(test::letters, key_bytes()); + auto const fixed_decoded = codecs::decode(test::letters, fixed_text.value(), tokens::secret); + BOOST_TEST(std::ranges::equal(fixed_decoded.value().view(), key_bytes())); + // An encode of public bytes through the token. + std::array const held_bytes = key_bytes(); + std::vector const heap_input(held_bytes.begin(), held_bytes.end()); + auto const encoded = codecs::encode(test::letters, heap_input, tokens::secret); + BOOST_TEST(encoded.value().view() == text_value); + auto const fixed_encoded = codecs::encode(test::letters, key_bytes(), tokens::secret); + BOOST_TEST(fixed_encoded.value().view() == text_value); + // The errors reach the caller, the token untouched. + BOOST_TEST(codecs::decode(test::letters, std::string_view{"abq"}, tokens::secret).error() == + codecs::error::invalid_character); + BOOST_TEST(codecs::decode(test::letters, codecs::text<4>{}, tokens::secret).has_value()); +} + +void a_secret_value_codec() { + auto const encoded = codecs::encode(secret_values, secret_number{0x1234}); + BOOST_TEST_EQ(encoded.value().size(), 2U); + BOOST_TEST_EQ(encoded.value().view()[0], 0x12); + BOOST_TEST_EQ(encoded.value().view()[1], 0x34); + auto const decoded = codecs::decode(secret_values, encoded.value().view()); + BOOST_TEST(decoded.value() == secret_number{0x1234}); + auto const word = codecs::encode(secret_values, secret_word{"open sesame"}); + BOOST_TEST(word.value().view() == "open sesame"); + // The buffer form of a secret value codec. + std::array buffer{}; + BOOST_TEST_EQ(codecs::encode(secret_values, secret_number{0xabcd}, std::span{buffer}).value(), + 2U); + BOOST_TEST_EQ(buffer[0], 0xab); + // A run of a size known at run time: the heap. + secret_run const run{.held_bytes = {0x01, 0xff}}; + auto const run_text = codecs::encode(test::letters, run); + BOOST_TEST(run_text.value().view() == "abpp"); +} + +void a_failed_secret_operation_into_assign_to() { + // The value codec writes its two secret bytes and then fails: assign_to's target keeps what it + // held, and the scratch that held the bytes was wiped, from the target's allocator and in + // place. + std::vector kept{9, 8, 7}; + test::clear_wipes(); + auto const failed = + codecs::encode(secret_values, secret_failing_number{0x1234}, tokens::assign_to(kept)); + BOOST_TEST(failed.error() == codecs::error::checksum_mismatch); + BOOST_TEST((kept == std::vector{9, 8, 7})); + BOOST_TEST(test::wiped_of_size(2)); + test::clear_wipes(); + auto const bounded = codecs::encode(secret_values, bounded_secret_failing_number{0x1234}, + tokens::assign_to(kept)); + BOOST_TEST(bounded.error() == codecs::error::checksum_mismatch); + BOOST_TEST((kept == std::vector{9, 8, 7})); + BOOST_TEST(test::wiped_of_size(2)); + // On success the scratch in place is wiped too, once its bytes are in the target. + std::string text_target = "kept"; + test::clear_wipes(); + BOOST_TEST( + codecs::encode(test::letters, make_key32(), tokens::assign_to(text_target)).has_value()); + BOOST_TEST(text_target == key_text()); + BOOST_TEST(test::wiped_of_size(64)); +} + +void a_programs_own_secret_token_makes_the_operation_secret() { + // The spec's tokens requirement: a token's static constexpr bool secret makes the operation + // secret. Each direction runs tagged_letters' secret overloads and gives the token's result. + std::array const public_bytes = key_bytes(); + std::string const text_value = key_text(); + test::tagged_calls.reset(); + test::secret_text_token text_token; + auto const encoded = codecs::encode(test::tagged_letters, public_bytes, text_token); + BOOST_TEST(encoded.value() == text_value); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.encode, 1U); + BOOST_TEST_EQ(test::tagged_calls.total(), 2U); + test::tagged_calls.reset(); + test::secret_byte_token byte_token; + auto const decoded = + codecs::decode(test::tagged_letters, std::string_view{text_value}, byte_token); + BOOST_TEST(std::ranges::equal(decoded.value(), public_bytes)); + BOOST_TEST_EQ(test::tagged_calls.decoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.decode, 1U); + BOOST_TEST_EQ(test::tagged_calls.total(), 2U); + // Passed as rvalues, the same; a text of a static size too. + test::tagged_calls.reset(); + BOOST_TEST( + codecs::encode(test::tagged_letters, public_bytes, test::secret_text_token{}).has_value()); + auto const fixed_text = codecs::encode(test::letters, public_bytes); + BOOST_TEST(codecs::decode(test::tagged_letters, fixed_text.value(), test::secret_byte_token{}) + .has_value()); + BOOST_TEST_EQ(test::tagged_calls.total(), 4U); +} + +/** A secure::secret<2> of 0x01 and 0xff, whose letters are "abpp". */ +secure::secret<2> make_short_secret() { + secure::secret<2> made; + made.writable()[0] = 0x01; + made.writable()[1] = 0xff; + return made; +} + +void the_core_tokens_wipe_what_they_do_not_give() { + // A secret value codec of text writes its characters and then fails: the token of + // return_string, of fixed and of append_to wipes what it wrote. + secret_failing_word const failing{.characters = "xy"}; + test::clear_wipes(); + BOOST_TEST(codecs::encode(secret_values, failing, tokens::return_string).error() == + codecs::error::checksum_mismatch); + BOOST_TEST(test::wiped_of_size(2)); + test::clear_wipes(); + BOOST_TEST(codecs::encode(secret_values, failing, tokens::fixed<8>{}).error() == + codecs::error::checksum_mismatch); + BOOST_TEST(test::wiped_of_size(2)); + std::string appended = "kept"; + test::clear_wipes(); + BOOST_TEST(codecs::encode(secret_values, failing, tokens::append_to(appended)).error() == + codecs::error::checksum_mismatch); + BOOST_TEST(appended == "kept"); + BOOST_TEST(test::wiped_of_size(2)); + std::vector appended_bytes{9}; + test::clear_wipes(); + BOOST_TEST(codecs::encode(secret_values, secret_failing_number{0x1234}, + tokens::append_to(appended_bytes)) + .error() == codecs::error::checksum_mismatch); + BOOST_TEST((appended_bytes == std::vector{9})); + BOOST_TEST(test::wiped_of_size(2)); +} + +void an_assigning_tokens_copy_and_move_take_the_target_alone() { + // A copy or a move of a token whose scratch is engaged takes the target and no scratch: the + // scratch is not duplicated (two wipes of one buffer) nor dropped (none), but given back, + // wiped, once, by the token that prepared it. + using wiping_token = codecs::detail::assigning_token; + static_assert(std::is_nothrow_copy_constructible_v); + static_assert(std::is_nothrow_copy_assignable_v); + static_assert(std::is_nothrow_move_constructible_v); + static_assert(std::is_nothrow_move_assignable_v); + std::string target = "kept"; + wiping_token prepared{target}; + std::fill_n(prepared.prepare(40), 40, 'x'); // past a small string: the heap + test::clear_wipes(); + { + wiping_token const copied{prepared}; + wiping_token copy_assigned{target}; + copy_assigned = prepared; + // The source of a move keeps its scratch, which is what the test pins. + // NOLINTBEGIN(bugprone-use-after-move) + wiping_token const moved{std::move(prepared)}; + wiping_token move_assigned{target}; + move_assigned = std::move(prepared); + // NOLINTEND(bugprone-use-after-move) + } + BOOST_TEST_EQ(test::wipes.count, 0U); + // The scratch is still the original's: its result is the text it holds, once. + // NOLINTNEXTLINE(bugprone-use-after-move) + BOOST_TEST_EQ(prepared.result().size(), 40U); + BOOST_TEST_EQ(test::wipes.count, 1U); + BOOST_TEST(target == std::string(40, 'x')); +} + +void a_secret_shrink_wipes_the_tail() { + // shrinking asks for one character more than it writes: a secret operation's shrink wipes the + // tail it cuts. + secure::secret<2> const secret_input = make_short_secret(); + test::clear_wipes(); + auto const returned = codecs::encode(test::shrinking, secret_input, tokens::return_string); + BOOST_TEST(returned.value() == "abpp"); + BOOST_TEST(test::wiped_of_size(1)); + test::clear_wipes(); + auto const fixed_text = codecs::encode(test::shrinking, secret_input, tokens::fixed<8>{}); + BOOST_TEST(fixed_text.value().view() == "abpp"); + BOOST_TEST(test::wiped_of_size(1)); + // The fixed token's own copy of the text is wiped once the result has it. + BOOST_TEST(test::wiped_of_size(4)); + std::string appended = "kept"; + test::clear_wipes(); + BOOST_TEST( + codecs::encode(test::shrinking, secret_input, tokens::append_to(appended)).has_value()); + BOOST_TEST(appended == "keptabpp"); + BOOST_TEST(test::wiped_of_size(1)); + std::string assigned = "kept"; + test::clear_wipes(); + BOOST_TEST( + codecs::encode(test::shrinking, secret_input, tokens::assign_to(assigned)).has_value()); + BOOST_TEST(assigned == "abpp"); + BOOST_TEST(test::wiped_of_size(5)); +} + +void a_public_operation_wipes_nothing() { + // Through each token of codecs', whether the conversion fails or shrinks. + std::array const public_input{0x01, 0xff}; + std::string appended = "kept"; + std::string assigned = "kept"; + std::vector public_bytes{9}; + test::clear_wipes(); + BOOST_TEST(codecs::encode(test::shrinking, public_input, tokens::return_string).has_value()); + BOOST_TEST(codecs::encode(test::shrinking, public_input, tokens::fixed<8>{}).has_value()); + BOOST_TEST( + codecs::encode(test::shrinking, public_input, tokens::append_to(appended)).has_value()); + BOOST_TEST( + codecs::encode(test::shrinking, public_input, tokens::assign_to(assigned)).has_value()); + BOOST_TEST( + !codecs::encode(test::be16, test::failing_number{1}, tokens::return_string).has_value()); + BOOST_TEST( + !codecs::encode(test::be16, test::failing_number{1}, tokens::fixed<8>{}).has_value()); + BOOST_TEST(!codecs::encode(test::be16, test::failing_number{1}, tokens::append_to(public_bytes)) + .has_value()); + BOOST_TEST(!codecs::encode(test::be16, test::failing_number{1}, tokens::assign_to(public_bytes)) + .has_value()); + BOOST_TEST_EQ(test::wipes.count, 0U); +} + +void a_value_codecs_secret_arithmetic_runs_in_a_secret_operation() { + // R7 for a value codec: the core calls its overloads that take secret_tag first in a secret + // operation, whether the value, the value codec or the token makes it secret, and never in a + // public one. + tagged_value_calls = {}; + auto const public_bytes = codecs::encode(tagged_values, tagged_number{0x1234}); + BOOST_TEST(public_bytes.has_value()); + std::array buffer{}; + BOOST_TEST(codecs::encode(tagged_values, tagged_number{0x1234}, std::span{buffer}).has_value()); + BOOST_TEST_EQ(codecs::encoded_size(tagged_values, tagged_number{0x1234}), 2U); + BOOST_TEST(codecs::decode(tagged_values, buffer).value() == + tagged_number{0x1234}); + BOOST_TEST_EQ(tagged_value_calls.total(), 0U); + // The secret token: a public value, the secret column, the secret encoded_size and encode. + auto const through_token = codecs::encode(tagged_values, tagged_number{0x1234}, tokens::secret); + static_assert( + std::is_same_v> const>); + BOOST_TEST(std::ranges::equal(through_token.value().view(), buffer)); + BOOST_TEST_EQ(tagged_value_calls.encoded_size, 1U); + BOOST_TEST_EQ(tagged_value_calls.encode, 1U); + BOOST_TEST_EQ(tagged_value_calls.total(), 2U); + // A token of a program's own whose secret is true, its result its own. + tagged_value_calls = {}; + auto const own = + codecs::encode(tagged_values, tagged_number{0x1234}, test::secret_byte_token{}); + static_assert(std::is_same_v> const>); + BOOST_TEST(std::ranges::equal(own.value(), buffer)); + BOOST_TEST_EQ(tagged_value_calls.encoded_size, 1U); + BOOST_TEST_EQ(tagged_value_calls.encode, 1U); + BOOST_TEST_EQ(tagged_value_calls.total(), 2U); + // A secret value, in each form: the default result, the buffer form, the size, the typed + // decode. + tagged_value_calls = {}; + auto const secret_encoded = codecs::encode(tagged_values, tagged_secret_number{0x1234}); + static_assert( + std::is_same_v> const>); + BOOST_TEST(std::ranges::equal(secret_encoded.value().view(), buffer)); + BOOST_TEST_EQ(tagged_value_calls.encoded_size, 1U); + BOOST_TEST_EQ(tagged_value_calls.encode, 1U); + tagged_value_calls = {}; + std::array secret_buffer{}; + BOOST_TEST_EQ( + codecs::encode(tagged_values, tagged_secret_number{0x1234}, std::span{secret_buffer}) + .value(), + 2U); + BOOST_TEST_EQ(codecs::encoded_size(tagged_values, tagged_secret_number{0x1234}), 2U); + BOOST_TEST_EQ(tagged_value_calls.encoded_size, 2U); + BOOST_TEST_EQ(tagged_value_calls.encode, 1U); + tagged_value_calls = {}; + BOOST_TEST(codecs::decode(tagged_values, secret_buffer).value() == + tagged_secret_number{0x1234}); + BOOST_TEST_EQ(tagged_value_calls.decode, 1U); + BOOST_TEST_EQ(tagged_value_calls.total(), 1U); +} + +// The core's check of a value codec's secret overloads (R7): those that take the core's arguments +// and return what the functions without the tag return pass; one of other parameters is found +// (refused_secret_value_overload is the message case of another return type). +static_assert(codecs::detail::secret_value_overloads_match); +static_assert(codecs::detail::takes_secret_value_decode); +static_assert(!codecs::detail::has_secret_value_decode); +static_assert(!codecs::detail::secret_value_overloads_match); + +// The secret overloads are noexcept, as the forms that call them are when nothing allocates. +static_assert(noexcept(codecs::encode(tagged_values, tagged_number{}, tokens::secret))); +static_assert(noexcept(codecs::encode(tagged_values, tagged_secret_number{}))); +static_assert(noexcept(codecs::encode(tagged_values, tagged_secret_number{}, + std::declval>()))); +static_assert(noexcept(codecs::decode(tagged_values, + std::array{}))); + +void the_secret_arithmetic_runs_in_a_secret_operation_alone() { + // A public operation runs the format's public arithmetic. + test::tagged_calls.reset(); + std::array const public_bytes = key_bytes(); + std::string const text_value = key_text(); + BOOST_TEST(codecs::encode(test::tagged_letters, public_bytes).has_value()); + BOOST_TEST(codecs::decode(test::tagged_letters, text_value).has_value()); + BOOST_TEST( + codecs::encode(test::tagged_letters, public_bytes, tokens::return_string).has_value()); + BOOST_TEST((codecs::decode>(test::tagged_letters, text_value) + .has_value())); + BOOST_TEST_EQ(test::tagged_calls.total(), 0U); + // Each secret operation runs its secret arithmetic, once each. + secure::secret<32> const key = make_secret(); + auto const encoded = codecs::encode(test::tagged_letters, key); + BOOST_TEST(encoded.value().view() == text_value); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.encode, 1U); + test::tagged_calls.reset(); + auto const decoded = codecs::decode>(test::tagged_letters, text_value); + BOOST_TEST(decoded.has_value()); + BOOST_TEST_EQ(test::tagged_calls.decoded_size, 1U); + BOOST_TEST_EQ(test::tagged_calls.decode, 1U); + test::tagged_calls.reset(); + auto const through_token = + codecs::decode(test::tagged_letters, std::string_view{text_value}, tokens::secret); + BOOST_TEST(through_token.has_value()); + auto const heap_encoded = + codecs::encode(test::tagged_letters, std::vector(2), tokens::secret); + BOOST_TEST(heap_encoded.value().view() == "aaaa"); + BOOST_TEST_EQ(test::tagged_calls.total(), 4U); + // The sizes and the buffer form of a secret input. + test::tagged_calls.reset(); + BOOST_TEST_EQ(codecs::encoded_size(test::tagged_letters, key), 64U); + std::array buffer{}; + BOOST_TEST_EQ(codecs::encode(test::tagged_letters, key, std::span{buffer}).value(), 64U); + BOOST_TEST_EQ(test::tagged_calls.encoded_size, 2U); + BOOST_TEST_EQ(test::tagged_calls.encode, 1U); + // A format with no secret overloads runs its own arithmetic in a secret operation. + auto const plain_encoded = codecs::encode(test::letters, key); + BOOST_TEST(plain_encoded.value().view() == text_value); +} + +void the_fixed_secret_forms_allocate_nothing() { + key32 const key = make_key32(); + secure::secret<32> const secret_key = make_secret(); + std::array const public_bytes = key_bytes(); + auto const fixed_text = codecs::encode(test::letters, public_bytes); + bool volatile verdict = false; + test::expect_no_allocation("the fixed secret forms", [&] { + auto const from_key = codecs::encode(test::letters, key); + auto const from_secret = codecs::encode(test::letters, secret_key); + auto const through_token = codecs::encode(test::letters, public_bytes, tokens::secret); + auto const into_secret = + codecs::decode>(test::letters, fixed_text.value().view()); + auto const into_bytes = + codecs::decode>(test::letters, fixed_text.value().view()); + auto const into_key = codecs::decode(test::letters, fixed_text.value().view()); + auto const back = codecs::decode(test::letters, fixed_text.value(), tokens::secret); + auto const number = codecs::encode(secret_values, secret_number{7}); + verdict = from_key.has_value() && from_secret.has_value() && through_token.has_value() && + into_secret.has_value() && into_bytes.has_value() && into_key.has_value() && + back.has_value() && number.has_value(); + }); + BOOST_TEST(verdict); +} + +/** + The spec's scenarios on hex: "A secret type encodes to a wiped text", key32 to secret_text<64>, + whose storage reads zero through the wipe seam after its destruction; "secure's secret is + secret", secure::secret<32> to secret_text<64> and back by decode>, both + secret, with no heap; and "Decode follows the requested type", decode>, secret, + its temporary wiped, with no heap. +*/ +void the_spec_scenarios_on_hex() { + std::string const expected = + codecs::encode(formats::hex, key_bytes(), tokens::return_string).value(); + key32 const key = make_key32(); + void const* storage = nullptr; + { + auto const encoded = codecs::encode(formats::hex, key); + static_assert( + std::is_same_v> const>); + BOOST_TEST(encoded.has_value() && encoded.value().view() == expected); + storage = encoded.value().data(); + test::clear_wipes(); + } + BOOST_TEST(test::wiped(storage, 64)); + + secure::secret<32> const secret_key = make_secret(); + static_assert(std::is_same_v>>); + static_assert( + std::is_same_v>(formats::hex, expected)), + codecs::result>>); + bool volatile verdict = false; + test::expect_no_allocation("hex of secure's secret and back", [&] { + auto const encoded = codecs::encode(formats::hex, secret_key); + test::clear_wipes(); + auto const decoded = + codecs::decode>(formats::hex, encoded.value().view()); + std::span const decoded_bytes = + decoded.has_value() ? decoded.value().bytes() : std::span{}; + verdict = encoded.has_value() && encoded.value().view() == expected && + std::ranges::equal(decoded_bytes, key_bytes()) && + test::wiped_elsewhere(decoded_bytes.data(), 32); + }); + BOOST_TEST(verdict); + + verdict = false; + test::expect_no_allocation("decode> of hex", [&] { + test::clear_wipes(); + auto const decoded = codecs::decode>(formats::hex, expected); + verdict = decoded.has_value() && std::ranges::equal(decoded.value().view(), key_bytes()) && + test::wiped_elsewhere(decoded.value().data(), 32); + }); + BOOST_TEST(verdict); + // The errors reach the caller, from a secret operation too. + BOOST_TEST(codecs::decode>(formats::hex, "abc").error() == + codecs::error::invalid_length); + BOOST_TEST(codecs::decode>(formats::hex, "zz").error() == + codecs::error::invalid_character); +} + +} // namespace +} // namespace secret_operation + +int main() { + secret_operation::a_secret_type_encodes_to_a_wiped_text(); + secret_operation::secures_secret_is_secret(); + secret_operation::a_libraries_secret_type_has_its_temporary_wiped(); + secret_operation::a_secret_result_type_is_secret(); + secret_operation::the_secret_token_both_ways(); + secret_operation::a_secret_value_codec(); + secret_operation::a_failed_secret_operation_into_assign_to(); + secret_operation::a_programs_own_secret_token_makes_the_operation_secret(); + secret_operation::the_core_tokens_wipe_what_they_do_not_give(); + secret_operation::an_assigning_tokens_copy_and_move_take_the_target_alone(); + secret_operation::a_secret_shrink_wipes_the_tail(); + secret_operation::a_public_operation_wipes_nothing(); + secret_operation::the_secret_arithmetic_runs_in_a_secret_operation_alone(); + secret_operation::a_value_codecs_secret_arithmetic_runs_in_a_secret_operation(); + secret_operation::the_fixed_secret_forms_allocate_nothing(); + secret_operation::the_spec_scenarios_on_hex(); + return boost::report_errors(); +} diff --git a/test/secret_stream_test.cpp b/test/secret_stream_test.cpp new file mode 100644 index 0000000..8e8e1bd --- /dev/null +++ b/test/secret_stream_test.cpp @@ -0,0 +1,1073 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Secret streams (D21), through both of secure's seams: support/timing_seam.hpp counts the timing +// guards codecs enters, and support/wipe_recorder.hpp records every wipe. A transformer is secret +// when it was made with secret_operation (format_encoder and format_decoder) or a part of it is +// (piped, each, buffered): it is move-only, each of its calls enters a guard of codecs', which +// nests with its parts' own, and its pending state (letters' carries, the pipe's intermediate, the +// storage of each and buffered) is wiped on reset, on destruction and in the moved-from object; a +// drain of a secret transformer wipes its own buffer. Where the guard acts +// (WEBCPP_SECURE_TIMING_COVERED) and the CPU has DIT, dit_probe, a secret transformer of the +// test's own, finds DIT set in each conversion call of a pipe, an each and a buffered of it, and +// DIT is clear after each call (D15, ruling R4); the program prints whether DIT applies. The spec's +// scenarios "A secret stream's state is wiped" and "Guards nest in a secret pipe", here on letters +// and on base64 and hex; every moved-from secret transformer converts a new input from the start +// (Review Focus 5). + +#include "support/timing_seam.hpp" + +#include "support/wipe_recorder.hpp" + +#include "support/timing_dit.hpp" + +#include "support/allocators.hpp" +#include "support/letters.hpp" +#include "support/samples.hpp" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace codecs = webcpp::codecs; +namespace secure = webcpp::secure; +namespace test = webcpp::codecs::test; + +namespace secret_stream { +namespace { + +/** The calls of every dit_probe, and those that found DIT set. */ +struct dit_record { + /** The conversion calls. */ + std::size_t calls = 0; + /** The conversion calls that found DIT set. */ + std::size_t calls_with_dit = 0; +}; + +/** The calls of every dit_probe since the test last cleared them. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the test's record +dit_record dit_seen; + +/** Counts a conversion call of a dit_probe, and whether it found DIT set. */ +void record_dit() noexcept { + ++dit_seen.calls; + if (secure::dit_is_set()) { + ++dit_seen.calls_with_dit; + } +} + +/** + A secret transformer of the test's own, std::uint8_t to std::uint8_t, one-shot and stream, that + copies its input and records whether DIT is set in each conversion call (`transform`, `send`, + `receive`, `flush`); it holds no guard of its own, so that DIT is set only by the composition + that holds it. It borrows what `send` accepts and copies it during `receive`. +*/ +class dit_probe { +public: + /** The bytes read. */ + using input_type = std::uint8_t; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** As many bytes out as in. */ + [[nodiscard]] static constexpr std::size_t max_output_size(std::size_t input_size) noexcept { + return input_size; + } + + /** Copies `input` into `output`. */ + [[nodiscard]] static codecs::result transform( + std::span input, std::span output) noexcept { + record_dit(); + if (output.size() < input.size()) { + return codecs::error::output_too_small; + } + std::ranges::copy(input, output.begin()); + return input.size(); + } + + /** Borrows all of `input` in `needs_input`. */ + [[nodiscard]] codecs::result send(std::span input) noexcept { + record_dit(); + if (state() != codecs::flow::needs_input) { + return codecs::step{.count = 0, .flow = state()}; + } + borrowed_ = input; + return codecs::step{.count = input.size(), .flow = state()}; + } + + /** Copies what it borrows into `output`, as it has room. */ + [[nodiscard]] codecs::result receive(std::span output) noexcept { + record_dit(); + std::size_t const count = std::min(borrowed_.size(), output.size()); + std::ranges::copy(borrowed_.first(count), output.begin()); + borrowed_ = borrowed_.subspan(count); + return codecs::step{.count = count, .flow = state()}; + } + + /** Ends the input. */ + [[nodiscard]] codecs::result flush() noexcept { + record_dit(); + flushed_ = true; + return state(); + } + + /** Back to `needs_input`, nothing borrowed. */ + void reset() noexcept { + borrowed_ = {}; + flushed_ = false; + } + +private: + /** The state the next call sees. */ + [[nodiscard]] codecs::flow state() const noexcept { + if (!borrowed_.empty()) { + return codecs::flow::output_pending; + } + return flushed_ ? codecs::flow::finished : codecs::flow::needs_input; + } + + /** The bytes `send` accepted and `receive` has not copied. */ + std::span borrowed_; + /** Whether `flush` ended the input. */ + bool flushed_ = false; +}; + +/** + A one-shot transformer of the test's own, `std::uint8_t` to `std::uint8_t`, that states no output + size, so that a heap output starts at the input's size and doubles: it writes every byte of its + input twice, as many as fit, and reports `output_too_small` after writing a part. Secret when + `Secret`. +*/ +template +class doubling_probe { +public: + /** The bytes read. */ + using input_type = std::uint8_t; + /** The bytes written. */ + using output_type = std::uint8_t; + + /** Writes each byte of `input` twice into `output`, as many as fit. */ + [[nodiscard]] static codecs::result transform( + std::span input, std::span output) noexcept { + std::size_t written = 0; + for (std::uint8_t const byte : input) { + if (output.size() - written < 2) { + return codecs::error::output_too_small; + } + output[written++] = byte; + output[written++] = byte; + } + return written; + } +}; + +} // namespace +} // namespace secret_stream + +/** dit_probe is secret. */ +template <> +struct webcpp::codecs::is_secret : std::true_type {}; + +/** A secret doubling_probe is secret. */ +template <> +struct webcpp::codecs::is_secret> : std::true_type {}; + +namespace secret_stream { +namespace { + +using secret_encoder = decltype(codecs::encoder(test::letters, codecs::secret_operation)); +using secret_decoder = decltype(codecs::decoder(test::letters, codecs::secret_operation)); +using public_encoder = decltype(codecs::encoder(test::letters)); +using public_decoder = decltype(codecs::decoder(test::letters)); +using secret_pipe = codecs::piped>; +using mixed_pipe = codecs::piped>; +using public_pipe = codecs::piped>; +using secret_each = codecs::each>; +using public_each = codecs::each>; +using secret_buffered = codecs::buffered>; +using public_buffered = codecs::buffered>; + +// A transformer is secret when it was made with secret_operation, or a part of it is (D21). +static_assert(codecs::is_secret_v && codecs::is_secret_v); +static_assert(!codecs::is_secret_v && !codecs::is_secret_v); +static_assert(codecs::is_secret_v && codecs::is_secret_v); +static_assert(codecs::is_secret_v< + codecs::piped>>); +static_assert(!codecs::is_secret_v); +static_assert(codecs::is_secret_v && !codecs::is_secret_v); +static_assert(codecs::is_secret_v>); +static_assert(codecs::is_secret_v && !codecs::is_secret_v); +static_assert(codecs::is_secret_v>); +static_assert(codecs::is_secret_v>>); +static_assert(std::same_as>); +static_assert(codecs::is_secret_v>); + +/** + Whether `T` is move-only: movable without throwing, and neither copy constructible nor + assignable. +*/ +template +inline constexpr bool move_only_v = + std::is_nothrow_move_constructible_v && std::is_nothrow_move_assignable_v && + !std::is_copy_constructible_v && !std::is_copy_assignable_v; + +// A secret transformer is move-only (D21); its public twin keeps its copy. +static_assert(move_only_v && move_only_v); +static_assert(move_only_v && move_only_v); +static_assert(move_only_v && move_only_v); +static_assert(move_only_v>>); +static_assert(move_only_v>>); +static_assert(!std::is_copy_constructible_v>); +static_assert(!std::is_copy_constructible_v>); +static_assert(!std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v && + std::is_copy_assignable_v); +static_assert(std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v && + std::is_copy_constructible_v); +static_assert(std::is_copy_constructible_v); + +// A public stream over trivially destructible parts stays trivially destructible: only a secret +// one has a destructor that wipes. +static_assert(std::is_trivially_destructible_v && + std::is_trivially_destructible_v && + std::is_trivially_destructible_v); +static_assert(!std::is_trivially_destructible_v && + !std::is_trivially_destructible_v && + !std::is_trivially_destructible_v); + +// A secret transformer keeps its concepts and its noexcept calls. +static_assert(codecs::stream_transformer && + codecs::one_shot_transformer); +static_assert(codecs::stream_transformer && codecs::stream_transformer && + codecs::stream_transformer); +static_assert(noexcept(std::declval().receive(std::declval>()))); +static_assert(noexcept(std::declval().receive(std::declval>()))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); + +/** The 31 secret bytes every check converts: 0x00, 0x11, ... with 0xf7 and 0x08 among them. */ +std::array thirty_one_bytes() { + std::array bytes{}; + for (std::size_t index = 0; index < bytes.size(); ++index) { + bytes[index] = static_cast((index * 0x11U) + (index / 16U)); + } + return bytes; +} + +/** + Checks the guards a call entered, from `before`: at least one of codecs' for a call of a secret + transformer (`Secret`), none at all for a public one; and DIT clear after it, the guards having + restored it. +*/ +template +void check_guards(std::size_t before, std::size_t all_before) { + if constexpr (Secret) { + BOOST_TEST_GT(test::timing_entries, before); + } else { + BOOST_TEST_EQ(test::timing_all_entries, all_before); + } + BOOST_TEST(!secure::dit_is_set()); +} + +/** + Runs `call`, one call of a transformer, and checks its guards as @ref check_guards does: at least + one of codecs' when `Secret`, the default, none otherwise. + + @return What the call returned. +*/ +template +auto guarded(Call call) { + std::size_t const before = test::timing_entries; + std::size_t const all_before = test::timing_all_entries; + if constexpr (std::is_void_v) { + call(); + check_guards(before, all_before); + } else { + auto const outcome = call(); + check_guards(before, all_before); + return outcome; + } +} + +/** + Streams `input` through `stream` from the state it is in: sends what it accepts, receives into + spans of `span_size` elements, flushes once the input is sent, until it is finished; every call + is checked by @ref guarded, a guard of codecs' entered when the stream is secret and none when it + is public, and the output appended to `output`. + + @return Whether every call succeeded and the stream finished. +*/ +template +bool stream_guarded(Stream& stream, std::span input, + std::size_t span_size, Output& output) { + using output_type = Stream::output_type; + constexpr bool secret = codecs::is_secret_v; + std::array buffer{}; + std::size_t sent = 0; + bool flushed = false; + codecs::flow state = codecs::flow::needs_input; + for (std::size_t calls = 0; calls < 100000; ++calls) { + if (state == codecs::flow::finished) { + return true; + } + if (state == codecs::flow::needs_input && sent < input.size()) { + auto const accepted = guarded([&] { return stream.send(input.subspan(sent)); }); + if (!accepted.has_value()) { + return false; + } + sent += accepted->count; + state = accepted->flow; + } else if (state == codecs::flow::needs_input && !flushed) { + auto const ended = guarded([&] { return stream.flush(); }); + if (!ended.has_value()) { + return false; + } + flushed = true; + state = *ended; + } else { + auto const received = + guarded([&] { return stream.receive(std::span{buffer}.first(span_size)); }); + if (!received.has_value()) { + return false; + } + output.insert(output.end(), buffer.begin(), + buffer.begin() + static_cast(received->count)); + state = received->flow; + if (state == codecs::flow::needs_input && flushed) { + return false; + } + } + } + return false; +} + +/** The text a stream of characters gives for `input`, through @ref stream_guarded. */ +template +std::string text_of(Stream& stream, std::span input, std::size_t span_size) { + std::string output; + BOOST_TEST(stream_guarded(stream, input, span_size, output)); + return output; +} + +/** The bytes a stream of bytes gives for `input`, through @ref stream_guarded. */ +template +std::vector bytes_of(Stream& stream, std::span input, + std::size_t span_size) { + std::vector output; + BOOST_TEST(stream_guarded(stream, input, span_size, output)); + return output; +} + +/** + Every call of a secret pipe of two secret letters encoders over 31 bytes enters a guard of + codecs' and leaves DIT clear, `reset` included, and the pipe is move-only; each and buffered over + a secret encoder the same; the output is the one-shot form's. +*/ +void every_call_of_a_secret_composition_is_guarded() { + std::array const input = thirty_one_bytes(); + test::force_dit(false); + for (std::size_t const span_size : {std::size_t{1}, std::size_t{3}, std::size_t{64}}) { + auto piped = codecs::pipe(codecs::encoder(test::letters, codecs::secret_operation), + codecs::encoder(test::letters, codecs::secret_operation)); + static_assert(std::same_as); + BOOST_TEST_EQ(text_of(piped, input, span_size), test::letters_of_letters(input)); + guarded([&] { piped.reset(); }); + BOOST_TEST_EQ(text_of(piped, input, span_size), test::letters_of_letters(input)); + + // One secret part makes the pipe secret: its own guard covers the public part's calls. + auto mixed = codecs::pipe(codecs::encoder(test::letters), + codecs::encoder(test::letters, codecs::secret_operation)); + BOOST_TEST_EQ(text_of(mixed, input, span_size), test::letters_of_letters(input)); + + auto each = codecs::each(codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<2>); + BOOST_TEST_EQ(text_of(each, input, span_size), test::letters_of(input)); + guarded([&] { each.reset(); }); + auto heap_each = codecs::each(codecs::encoder(test::letters, codecs::secret_operation)); + BOOST_TEST_EQ(text_of(heap_each, input, span_size), test::letters_of(input)); + + auto buffered = codecs::buffered(codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<31>); + BOOST_TEST_EQ(text_of(buffered, input, span_size), test::letters_of(input)); + guarded([&] { buffered.reset(); }); + auto heap_buffered = + codecs::buffered(codecs::encoder(test::letters, codecs::secret_operation)); + BOOST_TEST_EQ(text_of(heap_buffered, input, span_size), test::letters_of(input)); + } +} + +/** + Every call of a secret format transformer enters a guard of codecs': the four stream calls and + `transform` and `output_size`, of the encoder and of the decoder; a public one enters none. +*/ +void every_call_of_a_secret_format_transformer_is_guarded() { + std::array const input = thirty_one_bytes(); + std::string const text = test::letters_of(input); + test::force_dit(false); + auto encoder = codecs::encoder(test::letters, codecs::secret_operation); + BOOST_TEST_EQ(text_of(encoder, input, 5), text); + guarded([&] { encoder.reset(); }); + std::array text_buffer{}; + BOOST_TEST(guarded([&] { return encoder.transform(input, text_buffer); }).has_value()); + BOOST_TEST_EQ(guarded([&] { return encoder.output_size(input); }), 62U); + auto decoder = codecs::decoder(test::letters, codecs::secret_operation); + std::vector decoded; + BOOST_TEST(stream_guarded(decoder, test::characters_of(text), 7, decoded)); + BOOST_TEST(std::ranges::equal(decoded, input)); + guarded([&] { decoder.reset(); }); + std::array byte_buffer{}; + BOOST_TEST(guarded([&] { + return decoder.transform(test::characters_of(text), byte_buffer); + }).has_value()); + BOOST_TEST_EQ(guarded([&] { return decoder.output_size(test::characters_of(text)); }), 31U); + + // A public transformer enters no guard. + std::size_t const before = test::timing_all_entries; + auto public_letters = codecs::encoder(test::letters); + BOOST_TEST(public_letters.send(input).has_value()); + BOOST_TEST(public_letters.receive(text_buffer).has_value()); + BOOST_TEST(public_letters.flush().has_value()); + public_letters.reset(); + BOOST_TEST(public_letters.transform(input, text_buffer).has_value()); + auto public_pipe_of_letters = + codecs::pipe(codecs::encoder(test::letters), codecs::encoder(test::letters)); + BOOST_TEST(public_pipe_of_letters.send(input).has_value()); + public_pipe_of_letters.reset(); + BOOST_TEST_EQ(test::timing_all_entries, before); +} + +/** + Where the guard acts and the CPU has DIT, a dit_probe finds DIT set in each conversion call of a + pipe of two, of an each and of a buffered of one, which hold the guard, and DIT is clear after + each call; elsewhere it never finds DIT set (D15, ruling R4: the guards nest, and the count of + engaged guards returns to zero after each call). +*/ +void dit_is_set_in_every_call_of_a_secret_composition() { + std::array const input = thirty_one_bytes(); + std::vector const expected(input.begin(), input.end()); + bool const applies = test::dit_applies(); + test::force_dit(false); + BOOST_TEST(!secure::dit_is_set()); + + dit_seen = dit_record{}; + auto piped = codecs::pipe(dit_probe{}, dit_probe{}, codecs::capacity<4>); + BOOST_TEST(bytes_of(piped, input, 3) == expected); + auto each = codecs::each(dit_probe{}, codecs::capacity<1>); + BOOST_TEST(bytes_of(each, input, 2) == expected); + auto buffered = codecs::buffered(dit_probe{}, codecs::capacity<31>); + BOOST_TEST(bytes_of(buffered, input, 5) == expected); + auto heap_buffered = codecs::buffered(dit_probe{}); + BOOST_TEST(bytes_of(heap_buffered, input, 64) == expected); + + // Printed, so that a lane's log shows whether the DIT checks ran on its target. + std::printf("secret_stream: DIT %s; dit_probe calls %zu, with DIT set %zu\n", + applies ? "applies" : "does not apply", dit_seen.calls, dit_seen.calls_with_dit); + BOOST_TEST_GT(dit_seen.calls, 40U); + BOOST_TEST_EQ(dit_seen.calls_with_dit, applies ? dit_seen.calls : 0U); + BOOST_TEST(!secure::dit_is_set()); + + // A probe called outside any guard finds DIT clear: the check above is not vacuous. + dit_seen = dit_record{}; + std::array copied{}; + BOOST_TEST(dit_probe::transform(input, copied).has_value()); + BOOST_TEST_EQ(dit_seen.calls, 1U); + BOOST_TEST_EQ(dit_seen.calls_with_dit, 0U); +} + +/** + The spec's scenario "A secret stream's state is wiped", on letters: 31 secret bytes into a secret + encoder, received into spans of one letter, so that one letter waits; the wipe seam records the + waiting letter's wipe in the source after a move, at reset and at the destruction of each; the + moved-to encoder delivers the rest, and the moved-from one converts a new input from the start + (Review Focus 5). +*/ +void a_secret_encoders_pending_state_is_wiped() { + std::array const input = thirty_one_bytes(); + std::string const text = test::letters_of(input); + std::optional source; + source.emplace(test::letters); + auto const sent = source->send(input); + BOOST_TEST(sent.has_value() && sent->count == input.size()); + std::array letter{}; + auto const first = source->receive(letter); + BOOST_TEST(first.has_value() && first->count == 1 && + first->flow == codecs::flow::output_pending); + BOOST_TEST_EQ(letter[0], text[0]); + + // The move takes the waiting letter, and wipes it in the source. + test::clear_wipes(); + std::optional target; + target.emplace(std::move(*source)); + BOOST_TEST_EQ(test::wipes_in(*source, 1), 1U); + std::string rest; + BOOST_TEST(stream_guarded(*target, std::span{}, 1, rest)); + BOOST_TEST_EQ(text.substr(0, 1) + rest, text); + + // The moved-from encoder converts a new input from the start. + BOOST_TEST_EQ(text_of(*source, input, 1), text); + + // reset wipes; the reset encoder converts again. + BOOST_TEST(target->send(input).has_value()); + BOOST_TEST(target->receive(letter).has_value()); + test::clear_wipes(); + target->reset(); + BOOST_TEST_EQ(test::wipes_in(*target, 1), 1U); + BOOST_TEST_EQ(text_of(*target, input, 2), text); + + // The destruction of each wipes. + BOOST_TEST(target->send(input).has_value()); + BOOST_TEST(target->receive(letter).has_value()); + BOOST_TEST_EQ(test::wipes_at_destruction(target, 1), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(source, 1), 1U); + + // A move assignment wipes the source as the move does. + secret_encoder assigned{test::letters}; + secret_encoder moved{test::letters}; + BOOST_TEST(moved.send(input).has_value()); + BOOST_TEST(moved.receive(letter).has_value()); + test::clear_wipes(); + assigned = std::move(moved); + // NOLINTNEXTLINE(bugprone-use-after-move,hicpp-invalid-access-moved): the case under test + BOOST_TEST_EQ(test::wipes_in(moved, 1), 1U); + BOOST_TEST_EQ(text_of(moved, input, 3), text); +} + +/** + A secret decoder's held letter and error mask are wiped likewise: a byte each, in the source after + a move, at reset and at destruction; the moved-to decoder delivers the rest and the moved-from one + decodes a new text from the start (Review Focus 5). +*/ +void a_secret_decoders_pending_state_is_wiped() { + std::array const input = thirty_one_bytes(); + std::vector const expected(input.begin(), input.end()); + std::string const text = test::letters_of(input); + std::optional source; + source.emplace(test::letters); + // Three letters: a byte of the first two, the third held. + BOOST_TEST(source->send(test::characters_of(text).first(3)).has_value()); + std::array byte{}; + auto const first = source->receive(byte); + BOOST_TEST(first.has_value() && first->count == 1 && first->flow == codecs::flow::needs_input); + BOOST_TEST_EQ(byte[0], input[0]); + + test::clear_wipes(); + std::optional target; + target.emplace(std::move(*source)); + BOOST_TEST_EQ(test::wipes_in(*source, 1), 2U); + std::vector rest{input[0]}; + BOOST_TEST(stream_guarded(*target, test::characters_of(text).subspan(3), 1, rest)); + BOOST_TEST(rest == expected); + + std::vector again; + BOOST_TEST(stream_guarded(*source, test::characters_of(text), 1, again)); + BOOST_TEST(again == expected); + + test::clear_wipes(); + target->reset(); + BOOST_TEST_EQ(test::wipes_in(*target, 1), 2U); + BOOST_TEST_EQ(test::wipes_at_destruction(target, 1), 2U); + BOOST_TEST_EQ(test::wipes_at_destruction(source, 1), 2U); +} + +/** + The spec's scenario "Guards nest in a secret pipe", on base64 and hex: 31 secret bytes through + `pipe(encoder(base64, secret_operation), encoder(hex, secret_operation))`, and through each and + buffered over a secret base64 encoder, enter a guard of codecs' in every call and leave DIT + clear after it, and equal the one-shot over; a dit_probe after the base64 link in a pipe, which + holds no guard of its own, finds DIT set in each of its calls where DIT applies, so that the + nested guard of the base64 link left it set when it ended (the count of engaged guards returns + to zero after each call). +*/ +void base64_guards_nest_in_a_secret_pipe() { + namespace formats = webcpp::codecs::formats; + std::array const input = thirty_one_bytes(); + std::string const base64_text = + codecs::encode(formats::base64, input, codecs::tokens::return_string).value(); + std::string const expected = codecs::encode(codecs::over{formats::hex, formats::base64}, input, + codecs::tokens::return_string) + .value(); + test::force_dit(false); + for (std::size_t const span_size : {std::size_t{1}, std::size_t{3}, std::size_t{64}}) { + auto piped = codecs::pipe(codecs::encoder(formats::base64, codecs::secret_operation), + codecs::encoder(formats::hex, codecs::secret_operation)); + BOOST_TEST_EQ(text_of(piped, input, span_size), expected); + guarded([&] { piped.reset(); }); + BOOST_TEST_EQ(text_of(piped, input, span_size), expected); + + // One secret link makes the pipe secret. + auto mixed = codecs::pipe(codecs::encoder(formats::base64), + codecs::encoder(formats::hex, codecs::secret_operation)); + BOOST_TEST_EQ(text_of(mixed, input, span_size), expected); + + auto buffered = codecs::buffered(codecs::encoder(formats::base64, codecs::secret_operation), + codecs::capacity<31>); + BOOST_TEST_EQ(text_of(buffered, input, span_size), base64_text); + guarded([&] { buffered.reset(); }); + auto heap_buffered = + codecs::buffered(codecs::encoder(formats::base64, codecs::secret_operation)); + BOOST_TEST_EQ(text_of(heap_buffered, input, span_size), base64_text); + + // each: a byte at a time, which base64 pads, as the one-shot form of each byte does. + std::string per_byte; + for (std::uint8_t const byte : input) { + per_byte += codecs::encode(formats::base64, std::array{byte}, + codecs::tokens::return_string) + .value(); + } + auto each = codecs::each(codecs::encoder(formats::base64, codecs::secret_operation), + codecs::capacity<4>); + BOOST_TEST_EQ(text_of(each, input, span_size), per_byte); + guarded([&] { each.reset(); }); + } + + // The decoders, too: base64 text into bytes and hex text into base64, secret. + auto decoder = codecs::decoder(formats::base64, codecs::secret_operation); + std::vector decoded; + BOOST_TEST(stream_guarded(decoder, test::characters_of(base64_text), 7, decoded)); + BOOST_TEST(std::ranges::equal(decoded, input)); + auto unpiped = codecs::pipe(codecs::decoder(formats::hex, codecs::secret_operation), + codecs::decoder(formats::base64, codecs::secret_operation)); + std::vector back; + BOOST_TEST(stream_guarded(unpiped, test::characters_of(expected), 5, back)); + BOOST_TEST(std::ranges::equal(back, input)); + + // Where DIT applies, a probe after a secret base64 link finds it set. + bool const applies = test::dit_applies(); + dit_seen = dit_record{}; + auto probed = codecs::pipe(codecs::encoder(formats::base64, codecs::secret_operation), + dit_probe{}, codecs::capacity<8>); + std::vector probed_text; + BOOST_TEST(stream_guarded(probed, std::span{input}, 3, probed_text)); + BOOST_TEST(std::ranges::equal(probed_text, test::bytes_of(base64_text))); + BOOST_TEST_GT(dit_seen.calls, 10U); + BOOST_TEST_EQ(dit_seen.calls_with_dit, applies ? dit_seen.calls : 0U); + BOOST_TEST(!secure::dit_is_set()); +} + +/** + The spec's scenario "A secret stream's state is wiped", on base64: 31 secret bytes into a secret + base64 encoder leave one byte pending; the wipe seam records the wipe of the waiting bytes (3) + and characters (4) in the source after a move, at reset and at the destruction of each; every + call enters a guard and leaves DIT clear; the moved-to encoder delivers the last group with its + padding, and the moved-from one converts a new input from the start (Review Focus 5). The + decoder's six bytes of bits, masks and waiting byte likewise. +*/ +void a_secret_base64_streams_state_is_wiped() { + namespace formats = webcpp::codecs::formats; + using base64_secret_encoder = + decltype(codecs::encoder(formats::base64, codecs::secret_operation)); + using base64_secret_decoder = + decltype(codecs::decoder(formats::base64, codecs::secret_operation)); + std::array const input = thirty_one_bytes(); + std::string const text = + codecs::encode(formats::base64, input, codecs::tokens::return_string).value(); + std::optional source; + source.emplace(formats::base64); + BOOST_TEST(guarded([&] { return source->send(input); }).has_value()); + std::array characters{}; + auto const received = guarded([&] { return source->receive(characters); }); + BOOST_TEST(received.has_value() && received->count == 40 && + received->flow == codecs::flow::needs_input); + BOOST_TEST(std::string_view(characters.data(), 40) == std::string_view{text}.substr(0, 40)); + + // The move takes the waiting byte, and wipes it in the source. + test::clear_wipes(); + std::optional target; + target.emplace(std::move(*source)); + BOOST_TEST_EQ(test::wipes_in(*source, 3), 1U); + BOOST_TEST_EQ(test::wipes_in(*source, 4), 1U); + BOOST_TEST(guarded([&] { return target->flush(); }).has_value()); + std::string rest; + BOOST_TEST(stream_guarded(*target, std::span{}, 1, rest)); + BOOST_TEST_EQ(text.substr(0, 40) + rest, text); + + // The moved-from encoder converts a new input from the start. + BOOST_TEST_EQ(text_of(*source, input, 1), text); + + // reset wipes; the reset encoder converts again. + target->reset(); + BOOST_TEST(guarded([&] { return target->send(input); }).has_value()); + BOOST_TEST(guarded([&] { return target->receive(characters); }).has_value()); + test::clear_wipes(); + guarded([&] { target->reset(); }); + BOOST_TEST_EQ(test::wipes_in(*target, 3), 1U); + BOOST_TEST_EQ(test::wipes_in(*target, 4), 1U); + BOOST_TEST_EQ(text_of(*target, input, 2), text); + + // The destruction of each wipes. + target->reset(); + BOOST_TEST(target->send(input).has_value()); + BOOST_TEST(target->receive(characters).has_value()); + BOOST_TEST_EQ(test::wipes_at_destruction(target, 3), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(source, 3), 1U); + BOOST_TEST(!secure::dit_is_set()); + + // The decoder: a group's bits, the masks and the padding seen, six bytes wiped as one, and + // its two held and two waiting bytes. + std::optional decoder_source; + decoder_source.emplace(formats::base64); + BOOST_TEST(guarded([&] { + return decoder_source->send(test::characters_of(text).first(6)); + }).has_value()); + std::array bytes{}; + auto const delivered = guarded([&] { return decoder_source->receive(bytes); }); + BOOST_TEST(delivered.has_value() && delivered->count == 4); + test::clear_wipes(); + std::optional decoder_target; + decoder_target.emplace(std::move(*decoder_source)); + BOOST_TEST_EQ(test::wipes_in(*decoder_source, 6), 1U); + BOOST_TEST_EQ(test::wipes_in(*decoder_source, 2), 2U); + std::vector decoded(bytes.begin(), bytes.begin() + 4); + BOOST_TEST(stream_guarded(*decoder_target, test::characters_of(text).subspan(6), 3, decoded)); + BOOST_TEST(std::ranges::equal(decoded, input)); + std::vector again; + BOOST_TEST(stream_guarded(*decoder_source, test::characters_of(text), 3, again)); + BOOST_TEST(std::ranges::equal(again, input)); + decoder_target->reset(); + test::clear_wipes(); + guarded([&] { decoder_target->reset(); }); + BOOST_TEST_EQ(test::wipes_in(*decoder_target, 6), 1U); + BOOST_TEST_EQ(test::wipes_in(*decoder_target, 2), 2U); + BOOST_TEST_EQ(test::wipes_at_destruction(decoder_target, 6), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(decoder_source, 6), 1U); +} + +/** + A secret pipe's intermediate is wiped whole (512 characters) in the source after a move, at reset + and at destruction; the move is made where the second part borrows nothing, after a receive that + took everything, with the intermediate holding what the second part read; the moved-from pipe + converts a new input from the start (Review Focus 5). +*/ +void a_secret_pipes_intermediate_is_wiped() { + std::array const input = thirty_one_bytes(); + std::string const text = test::letters_of_letters(input); + constexpr std::size_t intermediate_size = codecs::default_capacity_v; + std::optional source; + source.emplace(codecs::encoder(test::letters, codecs::secret_operation), + codecs::encoder(test::letters, codecs::secret_operation)); + BOOST_TEST(source->send(input).has_value()); + std::array output{}; + auto const received = source->receive(output); + BOOST_TEST(received.has_value() && received->count == output.size() && + received->flow == codecs::flow::needs_input); + BOOST_TEST_EQ(std::string_view(output.data(), output.size()), text); + + test::clear_wipes(); + std::optional target; + target.emplace(std::move(*source)); + BOOST_TEST_EQ(test::wipes_in(*source, intermediate_size), 1U); + std::string rest; + BOOST_TEST(stream_guarded(*target, std::span{}, 8, rest)); + BOOST_TEST(rest.empty()); + + BOOST_TEST_EQ(text_of(*source, input, 7), text); + + test::clear_wipes(); + target->reset(); + BOOST_TEST_EQ(test::wipes_in(*target, intermediate_size), 1U); + BOOST_TEST_EQ(text_of(*target, input, 64), text); + BOOST_TEST_EQ(test::wipes_at_destruction(target, intermediate_size), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(source, intermediate_size), 1U); + + // A public pipe wipes nothing of its own. + std::optional public_holder; + public_holder.emplace(codecs::encoder(test::letters), codecs::encoder(test::letters)); + BOOST_TEST_EQ(text_of(*public_holder, input, 64).size(), text.size()); + BOOST_TEST_EQ(test::wipes_at_destruction(public_holder, intermediate_size), 0U); +} + +/** + A secret buffered's storage in place, 31 bytes of input and 62 letters of output, is wiped in the + source after a move, at reset and at destruction, with output pending at the move; the moved-to + stream delivers the rest and the moved-from one converts a new input from the start (Review Focus + 5). +*/ +void a_secret_buffereds_storage_is_wiped() { + std::array const input = thirty_one_bytes(); + std::string const text = test::letters_of(input); + std::optional source; + source.emplace(codecs::encoder(test::letters, codecs::secret_operation), codecs::capacity<31>); + BOOST_TEST(source->send(input).has_value()); + BOOST_TEST(source->flush().has_value()); + std::array letter{}; + auto const first = source->receive(letter); + BOOST_TEST(first.has_value() && first->count == 1 && + first->flow == codecs::flow::output_pending); + + test::clear_wipes(); + std::optional target; + target.emplace(std::move(*source)); + BOOST_TEST_EQ(test::wipes_in(*source, 31), 1U); + BOOST_TEST_EQ(test::wipes_in(*source, 62), 1U); + std::string rest{letter[0]}; + BOOST_TEST(stream_guarded(*target, std::span{}, 4, rest)); + BOOST_TEST_EQ(rest, text); + + BOOST_TEST_EQ(text_of(*source, input, 9), text); + + test::clear_wipes(); + target->reset(); + BOOST_TEST_EQ(test::wipes_in(*target, 31), 1U); + BOOST_TEST_EQ(test::wipes_in(*target, 62), 1U); + BOOST_TEST_EQ(text_of(*target, input, 64), text); + BOOST_TEST_EQ(test::wipes_at_destruction(target, 62), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(source, 31), 1U); +} + +/** + A secret each's item storage in place, the two letters of one byte, is wiped in the source after a + move made while a letter of the item waits in it, at reset and at destruction; the moved-to stream + delivers the rest and the moved-from one converts a new input from the start (Review Focus 5). +*/ +void a_secret_eachs_storage_is_wiped() { + std::array const input = thirty_one_bytes(); + std::string const text = test::letters_of(input); + std::optional source; + source.emplace(codecs::encoder(test::letters, codecs::secret_operation), codecs::capacity<2>); + auto const sent = source->send(input); + BOOST_TEST(sent.has_value() && sent->count == 1); + std::array letter{}; + // A span shorter than the item's two letters: the item goes through the storage. + auto const first = source->receive(letter); + BOOST_TEST(first.has_value() && first->count == 1 && + first->flow == codecs::flow::output_pending); + + test::clear_wipes(); + std::optional target; + target.emplace(std::move(*source)); + BOOST_TEST_EQ(test::wipes_in(*source, 2), 1U); + std::string rest{letter[0]}; + BOOST_TEST(stream_guarded(*target, std::span{input}.subspan(1), 1, rest)); + BOOST_TEST_EQ(rest, text); + + BOOST_TEST_EQ(text_of(*source, input, 1), text); + + test::clear_wipes(); + target->reset(); + BOOST_TEST_EQ(test::wipes_in(*target, 2), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(target, 2), 1U); + BOOST_TEST_EQ(test::wipes_at_destruction(source, 2), 1U); +} + +/** + From an allocator, the storage of a secret buffered and of a secret each goes back to it wiped, + every block: the blocks the input outgrows as many small sends grow it, and the last at + destruction; a public buffered gives its blocks back as they are, so that the count is not + vacuous. +*/ +void a_secret_streams_heap_storage_goes_back_wiped() { + std::array const input = thirty_one_bytes(); + std::string const text = test::letters_of(input); + test::wipe_checking_allocator const allocator; + { + auto buffered = + codecs::buffered(codecs::encoder(test::letters, codecs::secret_operation), allocator); + for (std::size_t index = 0; index < input.size(); ++index) { + BOOST_TEST(buffered.send(std::span{input}.subspan(index, 1)).has_value()); + } + std::string output; + BOOST_TEST(stream_guarded(buffered, std::span{}, 4, output)); + BOOST_TEST_EQ(output, text); + buffered.reset(); + BOOST_TEST_EQ(text_of(buffered, input, 64), text); + } + test::wipe_checking_allocator const each_allocator; + { + auto each = + codecs::each(codecs::encoder(test::letters, codecs::secret_operation), each_allocator); + BOOST_TEST_EQ(text_of(each, input, 1), text); + } + BOOST_TEST_GT(allocator.state()->deallocations, 4U); + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.state()->allocations); + BOOST_TEST_EQ(allocator.state()->wiped_deallocations, allocator.state()->deallocations); + BOOST_TEST_GT(each_allocator.state()->deallocations, 0U); + BOOST_TEST_EQ(each_allocator.state()->wiped_deallocations, + each_allocator.state()->deallocations); + + test::wipe_checking_allocator const public_allocator; + { + auto buffered = codecs::buffered(codecs::encoder(test::letters), public_allocator); + BOOST_TEST_EQ(text_of(buffered, input, 64), text); + } + BOOST_TEST_GT(public_allocator.state()->deallocations, 0U); + BOOST_TEST_LT(public_allocator.state()->wiped_deallocations, + public_allocator.state()->deallocations); +} + +/** + A move assignment wipes what the target held before it takes the source's: the whole intermediate + of a pipe (which takes only the elements the source's second part has not read, so that the + rest would stay), the storage of a buffered and of an each, each of the target populated by a + conversion that leaves its storage holding secret elements; the target then converts a new input + as a new stream does. +*/ +void a_move_assignment_wipes_what_the_target_held() { + std::array const input = thirty_one_bytes(); + std::string const text = test::letters_of(input); + { + constexpr std::size_t intermediate_size = codecs::default_capacity_v; + secret_pipe source{codecs::encoder(test::letters, codecs::secret_operation), + codecs::encoder(test::letters, codecs::secret_operation)}; + secret_pipe target{codecs::encoder(test::letters, codecs::secret_operation), + codecs::encoder(test::letters, codecs::secret_operation)}; + BOOST_TEST(target.send(input).has_value()); + std::array output{}; + auto const received = target.receive(output); + BOOST_TEST(received.has_value() && received->flow == codecs::flow::needs_input); + test::clear_wipes(); + target = std::move(source); + BOOST_TEST_EQ(test::wipes_in(target, intermediate_size), 1U); + BOOST_TEST_EQ(text_of(target, input, 64), test::letters_of_letters(input)); + } + { + secret_buffered source{codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<31>}; + secret_buffered target{codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<31>}; + BOOST_TEST(target.send(input).has_value()); + BOOST_TEST(target.flush().has_value()); + test::clear_wipes(); + target = std::move(source); + BOOST_TEST_EQ(test::wipes_in(target, 31), 1U); + BOOST_TEST_EQ(test::wipes_in(target, 62), 1U); + BOOST_TEST_EQ(text_of(target, input, 64), text); + } + { + secret_each source{codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<2>}; + secret_each target{codecs::encoder(test::letters, codecs::secret_operation), + codecs::capacity<2>}; + BOOST_TEST(target.send(input).has_value()); + std::array letter{}; + auto const first = target.receive(letter); + BOOST_TEST(first.has_value() && first->flow == codecs::flow::output_pending); + test::clear_wipes(); + target = std::move(source); + BOOST_TEST_EQ(test::wipes_in(target, 2), 1U); + BOOST_TEST_EQ(text_of(target, input, 1), text); + } +} + +/** + A heap output that outgrows a block holding secret bytes gives that block back wiped: a + transformer that states no output size starts the output at the input's size, writes part of the + output into it and reports `output_too_small`, and the output doubles over the secret bytes it + holds; a short input first and a longer one after a reset, as a reused stream does. A public + twin's blocks go back as they are, so that the count is not vacuous. +*/ +void a_secret_heap_output_wipes_the_block_it_outgrows() { + std::array const input = thirty_one_bytes(); + auto const convert = [&input](auto& stream, std::size_t size) { + BOOST_TEST(stream.send(std::span{input}.first(size)).has_value()); + BOOST_TEST(stream.flush().has_value()); + std::vector output(size * 2); + auto const received = stream.receive(output); + BOOST_TEST(received.has_value() && received->count == output.size()); + for (std::size_t index = 0; index < size; ++index) { + BOOST_TEST_EQ(output[2 * index], input[index]); + BOOST_TEST_EQ(output[(2 * index) + 1], input[index]); + } + }; + test::wipe_checking_allocator const allocator; + { + auto stream = codecs::buffered(doubling_probe{}, allocator); + convert(stream, 3); + stream.reset(); + convert(stream, 31); + } + BOOST_TEST_GT(allocator.state()->deallocations, 2U); + BOOST_TEST_EQ(allocator.state()->deallocations, allocator.state()->allocations); + BOOST_TEST_EQ(allocator.state()->wiped_deallocations, allocator.state()->deallocations); + + test::wipe_checking_allocator const public_allocator; + { + auto stream = codecs::buffered(doubling_probe{}, public_allocator); + convert(stream, 3); + stream.reset(); + convert(stream, 31); + } + BOOST_TEST_GT(public_allocator.state()->deallocations, 2U); + BOOST_TEST_LT(public_allocator.state()->wiped_deallocations, + public_allocator.state()->deallocations); +} + +/** + A drain of a secret transformer wipes its own buffer before it returns, of the default capacity + and of a capacity named; a drain of a public one does not. +*/ +void a_drain_of_a_secret_stream_wipes_its_buffer() { + std::array const input = thirty_one_bytes(); + std::string const text = test::letters_of(input); + std::string drained; + auto sink = [&](std::span piece) { drained.append(piece.begin(), piece.end()); }; + + auto encoder = codecs::encoder(test::letters, codecs::secret_operation); + BOOST_TEST(encoder.send(input).has_value()); + test::clear_wipes(); + auto const named = codecs::drain(encoder, sink, codecs::capacity<37>); + BOOST_TEST(named.has_value() && named.value() == codecs::flow::needs_input); + BOOST_TEST_EQ(drained, text); + BOOST_TEST_EQ(test::wipes_of_size(37), 1U); + + drained.clear(); + encoder.reset(); + BOOST_TEST(encoder.send(input).has_value()); + BOOST_TEST(encoder.flush().has_value()); + test::clear_wipes(); + auto const by_default = codecs::drain(encoder, sink); + BOOST_TEST(by_default.has_value() && by_default.value() == codecs::flow::finished); + BOOST_TEST_EQ(drained, text); + BOOST_TEST_EQ(test::wipes_of_size(codecs::default_capacity_v), 1U); + + drained.clear(); + auto public_letters = codecs::encoder(test::letters); + BOOST_TEST(public_letters.send(input).has_value()); + test::clear_wipes(); + BOOST_TEST(codecs::drain(public_letters, sink, codecs::capacity<37>).has_value()); + BOOST_TEST_EQ(drained, text); + BOOST_TEST_EQ(test::wipes.count, 0U); +} + +} // namespace +} // namespace secret_stream + +int main() { + secret_stream::every_call_of_a_secret_composition_is_guarded(); + secret_stream::every_call_of_a_secret_format_transformer_is_guarded(); + secret_stream::dit_is_set_in_every_call_of_a_secret_composition(); + secret_stream::a_secret_encoders_pending_state_is_wiped(); + secret_stream::a_secret_decoders_pending_state_is_wiped(); + secret_stream::base64_guards_nest_in_a_secret_pipe(); + secret_stream::a_secret_base64_streams_state_is_wiped(); + secret_stream::a_secret_pipes_intermediate_is_wiped(); + secret_stream::a_secret_buffereds_storage_is_wiped(); + secret_stream::a_secret_eachs_storage_is_wiped(); + secret_stream::a_secret_streams_heap_storage_goes_back_wiped(); + secret_stream::a_move_assignment_wipes_what_the_target_held(); + secret_stream::a_secret_heap_output_wipes_the_block_it_outgrows(); + secret_stream::a_drain_of_a_secret_stream_wipes_its_buffer(); + return boost::report_errors(); +} diff --git a/test/sizes_test.cpp b/test/sizes_test.cpp new file mode 100644 index 0000000..fe1ae46 --- /dev/null +++ b/test/sizes_test.cpp @@ -0,0 +1,255 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The sizes and the buffer forms over letters: the exact size and the bound in constant +// expressions (D6); a buffer form writes what fits and nothing on an error, in B23's order +// (input_too_long, the data's errors with the lowest value first, then output_too_small); +// empty inputs (Review Focus 3); bounds saturate at SIZE_MAX and an input whose bound saturates +// is refused (Review Focus 2). + +#include "support/letters.hpp" +#include "support/saturating.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace codecs = webcpp::codecs; +namespace test = webcpp::codecs::test; + +constexpr std::size_t size_maximum = SIZE_MAX; + +// The exact size and the bound, in constant expressions. +static_assert(codecs::encoded_size(test::letters, std::array{}) == 6); +static_assert(codecs::max_decoded_size(test::letters, std::string_view{"abcd"}) == 2); +static_assert(codecs::max_decoded_size(test::letters, "abcde") == 2); +static_assert(codecs::encoded_size(test::letters, std::array{}) == 0); + +// Saturating arithmetic. +static_assert(codecs::detail::saturating_multiply(size_maximum / 2, 3) == size_maximum); +static_assert(codecs::detail::saturating_multiply(size_maximum / 2, 2) == size_maximum - 1); +static_assert(codecs::detail::saturating_multiply(0, size_maximum) == 0); +static_assert(codecs::detail::saturating_multiply(size_maximum, 0) == 0); +static_assert(codecs::detail::saturating_multiply(size_maximum, 1) == size_maximum); +static_assert(codecs::detail::saturating_add(size_maximum, 1) == size_maximum); +static_assert(codecs::detail::saturating_add(size_maximum - 1, 1) == size_maximum); +static_assert(codecs::detail::saturating_add(3, 4) == 7); + +// A bound that saturates means "does not fit", and the input is refused before it is read. +static_assert(codecs::codec::max_encoded_size((size_maximum / 2) + 1) == + size_maximum); +static_assert(codecs::detail::input_size_fault(test::letters, (size_maximum / 2) + 1) == + codecs::error::input_too_long); +static_assert(!codecs::detail::input_size_fault(test::letters, size_maximum / 4).has_value()); +static_assert(!codecs::detail::input_size_fault(test::letters, 0).has_value()); +// letters' decoded bound never saturates: no text is too long to decode. +static_assert(!codecs::detail::text_size_fault(test::letters, size_maximum).has_value()); + +/** Bytes as a std::string_view, to compare. */ +std::string_view as_text(std::span viewed) { + return {reinterpret_cast(viewed.data()), viewed.size()}; +} + +/** Two bytes encode to four letters and decode back. */ +void round_trip() { + std::array const input{0x01, 0xff}; + std::array output{}; + output.fill('#'); + auto const written = codecs::encode(test::letters, input, output); + if (!BOOST_TEST(written.has_value())) { + return; + } + BOOST_TEST_EQ(*written, 4U); + BOOST_TEST_EQ((std::string_view{output.data(), output.size()}), "abpp####"); + std::array decoded{}; + decoded.fill(0x23); + auto const read = codecs::decode(test::letters, std::string_view{output.data(), *written}, + std::span{decoded}); + if (!BOOST_TEST(read.has_value())) { + return; + } + BOOST_TEST_EQ(*read, 2U); + BOOST_TEST_EQ(decoded[0], 0x01U); + BOOST_TEST_EQ(decoded[1], 0xffU); + BOOST_TEST_EQ(decoded[2], 0x23U); + // An exact output is enough. + std::array exact{}; + auto const exactly = codecs::encode(test::letters, input, exact); + BOOST_TEST(exactly.has_value() && *exactly == 4U); + BOOST_TEST_EQ((std::string_view{exact.data(), exact.size()}), "abpp"); +} + +/** Every kind of byte input encodes, a string literal as its characters without the zero (B5). */ +void each_byte_input() { + std::array output{}; + auto const from_literal = codecs::encode(test::letters, "A", output); + BOOST_TEST(from_literal.has_value() && *from_literal == 2U); + BOOST_TEST_EQ((std::string_view{output.data(), 2}), "eb"); + std::vector const heap_input{0x10}; + auto const from_vector = codecs::encode(test::letters, heap_input, output); + BOOST_TEST(from_vector.has_value() && *from_vector == 2U); + BOOST_TEST_EQ((std::string_view{output.data(), 2}), "ba"); + std::array const raw_input{std::byte{0x2f}}; + auto const from_bytes = codecs::encode(test::letters, raw_input, output); + BOOST_TEST(from_bytes.has_value() && *from_bytes == 2U); + BOOST_TEST_EQ((std::string_view{output.data(), 2}), "cp"); + std::string const text_input{"ab"}; + std::array decoded{}; + auto const from_string = codecs::decode(test::letters, text_input, decoded); + BOOST_TEST(from_string.has_value() && *from_string == 1U); + BOOST_TEST_EQ(decoded[0], 0x01U); + // A range of char is a text, read whole, with no std::string_view around it. + std::array const array_text{'p', 'a'}; + auto const from_array = codecs::decode(test::letters, array_text, decoded); + BOOST_TEST(from_array.has_value() && *from_array == 1U); + BOOST_TEST_EQ(decoded[0], 0xf0U); + BOOST_TEST_EQ(codecs::max_decoded_size(test::letters, array_text), 1U); +} + +/** 32 bytes need 64 letters: 63 are refused, and the buffer is unchanged. */ +void short_output() { + std::array input{}; + input.fill(0x5a); + std::array output{}; + output.fill('#'); + auto const written = codecs::encode(test::letters, input, output); + BOOST_TEST(!written.has_value()); + BOOST_TEST(written.error() == codecs::error::output_too_small); + BOOST_TEST(std::ranges::all_of(output, [](char held) { return held == '#'; })); + // A decode into too few bytes, after the text was found valid. + std::array decoded{0x23}; + auto const read = codecs::decode(test::letters, std::string_view{"abab"}, decoded); + BOOST_TEST(!read.has_value()); + BOOST_TEST(read.error() == codecs::error::output_too_small); + BOOST_TEST_EQ(decoded[0], 0x23U); +} + +/** A text with several faults reports the lowest value, and nothing is written. */ +void refused_text() { + std::array decoded{}; + decoded.fill(0x23); + // Both an odd length and a character past 'p': invalid_character, the lower value. + auto const both = codecs::decode(test::letters, std::string_view{"abq"}, decoded); + BOOST_TEST(!both.has_value()); + BOOST_TEST(both.error() == codecs::error::invalid_character); + // An odd length alone. + auto const odd = codecs::decode(test::letters, std::string_view{"abc"}, decoded); + BOOST_TEST(!odd.has_value()); + BOOST_TEST(odd.error() == codecs::error::invalid_length); + // A data error wins over a short output. + std::array no_room{}; + auto const bad_and_short = codecs::decode(test::letters, std::string_view{"zz"}, no_room); + BOOST_TEST(!bad_and_short.has_value()); + BOOST_TEST(bad_and_short.error() == codecs::error::invalid_character); + BOOST_TEST_EQ(as_text(decoded), "####"); + // Each byte value as a character, with char signed: only 'a' to 'p' decode. + for (unsigned value = 0; value < 256; ++value) { + std::array const pair{static_cast(value), 'a'}; + auto const verdict = + codecs::decode(test::letters, std::string_view{pair.data(), pair.size()}, decoded); + bool const in_alphabet = value >= 'a' && value <= 'p'; + BOOST_TEST_EQ(verdict.has_value(), in_alphabet); + if (!in_alphabet) { + BOOST_TEST(verdict.error() == codecs::error::invalid_character); + } + } + BOOST_TEST_EQ(as_text(std::span{decoded}.subspan(2)), "##"); +} + +/** Empty inputs give 0 and write nothing (Review Focus 3). */ +void empty_input() { + std::array output{'#', '#'}; + auto const written = + codecs::encode(test::letters, std::span{}, std::span{output}); + BOOST_TEST(written.has_value() && *written == 0U); + BOOST_TEST_EQ((std::string_view{output.data(), output.size()}), "##"); + auto const into_nothing = + codecs::encode(test::letters, std::span{}, std::span{}); + BOOST_TEST(into_nothing.has_value() && *into_nothing == 0U); + std::array decoded{0x23}; + auto const read = codecs::decode(test::letters, std::string_view{}, decoded); + BOOST_TEST(read.has_value() && *read == 0U); + BOOST_TEST_EQ(decoded[0], 0x23U); + auto const from_empty_literal = codecs::decode(test::letters, "", std::span{}); + BOOST_TEST(from_empty_literal.has_value() && *from_empty_literal == 0U); + BOOST_TEST_EQ(codecs::encoded_size(test::letters, std::vector{}), 0U); + BOOST_TEST_EQ(codecs::max_decoded_size(test::letters, std::string{}), 0U); +} + +/** + An input whose bound saturates is input_too_long in every form, before the codec runs, and the + output is untouched (Review Focus 2); one byte or character less reaches the codec, the control. +*/ +void saturated_bounds() { + constexpr std::size_t most_bytes = test::saturating_t::most_bytes; + constexpr std::size_t most_characters = test::saturating_t::most_characters; + std::array const long_input{}; + std::array output{}; + output.fill('#'); + BOOST_TEST_EQ(codecs::encoded_size(test::saturating, long_input), size_maximum); + auto const encoded = codecs::encode(test::saturating, long_input, output); + BOOST_TEST(!encoded.has_value()); + BOOST_TEST(encoded.error() == codecs::error::input_too_long); + BOOST_TEST(std::ranges::all_of(output, [](char held) { return held == '#'; })); + std::array const fitting_input{}; + auto const reached = codecs::encode(test::saturating, fitting_input, output); + BOOST_TEST(!reached.has_value()); + BOOST_TEST(reached.error() == codecs::error::checksum_mismatch); + BOOST_TEST_EQ(output[0], '!'); + + std::array long_text{}; + long_text.fill('a'); + std::array decoded{}; + decoded.fill(0x23); + BOOST_TEST_EQ(codecs::max_decoded_size(test::saturating, long_text), size_maximum); + auto const read = codecs::decode(test::saturating, long_text, decoded); + BOOST_TEST(!read.has_value()); + BOOST_TEST(read.error() == codecs::error::input_too_long); + BOOST_TEST(std::ranges::all_of(decoded, [](std::uint8_t held) { return held == 0x23U; })); + auto const text_reached = codecs::decode( + test::saturating, std::string_view{long_text.data(), most_characters}, decoded); + BOOST_TEST(!text_reached.has_value()); + BOOST_TEST(text_reached.error() == codecs::error::checksum_mismatch); +} + +/** A text decoded into its own storage (Review Focus 4). */ +void in_place() { + std::array buffer{'a', 'b', 'p', 'p', 'h', 'h'}; + auto const read = + codecs::decode(test::letters, std::string_view{buffer.data(), buffer.size()}, + std::span{reinterpret_cast(buffer.data()), 3}); + if (!BOOST_TEST(read.has_value())) { + return; + } + BOOST_TEST_EQ(*read, 3U); + BOOST_TEST_EQ(static_cast(buffer[0]), 0x01U); + BOOST_TEST_EQ(static_cast(buffer[1]), 0xffU); + BOOST_TEST_EQ(static_cast(buffer[2]), 0x77U); +} + +} // namespace + +int main() { + round_trip(); + each_byte_input(); + short_output(); + refused_text(); + empty_input(); + saturated_bounds(); + in_place(); + return boost::report_errors(); +} diff --git a/test/support/allocation_checks.hpp b/test/support/allocation_checks.hpp new file mode 100644 index 0000000..12785e4 --- /dev/null +++ b/test/support/allocation_checks.hpp @@ -0,0 +1,144 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// What the allocation tests of codecs share, once for both of them (allocation_test.cpp, whose +// program links no Boost.URL, and allocation_percent_test.cpp, whose program does): the control +// that every form of operator new moves support/counting.hpp's counter, so that a zero is not a +// replacement that never ran, and the stream of an input in random chunks through a transformer, +// drained into a fixed span, which allocates nothing once the transformer is made. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_ALLOCATION_CHECKS_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_ALLOCATION_CHECKS_HPP + +#include "counting.hpp" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** The alignment of the over-aligned forms of operator new the control calls. */ +inline constexpr std::align_val_t aligned{64}; + +/** Runs `body`, one allocation of operator new's form, and checks that the counter saw it. */ +template +void expect_counted(char const* form, Body body) { + std::size_t const before = counted_new.load(); + body(); + std::size_t const counted = counted_new.load() - before; + if (counted != 1) { + std::printf("not counted once: %s\n", form); + } + BOOST_TEST_EQ(counted, 1U); +} + +/** Every form of operator new moves the counter: the control of the zeros below. */ +inline void control_counts_every_form() { + expect_counted("new", [] { + void* volatile block = ::operator new(24); + ::operator delete(block); + }); + expect_counted("new[]", [] { + void* volatile block = ::operator new[](24); + ::operator delete[](block); + }); + expect_counted("sized delete", [] { + void* volatile block = ::operator new(24); + ::operator delete(block, std::size_t{24}); + }); + expect_counted("sized delete[]", [] { + void* volatile block = ::operator new[](24); + ::operator delete[](block, std::size_t{24}); + }); + expect_counted("nothrow new", [] { + void* volatile block = ::operator new(24, std::nothrow); + BOOST_TEST(block != nullptr); + ::operator delete(block, std::nothrow); + }); + expect_counted("nothrow new[]", [] { + void* volatile block = ::operator new[](24, std::nothrow); + BOOST_TEST(block != nullptr); + ::operator delete[](block, std::nothrow); + }); + expect_counted("aligned new", [] { + void* volatile block = ::operator new(24, aligned); + ::operator delete(block, aligned); + }); + expect_counted("aligned new[]", [] { + void* volatile block = ::operator new[](24, aligned); + ::operator delete[](block, aligned); + }); + expect_counted("aligned nothrow new", [] { + void* volatile block = ::operator new(24, aligned, std::nothrow); + BOOST_TEST(block != nullptr); + ::operator delete(block, aligned, std::nothrow); + }); + expect_counted("aligned nothrow new[]", [] { + void* volatile block = ::operator new[](24, aligned, std::nothrow); + BOOST_TEST(block != nullptr); + ::operator delete[](block, aligned, std::nothrow); + }); + // The standard allocator's storage, which every container takes: not a container's own, since + // MSVC's debug library (_ITERATOR_DEBUG_LEVEL 1 or 2) also allocates a proxy per container. + expect_counted("std::allocator's storage", [] { + std::allocator allocator; + std::uint8_t* volatile block = allocator.allocate(16); + BOOST_TEST(block != nullptr); + allocator.deallocate(block, 16); + }); + expect_counted("new int[]", [] { + int const* volatile block = new int[4]; + delete[] block; + }); +} + +/** + Streams `input`, in random chunks drawn from `generator`, through `transformer`, drained into a + fixed span of `Span` elements, and checks that what comes out is `expected`. + + @return Whether every call succeeded and the output is `expected`. +*/ +template +bool stream_in_random_chunks(Transformer& transformer, std::span input, + std::span expected, std::mt19937_64& generator) { + std::size_t compared = 0; + bool same = true; + auto const sink = [&](std::span piece) noexcept { + same = same && compared + piece.size() <= expected.size() && + std::ranges::equal(piece, expected.subspan(compared, piece.size())); + compared += piece.size(); + }; + bool streamed = true; + std::array fixed_span{}; + for (std::size_t position = 0; position < input.size() && streamed;) { + // The engine's output modulo the sizes, through no distribution, whose output is each + // standard library's own. + auto const drawn = static_cast(generator() % 3001U); + std::size_t const size = std::min(drawn, input.size() - position); + auto const sent = transformer.send(input.subspan(position, size)); + streamed = + sent.has_value() && codecs::drain(transformer, sink, std::span{fixed_span}).has_value(); + position += sent.has_value() ? sent->count : 0; + } + streamed = streamed && transformer.flush().has_value() && + codecs::drain(transformer, sink, std::span{fixed_span}).has_value(); + return streamed && same && compared == expected.size(); +} + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_ALLOCATION_CHECKS_HPP diff --git a/test/support/allocators.hpp b/test/support/allocators.hpp new file mode 100644 index 0000000..55c4551 --- /dev/null +++ b/test/support/allocators.hpp @@ -0,0 +1,292 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The allocators of the tests' own, as the standard library's rules see them (owner decision 23): +// +// - throwing_allocator throws std::bad_alloc on its fail_at-th allocation, counted across +// every copy and rebinding of it (a shared counter), and succeeds on every other; it counts the +// blocks given back and those of them that did not read zero; a standard container's own block +// (support/bookkeeping.hpp) is not counted; it is not declared when exceptions are off. +// - non_propagating_allocator never propagates (on copy assignment, move assignment and swap) +// and compares equal only to a copy of itself, so that a container's move between two of them +// copies the bytes. +// - wipe_checking_allocator counts allocations and deallocations and records whether every +// byte it was given back read zero at deallocate; a standard container's own block +// (support/bookkeeping.hpp), which holds no byte of a value, is not counted. +// +// A move of throwing_allocator or wipe_checking_allocator is a copy: the source keeps the shared +// count and stays equal to what it was, as the allocator requirements ask. Both give out blocks +// that read zero, so that a byte that does not read zero when its block is given back was written +// and not wiped, on every target: an allocator that reuses memory (Emscripten's dlmalloc) would +// otherwise hand out bytes nobody wrote, past the elements a container holds. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP + +#include "bookkeeping.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** Whether the `count` bytes at `block` all read zero. */ +inline bool reads_zero(void const* block, std::size_t count) noexcept { + auto const* const first_byte = static_cast(block); + return std::all_of(first_byte, first_byte + count, + [](unsigned char byte_value) { return byte_value == 0; }); +} + +/** + A block of `count` elements from `std::allocator`, every byte zero, raw storage in which no + element is constructed yet. +*/ +template +[[nodiscard]] T* allocate_zeroed(std::size_t count) { + T* const block = std::allocator{}.allocate(count); + std::memset(static_cast(block), 0, count * sizeof(T)); + return block; +} + +#ifndef WEBCPP_CODECS_NO_EXCEPTIONS + +/** The count a throwing_allocator and its copies share. */ +struct throwing_state { + /** The allocation that throws, counted from 1; 0 for none. */ + std::size_t fail_at = 0; + /** The allocations made so far. */ + std::size_t allocations = 0; + /** The blocks given back. */ + std::size_t deallocations = 0; + /** The blocks given back with a byte that did not read zero. */ + std::size_t unwiped_deallocations = 0; +}; + +/** An allocator that throws `std::bad_alloc` on its `fail_at`-th allocation. */ +template +class throwing_allocator { +public: + /** The element type. */ + using value_type = T; + + /** + Constructs an allocator whose `fail_at`-th allocation, counted from 1, throws; 0 is none. + */ + explicit throwing_allocator(std::size_t fail_at) + : state_(std::make_shared(throwing_state{.fail_at = fail_at})) {} + + /** A copy shares the count. */ + throwing_allocator(throwing_allocator const& other) noexcept = default; + + /** + A move is a copy: the source keeps the shared count and stays equal to what it was, as the + allocator requirements ask; the implicit move would leave it with none. + */ + // NOLINTNEXTLINE(cert-oop11-cpp,performance-move-constructor-init): the copy is the intent + throwing_allocator(throwing_allocator&& other) noexcept : state_(other.state_) {} + + /** A copy shares the count. */ + throwing_allocator& operator=(throwing_allocator const& other) noexcept = default; + + /** A move is a copy, as the move constructor's. */ + throwing_allocator& operator=(throwing_allocator&& other) noexcept { + state_ = other.state_; + return *this; + } + + /** Leaves the count to the other copies. */ + ~throwing_allocator() = default; + + /** Constructs the allocator of another element type that shares this one's count. */ + template + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) + throwing_allocator(throwing_allocator const& other) noexcept : state_(other.state()) {} + + /** Allocates `count` elements, every byte zero, or throws on the allocation that is to fail. */ + [[nodiscard]] T* allocate(std::size_t count) { + // A standard container's own block (the MSVC STL's debug proxy) is neither counted nor + // failed: it is allocated in noexcept constructors, where a throw ends the program. + if (!is_bookkeeping(count * sizeof(T), alignof(T))) { + ++state_->allocations; + if (state_->allocations == state_->fail_at) { + throw std::bad_alloc(); + } + } + return allocate_zeroed(count); + } + + /** Counts the block, and whether a byte of it was not zero, and returns it. */ + void deallocate(T* pointer, std::size_t count) noexcept { + if (!is_bookkeeping(count * sizeof(T), alignof(T))) { + ++state_->deallocations; + if (!reads_zero(pointer, count * sizeof(T))) { + ++state_->unwiped_deallocations; + } + } + std::allocator{}.deallocate(pointer, count); + } + + /** + Starts the count over for every copy: the `fail_at`-th allocation from now, counted from 1, + throws. A container built before the call is not counted. + */ + void arm(std::size_t fail_at) const noexcept { + state_->allocations = 0; + state_->fail_at = fail_at; + } + + /** The allocations made through this allocator and its copies. */ + [[nodiscard]] std::size_t allocations() const noexcept { return state_->allocations; } + + /** The shared count. */ + [[nodiscard]] std::shared_ptr const& state() const noexcept { return state_; } + + /** Equal when the count is shared. */ + template + [[nodiscard]] bool operator==(throwing_allocator const& other) const noexcept { + return state_ == other.state(); + } + +private: + std::shared_ptr state_; +}; + +#endif // WEBCPP_CODECS_NO_EXCEPTIONS + +/** An allocator that never propagates and is equal only to its own copies. */ +template +class non_propagating_allocator { +public: + /** The element type. */ + using value_type = T; + /** The allocator stays with its container on a copy assignment. */ + using propagate_on_container_copy_assignment = std::false_type; + /** The allocator stays with its container on a move assignment. */ + using propagate_on_container_move_assignment = std::false_type; + /** The allocator stays with its container on a swap. */ + using propagate_on_container_swap = std::false_type; + /** Two of them are not equal unless they are copies. */ + using is_always_equal = std::false_type; + + /** Constructs the allocator numbered `identity`; two with another number are unequal. */ + explicit non_propagating_allocator(int identity) noexcept : identity_(identity) {} + + /** Constructs the allocator of another element type with this one's number. */ + template + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) + non_propagating_allocator(non_propagating_allocator const& other) noexcept + : identity_(other.identity()) {} + + /** Allocates `count` elements. */ + [[nodiscard]] T* allocate(std::size_t count) { return std::allocator{}.allocate(count); } + + /** Returns the elements. */ + void deallocate(T* pointer, std::size_t count) noexcept { + std::allocator{}.deallocate(pointer, count); + } + + /** The number. */ + [[nodiscard]] int identity() const noexcept { return identity_; } + + /** Equal when the numbers are. */ + template + [[nodiscard]] bool operator==(non_propagating_allocator const& other) const noexcept { + return identity_ == other.identity(); + } + +private: + int identity_; +}; + +/** What a wipe_checking_allocator and its copies count. */ +struct wipe_state { + /** The allocations. */ + std::size_t allocations = 0; + /** The deallocations. */ + std::size_t deallocations = 0; + /** The deallocations whose every byte read zero. */ + std::size_t wiped_deallocations = 0; +}; + +/** An allocator that records whether each block was all zero when it was given back. */ +template +class wipe_checking_allocator { +public: + /** The element type. */ + using value_type = T; + + /** Constructs an allocator with a count of its own. */ + wipe_checking_allocator() : state_(std::make_shared()) {} + + /** A copy shares the count. */ + wipe_checking_allocator(wipe_checking_allocator const& other) noexcept = default; + + /** + A move is a copy: the source keeps the shared count and stays equal to what it was, as the + allocator requirements ask; the implicit move would leave it with none. + */ + // NOLINTNEXTLINE(cert-oop11-cpp,performance-move-constructor-init): the copy is the intent + wipe_checking_allocator(wipe_checking_allocator&& other) noexcept : state_(other.state_) {} + + /** A copy shares the count. */ + wipe_checking_allocator& operator=(wipe_checking_allocator const& other) noexcept = default; + + /** A move is a copy, as the move constructor's. */ + wipe_checking_allocator& operator=(wipe_checking_allocator&& other) noexcept { + state_ = other.state_; + return *this; + } + + /** Leaves the count to the other copies. */ + ~wipe_checking_allocator() = default; + + /** Constructs the allocator of another element type that shares this one's count. */ + template + // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions,misc-explicit-constructor) + wipe_checking_allocator(wipe_checking_allocator const& other) noexcept + : state_(other.state()) {} + + /** Allocates `count` elements, every byte zero. */ + [[nodiscard]] T* allocate(std::size_t count) { + if (!is_bookkeeping(count * sizeof(T), alignof(T))) { + ++state_->allocations; + } + return allocate_zeroed(count); + } + + /** Counts the block, whether it is all zero, and returns it. */ + void deallocate(T* pointer, std::size_t count) noexcept { + if (!is_bookkeeping(count * sizeof(T), alignof(T))) { + ++state_->deallocations; + if (reads_zero(pointer, count * sizeof(T))) { + ++state_->wiped_deallocations; + } + } + std::allocator{}.deallocate(pointer, count); + } + + /** The shared count. */ + [[nodiscard]] std::shared_ptr const& state() const noexcept { return state_; } + + /** Equal when the count is shared. */ + template + [[nodiscard]] bool operator==(wipe_checking_allocator const& other) const noexcept { + return state_ == other.state(); + } + +private: + std::shared_ptr state_; +}; + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_ALLOCATORS_HPP diff --git a/test/support/arena.hpp b/test/support/arena.hpp new file mode 100644 index 0000000..1ec9f10 --- /dev/null +++ b/test/support/arena.hpp @@ -0,0 +1,111 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// recording_resource, a memory resource of the tests' own for the allocator tests: every +// allocation of a container made over it lands in a buffer of 64 KiB (a monotonic buffer resource +// over it, which refuses what does not fit), and the resource counts and records each allocation's +// size and pointer, so that a test sees which allocations went through the allocator it gave. The +// records are in place: the resource allocates nothing through the global operator new once built, +// which a test that counts the global allocations relies on. A standard container's own block +// (support/bookkeeping.hpp, which the MSVC STL's debug containers allocate through their +// allocator) is not counted, recorded or owned-checked as one of an operation: it is no state of +// what a test measures; all_allocation_count() counts every block. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_ARENA_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_ARENA_HPP + +#include "bookkeeping.hpp" + +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** A memory resource that records every allocation made through it. */ +class recording_resource : public std::pmr::memory_resource { +public: + /** The size of the buffer the allocations come from. */ + static constexpr std::size_t buffer_size = std::size_t{64} * 1024; + /** The most allocations recorded; the count goes on past it. */ + static constexpr std::size_t most_records = 64; + + /** One allocation: its size and the pointer it returned. */ + struct record { + /** The bytes asked for. */ + std::size_t size; + /** What the resource returned. */ + void* pointer; + }; + + /** + Constructs a resource over a buffer of its own. The buffer is on the heap, so that the + resource is small on a stack; it is allocated here, not by an operation under test. + */ + recording_resource() + : buffer_(buffer_size), + upstream_(buffer_.data(), buffer_.size(), std::pmr::null_memory_resource()) { + static_cast(bookkeeping()); // measured here, not inside a test's window + } + + /** Every allocation made through this resource, a container's own block included. */ + [[nodiscard]] std::size_t all_allocation_count() const noexcept { return all_count_; } + + /** The allocations made through this resource so far, a container's own block left out. */ + [[nodiscard]] std::size_t allocation_count() const noexcept { return allocation_count_; } + + /** The deallocations made through this resource so far. */ + [[nodiscard]] std::size_t deallocation_count() const noexcept { return deallocation_count_; } + + /** The `index`th allocation, for an index below `allocation_count()` and `most_records`. */ + [[nodiscard]] record const& allocation(std::size_t index) const noexcept { + return records_[index]; + } + + /** Whether `pointer` is inside the buffer: made by this resource, not by another one. */ + [[nodiscard]] bool owns(void const* pointer) const noexcept { + auto const* const first_byte = buffer_.data(); + auto const* const byte_pointer = static_cast(pointer); + return byte_pointer >= first_byte && byte_pointer < first_byte + buffer_size; + } + +private: + void* do_allocate(std::size_t size, std::size_t alignment) override { + void* const pointer = upstream_.allocate(size, alignment); + ++all_count_; + if (is_bookkeeping(size, alignment)) { + return pointer; + } + if (allocation_count_ < most_records) { + records_[allocation_count_] = record{.size = size, .pointer = pointer}; + } + ++allocation_count_; + return pointer; + } + + void do_deallocate(void* pointer, std::size_t size, std::size_t alignment) override { + if (!is_bookkeeping(size, alignment)) { + ++deallocation_count_; + } + upstream_.deallocate(pointer, size, alignment); + } + + [[nodiscard]] bool do_is_equal(std::pmr::memory_resource const& other) const noexcept override { + return this == &other; + } + + std::vector buffer_; + std::pmr::monotonic_buffer_resource upstream_; + std::array records_{}; + std::size_t all_count_ = 0; + std::size_t allocation_count_ = 0; + std::size_t deallocation_count_ = 0; +}; + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_ARENA_HPP diff --git a/test/support/armor_files.hpp b/test/support/armor_files.hpp new file mode 100644 index 0000000..c52ca12 --- /dev/null +++ b/test/support/armor_files.hpp @@ -0,0 +1,119 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The armor's vectors of test/data/armor/ (its README.txt says where each comes from), read at run +// time from the directory WEBCPP_TEST_CODECS_ARMOR_DATA names (test/Jamfile, which gives WASI the +// directory through webcpp.data, as the fuzz corpus is): RFC 7468's examples with their DER, and +// the PEM files OpenSSL wrote, each with its label; and with_carriage_returns, a text's lines +// ended by a carriage return and a line feed. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_ARMOR_FILES_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_ARMOR_FILES_HPP + +#ifndef WEBCPP_TEST_CODECS_ARMOR_DATA +#error "WEBCPP_TEST_CODECS_ARMOR_DATA names test/data/armor (test/Jamfile)" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** An armor of the directory, and the DER of its payload. */ +struct armor_file { + /** The file's name, without its extension: `.pem` and `.der`. */ + std::string_view name; + /** The label of its boundaries. */ + std::string_view label; +}; + +/** RFC 7468's examples in the strict form, Figures 6 and 8 to 15, and OpenSSL's PEM files. */ +inline constexpr std::array armor_files{ + armor_file{.name = "rfc7468-figure-06-certificate", .label = "CERTIFICATE"}, + armor_file{.name = "rfc7468-figure-08-crl", .label = "X509 CRL"}, + armor_file{.name = "rfc7468-figure-09-pkcs10", .label = "CERTIFICATE REQUEST"}, + armor_file{.name = "rfc7468-figure-10-pkcs7", .label = "PKCS7"}, + armor_file{.name = "rfc7468-figure-11-cms", .label = "CMS"}, + armor_file{.name = "rfc7468-figure-12-pkcs8", .label = "PRIVATE KEY"}, + armor_file{.name = "rfc7468-figure-13-pkcs8-encrypted", .label = "ENCRYPTED PRIVATE KEY"}, + armor_file{.name = "rfc7468-figure-14-attribute-certificate", .label = "ATTRIBUTE CERTIFICATE"}, + armor_file{.name = "rfc7468-figure-15-spki", .label = "PUBLIC KEY"}, + armor_file{.name = "openssl-p256-spki", .label = "PUBLIC KEY"}, + armor_file{.name = "openssl-x509-certificate", .label = "CERTIFICATE"}, +}; + +/** RFC 7468's Figure 7: a certificate with explanatory text before its BEGIN line. */ +inline constexpr std::string_view armor_explanatory_file = + "rfc7468-figure-07-certificate-explanatory-text"; + +/** + The bytes of the directory's file `name`, as they are. + + @param name The file's name, its extension included. + @return Its bytes, or nothing when it cannot be read, which is printed. +*/ +inline std::optional read_armor_data(std::string const& name) { + std::string const path = std::string{WEBCPP_TEST_CODECS_ARMOR_DATA} + "/" + name; + std::ifstream file{path, std::ios::binary}; + if (!file) { + std::printf("cannot read %s\n", path.c_str()); + return std::nullopt; + } + return std::string{std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; +} + +/** An armor file's text and its DER. */ +struct armor_vector { + /** The file. */ + armor_file file; + /** The text of `.pem`. */ + std::string text; + /** The bytes of `.der`; the DER of openssl-x509-certificate is Figure 6's. */ + std::vector der; +}; + +/** + Every file of @ref armor_files, read. + + @return The vectors; a file that cannot be read is left out, which the caller sees in the count. +*/ +inline std::vector read_armor_vectors() { + std::vector vectors; + for (armor_file const& file : armor_files) { + std::string const der_name = file.name == "openssl-x509-certificate" + ? std::string{armor_files[0].name} + : std::string{file.name}; + auto const text = read_armor_data(std::string{file.name} + ".pem"); + auto const der = read_armor_data(der_name + ".der"); + if (text && der) { + vectors.push_back({.file = file, .text = *text, .der = {der->begin(), der->end()}}); + } + } + return vectors; +} + +/** `text` with every line feed after a carriage return. */ +inline std::string with_carriage_returns(std::string_view text) { + std::string lines; + for (char const character : text) { + if (character == '\n') { + lines += '\r'; + } + lines += character; + } + return lines; +} + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_ARMOR_FILES_HPP diff --git a/test/support/armor_reference.hpp b/test/support/armor_reference.hpp new file mode 100644 index 0000000..b62a8d4 --- /dev/null +++ b/test/support/armor_reference.hpp @@ -0,0 +1,143 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The armor's reference, which every test of it compares the library with: RFC 7468's strict form +// written plainly, by splitting the text at its line feeds. encode writes the BEGIN line, the +// padded base64 of the bytes by base64_reference.hpp's table in lines of 64 characters and the END +// line, each ended by a line feed. decode reads, in the format's order: the boundaries +// (invalid_prefix: the first line is `-----BEGIN