name: compact-core:standard-library
description: 当从CompactStandardLibrary导入时使用,涉及加密函数(persistentHash、persistentCommit、ecAdd、ecMul)、工具类型(Maybe、Either)、代币操作(mintToken、send、receive、mergeCoin)或时间函数(blockTime、blockTimeBefore、blockTimeAfter)。
Compact 标准库
CompactStandardLibrary 完整参考文档 - 提供加密函数、工具类型、代币操作和时间函数的内置模块。
导入
import { persistentHash, Maybe, mintToken, blockTime } from "CompactStandardLibrary";
快速参考
加密函数
| 函数 |
安全? |
用途 |
persistentCommit(value) |
是 |
创建带随机数的隐藏承诺(跨交易稳定) |
transientCommit(value) |
是 |
创建带随机数的隐藏承诺(交易本地) |
persistentHash(domain, value) |
否 |
领域分离哈希(跨交易稳定) |
transientHash(domain, value) |
否 |
领域分离哈希(交易本地) |
ecAdd(p1, p2) |
- |
椭圆曲线点加法 |
ecMul(scalar, point) |
- |
椭圆曲线标量乘法 |
安全与不安全:承诺函数包含随机数,使其具有隐藏性。哈希函数不包含随机数 - 如果输入熵值较低,哈希可能被暴力破解。
工具类型
| 类型 |
用途 |
变体 |
Maybe<T> |
可选值 |
Some(T)、None |
Either<L, R> |
结果/选择 |
Left(L)、Right(R) |
代币操作
| 函数 |
用途 |
mintToken(info) |
创建新代币 |
send(coin, recipient) |
发送代币到地址 |
receive() |
在电路中接收代币 |
mergeCoin(coins) |
合并多个代币 |
时间函数
| 函数 |
用途 |
blockTime() |
当前区块时间戳 |
blockTimeBefore(time) |
断言当前时间 < 时间 |
blockTimeAfter(time) |
断言当前时间 > 时间 |
常见模式
安全承诺
import { persistentCommit } from "CompactStandardLibrary";
witness get_secret(): Field;
export circuit commit_secret(): Bytes<32> {
const secret = get_secret();
// 安全:承诺隐藏了秘密
return persistentCommit(secret);
}
零知识证明无效器生成
import { persistentHash } from "CompactStandardLibrary";
witness get_secret(): Field;
export circuit generate_nullifier(): Bytes<32> {
const secret = get_secret();
// 不安全但有意为之:无效器应是确定性的
return persistentHash("nullifier", secret);
}
可选值处理
import { Maybe } from "CompactStandardLibrary";
ledger values: Map<Bytes<32>, Field>;
export circuit get_or_default(key: Bytes<32>): Field {
const result = values.lookup(key);
return if result is Maybe::Some(v) { v } else { 0 };
}
时间锁定操作
import { blockTime, blockTimeAfter } from "CompactStandardLibrary";
ledger unlock_time: Cell<Uint<64>>;
export circuit withdraw(): [] {
// 如果当前区块时间 <= 解锁时间则失败
blockTimeAfter(unlock_time.read());
// 执行提款操作...
}
参考
- 加密函数 - 哈希、承诺、椭圆曲线操作
- 工具类型 - Maybe、Either模式
- 代币操作 - mintToken、send、receive、mergeCoin
- 时间函数 - blockTime和时间约束
示例