Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : QYVORA7# File : security/tests/oracles/oracle.py8# Module : Tests9# Repository : https://git.spboucher.ai/qyvora10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Independent reference oracle of the QYVORA differential tests (test environment only).4243Usage: python3 -I oracle.py <default-op> < cases.json > answers.json4445stdin is a JSON array of case objects, stdout a JSON array of the same length. Every byte string46is lower-case hexadecimal. A case may carry its own "op"; otherwise the command-line operation is47used. An operation that cannot be evaluated answers {"error": "..."} for that case (the Swift side48counts it as a mismatch unless it expects a refusal).4950Nothing here imports or calls QYVORA code. References used:51 hashlib / hmac (CPython, OpenSSL) SHA-2, SHA-3, SHAKE, BLAKE2b, HMAC, PBKDF252 pycryptodome RIPEMD-160, Keccak-25653 argon2-cffi (reference C library) Argon2d / Argon2i / Argon2id54 coincurve (libsecp256k1) secp256k1 keys, ECDSA, recovery, tweaks, BIP-34055 third_party/bip340/reference.py BIP-340 reference implementation (pure Python)56 third_party/bech32/segwit_addr.py BIP-173 / BIP-350 reference implementation57 embit BIP-32, Bitcoin transactions, BIP-143 digests, addresses58 mnemonic (Trezor) BIP-3959 libspb_pqc.dylib through ctypes ML-KEM, ML-DSA, SLH-DSA (Rust library spb-quantum-crypto)60 pure Python written here HKDF, X25519 (RFC 7748), ECDSA verification on integers,61 RLP, Base58Check, EIP-55, EIP-1559 payloads, 256-bit integers62"""6364import ctypes65import hashlib66import hmac67import json68import os69import sys7071HERE = os.path.dirname(os.path.abspath(__file__))72sys.path.insert(0, os.path.join(HERE, "third_party", "bip340"))73sys.path.insert(0, os.path.join(HERE, "third_party", "bech32"))747576def h(b):77 return bytes(b).hex()787980def u(s):81 return bytes.fromhex(s)828384# --------------------------------------------------------------------------- hashes and KDFs8586def keccak256(data):87 from Crypto.Hash import keccak88 return keccak.new(digest_bits=256, data=data).digest()899091def ripemd160(data):92 from Crypto.Hash import RIPEMD16093 return RIPEMD160.new(data).digest()949596def op_hash(c):97 alg, data = c["alg"], u(c["data"])98 if alg == "ripemd160":99 out = ripemd160(data)100 elif alg == "keccak256":101 out = keccak256(data)102 elif alg == "hash160":103 out = ripemd160(hashlib.sha256(data).digest())104 elif alg == "sha256d":105 out = hashlib.sha256(hashlib.sha256(data).digest()).digest()106 elif alg in ("shake128", "shake256"):107 out = getattr(hashlib, "shake_" + alg[5:])(data).digest(c["len"])108 else:109 out = hashlib.new(alg, data).digest()110 return {"out": h(out)}111112113def op_blake2b(c):114 return {"out": h(hashlib.blake2b(u(c["data"]), digest_size=c["size"], key=u(c["key"])).digest())}115116117def op_hmac(c):118 return {"out": h(hmac.new(u(c["key"]), u(c["data"]), c["alg"]).digest())}119120121def op_hkdf(c):122 """RFC 5869, written here on top of hmac."""123 alg, ikm, salt, info, length = c["alg"], u(c["ikm"]), u(c["salt"]), u(c["info"]), c["len"]124 hlen = hashlib.new(alg).digest_size125 prk = hmac.new(salt if salt else b"\x00" * hlen, ikm, alg).digest()126 if length > 255 * hlen:127 return {"prk": h(prk), "okm": None}128 okm, t, i = b"", b"", 1129 while len(okm) < length:130 t = hmac.new(prk, t + info + bytes([i]), alg).digest()131 okm += t132 i += 1133 return {"prk": h(prk), "okm": h(okm[:length])}134135136def op_pbkdf2(c):137 return {"out": h(hashlib.pbkdf2_hmac(c["alg"], u(c["password"]), u(c["salt"]), c["iterations"], c["len"]))}138139140def op_argon2(c):141 """Reference C implementation through argon2-cffi's low-level context (supports the key K and data X)."""142 from argon2.low_level import ffi, lib, core143 pwd, salt, secret, ad = u(c["password"]), u(c["salt"]), u(c["secret"]), u(c["ad"])144 out = ffi.new("uint8_t[]", c["taglen"])145 cpwd, csalt = ffi.new("uint8_t[]", pwd), ffi.new("uint8_t[]", salt)146 csecret = ffi.new("uint8_t[]", secret) if secret else ffi.NULL147 cad = ffi.new("uint8_t[]", ad) if ad else ffi.NULL148 ctx = ffi.new("argon2_context *", dict(149 out=out, outlen=c["taglen"], version=0x13, pwd=cpwd, pwdlen=len(pwd), salt=csalt, saltlen=len(salt),150 secret=csecret, secretlen=len(secret), ad=cad, adlen=len(ad), t_cost=c["t"], m_cost=c["m"],151 lanes=c["p"], threads=1, allocate_cbk=ffi.NULL, free_cbk=ffi.NULL, flags=lib.ARGON2_DEFAULT_FLAGS))152 rv = core(ctx, {"d": 0, "i": 1, "id": 2}[c["variant"]])153 if rv != lib.ARGON2_OK:154 return {"error": "argon2 error %d" % rv}155 return {"out": h(bytes(ffi.buffer(out, c["taglen"])))}156157158# --------------------------------------------------------------------------- X25519 (RFC 7748, pure Python)159160P25519 = 2 ** 255 - 19161162163def x25519(k, ub):164 kb = bytearray(k)165 kb[0] &= 248166 kb[31] &= 127167 kb[31] |= 64168 k = int.from_bytes(kb, "little")169 ub = bytearray(ub)170 ub[31] &= 127171 x1 = int.from_bytes(ub, "little") % P25519172 x2, z2, x3, z3, swap = 1, 0, x1, 1, 0173 for t in reversed(range(255)):174 kt = (k >> t) & 1175 swap ^= kt176 if swap:177 x2, x3, z2, z3 = x3, x2, z3, z2178 swap = kt179 a, b = (x2 + z2) % P25519, (x2 - z2) % P25519180 aa, bb = a * a % P25519, b * b % P25519181 e = (aa - bb) % P25519182 cc, d = (x3 + z3) % P25519, (x3 - z3) % P25519183 da, cb = d * a % P25519, cc * b % P25519184 x3 = (da + cb) ** 2 % P25519185 z3 = x1 * (da - cb) ** 2 % P25519186 x2 = aa * bb % P25519187 z2 = e * (aa + 121665 * e) % P25519188 if swap:189 x2, x3, z2, z3 = x3, x2, z3, z2190 return (x2 * pow(z2, P25519 - 2, P25519) % P25519).to_bytes(32, "little")191192193def op_x25519(c):194 sk = u(c["sk"])195 out = {"pub": h(x25519(sk, (9).to_bytes(32, "little")))}196 if c.get("peer"):197 out["shared"] = h(x25519(sk, u(c["peer"])))198 return out199200201# --------------------------------------------------------------------------- secp256k1202203SECP_P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F204SECP_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141205SECP_G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,206 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)207208209def ec_add(a, b):210 if a is None:211 return b212 if b is None:213 return a214 if a[0] == b[0] and (a[1] + b[1]) % SECP_P == 0:215 return None216 if a == b:217 lam = 3 * a[0] * a[0] * pow(2 * a[1], SECP_P - 2, SECP_P) % SECP_P218 else:219 lam = (b[1] - a[1]) * pow(b[0] - a[0], SECP_P - 2, SECP_P) % SECP_P220 x = (lam * lam - a[0] - b[0]) % SECP_P221 return (x, (lam * (a[0] - x) - a[1]) % SECP_P)222223224def ec_mul(k, pt):225 r = None226 while k:227 if k & 1:228 r = ec_add(r, pt)229 pt = ec_add(pt, pt)230 k >>= 1231 return r232233234def ec_parse(pub):235 """SEC1 public key → affine point, or None (strict: canonical coordinates, on the curve)."""236 if len(pub) == 33 and pub[0] in (2, 3):237 x = int.from_bytes(pub[1:], "big")238 if x >= SECP_P:239 return None240 y2 = (pow(x, 3, SECP_P) + 7) % SECP_P241 y = pow(y2, (SECP_P + 1) // 4, SECP_P)242 if y * y % SECP_P != y2:243 return None244 if (y & 1) != (pub[0] & 1):245 y = SECP_P - y246 return (x, y)247 if len(pub) == 65 and pub[0] == 4:248 x, y = int.from_bytes(pub[1:33], "big"), int.from_bytes(pub[33:], "big")249 if x >= SECP_P or y >= SECP_P or (y * y - x * x * x - 7) % SECP_P != 0:250 return None251 return (x, y)252 return None253254255def ecdsa_verify_int(pub, digest, sig):256 """Textbook ECDSA verification on Python integers. Returns (valid, s is in the lower half)."""257 q = ec_parse(pub)258 if q is None or len(sig) != 64 or len(digest) != 32:259 return False, False260 r, s = int.from_bytes(sig[:32], "big"), int.from_bytes(sig[32:], "big")261 if not (1 <= r < SECP_N and 1 <= s < SECP_N):262 return False, False263 z = int.from_bytes(digest, "big")264 w = pow(s, SECP_N - 2, SECP_N)265 pt = ec_add(ec_mul(z * w % SECP_N, SECP_G), ec_mul(r * w % SECP_N, q))266 return (pt is not None and pt[0] % SECP_N == r), s <= SECP_N // 2267268269def op_secp_pub(c):270 import coincurve271 try:272 k = coincurve.PrivateKey(u(c["sk"]))273 except ValueError as e:274 return {"error": str(e)}275 return {"pub33": h(k.public_key.format(True)), "pub65": h(k.public_key.format(False)),276 "xonly": h(k.public_key_xonly.format())}277278279def op_secp_parse(c):280 """Public-key parsing: libsecp256k1 and the integer parser must agree; answers both encodings or null."""281 import coincurve282 raw = u(c["pub"])283 try:284 pk = coincurve.PublicKey(raw)285 lib_ok = True286 except Exception:287 pk, lib_ok = None, False288 mine = ec_parse(raw)289 # libsecp256k1 also accepts the hybrid encodings 0x06 / 0x07, which QYVORA refuses by design.290 hybrid = len(raw) == 65 and raw[0] in (6, 7)291 return {"valid": mine is not None, "libsecp_valid": lib_ok, "hybrid": hybrid,292 "pub33": h(pk.format(True)) if (pk is not None and mine is not None) else None,293 "pub65": h(pk.format(False)) if (pk is not None and mine is not None) else None}294295296def op_ecdsa_sign(c):297 """RFC 6979 deterministic ECDSA with low s (libsecp256k1 default nonce function)."""298 import coincurve299 sig = coincurve.PrivateKey(u(c["sk"])).sign_recoverable(u(c["digest"]), hasher=None)300 return {"compact": h(sig[:64]), "recid": sig[64]}301302303def op_ecdsa_verify(c):304 import coincurve305 """Verdicts of libsecp256k1: `libsecp_valid` as given (it accepts low-s signatures only), `valid` for the306 signature with s normalised to the lower half (validity regardless of s), `low_s`. With "int": true the307 textbook integer verification is evaluated as well (`int_valid`)."""308 pub, digest, sig = u(c["pub"]), u(c["digest"]), u(c["sig"])309 r, s = int.from_bytes(sig[:32], "big"), int.from_bytes(sig[32:], "big")310 in_range = len(sig) == 64 and 1 <= r < SECP_N and 1 <= s < SECP_N311312 def der_int(v):313 b = v.to_bytes(33, "big").lstrip(b"\x00") or b"\x00"314 if b[0] & 0x80:315 b = b"\x00" + b316 return b"\x02" + bytes([len(b)]) + b317318 def lib_verify(r, s):319 try:320 body = der_int(r) + der_int(s)321 return bool(coincurve.PublicKey(pub).verify(b"\x30" + bytes([len(body)]) + body, digest, hasher=None))322 except Exception:323 return False324325 low = in_range and s <= SECP_N // 2326 out = {"libsecp_valid": in_range and lib_verify(r, s),327 "valid": in_range and lib_verify(r, s if low else SECP_N - s), "low_s": low}328 if c.get("int"):329 out["int_valid"] = ecdsa_verify_int(pub, digest, sig)[0]330 return out331332333def op_ecdsa_recover(c):334 import coincurve335 try:336 pk = coincurve.PublicKey.from_signature_and_message(u(c["sig"]) + bytes([c["recid"]]), u(c["digest"]), hasher=None)337 return {"pub33": h(pk.format(True)), "pub65": h(pk.format(False))}338 except Exception:339 return {"pub33": None, "pub65": None}340341342def op_secp_tweak(c):343 import coincurve344 out = {}345 try:346 out["sk"] = h(coincurve.PrivateKey(u(c["sk"])).add(u(c["tweak"])).secret)347 except Exception:348 out["sk"] = None349 try:350 out["pub"] = h(coincurve.PublicKey(u(c["pub"])).add(u(c["tweak"])).format(True))351 except Exception:352 out["pub"] = None353 return out354355356def op_schnorr(c):357 """BIP-340: libsecp256k1 (coincurve) and, when "ref" is set, the BIP's reference Python."""358 import coincurve359 sk, msg, aux = u(c["sk"]), u(c["msg"]), u(c["aux"])360 k = coincurve.PrivateKey(sk)361 out = {"xonly": h(k.public_key_xonly.format()), "sig": h(k.sign_schnorr(msg, aux))}362 if c.get("ref"):363 import reference364 out["ref_xonly"] = h(reference.pubkey_gen(sk))365 out["ref_sig"] = h(reference.schnorr_sign(msg, sk, aux))366 return out367368369def op_schnorr_ref(c):370 """BIP-340 reference implementation only (messages of any length); libsecp256k1 too when the message is 32 bytes."""371 import reference372 sk, msg, aux = u(c["sk"]), u(c["msg"]), u(c["aux"])373 out = {"ref_xonly": h(reference.pubkey_gen(sk)), "ref_sig": h(reference.schnorr_sign(msg, sk, aux))}374 if len(msg) == 32:375 import coincurve376 if h(coincurve.PrivateKey(sk).sign_schnorr(msg, aux)) != out["ref_sig"]:377 return {"error": "the two reference implementations disagree"}378 return out379380381def op_schnorr_verify(c):382 import coincurve383 pub, msg, sig = u(c["pub"]), u(c["msg"]), u(c["sig"])384 try:385 lib_ok = coincurve.PublicKeyXOnly(pub).verify(sig, msg)386 except Exception:387 lib_ok = False388 out = {"valid": bool(lib_ok)}389 if c.get("ref"):390 import reference391 out["ref_valid"] = bool(reference.schnorr_verify(msg, pub, sig))392 return out393394395# --------------------------------------------------------------------------- BIP-32 / BIP-39396397def b58encode(b):398 alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"399 n = int.from_bytes(b, "big")400 s = ""401 while n:402 n, r = divmod(n, 58)403 s = alphabet[r] + s404 return "1" * (len(b) - len(b.lstrip(b"\x00"))) + s405406407def b58decode(s):408 alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"409 n = 0410 for ch in s:411 i = alphabet.find(ch)412 if i < 0:413 return None414 n = n * 58 + i415 zeros = len(s) - len(s.lstrip("1"))416 body = n.to_bytes((n.bit_length() + 7) // 8, "big")417 return b"\x00" * zeros + body418419420def b58check_encode(payload):421 return b58encode(payload + hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4])422423424def b58check_decode(s):425 raw = b58decode(s)426 if raw is None or len(raw) < 4:427 return None428 payload, check = raw[:-4], raw[-4:]429 if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4] != check:430 return None431 return payload432433434def bip32_own(seed, path):435 """BIP-32 written here on hmac + libsecp256k1; returns private and public-only derivations."""436 import coincurve437 i = hmac.new(b"Bitcoin seed", seed, "sha512").digest()438 k, chain = i[:32], i[32:]439 depth, parent_fp, child = 0, b"\x00" * 4, 0440 pub_k, pub_chain = None, None # public-only chain, restarted after each hardened step441 for index in path:442 pub = coincurve.PrivateKey(k).public_key.format(True)443 if index & 0x80000000:444 data = b"\x00" + k + index.to_bytes(4, "big")445 else:446 data = pub + index.to_bytes(4, "big")447 i = hmac.new(chain, data, "sha512").digest()448 if not (index & 0x80000000):449 base, base_chain = (pub_k, pub_chain) if pub_k is not None else (pub, chain)450 j = hmac.new(base_chain, base + index.to_bytes(4, "big"), "sha512").digest()451 pub_k = coincurve.PublicKey(base).add(j[:32]).format(True)452 pub_chain = j[32:]453 else:454 pub_k, pub_chain = None, None455 parent_fp = ripemd160(hashlib.sha256(pub).digest())[:4]456 k = coincurve.PrivateKey(k).add(i[:32]).secret457 chain, depth, child = i[32:], depth + 1, index458 pub = coincurve.PrivateKey(k).public_key.format(True)459 meta = bytes([depth]) + parent_fp + child.to_bytes(4, "big") + chain460 return {461 "priv": h(k), "pub": h(pub), "chain": h(chain),462 "xprv": b58check_encode(bytes.fromhex("0488ade4") + meta + b"\x00" + k),463 "xpub": b58check_encode(bytes.fromhex("0488b21e") + meta + pub),464 "public_only_pub": h(pub_k) if pub_k is not None else None,465 }466467468def op_bip32(c):469 from embit import bip32470 seed, path = u(c["seed"]), c["path"]471 own = bip32_own(seed, path)472 node = bip32.HDKey.from_seed(seed).derive(path)473 emb = {"xprv": node.to_base58(), "xpub": node.to_public().to_base58()}474 if emb["xprv"] != own["xprv"] or emb["xpub"] != own["xpub"]:475 return {"error": "the two reference implementations disagree", "embit": emb, "own": own}476 own["oracles_agree"] = True477 return own478479480def op_bip39(c):481 from mnemonic import Mnemonic482 m = Mnemonic("english")483 if "entropy" in c:484 words = m.to_mnemonic(u(c["entropy"]))485 return {"mnemonic": words, "seed": h(Mnemonic.to_seed(words, c.get("passphrase", "")))}486 return {"valid": bool(m.check(c["mnemonic"]))}487488489# --------------------------------------------------------------------------- encodings490491def op_base58check(c):492 if "payload" in c:493 return {"text": b58check_encode(u(c["payload"])), "raw": b58encode(u(c["payload"]))}494 payload = b58check_decode(c["text"])495 raw = b58decode(c["text"])496 return {"payload": h(payload) if payload is not None else None, "raw": h(raw) if raw is not None else None}497498499def op_segwit(c):500 import segwit_addr501 if "program" in c:502 return {"address": segwit_addr.encode(c["hrp"], c["version"], list(u(c["program"])))}503 ver, prog = segwit_addr.decode(c["hrp"], c["address"])504 return {"version": ver, "program": h(bytes(prog)) if prog is not None else None}505506507def op_bech32(c):508 import segwit_addr509 spec = segwit_addr.Encoding.BECH32M if c["variant"] == "bech32m" else segwit_addr.Encoding.BECH32510 if "words" in c:511 return {"text": segwit_addr.bech32_encode(c["hrp"], list(u(c["words"])), spec)}512 hrp, data, got = segwit_addr.bech32_decode(c["text"])513 if hrp is None or got != spec:514 return {"hrp": None, "words": None}515 return {"hrp": hrp, "words": h(bytes(data))}516517518def eip55(addr):519 hx = addr.hex()520 digest = keccak256(hx.encode()).hex()521 return "0x" + "".join(ch.upper() if ch.isalpha() and int(digest[i], 16) >= 8 else ch for i, ch in enumerate(hx))522523524def op_eip55(c):525 if "address" in c:526 return {"text": eip55(u(c["address"]))}527 t = c["text"]528 body = t[2:] if t[:2] in ("0x", "0X") else t529 try:530 raw = bytes.fromhex(body)531 except ValueError:532 return {"valid_checksum": False, "address": None}533 if len(raw) != 20 or len(body) != 40:534 return {"valid_checksum": False, "address": None}535 return {"valid_checksum": eip55(raw)[2:] == body, "single_case": body in (body.lower(), body.upper()), "address": h(raw)}536537538def rlp_encode(item):539 if isinstance(item, str):540 b = u(item)541 if len(b) == 1 and b[0] < 0x80:542 return b543 return rlp_len(len(b), 0x80) + b544 body = b"".join(rlp_encode(x) for x in item)545 return rlp_len(len(body), 0xC0) + body546547548def rlp_len(n, offset):549 if n < 56:550 return bytes([offset + n])551 nb = n.to_bytes((n.bit_length() + 7) // 8, "big")552 return bytes([offset + 55 + len(nb)]) + nb553554555class RLPError(Exception):556 pass557558559def rlp_decode_item(d, i, depth=0):560 """Strict (canonical) decoder following the Yellow Paper, appendix B."""561 if i >= len(d):562 raise RLPError("truncated")563 p = d[i]564 i += 1565 if p < 0x80:566 return h(bytes([p])), i567568 def long_len(n, i):569 if i + n > len(d):570 raise RLPError("truncated")571 lb = d[i:i + n]572 if lb[0] == 0:573 raise RLPError("non canonical length")574 v = int.from_bytes(lb, "big")575 if v < 56:576 raise RLPError("non canonical length")577 return v, i + n578579 if p <= 0xB7:580 n = p - 0x80581 if i + n > len(d):582 raise RLPError("truncated")583 if n == 1 and d[i] < 0x80:584 raise RLPError("non canonical single byte")585 return h(d[i:i + n]), i + n586 if p <= 0xBF:587 n, i = long_len(p - 0xB7, i)588 if i + n > len(d):589 raise RLPError("truncated")590 return h(d[i:i + n]), i + n591 if p <= 0xF7:592 n = p - 0xC0593 else:594 n, i = long_len(p - 0xF7, i)595 if i + n > len(d):596 raise RLPError("truncated")597 end, items = i + n, []598 while i < end:599 x, i = rlp_decode_item(d, i, depth + 1)600 items.append(x)601 if i != end:602 raise RLPError("item overruns its list")603 return items, i604605606def rlp_depth(x):607 return 0 if isinstance(x, str) else 1 + max([rlp_depth(y) for y in x], default=0)608609610def op_rlp(c):611 if "item" in c:612 return {"encoded": h(rlp_encode(c["item"]))}613 d = u(c["encoded"])614 try:615 item, i = rlp_decode_item(d, 0)616 if i != len(d):617 raise RLPError("trailing bytes")618 return {"item": item, "ok": True, "depth": rlp_depth(item)}619 except RLPError as e:620 return {"item": None, "ok": False, "why": str(e)}621 except RecursionError:622 return {"item": None, "ok": False, "why": "recursion"}623624625M256 = (1 << 256) - 1626627628def op_uint256(c):629 a, b, op = int(c["a"], 16), int(c.get("b", "0"), 16), c["fn"]630 if op == "add":631 r = a + b632 return {"r": "%x" % (r & M256), "overflow": r > M256}633 if op == "sub":634 r = a - b635 return {"r": "%x" % (r & M256), "overflow": r < 0}636 if op == "mul":637 r = a * b638 return {"r": "%x" % (r & M256), "overflow": r > M256}639 if op == "divmod64":640 q, m = divmod(a, b)641 return {"q": "%x" % q, "m": "%x" % m}642 if op == "cmp":643 return {"lt": a < b, "eq": a == b}644 if op == "decimal":645 return {"decimal": str(a), "hex": "0x%x" % a, "min": h(a.to_bytes((a.bit_length() + 7) // 8, "big"))}646 return {"error": "unknown uint256 function"}647648649# --------------------------------------------------------------------------- transactions650651def int_bytes(v):652 return h(v.to_bytes((v.bit_length() + 7) // 8, "big"))653654655def op_eth_tx(c):656 """EIP-1559 (type 2) transaction built, hashed and signed independently of QYVORA."""657 import coincurve658 access = [[a, list(keys)] for a, keys in c["access"]]659 fields = [int_bytes(int(c["chain"])), int_bytes(int(c["nonce"])), int_bytes(int(c["prio"], 16)),660 int_bytes(int(c["fee"], 16)), int_bytes(int(c["gas"])), c["to"], int_bytes(int(c["value"], 16)),661 c["data"], access]662 unsigned = b"\x02" + rlp_encode(fields)663 sighash = keccak256(unsigned)664 key = coincurve.PrivateKey(u(c["sk"]))665 sig = key.sign_recoverable(sighash, hasher=None)666 r, s, v = int.from_bytes(sig[:32], "big"), int.from_bytes(sig[32:64], "big"), sig[64]667 raw = b"\x02" + rlp_encode(fields + [int_bytes(v), int_bytes(r), int_bytes(s)])668 sender = keccak256(key.public_key.format(False)[1:])[12:]669 return {"unsigned": h(unsigned), "sighash": h(sighash), "raw": h(raw), "hash": h(keccak256(raw)),670 "sender": eip55(sender)}671672673def op_eth_recover(c):674 """Decodes a raw signed type-2 transaction and recovers its sender."""675 import coincurve676 raw = u(c["raw"])677 if not raw or raw[0] != 2:678 return {"error": "not a type-2 transaction"}679 try:680 items, i = rlp_decode_item(raw, 1)681 except RLPError as e:682 return {"error": str(e)}683 if i != len(raw) or not isinstance(items, list) or len(items) != 12:684 return {"error": "malformed"}685 sighash = keccak256(b"\x02" + rlp_encode(items[:9]))686 v = int(items[9] or "0", 16)687 sig = u(items[10]).rjust(32, b"\x00") + u(items[11]).rjust(32, b"\x00") + bytes([v])688 pk = coincurve.PublicKey.from_signature_and_message(sig, sighash, hasher=None)689 return {"sender": eip55(keccak256(pk.format(False)[1:])[12:]), "hash": h(keccak256(raw)), "sighash": h(sighash)}690691692def op_eth_personal(c):693 import coincurve694 msg = u(c["msg"])695 digest = keccak256(b"\x19Ethereum Signed Message:\n" + str(len(msg)).encode() + msg)696 key = coincurve.PrivateKey(u(c["sk"]))697 sig = key.sign_recoverable(digest, hasher=None)698 return {"digest": h(digest), "sig": h(sig[:64] + bytes([27 + sig[64]])),699 "signer": eip55(keccak256(key.public_key.format(False)[1:])[12:])}700701702def der_sig(compact):703 def der_int(b):704 b = b.lstrip(b"\x00") or b"\x00"705 if b[0] & 0x80:706 b = b"\x00" + b707 return b"\x02" + bytes([len(b)]) + b708 body = der_int(compact[:32]) + der_int(compact[32:])709 return b"\x30" + bytes([len(body)]) + body710711712def op_btc_p2wpkh(c):713 """A signed P2WPKH transaction checked with embit (parsing, BIP-143 digests) and libsecp256k1 (signatures)."""714 import coincurve715 from io import BytesIO716 from embit import script717 from embit.transaction import Transaction718 raw = u(c["tx"])719 tx = Transaction.parse(raw)720 out = {"txid": h(tx.txid()), "reserialized": h(tx.serialize()), "inputs": []}721 for i, inp in enumerate(c["inputs"]):722 key = coincurve.PrivateKey(u(inp["sk"]))723 pub = key.public_key.format(True)724 spk = script.Script(b"\x00\x14" + ripemd160(hashlib.sha256(pub).digest()))725 digest = tx.sighash_segwit(i, script.p2pkh_from_p2wpkh(spk), int(inp["value"]), inp["sighash"])726 sig = key.sign_recoverable(digest, hasher=None)[:64]727 out["inputs"].append({"digest": h(digest), "signature": h(der_sig(sig) + bytes([inp["sighash"]])),728 "pub": h(pub), "script_pubkey": h(spk.data)})729 wtx = hashlib.sha256(hashlib.sha256(raw).digest()).digest()[::-1]730 out["wtxid"] = h(wtx)731 return out732733734def op_btc_address(c):735 from embit import script736 net = script.NETWORKS[{"mainnet": "main", "testnet": "test", "signet": "signet"}[c["network"]]]737 if "script" in c:738 try:739 return {"address": script.Script(u(c["script"])).address(net)}740 except Exception as e:741 return {"address": None, "why": str(e)}742 try:743 spk = script.address_to_scriptpubkey(c["address"])744 return {"script": h(spk.data)}745 except Exception as e:746 return {"script": None, "why": str(e)}747748749# --------------------------------------------------------------------------- Rust library spb-quantum-crypto (FFI)750751PQ_ALG = {752 "ML-KEM-512": 257, "ML-KEM-768": 258, "ML-KEM-1024": 259,753 "ML-DSA-44": 513, "ML-DSA-65": 514, "ML-DSA-87": 515,754 "SLH-DSA-SHA2-128s": 769, "SLH-DSA-SHAKE-128s": 770, "SLH-DSA-SHA2-128f": 771, "SLH-DSA-SHAKE-128f": 772,755 "SLH-DSA-SHA2-192s": 773, "SLH-DSA-SHAKE-192s": 774, "SLH-DSA-SHA2-192f": 775, "SLH-DSA-SHAKE-192f": 776,756 "SLH-DSA-SHA2-256s": 777, "SLH-DSA-SHAKE-256s": 778, "SLH-DSA-SHA2-256f": 779, "SLH-DSA-SHAKE-256f": 780,757}758PQ_HASH = {"": 0, "SHA2-224": 1025, "SHA2-256": 1026, "SHA2-384": 1027, "SHA2-512": 1028, "SHA2-512/224": 1029,759 "SHA2-512/256": 1030, "SHA3-224": 1031, "SHA3-256": 1032, "SHA3-384": 1033, "SHA3-512": 1034,760 "SHAKE-128": 1035, "SHAKE-256": 1036}761_pq = None762763764def pq():765 global _pq766 if _pq is None:767 path = os.environ.get("QY_SPBPQC_DYLIB") or os.path.join(HERE, "..", "..", ".tools", "lib", "libspb_pqc.dylib")768 _pq = ctypes.CDLL(path)769 _pq.spb_pqc_version.restype = ctypes.c_char_p770 _pq.spb_pqc_error_name.restype = ctypes.c_char_p771 return _pq772773774def pq_sizes(alg):775 lib = pq()776 a, b, c, d = ctypes.c_size_t(), ctypes.c_size_t(), ctypes.c_size_t(), ctypes.c_size_t()777 if alg < 512:778 rv = lib.spb_pqc_kem_sizes(ctypes.c_uint32(alg), ctypes.byref(a), ctypes.byref(b), ctypes.byref(c), ctypes.byref(d))779 else:780 rv = lib.spb_pqc_sig_sizes(ctypes.c_uint32(alg), ctypes.byref(a), ctypes.byref(b), ctypes.byref(c))781 if rv != 0:782 raise ValueError("sizes failed")783 return a.value, b.value, c.value, d.value784785786def cbuf(data):787 return (ctypes.c_uint8 * max(1, len(data))).from_buffer_copy(data if data else b"\x00")788789790def op_pq(c):791 lib = pq()792 fn = c["fn"]793 if fn == "version":794 return {"version": lib.spb_pqc_version().decode(), "abi": lib.spb_pqc_abi_version(),795 "selftest": lib.spb_pqc_self_test()}796 alg = PQ_ALG[c["alg"]]797 pkl, skl, third, ssl = pq_sizes(alg)798 A, Z = ctypes.c_uint32(alg), ctypes.c_size_t799800 def err(rv):801 return {"error": lib.spb_pqc_error_name(ctypes.c_int32(rv)).decode(), "code": rv}802803 if fn == "kem_keypair":804 pk, sk = (ctypes.c_uint8 * pkl)(), (ctypes.c_uint8 * skl)()805 rv = lib.spb_pqc_kem_keypair(A, pk, Z(pkl), sk, Z(skl))806 return {"pk": h(pk), "sk": h(sk)} if rv == 0 else err(rv)807 if fn == "kem_encaps":808 pk = u(c["pk"])809 ct, ss = (ctypes.c_uint8 * third)(), (ctypes.c_uint8 * ssl)()810 rv = lib.spb_pqc_kem_encapsulate(A, cbuf(pk), Z(len(pk)), ct, Z(third), ss, Z(ssl))811 return {"ct": h(ct), "ss": h(ss)} if rv == 0 else err(rv)812 if fn == "kem_decaps":813 sk, ct = u(c["sk"]), u(c["ct"])814 ss = (ctypes.c_uint8 * ssl)()815 rv = lib.spb_pqc_kem_decapsulate(A, cbuf(sk), Z(len(sk)), cbuf(ct), Z(len(ct)), ss, Z(ssl))816 return {"ss": h(ss)} if rv == 0 else err(rv)817 if fn == "kem_check_pk":818 pk = u(c["pk"])819 return {"ok": lib.spb_pqc_kem_check_public_key(A, cbuf(pk), Z(len(pk))) == 0}820 if fn == "kem_check_sk":821 sk = u(c["sk"])822 return {"ok": lib.spb_pqc_kem_check_private_key(A, cbuf(sk), Z(len(sk))) == 0}823 if fn == "sig_keypair":824 pk, sk = (ctypes.c_uint8 * pkl)(), (ctypes.c_uint8 * skl)()825 rv = lib.spb_pqc_sig_keypair(A, pk, Z(pkl), sk, Z(skl))826 return {"pk": h(pk), "sk": h(sk)} if rv == 0 else err(rv)827 if fn == "sig_pub_from_priv":828 sk = u(c["sk"])829 pk = (ctypes.c_uint8 * pkl)()830 rv = lib.spb_pqc_sig_public_from_private(A, cbuf(sk), Z(len(sk)), pk, Z(pkl))831 return {"pk": h(pk)} if rv == 0 else err(rv)832 if fn == "sig_sign":833 sk, msg, ctx = u(c["sk"]), u(c["msg"]), u(c.get("ctx", ""))834 sig = (ctypes.c_uint8 * third)()835 rv = lib.spb_pqc_sig_sign(A, cbuf(sk), Z(len(sk)), cbuf(msg), Z(len(msg)), cbuf(ctx), Z(len(ctx)),836 ctypes.c_uint32(PQ_HASH[c.get("prehash", "")]),837 ctypes.c_uint32(1 if c.get("deterministic", True) else 0), sig, Z(third))838 return {"sig": h(sig)} if rv == 0 else err(rv)839 if fn == "sig_verify":840 pk, msg, ctx, sig = u(c["pk"]), u(c["msg"]), u(c.get("ctx", "")), u(c["sig"])841 rv = lib.spb_pqc_sig_verify(A, cbuf(pk), Z(len(pk)), cbuf(msg), Z(len(msg)), cbuf(ctx), Z(len(ctx)),842 ctypes.c_uint32(PQ_HASH[c.get("prehash", "")]), cbuf(sig), Z(len(sig)))843 return {"ok": rv == 0, "code": rv}844 return {"error": "unknown pq function"}845846847def op_versions(c):848 """Versions of every reference used, for the audit record."""849 from importlib import metadata850 out = {"python": sys.version.split()[0], "openssl": __import__("ssl").OPENSSL_VERSION}851 for pkg in ("coincurve", "pycryptodome", "argon2-cffi", "argon2-cffi-bindings", "embit", "mnemonic", "cffi"):852 try:853 out[pkg] = metadata.version(pkg)854 except metadata.PackageNotFoundError:855 out[pkg] = None856 try:857 lib = pq()858 out["spb-quantum-crypto"] = lib.spb_pqc_version().decode()859 except OSError:860 out["spb-quantum-crypto"] = None861 for name, rel_path in (("bip340-reference.py", "third_party/bip340/reference.py"),862 ("segwit_addr.py", "third_party/bech32/segwit_addr.py")):863 with open(os.path.join(HERE, rel_path), "rb") as f:864 out[name + " sha256"] = hashlib.sha256(f.read()).hexdigest()865 return out866867868OPS = {name[3:]: fn for name, fn in list(globals().items()) if name.startswith("op_")}869870871def main():872 default = sys.argv[1] if len(sys.argv) > 1 else ""873 cases = json.load(sys.stdin)874 answers = []875 for c in cases:876 try:877 answers.append(OPS[c.get("op", default)](c))878 except Exception as e: # one bad case must not hide the others879 answers.append({"error": "%s: %s" % (type(e).__name__, e)})880 json.dump(answers, sys.stdout)881882883if __name__ == "__main__":884 sys.setrecursionlimit(5000)885 main()886