关于 midnight-storage
介绍 Midnight 存储栈的技能,适合研究区块链状态如何组织、提交和查询的读者。内容涵盖 ParityDB、Patricia-Merkle Trie、存储键哈希及可用的查询方式。
主要功能
- 01使用 ParityDB 持久化状态
- 02Patricia-Merkle Trie 状态承诺
- 03使用 twoxhash 生成存储键
- 04逐区块提交状态
- 05提供 RPC 和 GraphQL 查询
适用场景
- 01了解 Midnight 状态持久化
- 02研究状态根的计算方式
- 03查找合约状态查询途径
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ kali-decoder/ midnight-skills --skill midnight-storage安装后在 Claude Code 中输入/midnight-storage确认已加载。
详细介绍
存储
Midnight 基于 Polkadot SDK(Substrate) 构建,并使用 ParityDB 作为默认数据库后端。
存储栈
flowchart TB
subgraph Runtime["Runtime execution"]
STF["State transition function (WASM)"]
PM["pallet-midnight + other pallets"]
end
subgraph Trie["State layer"]
MPT["Patricia-Merkle trie"]
T2H["twoxhash — storage key generation"]
MPT --- T2H
end
subgraph Persist["Persistence"]
PDB["ParityDB — key-value store"]
end
STF --> PM
PM --> MPT
MPT --> PDB
MPT --> Commit["State root commitment per block"]
ParityDB
ParityDB 是一款专为区块链工作负载设计的高速键值存储。
- 存储所有链上状态。
- 是包括 Midnight 在内的 Substrate/Polkadot SDK 链的默认后端。
- 针对区块导入和状态提交期间的高写入吞吐量进行了优化。
Patricia-Merkle trie
Trie 是用于状态承诺的底层数据结构。
| 属性 | 优势 |
|---|---|
| Merkle 结构 | 每个区块的状态根具备防篡改特性 |
| 包含性证明 | 高效验证合约状态、余额等 |
| 增量更新 | 每个区块仅重新计算发生变化的路径 |
运行时 pallet(包括 pallet-midnight)中的规范账本状态会组织在此 trie 中,并通过 ParityDB 持久化。
flowchart LR
BlockN["Block N state root"] --> Root["Trie root hash"]
Root --> Leaf1["Storage item A"]
Root --> Leaf2["Storage item B"]
Root --> Leaf3["Contract state …"]
Query["RPC / light client"] --> Proof["Merkle inclusion proof"]
Proof --> Leaf2
twoxhash(存储键)
twoxhash 用于在 trie 中生成存储键。
| 方面 | 详情 |
|---|---|
| 类型 | 非加密哈希 |
| 用途 | 快速进行内部键值查找 |
| 特性 | 速度快、冲突率低 |
| 不适用于 | 安全敏感的哈希(请使用 Blake2-256) |
twoxhash 显著提升了 map 查找的 trie 性能,同时避免了每次派生键时都进行加密哈希的开销。
完整的哈希/签名划分请参见 midnight-cryptography/。
状态提交流程
每个区块:
- 运行时执行交易并更新 pallet 存储。
- 计算发生变化的 trie 节点,并推导出状态根。
- Midnight Ledger 承诺与标准 Substrate 状态(
pallet-midnight)一同持久化。 - ParityDB 持久化更新后的 trie 后备存储。
sequenceDiagram
participant RT as Runtime
participant Trie as Patricia-Merkle trie
participant PM as pallet-midnight
participant DB as ParityDB
RT->>Trie: Apply storage writes (twoxhash keys)
RT->>PM: Commit ledger state
Trie->>Trie: Compute new state root
PM->>DB: Persist ledger commitment
Trie->>DB: Persist trie nodes
查询存储
| 访问路径 | 使用场景 |
|---|---|
state_getStorage(RPC) | 读取原始存储键 |
midnight_contractState(RPC) | 查询合约专属状态 |
| Indexer GraphQL | 便于应用使用的合约/事件查询 |
相关技能
midnight-onchain-logic/— 哪些内容会写入存储midnight-cryptography/— Blake2-256 与 twoxhash 的对比midnight-rpc/— 通过 JSON-RPC 读取状态midnight-transactions/— 交易如何触发存储更新
评论
支持 Markdown