#!/usr/bin/env python3 """offgrid-keys — air-gapped crypto key + address generator. Single file. Standard library only. No network. No third-party packages. Derives, from one secp256k1 secret key: * EVM address (Ethereum / BSC / Polygon / Arbitrum / ...) * Bitcoin bech32 (P2WPKH, BIP173) * TRON TRC-20 (USDT-TRC20 style address) Also implements BIP340 Schnorr (Nostr event signing) and verifies itself against the official published test vectors: python offgrid_keys.py --selftest Generate keys from OS entropy: python offgrid_keys.py --gen Generate keys from physical dice (recommended for cold storage): python offgrid_keys.py --dice Why this exists: most wallet generators pull a dependency tree you cannot audit in an afternoon. This is ~400 lines you can read end to end, run on a machine that has never touched a network, and check against vectors that are published in the BIPs themselves. """ from __future__ import annotations import hashlib import json import os import sys from datetime import datetime, timezone # ============================================================ keccak-256 _RC = [ 0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000, 0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, 0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A, 0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003, 0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A, 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008, ] _ROT = [ [0, 36, 3, 41, 18], [1, 44, 10, 45, 2], [62, 6, 43, 15, 61], [28, 55, 25, 21, 56], [27, 20, 39, 8, 14], ] _M64 = (1 << 64) - 1 def _rol(v: int, n: int) -> int: n %= 64 return ((v << n) | (v >> (64 - n))) & _M64 def _keccak_f(a): for rnd in range(24): c = [a[x][0] ^ a[x][1] ^ a[x][2] ^ a[x][3] ^ a[x][4] for x in range(5)] d = [c[(x - 1) % 5] ^ _rol(c[(x + 1) % 5], 1) for x in range(5)] for x in range(5): for y in range(5): a[x][y] ^= d[x] b = [[0] * 5 for _ in range(5)] for x in range(5): for y in range(5): b[y][(2 * x + 3 * y) % 5] = _rol(a[x][y], _ROT[x][y]) for x in range(5): for y in range(5): a[x][y] = b[x][y] ^ ((~b[(x + 1) % 5][y]) & b[(x + 2) % 5][y]) & _M64 a[0][0] ^= _RC[rnd] def keccak256(data: bytes) -> bytes: rate = 136 a = [[0] * 5 for _ in range(5)] m = bytearray(data) m.append(0x01) while len(m) % rate: m.append(0x00) m[-1] ^= 0x80 for off in range(0, len(m), rate): blk = m[off:off + rate] for i in range(rate // 8): a[i % 5][i // 5] ^= int.from_bytes(blk[i * 8:i * 8 + 8], "little") _keccak_f(a) out = b"".join(a[i % 5][i // 5].to_bytes(8, "little") for i in range(4)) return out # ============================================================ ripemd-160 _RL = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13, ] _RR = [ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11, ] _SL = [ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6, ] _SR = [ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11, ] _KL = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E] _KR = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000] def _rf(j, x, y, z): if j < 16: return x ^ y ^ z if j < 32: return (x & y) | (~x & z) if j < 48: return (x | (~y & _M32)) ^ z if j < 64: return (x & z) | (y & ~z) return x ^ (y | (~z & _M32)) _M32 = (1 << 32) - 1 def _rol32(v, n): v &= _M32 return ((v << n) | (v >> (32 - n))) & _M32 def ripemd160(data: bytes) -> bytes: h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0] m = bytearray(data) bitlen = (8 * len(data)) & 0xFFFFFFFFFFFFFFFF m.append(0x80) while len(m) % 64 != 56: m.append(0x00) m += bitlen.to_bytes(8, "little") for off in range(0, len(m), 64): x = [int.from_bytes(m[off + 4 * i:off + 4 * i + 4], "little") for i in range(16)] a, b, c, d, e = h a2, b2, c2, d2, e2 = h for j in range(80): t = (_rol32(a + _rf(j, b, c, d) + x[_RL[j]] + _KL[j // 16], _SL[j]) + e) & _M32 a, b, c, d, e = e, t, b, _rol32(c, 10), d t = (_rol32(a2 + _rf(79 - j, b2, c2, d2) + x[_RR[j]] + _KR[j // 16], _SR[j]) + e2) & _M32 a2, b2, c2, d2, e2 = e2, t, b2, _rol32(c2, 10), d2 t = (h[1] + c + d2) & _M32 h[1] = (h[2] + d + e2) & _M32 h[2] = (h[3] + e + a2) & _M32 h[3] = (h[4] + a + b2) & _M32 h[4] = (h[0] + b + c2) & _M32 h[0] = t return b"".join(v.to_bytes(4, "little") for v in h) def hash160(b: bytes) -> bytes: return ripemd160(hashlib.sha256(b).digest()) # ============================================================ secp256k1 P = 2**256 - 2**32 - 977 N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798 GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8 G = (GX, GY) def tagged_hash(tag: str, msg: bytes) -> bytes: t = hashlib.sha256(tag.encode()).digest() return hashlib.sha256(t + t + msg).digest() def point_add(p1, p2): if p1 is None: return p2 if p2 is None: return p1 if p1[0] == p2[0] and p1[1] != p2[1]: return None if p1 == p2: lam = (3 * p1[0] * p1[0] * pow(2 * p1[1], P - 2, P)) % P else: lam = ((p2[1] - p1[1]) * pow(p2[0] - p1[0], P - 2, P)) % P x3 = (lam * lam - p1[0] - p2[0]) % P return (x3, (lam * (p1[0] - x3) - p1[1]) % P) def point_mul(pt, k: int): r = None for i in range(256): if (k >> i) & 1: r = point_add(r, pt) pt = point_add(pt, pt) return r def lift_x(x: int): if x >= P: return None y_sq = (pow(x, 3, P) + 7) % P y = pow(y_sq, (P + 1) // 4, P) if pow(y, 2, P) != y_sq: return None return (x, y if y % 2 == 0 else P - y) def pubkey_xy(sk: bytes): return point_mul(G, int.from_bytes(sk, "big")) def pubkey_compressed(sk: bytes) -> bytes: x, y = pubkey_xy(sk) return bytes([2 + (y & 1)]) + x.to_bytes(32, "big") def xonly_pubkey(sk: bytes) -> bytes: x, y = pubkey_xy(sk) return x.to_bytes(32, "big") def schnorr_sign(msg32: bytes, sk: bytes, aux: bytes | None = None) -> bytes: d0 = int.from_bytes(sk, "big") assert 0 < d0 < N px, py = point_mul(G, d0) d = d0 if py % 2 == 0 else N - d0 aux = aux if aux is not None else os.urandom(32) t = bytes(a ^ b for a, b in zip(d.to_bytes(32, "big"), tagged_hash("BIP0340/aux", aux))) k0 = int.from_bytes(tagged_hash("BIP0340/nonce", t + px.to_bytes(32, "big") + msg32), "big") % N rx, ry = point_mul(G, k0) k = k0 if ry % 2 == 0 else N - k0 e = int.from_bytes(tagged_hash("BIP0340/challenge", rx.to_bytes(32, "big") + px.to_bytes(32, "big") + msg32), "big") % N return rx.to_bytes(32, "big") + ((k + e * d) % N).to_bytes(32, "big") def schnorr_verify(msg32: bytes, pk32: bytes, sig64: bytes) -> bool: if len(pk32) != 32 or len(sig64) != 64: return False pt = lift_x(int.from_bytes(pk32, "big")) if pt is None: return False r = int.from_bytes(sig64[:32], "big") s = int.from_bytes(sig64[32:], "big") if r >= P or s >= N: return False e = int.from_bytes(tagged_hash("BIP0340/challenge", sig64[:32] + pk32 + msg32), "big") % N rp = point_add(point_mul(G, s), point_mul((pt[0], P - pt[1]), e)) return rp is not None and rp[1] % 2 == 0 and rp[0] == r # ============================================================ encodings _BECH32 = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" _B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def _polymod(values): gen = [0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3] chk = 1 for v in values: b = chk >> 25 chk = (chk & 0x1FFFFFF) << 5 ^ v for i in range(5): if (b >> i) & 1: chk ^= gen[i] return chk def _convertbits(data, frombits, tobits, pad=True): acc = bits = 0 out = [] maxv = (1 << tobits) - 1 for v in data: acc = (acc << frombits) | v bits += frombits while bits >= tobits: bits -= tobits out.append((acc >> bits) & maxv) if pad and bits: out.append((acc << (tobits - bits)) & maxv) return out def segwit_encode(hrp: str, witver: int, prog: bytes) -> str: data = [witver] + _convertbits(prog, 8, 5) hrp_exp = [ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp] pm = _polymod(hrp_exp + data + [0] * 6) ^ 1 chk = [(pm >> 5 * (5 - i)) & 31 for i in range(6)] return hrp + "1" + "".join(_BECH32[d] for d in data + chk) def b58check(payload: bytes) -> str: chk = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] raw = payload + chk num = int.from_bytes(raw, "big") out = "" while num: num, rem = divmod(num, 58) out = _B58[rem] + out return "1" * (len(raw) - len(raw.lstrip(b"\x00"))) + out def evm_address(sk: bytes) -> str: x, y = pubkey_xy(sk) return "0x" + keccak256(x.to_bytes(32, "big") + y.to_bytes(32, "big")).hex()[-40:] def btc_p2wpkh(sk: bytes, hrp: str = "bc") -> str: return segwit_encode(hrp, 0, hash160(pubkey_compressed(sk))) def tron_address(sk: bytes) -> str: x, y = pubkey_xy(sk) return b58check(b"\x41" + keccak256(x.to_bytes(32, "big") + y.to_bytes(32, "big"))[-20:]) # ============================================================ entropy def dice_to_key(rolls: list[int]) -> bytes: """Rejection-sampled, uniform 32 bytes from base-6 dice rolls. Four rolls give a value in [0, 1296); values >= 1280 are rejected so each accepted value maps uniformly onto one byte. Roughly 36 rolls per 32 bytes of output, so 40 rolls of a die is already past the 256-bit mark. """ out = bytearray() buf = [] for r in rolls: if not 1 <= r <= 6: raise ValueError("dice faces must be 1..6") buf.append(r - 1) if len(buf) == 4: v = ((buf[0] * 6 + buf[1]) * 6 + buf[2]) * 6 + buf[3] if v < 1280: out.append(v % 256) buf = [] if len(out) < 32: raise ValueError("not enough entropy: roll at least 40 times") return bytes(out[:32]) # ============================================================ selftest VECTORS = { "keccak256_empty": ("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", lambda: keccak256(b"").hex()), "keccak256_abc": ("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45", lambda: keccak256(b"abc").hex()), "ripemd160_empty": ("9c1185a5c5e9fc54612808977ee8f548b2258d31", lambda: ripemd160(b"").hex()), "ripemd160_abc": ("8eb208f7e05d987a9b044a8e98c6b087f15a0bfc", lambda: ripemd160(b"abc").hex()), "bip340_pubkey_key1": ("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", lambda: xonly_pubkey((3).to_bytes(32, "big")).hex()), "bip340_sig_key1": ("e907831f80848d1069a5371b402410364bdf1c5f8307b0084c55f1ce2dca8215" "25f66a4a85ea8b71e482a74f382d2ce5ebeee8fdb2172f477df4900d310536c0", lambda: schnorr_sign(bytes(32), (3).to_bytes(32, "big"), bytes(32)).hex()), "bip173_btc_key1": ("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4", lambda: btc_p2wpkh((1).to_bytes(32, "big"))), "eth_key1": ("0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", lambda: evm_address((1).to_bytes(32, "big"))), } def selftest() -> bool: ok = True for name, (want, fn) in VECTORS.items(): got = fn() good = got.lower() == want.lower() ok &= good print(f"{'PASS' if good else 'FAIL'} {name}\n {got}") sig = schnorr_sign(bytes(32), (3).to_bytes(32, "big"), bytes(32)) v = schnorr_verify(bytes(32), bytes.fromhex(VECTORS["bip340_pubkey_key1"][0]), sig) print(f"{'PASS' if v else 'FAIL'} bip340_verify_roundtrip") ok &= v print("\nALL VECTORS PASS" if ok else "\nVECTOR MISMATCH") return ok def _emit(sk: bytes, source: str) -> dict: rec = { "source": source, "created_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"), "secret_key_hex": sk.hex(), "xonly_pubkey_hex": xonly_pubkey(sk).hex(), "addresses": { "evm": evm_address(sk), "btc_bech32": btc_p2wpkh(sk), "tron_trc20": tron_address(sk), }, } print(json.dumps(rec, indent=2)) print("\nStore secret_key_hex offline. Anyone with it owns these funds.", file=sys.stderr) return rec def main(argv: list[str]) -> int: if "--selftest" in argv: return 0 if selftest() else 1 if "--dice" in argv: print("Roll a die, type the faces as digits (e.g. 4 2 6 1 ...). Blank line to finish.", file=sys.stderr) rolls = [] while True: line = input("rolls> ").strip() if not line: break rolls.extend(int(c) for c in line if c.isdigit()) return 0 if _emit(dice_to_key(rolls), f"dice:{len(rolls)}rolls") else 1 if "--gen" in argv: while True: sk = os.urandom(32) if 1 <= int.from_bytes(sk, "big") < N: break return 0 if _emit(sk, "os.urandom") else 1 print(__doc__) return 0 if __name__ == "__main__": raise SystemExit(main(sys.argv[1:]))