Skip to content
Verified contractExactMIT

ChunkStore

Address0x56317b1f45e4c15310135ea72fa4d768ca902bcc
Balance

0 ETH

 

Transactions

70

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,330,978
Creation transaction
0xe04545ca6b…ff2a14d0d2

src/ChunkStore.sol

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

import {Multicallable} from "solady/utils/Multicallable.sol";

import {IChunkStore} from "./interfaces/IChunkStore.sol";
import {IStorageBackend} from "./interfaces/IStorageBackend.sol";

/// @title ChunkStore
/// @notice ABX FS chunk records. Any contract can be a backend; the backend's address, the hash of the input it was given and the
///         chunk's data hash and size are all inside the chunk id (see `IChunkStore`). No owner, no registry, no ETH.
///
/// @dev    Of the ABX FS contracts, this is the only one that calls a backend. `write` uses typed calls, so a reverting or malformed
///         backend fails only the write that chose it. `read` uses a raw `staticcall`, copies nothing larger than the
///         record says, and decodes the result by hand, so a misbehaving backend yields `RetrieveFailed` or `DataMismatch`,
///         never a bare decoding revert. Inherits Solady `Multicallable`, which refuses ETH.
contract ChunkStore is IChunkStore, Multicallable {
    bytes1 internal constant _CHUNK_PREFIX = 0x30;

    /// @dev Three slots; backend and size share the first. The input's hash is part of the id but is not kept: `read`
    ///      needs only these, and the `ChunkWritten` event carries it for anyone recomputing ids from logs.
    struct Record {
        address backend;
        uint48 size;
        bytes32 pointer;
        bytes32 dataHash;
    }

    mapping(bytes32 => Record) internal _records;

    /// @inheritdoc IChunkStore
    function write(address backend, bytes calldata input, bytes32 dataHash, uint48 size) external returns (bytes32 id) {
        if (backend.code.length == 0) revert InvalidBackend(backend);
        if (size == 0) revert EmptyChunk();
        bytes32 inputHash = keccak256(input);
        id = chunkId(backend, inputHash, dataHash, size);
        if (_records[id].backend != address(0)) return id;

        bytes32 pointer = IStorageBackend(backend).store(input, msg.sender);
        // The backend may have re-entered and recorded this very id; that record stands.
        if (_records[id].backend != address(0)) return id;

        if (IStorageBackend(backend).readable()) {
            bytes memory data = IStorageBackend(backend).retrieve(pointer);
            if (data.length != size || keccak256(data) != dataHash) revert DataMismatch(id);
        }

        _records[id] = Record({backend: backend, size: size, pointer: pointer, dataHash: dataHash});
        emit ChunkWritten(id, backend, pointer, inputHash, dataHash, size);
    }

    /// @inheritdoc IChunkStore
    function chunkId(address backend, bytes32 inputHash, bytes32 dataHash, uint48 size) public pure returns (bytes32) {
        return keccak256(abi.encodePacked(_CHUNK_PREFIX, backend, inputHash, dataHash, size));
    }

    /// @inheritdoc IChunkStore
    function read(bytes32 id) external view returns (bytes memory data) {
        Record storage r = _records[id];
        address backend = r.backend;
        if (backend == address(0)) revert ChunkNotFound(id);
        uint256 size = r.size;
        bytes32 pointer = r.pointer;
        bytes4 selector = IStorageBackend.retrieve.selector;

        // One ABI-encoded `bytes` of `size` bytes is an offset word, a length word and the data padded to a word.
        bool ok;
        uint256 returned;
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, selector)
            mstore(add(m, 0x04), pointer)
            ok := staticcall(gas(), backend, m, 0x24, 0x00, 0x00)
            returned := returndatasize()
        }
        if (!ok || returned < 0x40 + size || returned > 0x40 + ((size + 0x1f) & ~uint256(0x1f))) {
            revert RetrieveFailed(id, backend);
        }
        uint256 offset;
        uint256 length;
        assembly ("memory-safe") {
            returndatacopy(0x00, 0x00, 0x40)
            offset := mload(0x00)
            length := mload(0x20)
        }
        if (offset != 0x20) revert RetrieveFailed(id, backend);
        if (length != size) revert DataMismatch(id);
        data = new bytes(size);
        assembly ("memory-safe") {
            returndatacopy(add(data, 0x20), 0x40, size)
        }
        if (keccak256(data) != r.dataHash) revert DataMismatch(id);
    }

    /// @inheritdoc IChunkStore
    function exists(bytes32 id) external view returns (bool) {
        return _records[id].backend != address(0);
    }

    /// @inheritdoc IChunkStore
    function sizeOf(bytes32 id) external view returns (uint48) {
        return _record(id).size;
    }

    /// @inheritdoc IChunkStore
    function recordOf(bytes32 id)
        external
        view
        returns (address backend, uint48 size, bytes32 pointer, bytes32 dataHash)
    {
        Record memory r = _record(id);
        return (r.backend, r.size, r.pointer, r.dataHash);
    }

    function _record(bytes32 id) internal view returns (Record memory r) {
        r = _records[id];
        if (r.backend == address(0)) revert ChunkNotFound(id);
    }
}

lib/solady/src/utils/Multicallable.sol

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

/// @notice Contract that enables a single call to call multiple methods on itself.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Multicallable.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Multicallable.sol)
///
/// WARNING:
/// This implementation is NOT to be used with ERC2771 out-of-the-box.
/// https://blog.openzeppelin.com/arbitrary-address-spoofing-vulnerability-erc2771context-multicall-public-disclosure
/// This also applies to potentially other ERCs / patterns appending to the back of calldata.
///
/// We do NOT have a check for ERC2771, as we do not inherit from OpenZeppelin's context.
/// Moreover, it is infeasible and inefficient for us to add checks and mitigations
/// for all possible ERC / patterns appending to the back of calldata.
///
/// We would highly recommend using an alternative pattern such as
/// https://github.com/Vectorized/multicaller
/// which is more flexible, futureproof, and safer by default.
abstract contract Multicallable {
    /// @dev Apply `delegatecall` with the current contract to each calldata in `data`,
    /// and store the `abi.encode` formatted results of each `delegatecall` into `results`.
    /// If any of the `delegatecall`s reverts, the entire context is reverted,
    /// and the error is bubbled up.
    ///
    /// By default, this function directly returns the results and terminates the call context.
    /// If you need to add before and after actions to the multicall, please override this function.
    function multicall(bytes[] calldata data) public payable virtual returns (bytes[] memory) {
        // Revert if `msg.value` is non-zero by default to guard against double-spending.
        // (See: https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong)
        //
        // If you really need to pass in a `msg.value`, then you will have to
        // override this function and add in any relevant before and after checks.
        if (msg.value != 0) revert();
        // `_multicallDirectReturn` returns the results directly and terminates the call context.
        _multicallDirectReturn(_multicall(data));
    }

    /// @dev The inner logic of `multicall`.
    /// This function is included so that you can override `multicall`
    /// to add before and after actions, and use the `_multicallDirectReturn` function.
    function _multicall(bytes[] calldata data) internal virtual returns (bytes32 results) {
        /// @solidity memory-safe-assembly
        assembly {
            results := mload(0x40)
            mstore(results, 0x20)
            mstore(add(0x20, results), data.length)
            let c := add(0x40, results)
            let s := c
            let end := shl(5, data.length)
            calldatacopy(c, data.offset, end)
            end := add(c, end)
            let m := end
            if data.length {
                for {} 1 {} {
                    let o := add(data.offset, mload(c))
                    calldatacopy(m, add(o, 0x20), calldataload(o))
                    // forgefmt: disable-next-item
                    if iszero(delegatecall(gas(), address(), m, calldataload(o), codesize(), 0x00)) {
                        // Bubble up the revert if the delegatecall reverts.
                        returndatacopy(results, 0x00, returndatasize())
                        revert(results, returndatasize())
                    }
                    mstore(c, sub(m, s))
                    c := add(0x20, c)
                    // Append the `returndatasize()`, and the return data.
                    mstore(m, returndatasize())
                    let b := add(m, 0x20)
                    returndatacopy(b, 0x00, returndatasize())
                    // Advance `m` by `returndatasize() + 0x20`,
                    // rounded up to the next multiple of 32.
                    m := and(add(add(b, returndatasize()), 0x1f), 0xffffffffffffffe0)
                    mstore(add(b, returndatasize()), 0) // Zeroize the slot after the returndata.
                    if iszero(lt(c, end)) { break }
                }
            }
            mstore(0x40, m) // Allocate memory.
            results := or(shl(64, sub(m, results)), results) // Pack the bytes length into `results`.
        }
    }

    /// @dev Decodes the `results` into an array of bytes.
    /// This can be useful if you need to access the results or re-encode it.
    function _multicallResultsToBytesArray(bytes32 results)
        internal
        pure
        virtual
        returns (bytes[] memory decoded)
    {
        /// @solidity memory-safe-assembly
        assembly {
            decoded := mload(0x40)
            let c := and(0xffffffffffffffff, results) // Extract the offset.
            mstore(decoded, mload(add(c, 0x20))) // Store the length.
            let o := add(decoded, 0x20) // Start of elements in `decoded`.
            let end := add(o, shl(5, mload(decoded)))
            mstore(0x40, end) // Allocate memory.
            let s := add(c, 0x40) // Start of elements in `results`.
            let d := sub(s, o) // Difference between input and output pointers.
            for {} iszero(eq(o, end)) { o := add(o, 0x20) } { mstore(o, add(mload(add(d, o)), s)) }
        }
    }

    /// @dev Directly returns the `results` and terminates the current call context.
    /// `results` must be from `_multicall`, else behavior is undefined.
    function _multicallDirectReturn(bytes32 results) internal pure virtual {
        /// @solidity memory-safe-assembly
        assembly {
            return(and(0xffffffffffffffff, results), shr(64, results))
        }
    }
}

src/interfaces/IChunkStore.sol

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

/// @title IChunkStore
/// @notice Content-addressed chunk records for ABX FS. A chunk's id binds the backend that holds it, the exact input
///         given to that backend, and the hash and size of the chunk's data (what the backend's `retrieve` returns,
///         or what a reader obtains by following the backend's retrieval scheme):
///
///             id = keccak256(0x30 ‖ backend:20 ‖ keccak256(input):32 ‖ dataHash:32 ‖ size:6)
///
///         For a readable backend the chain checks `dataHash` and `size` when the chunk is written and on every read.
///         For any other backend they are claims bound into the id: a false claim yields an id no honest writer
///         would compute, so it can never occupy anyone else's chunk. See `specs/abx-fs.md` §4.
interface IChunkStore {
    error InvalidBackend(address backend);
    error EmptyChunk();
    error DataMismatch(bytes32 id);
    error ChunkNotFound(bytes32 id);
    /// @notice The backend's `retrieve` reverted, or its return data is not shaped like one ABI-encoded `bytes` of the
    ///         recorded size (an offset other than 0x20, or too short or too long for that size). Ask that backend's
    ///         `retrieval()` how to fetch the bytes instead. A well-shaped result whose length or hash disagrees with the
    ///         record is `DataMismatch`.
    error RetrieveFailed(bytes32 id, address backend);

    event ChunkWritten(
        bytes32 indexed id, address indexed backend, bytes32 pointer, bytes32 inputHash, bytes32 dataHash, uint48 size
    );

    /// @notice Store `input` through `backend` and record the chunk. Returns the existing id without calling the
    ///         backend when the chunk is already recorded.
    function write(address backend, bytes calldata input, bytes32 dataHash, uint48 size) external returns (bytes32 id);

    /// @notice The chunk id for these parts (see the notice above).
    function chunkId(address backend, bytes32 inputHash, bytes32 dataHash, uint48 size)
        external
        pure
        returns (bytes32 id);

    /// @notice The chunk's data, checked against its record. Reverts `RetrieveFailed` when the backend cannot serve it.
    function read(bytes32 id) external view returns (bytes memory data);

    function exists(bytes32 id) external view returns (bool);

    /// @notice The recorded size of the chunk's data. Reverts `ChunkNotFound` if the id is not recorded.
    function sizeOf(bytes32 id) external view returns (uint48 size);

    /// @notice The whole record. Reverts `ChunkNotFound` if the id is not recorded.
    function recordOf(bytes32 id) external view returns (address backend, uint48 size, bytes32 pointer, bytes32 dataHash);
}

src/interfaces/IStorageBackend.sol

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

/// @title IStorageBackend
/// @notice Where an ABX FS chunk's bytes live. Anyone can deploy a backend and use it at once: nothing registers
///         backends, and a backend's address is part of every chunk id stored through it, so no backend can affect
///         content stored through another.
///
/// @dev    Backends are never trusted for integrity. `ChunkStore` checks a readable backend's bytes when a chunk is
///         written and on every read; a reader checks any other backend's bytes against the chunk record. A backend
///         may compress, keep bytes in contract code, in logs, in blobs or anywhere else, and may change behaviour at
///         any time: availability is the backend's, integrity is not. Of the ABX FS contracts, only `ChunkStore` calls a backend. See
///         `specs/abx-fs.md` §3.
interface IStorageBackend {
    /// @notice Thrown by `retrieve` when the backend is not EVM-readable.
    error NotEvmReadable();

    /// @notice Store `input` and return an opaque pointer this backend resolves later. May revert to refuse.
    /// @param  caller The account that called `ChunkStore.write`, so a backend can bill, meter or gate writers (a
    ///         deposit it holds, an allowance it pulls). Anyone can call a backend directly with any `caller`, so a
    ///         backend that acts on it must first check that `msg.sender` is the `ChunkStore` it serves. Writes of an
    ///         existing chunk never reach the backend.
    function store(bytes calldata input, address caller) external returns (bytes32 pointer);

    /// @notice Whether `retrieve` returns a chunk's bytes from chain state.
    function readable() external view returns (bool);

    /// @notice The chunk's bytes, after any decoding this backend performs (for example FastLZ inflation).
    ///         MUST revert `NotEvmReadable()` when `readable()` is false.
    function retrieve(bytes32 pointer) external view returns (bytes memory data);

    /// @notice A best-effort, untrusted description of how to fetch this backend's bytes off chain. `scheme` is a
    ///         lowercase ASCII token, left-aligned and zero-padded (an SDK convention, for example "evm").
    function retrieval() external view returns (bytes32 scheme, string memory instructions);

    /// @notice The largest `input` that `store` accepts. For planners only: `ChunkStore` does not call it.
    function maxInputSize() external view returns (uint256);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 10000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "solady/=lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.