Skip to content
Verified contractExactMIT

EspressoNitroTEEVerifier

Address0x4e98a1a038831b7d756ea9214508c4b34f4e4d3a
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.25

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.25+commit.b61c2a91
Language
solidity
Optimization
Yes, 1 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,037,918
Creation transaction
0xdc4ce387fa…ac8d58f4e3

src/EspressoNitroTEEVerifier.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IEspressoNitroTEEVerifier} from "./interface/IEspressoNitroTEEVerifier.sol";
import {
    INitroEnclaveVerifier,
    VerifierJournal,
    ZkCoProcessorType,
    VerificationResult
} from "aws-nitro-enclave-attestation/interfaces/INitroEnclaveVerifier.sol";
import {TEEHelper} from "./TEEHelper.sol";
import {JournalValidation} from "./libraries/JournalValidation.sol";

/**
 * @title  Verifies quotes from the AWS Nitro Enclave (TEE) and attests on-chain
 * @notice Contains the logic to verify zk proof of the attestation on-chain. It uses the EspressoNitroTEEVerifier contract
 *         from `automata` to verify the proof.
 */
contract EspressoNitroTEEVerifier is IEspressoNitroTEEVerifier, TEEHelper {
    INitroEnclaveVerifier private _nitroEnclaveVerifier;

    constructor(address teeVerifier_, address nitroEnclaveVerifier_) TEEHelper(teeVerifier_) {
        _setNitroEnclaveVerifier(nitroEnclaveVerifier_);
    }

    /**
     * @notice This function registers a new Service by verifying an attestation from the AWS Nitro Enclave (TEE)
     * The signer is not the caller of the function but the address which was generated inside the TEE.
     * @param output The public output of the ZK proof
     * @param proofBytes The cryptographic proof bytes over attestation
     */
    function registerService(bytes calldata output, bytes calldata proofBytes) external {
        VerifierJournal memory journal = _nitroEnclaveVerifier.verify(
            output,
            // Currently only Succinct ZK coprocessor is supported
            ZkCoProcessorType.Succinct,
            proofBytes
        );

        if (journal.result != VerificationResult.Success) {
            revert VerificationFailed(journal.result);
        }

        // SECURITY: Validate journal format and integrity (Defense in Depth)
        JournalValidation.validateJournal(journal);

        // we hash the pcr0 value to get the the pcr0Hash and then
        // check if the given hash has been registered in the contract by the tee verifier
        // this allows us to verify that the registerSigner request is coming from a TEE
        // which is trusted
        bytes32 pcr0Hash =
            keccak256(abi.encodePacked(journal.pcrs[0].value.first, journal.pcrs[0].value.second));

        if (!_registeredEnclaveHashes[pcr0Hash]) {
            revert InvalidEnclaveHash(pcr0Hash);
        }

        // The publicKey's first byte 0x04 byte followed which only determine if the public key is compressed or not.
        // so we ignore the first byte.
        bytes memory publicKeyWithoutPrefix = new bytes(journal.publicKey.length - 1);
        for (uint256 i = 1; i < journal.publicKey.length; i++) {
            publicKeyWithoutPrefix[i - 1] = journal.publicKey[i];
        }

        bytes32 publicKeyHash = keccak256(publicKeyWithoutPrefix);
        // Note: We take the keccak hash first to derive the address.
        // This is the same which the go ethereum crypto library is doing for PubkeyToAddress()
        address enclaveAddress = address(uint160(uint256(publicKeyHash)));

        // Mark the signer as registered
        if (!_registeredServices[enclaveAddress]) {
            _registeredServices[enclaveAddress] = true;

            // Track which enclave hash this signer belongs to (for automatic revocation)
            _signerToEnclaveHash[enclaveAddress] = pcr0Hash;

            emit ServiceRegistered(enclaveAddress, pcr0Hash);
        }
    }

    /*
     * @notice This function sets the NitroEnclaveVerifier contract address
     * @param nitroEnclaveVerifier The address of the NitroEnclaveVerifier contract
     */
    function setNitroEnclaveVerifier(address nitroEnclaveVerifier_) external onlyTEEVerifier {
        _setNitroEnclaveVerifier(nitroEnclaveVerifier_);
    }

    function _setNitroEnclaveVerifier(address nitroEnclaveVerifier_) internal {
        if (nitroEnclaveVerifier_ == address(0) || nitroEnclaveVerifier_.code.length == 0) {
            revert InvalidNitroEnclaveVerifierAddress();
        }
        _nitroEnclaveVerifier = INitroEnclaveVerifier(nitroEnclaveVerifier_);
        emit NitroEnclaveVerifierSet(nitroEnclaveVerifier_);
    }

    /**
     * @notice Get the NitroEnclaveVerifier address
     * @return The NitroEnclaveVerifier interface
     */
    function nitroEnclaveVerifier() external view returns (INitroEnclaveVerifier) {
        return _nitroEnclaveVerifier;
    }
}

lib/aws-nitro-enclave-attestation/contracts/src/interfaces/INitroEnclaveVerifier.sol

//SPDX-License-Identifier: Apache2.0
pragma solidity ^0.8.0;

/**
 * @dev Enumeration of supported zero-knowledge proof coprocessor types
 * Used to specify which proving system to use for attestation verification
 */
enum ZkCoProcessorType {
    Unknown,
    // RISC Zero zkVM proving system
    RiscZero,
    // Succinct SP1 proving system
    Succinct,
    // Pico zkVM proving system
    Pico
}

/**
 * @dev Configuration parameters for a specific zero-knowledge coprocessor
 * Contains all necessary identifiers and addresses for ZK proof verification
 *
 * Note: This struct stores the "latest" (active) program identifiers.
 * Multiple versions can be supported simultaneously via the version management functions.
 */
struct ZkCoProcessorConfig {
    // Latest program ID for single attestation verification
    bytes32 verifierId;
    // Latest program ID for batch/aggregated verification
    bytes32 aggregatorId;
    // Default ZK verifier contract address (can be overridden per route)
    address zkVerifier;
}

/**
 * @dev Input structure for attestation report verification
 * Contains the raw attestation data and trusted certificate chain length
 */
struct VerifierInput {
    // Number of trusted certificates in the chain
    uint8 trustedCertsPrefixLen;
    // Raw AWS Nitro Enclave attestation report (COSE_Sign1 format)
    bytes attestationReport;
}

/**
 * @dev Output structure containing verified attestation data and metadata
 * This represents the journal/output from zero-knowledge proof verification
 */
struct VerifierJournal {
    // Overall verification result status
    VerificationResult result;
    // Number of certificates that were trusted during verification
    uint8 trustedCertsPrefixLen;
    // Attestation timestamp (Unix timestamp in milliseconds)
    uint64 timestamp;
    // Array of certificate hashes in the chain (root to leaf)
    bytes32[] certs;
    // User-defined data embedded in the attestation
    bytes userData;
    // Cryptographic nonce used for replay protection
    bytes nonce;
    // Public key extracted from the attestation
    bytes publicKey;
    // Platform Configuration Registers (integrity measurements)
    Pcr[] pcrs;
    // AWS Nitro Enclave module identifier
    string moduleId;
}

/**
 * @dev Public value (journal) structure for batch verification operations
 * Contains the aggregated results of multiple attestation verifications
 */
struct BatchVerifierJournal {
    // Verification key that was used for batch verification
    bytes32 verifierVk;
    // Array of verified attestation results
    VerifierJournal[] outputs;
}

/**
 * @dev 48-byte data structure for storing PCR values
 * Split into two parts due to Solidity's 32-byte word limitation
 */
struct Bytes48 {
    bytes32 first;
    bytes16 second;
}

/**
 * @dev Platform Configuration Register (PCR) entry
 * PCRs contain cryptographic measurements of the enclave's runtime state
 */
struct Pcr {
    // PCR index number (0-23 for AWS Nitro Enclaves)
    uint64 index;
    // 48-byte PCR measurement value (SHA-384 hash)
    Bytes48 value;
}

/**
 * @dev Enumeration of possible attestation verification results
 * Indicates the outcome of the verification process
 */
enum VerificationResult {
    // Attestation successfully verified
    Success,
    // Root certificate is not in the trusted set
    RootCertNotTrusted,
    // One or more intermediate certificates are not trusted
    IntermediateCertsNotTrusted,
    // Attestation timestamp is outside acceptable range
    InvalidTimestamp
}

/**
 * @title INitroEnclaveVerifier
 * @dev Interface for AWS Nitro Enclave attestation verification using zero-knowledge proofs
 *
 * This interface defines the contract for verifying AWS Nitro Enclave attestation reports
 * on-chain using zero-knowledge proof systems (RISC Zero or Succinct SP1). The verifier
 * validates the cryptographic integrity of attestation reports while maintaining privacy
 * and reducing gas costs through ZK proofs.
 *
 * Key features:
 * - Single and batch attestation verification
 * - Support for multiple ZK proving systems
 * - Multi-version program support for seamless upgrades
 * - Route-based verifier configuration
 * - Certificate chain management and revocation
 * - Timestamp validation with configurable tolerance
 * - Platform Configuration Register (PCR) verification
 */
interface INitroEnclaveVerifier {
    // ============ Errors ============

    /**
     * @dev Error thrown when an unsupported or unknown ZK coprocessor type is used
     */
    error Unknown_Zk_Coprocessor();

    /**
     * @dev Error thrown when a program identifier is not in the supported set
     */
    error InvalidProgramIdentifier(ZkCoProcessorType zkCoProcessor, bytes32 identifier);

    /**
     * @dev Error thrown when attempting to remove the currently active (latest) program ID
     */
    error CannotRemoveLatestProgramId(ZkCoProcessorType zkCoProcessor, bytes32 identifier);

    /**
     * @dev Error thrown when a ZK route has been permanently frozen
     */
    error ZkRouteFrozen(ZkCoProcessorType zkCoProcessor, bytes4 selector);

    /**
     * @dev Error thrown when no ZK verifier is configured for the coprocessor
     */
    error ZkVerifierNotConfigured(ZkCoProcessorType zkCoProcessor);

    // ============ Events ============

    /**
     * @dev Emitted when a new verifier program ID is added/updated
     */
    event VerifierIdUpdated(ZkCoProcessorType indexed zkCoProcessor, bytes32 indexed newId, bytes32 newProofId);

    /**
     * @dev Emitted when a new aggregator program ID is added/updated
     */
    event AggregatorIdUpdated(ZkCoProcessorType indexed zkCoProcessor, bytes32 indexed newId);

    /**
     * @dev Emitted when a program ID is removed from the supported set
     */
    event ProgramIdRemoved(ZkCoProcessorType indexed zkCoProcessor, bytes32 indexed programId, bool isAggregator);

    /**
     * @dev Emitted when a route-specific verifier is added
     */
    event ZkRouteAdded(ZkCoProcessorType indexed zkCoProcessor, bytes4 indexed selector, address verifier);

    /**
     * @dev Emitted when a route is permanently frozen
     */
    event ZkRouteWasFrozen(ZkCoProcessorType indexed zkCoProcessor, bytes4 indexed selector);

    /**
     * @dev Emitted when the proof of attestation has been successfully verified
     */
    event AttestationSubmitted(VerificationResult result, ZkCoProcessorType zkCoProcessor, bytes output);

    /**
     * @dev Emitted when a batched proof has been successfully verified
     * @dev encodedBatched = abi.encode(VerifierJournal[])
     */
    event BatchAttestationSubmitted(bytes32 verifierId, ZkCoProcessorType zkCoProcessor, bytes encodedBatch);

    // ============ Query Functions ============

    /**
     * @dev Returns the maximum allowed time difference for attestation timestamp validation
     * @return Maximum time difference in seconds between attestation time and current block time
     */
    function maxTimeDiff() external view returns (uint64);

    /**
     * @dev Returns the hash of the trusted root certificate
     * @return Hash of the AWS Nitro Enclave root certificate
     */
    function rootCert() external view returns (bytes32);

    /**
     * @dev Retrieves the configuration for a specific coprocessor
     * @param _zkCoProcessor Type of ZK coprocessor (RiscZero or Succinct)
     * @return ZkCoProcessorConfig Configuration parameters including program IDs and verifier address
     */
    function getZkConfig(ZkCoProcessorType _zkCoProcessor) external view returns (ZkCoProcessorConfig memory);

    /**
     * @dev Returns all supported verifier program IDs for a coprocessor
     * @param _zkCoProcessor Type of ZK coprocessor
     * @return Array of all supported verifier program IDs
     */
    function getVerifierIds(ZkCoProcessorType _zkCoProcessor) external view returns (bytes32[] memory);

    /**
     * @dev Returns all supported aggregator program IDs for a coprocessor
     * @param _zkCoProcessor Type of ZK coprocessor
     * @return Array of all supported aggregator program IDs
     */
    function getAggregatorIds(ZkCoProcessorType _zkCoProcessor) external view returns (bytes32[] memory);

    /**
     * @dev Checks if a verifier program ID is in the supported set
     * @param _zkCoProcessor Type of ZK coprocessor
     * @param _verifierId Verifier program ID to check
     * @return True if the ID is supported
     */
    function isVerifierIdSupported(ZkCoProcessorType _zkCoProcessor, bytes32 _verifierId) external view returns (bool);

    /**
     * @dev Checks if an aggregator program ID is in the supported set
     * @param _zkCoProcessor Type of ZK coprocessor
     * @param _aggregatorId Aggregator program ID to check
     * @return True if the ID is supported
     */
    function isAggregatorIdSupported(ZkCoProcessorType _zkCoProcessor, bytes32 _aggregatorId)
        external
        view
        returns (bool);

    /**
     * @dev Gets the verifier address for a specific route
     * @param _zkCoProcessor Type of ZK coprocessor
     * @param _selector Proof selector
     * @return Verifier address (route-specific or default fallback)
     *
     * Note: Reverts if the route is frozen
     */
    function getZkVerifier(ZkCoProcessorType _zkCoProcessor, bytes4 _selector) external view returns (address);

    /**
     * @dev Returns the verifierProofId for a given verifierId
     * @param _zkCoProcessor Type of ZK coprocessor
     * @param _verifierId The verifier program ID
     * @return The corresponding verifierProofId
     */
    function getVerifierProofId(ZkCoProcessorType _zkCoProcessor, bytes32 _verifierId) external view returns (bytes32);

    /**
     * @dev Checks how many certificates in each report are trusted
     * @param _report_certs Array of certificate chains, each containing certificate hashes
     * @return Array indicating the number of trusted certificates in each chain
     *
     * For each certificate chain:
     * - Validates that the first certificate matches the root certificate
     * - Counts consecutive trusted certificates starting from the root
     * - Returns the count of trusted certificates for each chain
     */
    function checkTrustedIntermediateCerts(bytes32[][] calldata _report_certs) external view returns (uint8[] memory);

    // ============ Admin Functions ============

    /**
     * @dev Sets the trusted root certificate hash
     * @param _rootCert Hash of the new root certificate
     *
     * Requirements:
     * - Only callable by contract owner
     */
    function setRootCert(bytes32 _rootCert) external;

    /**
     * @dev Configures the zero-knowledge verification parameters for a specific coprocessor
     * @param _zkCoProcessor Type of ZK coprocessor (RiscZero or Succinct)
     * @param _config Configuration parameters including program IDs and verifier address
     * @param _verifierProofId The verifierProofId corresponding to the verifierId in config
     *
     * Requirements:
     * - Only callable by contract owner
     * - Must specify valid coprocessor type and configuration
     */
    function setZkConfiguration(
        ZkCoProcessorType _zkCoProcessor,
        ZkCoProcessorConfig memory _config,
        bytes32 _verifierProofId
    ) external;

    /**
     * @dev Revokes a trusted intermediate certificate
     * @param _certHash Hash of the certificate to revoke
     *
     * Requirements:
     * - Only callable by contract owner
     * - Certificate must exist in the trusted set
     */
    function revokeCert(bytes32 _certHash) external;

    /**
     * @dev Updates the verifier program ID, adding the new version to the supported set
     * @param _zkCoProcessor Type of ZK coprocessor
     * @param _newVerifierId New verifier program ID to set as latest
     * @param _newVerifierProofId New verifier proof ID (used in batch verification)
     *
     * Requirements:
     * - Only callable by contract owner
     * - New ID must be different from current latest
     */
    function updateVerifierId(ZkCoProcessorType _zkCoProcessor, bytes32 _newVerifierId, bytes32 _newVerifierProofId)
        external;

    /**
     * @dev Updates the aggregator program ID, adding the new version to the supported set
     * @param _zkCoProcessor Type of ZK coprocessor
     * @param _newAggregatorId New aggregator program ID to set as latest
     *
     * Requirements:
     * - Only callable by contract owner
     * - New ID must be different from current latest
     */
    function updateAggregatorId(ZkCoProcessorType _zkCoProcessor, bytes32 _newAggregatorId) external;

    /**
     * @dev Removes a verifier program ID from the supported set
     * @param _zkCoProcessor Type of ZK coprocessor
     * @param _verifierId Verifier program ID to remove
     *
     * Requirements:
     * - Only callable by contract owner
     * - Cannot remove the currently active (latest) verifier ID
     * - ID must exist in the supported set
     */
    function removeVerifierId(ZkCoProcessorType _zkCoProcessor, bytes32 _verifierId) external;

    /**
     * @dev Removes an aggregator program ID from the supported set
     * @param _zkCoProcessor Type of ZK coprocessor
     * @param _aggregatorId Aggregator program ID to remove
     *
     * Requirements:
     * - Only callable by contract owner
     * - Cannot remove the currently active (latest) aggregator ID
     * - ID must exist in the supported set
     */
    function removeAggregatorId(ZkCoProcessorType _zkCoProcessor, bytes32 _aggregatorId) external;

    /**
     * @dev Adds a route-specific verifier override
     * @param _zkCoProcessor Type of ZK coprocessor
     * @param _selector Proof selector (first 4 bytes of proof data)
     * @param _verifier Address of the verifier contract for this route
     *
     * Requirements:
     * - Only callable by contract owner
     * - Route must not be frozen
     * - Verifier address must not be zero
     */
    function addVerifyRoute(ZkCoProcessorType _zkCoProcessor, bytes4 _selector, address _verifier) external;

    /**
     * @dev Permanently freezes a verification route
     * @param _zkCoProcessor Type of ZK coprocessor
     * @param _selector Proof selector to freeze
     *
     * Requirements:
     * - Only callable by contract owner
     * - Route must not already be frozen
     *
     * WARNING: This action is IRREVERSIBLE
     */
    function freezeVerifyRoute(ZkCoProcessorType _zkCoProcessor, bytes4 _selector) external;

    // ============ Verification Functions ============

    /**
     * @dev Verifies a single attestation report using zero-knowledge proof
     * @param output Encoded VerifierJournal containing the verification result
     * @param zkCoprocessor Type of ZK coprocessor used to generate the proof
     * @param proofBytes Zero-knowledge proof data for the attestation
     * @return VerifierJournal containing the verification result and extracted data
     *
     * This function:
     * 1. Verifies the ZK proof using the specified coprocessor
     * 2. Decodes the verification result
     * 3. Validates the certificate chain against trusted certificates
     * 4. Checks timestamp validity within the allowed time difference
     * 5. Caches newly discovered trusted certificates
     * 6. Returns the complete verification result
     */
    function verify(bytes calldata output, ZkCoProcessorType zkCoprocessor, bytes calldata proofBytes)
        external
        returns (VerifierJournal memory);

    /**
     * @dev Verifies multiple attestation reports in a single batch operation
     * @param output Encoded BatchVerifierJournal containing aggregated verification results
     * @param zkCoprocessor Type of ZK coprocessor used to generate the proof
     * @param proofBytes Zero-knowledge proof data for batch verification
     * @return Array of VerifierJournal results, one for each attestation in the batch
     *
     * This function:
     * 1. Verifies the ZK proof using the specified coprocessor
     * 2. Decodes the batch verification results
     * 3. Validates each attestation's certificate chain and timestamp
     * 4. Caches newly discovered trusted certificates
     * 5. Returns the verification results for all attestations
     */
    function batchVerify(bytes calldata output, ZkCoProcessorType zkCoprocessor, bytes calldata proofBytes)
        external
        returns (VerifierJournal[] memory);

    // ============ Explicit Program ID Verification Functions ============

    /**
     * @dev Verifies a single attestation with an explicit program ID
     * @param output Encoded VerifierJournal containing the verification result
     * @param zkCoprocessor Type of ZK coprocessor used to generate the proof
     * @param programId Explicit verifier program ID to use (must be in supported set)
     * @param proofBytes Zero-knowledge proof data for the attestation
     * @return VerifierJournal containing the verification result and extracted data
     *
     * This allows verification with older program versions that are still supported.
     */
    function verifyWithProgramId(
        bytes calldata output,
        ZkCoProcessorType zkCoprocessor,
        bytes32 programId,
        bytes calldata proofBytes
    ) external returns (VerifierJournal memory);

    /**
     * @dev Verifies multiple attestations with explicit program IDs
     * @param output Encoded BatchVerifierJournal containing aggregated verification results
     * @param zkCoprocessor Type of ZK coprocessor used to generate the proof
     * @param aggregatorId Explicit aggregator program ID to use
     * @param verifierId The verifier program ID (contract looks up corresponding verifierProofId)
     * @param proofBytes Zero-knowledge proof data for batch verification
     * @return Array of VerifierJournal results, one for each attestation in the batch
     *
     * This allows batch verification with older program versions that are still supported.
     * The contract internally looks up the verifierProofId from the verifierId mapping.
     */
    function batchVerifyWithProgramId(
        bytes calldata output,
        ZkCoProcessorType zkCoprocessor,
        bytes32 aggregatorId,
        bytes32 verifierId,
        bytes calldata proofBytes
    ) external returns (VerifierJournal[] memory);
}

src/TEEHelper.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./interface/ITEEHelper.sol";

abstract contract TEEHelper is ITEEHelper {
    mapping(bytes32 enclaveHash => bool valid) internal _registeredEnclaveHashes;
    mapping(address signer => bool valid) internal _registeredServices;
    address internal _teeVerifier;
    mapping(address signer => bytes32 enclaveHash) internal _signerToEnclaveHash;

    modifier onlyTEEVerifier() {
        if (msg.sender != teeVerifier()) {
            revert UnauthorizedTEEVerifier(msg.sender);
        }
        _;
    }

    constructor(address teeVerifier_) {
        _setTEEVerifier(teeVerifier_);
    }

    function teeVerifier() public view returns (address) {
        return _teeVerifier;
    }

    /**
     * @notice Allows the tee verifier to set the enclave hash, setting valid to true will allow any enclave
     * with a valid pcr0 hash to register a signer (address which was generated inside the TEE). Setting valid to false
     * will further remove the enclave hash from the registered enclave hash list thus preventing any enclave with the given
     * hash from registering a signer.
     * @param enclaveHash The hash of the enclave
     * @param valid Whether the enclave hash is valid or not
     */
    function setEnclaveHash(bytes32 enclaveHash, bool valid) external virtual onlyTEEVerifier {
        _registeredEnclaveHashes[enclaveHash] = valid;
        emit EnclaveHashSet(enclaveHash, valid);
    }

    /**
     * @notice Validates if a signer is registered AND its enclave hash is still valid
     * @param signer The address of the signer
     * @return bool True if signer is registered AND its enclave hash is still approved
     */
    function isSignerValid(address signer) external view virtual returns (bool) {
        // Check if signer is registered
        if (!_registeredServices[signer]) {
            return false;
        }

        // Check if signer's enclave hash is still approved
        bytes32 signerHash = _signerToEnclaveHash[signer];

        // If no hash recorded (shouldn't happen with new registrations), be safe and reject
        if (signerHash == bytes32(0)) {
            return false;
        }

        // Check if the hash is still valid
        return _registeredEnclaveHashes[signerHash];
    }

    /**
     * @notice This function retrieves whether an enclave hash is registered or not
     * @param enclaveHash The hash of the enclave
     * @return bool True if the enclave hash is registered, false otherwise
     */
    function registeredEnclaveHash(bytes32 enclaveHash) external view virtual returns (bool) {
        return _registeredEnclaveHashes[enclaveHash];
    }

    /**
     * @notice Allows the tee verifier to delete registered enclave hashes from the list of valid enclave hashes
     * @dev FIX: Removes unbounded loop to prevent DoS attack
     * @dev NOTE: This only removes the hash authorization, existing signers remain in registeredServices
     * @dev To fully revoke signers, use isSignerValid() which checks hash validity
     * @param enclaveHashes The list of enclave hashes to be deleted
     */
    function deleteEnclaveHashes(bytes32[] memory enclaveHashes) external virtual onlyTEEVerifier {
        for (uint256 i = 0; i < enclaveHashes.length; i++) {
            bytes32 enclaveHash = enclaveHashes[i];

            // Skip already-unregistered hashes to keep batch deletion idempotent.
            if (!_registeredEnclaveHashes[enclaveHash]) {
                continue;
            }

            // Delete the hash authorization (prevents NEW registrations)
            delete _registeredEnclaveHashes[enclaveHash];
            emit DeletedEnclaveHash(enclaveHash);

            // NOTE: Existing signers are NOT automatically revoked from registeredServices
            // They remain in the mapping to avoid unbounded loop DoS
            // Use isSignerValid() for verification - it checks if hash is still valid
        }
    }

    /**
     * @notice Updates the authorized TEE verifier address.
     * @param newTEEVerifier The new verifier address allowed to manage enclave hashes.
     */
    function _setTEEVerifier(address newTEEVerifier) internal {
        if (newTEEVerifier == address(0)) {
            revert InvalidTEEVerifierAddress();
        }
        _teeVerifier = newTEEVerifier;
        emit TeeVerifierSet(newTEEVerifier);
    }
}

src/interface/IEspressoNitroTEEVerifier.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {
    INitroEnclaveVerifier,
    VerificationResult
} from "aws-nitro-enclave-attestation/interfaces/INitroEnclaveVerifier.sol";
import "./ITEEHelper.sol";

interface IEspressoNitroTEEVerifier is ITEEHelper {
    // This error is thrown when the ZK proof verification fails
    error VerificationFailed(VerificationResult result);
    // This error is thrown when the NitroEnclaveVerifier address is invalid
    error InvalidNitroEnclaveVerifierAddress();
    event NitroEnclaveVerifierSet(address nitroEnclaveVerifierAddress);

    /*
     * @notice This function registers a new Service by verifying an attestation from the AWS Nitro Enclave (TEE)
     * The signer is not the caller of the function but the address which was generated inside the TEE.
     * @param output The public output of the ZK proof
     * @param proofBytes The cryptographic proof bytes over attestation
     */
    function registerService(bytes calldata output, bytes calldata proofBytes) external;

    /*
     * @notice This function sets the NitroEnclaveVerifier contract address
     */
    function setNitroEnclaveVerifier(address nitroEnclaveVerifierAddress) external;

    /*
     * @notice Get the NitroEnclaveVerifier contract address
     * @return The NitroEnclaveVerifier interface
     */
    function nitroEnclaveVerifier() external view returns (INitroEnclaveVerifier);
}

src/interface/ITEEHelper.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface ITEEHelper {
    // Thrown when a caller is not the tee verifier
    error UnauthorizedTEEVerifier(address caller);
    // Thrown when a zero tee verifier address is provided
    error InvalidTEEVerifierAddress();
    // Thrown when an invalid enclave hash is provided
    // function signature: 0x94f1e6f9
    error InvalidEnclaveHash(bytes32 enclaveHash);

    // Emitted when an enclave hash is deleted
    event DeletedEnclaveHash(bytes32 indexed enclaveHash);

    // Emitted when a service is registered
    event ServiceRegistered(address indexed signer, bytes32 indexed enclaveHash);

    // Emitted when the tee verifier is set
    event TeeVerifierSet(address indexed teeVerifier);

    // Emitted when an enclave hash is set
    event EnclaveHashSet(bytes32 indexed enclaveHash, bool indexed valid);

    /**
     * @notice Allows the tee verifier to set the enclave hash, setting valid to true will allow any enclave
     * with a valid pcr0 hash to register a signer (address which was generated inside the TEE). Setting valid to false
     * will further remove the enclave hash from the registered enclave hash list thus preventing any enclave with the given
     * hash from registering a signer.
     * @param enclaveHash The hash of the enclave
     * @param valid Whether the enclave hash is valid or not
     */
    function setEnclaveHash(bytes32 enclaveHash, bool valid) external;

    /*
     * @notice Returns the tee verifier allowed to administer helpers
     */
    function teeVerifier() external view returns (address);

    /*
     * @notice This function retrieves whether an enclave hash is registered or not
     * @param enclaveHash The hash of the enclave
     * @return bool True if the enclave hash is registered, false otherwise
     */
    function registeredEnclaveHash(bytes32 enclaveHash) external view returns (bool);

    /*
     * @notice Validates if a signer is registered AND its enclave hash is still valid
     * @param signer The address of the signer
     * @return bool True if signer is registered AND its enclave hash is still approved
     */
    function isSignerValid(address signer) external view returns (bool);

    /*
     * @notice Allows the tee verifier to delete registered enclave hashes from the list of valid enclave hashes
     * @param enclaveHashes The array of enclave hashes to delete
     */
    function deleteEnclaveHashes(bytes32[] memory enclaveHashes) external;
}

src/libraries/JournalValidation.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {VerifierJournal} from "aws-nitro-enclave-attestation/interfaces/INitroEnclaveVerifier.sol";

/**
 * @title JournalValidation
 * @notice Library for validating Nitro Enclave ZK proof journals
 * @dev Extracted as a library to be reusable across contracts and tests
 */
library JournalValidation {
    /**
     * @notice Validates the VerifierJournal format and integrity
     * @dev Implements defense-in-depth by validating critical fields even if ZK circuit validates them
     * @param journal The journal returned from ZK proof verification
     *
     * Security validations:
     * 1. PCR array bounds - Ensures we can safely access journal.pcrs[0]
     * 2. PCR index correctness - Ensures pcrs[0] is actually PCR0 (code measurement), not PCR3 or other
     * 3. Public key length - Ensures 65-byte format (prevents predictable address attacks)
     * 4. Public key format - Ensures uncompressed format (0x04 prefix)
     *
     * Why validate even if ZK circuit should validate:
     * - Defense in depth: Multiple security layers
     * - Protection against ZK circuit bugs or gaps
     * - Explicit documentation of security requirements
     * - Minimal gas cost (~500 gas) for critical protection
     */
    function validateJournal(VerifierJournal memory journal) internal pure {
        // 1. Validate PCR array is not empty (prevents out-of-bounds on journal.pcrs[0])
        require(journal.pcrs.length > 0, "PCR array cannot be empty");

        // 2. CRITICAL: Validate PCR index is 0 (prevents validating wrong PCR!)
        // Without this check, an attacker could put PCR3 in position 0
        // Contract would validate PCR3 (benign) while PCR0 (code) is compromised
        require(journal.pcrs[0].index == 0, "First PCR must be PCR0 (code measurement)");

        // 3. CRITICAL: Validate public key length (prevents predictable address attacks)
        // Malformed keys (e.g., length=1) would hash to predictable addresses
        // Anyone could compute these addresses without needing a TEE
        require(journal.publicKey.length == 65, "Invalid public key length - must be 65 bytes");

        // 4. CRITICAL: Validate public key format (ensures correct address derivation)
        // Must be uncompressed ECDSA format: 0x04 + 32-byte X + 32-byte Y
        // Other formats would derive incorrect addresses
        require(journal.publicKey[0] == 0x04, "Public key must be uncompressed (0x04 prefix)");
    }
}

Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "forge-std/=lib/forge-std/src/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "solady/=lib/automata-dcap-attestation/lib/automata-on-chain-pccs/lib/solady/src/",
    "aws-nitro-enclave-attestation/=lib/aws-nitro-enclave-attestation/contracts/src/",
    "safe-smart-account/=lib/safe-utils/lib/safe-smart-account/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@espresso-tee/=src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "risc0-ethereum/=lib/aws-nitro-enclave-attestation/contracts/lib/risc0-ethereum/",
    "safe-utils/=lib/safe-utils/src/",
    "solidity-http/=lib/safe-utils/lib/solidity-http/src/",
    "solidity-stringutils/=lib/safe-utils/lib/solidity-stringutils/",
    "sp1-contracts/=lib/aws-nitro-enclave-attestation/contracts/lib/sp1-contracts/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.