Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : QYVORA7# File : security/tests/oracles/mc/ed25519.py8# Module : Tests9# Repository : https://git.spboucher.ai/qyvora10# Project Website : Not specified11# Created : 2026-12-0512# Last Modified : 2026-12-0513#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 references for the Ed25519 audit tests (test environment only).4243 python3 -I ed25519.py <operation> JSON array of cases on stdin, JSON array of answers on stdout4445References:46 - "bigint": Python integers and a direct transcription of RFC 8032 section 5.1 written for this audit47 (field, scalar and group arithmetic, point decoding, cofactorless and cofactored verification equations);48 - PyNaCl (libsodium), `cryptography` (OpenSSL), solders (solana-sdk `Signature::verify`, i.e. ed25519-dalek49 `verify_strict`), bip-utils (SLIP-0010) and a direct HMAC-SHA512 transcription of SLIP-0010.50"""5152import hashlib53import hmac54import json55import sys5657P = 2**255 - 1958L = 2**252 + 2774231777737235353585193779088364849359D = (-121665 * pow(121666, P - 2, P)) % P60SQRT_M1 = pow(2, (P - 1) // 4, P)616263def inv(x):64 return pow(x, P - 2, P)656667# --- group arithmetic, extended coordinates (RFC 8032 section 5.1.4), integers only --------------------------6869def pt_add(a, b):70 x1, y1, z1, t1 = a71 x2, y2, z2, t2 = b72 A = (y1 - x1) * (y2 - x2) % P73 B = (y1 + x1) * (y2 + x2) % P74 C = t1 * 2 * D * t2 % P75 Dd = z1 * 2 * z2 % P76 E, F, G, H = B - A, Dd - C, Dd + C, B + A77 return (E * F % P, G * H % P, F * G % P, E * H % P)787980def pt_mul(s, p):81 q = (0, 1, 1, 0)82 while s > 0:83 if s & 1:84 q = pt_add(q, p)85 p = pt_add(p, p)86 s >>= 187 return q888990def pt_equal(a, b):91 return (a[0] * b[2] - b[0] * a[2]) % P == 0 and (a[1] * b[2] - b[1] * a[2]) % P == 0929394def recover_x(y, sign):95 """x for the reduced y (RFC 8032 5.1.3), or None when y is not the ordinate of a curve point."""96 x2 = (y * y - 1) * inv(D * y * y + 1) % P97 if x2 == 0:98 return 0 if not sign else None # the RFC refuses "x = 0 with sign bit"99 x = pow(x2, (P + 3) // 8, P)100 if (x * x - x2) % P != 0:101 x = x * SQRT_M1 % P102 if (x * x - x2) % P != 0:103 return None104 if (x & 1) != sign:105 x = P - x106 return x107108109def pt_decode(b, strict=True):110 """strict: RFC 8032 5.1.3 (y < p, no negative zero). lenient: y mod p, sign of x = 0 ignored (dalek decompress)."""111 if len(b) != 32:112 return None113 y = int.from_bytes(b, "little")114 sign = y >> 255115 y &= (1 << 255) - 1116 if strict and y >= P:117 return None118 y %= P119 x2 = (y * y - 1) * inv(D * y * y + 1) % P120 if x2 == 0:121 if sign and strict:122 return None123 return (0, y, 1, 0)124 x = recover_x(y, sign)125 if x is None:126 return None127 return (x, y, 1, x * y % P)128129130def pt_encode(p):131 zi = inv(p[2])132 x, y = p[0] * zi % P, p[1] * zi % P133 return (y | ((x & 1) << 255)).to_bytes(32, "little")134135136G_Y = 4 * inv(5) % P137BASE = (recover_x(G_Y, 0), G_Y, 1, recover_x(G_Y, 0) * G_Y % P)138IDENTITY = (0, 1, 1, 0)139140141def is_small_order(p):142 return pt_equal(pt_mul(8, p), IDENTITY)143144145def has_torsion(p):146 return not pt_equal(pt_mul(L, p), IDENTITY)147148149def challenge(r, a, m):150 return int.from_bytes(hashlib.sha512(r + a + m).digest(), "little") % L151152153def expand(seed):154 h = hashlib.sha512(seed).digest()155 a = int.from_bytes(h[:32], "little")156 a &= (1 << 254) - 8157 a |= 1 << 254158 return a, h[32:]159160161def ref_sign(seed, m):162 a, prefix = expand(seed)163 A = pt_encode(pt_mul(a, BASE))164 r = int.from_bytes(hashlib.sha512(prefix + m).digest(), "little") % L165 R = pt_encode(pt_mul(r, BASE))166 s = (r + challenge(R, A, m) * a) % L167 return A, R + s.to_bytes(32, "little")168169170def hx(case, key):171 return bytes.fromhex(case[key])172173174def versions(case):175 import importlib.metadata as md176 out = {"python": sys.version.split()[0], "bigint": "RFC 8032 transcription (this file)"}177 for name in ("pynacl", "cryptography", "solders", "bip-utils"):178 try:179 out[name] = md.version(name)180 except Exception:181 pass182 try:183 import nacl.bindings184 out["libsodium"] = nacl.bindings.sodium_version_string().decode() if hasattr(nacl.bindings, "sodium_version_string") else "bundled"185 except Exception:186 pass187 try:188 from cryptography.hazmat.backends.openssl import backend189 out["openssl"] = backend.openssl_version_text()190 except Exception:191 pass192 return out193194195def op_keys(case):196 """seed -> public key by every reference."""197 seed = hx(case, "seed")198 from nacl.signing import SigningKey199 from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey200 from cryptography.hazmat.primitives import serialization201 from solders.keypair import Keypair202 a, _ = expand(seed)203 return {204 "bigint": pt_encode(pt_mul(a, BASE)).hex(),205 "pynacl": bytes(SigningKey(seed).verify_key).hex(),206 "cryptography": Ed25519PrivateKey.from_private_bytes(seed).public_key().public_bytes(207 serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex(),208 "solders": bytes(Keypair.from_seed(seed).pubkey()).hex(),209 }210211212def op_sign(case):213 seed, m = hx(case, "seed"), hx(case, "message")214 from nacl.signing import SigningKey215 from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey216 from solders.keypair import Keypair217 return {218 "bigint": ref_sign(seed, m)[1].hex(),219 "pynacl": SigningKey(seed).sign(m).signature.hex(),220 "cryptography": Ed25519PrivateKey.from_private_bytes(seed).sign(m).hex(),221 "solders": bytes(Keypair.from_seed(seed).sign_message(m)).hex(),222 }223224225def classify(pk, m, sig):226 """Structure of a verification input according to the integer reference: which rule of the strict policy227 applies, and the two verification equations."""228 out = {"s_canonical": False, "a_canonical": False, "a_decodes_lenient": False, "a_small_order": None, "a_torsion": None,229 "r_canonical": False, "r_decodes_lenient": False, "r_small_order": None, "r_torsion": None,230 "cofactorless": False, "cofactored": False}231 if len(pk) != 32 or len(sig) != 64:232 return out233 rb, s = sig[:32], int.from_bytes(sig[32:], "little")234 out["s_canonical"] = s < L235 a_strict, a_len = pt_decode(pk, True), pt_decode(pk, False)236 r_strict, r_len = pt_decode(rb, True), pt_decode(rb, False)237 out["a_canonical"], out["a_decodes_lenient"] = a_strict is not None, a_len is not None238 out["r_canonical"], out["r_decodes_lenient"] = r_strict is not None, r_len is not None239 if a_len is not None:240 out["a_small_order"], out["a_torsion"] = is_small_order(a_len), has_torsion(a_len)241 if r_len is not None:242 out["r_small_order"], out["r_torsion"] = is_small_order(r_len), has_torsion(r_len)243 if a_len is not None and r_len is not None:244 k = challenge(rb, pk, m)245 left = pt_mul(s, BASE)246 right = pt_add(r_len, pt_mul(k, a_len))247 out["cofactorless"] = pt_equal(left, right)248 out["cofactored"] = pt_equal(pt_mul(8, left), pt_mul(8, right))249 return out250251252def strict_policy(c):253 """The documented policy of the engine, evaluated by the integer reference."""254 return bool(c["s_canonical"] and c["a_canonical"] and c["a_small_order"] is False and c["r_canonical"]255 and c["r_small_order"] is False and c["cofactorless"])256257258def op_verify(case):259 pk, m, sig = hx(case, "public_key"), hx(case, "message"), hx(case, "signature")260 out = {}261 c = classify(pk, m, sig)262 out["class"] = c263 out["bigint_strict"] = strict_policy(c)264 try:265 from nacl.signing import VerifyKey266 try:267 VerifyKey(pk).verify(m, sig)268 out["pynacl"] = True269 except Exception:270 out["pynacl"] = False271 except ImportError:272 pass273 try:274 from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey275 try:276 Ed25519PublicKey.from_public_bytes(pk).verify(sig, m)277 out["cryptography"] = True278 except Exception:279 out["cryptography"] = False280 except ImportError:281 pass282 try:283 from solders.pubkey import Pubkey284 from solders.signature import Signature285 if len(pk) != 32 or len(sig) != 64:286 out["solders"] = False # the Rust types are fixed-size arrays: other lengths cannot be expressed287 else:288 try:289 out["solders"] = bool(Signature.from_bytes(sig).verify(Pubkey.from_bytes(pk), m))290 except BaseException: # pyo3 PanicException derives from BaseException291 out["solders"] = False292 except ImportError:293 pass294 return out295296297def limbs_value(limbs):298 return sum(int(v) << (51 * i) for i, v in enumerate(limbs))299300301def op_field(case):302 """Field arithmetic on values given as five 51-bit-radix limbs (decimal strings; any limb below 2^63)."""303 a, b = limbs_value(case["a"]) , limbs_value(case["b"])304 le = lambda v: (v % P).to_bytes(32, "little").hex()305 u, v = a % P, b % P306 # sqrt(u/v): RFC 8032 5.1.3 on the ratio; "square" false when u/v is not a square (v = 0: square iff u = 0)307 if v == 0:308 is_square, root = (u == 0), 0309 else:310 ratio = u * inv(v) % P311 cand = pow(ratio, (P + 3) // 8, P)312 if (cand * cand - ratio) % P != 0:313 cand = cand * SQRT_M1 % P314 is_square = (cand * cand - ratio) % P == 0315 root = cand if cand % 2 == 0 else P - cand # the non-negative (even) root316 return {317 "a": le(a), "add": le(a + b), "sub": le(a - b), "mul": le(a * b), "square": le(a * a), "neg": le(-a),318 "invert": le(pow(a % P, P - 2, P)), "pow22523": le(pow(a % P, (P - 5) // 8, P)),319 "is_zero": a % P == 0, "is_negative": (a % P) & 1 == 1, "equal": (a - b) % P == 0,320 "sqrt_is_square": is_square, "sqrt_root": le(root) if is_square else "",321 }322323324def op_field_bytes(case):325 """fromBytes on 32 arbitrary bytes: the 255 low bits modulo p."""326 v = int.from_bytes(hx(case, "bytes"), "little") & ((1 << 255) - 1)327 return {"canonical": (v % P).to_bytes(32, "little").hex(), "is_canonical": v < P}328329330def op_scalar(case):331 a = int.from_bytes(hx(case, "a"), "little")332 b = int.from_bytes(hx(case, "b"), "little")333 c = int.from_bytes(hx(case, "c"), "little")334 wide = int.from_bytes(hx(case, "wide"), "little")335 le = lambda v: (v % L).to_bytes(32, "little").hex()336 return {"reduce": le(a), "reduce_wide": le(wide), "mul_add": le((a % L) * b + (c % L)), "add": le((a % L) + (c % L)),337 "mont_mul": le((a % L) * b * pow(2**256, L - 2, L)), "is_canonical": a < L}338339340def op_point(case):341 """Group operations on encoded points (decoded leniently) and scalars (any 256-bit integer)."""342 out = {}343 pb, qb = hx(case, "p"), hx(case, "q")344 s = int.from_bytes(hx(case, "scalar"), "little")345 out["base_mul"] = pt_encode(pt_mul(s, BASE)).hex()346 p, q = pt_decode(pb, False), pt_decode(qb, False)347 out["p_strict"] = pt_decode(pb, True) is not None348 out["p_lenient"] = p is not None349 if p is not None:350 out["p_encoded"] = pt_encode(p).hex()351 out["p_small_order"] = is_small_order(p)352 out["mul"] = pt_encode(pt_mul(s, p)).hex()353 out["double"] = pt_encode(pt_add(p, p)).hex()354 out["neg"] = pt_encode((P - p[0], p[1], p[2], P - p[3])).hex()355 if q is not None:356 out["add"] = pt_encode(pt_add(p, q)).hex()357 try:358 from solders.pubkey import Pubkey359 out["solders_on_curve"] = bool(Pubkey.from_bytes(pb).is_on_curve())360 except Exception:361 pass362 try:363 import nacl.bindings as nb364 out["sodium_valid_point"] = bool(nb.crypto_core_ed25519_is_valid_point(pb))365 try:366 out["sodium_base_mul"] = nb.crypto_scalarmult_ed25519_base_noclamp(s.to_bytes(32, "little")).hex()367 except Exception:368 out["sodium_base_mul"] = ""369 except Exception:370 pass371 return out372373374def slip10_ref(seed, path):375 i = hmac.new(b"ed25519 seed", seed, hashlib.sha512).digest()376 k, c = i[:32], i[32:]377 for index in path:378 i = hmac.new(c, b"\x00" + k + (index | 0x80000000).to_bytes(4, "big"), hashlib.sha512).digest()379 k, c = i[:32], i[32:]380 return k, c381382383def op_slip10(case):384 seed, path = hx(case, "seed"), [int(x) for x in case["path"]]385 k, c = slip10_ref(seed, path)386 a, _ = expand(k)387 out = {"hmac_private": k.hex(), "hmac_chain_code": c.hex(), "hmac_public": pt_encode(pt_mul(a, BASE)).hex()}388 try:389 from bip_utils import Bip32Slip10Ed25519390 node = Bip32Slip10Ed25519.FromSeed(seed)391 for index in path:392 node = node.ChildKey(index | 0x80000000)393 out["biputils_private"] = node.PrivateKey().Raw().ToHex()394 out["biputils_chain_code"] = node.ChainCode().ToHex()395 out["biputils_public"] = node.PublicKey().RawCompressed().ToHex()[2:]396 except Exception as e: # bip-utils refuses seeds shorter than 16 bytes, like the engine397 out["biputils_error"] = str(e)[:200]398 return out399400401OPS = {"versions": versions, "keys": op_keys, "sign": op_sign, "verify": op_verify, "field": op_field,402 "field_bytes": op_field_bytes, "scalar": op_scalar, "point": op_point, "slip10": op_slip10}403404405def main():406 op = OPS[sys.argv[1]]407 out = []408 for case in json.load(sys.stdin):409 try:410 out.append(op(case))411 except Exception as e:412 out.append({"error": f"{type(e).__name__}: {e}"[:300]})413 json.dump(out, sys.stdout)414415416if __name__ == "__main__":417 main()418