Skip to content
Verified contractExactMIT

ArweaveSmartAccount

Address0xa0b2f47cf2da7b8756ac89012db56c8617bbc62f
Balance

0 ETH

 

Transactions

4

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 20,000 runs
EVM version
prague
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,436,238
Creation transaction
0x202cb9f218…b85f0fc484

src/ArweaveSmartAccount.sol

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

import { ArweaveRSAPSS } from "./ArweaveRSAPSS.sol";

/// @notice A smart account controlled by an Arweave RSA-4096 public key.
/// @dev This first version provides permissionless direct relaying and ERC-1271.
contract ArweaveSmartAccount {
    struct Call {
        address target;
        uint256 value;
        bytes data;
    }

    bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256(
        "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
    );
    bytes32 public constant NAME_HASH = keccak256("Arweave Smart Account");
    bytes32 public constant VERSION_HASH = keccak256("1");
    bytes32 public constant CALL_TYPEHASH =
        keccak256("Call(address target,uint256 value,bytes data)");
    bytes32 public constant EXECUTE_TYPEHASH = keccak256(
        "ArweaveSmartAccountExecute(bytes32 context,uint256 nonce,uint48 validAfter,uint48 deadline,uint8 signatureProfile,Call[] calls)Call(address target,uint256 value,bytes data)"
    );
    bytes32 public constant INVALIDATE_NONCE_TYPEHASH = keccak256(
        "ArweaveSmartAccountInvalidateNonce(uint256 nonce,uint256 newNonce,uint48 validAfter,uint48 deadline,uint8 signatureProfile)"
    );
    bytes32 public constant ERC1271_TYPEHASH =
        keccak256("ArweaveSmartAccountERC1271(bytes32 hash,uint8 signatureProfile)");

    bytes4 public constant ERC1271_MAGIC_VALUE = 0x1626ba7e;
    bytes4 public constant ERC1271_INVALID_VALUE = 0xffffffff;
    uint8 public constant SIGNATURE_PROFILE_ARWEAVE_RSA_PSS_SHA256 = 0;
    uint8 public constant SIGNATURE_PROFILE_WANDER_SIGN_MESSAGE = 1;
    uint48 public constant MAX_AUTHORIZATION_WINDOW = 1 days;
    uint256 public constant MAX_NONCE_INVALIDATION_SKIP = 1_000_000;

    bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7;
    bytes4 private constant ERC721_RECEIVER_INTERFACE_ID = 0x150b7a02;
    bytes4 private constant ERC1155_RECEIVER_INTERFACE_ID = 0x4e2312e0;

    bytes32 public immutable ownerId;
    uint256 public nonce;

    uint256 private _executionLock = 1;

    error EmptyOwnerId();
    error EmptyContext();
    error EmptyCalls();
    error InvalidAuthorization();
    error InvalidNonce(uint256 expected, uint256 supplied);
    error InvalidNewNonce(uint256 current, uint256 supplied);
    error NonceInvalidationSkipTooLarge(uint256 current, uint256 supplied);
    error InvalidAuthorizationWindow(uint48 validAfter, uint48 deadline);
    error AuthorizationWindowTooLong(uint48 validAfter, uint48 deadline);
    error AuthorizationNotYetValid(uint48 validAfter);
    error AuthorizationExpired(uint48 deadline);
    error ReentrantExecution();
    error CallFailed(uint256 index, bytes revertData);

    event Executed(
        bytes32 indexed authorizationDigest,
        bytes32 indexed context,
        uint256 indexed nonce,
        address relayer
    );
    event NonceInvalidated(
        bytes32 indexed authorizationDigest,
        uint256 indexed previousNonce,
        uint256 indexed newNonce,
        address relayer
    );

    constructor(bytes32 ownerId_) {
        if (ownerId_ == bytes32(0)) revert EmptyOwnerId();
        ownerId = ownerId_;
    }

    receive() external payable { }

    function supportsInterface(bytes4 interfaceId) external pure returns (bool) {
        return interfaceId == ERC165_INTERFACE_ID || interfaceId == ERC1271_MAGIC_VALUE
            || interfaceId == ERC721_RECEIVER_INTERFACE_ID
            || interfaceId == ERC1155_RECEIVER_INTERFACE_ID;
    }

    function onERC721Received(address, address, uint256, bytes calldata)
        external
        pure
        returns (bytes4)
    {
        return this.onERC721Received.selector;
    }

    function onERC1155Received(address, address, uint256, uint256, bytes calldata)
        external
        pure
        returns (bytes4)
    {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] calldata,
        uint256[] calldata,
        bytes calldata
    ) external pure returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }

    /// @notice Execute an authorized batch. Any address may relay it and pay the outer gas.
    /// @dev Wallet integrations must render and confirm the typed authorization fields. A generic
    ///      arbitrary-message prompt that signs this digest is not informed user consent.
    function execute(
        Call[] calldata calls,
        bytes32 context,
        uint256 suppliedNonce,
        uint48 validAfter,
        uint48 deadline,
        uint8 signatureProfile,
        bytes calldata modulus,
        bytes calldata rsaSignature
    ) external returns (bytes[] memory results) {
        if (_executionLock != 1) revert ReentrantExecution();
        if (context == bytes32(0)) revert EmptyContext();
        if (calls.length == 0) revert EmptyCalls();
        _validateAuthorizationWindow(validAfter, deadline);

        uint256 currentNonce = nonce;
        if (suppliedNonce != currentNonce) revert InvalidNonce(currentNonce, suppliedNonce);

        bytes32 digest =
            getExecuteDigest(calls, context, suppliedNonce, validAfter, deadline, signatureProfile);
        if (!_isOwnerSignature(digest, signatureProfile, modulus, rsaSignature)) {
            revert InvalidAuthorization();
        }

        // State changes precede external calls. A reverted call rolls them back atomically.
        nonce = currentNonce + 1;
        _executionLock = 2;
        results = _executeCalls(calls);
        _executionLock = 1;

        emit Executed(digest, context, currentNonce, msg.sender);
    }

    /// @notice Revoke the current nonce and any skipped sequential authorizations.
    /// @dev A cancellation can still race an already disclosed execution authorization.
    function invalidateNonce(
        uint256 suppliedNonce,
        uint256 newNonce,
        uint48 validAfter,
        uint48 deadline,
        uint8 signatureProfile,
        bytes calldata modulus,
        bytes calldata rsaSignature
    ) external {
        if (_executionLock != 1) revert ReentrantExecution();
        _validateAuthorizationWindow(validAfter, deadline);

        uint256 currentNonce = nonce;
        if (suppliedNonce != currentNonce) revert InvalidNonce(currentNonce, suppliedNonce);
        if (newNonce <= currentNonce) revert InvalidNewNonce(currentNonce, newNonce);
        if (newNonce - currentNonce > MAX_NONCE_INVALIDATION_SKIP) {
            revert NonceInvalidationSkipTooLarge(currentNonce, newNonce);
        }

        bytes32 digest = getInvalidateNonceDigest(
            suppliedNonce, newNonce, validAfter, deadline, signatureProfile
        );
        if (!_isOwnerSignature(digest, signatureProfile, modulus, rsaSignature)) {
            revert InvalidAuthorization();
        }

        nonce = newNonce;
        emit NonceInvalidated(digest, currentNonce, newNonce, msg.sender);
    }

    function _executeCalls(Call[] calldata calls) private returns (bytes[] memory results) {
        results = new bytes[](calls.length);

        for (uint256 i; i < calls.length; ++i) {
            (bool success, bytes memory result) =
                calls[i].target.call{ value: calls[i].value }(calls[i].data);
            if (!success) revert CallFailed(i, result);
            results[i] = result;
        }
    }

    function getExecuteDigest(
        Call[] calldata calls,
        bytes32 context,
        uint256 suppliedNonce,
        uint48 validAfter,
        uint48 deadline,
        uint8 signatureProfile
    ) public view returns (bytes32) {
        bytes32 structHash = keccak256(
            abi.encode(
                EXECUTE_TYPEHASH,
                context,
                suppliedNonce,
                validAfter,
                deadline,
                signatureProfile,
                hashCalls(calls)
            )
        );
        return _hashTypedData(structHash);
    }

    function hashCalls(Call[] calldata calls) public pure returns (bytes32) {
        bytes32[] memory callHashes = new bytes32[](calls.length);
        for (uint256 i; i < calls.length; ++i) {
            callHashes[i] = keccak256(
                abi.encode(CALL_TYPEHASH, calls[i].target, calls[i].value, keccak256(calls[i].data))
            );
        }
        return keccak256(abi.encodePacked(callHashes));
    }

    function domainSeparator() public view returns (bytes32) {
        return keccak256(
            abi.encode(
                EIP712_DOMAIN_TYPEHASH, NAME_HASH, VERSION_HASH, block.chainid, address(this)
            )
        );
    }

    function getInvalidateNonceDigest(
        uint256 suppliedNonce,
        uint256 newNonce,
        uint48 validAfter,
        uint48 deadline,
        uint8 signatureProfile
    ) public view returns (bytes32) {
        bytes32 structHash = keccak256(
            abi.encode(
                INVALIDATE_NONCE_TYPEHASH,
                suppliedNonce,
                newNonce,
                validAfter,
                deadline,
                signatureProfile
            )
        );
        return _hashTypedData(structHash);
    }

    /// @notice Domain-separate an application hash for this account, chain, and profile.
    /// @dev Callers must present the underlying application action before requesting a signature.
    function getERC1271Digest(bytes32 hash, uint8 signatureProfile) public view returns (bytes32) {
        return _hashTypedData(keccak256(abi.encode(ERC1271_TYPEHASH, hash, signatureProfile)));
    }

    /// @notice Validate a domain-separated contract signature.
    /// @dev Encoding: profile (1 byte) || modulus (512 bytes) || RSA signature (512 bytes).
    function isValidSignature(bytes32 hash, bytes calldata signatureBlob)
        external
        view
        returns (bytes4)
    {
        if (signatureBlob.length != 1025) return ERC1271_INVALID_VALUE;
        uint8 signatureProfile = uint8(signatureBlob[0]);
        bytes calldata modulus = signatureBlob[1:513];
        bytes calldata rsaSignature = signatureBlob[513:1025];
        return _isOwnerSignature(
            getERC1271Digest(hash, signatureProfile), signatureProfile, modulus, rsaSignature
        ) ? ERC1271_MAGIC_VALUE : ERC1271_INVALID_VALUE;
    }

    function _hashTypedData(bytes32 structHash) private view returns (bytes32) {
        return keccak256(abi.encodePacked(hex"1901", domainSeparator(), structHash));
    }

    function _validateAuthorizationWindow(uint48 validAfter, uint48 deadline) private view {
        if (validAfter == 0 || deadline <= validAfter) {
            revert InvalidAuthorizationWindow(validAfter, deadline);
        }
        if (deadline - validAfter > MAX_AUTHORIZATION_WINDOW) {
            revert AuthorizationWindowTooLong(validAfter, deadline);
        }
        if (block.timestamp < validAfter) revert AuthorizationNotYetValid(validAfter);
        if (block.timestamp > deadline) revert AuthorizationExpired(deadline);
    }

    function _isOwnerSignature(
        bytes32 digest,
        uint8 signatureProfile,
        bytes calldata modulus,
        bytes calldata rsaSignature
    ) private view returns (bool) {
        if (signatureProfile == SIGNATURE_PROFILE_WANDER_SIGN_MESSAGE) {
            digest = sha256(abi.encodePacked(digest));
        } else if (signatureProfile != SIGNATURE_PROFILE_ARWEAVE_RSA_PSS_SHA256) {
            return false;
        }
        return modulus.length == 512 && sha256(modulus) == ownerId
            && ArweaveRSAPSS.verify(digest, rsaSignature, modulus);
    }
}

src/ArweaveRSAPSS.sol

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

/// @notice RSASSA-PSS verification for Arweave RSA-4096 keys.
/// @dev The profile is fixed to SHA-256, MGF1(SHA-256), e = 65537, and saltLen = 32.
library ArweaveRSAPSS {
    uint256 internal constant MODULUS_LENGTH = 512;
    uint256 internal constant SIGNATURE_LENGTH = 512;
    uint256 internal constant HASH_LENGTH = 32;
    uint256 internal constant SALT_LENGTH = 32;
    uint256 internal constant DB_LENGTH = MODULUS_LENGTH - HASH_LENGTH - 1;
    uint256 internal constant PS_LENGTH = DB_LENGTH - SALT_LENGTH - 1;

    address internal constant MODEXP = address(0x05);
    bytes3 internal constant PUBLIC_EXPONENT = 0x010001;

    /// @notice Verify a signature over the raw 32-byte message.
    /// @dev RSASSA-PSS hashes `message` once with SHA-256 before checking the encoding.
    function verify(bytes32 message, bytes calldata signature, bytes calldata modulus)
        internal
        view
        returns (bool)
    {
        if (signature.length != SIGNATURE_LENGTH || modulus.length != MODULUS_LENGTH) {
            return false;
        }

        // Arweave wallets use a full-width RSA-4096 modulus and e = 65537.
        if ((uint8(modulus[0]) & 0x80) == 0 || (uint8(modulus[MODULUS_LENGTH - 1]) & 1) == 0) {
            return false;
        }
        if (!_lessThan(signature, modulus)) return false;

        (bool success, bytes memory encodedMessage) = _modExp(signature, modulus);
        if (!success) return false;

        return _verifyEncodedMessage(message, encodedMessage);
    }

    function _modExp(bytes calldata signature, bytes calldata modulus)
        private
        view
        returns (bool success, bytes memory result)
    {
        bytes memory input = abi.encodePacked(
            uint256(SIGNATURE_LENGTH),
            uint256(PUBLIC_EXPONENT.length),
            uint256(MODULUS_LENGTH),
            signature,
            PUBLIC_EXPONENT,
            modulus
        );
        result = new bytes(MODULUS_LENGTH);
        address modExp = MODEXP;
        uint256 resultLength = MODULUS_LENGTH;

        assembly ("memory-safe") {
            success :=
                staticcall(
                    gas(), modExp, add(input, 0x20), mload(input), add(result, 0x20), resultLength
                )
        }
    }

    function _verifyEncodedMessage(bytes32 message, bytes memory encodedMessage)
        private
        pure
        returns (bool)
    {
        if (encodedMessage.length != MODULUS_LENGTH) return false;
        if (uint8(encodedMessage[MODULUS_LENGTH - 1]) != 0xbc) return false;

        // emBits = modBits - 1 = 4095, so the most significant bit must be zero.
        if ((uint8(encodedMessage[0]) & 0x80) != 0) return false;

        bytes32 h;
        uint256 hOffset = DB_LENGTH;
        assembly ("memory-safe") {
            h := mload(add(add(encodedMessage, 0x20), hOffset))
        }

        uint256 saltValue;
        for (uint256 counter; counter < 15; ++counter) {
            uint256 maskedWord;
            uint256 offset = counter * HASH_LENGTH;
            assembly ("memory-safe") {
                maskedWord := mload(add(add(encodedMessage, 0x20), offset))
            }

            // The MGF1 counter is four-byte big-endian and this loop stops at 14.
            // forge-lint: disable-next-line(unsafe-typecast)
            bytes4 encodedCounter = bytes4(uint32(counter));
            uint256 dbWord = maskedWord ^ uint256(sha256(abi.encodePacked(h, encodedCounter)));
            if (counter == 0) dbWord &= type(uint256).max >> 1;

            if (counter < 13) {
                if (dbWord != 0) return false;
            } else if (counter == 13) {
                // 30 zero bytes, the 0x01 delimiter, then the first salt byte.
                if (dbWord >> 8 != 1) return false;
                saltValue = (dbWord & 0xff) << 248;
            } else {
                // The final mask word contributes 31 bytes; its last byte overlaps H.
                saltValue |= dbWord >> 8;
            }
        }

        bytes32 messageHash = sha256(abi.encodePacked(message));
        bytes32 expectedH = sha256(abi.encodePacked(bytes8(0), messageHash, bytes32(saltValue)));
        return h == expectedH;
    }

    function _lessThan(bytes calldata left, bytes calldata right) private pure returns (bool) {
        for (uint256 i; i < MODULUS_LENGTH; ++i) {
            uint8 a = uint8(left[i]);
            uint8 b = uint8(right[i]);
            if (a < b) return true;
            if (a > b) return false;
        }
        return false;
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 20000,
    "enabled": true
  },
  "evmVersion": "prague"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.