Rust IC表示无关哈希库ic-representation-independent-hash的使用,实现跨平台数据哈希一致性

Representation Independent Hash

用于计算任意Rust对象的表示无关哈希的工具库。

安装

在项目目录中运行以下Cargo命令:

cargo add ic-representation-independent-hash

或者在Cargo.toml中添加以下行:

ic-representation-independent-hash = "3.0.3"

使用示例

这是一个使用ic-representation-independent-hash库计算哈希值的完整示例:

use ic_representation_independent_hash::hash;
use serde::Serialize;

#[derive(Serialize)]
struct MyData {
    field1: u32,
    field2: String,
    field3: Vec<u8>,
}

fn main() {
    // 创建要哈希的数据
    let data = MyData {
        field1: 42,
        field2: "hello".to_string(),
        field3: vec![1, 2, 3],
    };

    // 计算表示无关哈希
    let hash = hash(&data).expect("Failed to hash data");
    
    println!("Hash: {:?}", hash);
}

完整示例demo

下面是一个更完整的示例,展示了如何计算嵌套结构的表示无关哈希:

use ic_representation_independent_hash::hash;
use serde::Serialize;

// 定义嵌套数据结构
#[derive(Serialize)]
struct Address {
    street: String,
    city: String,
    zip: u32,
}

#[derive(Serialize)]
struct User {
    id: u64,
    name: String,
    email: String,
    addresses: Vec<Address>,
    is_active: bool,
}

fn main() {
    // 创建用户数据
    let user = User {
        id: 12345,
        name: "Alice".to_string(),
        email: "alice@example.com".to_string(),
        addresses: vec![
            Address {
                street: "123 Main St".to_string(),
                city: "New York".to_string(),
                zip: 10001,
            },
            Address {
                street: "456 Oak Ave".to_string(),
                city: "San Francisco".to_string(),
                zip: 94107,
            },
        ],
        is_active: true,
    };

    // 计算表示无关哈希
    match hash(&user) {
        Ok(hash_value) => println!("Generated hash: {:?}", hash_value),
        Err(e) => eprintln!("Hashing failed: {}", e),
    }
}

元数据

  • 版本: 3.0.3
  • 许可: Apache-2.0
  • 类别: 算法, API绑定, 加密货币
  • 发布时间: 6个月前

所有者

  • dfinity/trust团队
  • dfinity-publish用户

这个库可以帮助你在不同平台间保持数据哈希的一致性,特别适用于需要跨网络进行数据验证的场景。


1 回复

Rust IC表示无关哈希库 ic-representation-independent-hash 使用指南

介绍

ic-representation-independent-hash 是一个 Rust 库,用于实现与 Internet Computer (IC) 区块链兼容的表示无关哈希计算。它确保在不同平台和环境中对相同数据进行哈希计算时能得到一致的结果,特别适用于需要与 IC 区块链交互的场景。

主要特性

  • 跨平台哈希一致性
  • 与 IC 区块链的表示无关哈希算法兼容
  • 支持多种数据类型
  • 简单易用的 API

安装

Cargo.toml 中添加依赖:

[dependencies]
ic-representation-independent-hash = "0.1"

使用方法

基本使用

use ic_representation_independent_hash::hash;

fn main() {
    let data = b"hello world";
    let hash_result = hash(data);
    println!("Hash: {:?}", hash_result);
}

哈希结构化数据

use ic_representation_independent_hash::{hash, Value};

fn main() {
    let structured_data = Value::Map(vec![
        ("name".into(), Value::String("Alice".into())),
        ("age".into(), Value::Int(30)),
        ("active".into(), Value::Bool(true)),
    ]);
    
    let hash_result = hash(&structured_data);
    println!("Structured data hash: {:?}", hash_result);
}

计算 Candid 值的哈希

use ic_representation_independent_hash::{hash_candid, CandidValue};
use candid::Encode;

fn main() {
    let candid_value = CandidValue::from_bytes(&Encode!(&42).unwrap()).unwrap();
    let hash_result = hash_candid(&candid_value);
    println!("Candid value hash: {:?}", hash_result);
}

验证哈希一致性

use ic_representation_independent_hash::hash;

fn test_hash_consistency() {
    let data1 = b"consistent data";
    let data2 = b"consistent data"; // 相同内容
    
    let hash1 = hash(data1);
    let hash2 = hash(data2);
    
    assert_eq!(hash1, hash2, "Hashes should be identical for same input");
}

高级用法

自定义哈希种子

use ic_representation_independent_hash::{hash_with_seed, DEFAULT_HASH_SEED};

fn main() {
    let data = b"custom seed data";
    let custom_seed = [0u8; 32]; // 32字节种子
    let hash1 = hash_with_seed(data, &custom_seed);
    let hash2 = hash_with_seed(data, &DEFAULT_HASH_SEED);
    
    assert_ne!(hash1, hash2, "Different seeds should produce different hashes");
}

增量哈希计算

use ic_representation_independent_hash::Hasher;

fn main() {
    let mut hasher = Hasher::new();
    hasher.update(b"part1");
    hasher.update(b"part2");
    hasher.update(b"part3");
    
    let final_hash = hasher.finish();
    println!("Incremental hash: {:?}", final_hash);
}

注意事项

  1. 确保在不同平台上使用相同版本的库以保证哈希一致性
  2. 对于结构化数据,字段顺序会影响哈希结果
  3. 浮点数的哈希可能在不同架构上表现不同,建议避免使用浮点数

完整示例

下面是一个完整的示例,展示如何在真实应用场景中使用该库:

use ic_representation_independent_hash::{hash, hash_candid, Value, CandidValue, Hasher};
use candid::Encode;
use serde::Serialize;

#[derive(Serialize)]
struct UserProfile {
    user_id: u64,
    username: String,
    is_verified: bool,
    created_at: u64,
}

fn main() {
    // 示例1: 基本哈希计算
    let message = b"IC blockchain message";
    let message_hash = hash(message);
    println!("Message hash: {:?}", message_hash);

    // 示例2: 结构化数据哈希
    let profile_data = Value::Map(vec![
        ("user_id".into(), Value::Int(12345)),
        ("username".into(), Value::String("ic_user".into())),
        ("is_verified".into(), Value::Bool(true)),
    ]);
    let profile_hash = hash(&profile_data);
    println!("Profile hash: {:?}", profile_hash);

    // 示例3: Candid值哈希
    let candid_value = CandidValue::from_bytes(&Encode!(&42u64).unwrap()).unwrap();
    let candid_hash = hash_candid(&candid_value);
    println!("Candid hash: {:?}", candid_hash);

    // 示例4: 增量哈希计算
    let mut hasher = Hasher::new();
    hasher.update(b"header");
    hasher.update(b"payload");
    hasher.update(b"footer");
    let incremental_hash = hasher.finish();
    println!("Incremental hash: {:?}", incremental_hash);

    // 示例5: 实际应用场景
    let user = UserProfile {
        user_id: 67890,
        username: "blockchain_developer".to_string(),
        is_verified: true,
        created_at: 1672531200,
    };
    
    let user_value = Value::Map(vec![
        ("user_id".into(), Value::Int(user.user_id as i64)),
        ("username".into(), Value::String(user.username)),
        ("is_verified".into(), Value::Bool(user.is_verified)),
        ("created_at".into(), Value::Int(user.created_at as i64)),
    ]);
    
    let user_hash = hash(&user_value);
    println!("User profile hash: {:?}", user_hash);
    
    // 验证哈希一致性
    let data1 = b"consistency check";
    let data2 = b"consistency check";
    assert_eq!(hash(data1), hash(data2), "Hashes should be equal for identical data");
}

这个库特别适合需要在不同环境(如客户端、服务器和区块链智能合约)之间验证数据一致性的应用场景。

回到顶部