ERC-5018 · Stagnant(停滞) · ERC · 2022-04-18
ERC-5018: Filesystem-like Interface for Contracts
一个文件系统风格的合约接口,用于以分块方式在链上存储任意大小的命名文件,使网站等资源可以分多笔交易上传,并通过一次调用读回。
它解决什么问题?
ERC-4804 让 web3:// URL 指向某个合约,并像网页一样从中获取内容。然而真实的网站是由文件(HTML、CSS、图片)组成的目录,这些文件通过相对路径互相引用,而单个文件也可能大于一笔交易所能携带的数据量。
ERC-5018 标准化了一种目录合约:文件以名称为键,可一次调用读取,可分块写入。这样本地文件夹与其链上副本看起来一致,相对链接也能继续工作。
它如何运作
每个文件由一个 bytes 类型的名称标识,并存储为有序的分块列表。
整文件操作:
write(name, data):替换文件内容(payable,仅限有写权限者)。read(name) → (data, exist):返回拼接后的所有分块。size(name) → (size, chunks)和remove(name) → chunksRemoved。- 一个
fallback,把 calldata 视为以/开头的路径并返回对应文件,这正是让web3://路径式访问得以工作的原因。
面向大文件的分块操作:
writeChunk(name, chunkId, data):只能替换已有分块或追加下一个分块;chunkId > countChunks会失败。readChunk、chunkSize、countChunks、removeChunk、truncate(name, fromChunk)。getChunkHash(name, chunkId):让客户端可以跳过未改动分块的重复上传。
write 可以实现为 writeChunk(name, 0, data) 再接 truncate(name, 1)。谁拥有写权限由具体实现决定。
示例代码
接口,以及使用 ethers v6 分块上传大文件:
interface IERC5018 {
function write(bytes memory name, bytes memory data) external payable;
function read(bytes memory name) external view returns (bytes memory data, bool exist);
function size(bytes memory name) external view returns (uint256 size, uint256 chunks);
function remove(bytes memory name) external returns (uint256 numOfChunksRemoved);
function countChunks(bytes memory name) external view returns (uint256);
function writeChunk(bytes memory name, uint256 chunkId, bytes memory chunkData) external payable;
function readChunk(bytes memory name, uint256 chunkId) external view returns (bytes memory, bool);
function chunkSize(bytes memory name, uint256 chunkId) external view returns (uint256, bool);
function removeChunk(bytes memory name, uint256 chunkId) external returns (bool);
function truncate(bytes memory name, uint256 chunkId) external returns (uint256);
function getChunkHash(bytes memory name, uint256 chunkId) external view returns (bytes32);
}
import { Contract, toUtf8Bytes, keccak256 } from "ethers";
const CHUNK = 24 * 1024;
async function upload(dir: Contract, path: string, data: Uint8Array) {
const name = toUtf8Bytes(path);
for (let i = 0; i * CHUNK < data.length; i++) {
const part = data.slice(i * CHUNK, (i + 1) * CHUNK);
if ((await dir.getChunkHash(name, i)) === keccak256(part)) continue; // unchanged (if impl hashes this way)
await (await dir.writeChunk(name, i, part)).wait();
}
await (await dir.truncate(name, Math.ceil(data.length / CHUNK))).wait(); // drop leftovers
}