Compact标准库 compact-core:standard-library

Compact标准库是区块链智能合约开发的核心内置模块,提供加密函数(如持久哈希、椭圆曲线运算)、工具类型(Maybe、Either)、代币操作(铸造、发送、接收、合并)和时间函数(区块时间、时间约束)。适用于零知识证明电路开发、DeFi应用、隐私保护交易和时间敏感型智能合约。关键词:区块链开发、智能合约、零知识证明、加密算法、代币系统、时间锁、Compact语言、隐私计算。

智能合约 0 次安装 0 次浏览 更新于 2/26/2026

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());
    // 执行提款操作...
}

参考

示例