Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/developer/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ Reference-vector authors may use the following module-level interfaces without
depending on implementation-private names:

- `codex32.bech32`: `CHARSET`, `bech32_decode`, `bech32_encode`,
`bech32_hrp_expand`, `chars_to_u5`, and `u5_to_chars`;
`bech32_hrp_expand`, `chars_to_u5` (lowercases ASCII only), and `u5_to_chars`;
- `codex32.checksums`: `Checksum`, `CODEX32`, and `CODEX32_LONG`;
- `codex32.bip93`: `checksum_for_body_length` and
`checksum_for_encoded_length`.
Expand Down
6 changes: 3 additions & 3 deletions src/codex32/_cli_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from time import monotonic
from typing import Any, Literal, cast

from codex32.bech32 import _ascii_lower, interpret_mixed_case
from codex32.bech32 import interpret_mixed_case
from codex32.bip93 import (
Secret,
Share,
Expand All @@ -30,9 +30,9 @@
InvalidChecksum,
InvalidLength,
InvalidThreshold,
MismatchedHrp,
MismatchedIdentifier,
MismatchedPayloadLength,
MismatchedProfile,
MismatchedThreshold,
SecretInRecoverySet,
)
Expand Down Expand Up @@ -682,7 +682,7 @@ def allowed(candidate: CorrectionCandidate) -> bool:

_FRIENDLY_SET_ERRORS: dict[type[Exception], str] = {
InvalidChecksum: "The checksum does not match.",
MismatchedProfile: "These strings are for different applications.",
MismatchedHrp: "These strings are for different applications.",
MismatchedThreshold: "These strings require different numbers of shares.",
MismatchedIdentifier: "These strings have different identifiers.",
MismatchedPayloadLength: "These strings have different lengths.",
Expand Down
10 changes: 1 addition & 9 deletions src/codex32/bech32.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,16 @@ def bech32_hrp_expand(hrp: str) -> list[int]:
return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]


def _ascii_lower(value: str) -> str:
return "".join(character.lower() if character.isascii() else character for character in value)


def u5_to_chars(values: list[int] | tuple[int, ...]) -> str:
"""Convert 5-bit values to Bech32 characters."""

for index, value in enumerate(values):
if not 0 <= value < 32:
raise InvalidCharacter(f"u5 value {value} at index {index} is outside 0..31")
return "".join(CHARSET[value] for value in values)


def chars_to_u5(value: str, first_position: int = 1) -> list[int]:
"""Convert Bech32 characters to 5-bit values."""

result: list[int] = []
for index, character in enumerate(_ascii_lower(value)):
for index, character in enumerate(c.lower() if c.isascii() else c for c in value):
position = CHARSET.find(character)
if position < 0:
label = "Apostrophe (')" if character == "'" else f"The character {character!r}"
Expand Down
7 changes: 2 additions & 5 deletions src/codex32/bip93.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@ def _symbols(self) -> tuple[int, ...]:

def checksum_for_encoded_length(hrp: str, encoded_length: int) -> Checksum:
"""Return the codex32 checksum required by an encoded HRP/data length."""

expanded_length = 2 * len(hrp) + 1 + encoded_length
if 94 <= expanded_length <= 95:
raise InvalidLength("expanded codex32 lengths 94 and 95 are invalid")
Expand All @@ -101,10 +100,8 @@ def checksum_for_encoded_length(hrp: str, encoded_length: int) -> Checksum:

def checksum_for_body_length(hrp: str, body_length: int) -> Checksum:
"""Return the checksum required when constructing a codex32 body."""

checksum = CODEX32 if 2 * len(hrp) + 1 + body_length <= 80 else CODEX32_LONG
checksum_for_encoded_length(hrp, body_length + checksum.length)
return checksum
short = 2 * len(hrp) + 1 + body_length <= 80
return checksum_for_encoded_length(hrp, body_length + (CODEX32 if short else CODEX32_LONG).length)


def _decode_codex32(text: str) -> tuple[str, _ProfileRules | None, tuple[int, ...], Checksum]:
Expand Down
2 changes: 0 additions & 2 deletions src/codex32/checksums.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@

@dataclass(frozen=True, slots=True)
class Checksum:
"""Immutable checksum specification for reference-vector construction."""

kind: str
generators: tuple[int, ...]
length: int
Expand Down
1 change: 0 additions & 1 deletion src/codex32/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
from codex32._cli_input import read_artifacts as _artifacts
from codex32._cli_input import read_text as _text
from codex32._cli_parser import parser as _parser
from codex32.bech32 import _ascii_lower
from codex32.bip93 import (
IDX_SORT,
Header,
Expand Down
2 changes: 0 additions & 2 deletions src/codex32/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ def _error(name: str, base: type[CodexError], doc: str) -> type[CodexError]:
InvalidShareSet = _error("InvalidShareSet", CodexError, "Artifacts cannot form an interpolation set.")
WrongShareCount = _error("WrongShareCount", InvalidShareSet, "The share count differs from its threshold.")
MismatchedHrp = _error("MismatchedHrp", InvalidShareSet, "Application prefixes differ.")
# Compatibility name retained across the 1.0 boundary.
MismatchedProfile = MismatchedHrp
MismatchedThreshold = _error("MismatchedThreshold", InvalidShareSet, "Thresholds differ.")
MismatchedIdentifier = _error("MismatchedIdentifier", InvalidShareSet, "Identifiers differ.")
MismatchedPayloadLength = _error("MismatchedPayloadLength", InvalidShareSet, "Payload lengths differ.")
Expand Down
5 changes: 2 additions & 3 deletions tests/test_generic_hrp.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
recover_secret,
)
from codex32.cli import main, ms_main
from codex32.errors import InvalidChecksum, InvalidLength, MismatchedHrp, MismatchedProfile
from codex32.errors import InvalidChecksum, InvalidLength, MismatchedHrp
from tools._wallet_test_vectors import STUB_FINGERPRINT

UNKNOWN = {
Expand Down Expand Up @@ -52,8 +52,7 @@ def test_opaque_hrp_parse_complete_recover_and_derive(vector: dict[str, str]) ->
assert derive_share([secret, a], "d").text == vector["D"].upper()


def test_sharing_compares_normalized_hrp_and_keeps_compatibility_error_name() -> None:
assert MismatchedProfile is MismatchedHrp
def test_sharing_compares_normalized_hrp() -> None:
zz = parse_codex32(UNKNOWN["short"]["S"])
yy = parse_codex32(oracle_encode("yy", "2testa" + "p" * 26))
with pytest.raises(MismatchedHrp):
Expand Down
4 changes: 2 additions & 2 deletions tests/test_sharing.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@
InvalidBip39Checksum,
InvalidPadding,
InvalidTargetIndex,
MismatchedHrp,
MismatchedIdentifier,
MismatchedPayloadLength,
MismatchedProfile,
MismatchedThreshold,
SecretInRecoverySet,
WrongShareCount,
Expand Down Expand Up @@ -113,7 +113,7 @@ def test_every_threshold_recovers_exactly_k_shares(threshold: int) -> None:
def test_share_set_mismatches_have_distinct_errors() -> None:
ms_secret, ms_masks = _ms_basis()
cl = parse_codex32(oracle_encode("cl", "2testa" + "q" * 52))
with pytest.raises(MismatchedProfile):
with pytest.raises(MismatchedHrp):
derive_share([ms_secret, cl], "c") # type: ignore[list-item]

threshold_three = parse_codex32(oracle_encode("ms", "3testc" + "q" * len(ms_secret.payload_symbols)))
Expand Down
Loading