Rust认证映射库ic-certified-map的使用,为区块链和分布式应用提供高效可验证的数据结构
Rust认证映射库ic-certified-map的使用,为区块链和分布式应用提供高效可验证的数据结构
特性
-
增量认证
容器可以存储数千个条目,同时保持相对较低的认证成本。 -
缺席证明
如果请求的键不在映射中,返回的树结构允许调用者验证这一事实。 -
相对较小的Merkle证明
证书的大小开销为O(log N),其中N是映射中的条目数量。
实现细节
容器使用增强的红黑二叉搜索树来存储条目。搜索树的每个节点都注释了从该节点为根的子树构建的哈希树的根哈希。每次旋转或修改树时,相应的哈希会在O(1)时间内重新计算。
安装
在项目目录中运行以下Cargo命令:
cargo add ic-certified-map
或者在Cargo.toml中添加以下行:
ic-certified-map = "0.4.0"
完整示例代码
use ic_certified_map::{Hash, RbTree};
use std::borrow::Cow;
fn main() {
// 创建一个新的红黑树实例
let mut tree = RbTree::new();
// 插入一些键值对
tree.insert(Cow::Borrowed("key1"), Cow::Borrowed("value1"));
tree.insert(Cow::Borrowed("key2"), Cow::Borrowed("value2"));
tree.insert(Cow::Borrowed("key3"), Cow::Borrowed("value3"));
// 获取根哈希(用于认证)
let root_hash: Hash = tree.root_hash();
println!("Root hash: {:?}", root_hash);
// 查询一个存在的键
if let Some(value) = tree.get(&"key2") {
println!("Found value: {}", value);
}
// 查询一个不存在的键
if tree.get(&"nonexistent").is_none() {
println!("Key not found - this can be cryptographically proven");
}
// 删除一个键
tree.delete(&"key1");
// 验证树的状态
println!("New root hash after deletion: {:?}", tree.root_hash());
}
使用场景
这个库特别适合以下场景:
- 区块链应用:需要高效验证状态数据的存在或不存在
- 分布式系统:需要向客户端提供可验证的查询结果
- 智能合约:需要存储大量数据同时保持可验证性
性能特点
- 插入、删除和查找操作的时间复杂度为O(log N)
- 根哈希计算在每次修改后自动维护
- 证明生成高效,适合高频查询场景
该库由DFinity团队维护,是互联网计算机(Internet Computer)生态系统的核心组件之一。
扩展示例代码
use ic_certified_map::{Hash, RbTree};
use std::borrow::Cow;
// 自定义数据结构示例
#[derive(Debug)]
struct CustomData {
id: u32,
name: String,
}
fn main() {
// 创建一个新的红黑树实例
let mut tree = RbTree::new();
// 插入基本类型的键值对
tree.insert(Cow::Borrowed("basic_key"), Cow::Borrowed("basic_value"));
// 插入自定义数据
let custom_data = CustomData {
id: 42,
name: "Test".to_string(),
};
tree.insert(
Cow::Borrowed("custom_key"),
Cow::Owned(serde_json::to_string(&custom_data).unwrap())
);
// 批量插入数据
let data = vec![
("batch1", "value1"),
("batch2", "value2"),
("batch3", "value3"),
];
for (k, v) in data {
tree.insert(Cow::Borrowed(k), Cow::Borrowed(v));
}
// 获取并打印根哈希
println!("Current root hash: {:?}", tree.root_hash());
// 范围查询示例
let start = "batch2";
let end = "custom_key";
for (key, value) in tree.range(start..=end) {
println!("Range item - Key: {}, Value: {}", key, value);
}
// 验证数据存在性
if let Some(data) = tree.get(&"custom_key") {
let parsed: CustomData = serde_json::from_str(&data).unwrap();
println!("Parsed custom data: {:?}", parsed);
}
// 生成Merkle证明(伪代码示例)
// let proof = tree.generate_proof(&"batch2");
// println!("Merkle proof: {:?}", proof);
// 验证树中不存在的键
assert!(tree.get(&"non_existent_key").is_none());
// 删除操作
tree.delete(&"basic_key");
println!("Root hash after deletion: {:?}", tree.root_hash());
// 清空树
tree.clear();
assert!(tree.is_empty());
}
注释说明
- 示例展示了基本CRUD操作和自定义数据类型的使用
Cow
类型用于高效处理借用和拥有的数据- 范围查询演示了如何遍历特定区间的键
- 注释中的Merkle证明生成是伪代码,实际API可能有所不同
- 实际应用中,数据结构需要实现序列化/反序列化
这个扩展示例展示了更丰富的使用场景,包括处理自定义数据类型、批量操作和范围查询等高级功能。
1 回复
Rust认证映射库ic-certified-map使用指南
ic-certified-map是一个为区块链和分布式应用设计的Rust库,提供了高效可验证的数据结构实现。它特别适用于需要数据认证的场景,如智能合约和分布式系统。
主要特性
- 提供可验证的键值存储
- 支持高效的成员证明
- 专为区块链环境优化
- 与Internet Computer(IC)生态良好兼容
- 内存高效的设计
安装方法
在Cargo.toml中添加依赖:
[dependencies]
ic-certified-map = "0.5"
基本使用方法
创建和插入数据
use ic_certified_map::{RbTree, Hash};
let mut map = RbTree::new();
map.insert(b"key1", b"value1");
map.insert(b"key2", b"value2");
生成认证证明
let witness = map.witness(b"key1");
let root_hash = map.root_hash();
验证证明
if witness.verify(root_hash, b"key1", b"value1") {
println!("验证成功!");
} else {
println!("验证失败!");
}
高级用法
批量操作
let entries = vec![
(b"key3".to_vec(), b"value3".to_vec()),
(b"key4".to_vec(), b"value4".to_vec()),
];
let mut map = RbTree::new();
map.insert_all(entries);
与Internet Computer集成
use ic_cdk::api;
use ic_certified_map::{RbTree, Hash};
#[ic_cdk::update]
fn store_data(key: Vec<u8>, value: Vec<u8>) {
let mut map: RbTree<Vec<u8>, Vec<u8>> = api::data_certificate()
.and_then(|cert| api::get_certified_data(&cert))
.unwrap_or_else(RbTree::new);
map.insert(key, value);
api::set_certified_data(&map.root_hash());
}
性能考虑
ic-certified-map使用红黑树实现,保证了O(log n)的查询、插入和删除时间复杂度。对于需要频繁更新的场景,建议:
- 批量处理更新操作
- 定期重建树以减少碎片
- 考虑使用更简单的数据结构如果不需要所有特性
实际应用示例
区块链状态存储
use ic_certified_map::{RbTree, Hash};
struct BlockchainState {
accounts: RbTree<Vec<u8>, Vec<u8>>,
contracts: RbTree<Vec<u8>, Vec<u8>>,
}
impl BlockchainState {
pub fn new() -> Self {
Self {
accounts: RbTree::new(),
contracts: RbTree::new(),
}
}
pub fn update_account(&mut self, address: Vec<u8>, balance: Vec<u8>) {
self.accounts.insert(address, balance);
}
pub fn get_account_proof(&self, address: &[u8]) -> Option<(Vec<u8>, Hash)> {
self.accounts
.get(address)
.map(|value| (value.clone(), self.accounts.witness(address)))
}
}
完整示例代码
use ic_certified_map::{RbTree, Hash};
use serde::{Serialize, Deserialize};
// 定义一个简单的区块链账户系统
#[derive(Debug, Default)]
struct Blockchain {
state: BlockchainState,
}
#[derive(Debug, Default)]
struct BlockchainState {
accounts: RbTree<Vec<u8>, Vec<u8>>,
transactions: RbTree<Vec<u8>, Transaction>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Transaction {
from: Vec<u8>,
to: Vec<u8>,
amount: u64,
timestamp: u64,
}
impl Blockchain {
// 创建新区块链
pub fn new() -> Self {
Self::default()
}
// 更新账户余额
pub fn update_balance(&mut self, address: Vec<u8>, balance: Vec<u8>) {
self.state.accounts.insert(address, balance);
}
// 添加交易
pub fn add_transaction(&mut self, tx_id: Vec<u8>, tx: Transaction) {
self.state.transactions.insert(tx_id, tx);
}
// 获取账户证明
pub fn get_account_proof(&self, address: &[u8]) -> Option<(Vec<u8>, Hash)> {
self.state.accounts
.get(address)
.map(|value| (value.clone(), self.state.accounts.witness(address)))
}
// 获取交易证明
pub fn get_transaction_proof(&self, tx_id: &[u8]) -> Option<(Transaction, Hash)> {
self.state.transactions
.get(tx_id)
.map(|value| (value.clone(), self.state.transactions.witness(tx_id)))
}
// 获取状态根哈希
pub fn get_root_hashes(&self) -> (Hash, Hash) {
(
self.state.accounts.root_hash(),
self.state.transactions.root_hash()
)
}
}
fn main() {
// 初始化区块链
let mut blockchain = Blockchain::new();
// 添加账户
blockchain.update_balance(b"alice".to_vec(), b"100".to_vec());
blockchain.update_balance(b"bob".to_vec(), b"50".to_vec());
// 添加交易
let tx1 = Transaction {
from: b"alice".to_vec(),
to: b"bob".to_vec(),
amount: 10,
timestamp: 123456789,
};
blockchain.add_transaction(b"tx1".to_vec(), tx1);
// 获取账户证明并验证
if let Some((balance, witness)) = blockchain.get_account_proof(b"alice") {
let (accounts_root, _) = blockchain.get_root_hashes();
if witness.verify(accounts_root, b"alice", &balance) {
println!("Alice账户验证成功,余额: {:?}", String::from_utf8_lossy(&balance));
}
}
// 获取交易证明并验证
if let Some((tx, witness)) = blockchain.get_transaction_proof(b"tx1") {
let (_, tx_root) = blockchain.get_root_hashes();
let tx_bytes = bincode::serialize(&tx).unwrap();
if witness.verify(tx_root, b"tx1", &tx_bytes) {
println!("交易验证成功: {:?}", tx);
}
}
}
ic-certified-map为需要数据认证的分布式应用提供了强大而高效的工具,特别适合区块链和智能合约开发场景。