Skip to content
Open
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
21 changes: 21 additions & 0 deletions reference/python-codex32/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Ben Westgate

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
28 changes: 28 additions & 0 deletions reference/python-codex32/LICENSES/BSD-3-Clause-Curr-Sneed.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
BSD 3-Clause License

Copyright 2023 Leon Olsson Curr and Pearlwort Sneed <pearlwort@wpsoftware.net>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
95 changes: 95 additions & 0 deletions reference/python-codex32/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# python-codex32

Reference implementation of BIP-0093 (codex32): checksummed, SSSS-aware BIP32 seed strings.

This repository implements the codex32 string format described by BIP-0093.
It provides encoding/decoding, regular/long codex32 checksums, CRC padding for base conversions,
Shamir secret sharing scheme (SSSS) interpolation helpers and helpers to build codex32 strings from seed bytes.

## Features
- Encode/decode codex32 data via `from_string` and `from_unchecksummed_string`.
- Regular and long codex32 checksum support.
- Construct codex32 strings from raw seed bytes via `from_seed`.
- `from_seed` uses default bech32-encoded BIP32 fingerprint identifier and CRC padding.
- Interpolate shares recover secrets via `interpolate_at`.
- Parse codex32 strings and access parts via properties.
- Mutate codex32 strings by reassigning `is_upper`, `hrp`, `k`, `ident`, `share_idx`, `data`, and `pad_val`.
- Supports Bech32/Bech32m and segwit address format aswell.

## Security
Caution: This is reference code. Verify carefully before using with real funds.

## Installation
**Compatibility:** Python 3.10–3.14

**Recommended:** use a virtual environment
### Linux / macOS
```bash
python -m venv .venv
source .venv/bin/activate
pip install codex32
```
### Windows
```powershell
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install codex32
```


## Quick usage
```python
from codex32 import Codex32String

# Create from seed bytes
s = Codex32String.from_seed(
bytes.fromhex('ffeeddccbbaa99887766554433221100'),
"ms13cashs", # prefix string, (HRP + '1' + header)
0 # padding value (default "CRC", otherwise integer)
)
print(s.s) # codex32 string

# Parse an existing codex32 string and inspect parts
a = Codex32String("ms13casha320zyxwvutsrqpnmlkjhgfedca2a8d0zehn8a0t")
print(a.hrp) # human-readable part
print(a.k) # threshold parameter
print(a.ident) # 4 character identifier
print(a.share_idx) # share index character
print(a.payload) # payload part
print(a.checksum) # checksum part
print(len(a)) # length of the codex32 string
print(a.is_upper) # case is upper True/False
print(s.data.hex()) # raw seed bytes as hex
print(a.pad_val) # padding value integer, (MSB first)



# Create from unchecksummed string (will append checksum)
c = Codex32String.from_unchecksummed_string("ms13cashcacdefghjklmnpqrstuvwxyz023")
print(str(c)) # equivalent to print(c.s)

# Interpolate shares to recover or derive target share index
shares = [s, a, c]
derived_share_d = Codex32String.interpolate_at(shares, target='d')
print(derived_share_d.s)

# Create Codex32String object from existing codex32 string and validate any HRP
e = Codex32String.from_string("cl", "cl10lueasd35kw6r5de5kueedxyesqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqanvrktzhlhusz")
print(e.ident)
print(e.s)

# Relabel a Codex32String object
e.ident = "cln2"
print(e.ident)
print(e.s)

# Uppercase a Codex32String object (for encoding in QR codes or handwriting)
e.is_upper = True
print(e.s)
```

## Tests
``` bash
pip install -e .[dev]
pytest
```
49 changes: 49 additions & 0 deletions reference/python-codex32/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
[build-system]
requires = ["setuptools>=80", "setuptools-scm>=8"]
build-backend = "setuptools.build_meta"

[project]
name = "codex32"
version = "0.6.0"
authors = [
{ name = "Ben Westgate", email = "benwestgate@protonmail.com" },
]
description = "Python reference implementation for codex32 (BIP93) and codex32-encoded master seeds."
readme = "README.md"
requires-python = ">=3.10"
license = "MIT"
license-files = ["LICENSE*"]
maintainers = [
{ name = "Ben Westgate", email = "benwestgate@protonmail.com" },
]
keywords = ["bitcoin", "HD wallet", "BIP32", "BIP93", "BIP173", "BIP350", "codex32", "cryptography", "secret sharing", "secrets", "entropy", "bech32"]
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Operating System :: OS Independent",
"Topic :: Security :: Cryptography",
"Topic :: Software Development :: Libraries",
]
dependencies = ["bip32>=5.0.0"]

[project.optional-dependencies]
dev = ["pytest"]

[tool.setuptools.packages.find]
where = ["src"]

[tool.pytest.ini_options]
testpaths = ["tests"]

[project.urls]
Homepage = "https://github.com/benwestgate/python-codex32"
Repository = "https://github.com/benwestgate/python-codex32"
Issues = "https://github.com/benwestgate/python-codex32/issues"
Changelog = "https://github.com/benwestgate/python-codex32/tree/master/CHANGELOG.md"
27 changes: 27 additions & 0 deletions reference/python-codex32/src/codex32/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Copyright (c) 2026 Ben Westgate <benwestgate@protonmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

"""codex32 package: bech32/codex32 helpers and encoders/decoders."""

from .bip93 import Codex32String, encode, decode
from .errors import CodexError


__all__ = ["CodexError", "Codex32String", "encode", "decode"]
159 changes: 159 additions & 0 deletions reference/python-codex32/src/codex32/bech32.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
# Portions of this file are derived from work by:
# Copyright (c) 2017, 2020 Pieter Wuille
#
# Additional code and modifications:
# Copyright (c) 2026 Ben Westgate <benwestgate@protonmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

"""Internal bech32 and u5 helpers for Bech32/codex32 encoding and decoding."""

from codex32.errors import CodexError
from codex32.checksums import Checksum, crc_pad


# pylint: disable=missing-class-docstring
class InvalidDataValue(CodexError): ...


class IncompleteGroup(CodexError): ...


class InvalidLength(CodexError): ...


class InvalidChar(CodexError): ...


class InvalidCase(CodexError): ...


class InvalidChecksum(CodexError): ...


class InvalidPadding(CodexError): ...


class MissingHrp(CodexError): ...


class SeparatorNotFound(CodexError): ...


class MissingChecksum(CodexError): ...


class MissingEncoding(CodexError): ...


CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"


def bech32_hrp_expand(hrp: str) -> list[int]:
"""Expand the HRP into values for checksum computation."""
return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]


def u5_to_chars(data: list[int]) -> str:
"""Map list of 5-bit integers (0-31) -> Bech32 data-part string."""
for i, x in enumerate(data):
if not 0 <= x < 32:
raise InvalidDataValue(f"from 0 to 31 index={i} value={x}")
return "".join(CHARSET[d] for d in data)


def u5_encode(hrp: str, data: list[int], spec: Checksum) -> str:
"""Compute a Bech32 string given HRP and data values."""
combined = data + spec.create(bech32_hrp_expand(hrp) + data)
return hrp + "1" + u5_to_chars(combined)


def chars_to_u5(bech: str) -> list[int]:
"""Map Bech32 data-part string -> list of 5-bit integers (0-31)."""
for i, ch in enumerate(bech):
if ch not in CHARSET:
raise InvalidChar(f"'{ch!r}' at pos={i} in data part")
return [CHARSET.find(x) for x in bech]


def u5_parse(bech: str) -> tuple[str, list[int]]:
"""Parse a Bech32/Codex32 string, and return HRP and 5-bit data."""
for i, ch in enumerate(bech):
if ord(ch) < 33 or ord(ch) > 126:
raise InvalidChar(f"non-printable U+{ord(ch):04X} at pos={i}")
if bech.upper() != bech and bech.lower() != bech:
raise InvalidCase("mixed upper/lower case bech32 string")
if (pos := (bech := bech.lower()).rfind("1")) < 1:
raise MissingHrp("empty HRP") if not pos else SeparatorNotFound("'1' not found")
hrp = bech[:pos]
data = chars_to_u5(bech[pos + 1 :])
return hrp, data


def u5_decode(bech: str, encodings: list[Checksum]) -> tuple[str, list[int], Checksum]:
"""Validate a Bech32/Codex32 string, and determine HRP and data."""
hrp, data = u5_parse(bech)
e = MissingEncoding("no encoding or encodings were passed")
for spec in encodings:
if len(hrp) <= (datlen := len(bech) - 1 - spec.cs_len):
if datlen in (c := spec.coverage):
if spec.verify(bech32_hrp_expand(hrp) + data):
return hrp, data[: -spec.cs_len], spec
e = InvalidChecksum(f"{spec.kind} checksum invalid for hrp and data")
if not isinstance(e, InvalidChecksum):
e = InvalidLength(f"{datlen} chars {spec.kind} reqs {min(c)}..{max(c)}")
if not isinstance(e, (InvalidLength, InvalidChecksum)):
e = MissingChecksum(f"{spec.kind}: {len(data)} data chars < {spec.cs_len}")
raise e


def convertbits(
data: list[int] | bytes,
frombits: int,
tobits: int,
pad: bool = True,
pad_val: int | str = 0,
) -> list[int]:
"""General power-of-2 base conversion."""
acc = 0
bits = 0
ret = []
maxv = (1 << tobits) - 1
max_acc = (1 << (frombits + tobits - 1)) - 1
for value in data:
if value < 0 or (value >> frombits):
raise InvalidDataValue(f"{value} is not in 0 to {(1 << frombits) - 1}")
acc = ((acc << frombits) | value) & max_acc
bits += frombits
while bits >= tobits:
bits -= tobits
ret.append((acc >> bits) & maxv)
if not pad and bits >= frombits:
raise IncompleteGroup(f" {bits} bits remaining, must be {frombits - 1} or less")
pad_len = (tobits - bits) if pad and bits else bits
pv = crc_pad(convertbits(data, frombits, 1)) if pad_val == "CRC" else pad_val
if isinstance(pad_val, int) and not 0 <= pad_val < (1 << pad_len):
raise InvalidDataValue(f"padding int {pad_val} must be 0 to {(1<<pad_len) - 1}")
if pad and bits:
if not isinstance(pv, int):
raise InvalidPadding(f"pad_val must be int or 'CRC' if pad=True, got {pv}")
ret.append((acc << (tobits - bits) | pv) & maxv)
elif pv not in ("any", acc % (1 << bits)):
raise InvalidPadding(f"padding has to be {pad_val}")
return ret
Loading