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