Skip to main content

vouch_core/
threshold_json.rs

1//! JSON facade for [`crate::threshold`] (FROST threshold signing).
2//!
3//! The threshold core works in typed Rust. This facade presents every step as
4//! JSON-in / JSON-out with binary fields as standard base64 strings, matching
5//! the convention the rest of the FFI-facing core uses (see
6//! [`crate::robotics_json`]), so UniFFI, the C ABI, and WASM all share one
7//! implementation instead of re-deriving the plumbing per language.
8
9#[allow(unused_imports)]
10use crate::prelude::*;
11
12use base64::{engine::general_purpose::STANDARD, Engine};
13use serde_json::{json, Value};
14
15use crate::error::{CoreError, Result};
16use crate::threshold as t;
17
18fn b64(bytes: &[u8]) -> String {
19    STANDARD.encode(bytes)
20}
21
22fn unb64(s: &str) -> Result<Vec<u8>> {
23    STANDARD
24        .decode(s)
25        .map_err(|e| CoreError::Json(format!("base64: {e}")))
26}
27
28fn parse(s: &str) -> Result<Value> {
29    serde_json::from_str(s).map_err(|e| CoreError::Json(format!("json: {e}")))
30}
31
32fn gs(v: &Value, k: &str) -> Result<String> {
33    v.get(k)
34        .and_then(|x| x.as_str())
35        .map(String::from)
36        .ok_or_else(|| CoreError::Json(format!("missing or non-string field: {k}")))
37}
38
39fn key_share_to_json(share: &t::KeyShare) -> Value {
40    json!({
41        "identifier": b64(&share.identifier),
42        "key_package": b64(&share.key_package),
43    })
44}
45
46fn key_share_from_json(v: &Value) -> Result<t::KeyShare> {
47    Ok(t::KeyShare {
48        identifier: unb64(&gs(v, "identifier")?)?,
49        key_package: unb64(&gs(v, "key_package")?)?,
50    })
51}
52
53fn group_public_key_to_json(gpk: &t::GroupPublicKey) -> Value {
54    json!({
55        "verifying_key": b64(&gpk.verifying_key),
56        "public_key_package": b64(&gpk.public_key_package),
57    })
58}
59
60fn group_public_key_from_json(v: &Value) -> Result<t::GroupPublicKey> {
61    let verifying_key_bytes = unb64(&gs(v, "verifying_key")?)?;
62    let verifying_key: [u8; 32] = verifying_key_bytes
63        .try_into()
64        .map_err(|_| CoreError::Json("verifying_key must be 32 bytes".into()))?;
65    Ok(t::GroupPublicKey {
66        verifying_key,
67        public_key_package: unb64(&gs(v, "public_key_package")?)?,
68    })
69}
70
71/// A map keyed by base64-encoded participant identifier, valued by
72/// base64-encoded bytes (a commitment or a signature share).
73fn b64_map_from_json(v: &Value) -> Result<alloc::collections::BTreeMap<Vec<u8>, Vec<u8>>> {
74    let obj = v
75        .as_object()
76        .ok_or_else(|| CoreError::Json("expected a JSON object".into()))?;
77    let mut out = alloc::collections::BTreeMap::new();
78    for (id_b64, val) in obj {
79        let val_b64 = val
80            .as_str()
81            .ok_or_else(|| CoreError::Json(format!("value for {id_b64} must be a string")))?;
82        out.insert(unb64(id_b64)?, unb64(val_b64)?);
83    }
84    Ok(out)
85}
86
87/// Mint a fresh threshold-native Ed25519 identity. Returns JSON:
88/// `{"shares": [{"identifier": b64, "key_package": b64}, ...],
89///   "group_public_key": {"verifying_key": b64, "public_key_package": b64}}`
90pub fn generate_key(min_signers: u16, max_signers: u16) -> Result<String> {
91    let result = t::generate_key(min_signers, max_signers)?;
92    let out = json!({
93        "shares": result.shares.iter().map(key_share_to_json).collect::<Vec<_>>(),
94        "group_public_key": group_public_key_to_json(&result.group_public_key),
95    });
96    Ok(out.to_string())
97}
98
99/// Round 1 for one signer. `key_share_json` is one entry from `generate_key`'s
100/// `shares` array. Returns JSON `{"nonces": b64, "commitments": b64}`. The
101/// `nonces` field is SECRET: keep it only on this signer's device, use it for
102/// exactly one `sign_share` call, then discard it.
103pub fn commit(key_share_json: &str) -> Result<String> {
104    let share = key_share_from_json(&parse(key_share_json)?)?;
105    let round1 = t::commit(&share)?;
106    let out = json!({
107        "nonces": b64(&round1.nonces),
108        "commitments": b64(&round1.commitments),
109    });
110    Ok(out.to_string())
111}
112
113/// Round 2 for one signer. `commitments_json` is a JSON object mapping each
114/// participating signer's base64 identifier to its base64 commitment
115/// (including this signer's own). Returns the base64-encoded signature share.
116pub fn sign_share(
117    message: &[u8],
118    key_share_json: &str,
119    nonces_b64: &str,
120    commitments_json: &str,
121) -> Result<String> {
122    let share = key_share_from_json(&parse(key_share_json)?)?;
123    let nonces = zeroize::Zeroizing::new(unb64(nonces_b64)?);
124    let commitments = b64_map_from_json(&parse(commitments_json)?)?;
125    let sig_share = t::sign_share(message, &share, &nonces, &commitments)?;
126    Ok(b64(&sig_share))
127}
128
129/// Combine signature shares into the final signature. `commitments_json` and
130/// `shares_json` are JSON objects mapping each signer's base64 identifier to
131/// its base64 commitment / signature share respectively.
132/// `group_public_key_json` is the `group_public_key` object from
133/// `generate_key`. Returns the raw 64-byte Ed25519 signature, verifiable with
134/// the same `verify` used for any other Vouch credential.
135pub fn aggregate(
136    message: &[u8],
137    commitments_json: &str,
138    shares_json: &str,
139    group_public_key_json: &str,
140) -> Result<Vec<u8>> {
141    let commitments = b64_map_from_json(&parse(commitments_json)?)?;
142    let shares = b64_map_from_json(&parse(shares_json)?)?;
143    let group_public_key = group_public_key_from_json(&parse(group_public_key_json)?)?;
144    let sig = t::aggregate(message, &commitments, &shares, &group_public_key)?;
145    Ok(sig.to_vec())
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn full_ceremony_round_trips_through_json() {
154        let generated_json = generate_key(2, 3).expect("generate_key");
155        let generated: Value = serde_json::from_str(&generated_json).unwrap();
156        let shares = generated["shares"].as_array().unwrap();
157        assert_eq!(shares.len(), 3);
158
159        let message = b"read did:web:files https://files/x";
160        let chosen = [&shares[0], &shares[2]];
161
162        let mut nonces_by_id = crate::collections::HashMap::new();
163        let mut commitments_obj = serde_json::Map::new();
164        for share in &chosen {
165            let round1_json = commit(&share.to_string()).expect("commit");
166            let round1: Value = serde_json::from_str(&round1_json).unwrap();
167            let id = share["identifier"].as_str().unwrap().to_string();
168            commitments_obj.insert(id.clone(), round1["commitments"].clone());
169            nonces_by_id.insert(id, round1["nonces"].as_str().unwrap().to_string());
170        }
171        let commitments_json = Value::Object(commitments_obj).to_string();
172
173        let mut shares_obj = serde_json::Map::new();
174        for share in &chosen {
175            let id = share["identifier"].as_str().unwrap().to_string();
176            let nonces_b64 = nonces_by_id.get(&id).unwrap();
177            let sig_share_b64 =
178                sign_share(message, &share.to_string(), nonces_b64, &commitments_json)
179                    .expect("sign_share");
180            shares_obj.insert(id, Value::String(sig_share_b64));
181        }
182        let shares_json = Value::Object(shares_obj).to_string();
183
184        let group_public_key_json = generated["group_public_key"].to_string();
185        let signature = aggregate(
186            message,
187            &commitments_json,
188            &shares_json,
189            &group_public_key_json,
190        )
191        .expect("aggregate");
192        assert_eq!(signature.len(), 64);
193
194        let gpk = group_public_key_from_json(&generated["group_public_key"]).unwrap();
195        let ok = crate::keys::verify(&gpk.verifying_key, message, &signature).unwrap();
196        assert!(ok);
197    }
198
199    #[test]
200    fn generate_key_rejects_bad_threshold_through_json() {
201        assert!(generate_key(1, 3).is_err());
202    }
203}