#!/usr/bin/env python3 """The canary address, second implementation: Python standard library only, written from the RFC 9380 text. It shares no code with shared/canary.mjs (which uses @noble/curves) and must give the same address byte for byte. python3 canary/py/canary.py canary/seeds/devnet.txt → the address python3 canary/py/canary.py --json canary/seeds/*.txt python3 canary/py/canary.py --selftest → the RFC 9380 J.5.1 vector (msg "") Suite edwards25519_XMD:SHA-512_ELL2_RO_ (RFC 9380 §8.5), DST "HASHVAULT-CANARY-V1", message = the seed file's exact bytes. Exit code 2 when the seed's anchor hash is still PENDING.""" import hashlib, json, re, sys P = 2 ** 255 - 19 L = 2 ** 252 + 27742317777372353535851937790883648493 D = (-121665 * pow(121666, P - 2, P)) % P J = 486662 SQRT_M1 = pow(2, (P - 1) // 4, P) DST = b'HASHVAULT-CANARY-V1' def inv(x): return pow(x, P - 2, P) def sgn0(x): return x % 2 def is_square(x): return x % P == 0 or pow(x, (P - 1) // 2, P) == 1 def sqrt(a): a %= P c = pow(a, (P + 3) // 8, P) if c * c % P == a: return c c = c * SQRT_M1 % P if c * c % P == a: return c raise ValueError('not a square') def expand_message_xmd(msg, dst, n): b_len, r_len = 64, 128 ell = -(-n // b_len) assert ell <= 255 and len(dst) <= 255 dst_prime = dst + bytes([len(dst)]) msg_prime = bytes(r_len) + msg + n.to_bytes(2, 'big') + b'\x00' + dst_prime b0 = hashlib.sha512(msg_prime).digest() b = [hashlib.sha512(b0 + b'\x01' + dst_prime).digest()] for i in range(2, ell + 1): b.append(hashlib.sha512(bytes(x ^ y for x, y in zip(b0, b[-1])) + bytes([i]) + dst_prime).digest()) return b''.join(b)[:n] def hash_to_field(msg, dst, count=2, Lb=48): u = expand_message_xmd(msg, dst, count * Lb) return [int.from_bytes(u[i * Lb:(i + 1) * Lb], 'big') % P for i in range(count)] def elligator2(u): """RFC 9380 §6.7.1 onto curve25519 (K = 1, Z = 2): returns (s, t).""" Z = 2 tv = (1 + Z * u * u) % P x1 = (-J * (inv(tv) if tv else 0)) % P if x1 == 0: x1 = (-J) % P gx1 = (x1 ** 3 + J * x1 * x1 + x1) % P x2 = (-x1 - J) % P gx2 = (x2 ** 3 + J * x2 * x2 + x2) % P if is_square(gx1): x, y = x1, sqrt(gx1) if sgn0(y) != 1: y = (-y) % P else: x, y = x2, sqrt(gx2) if sgn0(y) != 0: y = (-y) % P return x, y C_MAP = sqrt(-486664 % P) if sgn0(C_MAP) != 0: C_MAP = (-C_MAP) % P def to_edwards(s, t): """RFC 7748 rational map curve25519 → edwards25519 (RFC 9380 §6.8.2): x = c·s/t, y = (s − 1)/(s + 1).""" if t == 0 or (s + 1) % P == 0: return (0, 1) return (C_MAP * s * inv(t) % P, (s - 1) * inv(s + 1) % P) def ed_add(p1, p2): (x1, y1), (x2, y2) = p1, p2 k = D * x1 * x2 * y1 * y2 % P return ((x1 * y2 + y1 * x2) * inv(1 + k) % P, (y1 * y2 + x1 * x2) * inv(1 - k) % P) def ed_mul(k, pt): r, q = (0, 1), pt while k: if k & 1: r = ed_add(r, q) q = ed_add(q, q); k >>= 1 return r def on_curve(pt): x, y = pt return (-x * x + y * y - 1 - D * x * x * y * y) % P == 0 def hash_to_curve(msg, dst): u0, u1 = hash_to_field(msg, dst) q0, q1 = to_edwards(*elligator2(u0)), to_edwards(*elligator2(u1)) pt = ed_mul(8, ed_add(q0, q1)) return pt, (u0, u1) B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def b58(b): n = int.from_bytes(b, 'big'); out = '' while n: n, r = divmod(n, 58); out = B58[r] + out return '1' * (len(b) - len(b.lstrip(b'\x00'))) + out def encode(pt): x, y = pt raw = bytearray(y.to_bytes(32, 'little')) raw[31] |= (x & 1) << 7 return bytes(raw) SEED_RE = re.compile(r'^Vault Canary v1\nnetwork: [a-z0-9-]+\nanchor: bitcoin block [0-9]{1,3}(?:,[0-9]{3})* hash ([0-9a-f]{64}|PENDING)\nstatement: \S(?:.*\S)?$') def derive(data): if any(not (0x20 <= c <= 0x7e or c == 0x0a) for c in data): raise ValueError('only printable ASCII and LF are allowed') text = data.decode('ascii') m = SEED_RE.match(text) if not m: raise ValueError('not a canary seed (4 lines, no trailing newline)') if m.group(1) == 'PENDING': raise LookupError('PENDING') pt, _ = hash_to_curve(data, DST) if pt == (0, 1): raise ValueError('identity') if ed_mul(8, pt) == (0, 1): raise ValueError('small order') if ed_mul(L, pt) != (0, 1): raise ValueError('not in the prime-order subgroup') assert on_curve(pt) raw = encode(pt) return {'address': b58(raw), 'bytesHex': raw.hex(), 'seedSha256': hashlib.sha256(data).hexdigest()} def selftest(): pt, _ = hash_to_curve(b'', b'QUUX-V01-CS02-with-edwards25519_XMD:SHA-512_ELL2_RO_') want = (0x3c3da6925a3c3c268448dcabb47ccde5439559d9599646a8260e47b1e4822fc6, 0x09a6c8561a0b22bef63124c588ce4c62ea83a3c899763af26d795302e115dc21) ok = pt == want print('RFC 9380 J.5.1 (msg ""):', 'ok' if ok else 'MISMATCH', hex(pt[0]), hex(pt[1])) return ok if __name__ == '__main__': args = sys.argv[1:] if args == ['--selftest']: sys.exit(0 if selftest() else 1) as_json = '--json' in args files = [a for a in args if a != '--json'] out, code = {}, 0 for f in files: try: out[f] = derive(open(f, 'rb').read()) except LookupError: out[f] = {'pending': True}; code = 2 except ValueError as e: out[f] = {'error': str(e)}; code = 1 if as_json: print(json.dumps(out, indent=1)) else: for f, r in out.items(): print(f, r.get('address') or ('PENDING' if r.get('pending') else 'ERROR ' + r.get('error', ''))) sys.exit(code)