SPB Git

Repository Public

solana.py 15.6 KB 353 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : QYVORA7# File             : security/tests/oracles/mc/solana.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"""Solana reference for the QYVORA multi-chain audit (test environment only).4243Protocol (see README.md): `python3 -I solana.py <operation>` reads a JSON array of cases on standard input and44writes a JSON array of the same length. A case the reference rejects answers {"error": "..."}.4546References: solders (Rust solana-sdk types, ed25519-dalek) for keys, program-derived addresses, messages,47transactions and signatures; PyNaCl (libsodium) as a second Ed25519 signer; base58 for a second base58 codec;48bip-utils for the SLIP-0010 derivation of the account. The SPL Token, Associated Token Account and Memo49instructions are written here from the programs' published layouts (solders does not ship them).50"""5152import json53import sys54from importlib import metadata5556import base5857from nacl.signing import SigningKey58from solders.compute_budget import set_compute_unit_limit, set_compute_unit_price59from solders.hash import Hash60from solders.instruction import AccountMeta, Instruction61from solders.keypair import Keypair62from solders.message import Message, MessageV0, from_bytes_versioned, to_bytes_versioned63from solders.pubkey import Pubkey64from solders.system_program import TransferParams, transfer65from solders.transaction import Transaction, VersionedTransaction6667SYSTEM = Pubkey.from_string("11111111111111111111111111111111")68TOKEN = Pubkey.from_string("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")69TOKEN_2022 = Pubkey.from_string("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb")70ATA = Pubkey.from_string("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL")71MEMO = Pubkey.from_string("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr")727374def h(b):75    return bytes(b).hex()767778def pk(hexstr):79    return Pubkey.from_bytes(bytes.fromhex(hexstr))808182def token_program(name):83    return TOKEN_2022 if name == "token2022" else TOKEN848586def ata_of(owner, mint, program):87    return Pubkey.find_program_address([bytes(owner), bytes(program), bytes(mint)], ATA)888990def op_versions(_case):91    out = {}92    for name in ("solders", "base58", "pynacl", "bip-utils"):93        try:94            out[name] = metadata.version(name)95        except metadata.PackageNotFoundError:96            pass97    return out9899100def op_address(case):101    """bytes (hex, 32) -> base58 by two codecs and is_on_curve; or text -> bytes when solders accepts the text."""102    if "bytes" in case:103        raw = bytes.fromhex(case["bytes"])104        key = Pubkey.from_bytes(raw)105        return {"base58": str(key), "base58_alt": base58.b58encode(raw).decode(), "on_curve": key.is_on_curve()}106    key = Pubkey.from_string(case["text"])107    return {"bytes": h(bytes(key)), "on_curve": key.is_on_curve()}108109110def op_pda(case):111    seeds = [bytes.fromhex(s) for s in case["seeds"]]112    program = pk(case["program"])113    if case.get("create"):114        return {"address": h(bytes(Pubkey.create_program_address(seeds, program)))}115    address, bump = Pubkey.find_program_address(seeds, program)116    return {"address": h(bytes(address)), "bump": bump}117118119def op_ata(case):120    """Associated token account: by find_program_address, and by solders' own helper (a second derivation)."""121    from solders.token.associated import get_associated_token_address122123    program = token_program(case.get("program", "token"))124    address, bump = ata_of(pk(case["owner"]), pk(case["mint"]), program)125    helper = get_associated_token_address(pk(case["owner"]), pk(case["mint"]), program)126    return {"address": h(bytes(address)), "bump": bump, "helper": h(bytes(helper)), "base58": str(address)}127128129def op_constants(_case):130    """Program and sysvar addresses as solders (solana-sdk) publishes them."""131    import solders.address_lookup_table_account as alt132    import solders.compute_budget as compute_budget133    import solders.system_program as system_program134    import solders.sysvar as sysvar135    import solders.token as token136137    return {"system": str(system_program.ID), "computeBudget": str(compute_budget.ID), "token": str(token.ID),138            "addressLookupTable": str(alt.ID), "sysvarRent": str(sysvar.RENT), "sysvarClock": str(sysvar.CLOCK),139            "sysvarRecentBlockhashes": str(sysvar.RECENT_BLOCKHASHES), "sysvarInstructions": str(sysvar.INSTRUCTIONS)}140141142def build_instructions(case, payer):143    """The instruction list of a QYVORA payment, rebuilt independently: compute-unit limit, compute-unit price,144    [create the recipient's associated token account], System transfer or TransferChecked, [memo]."""145    recipient = pk(case["recipient"])146    out = [set_compute_unit_limit(int(case["unit_limit"])), set_compute_unit_price(int(case["unit_price"]))]147    if case.get("mint"):148        mint = pk(case["mint"])149        program = token_program(case.get("program", "token"))150        source, _ = ata_of(payer, mint, program)151        destination, _ = ata_of(recipient, mint, program)152        if case.get("create_ata"):153            # Associated Token Account program, instruction 1 (CreateIdempotent)154            out.append(Instruction(ATA, bytes([1]), [155                AccountMeta(payer, True, True), AccountMeta(destination, False, True), AccountMeta(recipient, False, False),156                AccountMeta(mint, False, False), AccountMeta(SYSTEM, False, False), AccountMeta(program, False, False)]))157        # SPL Token instruction 12 (TransferChecked): u8 tag, u64 amount (little endian), u8 decimals158        data = bytes([12]) + int(case["amount"]).to_bytes(8, "little") + bytes([int(case["decimals"])])159        out.append(Instruction(program, data, [160            AccountMeta(source, False, True), AccountMeta(mint, False, False), AccountMeta(destination, False, True),161            AccountMeta(payer, True, False)]))162    else:163        out.append(transfer(TransferParams(from_pubkey=payer, to_pubkey=recipient, lamports=int(case["amount"]))))164    if case.get("memo") is not None:165        out.append(Instruction(MEMO, case["memo"].encode("utf-8"), [AccountMeta(payer, True, False)]))166    return out167168169def op_payment(case):170    """A payment as the wallet builds it: message bytes, unsigned and signed transaction, signature (two signers)."""171    seed = bytes.fromhex(case["seed"])172    keypair = Keypair.from_seed(seed)173    payer = keypair.pubkey()174    blockhash = Hash.from_bytes(bytes.fromhex(case["blockhash"]))175    message = Message.new_with_blockhash(build_instructions(case, payer), payer, blockhash)176    signed = Transaction([keypair], message, blockhash)177    signature = bytes(signed.signatures[0])178    sodium = SigningKey(seed).sign(bytes(message)).signature179    return {"payer": h(bytes(payer)), "message": h(bytes(message)), "unsigned": h(bytes(Transaction.new_unsigned(message))),180            "signed": h(bytes(signed)), "signature": h(signature), "signature_b58": str(signed.signatures[0]),181            "signature_libsodium": h(sodium)}182183184def op_compile(case):185    """Generic legacy message: payer, instructions [{program, accounts: [[key, signer, writable]], data}], blockhash,186    optional signer seeds (in any order) -> message, transaction."""187    payer = pk(case["payer"])188    instructions = [Instruction(pk(i["program"]), bytes.fromhex(i["data"]), [AccountMeta(pk(a[0]), bool(a[1]), bool(a[2])) for a in i["accounts"]])189                    for i in case["instructions"]]190    blockhash = Hash.from_bytes(bytes.fromhex(case["blockhash"]))191    message = Message.new_with_blockhash(instructions, payer, blockhash)192    out = {"message": h(bytes(message)), "keys": [h(bytes(k)) for k in message.account_keys],193           "header": [message.header.num_required_signatures, message.header.num_readonly_signed_accounts, message.header.num_readonly_unsigned_accounts]}194    if "seeds" in case:195        signers = required_signers(message, case["seeds"])196        if signers is not None:197            out["signed"] = h(bytes(Transaction(signers, message, blockhash)))198    return out199200201def required_signers(message, seeds):202    """The key pairs of `seeds` that are required signers of the message (solders refuses any other); None when a203    required signer has no seed."""204    required = [bytes(k) for k in message.account_keys[: message.header.num_required_signatures]]205    pairs = {bytes(kp.pubkey()): kp for kp in (Keypair.from_seed(bytes.fromhex(s)) for s in seeds)}206    if any(k not in pairs for k in required):207        return None208    return [pairs[k] for k in required]209210211def sanitize_verdict(message):212    """What solana-sdk's `sanitize` says about a decoded message (through a transaction with empty signatures):213    "" when it passes, the error otherwise. bincode decoding alone checks no structural rule."""214    from solders.signature import Signature215216    try:217        count = message.header.num_required_signatures218        VersionedTransaction.populate(message, [Signature.default()] * count).sanitize()219        return ""220    except BaseException as e:  # noqa: BLE001221        return f"{type(e).__name__}: {str(e)[:80]}"222223224def message_fields(message, version):225    out = {226        "version": version,227        "header": [message.header.num_required_signatures, message.header.num_readonly_signed_accounts, message.header.num_readonly_unsigned_accounts],228        "keys": [h(bytes(k)) for k in message.account_keys], "blockhash": h(bytes(message.recent_blockhash)),229        "instructions": [[i.program_id_index, h(bytes(i.accounts)), h(bytes(i.data))] for i in message.instructions],230        "lookups": [],231    }232    if version == "v0":233        out["lookups"] = [[h(bytes(l.account_key)), h(bytes(l.writable_indexes)), h(bytes(l.readonly_indexes))] for l in message.address_table_lookups]234    return out235236237def op_decode_message(case):238    """What solders reads in message bytes; "canonical" says whether it serializes back to the same bytes, and239    "sanitize" what Message::sanitize says (solders decodes with bincode, which is laxer than a validator)."""240    raw = bytes.fromhex(case["bytes"])241    if raw and raw[0] & 0x80:242        message = from_bytes_versioned(raw)243        version = "v0" if isinstance(message, MessageV0) else "legacy"244        again = to_bytes_versioned(message)245    else:246        message = Message.from_bytes(raw)247        version = "legacy"248        again = bytes(message)249    out = message_fields(message, version)250    out["canonical"] = again == raw251    out["sanitize"] = sanitize_verdict(message)252    return out253254255def op_decode_transaction(case):256    raw = bytes.fromhex(case["bytes"])257    tx = VersionedTransaction.from_bytes(raw)258    message = tx.message259    version = "v0" if isinstance(message, MessageV0) else "legacy"260    out = message_fields(message, version)261    out["signatures"] = [h(bytes(s)) for s in tx.signatures]262    out["canonical"] = bytes(tx) == raw263    try:264        tx.sanitize()265        out["sanitize"] = ""266    except BaseException as e:  # noqa: BLE001267        out["sanitize"] = f"{type(e).__name__}: {str(e)[:80]}"268    try:269        out["verifies"] = bool(tx.verify_with_results()) and all(tx.verify_with_results())270    except BaseException as e:  # noqa: BLE001271        out["verifies"] = False272    return out273274275def op_v0(case):276    """A version-0 message with static keys only or with lookups, compiled by solders."""277    from solders.address_lookup_table_account import AddressLookupTableAccount278279    payer = pk(case["payer"])280    instructions = [Instruction(pk(i["program"]), bytes.fromhex(i["data"]), [AccountMeta(pk(a[0]), bool(a[1]), bool(a[2])) for a in i["accounts"]])281                    for i in case["instructions"]]282    tables = [AddressLookupTableAccount(pk(t["key"]), [pk(a) for a in t["addresses"]]) for t in case.get("tables", [])]283    message = MessageV0.try_compile(payer, instructions, tables, Hash.from_bytes(bytes.fromhex(case["blockhash"])))284    out = message_fields(message, "v0")285    out["message"] = h(to_bytes_versioned(message))286    if "seeds" in case:287        signers = required_signers(message, case["seeds"])288        if signers is not None:289            out["signed"] = h(bytes(VersionedTransaction(message, signers)))290    return out291292293def op_sign(case):294    seed = bytes.fromhex(case["seed"])295    message = bytes.fromhex(case["message"])296    keypair = Keypair.from_seed(seed)297    return {"public": h(bytes(keypair.pubkey())), "signature": h(bytes(keypair.sign_message(message))),298            "signature_libsodium": h(SigningKey(seed).sign(message).signature)}299300301def op_derive(case):302    """Address of an account from a BIP-39 seed: SLIP-0010 Ed25519 at m/44'/501'/account'/0' (bip-utils)."""303    from bip_utils import Bip44, Bip44Changes, Bip44Coins304305    node = Bip44.FromSeed(bytes.fromhex(case["seed"]), Bip44Coins.SOLANA).Purpose().Coin().Account(int(case.get("account", 0)))306    style = case.get("style", "bip44Change")307    if style == "bip44Change":308        node = node.Change(Bip44Changes.CHAIN_EXT)309    private = node.PrivateKey().Raw().ToBytes()310    return {"private": h(private), "address": str(Keypair.from_seed(private).pubkey())}311312313def op_derive_path(case):314    """Generic SLIP-0010 Ed25519 derivation along hardened indexes (for the m/44'/501' style)."""315    from bip_utils import Bip32Slip10Ed25519316317    node = Bip32Slip10Ed25519.FromSeed(bytes.fromhex(case["seed"]))318    for index in case["path"]:319        node = node.ChildKey(int(index) | 0x80000000)320    private = node.PrivateKey().Raw().ToBytes()321    return {"private": h(private), "address": str(Keypair.from_seed(private).pubkey())}322323324def op_compact(case):325    """solders' own short-vec through a message: the encoded length of `n` instruction-data bytes."""326    n = int(case["n"])327    payer = Pubkey.from_bytes(bytes([1]) * 32)328    message = Message.new_with_blockhash([Instruction(SYSTEM, bytes(n), [])], payer, Hash.from_bytes(bytes(32)))329    raw = bytes(message)330    # header(3) + 1 + 2 keys (64) + blockhash (32) + 1 (instruction count) + program index (1) + account count (1)331    start = 3 + 1 + 64 + 32 + 1 + 1 + 1332    return {"prefix": h(raw[start:len(raw) - n])}333334335OPS = {name[3:]: fn for name, fn in globals().items() if name.startswith("op_")}336337338def main():339    op = sys.argv[1]340    cases = json.load(sys.stdin)341    fn = OPS[op]342    out = []343    for case in cases:344        try:345            out.append(fn(case))346        except BaseException as e:  # noqa: BLE001 - pyo3 panics are not Exception subclasses347            out.append({"error": f"{type(e).__name__}: {str(e)[:200]}"})348    json.dump(out, sys.stdout)349350351if __name__ == "__main__":352    main()353
Files main
Menu

Theme