公平随机与抽签见证

属于 kxed 全栈 Rust 后端框架生态:官网 | 在线文档 | 源码仓库 | 主包 crates.io

基于操作系统密码学随机源(getrandom)提供无取模偏差的公平洗牌、不放回随机抽取,以及基于 blake3 的先承诺后揭示(Commit-Reveal)公开可验证抽签原语。本模块是无配置、无生命周期的纯函数库,无需在 App 上注册插件,在 Procedure、Task 或 Resident 中直接调用即可。

快速接入#

在 Cargo.toml 开启主包 kxed 的 draw 特性(或独立依赖 kxed-plugins = { version = "0.0.5-alpha", features = ["draw"] }):

TOML
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["draw"] }

在业务 Procedure 中直接从候选池公平抽取中奖名单:

Rust
use kxed::plugins::draw::pick_without_replacement;
use kxed::prelude::*;

#[derive(Debug, Serialize, Deserialize, Validate, ToSchema)]
#[garde(allow_unvalidated)]
pub struct DrawInput {
    pub candidates: Vec<String>,
    pub count: usize,
}

#[mutation(name = "lottery.draw", post = "/api/lottery/draw")]
pub async fn draw_winners(_ctx: &AppCtx, input: DrawInput) -> Result<Vec<String>, AppErr> {
    let winners = pick_without_replacement(&input.candidates, input.count)
        .map_err(|err| AppErr::unprocessable(err.to_string()))?;
    Ok(winners)
}

核心用法#

无偏洗牌与不放回抽取#

Rust
use kxed_plugins::draw::{pick_without_replacement, shuffle, DrawError};

fn deal() -> Result<(Vec<u8>, Vec<&'static str>), DrawError> {
    let mut deck: Vec<u8> = (0..52).collect();
    shuffle(&mut deck)?;
    let winners = pick_without_replacement(&["ana", "bo", "cy", "dee", "eli"], 2)?;
    Ok((deck, winners))
}
  • 严格等概率无偏差:shuffle(&mut slice) 采用正向 Fisher-Yates 洗牌,每一步通过拒绝采样生成 [0, n) 均匀整数,彻底消除取模偏差;批量按块读取系统随机源(洗 52 张牌仅需 2 次系统调用)。
  • 低内存大池抽取:pick_without_replacement(&pool, k) 只执行前 k 步交换并仅记录被置换的索引,内存开销只随抽取数 k 而非总候选池大小增长(当 k > pool.len() 时返回 DrawError::PoolTooSmall;系统熵源故障返回 DrawError::Entropy,绝不退回伪随机数)。

可插拔熵源#

需要接入外部硬件随机源、独立熵池、统计检测样本采集或确定性测试桩时,可实现 EntropySource trait,并通过对应注入入口替代默认的 OsEntropy:

Rust
use kxed_plugins::draw::{
    draw_bytes_with, pick_without_replacement_with, shuffle_with, DrawError, EntropySource,
    OsEntropy, Seed,
};

struct CustomEntropy;

impl EntropySource for CustomEntropy {
    fn fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), DrawError> {
        OsEntropy.fill_bytes(dest)
    }
}

fn draw_with_custom_source() -> Result<(), DrawError> {
    let mut source = CustomEntropy;
    let mut deck: Vec<u8> = (0..52).collect();
    shuffle_with(&mut deck, &mut source)?;
    let _hand = pick_without_replacement_with(&deck, 5, &mut source)?;
    let _seed = Seed::from_entropy(&mut source)?;
    let _sample = draw_bytes_with(64, &mut source)?;
    Ok(())
}
  • OsEntropy 是基于 getrandom 的默认实现,与无后缀的 shuffle、pick_without_replacement、Seed::random 行为完全一致。
  • 任意 EntropySource::fill_bytes 返回错误时,所有注入入口立即中止并向上返回 DrawError::Entropy(fail-closed),不会静默回退到其他随机源。

Commit-Reveal 公开核验见证#

针对棋牌发牌、公开抽奖等需要向参与者自证「开局前结果已锁定、中途未暗箱篡改」的场景,使用 Commitment 与 Reveal:

  1. 开局前公布承诺:生成秘密随机种子 Seed::random()?,调用 Commitment::new(seed) 得到公开承诺哈希 commitment(64 位十六进制字符串)下发给客户端,同时在服务端安全保存 reveal。
  2. 用揭示流执行抽取:调用确定性的 reveal.shuffle 或 reveal.pick_without_replacement 产出结果。
  3. 结束后公开核验:公开 reveal.to_hex(),任何第三方调用 commitment.verify(&reveal, &pool, &result) 即可复算核对:
Rust
use kxed_plugins::draw::{Commitment, DrawError, Reveal, Seed};

fn round() -> Result<(), DrawError> {
    let deck: Vec<u8> = (0..52).collect();
    let (commitment, reveal) = Commitment::new(Seed::random()?);
    let published = commitment.to_string();
    let hand = reveal.pick_without_replacement(&deck, 3)?;
    let revealed = reveal.to_hex();

    let checked: Commitment = published.parse()?;
    checked.verify(&Reveal::from_hex(&revealed)?, &deck, &hand)?;
    Ok(())
}

安全与兼容保障:

  • Seed 与 Reveal 的 Debug 实现已脱敏,防止开局前意外打入日志泄露。
  • 承诺与随机流均采用带版本域分离的 blake3 派生函数,跨平台、跨后续框架升级保持逐位确定性可复算;篡改种子返回 DrawError::RevealMismatch,篡改候选池顺序或结果返回 DrawError::ResultMismatch。承诺与揭示字符串落在哪张业务表由应用自行决定。