tvc 0.9.0

CLI for Turnkey Verifiable Cloud
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! App configuration file format for `tvc app create`.

use std::fmt::Display;

use crate::prompts;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use thiserror::Error;

pub const MIN_SHARE_SET_THRESHOLD: u32 = 2;

/// App configuration loaded from JSON file.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppConfig {
    pub name: String,
    pub quorum_public_key: String,
    #[serde(default)]
    pub enable_egress: bool,
    #[serde(default)]
    pub manifest_set_id: Option<String>,
    #[serde(default)]
    pub manifest_set_params: Option<OperatorSetParams>,
    #[serde(default)]
    pub share_set_id: Option<String>,
    #[serde(default)]
    pub share_set_params: Option<OperatorSetParams>,
    /// Whether this app permits debug-mode deployments. Must be set at app
    /// creation and cannot be changed after. Setting this true means the app's
    /// quorum key is considered permanently insecure.
    #[serde(default)]
    pub dangerous_enable_debug_mode_deployments: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperatorSetParams {
    pub name: String,
    pub threshold: u32,
    #[serde(default)]
    pub new_operators: Vec<OperatorParams>,
    #[serde(default)]
    pub existing_operator_ids: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperatorParams {
    pub name: String,
    pub public_key: String,
}

/// Known share set public keys. This is for known share keys
/// that encrypt known operator keys. Assume the secrets are well known
pub const KNOWN_SHARE_SET_KEYS: [(&str, &str); 2] = [
    (
        "1",
        "044af8b082b9ef41a238037811a188309d8c8b00b6d49c0574538d7746d7383739e67e1107f134bc102a48301b07e7c53280decbe9c16c9fc1f19b9832018e1485048139aa5de49d9505465bcf1a879954c51ba7b258b669f4e42697088cbbca54aeb888d61e65b2602ce92ae945a0160533acc94942511f8e5b1940ed89cc8f141f",
    ),
    (
        "2",
        "04c1c4b4eb784505f167affae00e18b1521e7a0bfa3be46e6a6b43ba1f386afce48d964c885480cb197e3538fd30ebe38a07f76b6a286b37ba6d2abddbbd6c9c8304e492ca7bce95912a7b2565c8553e38cf3a4b1f858171900ed81888282db13d41e214dd6def2de2aacb1fcf92e3ae5a83e1b0ffa660fc59b9dd10e277cfd128dc",
    ),
];

/// Well known Quorum Key. This is for applications that do not need secure quorum keys
pub const KNOWN_QUORUM_KEY: &str = "04451028fc9d42cef6d8f2a3ebe17d65783c470dbc6f04663d500c12009930cf9b209e733f6ac6103cc28f07ecde2dbb55095738b828d6b7a55caf4ddf9d67f2ae047827dcd2325b8d58694c2ea14e8f1e1f8a36c84438d291ff9b1b067debdb3e2ba3822984cde8bed4de2c237bd323526da4961d368bcc63cbd2d37d00e936683e";

impl AppConfig {
    /// Generate a default template config with placeholders.
    pub fn template(operator_public_key: Option<&str>) -> Self {
        Self {
            name: "<FILL_IN_APP_NAME>".to_string(),
            quorum_public_key: KNOWN_QUORUM_KEY.to_string(),
            enable_egress: false,
            manifest_set_id: None,
            manifest_set_params: Some(OperatorSetParams {
                name: "<FILL_IN_MANIFEST_SET_NAME>".to_string(),
                threshold: 1,
                new_operators: vec![OperatorParams {
                    name: "operator-1".to_string(),
                    public_key: operator_public_key
                        .unwrap_or("<FILL_IN_OPERATOR_PUBLIC_KEY>")
                        .to_string(),
                }],
                existing_operator_ids: vec![],
            }),
            share_set_id: None,
            share_set_params: None,
            dangerous_enable_debug_mode_deployments: false,
        }
    }

    /// Get the hardcoded share set params using known share set keys.
    pub fn share_set_params() -> OperatorSetParams {
        OperatorSetParams {
            name: "dev-known-share-set".to_string(),
            threshold: 2,
            new_operators: KNOWN_SHARE_SET_KEYS
                .iter()
                .map(|(name, key)| OperatorParams {
                    name: name.to_string(),
                    public_key: key.to_string(),
                })
                .collect(),
            existing_operator_ids: vec![],
        }
    }

    /// Walk the user through any placeholder fields and fill them in.
    /// Non-placeholder fields are preserved unchanged so partial edits work.
    ///
    /// `saved_operator_public_key` is offered as the default when prompting
    /// for a `<FILL_IN>` operator public key.
    pub fn fill_interactively(&mut self, saved_operator_public_key: Option<&str>) -> Result<()> {
        if self.name.starts_with("<FILL_IN") {
            self.name = prompts::required_text("App name", None)?;
        }
        if let Some(set_params) = self.manifest_set_params.as_mut() {
            if set_params.name.starts_with("<FILL_IN") {
                set_params.name = prompts::required_text("Manifest set name", None)?;
            }
            for op in set_params.new_operators.iter_mut() {
                if op.public_key.starts_with("<FILL_IN") {
                    let prompt = format!("Operator '{}' public key", op.name);
                    op.public_key = prompts::required_text(&prompt, saved_operator_public_key)?;
                }
            }
        }
        if let Some(set_params) = self.share_set_params.as_mut() {
            if set_params.name.starts_with("<FILL_IN") {
                set_params.name = prompts::required_text("Share set name", None)?;
            }
            for op in set_params.new_operators.iter_mut() {
                if op.public_key.starts_with("<FILL_IN") {
                    let prompt = format!("Share set operator '{}' public key", op.name);
                    op.public_key = prompts::required_text(&prompt, None)?;
                }
            }
        }
        Ok(())
    }

    /// Check if config contains placeholder values.
    pub fn has_placeholders(&self) -> bool {
        self.name.starts_with("<FILL_IN")
            || self.manifest_set_params.as_ref().is_some_and(|p| {
                p.name.starts_with("<FILL_IN")
                    || p.new_operators
                        .iter()
                        .any(|o| o.public_key.starts_with("<FILL_IN"))
            })
            || self.share_set_params.as_ref().is_some_and(|p| {
                p.name.starts_with("<FILL_IN")
                    || p.new_operators
                        .iter()
                        .any(|o| o.public_key.starts_with("<FILL_IN"))
            })
    }

    pub fn validate(&self) -> Result<(), AppConfigValidationErrors> {
        let mut errors = Vec::new();

        if self.name.starts_with("<FILL_IN") {
            errors.push(AppConfigValidationError::Placeholder {
                field: "name",
                placeholder: self.name.clone(),
            });
        }

        if let Some(params) = &self.manifest_set_params {
            collect_operator_set_placeholder_errors("manifestSetParams", params, &mut errors);
        }

        if let Some(params) = &self.share_set_params {
            collect_operator_set_placeholder_errors("shareSetParams", params, &mut errors);
        }
        // TODO: use types to make this smarter
        if self.manifest_set_id.is_some() && self.manifest_set_params.is_some() {
            errors.push(AppConfigValidationError::ConflictingFields {
                first: "manifestSetId",
                second: "manifestSetParams",
            });
        }

        if self.manifest_set_id.is_none() && self.manifest_set_params.is_none() {
            errors.push(AppConfigValidationError::MissingOneOf {
                first: "manifestSetId",
                second: "manifestSetParams",
            });
        }

        if self.share_set_id.is_some() && self.share_set_params.is_some() {
            errors.push(AppConfigValidationError::ConflictingFields {
                first: "shareSetId",
                second: "shareSetParams",
            });
        }

        // It is fine if both share set id and params are none since we support a default dev share set
        if let Some(params) = &self.share_set_params
            && params.threshold < MIN_SHARE_SET_THRESHOLD
        {
            errors.push(AppConfigValidationError::ThresholdTooLow {
                field: "shareSetParams.threshold",
                minimum: MIN_SHARE_SET_THRESHOLD,
                actual: params.threshold,
            });
        }

        AppConfigValidationErrors::ok_or_errors(errors)
    }

    pub fn effective_share_set_params(&self) -> Option<OperatorSetParams> {
        if self.share_set_id.is_some() {
            None
        } else {
            Some(
                self.share_set_params
                    .clone()
                    .unwrap_or_else(Self::share_set_params),
            )
        }
    }
}

fn collect_operator_set_placeholder_errors(
    prefix: &'static str,
    params: &OperatorSetParams,
    errors: &mut Vec<AppConfigValidationError>,
) {
    if params.name.starts_with("<FILL_IN") {
        errors.push(AppConfigValidationError::Placeholder {
            field: if prefix == "manifestSetParams" {
                "manifestSetParams.name"
            } else {
                "shareSetParams.name"
            },
            placeholder: params.name.clone(),
        });
    }

    for (index, operator) in params.new_operators.iter().enumerate() {
        if operator.public_key.starts_with("<FILL_IN") {
            errors.push(AppConfigValidationError::OperatorPublicKeyPlaceholder {
                set: prefix,
                index,
                placeholder: operator.public_key.clone(),
            });
        }
    }
}

#[derive(Debug, Clone, Error)]
pub enum AppConfigValidationError {
    #[error("{field} contains placeholder value {placeholder}")]
    Placeholder {
        field: &'static str,
        placeholder: String,
    },
    #[error("{set}.newOperators[{index}].publicKey contains placeholder value {placeholder}")]
    OperatorPublicKeyPlaceholder {
        set: &'static str,
        index: usize,
        placeholder: String,
    },
    #[error("Cannot specify both {first} and {second}")]
    ConflictingFields {
        first: &'static str,
        second: &'static str,
    },
    #[error("Must specify either {first} or {second}")]
    MissingOneOf {
        first: &'static str,
        second: &'static str,
    },
    #[error("{field} must be >= {minimum}, got {actual}")]
    ThresholdTooLow {
        field: &'static str,
        minimum: u32,
        actual: u32,
    },
}

#[derive(Debug)]
pub struct AppConfigValidationErrors(Vec<AppConfigValidationError>);

impl AppConfigValidationErrors {
    // a bit of a hack, removes need for empty checks
    fn ok_or_errors(errors: Vec<AppConfigValidationError>) -> Result<(), Self> {
        if errors.is_empty() {
            return Ok(());
        }

        Err(Self(errors))
    }

    pub fn has_non_placeholder_error(&self) -> bool {
        self.0.iter().any(|e| !e.is_placeholder())
    }
}

impl AppConfigValidationError {
    pub fn is_placeholder(&self) -> bool {
        matches!(
            self,
            Self::Placeholder { .. } | Self::OperatorPublicKeyPlaceholder { .. }
        )
    }
}

impl Display for AppConfigValidationErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = self
            .0
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("; ");

        Display::fmt(&s, f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn valid_config_json() -> serde_json::Value {
        json!({
            "name": "test-app",
            "quorumPublicKey": KNOWN_QUORUM_KEY,
            "manifestSetParams": {
                "name": "manifest-set",
                "threshold": 1,
                "newOperators": [{
                    "name": "operator-1",
                    "publicKey": "operator-public-key"
                }]
            }
        })
    }

    #[test]
    fn validate_accepts_omitted_share_set_params() {
        let config: AppConfig = serde_json::from_value(valid_config_json()).unwrap();

        config.validate().unwrap();
        assert_eq!(config.effective_share_set_params().unwrap().threshold, 2);
    }

    #[test]
    fn config_deserializes_enable_egress() {
        let mut json = valid_config_json();
        json["enableEgress"] = json!(true);
        let config: AppConfig = serde_json::from_value(json).unwrap();

        assert!(config.enable_egress);
    }

    #[test]
    fn config_defaults_enable_egress_to_false() {
        let config: AppConfig = serde_json::from_value(valid_config_json()).unwrap();

        assert!(!config.enable_egress);
    }

    #[test]
    fn validate_accepts_share_set_id() {
        let mut json = valid_config_json();
        json["shareSetId"] = json!("share-set-id");
        let config: AppConfig = serde_json::from_value(json).unwrap();

        config.validate().unwrap();
        assert_eq!(config.share_set_id.as_deref(), Some("share-set-id"));
        assert!(config.effective_share_set_params().is_none());
    }

    #[test]
    fn validate_rejects_share_set_id_and_params() {
        let mut json = valid_config_json();
        json["shareSetId"] = json!("share-set-id");
        json["shareSetParams"] = json!({
            "name": "custom-share-set",
            "threshold": 2,
            "newOperators": []
        });
        let config: AppConfig = serde_json::from_value(json).unwrap();

        assert!(
            config
                .validate()
                .unwrap_err()
                .to_string()
                .contains("Cannot specify both shareSetId and shareSetParams")
        );
    }

    #[test]
    fn validate_rejects_low_share_set_threshold() {
        let mut json = valid_config_json();
        json["shareSetParams"] = json!({
            "name": "custom-share-set",
            "threshold": 1,
            "newOperators": []
        });
        let config: AppConfig = serde_json::from_value(json).unwrap();

        assert!(
            config
                .validate()
                .unwrap_err()
                .to_string()
                .contains("shareSetParams.threshold must be")
        );
    }
}