Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
61df838
secp256k1: implement ec_pubkey_tweak_mul and ec_pubkey_combine python…
kdmukai May 13, 2026
14cc323
secp256k1: fix mutable key in tweak functions and add ec_privkey_twea…
miketlk May 15, 2026
bf6472b
ref: make bech32 more flexible for larger payloads(sp)
notTanveer Jul 6, 2026
f56f44f
feat(BIP-352): silent payments
notTanveer Jul 6, 2026
63dde62
feat(BIP-370): PSBTv2 support
notTanveer Jul 6, 2026
a732d6a
feat(BIP-374): DLEQ proofs
notTanveer Jul 6, 2026
9f70fd0
feat(BIP-375 & BIP-376): SP PSBT support
notTanveer Jul 9, 2026
acf2665
feat(BIP-392): SP descriptor
notTanveer Jul 9, 2026
556c4ed
fix(sp): skip keys that cannot sign, dedupe TX_MODIFIABLE update
notTanveer Aug 19, 2026
64f27f4
fix(psbt): close PSBTv2 global-field validation gaps left by upstream…
notTanveer Aug 19, 2026
bf297b7
fix(sp): bind the NUMS eligibility claim to the scriptPubKey
notTanveer Aug 21, 2026
f4f682d
fix(psbt): correctness, RAM fixes in PSBTv2 parsing paths and revert …
notTanveer Aug 22, 2026
a1ffd5c
fix(sp): derive the SP send once per root, not once per descriptor key
notTanveer Aug 27, 2026
20fa1ee
perf(sp): cut redundant secp256k1 and allocation work
notTanveer Sep 2, 2026
5b4437e
update bip-375 test vectors
notTanveer Sep 3, 2026
2844fc2
fix(liquid): honour v2 locktime and sequence 0 in the pset tx
notTanveer Sep 26, 2026
fbbab0a
fix(psbt): make the v2 prescan work on micropython, cut parse RAM
notTanveer Sep 26, 2026
ac2ff13
fix(sp): make sp() descriptors serialize, share one bech32m codec
notTanveer Sep 26, 2026
3fb1227
refactor(sp): resolve the signing root once in sign_with
notTanveer Sep 26, 2026
b548695
fix: reject unknown sp networks and map hrps per network
notTanveer Sep 28, 2026
ca116db
fix: treat the bip-374 dleq challenge as a scalar
notTanveer Sep 28, 2026
371b9f2
test: sync bip-352 and bip-375 test vectors with upstream
notTanveer Sep 28, 2026
95ae446
feat: add sp_output_scripts to preview silent payment outputs
notTanveer Oct 3, 2026
e89d799
fix: don't use super() inside classmethod, breaks micropython
notTanveer Oct 28, 2026
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
6 changes: 4 additions & 2 deletions docs/api/bech32.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ Encodes a segwit address

bech32(m) encoded string. For `ver=0` uses `bech32` encoding, for larger versions uses `bech32m`.

Raises `bech32.Bech32DecodeError` (a subclass of `EmbitError`) if `ver` is not in `0..16` or the length of `witprog` is not valid for it.

**Example**

```python
Expand Down Expand Up @@ -48,7 +50,7 @@ Decodes segwit address from bech32(m) encoding

a tuple `(ver, witprog)` where `ver` is segwit version (0-16) and `witprog` is a witness program (list of ints).

If decoding fails returns `(None, None)`.
If decoding fails raises `bech32.Bech32DecodeError` (a subclass of `EmbitError`).

**Example**

Expand All @@ -64,5 +66,5 @@ ver, prog = bech32.decode(hrp, addr)
# >>> (1, [123, 150, 219, 206, 65, 72, 102, 220, 67, 68, 173, 10, 176, 38, 17, 28, 45, 2, 96, 208, 164, 112, 195, 238, 29, 84, 72, 65, 210, 159, 233, 20])

ver, prog = bech32.decode("bc", "bc1qsvsxz8lsxg3rc86t")
# >>> (None, None)
# >>> raises Bech32DecodeError: Checksum verification failed
```
106 changes: 85 additions & 21 deletions src/embit/bech32.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
# THE SOFTWARE.

"""Reference implementation for Bech32 and segwit addresses."""

from .misc import const
from .base import EmbitError

CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
BECH32_CONST = const(1)
Expand All @@ -33,6 +35,10 @@ class Encoding:
BECH32M = 2


class Bech32DecodeError(EmbitError):
pass


def bech32_polymod(values):
"""Internal function that computes the Bech32 checksum."""
generator = [0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3]
Expand Down Expand Up @@ -77,21 +83,32 @@ def bech32_encode(encoding, hrp, data):

def bech32_decode(bech):
"""Validate a Bech32/Bech32m string, and determine HRP and data."""
if (any(ord(x) < 33 or ord(x) > 126 for x in bech)) or (
bech.lower() != bech and bech.upper() != bech
):
return (None, None, None)
if any(ord(x) < 33 or ord(x) > 126 for x in bech):
raise Bech32DecodeError("Invalid character in input")
if bech.lower() != bech and bech.upper() != bech:
raise Bech32DecodeError("Mixed case strings not allowed")
bech = bech.lower()
pos = bech.rfind("1")
if pos < 1 or pos + 7 > len(bech) or len(bech) > 90:
return (None, None, None)
if not all(x in CHARSET for x in bech[pos + 1 :]):
return (None, None, None)
if pos < 1:
raise Bech32DecodeError("Separator '1' not found or misplaced")
# BIP-173: the HRP must contain 1 to 83 characters.
if pos > 83:
raise Bech32DecodeError("HRP too long (max 83 characters)")
if pos + 7 > len(bech):
raise Bech32DecodeError("Data part too short")
# BIP-173 caps Bech32 strings at 90 chars, but BIP-352 silent payment
# addresses are longer (>=117) and recommend a 1023-char limit to leave
# room for future versions.
if len(bech) > 1023:
raise Bech32DecodeError("String too long (max 1023 characters)")
hrp = bech[:pos]
data = [CHARSET.find(x) for x in bech[pos + 1 :]]
data_part = bech[pos + 1 :]
if not all(x in CHARSET for x in data_part):
raise Bech32DecodeError("Data part contains invalid characters")
data = [CHARSET.find(x) for x in data_part]
encoding = bech32_verify_checksum(hrp, data)
if encoding is None:
return (None, None, None)
raise Bech32DecodeError("Checksum verification failed")
return (encoding, hrp, data[:-6])


Expand All @@ -104,7 +121,7 @@ def convertbits(data, frombits, tobits, pad=True):
max_acc = (1 << (frombits + tobits - 1)) - 1
for value in data:
if value < 0 or (value >> frombits):
return None
raise Bech32DecodeError("Invalid input value for bit conversion")
acc = ((acc << frombits) | value) & max_acc
bits += frombits
while bits >= tobits:
Expand All @@ -114,33 +131,80 @@ def convertbits(data, frombits, tobits, pad=True):
if bits:
ret.append((acc << (tobits - bits)) & maxv)
elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
return None
raise Bech32DecodeError("Invalid padding in bit conversion")
return ret


def decode(hrp, addr):
"""Decode a segwit address."""
"""Decode a segwit address.

Silent payment (sp/tsp) addresses are not witness programs and must not be
decoded here; use bech32_decode + convertbits for those.
"""
# BIP-173/BIP-350: segwit addresses are capped at 90 characters.
if len(addr) > 90:
raise Bech32DecodeError("Segwit address too long (max 90 characters)")
encoding, hrpgot, data = bech32_decode(addr)
if hrpgot != hrp:
return (None, None)
raise Bech32DecodeError("HRP mismatch: expected {}, got {}".format(hrp, hrpgot))
decoded = convertbits(data[1:], 5, 8, False)
if decoded is None or len(decoded) < 2 or len(decoded) > 40:
return (None, None)
# BIP-141: a witness program is 2 to 40 bytes.
if len(decoded) < 2 or len(decoded) > 40:
raise Bech32DecodeError("Invalid witness program length")
if data[0] > 16:
return (None, None)
raise Bech32DecodeError("Invalid witness version")
if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:
return (None, None)
raise Bech32DecodeError("Invalid witness program length for version 0")
if (data[0] == 0 and encoding != Encoding.BECH32) or (
data[0] != 0 and encoding != Encoding.BECH32M
):
return (None, None)
raise Bech32DecodeError("Invalid encoding for witness version")
return (data[0], decoded)


def encode(hrp, witver, witprog):
"""Encode a segwit address."""
if witver < 0 or witver > 16:
raise Bech32DecodeError("Invalid witness version")
if len(witprog) < 2 or len(witprog) > 40:
raise Bech32DecodeError("Invalid witness program length")
if witver == 0 and len(witprog) != 20 and len(witprog) != 32:
raise Bech32DecodeError("Invalid witness program length for version 0")

encoding = Encoding.BECH32 if witver == 0 else Encoding.BECH32M
ret = bech32_encode(encoding, hrp, [witver] + convertbits(witprog, 8, 5))
if decode(hrp, ret) == (None, None):
return None

# Sanity check: the result must round-trip. Any failure propagates with its
# original, descriptive Bech32DecodeError.
decode(hrp, ret)

return ret


def bech32m_encode_versioned(hrp, version, payload):
"""Bech32m-encode ``payload`` bytes behind a leading version value.

Shared framing of BIP-352 silent payment addresses and BIP-392 spscan
keys. Only the range of ``version`` is checked here; the caller applies
its own version and length policy.
"""
# bech32_encode indexes CHARSET with the version, so an out-of-range one
# would raise IndexError (32) or wrap to the wrong character (-1).
if not 0 <= version <= 31:
raise Bech32DecodeError("Version must be in [0, 31], got %d" % version)
return bech32_encode(Encoding.BECH32M, hrp, [version] + convertbits(payload, 8, 5))


def bech32m_decode_versioned(bech):
"""Inverse of bech32m_encode_versioned: return (hrp, version, payload bytes).

Checks the Bech32m checksum and encoding, that a version value is present
and that the payload converts to whole bytes with zero padding. The
caller checks the HRP, the version and the payload length.
"""
encoding, hrp, data = bech32_decode(bech)
if encoding != Encoding.BECH32M:
raise Bech32DecodeError("Must use bech32m encoding")
if not data:
raise Bech32DecodeError("Missing version")
return hrp, data[0], bytes(convertbits(data[1:], 5, 8, False))
1 change: 1 addition & 0 deletions src/embit/descriptor/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from . import miniscript
from .descriptor import Descriptor
from .arguments import Key
from .sp import SilentPaymentDescriptor
5 changes: 5 additions & 0 deletions src/embit/descriptor/descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from .miniscript import Miniscript, Multi, Sortedmulti
from .arguments import Key
from .taptree import TapTree
from .sp import SilentPaymentDescriptor


class Descriptor(DescriptorBase):
Expand Down Expand Up @@ -302,6 +303,10 @@ def read_from(cls, s):
is_miniscript = True
taproot = False
taptree = TapTree()
if start.startswith(b"sp("):
# rewind with a relative seek, MicroPython's BytesIO has no tell()
s.seek(-len(start), 1)
return SilentPaymentDescriptor.read_from(s)
if start.startswith(b"tr("):
taproot = True
s.seek(-5, 1)
Expand Down
Loading
Loading