// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

/// @notice The KAT-proven, pure-Solidity Falcon-512 verifier used to back the shim.
interface IFalcon512Ref {
    function verifySignedMessage(bytes memory pk, bytes memory sm) external pure returns (bool);
}

/**
 * @title Falcon512PrecompileShim, TEST-ONLY faithful stand-in for the LIVE Falcon-512 precompile
 *
 * @notice The Hardhat EVM has no PQC precompile, so tests install this at 0x0AE1 via
 *         hardhat_setCode to exercise the message verifier's REAL precompile-calling path
 *         against REAL Falcon-512 cryptography. Unlike MockPQCPrecompile (which fakes validity
 *         with a keccak commitment), this shim performs the ACTUAL NIST Falcon-512 verification
 *         by delegating to AereFalcon512Verifier, which is validated bit-for-bit against the
 *         official Falcon-512 Known-Answer-Test vectors. So a signature accepted through this
 *         shim is a genuine Falcon-512 signature, proven by the KAT verifier path.
 *
 * @dev    The live Falcon-512 precompile takes input = pk(897) || sm and returns a RAW 32-byte
 *         word (0x..01 valid, else 0x..00) with NO ABI wrapping. This shim parses the same layout
 *         and returns the same raw word via assembly, so the caller's
 *         `ret.length >= 32 && ret[31] == 0x01` check behaves exactly as it does against the live
 *         precompile on mainnet 2800. The `ref` verifier is baked in as an immutable at
 *         construction, so capturing the deployed runtime code (getCode) and installing it at
 *         0x0AE1 (setCode) preserves the pointer. verifySignedMessage is `pure`, so the delegate
 *         call is a STATICCALL and works inside the message verifier's static verification path.
 */
contract Falcon512PrecompileShim {
    uint256 internal constant FALCON512_PK_LEN = 897;

    IFalcon512Ref public immutable ref;

    constructor(IFalcon512Ref ref_) {
        ref = ref_;
    }

    // input = pk(897) || sm ; return a RAW 32-byte word matching the live precompile.
    fallback() external {
        bytes calldata data = msg.data;
        bool ok = false;
        if (data.length > FALCON512_PK_LEN) {
            ok = ref.verifySignedMessage(data[0:FALCON512_PK_LEN], data[FALCON512_PK_LEN:]);
        }
        bytes32 w = ok ? bytes32(uint256(1)) : bytes32(0);
        assembly {
            mstore(0x0, w)
            return(0x0, 32)
        }
    }
}
