SPB Git

Repository Public

tron.py 15.6 KB 388 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : QYVORA7# File             : security/tests/oracles/mc/tron.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"""TRON reference for the QYVORA multi-chain audit (test environment only).4243Protocol (see README.md): `python3 -I tron.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, and how independent each one is from the Swift engine:47- addresses: tronpy (`PrivateKey(...).public_key.to_base58check_address()`: OpenSSL through `cryptography` for the48  point, pycryptodome Keccak-256, the `base58` package) and, separately, coincurve (libsecp256k1) for the public key;49- `Transaction.raw` bytes: Google's protobuf runtime (upb) driven by the descriptors tronpy ships, generated from50  the protocol's own `tron.proto`; and a second encoder written here by hand from the field numbers of51  https://github.com/tronprotocol/protocol (core/Tron.proto, core/contract/*.proto). The two must agree with each52  other before either is compared with the engine;53- decoding: the same protobuf runtime (parse, re-serialise, unknown-field sets), which is deliberately more54  permissive than the engine: the Swift test states the policy differences one by one;55- signatures: coincurve (libsecp256k1, RFC 6979, low s) and tronpy's own signer (OpenSSL DER + its recovery code);56- TRC-20 call data: eth-abi;57- derivation: bip-utils (BIP-32/BIP-44, coin type 195).58"""5960import hashlib61import json62import sys63from importlib import metadata6465import base5866import coincurve67from Crypto.Hash import keccak68from google.protobuf import any_pb2, unknown_fields69from tronpy import keys as tk70from tronpy.proto import tron_pb27172N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD036414173TRANSFER_URL = "type.googleapis.com/protocol.TransferContract"74TRIGGER_URL = "type.googleapis.com/protocol.TriggerSmartContract"757677def versions(_case):78    out = {}79    for name in ("tronpy", "coincurve", "base58", "pycryptodome", "protobuf", "eth-abi", "bip-utils", "cryptography"):80        try:81            out[name] = metadata.version(name)82        except metadata.PackageNotFoundError:83            pass84    return out858687def keccak256(data):88    return keccak.new(digest_bits=256, data=data).digest()899091# ---------------------------------------------------------------- addresses9293def address(case):94    sk = bytes.fromhex(case["sk"])95    key = tk.PrivateKey(sk)96    pub = coincurve.PublicKey.from_valid_secret(sk).format(compressed=False)97    raw = b"\x41" + keccak256(pub[1:])[-20:]98    return {99        "base58": key.public_key.to_base58check_address(),100        "hex": key.public_key.to_hex_address(),101        "base58_coincurve": base58.b58encode_check(raw).decode(),102        "hex_coincurve": raw.hex(),103        "public": pub.hex(),104    }105106107def parse(case):108    text = case["text"]109    out = {"strict": None, "tronpy": None, "tronpy_is_base58": False, "tronpy_is_hex": False}110    # the strict rule, written independently: 34 characters, "T", Base58Check, 21 bytes, prefix 0x41111    try:112        if len(text) == 34 and text[0] == "T" and all(c in base58.BITCOIN_ALPHABET.decode() for c in text):113            raw = base58.b58decode_check(text)114            if len(raw) == 21 and raw[0] == 0x41:115                out["strict"] = raw.hex()116    except Exception:117        pass118    # what tronpy accepts, for the record of the policy differences119    try:120        out["tronpy"] = tk.to_raw_address(text).hex()121    except Exception:122        pass123    try:124        out["tronpy_is_base58"] = bool(tk.is_base58check_address(text))125    except Exception:126        pass127    try:128        out["tronpy_is_hex"] = bool(tk.is_hex_address(text))129    except Exception:130        pass131    return out132133134def derive(case):135    from bip_utils import Bip44, Bip44Changes, Bip44Coins136137    seed = bytes.fromhex(case["seed"])138    node = Bip44.FromSeed(seed, Bip44Coins.TRON).Purpose().Coin().Account(0).Change(Bip44Changes.CHAIN_EXT).AddressIndex(int(case.get("index", 0)))139    return {"address": node.PublicKey().ToAddress(), "private": node.PrivateKey().Raw().ToHex()}140141142# ---------------------------------------------------------------- hand-written protobuf encoder143144def varint(v):145    out = bytearray()146    while v >= 0x80:147        out.append((v & 0x7F) | 0x80)148        v >>= 7149    out.append(v)150    return bytes(out)151152153def f_varint(field, v):154    return b"" if v == 0 else varint(field << 3) + varint(v)155156157def f_bytes(field, b, always=False):158    return b"" if (not b and not always) else varint(field << 3 | 2) + varint(len(b)) + b159160161def trc20_data(to21, amount):162    from eth_abi import encode163164    return bytes.fromhex("a9059cbb") + encode(["address", "uint256"], ["0x" + to21[1:].hex(), amount])165166167def contract_of(case):168    """(type number, type URL, inner message as a protobuf object, inner message by hand)"""169    owner = bytes.fromhex(case["owner"])170    kind = case["kind"]171    if kind == "trx":172        to = bytes.fromhex(case["to"])173        amount = int(case["amount"])174        pb = tron_pb2.TransferContract(owner_address=owner, to_address=to, amount=amount)175        hand = f_bytes(1, owner) + f_bytes(2, to) + f_varint(3, amount)176        return 1, TRANSFER_URL, pb, hand177    contract = bytes.fromhex(case["contract"])178    if kind == "trc20":179        data = trc20_data(bytes.fromhex(case["to"]), int(case["amount"]))180        value = token_value = token_id = 0181    else:182        data = bytes.fromhex(case["data"])183        value, token_value, token_id = int(case.get("call_value", 0)), int(case.get("token_value", 0)), int(case.get("token_id", 0))184    pb = tron_pb2.TriggerSmartContract(owner_address=owner, contract_address=contract, call_value=value, data=data,185                                       call_token_value=token_value, token_id=token_id)186    hand = f_bytes(1, owner) + f_bytes(2, contract) + f_varint(3, value) + f_bytes(4, data) + f_varint(5, token_value) + f_varint(6, token_id)187    return 31, TRIGGER_URL, pb, hand188189190def raw(case):191    ctype, url, inner_pb, inner_hand = contract_of(case)192    ref_bytes, ref_hash = bytes.fromhex(case["ref_bytes"]), bytes.fromhex(case["ref_hash"])193    expiration, timestamp, fee_limit = int(case["expiration"]), int(case["timestamp"]), int(case.get("fee_limit", 0))194    memo, permission = bytes.fromhex(case.get("memo", "")), int(case.get("permission", 0))195196    contract = tron_pb2.Transaction.Contract(type=ctype, parameter=any_pb2.Any(type_url=url, value=inner_pb.SerializeToString()), Permission_id=permission)197    message = tron_pb2.Transaction.raw(ref_block_bytes=ref_bytes, ref_block_hash=ref_hash, expiration=expiration, timestamp=timestamp,198                                       contract=[contract], fee_limit=fee_limit, data=memo)199    reference = message.SerializeToString(deterministic=True)200201    any_hand = f_bytes(1, url.encode()) + f_bytes(2, inner_hand)202    contract_hand = f_varint(1, ctype) + f_bytes(2, any_hand, always=True) + f_varint(5, permission)203    hand = (f_bytes(1, ref_bytes) + f_bytes(4, ref_hash) + f_varint(8, expiration) + f_bytes(10, memo)204            + f_bytes(11, contract_hand, always=True) + f_varint(14, timestamp) + f_varint(18, fee_limit))205    if hand != reference:206        return {"error": "the two reference encoders disagree", "protobuf": reference.hex(), "hand": hand.hex()}207208    txid = hashlib.sha256(reference).digest()209    out = {"raw": reference.hex(), "txid": txid.hex(), "data": (inner_pb.data.hex() if ctype == 31 else "")}210    if case.get("sk"):211        sk = bytes.fromhex(case["sk"])212        # libsecp256k1: r ‖ s ‖ recovery id (0 or 1), deterministic nonce, low s213        sig = coincurve.PrivateKey(sk).sign_recoverable(txid, hasher=None)214        out["sig"] = sig.hex()215        # tronpy's own signer (OpenSSL): same r and s expected, v normalised to 0 or 1216        tsig = tk.PrivateKey(sk).sign_msg_hash(txid)217        out["sig_tronpy"] = tsig.to_bytes().hex()218        out["signer"] = tsig.recover_public_key_from_msg_hash(txid).to_base58check_address()219        # the broadcast form with v = 27 + recovery id, as TronWeb writes it220        signed = tron_pb2.Transaction(raw_data=message, signature=[sig[:64] + bytes([27 + sig[64]])])221        out["signed"] = signed.SerializeToString(deterministic=True).hex()222    return out223224225# ---------------------------------------------------------------- decoding with the protobuf runtime226227def _unknown(message):228    return len(unknown_fields.UnknownFieldSet(message))229230231def _canonical(message, data):232    return message.SerializeToString(deterministic=True) == data233234235def _decode_raw(data):236    """Facts about a Transaction.raw as Google's runtime reads it. The engine is stricter: the test applies its policy."""237    message = tron_pb2.Transaction.raw()238    try:239        message.ParseFromString(data)240    except Exception as e:241        return {"parse": False, "why": type(e).__name__}242    out = {243        "parse": True,244        "canonical": _canonical(message, data),245        "unknown": _unknown(message),246        "ref_bytes": message.ref_block_bytes.hex(),247        "ref_hash": message.ref_block_hash.hex(),248        "ref_block_num": str(message.ref_block_num),249        "expiration": str(message.expiration),250        "timestamp": str(message.timestamp),251        "fee_limit": str(message.fee_limit),252        "memo": message.data.hex(),253        "auths": len(message.auths),254        "scripts": message.scripts.hex(),255        "contracts": len(message.contract),256    }257    if len(message.contract) >= 1:258        c = message.contract[0]259        out.update({260            "type": int(c.type), "url": c.parameter.type_url.encode().hex(), "value": c.parameter.value.hex(), "permission": str(c.Permission_id),261            "provider": c.provider.hex(), "name": c.ContractName.hex(), "has_parameter": c.HasField("parameter"),262            "unknown_contract": _unknown(c), "unknown_any": _unknown(c.parameter) if c.HasField("parameter") else 0,263        })264        inner = None265        if c.type == 1:266            inner = tron_pb2.TransferContract()267        elif c.type == 31:268            inner = tron_pb2.TriggerSmartContract()269        if inner is not None:270            try:271                inner.ParseFromString(c.parameter.value)272                facts = {"parse": True, "canonical": _canonical(inner, c.parameter.value), "unknown": _unknown(inner), "owner": inner.owner_address.hex()}273                if c.type == 1:274                    facts.update({"to": inner.to_address.hex(), "amount": str(inner.amount)})275                else:276                    facts.update({"contract": inner.contract_address.hex(), "call_value": str(inner.call_value), "data": inner.data.hex(),277                                  "token_value": str(inner.call_token_value), "token_id": str(inner.token_id)})278                out["inner"] = facts279            except Exception as e:280                out["inner"] = {"parse": False, "why": type(e).__name__}281    return out282283284def decode(case):285    data = bytes.fromhex(case["raw"])286    out = _decode_raw(data)287    out["txid"] = hashlib.sha256(data).hexdigest()288    return out289290291def _recover(txid, sig):292    """Address a 65-byte r ‖ s ‖ v signature recovers to with libsecp256k1 (v in 0, 1, 27, 28), or None."""293    if len(sig) != 65:294        return None295    v = sig[64] - 27 if sig[64] >= 27 else sig[64]296    if v not in (0, 1):297        return None298    r, s = int.from_bytes(sig[:32], "big"), int.from_bytes(sig[32:64], "big")299    if not (0 < r < N and 0 < s < N):300        return None301    try:302        pub = coincurve.PublicKey.from_signature_and_message(sig[:64] + bytes([v]), txid, hasher=None).format(compressed=False)303    except Exception:304        return None305    return base58.b58encode_check(b"\x41" + keccak256(pub[1:])[-20:]).decode()306307308def recover(case):309    txid, sig = bytes.fromhex(case["txid"]), bytes.fromhex(case["sig"])310    out = {"address": _recover(txid, sig), "tronpy": None}311    try:312        out["tronpy"] = tk.Signature(sig).recover_public_key_from_msg_hash(txid).to_base58check_address()313    except Exception:314        pass315    return out316317318def signed(case):319    data = bytes.fromhex(case["hex"])320    message = tron_pb2.Transaction()321    try:322        message.ParseFromString(data)323    except Exception as e:324        return {"parse": False, "why": type(e).__name__}325    raw_bytes = message.raw_data.SerializeToString(deterministic=True)326    txid = hashlib.sha256(raw_bytes).digest()327    return {328        "parse": True, "canonical": _canonical(message, data), "unknown": _unknown(message), "has_raw": message.HasField("raw_data"),329        "raw": raw_bytes.hex(), "txid": txid.hex(),330        "signatures": [s.hex() for s in message.signature], "signers": [_recover(txid, bytes(s)) for s in message.signature],331        "raw_facts": _decode_raw(raw_bytes),332    }333334335# ---------------------------------------------------------------- TRC-20 ABI336337def abi_transfer(case):338    out = {"data": trc20_data(bytes.fromhex(case["to"]), int(case["amount"])).hex()}339    return out340341342def abi_decode(case):343    """Strict decoding of `transfer(address,uint256)` / `approve(address,uint256)` call data with eth-abi."""344    from eth_abi import decode345346    data = bytes.fromhex(case["data"])347    names = {"a9059cbb": "transfer", "095ea7b3": "approve"}348    if len(data) != 68 or data[:4].hex() not in names:349        return {"call": None}350    try:351        who, amount = decode(["address", "uint256"], data[4:], strict=True)352    except Exception:353        return {"call": None}354    return {"call": names[data[:4].hex()], "address": who.lower(), "amount": str(amount)}355356357def abi_uint(case):358    from eth_abi import decode359360    data = bytes.fromhex(case["data"])361    try:362        (v,) = decode(["uint256"], data, strict=True)363        return {"value": str(v)}364    except Exception:365        return {"value": None}366367368OPERATIONS = {369    "versions": versions, "address": address, "parse": parse, "derive": derive, "raw": raw, "decode": decode,370    "recover": recover, "signed": signed, "abi_transfer": abi_transfer, "abi_decode": abi_decode, "abi_uint": abi_uint,371}372373374def main():375    op = OPERATIONS[sys.argv[1]]376    cases = json.load(sys.stdin)377    out = []378    for case in cases:379        try:380            out.append(op(case))381        except Exception as e:  # a case the reference rejects382            out.append({"error": f"{type(e).__name__}: {e}"})383    json.dump(out, sys.stdout)384385386if __name__ == "__main__":387    main()388
Files main
Menu

Theme