From 8c3279b4d36e45843700adc28e477535cdc10d08 Mon Sep 17 00:00:00 2001 From: R Date: Fri, 4 Dec 2026 00:21:52 -0300 Subject: [PATCH 1/5] codecs: base32's one implementation takes its alphabet as a type, its codec and stream codec in detail/formats/base32_codec.hpp --- include/webcpp/codecs/base32.hpp | 773 +---------------- .../webcpp/codecs/detail/formats/base32.hpp | 95 ++- .../codecs/detail/formats/base32_codec.hpp | 807 ++++++++++++++++++ test/base32_stream_test.cpp | 6 +- test/base32_test.cpp | 8 +- 5 files changed, 896 insertions(+), 793 deletions(-) create mode 100644 include/webcpp/codecs/detail/formats/base32_codec.hpp diff --git a/include/webcpp/codecs/base32.hpp b/include/webcpp/codecs/base32.hpp index b91df29..bb235ca 100644 --- a/include/webcpp/codecs/base32.hpp +++ b/include/webcpp/codecs/base32.hpp @@ -11,8 +11,8 @@ default and take its omission by a call, `formats::base32(formats::padding::omitted)`. Encode writes upper case and decode takes either (B13); decode is otherwise canonical: it takes the format's own alphabet and the padding the option gives, and nothing else. Both are constant time on - every call and stream natively; one implementation serves both, over the arithmetic of - `detail/formats/base32.hpp`. + every call and stream natively; one implementation serves both, and z-base-32, over the + arithmetic of `detail/formats/base32.hpp` (`detail/formats/base32_codec.hpp`). */ #ifndef WEBCPP_CODECS_BASE32_HPP #define WEBCPP_CODECS_BASE32_HPP @@ -21,15 +21,9 @@ #include #include +#include #include -#include -#include - -#include -#include -#include -#include #include namespace webcpp::codecs::formats { @@ -87,774 +81,27 @@ inline constexpr base32hex_t base32hex{}; } // namespace webcpp::codecs::formats -namespace webcpp::codecs::detail { - -/** - The codec of base32 and of base32hex, which differ in their alphabet alone: eight characters a - group of five bytes, in constant time. - - @tparam Hex Whether the alphabet is the extended hex one. - @tparam Format The format's type. -*/ -template -struct base32_codec { - /** base32 indexes no table by a data byte and branches on none. */ - static constexpr bool constant_time = true; - - /** - The padded size, eight characters a group of five bytes, which is the unpadded size's bound. - - @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 base32_max_text_size(input_size); - } - - /** - Five bytes every eight characters, and of a last short group 5/8 of a byte a character, down. - - @param text_size The characters. - @return The most bytes. - */ - static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { - return base32_max_byte_size(text_size); - } - - /** - The exact size of the text of `input_bytes`, as the format's padding makes it. - - @param format_value The format. - @param input_bytes The bytes. - @return The characters, `SIZE_MAX` when they do not fit. - */ - static constexpr std::size_t encoded_size(Format const& format_value, - std::span input_bytes) noexcept { - return base32_text_size(input_bytes.size(), padding_is_written(format_value)); - } - - /** - The exact size of the bytes of `text_characters`, every character read. - - @param format_value The format. - @param text_characters The text. - @return The bytes, or the text's error of the lowest value: @ref error::invalid_character, - else @ref error::invalid_length, else @ref error::invalid_padding. - */ - [[nodiscard]] static result decoded_size( - Format const& format_value, std::string_view text_characters) noexcept { - base32_reader reader{padding_is_written(format_value)}; - for (char const text_character : text_characters) { - static_cast(reader.read(text_character)); - } - // The bytes the `=` drop are public with the verdict alone, for a valid text: the result's - // length. - result const dropped_count = reader.verdict(); - // The reader's bits and masks may be secret. The arithmetic is the same in a secret - // operation, so that the codec has no overloads that take secret_tag (R7): wiping these - // few bytes always, seven bytes, is cheaper than such an overload; a codec with a large - // scratch, base58's, wipes it through its secret overloads alone. - reader.wipe(); - if (!dropped_count) { - return dropped_count.error(); - } - // Read unchecked: the error was returned above. - return base32_max_byte_size(text_characters.size()) - dropped_count.unsafe_value(); - } - - /** - Writes the characters of `input_bytes` at the start of `output_characters`. - - @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(Format 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; - } - base32_encode_bytes(input_bytes, output_characters.first(written_size), - padding_is_written(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(Format 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; - } - // The character at column c of group g that completes a byte gives the byte at 5g + b, b - // being the bytes the group's earlier columns completed, which is a byte of the result when - // it is below the public count: every byte is written after the character that completes - // it is read, below that character (a byte is complete at column 1, 3, 4, 6 or 7 for b = 0 - // to 4), so that the text may be the output's own storage. Which characters are `=` decides - // nothing here. - base32_reader reader{padding_is_written(format_value)}; - std::size_t byte_index = 0; - for (char const text_character : text_characters) { - bool const completes_a_byte = base32_completes_byte(reader.column()); - std::uint8_t const byte = reader.read(text_character); - if (completes_a_byte) { - if (byte_index < byte_count) { - output_bytes[byte_index] = byte; - } - ++byte_index; - } - } - reader.wipe(); - return byte_count; - } -}; - -/** - The stream codec of base32 and of base32hex (D20): an encoder that holds the up to four bytes of - a group and the characters its output had no room for, and a decoder that holds the bits of a - group, the padding seen and the fault masks, and with the padding written the bytes of a group - from its fourth place on until it is known not to be the last, each in constant time. - - @tparam Hex Whether the alphabet is the extended hex one. - @tparam Format The format's type. -*/ -template -struct base32_stream_codec { - /** - The stream encoder: eight characters a group of five borrowed bytes, written straight into - the caller's span. - - The bytes of a group not yet whole wait in the encoder, and the characters of a group the - span had no room for wait for the next `receive`; `flush` completes the last group, with the - format's padding. It never fails. With `Options.secret` it is move-only and wipes the waiting - bytes and 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`, writing the padding of `format_value`. - - @param format_value The format. - */ - explicit encoder(Format const& format_value) noexcept - : padded_(padding_is_written(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_), - held_(other.held_), - held_count_(other.held_count_), - characters_(other.characters_), - character_count_(other.character_count_), - character_position_(other.character_position_), - flushed_(other.flushed_), - padded_(other.padded_) { - 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) { - wipe_pending(); - borrowed_ = other.borrowed_; - position_ = other.position_; - held_ = other.held_; - held_count_ = other.held_count_; - characters_ = other.characters_; - character_count_ = other.character_count_; - character_position_ = other.character_position_; - flushed_ = other.flushed_; - padded_ = other.padded_; - other.reset(); - } - return *this; - } - - /** Wipes the waiting bytes and 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 characters of the borrowed bytes, a group of eight for each five, as `output` - has room; after `flush`, the last group too. - - @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; - for (;;) { - while (character_position_ < character_count_ && written < output.size()) { - output[written++] = characters_[character_position_++]; - } - if (character_position_ < character_count_ || written == output.size()) { - break; - } - character_count_ = 0; - character_position_ = 0; - if (position_ < borrowed_.size()) { - if (held_count_ == 0 && borrowed_.size() - position_ >= base32_group_bytes && - output.size() - written >= base32_group_characters) { - // A whole group into a span with room for it, with no stop on the way. - static_cast(base32_group_symbols( - borrowed_.subspan(position_, base32_group_bytes), - output.subspan(written).template first())); - position_ += base32_group_bytes; - written += base32_group_characters; - } else { - take_byte(); - } - } else if (flushed_ && held_count_ != 0) { - character_count_ = base32_last_group( - std::span{held_}.first(held_count_), padded_, - characters_); - held_count_ = 0; - } else { - break; - } - } - if (position_ == borrowed_.size()) { - borrowed_ = {}; - position_ = 0; - } - return step{.count = written, .flow = state()}; - } - - /** - Ends the input: base32 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 bytes and characters - of a secret stream wiped. - */ - void reset() noexcept { - wipe_pending(); - borrowed_ = {}; - position_ = 0; - held_ = {}; - held_count_ = 0; - characters_ = {}; - character_count_ = 0; - character_position_ = 0; - flushed_ = false; - } - - private: - /** Wipes the waiting bytes and characters when the stream is secret. */ - void wipe_pending() noexcept { - if constexpr (Options.secret) { - secure::erase_secret(held_); - secure::erase_secret(characters_); - } - } - - /** Takes the next borrowed byte into the group, which is encoded when it is whole. */ - void take_byte() noexcept { - held_[held_count_++] = borrowed_[position_++]; - if (held_count_ == base32_group_bytes) { - character_count_ = base32_group_symbols(held_, characters_); - character_position_ = 0; - held_count_ = 0; - } - } - - /** The state the next call sees. */ - [[nodiscard]] flow state() const noexcept { - if (character_position_ < character_count_ || position_ < borrowed_.size() || - (flushed_ && held_count_ != 0)) { - 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 bytes of the group not yet whole; the fifth is encoded at once. */ - std::array held_{}; - /** How many of `held_` wait: 0 to 4. */ - std::size_t held_count_ = 0; - /** The characters of a group the output had no room for. */ - std::array characters_{}; - /** How many characters `characters_` holds. */ - std::size_t character_count_ = 0; - /** The next character of `characters_` to write. */ - std::size_t character_position_ = 0; - /** Whether `flush` ended the input. */ - bool flushed_ = false; - /** Whether the padding is written: the format's, which stays across `reset`. */ - bool padded_; - }; - - /** - The stream decoder: the bytes of a group written straight into the caller's span as its - characters are read. - - It holds the bits of a group not yet in a byte and the masks of what is wrong, and decides - which bytes it delivers from public facts alone, never from whether a character is a `=`. With - the padding omitted, the byte each character that completes one gives (the second, fourth, - fifth, seventh and eighth of a group) is delivered at once (any `=` is a fault, which the - verdict reports). With the padding written, the first byte of a group is delivered at once, and - the bytes of its fourth, fifth, seventh and eighth places, which are `=` in the last group of a - short input, are held until the group is known not to be the last: the next character - delivers them; at the end, how many bytes the `=` of the last group drop, made public with the - verdict once the input is valid (it is the result's length), says how many of the held bytes - are bytes. Bytes the span has no room for wait for the next `receive`, and every character - that delivers nothing is read whether the span has room or not: a caller that gives a span of - exactly the room the bytes need reaches `flow::needs_input` with the padding read, and - `flow::finished` after `flush` and the receive of the held bytes, or at `flush` when none are - held. Every character's verdict is accumulated in the masks, 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, else @ref error::invalid_padding. The bytes delivered before - `flush` may come from characters 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. With `Options.secret` it is move-only and - wipes the bits, the masks and the held and waiting bytes 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`, requiring the padding of `format_value`, or refusing it. - - @param format_value The format. - */ - explicit decoder(Format const& format_value) noexcept - : reader_(padding_is_written(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_), - reader_(other.reader_), - held_(other.held_), - held_count_(other.held_count_), - waiting_(other.waiting_), - waiting_count_(other.waiting_count_), - waiting_position_(other.waiting_position_), - last_padding_(other.last_padding_), - 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) { - wipe_state(); - borrowed_ = other.borrowed_; - position_ = other.position_; - reader_ = other.reader_; - held_ = other.held_; - held_count_ = other.held_count_; - waiting_ = other.waiting_; - waiting_count_ = other.waiting_count_; - waiting_position_ = other.waiting_position_; - last_padding_ = other.last_padding_; - flushed_ = other.flushed_; - verdict_passed_ = other.verdict_passed_; - error_ = other.error_; - other.reset(); - } - return *this; - } - - /** Wipes the bits, the masks and the held and waiting bytes of a secret stream. */ - ~decoder() - requires wipes - { - wipe_state(); - } - - /** A public stream wipes nothing. */ - ~decoder() = default; - - /** - Borrows all of `input` in `flow::needs_input`, and accepts nothing in another state; the - characters that deliver no byte at the front of it are read at once, which frees a lone - first character of a group. - - @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; - std::size_t none_written = 0; - while (position_ < borrowed_.size() && delivered_by_next() == 0) { - read_next({}, none_written); - } - return step{.count = input.size(), .flow = state()}; - } - - /** - Writes the bytes each character delivers as it is read, as `output` has room, and after - `flush` the held bytes of the last group. - - 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; - // A character is read when no byte waits, so that the at most two it delivers have - // room to wait; one that delivers none is read with or without room in `output`. - for (;;) { - while (waiting_position_ < waiting_count_ && written < output.size()) { - output[written++] = waiting_[waiting_position_++]; - } - if (waiting_position_ < waiting_count_) { - break; - } - waiting_count_ = 0; - waiting_position_ = 0; - if (position_ < borrowed_.size()) { - read_next(output, written); - } else if (flushed_ && held_count_ != 0) { - end_input(); - release_held(output, written); - } else { - break; - } - } - 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()) { - if (!pass_verdict()) { - return error_; - } - end_input(); - } - } - return state(); - } - - /** - Back to `flow::needs_input`, nothing borrowed, the verdict and the error forgotten; the - bits, the masks and the held and waiting bytes of a secret stream wiped. - */ - void reset() noexcept { - wipe_state(); - borrowed_ = {}; - position_ = 0; - reader_.reset(); - held_ = {}; - held_count_ = 0; - waiting_ = {}; - waiting_count_ = 0; - waiting_position_ = 0; - last_padding_ = 0; - flushed_ = false; - verdict_passed_ = false; - error_.clear(); - } - - private: - /** Wipes the bits, the masks and the held and waiting bytes when the stream is secret. */ - void wipe_state() noexcept { - if constexpr (Options.secret) { - reader_.wipe(); - secure::erase_secret(held_); - secure::erase_secret(waiting_); - } - } - - /** - How many bytes the next character delivers, from public facts alone: its column, the - padding option and how many bytes are held. - - @return 0 to 4. - */ - [[nodiscard]] std::size_t delivered_by_next() const noexcept { - unsigned const column = reader_.column(); - if (!reader_.padded()) { - return base32_completes_byte(column) ? 1 : 0; - } - if (column == 0) { - return held_count_; - } - return column == 1 ? 1 : 0; - } - - /** Writes `byte` into `output` when it has room and no byte waits, else makes it wait. */ - void deliver(std::uint8_t byte, std::span output, - std::size_t& written) noexcept { - if (waiting_count_ == 0 && written < output.size()) { - output[written++] = byte; - } else { - waiting_[waiting_count_++] = byte; - } - } - - /** Delivers the held bytes: those of a group that is not the last. */ - void release_held(std::span output, std::size_t& written) noexcept { - for (std::size_t index = 0; index < held_count_; ++index) { - deliver(held_[index], output, written); - } - held_count_ = 0; - } - - /** Reads the next borrowed character and delivers or holds the byte its place gives. */ - void read_next(std::span output, std::size_t& written) noexcept { - unsigned const column = reader_.column(); - std::uint8_t const byte = reader_.read(borrowed_[position_++]); - if (column == 0) { - // A group follows the one whose bytes are held: they are bytes of the result. - release_held(output, written); - } else if (base32_completes_byte(column)) { - if (column == 1 || !reader_.padded()) { - deliver(byte, output, written); - } else { - held_[held_count_++] = byte; - } - } - } - - /** - At the end of a valid input, nothing borrowed: of the held bytes of the last group, those - the `=` drop, which come last, are no bytes. - */ - void end_input() noexcept { - held_count_ -= last_padding_; - last_padding_ = 0; - } - - /** - The verdict over the whole input, what is still borrowed included, as `decoded_size` - gives it for the whole text: a copy of the reader reads the rest, so that the characters - are read again, and delivered, by the calls that follow. For a valid input, it keeps the - count of bytes the `=` of the last group drop, public with the verdict. - - @return Whether the input is valid; the error is set when it is not. - */ - [[nodiscard]] bool pass_verdict() noexcept { - auto scan = reader_; - for (char const unread : borrowed_.subspan(position_)) { - static_cast(scan.read(unread)); - } - result const dropped_count = scan.verdict(); - if constexpr (Options.secret) { - scan.wipe(); - } - if (!dropped_count) { - error_ = dropped_count.error(); - return false; - } - // Read unchecked: the error was returned above. - last_padding_ = dropped_count.unsafe_value(); - verdict_passed_ = true; - return true; - } - - /** 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 (waiting_position_ < waiting_count_ || position_ < borrowed_.size()) { - return flow::output_pending; - } - if (!flushed_) { - return flow::needs_input; - } - return held_count_ != 0 ? flow::output_pending : flow::finished; - } - - /** The characters `send` accepted. */ - std::span borrowed_; - /** The next borrowed character to read. */ - std::size_t position_ = 0; - /** The bits of the group in progress, the masks and the padding seen. */ - base32_reader reader_; - /** With the padding written, the bytes of the fourth, fifth, seventh and eighth places. */ - std::array held_{}; - /** How many of `held_` are held: 0 to 4, by the column, public. */ - std::size_t held_count_ = 0; - /** The bytes delivered that the output had no room for. */ - std::array waiting_{}; - /** How many bytes `waiting_` holds. */ - std::size_t waiting_count_ = 0; - /** The next byte of `waiting_` to write. */ - std::size_t waiting_position_ = 0; - /** The count of bytes the `=` of the last group drop, public once the verdict passed. */ - std::size_t last_padding_ = 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::detail - namespace webcpp::codecs { /** The codec of base32: eight characters a group of five bytes, in constant time. */ template <> -struct codec : detail::base32_codec {}; +struct codec + : detail::base32_codec, formats::base32_t> {}; /** The codec of base32hex: base32's, over the extended hex alphabet. */ template <> -struct codec : detail::base32_codec {}; +struct codec + : detail::base32_codec, formats::base32hex_t> {}; /** The stream codec of base32 (D20): its encoder and decoder hold a group, in constant time. */ template <> -struct stream_codec : detail::base32_stream_codec {}; +struct stream_codec + : detail::base32_stream_codec, formats::base32_t> {}; /** The stream codec of base32hex: base32's, over the extended hex alphabet. */ template <> struct stream_codec - : detail::base32_stream_codec {}; + : detail::base32_stream_codec, formats::base32hex_t> {}; } // namespace webcpp::codecs diff --git a/include/webcpp/codecs/detail/formats/base32.hpp b/include/webcpp/codecs/detail/formats/base32.hpp index 4925c1d..18d372e 100644 --- a/include/webcpp/codecs/detail/formats/base32.hpp +++ b/include/webcpp/codecs/detail/formats/base32.hpp @@ -5,15 +5,17 @@ // 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). + The arithmetic of base32 and base32hex, and of every format of five bytes as eight symbols, which + their codec and stream codec share (`base32_codec.hpp`): 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). + + RFC 4648's two alphabets differ in where their digits and letters lie alone, so that one + template, by a flag, is the arithmetic of both (section 6 and section 7), `base32_alphabet`. + The templates below take any alphabet of that shape: z-base-32's + (`detail/formats/zbase32.hpp`) is the other. */ #ifndef WEBCPP_CODECS_DETAIL_FORMATS_BASE32_HPP #define WEBCPP_CODECS_DETAIL_FORMATS_BASE32_HPP @@ -98,6 +100,41 @@ template namespace webcpp::codecs::detail { +/** + The alphabet of base32 (RFC 4648 section 6) or of base32hex (section 7), as the templates of this + header and of `base32_codec.hpp` read an alphabet: a 5-bit value's symbol, a symbol's 5-bit value + and its fault, by the masks of @ref base32_arithmetic, and `=` as the padding. + + @tparam Hex Whether the alphabet is the extended hex one of RFC 4648 section 7. +*/ +template +struct base32_alphabet { + /** `=` completes the last group, when the format writes its padding. */ + static constexpr bool has_padding = true; + + /** + The symbol of a 5-bit value, in upper case. + + @param five_bits A value of 0 to 31, which may be secret; a value above 31 gives `\0`. + @return The symbol. + */ + [[nodiscard]] static constexpr std::uint8_t symbol_of(std::uint8_t five_bits) noexcept { + return base32_arithmetic::symbol_of(five_bits); + } + + /** + The 5-bit value of a symbol in either case, and whether it is no symbol of the alphabet. + + @param symbol The byte of the character, which may be secret. + @param error_mask Set to all ones when `symbol` is no symbol; left as it was otherwise. + @return The value, 0 for a byte that is no symbol. + */ + [[nodiscard]] static constexpr std::uint8_t five_bits_of(std::uint8_t symbol, + std::uint8_t& error_mask) noexcept { + return base32_arithmetic::five_bits_of(symbol, error_mask); + } +}; + /** The padding character of RFC 4648 section 3.2. */ inline constexpr char base32_padding_character = '='; @@ -111,13 +148,13 @@ inline constexpr std::size_t base32_group_characters = 8; 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. + @tparam Alphabet The alphabet: its symbols, and whether `=` is its padding. @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 +template constexpr std::size_t base32_group_symbols(std::span group_bytes, std::span symbols) noexcept { std::uint64_t bits = 0; @@ -127,7 +164,7 @@ constexpr std::size_t base32_group_symbols(std::span group_b 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)); + symbols[index] = static_cast(Alphabet::symbol_of(five_bits)); } // Nothing of the group stays in a temporary but this word, which the caller's bytes made. return count; @@ -137,16 +174,16 @@ constexpr std::size_t base32_group_symbols(std::span group_b 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. + @tparam Alphabet The alphabet: its symbols, and whether `=` is its padding. @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 +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); + std::size_t const symbol_count = base32_group_symbols(group_bytes, characters); if (!padded) { return symbol_count; } @@ -160,27 +197,27 @@ constexpr std::size_t base32_last_group(std::span group_byte 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. + @tparam Alphabet The alphabet: its symbols, and whether `=` is its padding. @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 +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( + 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))); + static_cast(base32_last_group(input_bytes.subspan(byte_index), padded, + output_characters.subspan(character_index))); } } @@ -244,7 +281,7 @@ constexpr void base32_encode_bytes(std::span input_bytes, } /** - The decoder's state machine, one character at a time, for the alphabet of `Hex` and the format's + The decoder's state machine, one character at a time, for the alphabet `Alphabet` 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 @@ -262,11 +299,14 @@ constexpr void base32_encode_bytes(std::span input_bytes, error::invalid_padding. Nothing else passes through `secure::declassify`: for an invalid text, where its `=` are stays secret. + In an alphabet that has no padding (`Alphabet::has_padding` false), `=` is a character that is no + symbol, @ref error::invalid_character, and the padding faults are the non-zero bits at the end. + 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. + @tparam Alphabet The alphabet: its symbols, and whether `=` is its padding. */ -template +template class base32_reader { public: /** @@ -300,9 +340,12 @@ class base32_reader { [[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 value = Alphabet::five_bits_of(code, symbol_error); + // `=` is a padding character only in an alphabet that has one; elsewhere it is a character + // that is no symbol, as any other. + unsigned const padding_mask = Alphabet::has_padding ? secure::constant_time::is_equal_mask( + unsigned{code}, unsigned{'='}) + : 0U; 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 diff --git a/include/webcpp/codecs/detail/formats/base32_codec.hpp b/include/webcpp/codecs/detail/formats/base32_codec.hpp new file mode 100644 index 0000000..3dcde62 --- /dev/null +++ b/include/webcpp/codecs/detail/formats/base32_codec.hpp @@ -0,0 +1,807 @@ +// 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 codec and the stream codec of every format of five bytes as eight symbols, over the arithmetic + of `detail/formats/base32.hpp` and an alphabet: base32 and base32hex + (``, `base32_alphabet`) and z-base-32 + (``, `zbase32_alphabet`), one implementation in constant time. A + format's padding is its option when its alphabet has one (`padding_options`), and never written + when it has none. +*/ +#ifndef WEBCPP_CODECS_DETAIL_FORMATS_BASE32_CODEC_HPP +#define WEBCPP_CODECS_DETAIL_FORMATS_BASE32_CODEC_HPP + +#include + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace webcpp::codecs::detail { + +/** + Whether a format of the alphabet `Alphabet` writes its padding: its option, read as + `padding_is_written` reads it, when the alphabet has a padding; never when it has none. + + @tparam Alphabet The alphabet. + @tparam Format The format's type. + @param format_value The format. + @return Whether the padding is written, which is public. +*/ +template +[[nodiscard]] constexpr bool base32_padded([[maybe_unused]] Format const& format_value) noexcept { + if constexpr (Alphabet::has_padding) { + return padding_is_written(format_value); + } else { + return false; + } +} + +/** + The codec of base32, base32hex and z-base-32, which differ in their alphabet alone (and z-base-32 + in having no padding): eight characters a group of five bytes, in constant time. + + @tparam Alphabet The alphabet: `base32_alphabet` or `zbase32_alphabet`. + @tparam Format The format's type. +*/ +template +struct base32_codec { + /** The format indexes no table by a data byte and branches on none. */ + static constexpr bool constant_time = true; + + /** + The padded size, eight characters a group of five bytes, which is the unpadded size's bound, + for an alphabet that has a padding; the exact unpadded size for one that has none. + + @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 { + if constexpr (Alphabet::has_padding) { + return base32_max_text_size(input_size); + } else { + return base32_text_size(input_size, false); + } + } + + /** + Five bytes every eight characters, and of a last short group 5/8 of a byte a character, down. + + @param text_size The characters. + @return The most bytes. + */ + static constexpr std::size_t max_decoded_size(std::size_t text_size) noexcept { + return base32_max_byte_size(text_size); + } + + /** + The exact size of the text of `input_bytes`, as the format's padding makes it. + + @param format_value The format. + @param input_bytes The bytes. + @return The characters, `SIZE_MAX` when they do not fit. + */ + static constexpr std::size_t encoded_size(Format const& format_value, + std::span input_bytes) noexcept { + return base32_text_size(input_bytes.size(), base32_padded(format_value)); + } + + /** + The exact size of the bytes of `text_characters`, every character read. + + @param format_value The format. + @param text_characters The text. + @return The bytes, or the text's error of the lowest value: @ref error::invalid_character, + else @ref error::invalid_length, else @ref error::invalid_padding. + */ + [[nodiscard]] static result decoded_size( + Format const& format_value, std::string_view text_characters) noexcept { + base32_reader reader{base32_padded(format_value)}; + for (char const text_character : text_characters) { + static_cast(reader.read(text_character)); + } + // The bytes the `=` drop are public with the verdict alone, for a valid text: the result's + // length. + result const dropped_count = reader.verdict(); + // The reader's bits and masks may be secret. The arithmetic is the same in a secret + // operation, so that the codec has no overloads that take secret_tag (R7): wiping these + // few bytes always, seven bytes, is cheaper than such an overload; a codec with a large + // scratch, base58's, wipes it through its secret overloads alone. + reader.wipe(); + if (!dropped_count) { + return dropped_count.error(); + } + // Read unchecked: the error was returned above. + return base32_max_byte_size(text_characters.size()) - dropped_count.unsafe_value(); + } + + /** + Writes the characters of `input_bytes` at the start of `output_characters`. + + @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(Format 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; + } + base32_encode_bytes(input_bytes, output_characters.first(written_size), + base32_padded(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(Format 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; + } + // The character at column c of group g that completes a byte gives the byte at 5g + b, b + // being the bytes the group's earlier columns completed, which is a byte of the result when + // it is below the public count: every byte is written after the character that completes + // it is read, below that character (a byte is complete at column 1, 3, 4, 6 or 7 for b = 0 + // to 4), so that the text may be the output's own storage. Which characters are `=` decides + // nothing here. + base32_reader reader{base32_padded(format_value)}; + std::size_t byte_index = 0; + for (char const text_character : text_characters) { + bool const completes_a_byte = base32_completes_byte(reader.column()); + std::uint8_t const byte = reader.read(text_character); + if (completes_a_byte) { + if (byte_index < byte_count) { + output_bytes[byte_index] = byte; + } + ++byte_index; + } + } + reader.wipe(); + return byte_count; + } +}; + +/** + The stream codec of base32, base32hex and z-base-32 (D20): an encoder that holds the up to four + bytes of a group and the characters its output had no room for, and a decoder that holds the bits + of a group, the padding seen and the fault masks, and with the padding written the bytes of a group + from its fourth place on until it is known not to be the last, each in constant time. + + @tparam Alphabet The alphabet: `base32_alphabet` or `zbase32_alphabet`. + @tparam Format The format's type. +*/ +template +struct base32_stream_codec { + /** + The stream encoder: eight characters a group of five borrowed bytes, written straight into + the caller's span. + + The bytes of a group not yet whole wait in the encoder, and the characters of a group the + span had no room for wait for the next `receive`; `flush` completes the last group, with the + format's padding. It never fails. With `Options.secret` it is move-only and wipes the waiting + bytes and 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`, writing the padding of `format_value`. + + @param format_value The format. + */ + explicit encoder(Format const& format_value) noexcept + : padded_(base32_padded(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_), + held_(other.held_), + held_count_(other.held_count_), + characters_(other.characters_), + character_count_(other.character_count_), + character_position_(other.character_position_), + flushed_(other.flushed_), + padded_(other.padded_) { + 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) { + wipe_pending(); + borrowed_ = other.borrowed_; + position_ = other.position_; + held_ = other.held_; + held_count_ = other.held_count_; + characters_ = other.characters_; + character_count_ = other.character_count_; + character_position_ = other.character_position_; + flushed_ = other.flushed_; + padded_ = other.padded_; + other.reset(); + } + return *this; + } + + /** Wipes the waiting bytes and 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 characters of the borrowed bytes, a group of eight for each five, as `output` + has room; after `flush`, the last group too. + + @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; + for (;;) { + while (character_position_ < character_count_ && written < output.size()) { + output[written++] = characters_[character_position_++]; + } + if (character_position_ < character_count_ || written == output.size()) { + break; + } + character_count_ = 0; + character_position_ = 0; + if (position_ < borrowed_.size()) { + if (held_count_ == 0 && borrowed_.size() - position_ >= base32_group_bytes && + output.size() - written >= base32_group_characters) { + // A whole group into a span with room for it, with no stop on the way. + static_cast(base32_group_symbols( + borrowed_.subspan(position_, base32_group_bytes), + output.subspan(written).template first())); + position_ += base32_group_bytes; + written += base32_group_characters; + } else { + take_byte(); + } + } else if (flushed_ && held_count_ != 0) { + character_count_ = base32_last_group( + std::span{held_}.first(held_count_), padded_, + characters_); + held_count_ = 0; + } else { + break; + } + } + if (position_ == borrowed_.size()) { + borrowed_ = {}; + position_ = 0; + } + return step{.count = written, .flow = state()}; + } + + /** + Ends the input: the format 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 bytes and characters + of a secret stream wiped. + */ + void reset() noexcept { + wipe_pending(); + borrowed_ = {}; + position_ = 0; + held_ = {}; + held_count_ = 0; + characters_ = {}; + character_count_ = 0; + character_position_ = 0; + flushed_ = false; + } + + private: + /** Wipes the waiting bytes and characters when the stream is secret. */ + void wipe_pending() noexcept { + if constexpr (Options.secret) { + secure::erase_secret(held_); + secure::erase_secret(characters_); + } + } + + /** Takes the next borrowed byte into the group, which is encoded when it is whole. */ + void take_byte() noexcept { + held_[held_count_++] = borrowed_[position_++]; + if (held_count_ == base32_group_bytes) { + character_count_ = base32_group_symbols(held_, characters_); + character_position_ = 0; + held_count_ = 0; + } + } + + /** The state the next call sees. */ + [[nodiscard]] flow state() const noexcept { + if (character_position_ < character_count_ || position_ < borrowed_.size() || + (flushed_ && held_count_ != 0)) { + 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 bytes of the group not yet whole; the fifth is encoded at once. */ + std::array held_{}; + /** How many of `held_` wait: 0 to 4. */ + std::size_t held_count_ = 0; + /** The characters of a group the output had no room for. */ + std::array characters_{}; + /** How many characters `characters_` holds. */ + std::size_t character_count_ = 0; + /** The next character of `characters_` to write. */ + std::size_t character_position_ = 0; + /** Whether `flush` ended the input. */ + bool flushed_ = false; + /** Whether the padding is written: the format's, which stays across `reset`. */ + bool padded_; + }; + + /** + The stream decoder: the bytes of a group written straight into the caller's span as its + characters are read. + + It holds the bits of a group not yet in a byte and the masks of what is wrong, and decides + which bytes it delivers from public facts alone, never from whether a character is a `=`. With + the padding omitted, the byte each character that completes one gives (the second, fourth, + fifth, seventh and eighth of a group) is delivered at once (any `=` is a fault, which the + verdict reports); an alphabet with no padding is read so, always. With the padding written, the + first byte of a group is delivered at once, and the bytes of its fourth, fifth, seventh and + eighth places, which are `=` in the last group of a short input, are held until the group is + known not to be the last: the next character delivers them; at the end, how many bytes the `=` + of the last group drop, made public with the verdict once the input is valid (it is the + result's length), says how many of the held bytes are bytes. Bytes the span has no room for + wait for the next `receive`, and every character that delivers nothing is read whether the span + has room or not: a caller that gives a span of exactly the room the bytes need reaches + `flow::needs_input` with the padding read, and `flow::finished` after `flush` and the receive + of the held bytes, or at `flush` when none are held. Every character's verdict is accumulated + in the masks, 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, else @ref error::invalid_padding. The bytes delivered before + `flush` may come from characters 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. With `Options.secret` it is move-only and + wipes the bits, the masks and the held and waiting bytes 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`, requiring the padding of `format_value`, or refusing it. + + @param format_value The format. + */ + explicit decoder(Format const& format_value) noexcept + : reader_(base32_padded(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_), + reader_(other.reader_), + held_(other.held_), + held_count_(other.held_count_), + waiting_(other.waiting_), + waiting_count_(other.waiting_count_), + waiting_position_(other.waiting_position_), + last_padding_(other.last_padding_), + 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) { + wipe_state(); + borrowed_ = other.borrowed_; + position_ = other.position_; + reader_ = other.reader_; + held_ = other.held_; + held_count_ = other.held_count_; + waiting_ = other.waiting_; + waiting_count_ = other.waiting_count_; + waiting_position_ = other.waiting_position_; + last_padding_ = other.last_padding_; + flushed_ = other.flushed_; + verdict_passed_ = other.verdict_passed_; + error_ = other.error_; + other.reset(); + } + return *this; + } + + /** Wipes the bits, the masks and the held and waiting bytes of a secret stream. */ + ~decoder() + requires wipes + { + wipe_state(); + } + + /** A public stream wipes nothing. */ + ~decoder() = default; + + /** + Borrows all of `input` in `flow::needs_input`, and accepts nothing in another state; the + characters that deliver no byte at the front of it are read at once, which frees a lone + first character of a group. + + @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; + std::size_t none_written = 0; + while (position_ < borrowed_.size() && delivered_by_next() == 0) { + read_next({}, none_written); + } + return step{.count = input.size(), .flow = state()}; + } + + /** + Writes the bytes each character delivers as it is read, as `output` has room, and after + `flush` the held bytes of the last group. + + 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; + // A character is read when no byte waits, so that the at most two it delivers have + // room to wait; one that delivers none is read with or without room in `output`. + for (;;) { + while (waiting_position_ < waiting_count_ && written < output.size()) { + output[written++] = waiting_[waiting_position_++]; + } + if (waiting_position_ < waiting_count_) { + break; + } + waiting_count_ = 0; + waiting_position_ = 0; + if (position_ < borrowed_.size()) { + read_next(output, written); + } else if (flushed_ && held_count_ != 0) { + end_input(); + release_held(output, written); + } else { + break; + } + } + 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()) { + if (!pass_verdict()) { + return error_; + } + end_input(); + } + } + return state(); + } + + /** + Back to `flow::needs_input`, nothing borrowed, the verdict and the error forgotten; the + bits, the masks and the held and waiting bytes of a secret stream wiped. + */ + void reset() noexcept { + wipe_state(); + borrowed_ = {}; + position_ = 0; + reader_.reset(); + held_ = {}; + held_count_ = 0; + waiting_ = {}; + waiting_count_ = 0; + waiting_position_ = 0; + last_padding_ = 0; + flushed_ = false; + verdict_passed_ = false; + error_.clear(); + } + + private: + /** Wipes the bits, the masks and the held and waiting bytes when the stream is secret. */ + void wipe_state() noexcept { + if constexpr (Options.secret) { + reader_.wipe(); + secure::erase_secret(held_); + secure::erase_secret(waiting_); + } + } + + /** + How many bytes the next character delivers, from public facts alone: its column, the + padding option and how many bytes are held. + + @return 0 to 4. + */ + [[nodiscard]] std::size_t delivered_by_next() const noexcept { + unsigned const column = reader_.column(); + if (!reader_.padded()) { + return base32_completes_byte(column) ? 1 : 0; + } + if (column == 0) { + return held_count_; + } + return column == 1 ? 1 : 0; + } + + /** Writes `byte` into `output` when it has room and no byte waits, else makes it wait. */ + void deliver(std::uint8_t byte, std::span output, + std::size_t& written) noexcept { + if (waiting_count_ == 0 && written < output.size()) { + output[written++] = byte; + } else { + waiting_[waiting_count_++] = byte; + } + } + + /** Delivers the held bytes: those of a group that is not the last. */ + void release_held(std::span output, std::size_t& written) noexcept { + for (std::size_t index = 0; index < held_count_; ++index) { + deliver(held_[index], output, written); + } + held_count_ = 0; + } + + /** Reads the next borrowed character and delivers or holds the byte its place gives. */ + void read_next(std::span output, std::size_t& written) noexcept { + unsigned const column = reader_.column(); + std::uint8_t const byte = reader_.read(borrowed_[position_++]); + if (column == 0) { + // A group follows the one whose bytes are held: they are bytes of the result. + release_held(output, written); + } else if (base32_completes_byte(column)) { + if (column == 1 || !reader_.padded()) { + deliver(byte, output, written); + } else { + held_[held_count_++] = byte; + } + } + } + + /** + At the end of a valid input, nothing borrowed: of the held bytes of the last group, those + the `=` drop, which come last, are no bytes. + */ + void end_input() noexcept { + held_count_ -= last_padding_; + last_padding_ = 0; + } + + /** + The verdict over the whole input, what is still borrowed included, as `decoded_size` + gives it for the whole text: a copy of the reader reads the rest, so that the characters + are read again, and delivered, by the calls that follow. For a valid input, it keeps the + count of bytes the `=` of the last group drop, public with the verdict. + + @return Whether the input is valid; the error is set when it is not. + */ + [[nodiscard]] bool pass_verdict() noexcept { + auto scan = reader_; + for (char const unread : borrowed_.subspan(position_)) { + static_cast(scan.read(unread)); + } + result const dropped_count = scan.verdict(); + if constexpr (Options.secret) { + scan.wipe(); + } + if (!dropped_count) { + error_ = dropped_count.error(); + return false; + } + // Read unchecked: the error was returned above. + last_padding_ = dropped_count.unsafe_value(); + verdict_passed_ = true; + return true; + } + + /** 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 (waiting_position_ < waiting_count_ || position_ < borrowed_.size()) { + return flow::output_pending; + } + if (!flushed_) { + return flow::needs_input; + } + return held_count_ != 0 ? flow::output_pending : flow::finished; + } + + /** The characters `send` accepted. */ + std::span borrowed_; + /** The next borrowed character to read. */ + std::size_t position_ = 0; + /** The bits of the group in progress, the masks and the padding seen. */ + base32_reader reader_; + /** With the padding written, the bytes of the fourth, fifth, seventh and eighth places. */ + std::array held_{}; + /** How many of `held_` are held: 0 to 4, by the column, public. */ + std::size_t held_count_ = 0; + /** The bytes delivered that the output had no room for. */ + std::array waiting_{}; + /** How many bytes `waiting_` holds. */ + std::size_t waiting_count_ = 0; + /** The next byte of `waiting_` to write. */ + std::size_t waiting_position_ = 0; + /** The count of bytes the `=` of the last group drop, public once the verdict passed. */ + std::size_t last_padding_ = 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::detail + +#endif // WEBCPP_CODECS_DETAIL_FORMATS_BASE32_CODEC_HPP diff --git a/test/base32_stream_test.cpp b/test/base32_stream_test.cpp index 10d1d0f..414a63d 100644 --- a/test/base32_stream_test.cpp +++ b/test/base32_stream_test.cpp @@ -103,9 +103,11 @@ 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, +static_assert(std::is_base_of_v, formats::base32_t>, codecs::stream_codec>); -static_assert(std::is_base_of_v, +static_assert(std::is_base_of_v, formats::base32hex_t>, codecs::stream_codec>); /** Whether a format of the pair is the extended hex one, which the reference reads. */ diff --git a/test/base32_test.cpp b/test/base32_test.cpp index 2738405..50e97b6 100644 --- a/test/base32_test.cpp +++ b/test/base32_test.cpp @@ -85,8 +85,12 @@ static_assert(codecs::encoded_size(formats::base32hex(formats::padding{9}), // 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>); +static_assert( + std::is_base_of_v, formats::base32_t>, + base32_codec>); +static_assert( + std::is_base_of_v, formats::base32hex_t>, + 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). From 683bd4063204dbc67b89d0f2594cf5444c3e715c Mon Sep 17 00:00:00 2001 From: R Date: Fri, 4 Dec 2026 00:27:45 -0300 Subject: [PATCH 2/5] codecs: z-base-32, the format of pkarr's keys, on base32's implementation over its own alphabet, constant time and streaming, tested against pkarr's vectors --- .../webcpp/codecs/detail/formats/zbase32.hpp | 84 +++ include/webcpp/codecs/zbase32.hpp | 70 +++ meta/include-boundaries.json | 2 + meta/libraries.json | 2 +- test/Jamfile | 14 +- test/allocation_test.cpp | 56 ++ test/noexcept_test.cpp | 37 ++ test/support/zbase32_reference.hpp | 91 ++++ test/windows_h_after_test.cpp | 3 + test/windows_h_before_test.cpp | 3 + test/zbase32_stream_test.cpp | 348 ++++++++++++ test/zbase32_test.cpp | 510 ++++++++++++++++++ test/zbase32_vectors.hpp | 113 ++++ 13 files changed, 1330 insertions(+), 3 deletions(-) create mode 100644 include/webcpp/codecs/detail/formats/zbase32.hpp create mode 100644 include/webcpp/codecs/zbase32.hpp create mode 100644 test/support/zbase32_reference.hpp create mode 100644 test/zbase32_stream_test.cpp create mode 100644 test/zbase32_test.cpp create mode 100644 test/zbase32_vectors.hpp diff --git a/include/webcpp/codecs/detail/formats/zbase32.hpp b/include/webcpp/codecs/detail/formats/zbase32.hpp new file mode 100644 index 0000000..88102bf --- /dev/null +++ b/include/webcpp/codecs/detail/formats/zbase32.hpp @@ -0,0 +1,84 @@ +// 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 alphabet of z-base-32 (``), as base32's templates read an alphabet + (`detail/formats/base32.hpp`, `base32_codec.hpp`): `ybndrfg8ejkmcpqxot1uwisza345h769`, lower case + alone, no padding. Its symbols lie in no ranges of ASCII, so a value's symbol is read from the + whole alphabet by `secure::constant_time::lookup` and a symbol's value by masks against each of the + 32 symbols, as bech32's are, with no table indexed by a data byte and no branch on one (D12, the + change zbase32's D2). +*/ +#ifndef WEBCPP_CODECS_DETAIL_FORMATS_ZBASE32_HPP +#define WEBCPP_CODECS_DETAIL_FORMATS_ZBASE32_HPP + +#include + +#include + +#include +#include +#include +#include + +namespace webcpp::codecs::detail { + +/** + z-base-32's alphabet: the symbol of each 5-bit value its entry, the value of each symbol its + index; every other character, `=` and the upper-case letters among them, is no symbol. +*/ +struct zbase32_alphabet { + /** z-base-32 has no padding: `=` is a character that is no symbol. */ + static constexpr bool has_padding = false; + + /** The 32 symbols, the value of each its index. */ + static constexpr std::array symbols{ + 'y', 'b', 'n', 'd', 'r', 'f', 'g', '8', 'e', 'j', 'k', 'm', 'c', 'p', 'q', 'x', + 'o', 't', '1', 'u', 'w', 'i', 's', 'z', 'a', '3', '4', '5', 'h', '7', '6', '9', + }; + + /** + The symbol of a 5-bit value, read from the whole alphabet by `lookup`. + + @param five_bits A value of 0 to 31, which may be secret; a value above 31 gives `\0`. + @return The symbol. + */ + [[nodiscard]] static constexpr std::uint8_t symbol_of(std::uint8_t five_bits) noexcept { + return secure::constant_time::lookup(std::span{symbols}, + std::size_t{five_bits}); + } + + /** + The 5-bit value of a symbol, and a mask of whether it is no symbol: the indexes of the + alphabet, each masked by whether its entry is the character, ORed together, the fault the + complement of the masks' OR. The byte is read as unsigned first, so that a `char` from 0x80 + up, negative where `char` is signed, equals no entry. + + @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. + */ + [[nodiscard]] static constexpr std::uint8_t five_bits_of(std::uint8_t symbol, + std::uint8_t& error_mask) noexcept { + auto const code = static_cast(symbol); + unsigned value = 0; + unsigned symbol_mask = 0; + for (std::size_t index = 0; index < symbols.size(); ++index) { + unsigned const match = + secure::constant_time::is_equal_mask(code, unsigned{symbols[index]}); + value |= match & static_cast(index); + symbol_mask |= match; + } + error_mask = + static_cast(error_mask | static_cast(~symbol_mask)); + return static_cast(value); + } +}; + +} // namespace webcpp::codecs::detail + +#endif // WEBCPP_CODECS_DETAIL_FORMATS_ZBASE32_HPP diff --git a/include/webcpp/codecs/zbase32.hpp b/include/webcpp/codecs/zbase32.hpp new file mode 100644 index 0000000..7e3aef4 --- /dev/null +++ b/include/webcpp/codecs/zbase32.hpp @@ -0,0 +1,70 @@ +// 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) + +/** + z-base-32 (Zooko O'Whielacronx's human-oriented base-32 encoding, version 0.9.4.6 of its document): + each five bytes as eight symbols of five bits over the alphabet `ybndrfg8ejkmcpqxot1uwisza345h769`, + the bytes' bits most significant first, with no padding: the format of pkarr's keys, a 32-byte + Ed25519 public key as 52 characters. Encode writes lower case; decode takes lower case alone and is + canonical. It is constant time on every call and streams natively, on base32's one implementation + (`detail/formats/base32_codec.hpp`) over its own alphabet (`detail/formats/zbase32.hpp`). +*/ +#ifndef WEBCPP_CODECS_ZBASE32_HPP +#define WEBCPP_CODECS_ZBASE32_HPP + +#include + +#include +#include +#include + +#include + +namespace webcpp::codecs::formats { + +/** + The type of the format z-base-32: bytes only, five bytes as eight symbols, the last group as short + as its bytes make it (2, 4, 5 or 7 symbols) and its unused bits zero, no padding, no option. + + Encode writes lower case, and its exact size: 32 bytes are `text<52>`. Decode is canonical, one + text for one byte string: a character that is no symbol of the alphabet, an upper-case letter and + `=` among them (z-base-32 has no padding), is @ref error::invalid_character; a length no byte count + has (a remainder of 1, 3 or 6 characters modulo 8) is @ref error::invalid_length; non-zero bits + past the last byte are @ref error::invalid_padding (`yb` is no text: one byte leaves two bits, and + `b` is 1). When a text has more than one fault, the lowest value of @ref error is reported (B23). + pkarr's decoder is more lenient on the last two (it truncates such a length and ignores those + bits): a text it takes that this decode refuses is no z-base-32 its encoder writes. + + The document's bit-length mode, a length in bits known to both sides, is not this format's: it + converts bytes. A text may be decoded into its own storage. Encode and decode, one-shot and + streamed, index no table by a data byte and branch on none (D12); the text's length, the result's + length and its success are public. +*/ +struct zbase32_t { + /** The format's name. */ + static constexpr std::string_view name = "zbase32"; +}; + +/** The format z-base-32: `codecs::encode(codecs::formats::zbase32, public_key)`. */ +inline constexpr zbase32_t zbase32{}; + +} // namespace webcpp::codecs::formats + +namespace webcpp::codecs { + +/** The codec of z-base-32: base32's over z-base-32's alphabet, in constant time. */ +template <> +struct codec + : detail::base32_codec {}; + +/** The stream codec of z-base-32 (D20): base32's, which holds a group, in constant time. */ +template <> +struct stream_codec + : detail::base32_stream_codec {}; + +} // namespace webcpp::codecs + +#endif // WEBCPP_CODECS_ZBASE32_HPP diff --git a/meta/include-boundaries.json b/meta/include-boundaries.json index d187245..a1ada4a 100644 --- a/meta/include-boundaries.json +++ b/meta/include-boundaries.json @@ -13,6 +13,7 @@ "webcpp/codecs/bech32", "webcpp/codecs/percent", "webcpp/codecs/armor", + "webcpp/codecs/zbase32", "webcpp/codecs/detail/formats", "boost/url" ], @@ -30,6 +31,7 @@ "webcpp/codecs/bech32", "webcpp/codecs/percent", "webcpp/codecs/armor", + "webcpp/codecs/zbase32", "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)" diff --git a/meta/libraries.json b/meta/libraries.json index 61e7d16..55dec87 100644 --- a/meta/libraries.json +++ b/meta/libraries.json @@ -2,7 +2,7 @@ "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.", + "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, z-base-32, base58, base64, bech32, percent-encoding and RFC 7468's armor.", "category": ["String", "Cryptography"], "maintainers": ["R "], "cxxstd": "20", diff --git a/test/Jamfile b/test/Jamfile index a1782ab..187dad7 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -28,8 +28,8 @@ rule codecs-compile ( name : sources + : requirements * : 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/hex.hpp codecs/base32.hpp codecs/zbase32.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 @@ -131,6 +131,16 @@ codecs-run base32 : base32_test.cpp ; # 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 ; +# z-base-32 (the change zbase32): pkarr's key with its bytes, pkarr's other +# keys and refused keys, the document's byte examples, 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 exact sizes and the bounds at SIZE_MAX. +codecs-run zbase32 : zbase32_test.cpp ; +# z-base-32 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 zbase32_stream : zbase32_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 diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index 6457589..186439d 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include @@ -1333,6 +1334,60 @@ void check_base32_streams() { BOOST_TEST(verdict); } +/** + z-base-32's buffer forms, fixed results, typed decodes into fixed types, secret fixed results and + streams allocate nothing, in the window of each: a pkarr key's 32 bytes in text<52> and back. +*/ +void check_zbase32() { + 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::zbase32, digest); // built before the windows + bool volatile verdict = false; + test::expect_no_allocation("z-base-32's buffer forms and refusals", [&] { + auto const written = codecs::encode(formats::zbase32, digest, text); + auto const back = codecs::decode(formats::zbase32, + std::string_view{text.data(), written.value()}, decoded); + verdict = written.has_value() && written.value() == 52 && back.has_value() && + back.value() == 32 && decoded == digest && + !codecs::decode(formats::zbase32, std::string_view{"yb"}, decoded).has_value() && + !codecs::decode(formats::zbase32, std::string_view{"Yy"}, decoded).has_value() && + !codecs::encode(formats::zbase32, digest, std::span{text}.first(51)).has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("z-base-32's fixed and secret fixed results", [&] { + auto const encoded = codecs::encode(formats::zbase32, digest); + auto const back = codecs::decode(formats::zbase32, encoded.value()); + auto const into_array = codecs::decode>( + formats::zbase32, fixed_text.value().view()); + auto const from_key = codecs::encode(formats::zbase32, key); + auto const into_secret = + codecs::decode>(formats::zbase32, fixed_text.value().view()); + auto const secret_back = + codecs::decode(formats::zbase32, fixed_text.value(), codecs::tokens::secret); + verdict = encoded.has_value() && back.has_value() && back.value().size() == 32 && + into_array.has_value() && from_key.has_value() && into_secret.has_value() && + secret_back.has_value(); + }); + BOOST_TEST(verdict); + test::expect_no_allocation("encoder(zbase32) and a secret decoder(zbase32)", [&] { + auto encoder = codecs::encoder(formats::zbase32); + bool streamed = encoder.send(digest).has_value() && + encoder.receive(std::span{text}.first(7)).has_value() && + encoder.flush().has_value() && + encoder.receive(std::span{text}.subspan(7)).has_value(); + auto decoder = codecs::decoder(formats::zbase32, codecs::secret_operation); + streamed = streamed && decoder.send(std::span{text}).has_value() && + decoder.receive(decoded).has_value() && decoder.flush().has_value(); + auto moved{std::move(decoder)}; + moved.reset(); + verdict = streamed && decoded == digest; + }); + 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 @@ -1694,6 +1749,7 @@ int main() { check_base32_one_shot_forms(); check_base32_mebibyte(); check_base32_streams(); + check_zbase32(); check_bech32_one_shot_forms(); check_bech32_mebibyte(); check_base58_one_shot_forms(); diff --git a/test/noexcept_test.cpp b/test/noexcept_test.cpp index 3e683ba..6fcbe97 100644 --- a/test/noexcept_test.cpp +++ b/test/noexcept_test.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -789,6 +790,42 @@ static_assert(noexcept(std::declval().receive(std::span< static_assert(noexcept(std::declval().receive(std::span{}))); static_assert(noexcept(std::declval().flush())); +// z-base-32 (the change zbase32): base32's implementation over its alphabet, so the same: the +// codec's six functions, the buffer forms, the fixed and secret fixed results and every call of the +// streams, public and secret, are noexcept; a heap result is not. +using zbase32_codec = codecs::codec; +static_assert(noexcept(zbase32_codec::max_encoded_size(0))); +static_assert(noexcept(zbase32_codec::max_decoded_size(0))); +static_assert(noexcept(zbase32_codec::encoded_size(formats::zbase32, + std::span{}))); +static_assert(noexcept(zbase32_codec::decoded_size(formats::zbase32, std::string_view{}))); +static_assert(noexcept(zbase32_codec::encode(formats::zbase32, std::span{}, + std::span{}))); +static_assert(noexcept(zbase32_codec::decode(formats::zbase32, std::string_view{}, + std::span{}))); +static_assert(noexcept(codecs::encode(formats::zbase32, std::array{}))); +static_assert(noexcept(codecs::decode(formats::zbase32, codecs::text<52>{}))); +static_assert(noexcept(codecs::decode>(formats::zbase32, "yy"))); +static_assert(noexcept(codecs::decode>(formats::zbase32, "yy"))); +static_assert(noexcept(codecs::encode(formats::zbase32, + std::declval>()))); +static_assert(!noexcept(codecs::encode(formats::zbase32, std::vector{}))); +static_assert(!noexcept(codecs::decode(formats::zbase32, std::string_view{}))); +using zbase32_encoder = decltype(codecs::encoder(formats::zbase32)); +using secret_zbase32_decoder = + decltype(codecs::decoder(formats::zbase32, codecs::secret_operation)); +static_assert(noexcept(codecs::encoder(formats::zbase32))); +static_assert(noexcept(codecs::decoder(formats::zbase32, codecs::secret_operation))); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().send(std::span{}))); +static_assert(noexcept(std::declval().receive(std::span{}))); +static_assert(noexcept(std::declval().flush())); +static_assert(noexcept(std::declval().reset())); + // bech32 and bech32m (Task 17): every instance's codec, the configuring calls, the word helper // that writes into a span, the buffer, fixed, secret fixed and parts forms, and every call of the // streams, public and secret, are noexcept; a heap result is not, nor append_words_from_bytes, diff --git a/test/support/zbase32_reference.hpp b/test/support/zbase32_reference.hpp new file mode 100644 index 0000000..9ad0158 --- /dev/null +++ b/test/support/zbase32_reference.hpp @@ -0,0 +1,91 @@ +// 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) + +// z-base-32's reference, which every test of it compares the library with: the plain table, the +// plain branches and the rules of the change zbase32's canonical decode written out once, in the +// order of the error values (B23). encode writes the text by the table, in lower case, the bytes' +// bits most significant first and the last symbol's unused bits zero; decode reads it by the rules: +// every character a symbol of the alphabet, lower case alone, `=` none (invalid_character), then +// the length (invalid_length: a remainder of 1, 3 or 6), then the bits at the end of the last group +// (invalid_padding: zero), and the bytes of a text with no fault. + +#ifndef WEBCPP_CODECS_TEST_SUPPORT_ZBASE32_REFERENCE_HPP +#define WEBCPP_CODECS_TEST_SUPPORT_ZBASE32_REFERENCE_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace webcpp::codecs::test { + +/** The 32 symbols of z-base-32, the value of each its index. */ +inline constexpr std::string_view zbase32_symbols = "ybndrfg8ejkmcpqxot1uwisza345h769"; + +/** The text of `bytes` by the plain table. */ +inline std::string reference_zbase32_encode(std::span bytes) { + std::string text; + unsigned bits = 0; + std::size_t bit_count = 0; + for (std::uint8_t const byte : bytes) { + bits = ((bits << 8U) | byte) & 0xfffU; + bit_count += 8; + while (bit_count >= 5) { + bit_count -= 5; + text += zbase32_symbols[(bits >> bit_count) & 31U]; + } + } + if (bit_count != 0) { + text += zbase32_symbols[(bits << (5 - bit_count)) & 31U]; + } + return text; +} + +/** What the reference reads in a text: its fault, or its bytes. */ +struct zbase32_reading { + /** The fault of the lowest value, if the text has one. */ + std::optional fault; + /** The bytes of a text with no fault. */ + std::vector bytes; +}; + +/** The plain reading of `text`, by the rules of the header's comment. */ +inline zbase32_reading reference_zbase32_decode(std::string_view text) { + for (char const character : text) { + if (zbase32_symbols.find(character) == std::string_view::npos) { + return {.fault = error::invalid_character, .bytes = {}}; + } + } + std::size_t const rest = text.size() % 8; + if (rest == 1 || rest == 3 || rest == 6) { + return {.fault = error::invalid_length, .bytes = {}}; + } + std::vector bytes; + unsigned bits = 0; + std::size_t bit_count = 0; + for (char const character : text) { + bits = ((bits << 5U) | static_cast(zbase32_symbols.find(character))) & 0xfffU; + bit_count += 5; + if (bit_count >= 8) { + bit_count -= 8; + bytes.push_back(static_cast((bits >> bit_count) & 255U)); + } + } + // The bits past the last whole byte must be zero. + if ((bits & ((1U << bit_count) - 1U)) != 0) { + return {.fault = error::invalid_padding, .bytes = {}}; + } + return {.fault = std::nullopt, .bytes = bytes}; +} + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_SUPPORT_ZBASE32_REFERENCE_HPP diff --git a/test/windows_h_after_test.cpp b/test/windows_h_after_test.cpp index a16d703..a56ff23 100644 --- a/test/windows_h_after_test.cpp +++ b/test/windows_h_after_test.cpp @@ -20,6 +20,7 @@ #include #include #include +#include // codecs defines neither macro: it includes no . #if defined(_WIN32) && (defined(NOMINMAX) || defined(WIN32_LEAN_AND_MEAN)) @@ -50,6 +51,8 @@ int main() { BOOST_TEST(base64.value().view() == "Aav/"); auto const base32 = codecs::encode(formats::base32, bytes); BOOST_TEST(base32.value().view() == "AGV76==="); + auto const zbase32 = codecs::encode(formats::zbase32, bytes); + BOOST_TEST(zbase32.value().view() == "ygi96"); auto const base58 = codecs::encode(formats::base58, bytes); auto const back = codecs::decode(formats::base58, base58.value()); BOOST_TEST(back.has_value() && back->size() == 3); diff --git a/test/windows_h_before_test.cpp b/test/windows_h_before_test.cpp index f89ba74..024a415 100644 --- a/test/windows_h_before_test.cpp +++ b/test/windows_h_before_test.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include @@ -53,6 +54,8 @@ int main() { BOOST_TEST(base64.value().view() == "Aav/"); auto const base32 = codecs::encode(formats::base32, bytes); BOOST_TEST(base32.value().view() == "AGV76==="); + auto const zbase32 = codecs::encode(formats::zbase32, bytes); + BOOST_TEST(zbase32.value().view() == "ygi96"); auto const base58 = codecs::encode(formats::base58, bytes); auto const back = codecs::decode(formats::base58, base58.value()); BOOST_TEST(back.has_value() && back->size() == 3); diff --git a/test/zbase32_stream_test.cpp b/test/zbase32_stream_test.cpp new file mode 100644 index 0000000..9e52b06 --- /dev/null +++ b/test/zbase32_stream_test.cpp @@ -0,0 +1,348 @@ +// 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) + +// z-base-32 as a stream (D20, the change zbase32's "The stream equals the one-shot form"): +// encoder(zbase32) and decoder(zbase32) are its one-shot transformers always and its stream +// transformers through stream_codec, base32's over z-base-32's alphabet, which has no padding: the +// decoder delivers each byte as the character that completes it is read and holds none. pkarr's +// key, bytes of 0 to 11, 31 to 33 and 200, and 1000 random inputs equal the one-shot forms for +// every chunking (support/chunkings.hpp), public and secret; every invalid text gives the one-shot +// form's error after flush, each class of fault and every byte value as a character at each place +// of a group among them; empty input; a moved-from stream converts from the start; a secret stream +// wipes its pending state, as secure's wipe seam records it. + +#include "support/wipe_recorder.hpp" + +#include "support/counting.hpp" + +#include "support/chunkings.hpp" +#include "support/samples.hpp" +#include "support/steps.hpp" +#include "support/zbase32_reference.hpp" +#include "zbase32_vectors.hpp" + +#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 zbase32_encoder = decltype(codecs::encoder(formats::zbase32)); +using zbase32_decoder = decltype(codecs::decoder(formats::zbase32)); +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; + +// z-base-32 streams natively, 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(codecs::is_constant_time_v); +static_assert(codecs::is_constant_time_v); +static_assert(zbase32_encoder::max_output_size(32) == 52); +static_assert(zbase32_decoder::max_output_size(52) == 32); +// A public stream is copyable and trivially destructible, a secret one move-only and wiping (D21). +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( + codecs::is_secret_v); +// One implementation: base32's stream codec over z-base-32's alphabet. +static_assert( + std::is_base_of_v< + codecs::detail::base32_stream_codec, + codecs::stream_codec>); + +/** + The encoder, the decoder and the secret ones over every chunking of `bytes` equal the one-shot + forms: the text the reference writes, and the bytes back. +*/ +void expect_every_chunking_of(std::span bytes) { + std::string const text = test::reference_zbase32_encode(bytes); + BOOST_TEST(codecs::encode(formats::zbase32, bytes).value() == text); + auto encoder = codecs::encoder(formats::zbase32); + auto decoder = codecs::decoder(formats::zbase32); + test::expect_every_chunking(encoder, bytes, text); + test::expect_every_chunking(decoder, test::characters_of(text), bytes); + auto secret_encoder = codecs::encoder(formats::zbase32, codecs::secret_operation); + auto secret_decoder = codecs::decoder(formats::zbase32, codecs::secret_operation); + test::expect_every_chunking(secret_encoder, bytes, text); + test::expect_every_chunking(secret_decoder, test::characters_of(text), bytes); +} + +/** `bytes` through `chunkings` random chunkings, public and secret, both directions. */ +void expect_random_chunkings_of(std::span bytes, std::mt19937_64& generator, + int chunkings) { + std::string const text = test::reference_zbase32_encode(bytes); + std::span const characters = test::characters_of(text); + auto encoder = codecs::encoder(formats::zbase32); + auto decoder = codecs::decoder(formats::zbase32); + auto secret_encoder = codecs::encoder(formats::zbase32, codecs::secret_operation); + auto secret_decoder = codecs::decoder(formats::zbase32, 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); +} + +/** + Bytes of every length from 0 to 11, 31 to 33, 200 (past the exhaustive splits' limit, so on the + grid of cuts), the document's examples and pkarr's key (by its text: the decode of the text, then + every chunking of its bytes), over every chunking. +*/ +void every_chunking_equals_the_one_shot_form() { + for (std::size_t size = 0; size < 12; ++size) { + expect_every_chunking_of(test::random_bytes(size)); + } + for (std::size_t const size : std::array{31, 32, 33, 200}) { + expect_every_chunking_of(test::random_bytes(size)); + } + for (std::string_view const text : + {test::pkarr_key.text, test::zbase32_document_vectors[0].text, + test::zbase32_document_vectors[1].text}) { + auto const bytes = codecs::decode(formats::zbase32, text); + BOOST_TEST(bytes.has_value()); + if (bytes) { + BOOST_TEST(test::reference_zbase32_encode(bytes.value()) == text); + expect_every_chunking_of(bytes.value()); + } + } +} + +/** + 1000 random inputs of 0 to 13 bytes: the first 40 over every chunking, the other 960 over 6 random + chunkings each, public and secret. +*/ +void a_thousand_random_inputs() { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): a fixed seed + std::mt19937_64 generator{20261204}; + for (int iteration = 0; iteration < 1000; ++iteration) { + std::vector bytes(generator() % 14); + for (std::uint8_t& byte : bytes) { + byte = static_cast(generator()); + } + if (iteration < 40) { + expect_every_chunking_of(bytes); + } else { + expect_random_chunkings_of(bytes, generator, 6); + } + } +} + +/** + Every chunking of `text` decodes as the one-shot form does, which the plain reference confirms: the + same bytes, or the same error, reported after flush by the call that reads the end (B44). +*/ +void expect_the_one_shot_verdict(std::string_view text) { + auto const one_shot = codecs::decode(formats::zbase32, text); + test::zbase32_reading const reference = test::reference_zbase32_decode(text); + 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(formats::zbase32, text); +} + +/** + Invalid texts give the one-shot form's error after flush, for every chunking: an upper-case + letter, `=` or any other character that is no symbol is invalid_character wherever it is, a + remainder of 1, 3 or 6 invalid_length, non-zero trailing bits invalid_padding, two faults the + lowest value (B23); then each byte value (one in five, and those that matter most) as a character + at each place of a group and as the lone last character. +*/ +void invalid_texts_give_the_one_shot_error_after_flush() { + std::string const high_character{'y', 'b', static_cast(0xc1), 'd'}; + for (std::string_view const text : { + std::string_view{"Ybndrfg8"}, + std::string_view{"yy======"}, + std::string_view{"ybndrfg8="}, + std::string_view{"ybndrfg8\n"}, + std::string_view{"ybndrfg0"}, + std::string_view{"ybndrfgl"}, + std::string_view{"y"}, + std::string_view{"yyy"}, + std::string_view{"yyyyyy"}, + std::string_view{"ybndrfg8y"}, + std::string_view{"yb"}, + std::string_view{"yyyyb"}, + std::string_view{"yyyyyyb"}, + std::string_view{"yb="}, + std::string_view{"ybb"}, + std::string_view{high_character}, + test::pkarr_refused_keys[0].text, + }) { + expect_the_one_shot_verdict(text); + } + for (std::string_view const base : {"ybndrfg8", "6n9hq", "yyyyyyy"}) { + for (std::size_t place = 0; place <= base.size(); ++place) { + for (unsigned value = 0; value < 256; ++value) { + if (value % 5 != 0 && value != '=' && value != 'Y' && value != 'o' && + 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; + } + expect_the_one_shot_verdict(text); + } + } + } +} + +/** + 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() { + auto encoder = codecs::encoder(formats::zbase32); + 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(formats::zbase32); + 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); +} + +/** + 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(32); + std::string const text = codecs::encode(formats::zbase32, 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): the moved-from state + 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); + 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): the moved-from state + 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 waiting bytes (5) and characters (8), + the decoder's seven bytes of bits and masks and its held and waiting bytes (4 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(31); + std::array text{}; + std::optional encoder; + encoder.emplace(formats::zbase32); + 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()); + // The last byte's two characters: no padding. + BOOST_TEST(test::is_step(moved_encoder.receive(text), 2, codecs::flow::finished)); + 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::zbase32); + BOOST_TEST(decoder->send(test::characters_of("ybndrfg8ejkmcp")).has_value()); + std::array decoded{}; + BOOST_TEST(test::is_step(decoder->receive(decoded), 8, 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); + + test::clear_wipes(); + { + stream_encoder public_encoder{formats::zbase32}; + BOOST_TEST(public_encoder.send(bytes).has_value()); + BOOST_TEST(public_encoder.receive(text).has_value()); + public_encoder.reset(); + stream_decoder public_decoder{formats::zbase32}; + BOOST_TEST(public_decoder.send(test::characters_of("6n9hq")).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(); + empty_input(); + a_moved_from_stream_converts_from_the_start(codecs::encoder(formats::zbase32), + codecs::decoder(formats::zbase32)); + a_moved_from_stream_converts_from_the_start( + codecs::encoder(formats::zbase32, codecs::secret_operation), + codecs::decoder(formats::zbase32, codecs::secret_operation)); + a_secret_streams_state_is_wiped(); + return boost::report_errors(); +} diff --git a/test/zbase32_test.cpp b/test/zbase32_test.cpp new file mode 100644 index 0000000..4156e2e --- /dev/null +++ b/test/zbase32_test.cpp @@ -0,0 +1,510 @@ +// 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) + +// z-base-32, the format (the change zbase32's "Format: zbase32", design D1 to D3, R1 to R10): +// pkarr's key with its bytes, pkarr's other keys and the document's byte examples (vectors of +// zbase32_vectors.hpp), through the buffer, token, default and typed forms; pkarr's refused keys +// with codecs' errors; every error of the format, one input each, among them the spec's canonical +// decode (upper case, `=`, a length of 51, a trailing bit set), and 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, and 5000 texts near the valid ones; the arithmetic of the alphabet against its +// table; a text decoded into its own storage; empty input in every form; the exact sizes and the +// default results' types, a 32-byte key in text<52> and back in bytes<32>, and the bounds +// saturating. The implementation is base32's (base32_codec.hpp), over z-base-32's alphabet. + +#include "support/counting.hpp" + +#include "support/decode_checks.hpp" +#include "support/samples.hpp" +#include "support/zbase32_reference.hpp" +#include "zbase32_vectors.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 zbase32_codec = codecs::codec; + +constexpr std::size_t size_maximum = std::numeric_limits::max(); + +// The format: a value with no option (R7). +static_assert(codecs::format); +static_assert(formats::zbase32_t::name == "zbase32"); +static_assert(std::is_empty_v); +static_assert(!std::is_invocable_v); +static_assert(!detail::takes_configuration_fault); +static_assert(!detail::configuration_fault_of(formats::zbase32).has_value()); + +// Its codec: constant time (R6), base32's implementation over its alphabet (D1), which has no +// padding (D3). +static_assert(zbase32_codec::constant_time); +static_assert(std::is_base_of_v, + zbase32_codec>); +static_assert(!detail::zbase32_alphabet::has_padding); +static_assert(!detail::base32_padded(formats::zbase32)); + +// The exact sizes (R8): ceil(8n / 5) characters, floor(5m / 8) bytes. +static_assert(zbase32_codec::max_encoded_size(0) == 0); +static_assert(zbase32_codec::max_encoded_size(1) == 2); +static_assert(zbase32_codec::max_encoded_size(2) == 4); +static_assert(zbase32_codec::max_encoded_size(3) == 5); +static_assert(zbase32_codec::max_encoded_size(4) == 7); +static_assert(zbase32_codec::max_encoded_size(5) == 8); +static_assert(zbase32_codec::max_encoded_size(6) == 10); +static_assert(zbase32_codec::max_encoded_size(32) == 52); +static_assert(zbase32_codec::max_decoded_size(0) == 0); +static_assert(zbase32_codec::max_decoded_size(1) == 0); +static_assert(zbase32_codec::max_decoded_size(2) == 1); +static_assert(zbase32_codec::max_decoded_size(7) == 4); +static_assert(zbase32_codec::max_decoded_size(8) == 5); +static_assert(zbase32_codec::max_decoded_size(52) == 32); +static_assert(codecs::encoded_size(formats::zbase32, std::array{}) == 52); +static_assert(codecs::max_decoded_size(formats::zbase32, "6n9hq") == 3); + +// The bound is exact, so it reaches SIZE_MAX, the size sentinel, at 5 * (SIZE_MAX / 8) + 4 bytes +// (SIZE_MAX is 8k + 7, the text of 5k + 4 bytes); the core refuses that input and every longer one. +constexpr std::size_t longest_input = (5 * (size_maximum / 8)) + 3; +static_assert(zbase32_codec::max_encoded_size(longest_input) == (8 * (size_maximum / 8)) + 5); +static_assert(zbase32_codec::max_encoded_size(longest_input + 1) == size_maximum); +static_assert(zbase32_codec::max_encoded_size(longest_input + 2) == size_maximum); +static_assert(zbase32_codec::max_encoded_size(size_maximum) == size_maximum); +static_assert(!detail::input_size_fault(formats::zbase32, longest_input).has_value()); +static_assert(detail::input_size_fault(formats::zbase32, longest_input + 1) == + codecs::error::input_too_long); +static_assert(zbase32_codec::max_decoded_size(size_maximum) == (size_maximum / 8 * 5) + 4); +static_assert(!detail::text_size_fault(formats::zbase32, size_maximum).has_value()); + +// The default results (R8): a pkarr key's 32 bytes in text<52>, and text<52> back in bytes<32>. +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 alphabet, as constant expressions: a value's symbol, a symbol's value and its verdict. +static_assert(detail::zbase32_alphabet::symbol_of(0) == 'y'); +static_assert(detail::zbase32_alphabet::symbol_of(1) == 'b'); +static_assert(detail::zbase32_alphabet::symbol_of(16) == 'o'); +static_assert(detail::zbase32_alphabet::symbol_of(31) == '9'); +// A value above 31 gives `\0`, as base32's arithmetic does. +static_assert(detail::zbase32_alphabet::symbol_of(32) == 0); + +/** The value of `symbol` in z-base-32's alphabet as the library reads it, and whether it is none. + */ +constexpr std::pair read_symbol(char symbol) { + std::uint8_t mask = 0; + unsigned const value = + detail::zbase32_alphabet::five_bits_of(static_cast(symbol), mask); + return {value, mask != 0}; +} + +static_assert(read_symbol('y') == std::pair{0U, false}); +static_assert(read_symbol('o') == std::pair{16U, false}); +static_assert(read_symbol('9') == std::pair{31U, false}); +static_assert(read_symbol('Y') == std::pair{0U, true}); +static_assert(read_symbol('=') == std::pair{0U, true}); +static_assert(read_symbol('0').second && read_symbol('2').second && read_symbol('l').second); +static_assert(read_symbol('v').second && read_symbol(static_cast(0xf9)).second); +static_assert(read_symbol('\0').second); + +/** The bytes of `hex_digits`, two lower-case hex digits a byte. */ +std::vector bytes_of_hex(std::string_view hex_digits) { + auto const digit = [](char character) { + return static_cast(character <= '9' ? character - '0' : character - 'a' + 10); + }; + std::vector bytes; + for (std::size_t index = 0; index + 1 < hex_digits.size(); index += 2) { + bytes.push_back(static_cast((digit(hex_digits[index]) << 4U) | + digit(hex_digits[index + 1]))); + } + return bytes; +} + +/** + One vector through every form: the default form, the buffer form (the characters past the text + unchanged, a short buffer refused), the tokens and the size; then its decode through the default, + typed, token and buffer forms and the codec's own. +*/ +void expect_vector(std::vector const& bytes, std::string_view text) { + // The reference agrees with the source. + BOOST_TEST(test::reference_zbase32_encode(bytes) == text); + auto const defaulted = codecs::encode(formats::zbase32, bytes); + BOOST_TEST(defaulted.has_value() && defaulted.value() == text); + BOOST_TEST_EQ(codecs::encoded_size(formats::zbase32, bytes), text.size()); + std::array buffer{}; + buffer.fill('x'); + auto const written = codecs::encode(formats::zbase32, bytes, std::span{buffer}); + BOOST_TEST(written.has_value() && written.value() == text.size()); + BOOST_TEST(std::string_view(buffer.data(), text.size()) == text); + BOOST_TEST(std::all_of(buffer.begin() + static_cast(text.size()), buffer.end(), + [](char character) { return character == 'x'; })); + if (!text.empty()) { + auto const short_buffer = + codecs::encode(formats::zbase32, 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(formats::zbase32, bytes, tokens::return_string); + BOOST_TEST(returned.has_value() && returned.value() == text); + std::string appended{"<"}; + BOOST_TEST(codecs::encode(formats::zbase32, bytes, tokens::append_to(appended)).has_value()); + BOOST_TEST(appended == "<" + std::string{text}); + auto const fixed = codecs::encode(formats::zbase32, bytes, tokens::fixed<64>{}); + BOOST_TEST(fixed.has_value() && fixed.value().view() == text); + + auto const decoded = codecs::decode(formats::zbase32, text); + BOOST_TEST(decoded.has_value() && decoded.value() == bytes); + auto const typed = codecs::decode>(formats::zbase32, text); + BOOST_TEST(typed.has_value() && typed.value() == bytes); + auto const fixed_bytes = codecs::decode(formats::zbase32, text, tokens::fixed<40>{}); + BOOST_TEST(fixed_bytes.has_value() && std::ranges::equal(fixed_bytes.value().view(), bytes)); + std::vector appended_bytes{0x5a}; + BOOST_TEST( + codecs::decode(formats::zbase32, text, tokens::append_to(appended_bytes)).has_value()); + BOOST_TEST_EQ(appended_bytes.size(), bytes.size() + 1); + auto const size = zbase32_codec::decoded_size(formats::zbase32, text); + BOOST_TEST(size.has_value() && size.value() == bytes.size()); + test::expect_tail_unchanged<40>( + [&](std::span output) { + return codecs::decode(formats::zbase32, text, output); + }, + bytes); + test::expect_tail_unchanged<40>( + [&](std::span output) { + return zbase32_codec::decode(formats::zbase32, text, output); + }, + bytes); +} + +/** + The spec's "pkarr's key": its 32 bytes encode into its text, of type text<52>, and the text + decodes back, into bytes<32>, an array of 32 bytes and a secret; pkarr's other keys decode to 32 + bytes and encode back to themselves; the document's byte examples (R1). +*/ +void pkarr_and_the_document() { + std::vector const key_bytes = bytes_of_hex(test::pkarr_key.bytes_hex); + BOOST_TEST_EQ(key_bytes.size(), 32U); + expect_vector(key_bytes, test::pkarr_key.text); + std::array key{}; + std::ranges::copy(key_bytes, key.begin()); + auto const encoded = codecs::encode(formats::zbase32, key); + BOOST_TEST(encoded.has_value() && encoded.value().view() == test::pkarr_key.text); + auto const back = codecs::decode(formats::zbase32, encoded.value()); + BOOST_TEST(back.has_value() && std::ranges::equal(back.value().view(), key)); + auto const as_array = + codecs::decode>(formats::zbase32, test::pkarr_key.text); + BOOST_TEST(as_array.has_value() && as_array.value() == key); + auto const as_secret = codecs::decode(formats::zbase32, test::pkarr_key.text, tokens::secret); + BOOST_TEST(as_secret.has_value() && std::ranges::equal(as_secret.value().view(), key)); + + for (std::string_view const text : test::pkarr_keys) { + auto const decoded = codecs::decode>(formats::zbase32, text); + BOOST_TEST(decoded.has_value()); + if (decoded) { + auto const again = codecs::encode(formats::zbase32, decoded.value()); + BOOST_TEST(again.has_value() && again.value().view() == text); + BOOST_TEST(test::reference_zbase32_decode(text).bytes == + std::vector(decoded.value().begin(), decoded.value().end())); + } + } + + for (test::zbase32_vector const& vector : test::zbase32_document_vectors) { + expect_vector(bytes_of_hex(vector.bytes_hex), vector.text); + } +} + +/** Checks that z-base-32 refuses `text` with `expected` in every form, writing nothing. */ +void expect_refusal(std::string_view text, codecs::error expected) { + auto const defaulted = codecs::decode(formats::zbase32, text); + BOOST_TEST(!defaulted.has_value() && defaulted.error() == expected); + auto const size = zbase32_codec::decoded_size(formats::zbase32, text); + BOOST_TEST(!size.has_value() && size.error() == expected); + std::array buffer{}; + buffer.fill(0x5a); + auto const written = codecs::decode(formats::zbase32, 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(formats::zbase32, text, tokens::append_to(appended)); + BOOST_TEST(!token.has_value() && token.error() == expected); + BOOST_TEST(appended == std::vector{0x5a}); + auto const typed = codecs::decode>(formats::zbase32, text); + BOOST_TEST(!typed.has_value() && typed.error() == expected); + BOOST_TEST(test::reference_zbase32_decode(text).fault == std::optional{expected}); +} + +/** pkarr's refused keys, with what codecs reports for each as a text of z-base-32. */ +void pkarr_refused_keys() { + for (test::pkarr_refused_key const& key : test::pkarr_refused_keys) { + if (key.error) { + expect_refusal(key.text, *key.error); + } else { + auto const decoded = codecs::decode(formats::zbase32, key.text); + BOOST_TEST(decoded.has_value() && decoded.value().size() == key.byte_count); + } + } +} + +/** + Every error of the format, one input each (R2 to R5, R9): the spec's "Canonical decode" on pkarr's + key, then each class of character that is no symbol, each remainder of no byte count, non-zero + bits at the end of each length of the last group, and two faults. +*/ +void every_error() { + constexpr auto character = codecs::error::invalid_character; + constexpr auto length = codecs::error::invalid_length; + constexpr auto padding = codecs::error::invalid_padding; + std::string const key{test::pkarr_key.text}; + // The spec's scenario: upper case, `=` appended, 51 characters, a trailing bit set. + std::string upper = key; + std::ranges::transform(upper, upper.begin(), [](char symbol) { + return symbol >= 'a' && symbol <= 'z' ? static_cast(symbol - 'a' + 'A') : symbol; + }); + expect_refusal(upper, character); + expect_refusal(key + "=", character); + expect_refusal(std::string_view{key}.substr(0, 51), length); + std::string trailing = key; + trailing.back() = 't'; + expect_refusal(trailing, padding); + // One upper-case letter alone, wherever it is (R2). + expect_refusal("Ybndrfg8", character); + expect_refusal("ybndrfgE", character); + // `=` is no symbol (R3), wherever it is: no padding is valid. + expect_refusal("yy======", character); + expect_refusal("6n9hq===", character); + expect_refusal("=", character); + expect_refusal("yy=", character); + // The characters of RFC 4648's alphabets that z-base-32 lacks, and the others. + for (char const odd : std::string_view{"02lvABZ*-_ \n\r\t/:@[`{"}) { + expect_refusal(std::string{"ybndrfg"} + odd, character); + } + expect_refusal(std::string_view{"ybndrfg\0", 8}, character); + expect_refusal("ybndrfg\x80", character); + expect_refusal("ybndrfg\xc1", character); + expect_refusal("ybndrfg\xff", character); + // The remainders that have no byte count: 1, 3 and 6 (R4). + expect_refusal("y", length); + expect_refusal("yyy", length); + expect_refusal("yyyyyy", length); + expect_refusal("yyyyyyyyy", length); + expect_refusal("yyyyyyyyyyy", length); + expect_refusal("yyyyyyyyyyyyyy", length); + // Non-zero bits at the end (R5): one byte ends in 2 bits, two in 4, three in 1, four in 3. + expect_refusal("yb", padding); + expect_refusal("yyyb", padding); + expect_refusal("yyyyb", padding); + expect_refusal("yyyyyyb", padding); + expect_refusal("yyyyyyyyyb", padding); + // Two faults give the lowest value (B23, R9). + expect_refusal("yb=", character); + expect_refusal("Yb", character); + expect_refusal("ybY", character); + expect_refusal("ybb", length); + // The valid texts of the same shapes. + for (std::string_view const valid : {"yy", "yyyy", "yyyyy", "yyyyyyy", "yyyyyyyy", "ya", "yyyo", + "yyyyo", "yyyyyye", "yyyyyyyyya"}) { + BOOST_TEST(codecs::decode(formats::zbase32, valid).has_value()); + } +} + +/** + The plain reading of `text`, compared with the library's decode and decoded_size: the same bytes, + or the same error. +*/ +void expect_the_reference_reading(std::string_view text) { + test::zbase32_reading const reference = test::reference_zbase32_decode(text); + auto const size = zbase32_codec::decoded_size(formats::zbase32, text); + std::array buffer{}; + std::span const output = std::span{buffer}.first( + std::min(buffer.size(), codecs::max_decoded_size(formats::zbase32, text))); + auto const written = codecs::decode(formats::zbase32, 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)); +} + +/** + Each of the 256 byte values as a character, `char` signed, at each place of a text: the eight of a + group, in the first group and in the last, and as the lone last character of a text of every + remainder; the verdict and the bytes equal the plain reference's. Then the alphabet alone: every + byte against the table, and every value's symbol. +*/ +void every_byte_value_as_a_character() { + for (std::string_view const base : { + "ybndrfg8ejkmcpqx", + "ybndrfg8", + "6n9hq", + "4t7ye", + "yy", + "yyyy", + "yyyyyyy", + "999999999", + "ot1uwisza345h769", + }) { + 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(replaced); + } + } + } + for (unsigned value = 0; value < 256; ++value) { + auto const character = static_cast(static_cast(value)); + std::size_t const at = test::zbase32_symbols.find(character); + auto const [five_bits, invalid] = 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) { + BOOST_TEST_EQ(static_cast( + detail::zbase32_alphabet::symbol_of(static_cast(value))), + test::zbase32_symbols[value]); + } +} + +/** + Texts near the valid ones, against the plain reference: the z-base-32 of random bytes, from 0 to + 40, with up to three characters replaced by a symbol, a symbol in upper case, `=`, a character of + RFC 4648's alphabets or any byte, and cut or lengthened by up to two characters. +*/ +void texts_near_the_valid_ones() { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): a fixed seed + std::mt19937_64 generator{20261204}; + constexpr std::string_view odd_characters = "=0l2vYBO \n*\x7f\x80\xc1\xff-_AZ"; + 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()); + } + std::string text = test::reference_zbase32_encode(bytes); + 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() % 3; + if (kind == 0) { + text[at] = odd_characters[generator() % odd_characters.size()]; + } else if (kind == 1) { + text[at] = test::zbase32_symbols[generator() % 32]; + } else { + text[at] = static_cast(generator()); + } + } + 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, 'y'); + } + expect_the_reference_reading(text); + } +} + +/** A text decoded into its own storage, each length of the last group (D1: base32's property). */ +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::zbase32, test::reference_zbase32_encode(bytes), bytes); + } +} + +/** Empty input in every encode and every decode gives an empty result. */ +void empty_input_in_every_form() { + std::array const nothing{}; + auto const fixed = codecs::encode(formats::zbase32, nothing); + static_assert(std::is_same_v> const>); + BOOST_TEST(fixed.has_value() && fixed.value().size() == 0); + auto const heap = codecs::encode(formats::zbase32, std::vector{}); + BOOST_TEST(heap.has_value() && heap.value().empty()); + auto const buffer_written = + codecs::encode(formats::zbase32, std::span{}, std::span{}); + BOOST_TEST(buffer_written.has_value() && buffer_written.value() == 0); + auto const secret_empty = codecs::encode(formats::zbase32, nothing, tokens::secret); + BOOST_TEST(secret_empty.has_value() && secret_empty.value().size() == 0); + test::expect_empty_text_decodes(formats::zbase32); +} + +/** + The typed decodes of a key: into an array of exactly 32 bytes (invalid_length otherwise), into + bytes (output_too_small below 32), with no heap. +*/ +void the_typed_decodes() { + std::array const digest = test::digest_bytes(); + auto const text = codecs::encode(formats::zbase32, digest); + BOOST_TEST(text.has_value() && text.value().size() == 52); + bool volatile verdict = false; + test::expect_no_allocation("typed decodes into fixed arrays", [&] { + auto const key = + codecs::decode>(formats::zbase32, text.value()); + auto const short_key = + codecs::decode>(formats::zbase32, text.value()); + auto const fixed = codecs::decode>(formats::zbase32, text.value()); + auto const too_small = codecs::decode>(formats::zbase32, 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); + auto const as_string = codecs::decode(formats::zbase32, text.value()); + BOOST_TEST(as_string.has_value() && as_string.value().size() == 32); +} + +} // namespace + +int main() { + pkarr_and_the_document(); + pkarr_refused_keys(); + every_error(); + every_byte_value_as_a_character(); + texts_near_the_valid_ones(); + decoding_in_place(); + empty_input_in_every_form(); + the_typed_decodes(); + return boost::report_errors(); +} diff --git a/test/zbase32_vectors.hpp b/test/zbase32_vectors.hpp new file mode 100644 index 0000000..b335cc3 --- /dev/null +++ b/test/zbase32_vectors.hpp @@ -0,0 +1,113 @@ +// 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 z-base-32, each copied as its source writes it (design R10 of the change +// zbase32: pkarr is read, never vendored, and its vectors are a few lines). +// +// pkarr, https://github.com/pubky/pkarr at 3dca3397409109f7da55d1c65ba7c3018dbfb5c7 (2026-12-01), +// which writes and reads its keys with the Rust crate base32 0.5.1, Alphabet::Z: +// - pkarr/src/types/keys.rs, lines 367 to 371 (test from_string_ref, and from_string, to_uri and +// from_uri after it): the key yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no and its 32 +// bytes, written there in decimal (1, 180, 103, ...), here in hex; +// - the keys pkarr writes without their bytes, each a valid z-base-32 text of 32 bytes: +// o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy (keys.rs, line 206, the doc comment of +// PublicKey::from_str), ed4mn3aoazuf1ahpy9rz1nyswhukbj5483ryefwkue7fbp3egkzo +// (pkarr/src/types/signed_packet.rs, line 776, test normalize_names), +// pxnu33x7jtpx9ar1ytsi4yxbp6a5o36gwhffs8zoxmbuptici1jy (design/endpoints.md, line 11) and +// yqrx81zchh6aotjj85s96gdqbmsoprxr3ks6ks6y8eccpj8b7oiy (docs/quickstart.md, line 104); +// - keys.rs, line 613 (test invalid_key): c1bkg8tfsyy8wcedtmw4fwhdmm7bbzhgg3z58tf43m5ow8w9mbus, +// which pkarr decodes, ignoring its bits past the 32nd byte (0110), and refuses as an Ed25519 +// point; codecs refuses the text itself, invalid_padding (design R5); +// - bindings/js/pkg/test/edge-cases.js, lines 64 to 69 (test "Invalid public key formats"): the +// keys pkarr's JavaScript binding refuses, with what codecs reports for each as a text of +// z-base-32 (a key of the wrong length is a valid text: its length is pkarr's to refuse). +// +// Zooko O'Whielacronx, "human-oriented base-32 encoding", version 0.9.4.6 (November 2009), +// https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt, its table of examples: the +// two rows of 24 bits, the only ones of a whole number of bytes (design R1). + +#ifndef WEBCPP_CODECS_TEST_ZBASE32_VECTORS_HPP +#define WEBCPP_CODECS_TEST_ZBASE32_VECTORS_HPP + +#include + +#include +#include +#include + +namespace webcpp::codecs::test { + +/** A text and its bytes, in hex. */ +struct zbase32_vector { + /** The bytes, two hex digits each. */ + std::string_view bytes_hex; + /** Their z-base-32 text. */ + std::string_view text; +}; + +/** pkarr's key whose bytes its tests give (keys.rs, lines 367 to 371). */ +inline constexpr zbase32_vector pkarr_key{ + .bytes_hex = "01b467a3b7913ab27a04a8edf2f3fb074cfe0ecf4babe108d67be3853b0f26c5", + .text = "yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no", +}; + +/** The keys pkarr writes without their bytes: each a valid text of 32 bytes. */ +inline constexpr std::array pkarr_keys{ + "o4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy", + "ed4mn3aoazuf1ahpy9rz1nyswhukbj5483ryefwkue7fbp3egkzo", + "pxnu33x7jtpx9ar1ytsi4yxbp6a5o36gwhffs8zoxmbuptici1jy", + "yqrx81zchh6aotjj85s96gdqbmsoprxr3ks6ks6y8eccpj8b7oiy", +}; + +/** The document's examples of a whole number of bytes: its two rows of 24 bits. */ +inline constexpr std::array zbase32_document_vectors{ + zbase32_vector{.bytes_hex = "f0bfc7", .text = "6n9hq"}, + zbase32_vector{.bytes_hex = "d47a04", .text = "4t7ye"}, +}; + +/** A text pkarr refuses as a key, and what codecs reports for it as a text of z-base-32. */ +struct pkarr_refused_key { + /** The text. */ + std::string_view text; + /** codecs' error, or std::nullopt for a valid text (of a length pkarr refuses). */ + std::optional error; + /** The bytes of a valid text. */ + std::size_t byte_count; +}; + +/** + pkarr's refused keys: its test invalid_key (keys.rs, line 613) and its JavaScript binding's list + (edge-cases.js, lines 64 to 69), in the order the binding writes them; `"1".repeat(51)` and + `"a".repeat(53)` written out. +*/ +inline constexpr std::array pkarr_refused_keys{ + pkarr_refused_key{.text = "c1bkg8tfsyy8wcedtmw4fwhdmm7bbzhgg3z58tf43m5ow8w9mbus", + .error = codecs::error::invalid_padding, + .byte_count = 0}, + pkarr_refused_key{.text = "", .error = std::nullopt, .byte_count = 0}, + // `v` and `l` are no symbols of z-base-32. + pkarr_refused_key{ + .text = "invalid", .error = codecs::error::invalid_character, .byte_count = 0}, + // 51 characters: a remainder of 3, which no byte count has. + pkarr_refused_key{.text = "111111111111111111111111111111111111111111111111111", + .error = codecs::error::invalid_length, + .byte_count = 0}, + // 53 characters, 33 bytes, its one bit past the last byte zero (`a` is 24, 11000). + pkarr_refused_key{.text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + .error = std::nullopt, + .byte_count = 33}, + // Upper case: z-base-32 is lower case alone (design R2). + pkarr_refused_key{.text = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + .error = codecs::error::invalid_character, + .byte_count = 0}, + pkarr_refused_key{.text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!", + .error = codecs::error::invalid_character, + .byte_count = 0}, +}; + +} // namespace webcpp::codecs::test + +#endif // WEBCPP_CODECS_TEST_ZBASE32_VECTORS_HPP From 1a4365b8ae8fe7b8f83ea1136c30644a423f8e90 Mon Sep 17 00:00:00 2001 From: R Date: Fri, 4 Dec 2026 00:30:29 -0300 Subject: [PATCH 3/5] codecs: z-base-32 in the own lanes: the constant-time paths, dudect's zbase32_decode and zbase32_encode with their A/A controls, the fuzz target with its corpus --- test/constant_time/dudect_test.cpp | 66 +++++++++++- test/constant_time/paths.hpp | 97 ++++++++++++++---- test/fuzz/Jamfile | 15 ++- test/fuzz/corpus/zbase32/alphabet | 1 + test/fuzz/corpus/zbase32/character_digit_two | 1 + test/fuzz/corpus/zbase32/character_digit_zero | 1 + test/fuzz/corpus/zbase32/character_equals | 1 + test/fuzz/corpus/zbase32/character_ff | 1 + test/fuzz/corpus/zbase32/character_high_byte | 1 + test/fuzz/corpus/zbase32/character_letter_l | 1 + test/fuzz/corpus/zbase32/character_letter_v | 1 + test/fuzz/corpus/zbase32/character_newline | 1 + test/fuzz/corpus/zbase32/character_nul | Bin 0 -> 12 bytes .../corpus/zbase32/character_rfc4648_letter | 1 + test/fuzz/corpus/zbase32/character_space | 1 + test/fuzz/corpus/zbase32/document_d47a04 | 1 + test/fuzz/corpus/zbase32/document_f0bfc7 | 1 + test/fuzz/corpus/zbase32/empty | 1 + test/fuzz/corpus/zbase32/four_bytes | 1 + test/fuzz/corpus/zbase32/length_1 | 1 + test/fuzz/corpus/zbase32/length_3 | 1 + test/fuzz/corpus/zbase32/length_6 | 1 + test/fuzz/corpus/zbase32/length_and_character | 1 + .../corpus/zbase32/length_and_trailing_bits | 1 + test/fuzz/corpus/zbase32/one_byte | 1 + test/fuzz/corpus/zbase32/pkarr_invalid_key | 1 + test/fuzz/corpus/zbase32/pkarr_key | 1 + test/fuzz/corpus/zbase32/pkarr_key_cut | 1 + test/fuzz/corpus/zbase32/pkarr_key_padded | 1 + .../corpus/zbase32/pkarr_key_trailing_bit | 1 + test/fuzz/corpus/zbase32/pkarr_key_upper_case | 1 + test/fuzz/corpus/zbase32/pkarr_other_key | 1 + test/fuzz/corpus/zbase32/sixty_four_bytes | 1 + .../corpus/zbase32/trailing_bits_four_bytes | 1 + .../corpus/zbase32/trailing_bits_one_byte | 1 + .../corpus/zbase32/trailing_bits_three_bytes | 1 + .../corpus/zbase32/trailing_bits_two_bytes | 1 + test/fuzz/corpus/zbase32/two_bytes | 1 + test/fuzz/zbase32_fuzz.cpp | 28 +++++ 39 files changed, 215 insertions(+), 25 deletions(-) create mode 100644 test/fuzz/corpus/zbase32/alphabet create mode 100644 test/fuzz/corpus/zbase32/character_digit_two create mode 100644 test/fuzz/corpus/zbase32/character_digit_zero create mode 100644 test/fuzz/corpus/zbase32/character_equals create mode 100644 test/fuzz/corpus/zbase32/character_ff create mode 100644 test/fuzz/corpus/zbase32/character_high_byte create mode 100644 test/fuzz/corpus/zbase32/character_letter_l create mode 100644 test/fuzz/corpus/zbase32/character_letter_v create mode 100644 test/fuzz/corpus/zbase32/character_newline create mode 100644 test/fuzz/corpus/zbase32/character_nul create mode 100644 test/fuzz/corpus/zbase32/character_rfc4648_letter create mode 100644 test/fuzz/corpus/zbase32/character_space create mode 100644 test/fuzz/corpus/zbase32/document_d47a04 create mode 100644 test/fuzz/corpus/zbase32/document_f0bfc7 create mode 100644 test/fuzz/corpus/zbase32/empty create mode 100644 test/fuzz/corpus/zbase32/four_bytes create mode 100644 test/fuzz/corpus/zbase32/length_1 create mode 100644 test/fuzz/corpus/zbase32/length_3 create mode 100644 test/fuzz/corpus/zbase32/length_6 create mode 100644 test/fuzz/corpus/zbase32/length_and_character create mode 100644 test/fuzz/corpus/zbase32/length_and_trailing_bits create mode 100644 test/fuzz/corpus/zbase32/one_byte create mode 100644 test/fuzz/corpus/zbase32/pkarr_invalid_key create mode 100644 test/fuzz/corpus/zbase32/pkarr_key create mode 100644 test/fuzz/corpus/zbase32/pkarr_key_cut create mode 100644 test/fuzz/corpus/zbase32/pkarr_key_padded create mode 100644 test/fuzz/corpus/zbase32/pkarr_key_trailing_bit create mode 100644 test/fuzz/corpus/zbase32/pkarr_key_upper_case create mode 100644 test/fuzz/corpus/zbase32/pkarr_other_key create mode 100644 test/fuzz/corpus/zbase32/sixty_four_bytes create mode 100644 test/fuzz/corpus/zbase32/trailing_bits_four_bytes create mode 100644 test/fuzz/corpus/zbase32/trailing_bits_one_byte create mode 100644 test/fuzz/corpus/zbase32/trailing_bits_three_bytes create mode 100644 test/fuzz/corpus/zbase32/trailing_bits_two_bytes create mode 100644 test/fuzz/corpus/zbase32/two_bytes create mode 100644 test/fuzz/zbase32_fuzz.cpp diff --git a/test/constant_time/dudect_test.cpp b/test/constant_time/dudect_test.cpp index ce5d702..ffb5da0 100644 --- a/test/constant_time/dudect_test.cpp +++ b/test/constant_time/dudect_test.cpp @@ -21,7 +21,9 @@ // class 1 random), and base32's decode of an invalid text of 64 characters, one-shot and through // the secret stream, whose `=` lie where a class puts them (class 0 in the last group alone, class // 1 also at the third to eighth places of the 7 groups before it, drawn at random), the verdict -// invalid_padding in both; bech32's decode of the 61 characters +// invalid_padding in both; z-base-32's decode of 64 characters into a secure::secret<40> against +// its text (class 0 every character 'y', class 1 random symbols) and its encode of a +// secure::secret<40> (class 0 zeros, class 1 random); bech32's decode of the 61 characters // of 32 bytes under "bc" into a secure::secret<32> (class 0 the text of zeros, class 1 the text of // random bytes, both valid, encoded unmeasured by the constant-time conversion of a // secure::secret<32>), the same text through the secret stream decoder, @@ -59,6 +61,7 @@ #include #include #include +#include #include #include @@ -296,6 +299,62 @@ void measure_base32_cases(test::case_results& results, test::case_selection cons static_cast(character_sink); } +/** + * The z-base-32 symbol of a drawn byte, by the library's own arithmetic (the class's input is + * prepared by the same instructions for both classes, unmeasured): its low five bits' symbol; the + * byte 0 gives 'y', the class 0 input. + */ +char zbase32_symbol_of(std::uint8_t drawn) { + return static_cast( + codecs::detail::zbase32_alphabet::symbol_of(static_cast(drawn & 31U))); +} + +/** + * Measures z-base-32's cases (the change zbase32), each with its A/A control, when selected: the + * decode of 64 characters (40 bytes, a whole number of groups) into a secure::secret<40>, every one + * 'y' against random symbols of the alphabet, and the encode of a secure::secret<40>, zeros against + * random bytes. Its alphabet is read by masks over its 32 symbols, which no range of ASCII holds. + * @param results Where each case measured is recorded. + * @param selection The cases to measure. + */ +void measure_zbase32_cases(test::case_results& results, test::case_selection const& selection) { + std::uint8_t volatile byte_sink = 0; // keeps an operation from being optimised away + char volatile character_sink = 0; + std::array const zero_symbols{}; + std::array symbol_draws{}; + std::array symbols{}; + measure_with_control( + results, selection, "zbase32_decode", + [&](int which, auto& generator) { + test::choose(which, generator, zero_symbols, symbol_draws); + std::ranges::transform(symbol_draws, symbols.begin(), zbase32_symbol_of); + }, + [&] { + auto const key = codecs::decode>( + formats::zbase32, std::string_view{symbols.data(), symbols.size()}); + byte_sink = key ? key->bytes()[0] : std::uint8_t{0}; + }, + {{"symbols", symbols.data()}}); + + std::array const zero_bytes{}; + std::array drawn_bytes{}; + secure::secret<40> key; + measure_with_control( + results, selection, "zbase32_encode", + [&](int which, auto& generator) { + test::choose(which, generator, zero_bytes, drawn_bytes); + std::ranges::copy(drawn_bytes, key.writable().begin()); + }, + [&] { + auto const encoded = codecs::encode(formats::zbase32, key); + character_sink = encoded ? encoded->data()[0] : '\0'; + }, + {{"key", key.bytes().data()}}); + + static_cast(byte_sink); + static_cast(character_sink); +} + /** * base58's cases, its secret operations: 32 bytes, 0xc0 then zeros for class 0 and random for * class 1, their two top bits set in both by the same instructions, so that every text is of one @@ -470,6 +529,10 @@ int main(int argc, char** argv) { "base32_padding_layout_aa", "base32_stream_padding_layout", "base32_stream_padding_layout_aa", + "zbase32_decode", + "zbase32_decode_aa", + "zbase32_encode", + "zbase32_encode_aa", "bech32_decode", "bech32_decode_aa", "bech32_stream_decode", @@ -625,6 +688,7 @@ int main(int argc, char** argv) { {{"text", layout_text.data()}}); measure_base32_cases(results, *selection); + measure_zbase32_cases(results, *selection); // bech32 decode: the text of 32 zero bytes under "bc", against the text of random bytes, each // encoded unmeasured: the same length, both valid. Each text is encoded by the constant-time diff --git a/test/constant_time/paths.hpp b/test/constant_time/paths.hpp index 2af8317..8a58364 100644 --- a/test/constant_time/paths.hpp +++ b/test/constant_time/paths.hpp @@ -14,7 +14,8 @@ // of 7 elements (a fixed, public size), received into spans of 5, every input marked secret with // Checker::mark_secret; base32's and base32hex's, with the padding written and omitted, the same // over the same 64 bytes (104 characters with the padding, 103 without: the last group's padding is -// the result's public length) and over invalid texts of the three faults the data can have; +// the result's public length) and over invalid texts of the three faults the data can have, and +// z-base-32's by the same paths (103 characters, `=` no symbol of it); // base64's and base64url's, with the padding written and omitted, the same // over the same 64 bytes (88 characters with the padding, 86 without: the last group's padding is // the result's public length) and over invalid texts of the three faults the data can have; @@ -64,6 +65,7 @@ #include "../support/bech32_reference.hpp" #include "../support/bounded_records.hpp" #include "../support/constant_time_marks.hpp" +#include "../support/zbase32_reference.hpp" #include #include @@ -72,6 +74,7 @@ #include #include #include +#include #include #include @@ -604,6 +607,15 @@ struct base32_configuration { /** The characters of the 64 bytes: eight a group, the padding written or omitted. */ static constexpr std::size_t text_size = Padded ? 104 : 103; + /** The symbol of the value 1, which sets a trailing bit in the last group's seventh place. */ + static constexpr char symbol_of_one = 'B'; + + /** Where a `=` is out of place: the last group's second place, or the unpadded text's last. */ + static constexpr std::size_t misplaced_padding_place = Padded ? 97 : text_size - 1; + + /** The error of a `=` out of place. */ + static constexpr error misplaced_padding_error = error::invalid_padding; + /** The format of the configuration. */ static auto format() noexcept { namespace formats = codecs::formats; @@ -663,10 +675,51 @@ struct base32_configuration { } }; +/** + The configuration of the z-base-32 block (the change zbase32), which base32's paths run: the same + 64 bytes, 103 characters with no padding, its alphabet's symbol of 1, and `=`, which is no symbol + of it, invalid_character. +*/ +struct zbase32_configuration { + /** The characters of the 64 bytes: eight a group, no padding. */ + static constexpr std::size_t text_size = 103; + + /** The symbol of the value 1, which sets a trailing bit in the last group's seventh place. */ + static constexpr char symbol_of_one = 'b'; + + /** Where a `=` is put: the text's last place. */ + static constexpr std::size_t misplaced_padding_place = text_size - 1; + + /** `=` is no symbol of z-base-32 (its design R3). */ + static constexpr error misplaced_padding_error = error::invalid_character; + + /** The format. */ + static auto format() noexcept { return codecs::formats::zbase32; } + + /** The configuration's name, for a failed check's line. */ + static constexpr char const* encode_name() noexcept { return "zbase32 encode"; } + + /** The configuration's name, for a failed check's line. */ + static constexpr char const* decode_name() noexcept { return "zbase32 decode"; } + + /** The configuration's name for its invalid texts, for a failed check's line. */ + static constexpr char const* invalid_name() noexcept { + return "zbase32 decode of an invalid text"; + } + + /** The text of `hex_plain_bytes`, written plainly from public bytes by the reference. */ + static std::array plain_text() { + std::string const text = reference_zbase32_encode(hex_plain_bytes()); + std::array characters{}; + std::ranges::copy(text, characters.begin()); + return characters; + } +}; + /** base32's encode of 64 secret bytes: one-shot, the buffer form, secret_text and the stream. */ -template +template int base32_encode_paths() { - using configuration = base32_configuration; + using configuration = Configuration; constexpr std::size_t text_size = configuration::text_size; auto const format = configuration::format(); char const* const name = configuration::encode_name(); @@ -721,10 +774,10 @@ int base32_encode_paths() { decode into secure::secret<64> and the stream, each verdict held public after the library's declassify. */ -template +template int base32_decode_paths() { namespace tokens = codecs::tokens; - using configuration = base32_configuration; + using configuration = Configuration; constexpr std::size_t text_size = configuration::text_size; auto const format = configuration::format(); char const* const name = configuration::decode_name(); @@ -789,9 +842,9 @@ int base32_decode_paths() { (invalid_padding): the verdict is accumulated over the whole text and reported once, after the library's declassify, in the buffer form and through the secret stream. */ -template +template int base32_invalid_paths() { - using configuration = base32_configuration; + using configuration = Configuration; constexpr std::size_t text_size = configuration::text_size; auto const format = configuration::format(); char const* const name = configuration::invalid_name(); @@ -815,25 +868,26 @@ int base32_invalid_paths() { std::array text = configuration::plain_text(); text[41] = '*'; expect_the_error(text, error::invalid_character); - // The last group's seventh symbol holds the last byte's bits and three zero ones: 'B' (1) - // sets one. + // The last group's seventh symbol holds the last byte's bits and three zero ones: the symbol + // of 1 sets one. text = configuration::plain_text(); - text[102] = 'B'; + text[102] = configuration::symbol_of_one; expect_the_error(text, error::invalid_padding); // A `=` where a symbol is: the last group's second place, where no padding starts, or in the - // unpadded text, which has no padding, its last place. + // unpadded text, which has no padding, its last place; in an alphabet with no padding, `=` is + // no symbol. text = configuration::plain_text(); - text[Padded ? 97 : text_size - 1] = '='; - expect_the_error(text, error::invalid_padding); + text[configuration::misplaced_padding_place] = '='; + expect_the_error(text, configuration::misplaced_padding_error); return failures; } /** base32's block in a configuration. */ -template +template int base32_configuration_paths() { - return base32_encode_paths() + - base32_decode_paths() + - base32_invalid_paths(); + return base32_encode_paths() + + base32_decode_paths() + + base32_invalid_paths(); } /** The configuration of a bech32 block: the format, its names and its text. */ @@ -1600,10 +1654,11 @@ int format_paths() { base64_configuration_paths() + base64_configuration_paths() + base64_configuration_paths() + - base32_configuration_paths() + - base32_configuration_paths() + - base32_configuration_paths() + - base32_configuration_paths() + + base32_configuration_paths>() + + base32_configuration_paths>() + + base32_configuration_paths>() + + base32_configuration_paths>() + + base32_configuration_paths() + bech32_configuration_paths() + bech32_configuration_paths() + base58_paths() + armor_paths() + over_value_paths(); diff --git a/test/fuzz/Jamfile b/test/fuzz/Jamfile index ecfbb3c..d9ad6b6 100644 --- a/test/fuzz/Jamfile +++ b/test/fuzz/Jamfile @@ -91,6 +91,15 @@ codecs-fuzz over_value ; codecs-fuzz base32 ; codecs-fuzz base32hex ; +# z-base-32: pkarr's keys, its invalid key (a trailing bit set) and that key in +# upper case, padded and cut, the document's texts, the alphabet, a text of +# each length of the last group and of 64 bytes, each length no byte count +# has, non-zero trailing bits of each length of the last group, one of each +# class of character that is no symbol (RFC 4648's letters and digits that +# z-base-32 lacks, `=`, NUL, a space, high bytes), and two faults. Decode is +# canonical: the round trip is the same text. +codecs-fuzz zbase32 ; + # base64 and base64url: RFC 4648's texts with the padding and without it, the # symbols of each alphabet and the other's, non-zero trailing bits, a length no # encoding has, padding out of place, one of each class of character that is no @@ -145,6 +154,6 @@ codecs-fuzz percent : /webcpp/codecs//percent ; # lines as the format writes them, under the label the parts decode returned. codecs-fuzz armor ; -webcpp.lane fuzz : hex_fuzz over_fuzz over_value_fuzz base32_fuzz base32hex_fuzz base64_fuzz - base64url_fuzz bech32_fuzz bech32m_fuzz bech32_words_fuzz base58_fuzz base58_with_checksum_fuzz - percent_fuzz armor_fuzz : native ; +webcpp.lane fuzz : hex_fuzz over_fuzz over_value_fuzz base32_fuzz base32hex_fuzz zbase32_fuzz + base64_fuzz base64url_fuzz bech32_fuzz bech32m_fuzz bech32_words_fuzz base58_fuzz + base58_with_checksum_fuzz percent_fuzz armor_fuzz : native ; diff --git a/test/fuzz/corpus/zbase32/alphabet b/test/fuzz/corpus/zbase32/alphabet new file mode 100644 index 0000000..5d0d92c --- /dev/null +++ b/test/fuzz/corpus/zbase32/alphabet @@ -0,0 +1 @@ +MÔóƒybndrfg8ejkmcpqxot1uwisza345h769 \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/character_digit_two b/test/fuzz/corpus/zbase32/character_digit_two new file mode 100644 index 0000000..6374134 --- /dev/null +++ b/test/fuzz/corpus/zbase32/character_digit_two @@ -0,0 +1 @@ +”)8ãybndrfg2 \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/character_digit_zero b/test/fuzz/corpus/zbase32/character_digit_zero new file mode 100644 index 0000000..f44b109 --- /dev/null +++ b/test/fuzz/corpus/zbase32/character_digit_zero @@ -0,0 +1 @@ +;•ybndrfg0 \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/character_equals b/test/fuzz/corpus/zbase32/character_equals new file mode 100644 index 0000000..6b67b09 --- /dev/null +++ b/test/fuzz/corpus/zbase32/character_equals @@ -0,0 +1 @@ +7êôOyy= \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/character_ff b/test/fuzz/corpus/zbase32/character_ff new file mode 100644 index 0000000..ac940c0 --- /dev/null +++ b/test/fuzz/corpus/zbase32/character_ff @@ -0,0 +1 @@ +h !Ñybndrfgÿ \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/character_high_byte b/test/fuzz/corpus/zbase32/character_high_byte new file mode 100644 index 0000000..b69e2f5 --- /dev/null +++ b/test/fuzz/corpus/zbase32/character_high_byte @@ -0,0 +1 @@ +]̯¢ybndrfgÁ \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/character_letter_l b/test/fuzz/corpus/zbase32/character_letter_l new file mode 100644 index 0000000..c861f4f --- /dev/null +++ b/test/fuzz/corpus/zbase32/character_letter_l @@ -0,0 +1 @@ +ìªúMybndrfgl \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/character_letter_v b/test/fuzz/corpus/zbase32/character_letter_v new file mode 100644 index 0000000..ef12be1 --- /dev/null +++ b/test/fuzz/corpus/zbase32/character_letter_v @@ -0,0 +1 @@ +^×uŒybndrfgv \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/character_newline b/test/fuzz/corpus/zbase32/character_newline new file mode 100644 index 0000000..fa93614 --- /dev/null +++ b/test/fuzz/corpus/zbase32/character_newline @@ -0,0 +1 @@ +¡²úybndrfg8 diff --git a/test/fuzz/corpus/zbase32/character_nul b/test/fuzz/corpus/zbase32/character_nul new file mode 100644 index 0000000000000000000000000000000000000000..d7451773ef85e33f644dc73c45a614eb26531619 GIT binary patch literal 12 TcmZ1>%eS{ODKDicEu8@XA0h;O literal 0 HcmV?d00001 diff --git a/test/fuzz/corpus/zbase32/character_rfc4648_letter b/test/fuzz/corpus/zbase32/character_rfc4648_letter new file mode 100644 index 0000000..f7c8075 --- /dev/null +++ b/test/fuzz/corpus/zbase32/character_rfc4648_letter @@ -0,0 +1 @@ +ôjŒýybndrfgA \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/character_space b/test/fuzz/corpus/zbase32/character_space new file mode 100644 index 0000000..bc982ca --- /dev/null +++ b/test/fuzz/corpus/zbase32/character_space @@ -0,0 +1 @@ +,æŠæybnd rfg8 \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/document_d47a04 b/test/fuzz/corpus/zbase32/document_d47a04 new file mode 100644 index 0000000..aee00b8 --- /dev/null +++ b/test/fuzz/corpus/zbase32/document_d47a04 @@ -0,0 +1 @@ +�ƒA'4t7ye \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/document_f0bfc7 b/test/fuzz/corpus/zbase32/document_f0bfc7 new file mode 100644 index 0000000..59732ed --- /dev/null +++ b/test/fuzz/corpus/zbase32/document_f0bfc7 @@ -0,0 +1 @@ +w™î}6n9hq \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/empty b/test/fuzz/corpus/zbase32/empty new file mode 100644 index 0000000..5cca61f --- /dev/null +++ b/test/fuzz/corpus/zbase32/empty @@ -0,0 +1 @@ +.ú‚ \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/four_bytes b/test/fuzz/corpus/zbase32/four_bytes new file mode 100644 index 0000000..0676b37 --- /dev/null +++ b/test/fuzz/corpus/zbase32/four_bytes @@ -0,0 +1 @@ +N#ë¾54s575a \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/length_1 b/test/fuzz/corpus/zbase32/length_1 new file mode 100644 index 0000000..7fee861 --- /dev/null +++ b/test/fuzz/corpus/zbase32/length_1 @@ -0,0 +1 @@ +|@d¿y \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/length_3 b/test/fuzz/corpus/zbase32/length_3 new file mode 100644 index 0000000..97fc61d --- /dev/null +++ b/test/fuzz/corpus/zbase32/length_3 @@ -0,0 +1 @@ +Àè­&ybn \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/length_6 b/test/fuzz/corpus/zbase32/length_6 new file mode 100644 index 0000000..b144004 --- /dev/null +++ b/test/fuzz/corpus/zbase32/length_6 @@ -0,0 +1 @@ +=ÁPµybndrf \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/length_and_character b/test/fuzz/corpus/zbase32/length_and_character new file mode 100644 index 0000000..5159cac --- /dev/null +++ b/test/fuzz/corpus/zbase32/length_and_character @@ -0,0 +1 @@ +NH¶ybY \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/length_and_trailing_bits b/test/fuzz/corpus/zbase32/length_and_trailing_bits new file mode 100644 index 0000000..3dd534e --- /dev/null +++ b/test/fuzz/corpus/zbase32/length_and_trailing_bits @@ -0,0 +1 @@ +;ÜJåybb \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/one_byte b/test/fuzz/corpus/zbase32/one_byte new file mode 100644 index 0000000..74c2896 --- /dev/null +++ b/test/fuzz/corpus/zbase32/one_byte @@ -0,0 +1 @@ ++kFoy \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/pkarr_invalid_key b/test/fuzz/corpus/zbase32/pkarr_invalid_key new file mode 100644 index 0000000..4839f80 --- /dev/null +++ b/test/fuzz/corpus/zbase32/pkarr_invalid_key @@ -0,0 +1 @@ +4QÕc1bkg8tfsyy8wcedtmw4fwhdmm7bbzhgg3z58tf43m5ow8w9mbus \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/pkarr_key b/test/fuzz/corpus/zbase32/pkarr_key new file mode 100644 index 0000000..76d49b7 --- /dev/null +++ b/test/fuzz/corpus/zbase32/pkarr_key @@ -0,0 +1 @@ +ƒ™ �yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/pkarr_key_cut b/test/fuzz/corpus/zbase32/pkarr_key_cut new file mode 100644 index 0000000..93669a0 --- /dev/null +++ b/test/fuzz/corpus/zbase32/pkarr_key_cut @@ -0,0 +1 @@ +¸JéÌyg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5n \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/pkarr_key_padded b/test/fuzz/corpus/zbase32/pkarr_key_padded new file mode 100644 index 0000000..dcba334 --- /dev/null +++ b/test/fuzz/corpus/zbase32/pkarr_key_padded @@ -0,0 +1 @@ +-÷%¨yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no==== \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/pkarr_key_trailing_bit b/test/fuzz/corpus/zbase32/pkarr_key_trailing_bit new file mode 100644 index 0000000..33f6645 --- /dev/null +++ b/test/fuzz/corpus/zbase32/pkarr_key_trailing_bit @@ -0,0 +1 @@ +…ÿ{¦yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5nt \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/pkarr_key_upper_case b/test/fuzz/corpus/zbase32/pkarr_key_upper_case new file mode 100644 index 0000000..511af99 --- /dev/null +++ b/test/fuzz/corpus/zbase32/pkarr_key_upper_case @@ -0,0 +1 @@ +æ ŠmYG4GXE7Z1R7MR6ORIDS9FH95Y7GXHDSXJQI6NNGSXXTAKQAXR5NO \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/pkarr_other_key b/test/fuzz/corpus/zbase32/pkarr_other_key new file mode 100644 index 0000000..8e568f9 --- /dev/null +++ b/test/fuzz/corpus/zbase32/pkarr_other_key @@ -0,0 +1 @@ +Ô'ƒQo4dksfbqk85ogzdb5osziw6befigbuxmuxkuxq8434q89uj56uyy \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/sixty_four_bytes b/test/fuzz/corpus/zbase32/sixty_four_bytes new file mode 100644 index 0000000..c906b95 --- /dev/null +++ b/test/fuzz/corpus/zbase32/sixty_four_bytes @@ -0,0 +1 @@ +"\¦¦yyyoryarywdyqnyjbefoadeqbhebnrounoktcfaadrpbs8y7dax1yejnrc1nkjt8fyw1wk3cfwzn6cbtge3uepjsghhd1qt58o6uhxa \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/trailing_bits_four_bytes b/test/fuzz/corpus/zbase32/trailing_bits_four_bytes new file mode 100644 index 0000000..bc56733 --- /dev/null +++ b/test/fuzz/corpus/zbase32/trailing_bits_four_bytes @@ -0,0 +1 @@ +;Cyyyyyyb \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/trailing_bits_one_byte b/test/fuzz/corpus/zbase32/trailing_bits_one_byte new file mode 100644 index 0000000..a5c24ae --- /dev/null +++ b/test/fuzz/corpus/zbase32/trailing_bits_one_byte @@ -0,0 +1 @@ +¢¦7’yb \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/trailing_bits_three_bytes b/test/fuzz/corpus/zbase32/trailing_bits_three_bytes new file mode 100644 index 0000000..fd70354 --- /dev/null +++ b/test/fuzz/corpus/zbase32/trailing_bits_three_bytes @@ -0,0 +1 @@ +@~ÑÌyyyyb \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/trailing_bits_two_bytes b/test/fuzz/corpus/zbase32/trailing_bits_two_bytes new file mode 100644 index 0000000..ea6c825 --- /dev/null +++ b/test/fuzz/corpus/zbase32/trailing_bits_two_bytes @@ -0,0 +1 @@ +m,Õyyyb \ No newline at end of file diff --git a/test/fuzz/corpus/zbase32/two_bytes b/test/fuzz/corpus/zbase32/two_bytes new file mode 100644 index 0000000..af58bcb --- /dev/null +++ b/test/fuzz/corpus/zbase32/two_bytes @@ -0,0 +1 @@ +Á«‰Vne4y \ No newline at end of file diff --git a/test/fuzz/zbase32_fuzz.cpp b/test/fuzz/zbase32_fuzz.cpp new file mode 100644 index 0000000..5e483e0 --- /dev/null +++ b/test/fuzz/zbase32_fuzz.cpp @@ -0,0 +1,28 @@ +// 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 fuzz target of z-base-32 (the change zbase32): every input is a text decoded in +// formats::zbase32, through the buffer form with no heap and through its public and secret +// streams, each split where the input's seed chooses, which give the same bytes or the same error; +// what decodes encodes back to the same text, since decode is canonical (lower case alone, no +// padding, zero trailing bits); the input's bytes are also encoded, and their text checked alike +// (target.hpp). + +#include "target.hpp" + +#include + +#include +#include +#include + +// NOLINTNEXTLINE(readability-identifier-naming): libFuzzer's name for the target +extern "C" int LLVMFuzzerTestOneInput(std::uint8_t const* data, std::size_t size) { + namespace formats = webcpp::codecs::formats; + namespace test = webcpp::codecs::test; + test::check_decoder(formats::zbase32, std::span{data, size}, test::round_trip::same_text); + return 0; +} From cb8afe5b4ce991a343427ecefb2f8b80e334469e Mon Sep 17 00:00:00 2001 From: R Date: Fri, 4 Dec 2026 00:30:29 -0300 Subject: [PATCH 4/5] codecs: z-base-32 on the page: its section with the example zbase32_pkarr.cpp, the tables, the changelog's line --- AGENTS.md | 4 +-- README.md | 4 +-- doc/allocators.adoc | 2 +- doc/changelog.adoc | 2 +- doc/codecs.adoc | 6 ++-- doc/formats.adoc | 41 ++++++++++++++++++++++- doc/overview.adoc | 9 +++++- doc/secrecy.adoc | 2 +- doc/streams.adoc | 2 +- example/Jamfile | 1 + example/zbase32_pkarr.cpp | 59 ++++++++++++++++++++++++++++++++++ example/zbase32_pkarr.expected | 6 ++++ 12 files changed, 125 insertions(+), 13 deletions(-) create mode 100644 example/zbase32_pkarr.cpp create mode 100644 example/zbase32_pkarr.expected diff --git a/AGENTS.md b/AGENTS.md index 5ad6934..0e02672 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,8 +10,8 @@ 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). + values to text and back, and any data through one-shot and stream transformers, with eight + formats (hex, base32, z-base-32, 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`. diff --git a/README.md b/README.md index d89f347..60815bb 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ codecs holds webcpp's one contract for converting bytes and typed values to text and back, and any data through one-shot and stream transformers, for C++20 on every target [webcpp](https://github.com/webcpporg/webcpp) has: native (Linux, macOS, Windows with MSVC), -wasip2, wasip3 and Emscripten. Over that contract it ships seven formats: hex, base32, base58, -base64, bech32, percent-encoding and RFC 7468's armor, every name in `webcpp::codecs`. It is +wasip2, wasip3 and Emscripten. Over that contract it ships eight formats: hex, base32, z-base-32, +base58, 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. Every format is a value (`codecs::formats::hex`), an operation a function of it diff --git a/doc/allocators.adoc b/doc/allocators.adoc index d208320..d418da0 100644 --- a/doc/allocators.adoc +++ b/doc/allocators.adoc @@ -23,7 +23,7 @@ codecs allocates through it and through nothing else. | `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 +| the conversion of every format, in every form: hex, base32, z-base-32, 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 diff --git a/doc/changelog.adoc b/doc/changelog.adoc index d21c456..46c6c31 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -19,7 +19,7 @@ of every version are on webcpp's index page. * Added codecs.hpp and config.hpp: encode, decode, tokens, results, secrecy and over, errors as values, value_formats for a library's value types, and max_decode_input_size as a value codec's bound on every path. * 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 base32.hpp and zbase32.hpp: base32 and base32hex of RFC 4648, padding an option, and z-base-32, pkarr's keys, 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. diff --git a/doc/codecs.adoc b/doc/codecs.adoc index 5a20434..5465d59 100644 --- a/doc/codecs.adoc +++ b/doc/codecs.adoc @@ -16,9 +16,9 @@ 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. +base32, z-base-32, 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 diff --git a/doc/formats.adoc b/doc/formats.adoc index 8c585d2..21b9411 100644 --- a/doc/formats.adoc +++ b/doc/formats.adoc @@ -19,7 +19,7 @@ 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 +core: hex, base32, z-base-32 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). @@ -96,6 +96,45 @@ include::{examples}/rfc4648.expected[] than the text seems to give is not stuck: it waits for the next character or for `flush`. +[#codecs-zbase32] +=== z-base-32 + +`formats::zbase32` is z-base-32, Zooko O'Whielacronx's human-oriented base-32 +encoding: base32's grouping of five bytes as eight symbols, over the alphabet +`ybndrfg8ejkmcpqxot1uwisza345h769`, in lower case and with no padding. pkarr +writes an Ed25519 public key in it, 32 bytes as the 52 characters of a name, +and iroh reaches pkarr's names. It has no option. Encode writes the exact size, +so a 32-byte key is a `text<52>`, and decode is canonical: an upper-case +letter, a `=` and any other character that is no symbol are +`invalid_character`, a length no byte count has is `invalid_length`, and +non-zero bits past the last byte are `invalid_padding`. It is constant time on +every call and streams natively, by base32's implementation over its own +alphabet. + +[source,cpp] +---- +include::{examples}/zbase32_pkarr.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/zbase32_pkarr.expected[] +---- + +*Pitfalls.* + +* z-base-32 is lower case alone. A name that went through a system that + changes case (a DNS label is compared without case) is lowered by the + program before it is decoded. +* pkarr's decoder is more lenient than this one: it ignores the bits past the + last byte and truncates a length no byte count has. A key's 52nd character is + `y` or `o`; a text that pkarr takes and codecs refuses is no text a z-base-32 + encoder writes. +* The document's bit-length mode, a length in bits known to both sides, is not + codecs': the format converts bytes. +* codecs reads the text alone: a `pk:` prefix, a key in a URL's host and the + check that the bytes are a point of the curve are the program's, or pkarr's. + [#codecs-base64] === base64 and base64url diff --git a/doc/overview.adoc b/doc/overview.adoc index 91f2d5b..194ddf4 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -48,6 +48,13 @@ typed decode gives the digest back as a `std::array`, and a fault is a value of | yes | <> +| `zbase32` +| `` +| always +| yes +| yes +| <> + | `base64`, `base64url` | `` | always @@ -118,7 +125,7 @@ The values are fixed and never reused: | 1 | `invalid_character` | a character is outside the format's alphabet (a byte of 128 or more included), or a word of bech32 is above 31 | 2 | `invalid_length` | the length is one no encoding of the format has, or a typed decode into a `std::array` finds another number of bytes than the array's size -| 3 | `invalid_padding` | the padding is missing, misplaced or not zero: base32 and base64's `=` and trailing bits, bech32's padding bits +| 3 | `invalid_padding` | the padding is missing, misplaced or not zero: base32 and base64's `=` and trailing bits, z-base-32's trailing bits, bech32's padding bits | 4 | `checksum_mismatch` | the checksum of bech32 or of a base58 with a checksum is wrong | 5 | `invalid_prefix` | the human-readable part or the label is not the format's, or is a fault of the format's configuration | 6 | `mixed_case` | a bech32 text holds both cases diff --git a/doc/secrecy.adoc b/doc/secrecy.adoc index 570abd2..ba927df 100644 --- a/doc/secrecy.adoc +++ b/doc/secrecy.adoc @@ -58,7 +58,7 @@ and is not offered on a temporary. === What is constant time -The encode and decode of `hex`, `base32`, `base32hex`, `base64`, `base64url`, +The encode and decode of `hex`, `base32`, `base32hex`, `zbase32`, `base64`, `base64url`, `bech32`, `bech32m` and the armor's payload are constant time on every call, one-shot and streamed, public or secret: they index no table by a data byte and branch on no data byte, a decode accumulates its verdict over the whole input and reports it diff --git a/doc/streams.adoc b/doc/streams.adoc index 6168fa9..38c1f9d 100644 --- a/doc/streams.adoc +++ b/doc/streams.adoc @@ -136,7 +136,7 @@ before it returns, by every path. | `hex` | an encoder that holds the low digit of a byte, a decoder that holds one digit of a pair -| `base32`, `base32hex`, `base64`, `base64url` +| `base32`, `base32hex`, `zbase32`, `base64`, `base64url` | an encoder that holds the bytes of a group not yet whole, a decoder that holds the bits of a group; a padded decoder holds the bytes of the group's last places until the next character or `flush` | `percent` diff --git a/example/Jamfile b/example/Jamfile index cd319bd..00644c4 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -23,6 +23,7 @@ webcpp.example percent_segment.cpp : /webcpp/codecs//percent ; webcpp.example base58_address.cpp ; webcpp.example own_format.cpp ; webcpp.example rfc4648.cpp ; +webcpp.example zbase32_pkarr.cpp ; webcpp.example tokens.cpp ; webcpp.example results.cpp ; webcpp.example over_chain.cpp ; diff --git a/example/zbase32_pkarr.cpp b/example/zbase32_pkarr.cpp new file mode 100644 index 0000000..d469f29 --- /dev/null +++ b/example/zbase32_pkarr.cpp @@ -0,0 +1,59 @@ +// 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) + +// z-base-32 in a program: a pkarr public key, the 32 bytes of an Ed25519 key, as the 52 characters +// of a pkarr name, held in place both ways, and the texts a canonical decode refuses. codecs reads +// the text alone: the `pk:` prefix, a key in a URL's host and the check that the bytes are a point +// of the curve are pkarr's. + +// tag::example[] +#include +#include + +#include +#include +#include +#include + +namespace codecs = webcpp::codecs; +namespace formats = webcpp::codecs::formats; + +namespace { + +// The public key of pkarr's own tests: 32 bytes, so its text is a text<52>, with no heap. +constexpr std::array public_key{ + 0x01, 0xb4, 0x67, 0xa3, 0xb7, 0x91, 0x3a, 0xb2, 0x7a, 0x04, 0xa8, 0xed, 0xf2, 0xf3, 0xfb, 0x07, + 0x4c, 0xfe, 0x0e, 0xcf, 0x4b, 0xab, 0xe1, 0x08, 0xd6, 0x7b, 0xe3, 0x85, 0x3b, 0x0f, 0x26, 0xc5, +}; + +// What a decode says of a text. +void show(std::string_view label, std::string_view text) { + auto const key = codecs::decode>(formats::zbase32, text); + std::cout << label << ": " << (key ? "a key" : key.error().message()) << '\n'; +} + +} // namespace + +int main() { + codecs::text<52> const name = codecs::encode(formats::zbase32, public_key).value(); + std::cout << "pkarr name: " << name.view() << '\n'; + + // The name back to the key, into an array of exactly 32 bytes. + auto const key = codecs::decode>(formats::zbase32, name); + std::cout << "decodes back: " << (key && *key == public_key) << '\n'; + + // z-base-32 is lower case alone, has no padding, and its bits past the last byte are zero: a + // 52nd character other than `y` or `o` is no encoding of 32 bytes. + show("upper case", "YG4GXE7Z1R7MR6ORIDS9FH95Y7GXHDSXJQI6NNGSXXTAKQAXR5NO"); + show("a trailing bit", "yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5nt"); + show("51 characters", "yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5n"); + // A valid text of another length is no key: decode into 32 bytes is exact. + codecs::text<7> const four_bytes = + codecs::encode(formats::zbase32, std::array{}).value(); + show("4 bytes", four_bytes.view()); +} + +// end::example[] diff --git a/example/zbase32_pkarr.expected b/example/zbase32_pkarr.expected new file mode 100644 index 0000000..f2ff565 --- /dev/null +++ b/example/zbase32_pkarr.expected @@ -0,0 +1,6 @@ +pkarr name: yg4gxe7z1r7mr6orids9fh95y7gxhdsxjqi6nngsxxtakqaxr5no +decodes back: 1 +upper case: a character is outside the format's alphabet +a trailing bit: the padding is missing, misplaced or not zero +51 characters: the length is one no encoding of the format has +4 bytes: the length is one no encoding of the format has From e55940b52f2b4eb63106a42485b714ca06775f5b Mon Sep 17 00:00:00 2001 From: R Date: Fri, 4 Dec 2026 00:32:55 -0300 Subject: [PATCH 5/5] codecs: z-base-32's tests, lint fix --- test/zbase32_stream_test.cpp | 8 +++--- test/zbase32_test.cpp | 30 ++++++++++++++++----- test/zbase32_vectors.hpp | 51 ++++++++++++++++++++++++------------ 3 files changed, 63 insertions(+), 26 deletions(-) diff --git a/test/zbase32_stream_test.cpp b/test/zbase32_stream_test.cpp index 9e52b06..bcb5829 100644 --- a/test/zbase32_stream_test.cpp +++ b/test/zbase32_stream_test.cpp @@ -125,9 +125,11 @@ void every_chunking_equals_the_one_shot_form() { for (std::size_t const size : std::array{31, 32, 33, 200}) { expect_every_chunking_of(test::random_bytes(size)); } - for (std::string_view const text : - {test::pkarr_key.text, test::zbase32_document_vectors[0].text, - test::zbase32_document_vectors[1].text}) { + for (std::string_view const text : { + test::pkarr_key.text, + test::zbase32_document_vectors[0].text, + test::zbase32_document_vectors[1].text, + }) { auto const bytes = codecs::decode(formats::zbase32, text); BOOST_TEST(bytes.has_value()); if (bytes) { diff --git a/test/zbase32_test.cpp b/test/zbase32_test.cpp index 4156e2e..646c902 100644 --- a/test/zbase32_test.cpp +++ b/test/zbase32_test.cpp @@ -155,11 +155,10 @@ std::vector bytes_of_hex(std::string_view hex_digits) { } /** - One vector through every form: the default form, the buffer form (the characters past the text - unchanged, a short buffer refused), the tokens and the size; then its decode through the default, - typed, token and buffer forms and the codec's own. + One vector's encode through every form: the default form, the buffer form (the characters past the + text unchanged, a short buffer refused), the tokens and the size. */ -void expect_vector(std::vector const& bytes, std::string_view text) { +void expect_encodes(std::vector const& bytes, std::string_view text) { // The reference agrees with the source. BOOST_TEST(test::reference_zbase32_encode(bytes) == text); auto const defaulted = codecs::encode(formats::zbase32, bytes); @@ -185,7 +184,10 @@ void expect_vector(std::vector const& bytes, std::string_view text BOOST_TEST(appended == "<" + std::string{text}); auto const fixed = codecs::encode(formats::zbase32, bytes, tokens::fixed<64>{}); BOOST_TEST(fixed.has_value() && fixed.value().view() == text); +} +/** One vector's decode through the default, typed, token and buffer forms and the codec's own. */ +void expect_decodes(std::vector const& bytes, std::string_view text) { auto const decoded = codecs::decode(formats::zbase32, text); BOOST_TEST(decoded.has_value() && decoded.value() == bytes); auto const typed = codecs::decode>(formats::zbase32, text); @@ -210,6 +212,12 @@ void expect_vector(std::vector const& bytes, std::string_view text bytes); } +/** One vector through every form, both directions. */ +void expect_vector(std::vector const& bytes, std::string_view text) { + expect_encodes(bytes, text); + expect_decodes(bytes, text); +} + /** The spec's "pkarr's key": its 32 bytes encode into its text, of type text<52>, and the text decodes back, into bytes<32>, an array of 32 bytes and a secret; pkarr's other keys decode to 32 @@ -335,8 +343,18 @@ void every_error() { expect_refusal("ybY", character); expect_refusal("ybb", length); // The valid texts of the same shapes. - for (std::string_view const valid : {"yy", "yyyy", "yyyyy", "yyyyyyy", "yyyyyyyy", "ya", "yyyo", - "yyyyo", "yyyyyye", "yyyyyyyyya"}) { + for (std::string_view const valid : { + "yy", + "yyyy", + "yyyyy", + "yyyyyyy", + "yyyyyyyy", + "ya", + "yyyo", + "yyyyo", + "yyyyyye", + "yyyyyyyyya", + }) { BOOST_TEST(codecs::decode(formats::zbase32, valid).has_value()); } } diff --git a/test/zbase32_vectors.hpp b/test/zbase32_vectors.hpp index b335cc3..bd91735 100644 --- a/test/zbase32_vectors.hpp +++ b/test/zbase32_vectors.hpp @@ -84,28 +84,45 @@ struct pkarr_refused_key { `"a".repeat(53)` written out. */ inline constexpr std::array pkarr_refused_keys{ - pkarr_refused_key{.text = "c1bkg8tfsyy8wcedtmw4fwhdmm7bbzhgg3z58tf43m5ow8w9mbus", - .error = codecs::error::invalid_padding, - .byte_count = 0}, - pkarr_refused_key{.text = "", .error = std::nullopt, .byte_count = 0}, + pkarr_refused_key{ + .text = "c1bkg8tfsyy8wcedtmw4fwhdmm7bbzhgg3z58tf43m5ow8w9mbus", + .error = codecs::error::invalid_padding, + .byte_count = 0, + }, + pkarr_refused_key{ + .text = "", + .error = std::nullopt, + .byte_count = 0, + }, // `v` and `l` are no symbols of z-base-32. pkarr_refused_key{ - .text = "invalid", .error = codecs::error::invalid_character, .byte_count = 0}, + .text = "invalid", + .error = codecs::error::invalid_character, + .byte_count = 0, + }, // 51 characters: a remainder of 3, which no byte count has. - pkarr_refused_key{.text = "111111111111111111111111111111111111111111111111111", - .error = codecs::error::invalid_length, - .byte_count = 0}, + pkarr_refused_key{ + .text = "111111111111111111111111111111111111111111111111111", + .error = codecs::error::invalid_length, + .byte_count = 0, + }, // 53 characters, 33 bytes, its one bit past the last byte zero (`a` is 24, 11000). - pkarr_refused_key{.text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - .error = std::nullopt, - .byte_count = 33}, + pkarr_refused_key{ + .text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + .error = std::nullopt, + .byte_count = 33, + }, // Upper case: z-base-32 is lower case alone (design R2). - pkarr_refused_key{.text = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", - .error = codecs::error::invalid_character, - .byte_count = 0}, - pkarr_refused_key{.text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!", - .error = codecs::error::invalid_character, - .byte_count = 0}, + pkarr_refused_key{ + .text = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + .error = codecs::error::invalid_character, + .byte_count = 0, + }, + pkarr_refused_key{ + .text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!", + .error = codecs::error::invalid_character, + .byte_count = 0, + }, }; } // namespace webcpp::codecs::test