"""Bech32 for NIP-19 identifiers (npub), and nothing else.
A leaf module: it imports nothing from node/, so the transport layer and the
CLI can both reach it without one depending on the other. It used to live in
node/commands/base.py, where node/fips_transport.py fetched it lazily from the
CLI package, which made a transport
module depend on the command line that drives it (a 17-module import cycle,
lazy only by luck of where the imports sat).
"""
from __future__ import annotations
from typing import Sequence
_BECH32_CHARSET: str = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'
_BECH32_GEN: tuple[int, ...] = (0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3)
[docs]def bech32_polymod(values: Sequence[int]) -> int:
chk = 1
for v in values:
top = chk >> 25
chk = ((chk & 0x1ffffff) << 5) ^ v
for i in range(5):
chk ^= _BECH32_GEN[i] if (top >> i) & 1 else 0
return chk
[docs]def bech32_encode(hrp: str, data: Sequence[int] | bytes) -> str:
"""npub encoding, NIP-19: bech32 over the 32 key bytes."""
bits, acc, out = 0, 0, []
for b in data:
acc = (acc << 8) | b
bits += 8
while bits >= 5:
bits -= 5
out.append((acc >> bits) & 31)
if bits:
out.append((acc << (5 - bits)) & 31)
exp = [ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp]
pm = bech32_polymod(exp + out + [0] * 6) ^ 1
chk = [(pm >> 5 * (5 - i)) & 31 for i in range(6)]
return hrp + '1' + ''.join(_BECH32_CHARSET[d] for d in out + chk)
[docs]def bech32_decode(hrp: str, s: str) -> bytes | None:
"""Bech32 decoding for NIP-19 identifiers (npub). Returns 32 key bytes or None."""
s = s.lower()
if not s.startswith(hrp + '1'):
return None
data = s[len(hrp) + 1:]
if len(data) < 6:
return None
vals = []
for c in data:
idx = _BECH32_CHARSET.find(c)
if idx == -1:
return None
vals.append(idx)
exp = [ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp]
if bech32_polymod(exp + vals) != 1:
return None
data_vals = vals[:-6]
acc, bits, out = 0, 0, []
for v in data_vals:
acc = (acc << 5) | v
bits += 5
while bits >= 8:
bits -= 8
out.append((acc >> bits) & 0xff)
if bits >= 5 or ((acc << (8 - bits)) & 0xff) != 0:
return None
return bytes(out)