forked from sine-fdn/tandem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
619 lines (570 loc) · 19.4 KB
/
lib.rs
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! HTTP client for the Tandem SMPC engine.
//!
//! This crate provides an HTTP client acting as the `evaluator` and running the Tandem Multi-Party
//! Computation engine. An HTTP server is expected to act as the `contributor`.
//!
//! This crate provides a CLI client, as well as functions targeting WebAssembly to provide an easy
//! integration of the Tandem engine with JavaScript.
//!
//! This crate additionally includes an interactive notebook (provided by `index.html`) to run and
//! test Garble programs during development.
#![deny(unsafe_code)]
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
// otherwise wasm_bindgen causes a clippy warning, see
// https://github.com/rustwasm/wasm-bindgen/issues/2774
#![allow(clippy::unused_unit)]
use msg_queue::{MessageId, MsgQueue};
use rand_chacha::{rand_core::SeedableRng, ChaCha20Rng};
use reqwest::Response;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fmt};
use tandem::{states::Msg, Circuit, CircuitBlake3Hash};
use tandem_garble_interop::{
check_program, compile_program, deserialize_output, parse_input, Role, TypedCircuit,
};
pub use tandem_garble_interop::{Literal, VariantLiteral};
use url::Url;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
use self::ValidationError::*;
mod msg_queue;
/// An MPC program that was type-checked and can be executed by the Tandem engine.
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Debug, Clone)]
pub struct MpcProgram {
source_code: String,
function_name: String,
ast: tandem_garble_interop::TypedProgram,
circuit: tandem_garble_interop::TypedCircuit,
}
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl MpcProgram {
/// Type-checks the specified function, returning a compiled program.
#[cfg_attr(target_arch = "wasm32", wasm_bindgen(constructor))]
pub fn new(source_code: String, function_name: String) -> Result<MpcProgram, Error> {
let source_code = source_code.trim().to_string();
let ast = check_program(&source_code).map_err(GarbleCompileTimeError)?;
let circuit = compile_program(&ast, &function_name).map_err(GarbleCompileTimeError)?;
if circuit.fn_def.params.len() != 2 {
return Err(ValidationError::GarbleProgramIsNoTwoPartyFunction.into());
}
Ok(Self {
source_code,
function_name,
ast,
circuit,
})
}
/// Returns the number of gates in the circuit as a formatted string.
///
/// E.g. "79k gates (XOR: 44k, NOT: 13k, AND: 21k)"
pub fn report_gates(&self) -> String {
self.circuit.info_about_gates.to_string()
}
}
/// Stores data (either inputs or output) in an Tandem-compatible format.
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MpcData {
literal: Literal,
}
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl MpcData {
/// Parses and type-checks a Garble string literal as MpcData.
/// ```
/// // Garble program stored as a string.
/// let source_code = "pub fn card_guess(house: Card, player: Card) -> bool {
/// house == player
/// }
///
/// struct Card {
/// suit: Suit,
/// value: Value,
/// }
//
/// enum Suit {
/// Diamonds,
/// Clubs,
/// Hearts,
/// Spades,
/// }
///
/// enum Value {
/// Jack,
/// Queen,
/// King,
/// }";
///
/// let card_guess_program =
/// tandem_http_client::MpcProgram::new(source_code.to_string(), "card_guess".to_string()).unwrap();
///
/// let player_card_string = "Card {suit: Suit::Diamonds, value: Value::Jack}";
///
/// let player_card =
/// tandem_http_client::MpcData::from_string(&card_guess_program, player_card_string.to_string())
/// .unwrap();
///
/// assert_eq!(
/// player_card.to_literal_string(),
/// "Card {suit: Suit::Diamonds, value: Value::Jack}"
/// );
/// ```
pub fn from_string(program: &MpcProgram, input: String) -> Result<MpcData, Error> {
let literal = parse_input(
Role::Evaluator,
&program.ast,
&program.circuit.fn_def,
&input,
)
.map_err(GarbleCompileTimeError)?;
Ok(MpcData { literal })
}
/// Type-checks a Garble literal, returning it as MpcData.
/// ```
///
/// use tandem_http_client::{Literal, VariantLiteral};
///
/// let source_code = "pub fn card_guess(house: Card, player: Card) -> bool {
/// house == player
/// }
///
/// pub struct Card {
/// suit: Suit,
/// value: Value,
/// }
///
/// enum Suit {
/// Diamonds,
/// Clubs,
/// Hearts,
/// Spades,
/// }
///
/// enum Value {
/// Jack,
/// Queen,
/// King,
/// }";
///
/// let player_card_literal = Literal::Struct(
/// "Card".to_string(),
/// vec![
/// (
/// "suit".to_string(),
/// Literal::Enum(
/// "Suit".to_string(),
/// "Diamonds".to_string(),
/// VariantLiteral::Unit,
/// ),
/// ),
/// (
/// "value".to_string(),
/// Literal::Enum(
/// "Value".to_string(),
/// "Jack".to_string(),
/// VariantLiteral::Unit,
/// ),
/// ),
/// ],
/// );
///
/// let card_guess_program =
/// tandem_http_client::MpcProgram::new(source_code.to_string(), "card_guess".to_string()).unwrap();
///
/// let player_card =
/// tandem_http_client::MpcData::from_literal(&card_guess_program, player_card_literal)
/// .unwrap();
///
/// assert_eq!(
/// player_card.to_literal_string(),
/// "Card {suit: Suit::Diamonds, value: Value::Jack}"
/// );
/// ```
#[cfg(not(target_arch = "wasm32"))]
pub fn from_literal(program: &MpcProgram, literal: Literal) -> Result<MpcData, Error> {
let expected_type =
tandem_garble_interop::input_type(Role::Evaluator, &program.circuit.fn_def);
if !literal.is_of_type(&program.ast, expected_type) {
return Err(Error::ValidationError(
ValidationError::GarbleCompileTimeError(format!(
"Input literal is not of the type {expected_type}"
)),
));
}
Ok(MpcData { literal })
}
/// Parses and type-checks a Garble literal in its JSON representation as MpcData.
/// ```
/// // Garble program stored as a string.
/// let source_code = "pub fn card_guess(house: Card, player: Card) -> bool {
/// house == player
/// }
///
/// struct Card {
/// suit: Suit,
/// value: Value,
/// }
///
/// enum Suit {
/// Diamonds,
/// Clubs,
/// Hearts,
/// Spades,
/// }
///
/// enum Value {
/// Jack,
/// Queen,
/// King,
/// }";
///
/// let card_game_program =
/// tandem_http_client::MpcProgram::new(source_code.to_string(), "card_game".to_string()).unwrap();
///
/// let json_string = "{
/// \"Struct\": [
/// \"Card\",
/// [
/// [
/// \"suit\",
/// {
/// \"Enum\": [
/// \"Suit\",
/// \"Diamonds\",
/// \"Unit\"
/// ]
/// }
/// ],
/// [
/// \"value\",
/// {
/// \"Enum\": [
/// \"Value\",
/// \"Jack\",
/// \"Unit\"
/// ]
/// }
/// ]
/// ]
/// ]
/// }";
///
/// let js_value_literal = serde_json::from_str(json_string);
///
/// let player_card = tandem_http_client::MpcData::from_object(&card_guess_program, js_value_literal);
///
/// assert_eq!(
/// player_card.to_literal_string(),
/// "Card {suit: Suit::Diamonds, value: Value::Jack}"
/// );
/// ```
///
#[cfg(target_arch = "wasm32")]
pub fn from_object(program: &MpcProgram, literal: JsValue) -> Result<MpcData, Error> {
let literal: Literal =
serde_wasm_bindgen::from_value(literal).map_err(|e| Error::JsonError(e.to_string()))?;
let expected_type =
tandem_garble_interop::input_type(Role::Evaluator, &program.circuit.fn_def);
if !literal.is_of_type(&program.ast, &expected_type) {
return Err(Error::ValidationError(
ValidationError::GarbleCompileTimeError(format!(
"Input literal is not of the type {expected_type}"
)),
));
}
Ok(MpcData { literal })
}
/// Returns MpcData as a Garble literal string.
///
/// See [`MpcData::from_string`] for the format of the literal string returned here.
pub fn to_literal_string(&self) -> String {
format!("{}", self.literal)
}
/// Returns MpcData as a Garble literal in its JSON representation.
///
/// See [`MpcData::from_object`] for the format of the JsValue returned here.
#[cfg(target_arch = "wasm32")]
pub fn to_literal(&self) -> Result<JsValue, serde_wasm_bindgen::Error> {
serde_wasm_bindgen::to_value(&self.literal)
}
}
/// Computes the specified program using Multi-Party Computation, keeping the input private.
///
/// A Tandem server must be running at the specified url, to provide the contributor's input.
///
/// The client can send plaintext metadata to the server, to influence the server's choice of the
/// input.
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
pub async fn compute(
url: String,
plaintext_metadata: String,
program: MpcProgram,
input: MpcData,
) -> Result<MpcData, Error> {
let url = Url::parse(&url)?;
let my_input = input.literal.as_bits(&program.ast);
let expected_input_len = program
.circuit
.gates
.gates()
.iter()
.filter(|&gate| gate == &tandem::Gate::InEval)
.count();
if expected_input_len != my_input.len() {
return Err(ValidationError::InvalidInput.into());
}
let client = TandemClient::new(&url);
let TypedCircuit { gates, fn_def, .. } = program.circuit;
let session = client
.new_session(
&gates,
program.source_code.clone(),
program.function_name.clone(),
plaintext_metadata,
)
.await?;
let result = session.evaluate(gates, my_input).await?;
let literal =
deserialize_output(&program.ast, &fn_def, &result).map_err(GarbleCompileTimeError)?;
Ok(MpcData { literal })
}
type MessageLog = Vec<(Msg, MessageId)>;
#[derive(Debug)]
struct TandemClient {
url: Url,
}
struct TandemSession {
url: Url,
request_headers: HashMap<String, String>,
}
#[derive(Serialize, Debug)]
struct NewSession {
plaintext_metadata: String,
program: String,
function: String,
circuit_hash: CircuitBlake3Hash,
client_version: String,
}
#[derive(Deserialize, Debug, PartialEq, Eq)]
struct EngineCreationResult {
engine_id: String,
request_headers: HashMap<String, String>,
server_version: String,
}
impl TandemClient {
fn new(url: &Url) -> Self {
Self { url: url.clone() }
}
async fn new_session<'a, 'b>(
&'a self,
circuit: &Circuit,
source_code: String,
function: String,
plaintext_metadata: String,
) -> Result<TandemSession, Error> {
let client_version = env!("CARGO_PKG_VERSION").to_string();
let req = NewSession {
plaintext_metadata,
program: source_code,
function,
circuit_hash: circuit.blake3_hash(),
client_version: client_version.clone(),
};
let EngineCreationResult {
engine_id,
request_headers,
server_version: _server_version,
} = send_new_session(self.url.clone(), &req).await?;
let url = self.url.join(&engine_id)?;
Ok(TandemSession {
url,
request_headers,
})
}
}
impl TandemSession {
async fn evaluate(self, circuit: Circuit, input: Vec<bool>) -> Result<Vec<bool>, Error> {
let mut context = MsgQueue::new();
let mut evaluator =
tandem::states::Evaluator::new(circuit, input, ChaCha20Rng::from_entropy())?;
let mut last_durably_received_offset: Option<MessageId> = None;
let mut steps_remaining = evaluator.steps();
loop {
let messages: Vec<(&Msg, MessageId)> = context.msgs_iter().collect();
let (upstream_msgs, server_commited_offset) =
self.dialog(last_durably_received_offset, &messages).await?;
if messages.last().map(|v| v.1) != server_commited_offset {
return Err(Error::MessageOffsetMismatch);
}
if let Some(last_durably_received_offset) = server_commited_offset {
context.flush_queue(last_durably_received_offset);
}
for (msg, server_offset) in &upstream_msgs {
if *server_offset != last_durably_received_offset.map(|o| o + 1).unwrap_or(0) {
return Err(Error::MessageOffsetMismatch);
}
if steps_remaining > 0 {
let (next_state, msg) = evaluator.run(msg)?;
evaluator = next_state;
steps_remaining -= 1;
context.send(msg);
} else {
return Ok(evaluator.output(msg)?);
}
last_durably_received_offset = Some(*server_offset);
}
}
}
async fn dialog(
&self,
last_durably_received_offset: Option<u32>,
messages: &[(&Msg, MessageId)],
) -> Result<(MessageLog, Option<MessageId>), Error> {
send_msgs(
self.url.clone(),
&self.request_headers,
last_durably_received_offset,
messages,
)
.await
}
}
async fn send_new_session(url: Url, session: &NewSession) -> Result<EngineCreationResult, Error> {
let client = reqwest::Client::new();
let resp = client.post(url).json(session).send().await?;
let resp = resp_or_err(resp).await?;
Ok(resp.json::<EngineCreationResult>().await?)
}
async fn send_msgs(
url: Url,
request_headers: &HashMap<String, String>,
last_durably_received_offset: Option<u32>,
msgs: &[(&Msg, MessageId)],
) -> Result<(MessageLog, Option<MessageId>), Error> {
let client = reqwest::Client::new();
let body = bincode::serialize(&(last_durably_received_offset, msgs))?;
let mut req = client.post(url).body(body);
for (k, v) in request_headers.iter() {
req = req.header(k, v);
}
let resp = req.send().await?;
let resp = resp_or_err(resp).await?;
Ok(bincode::deserialize(&resp.bytes().await?)?)
}
async fn resp_or_err(resp: Response) -> Result<Response, Error> {
if resp.status().is_success() {
Ok(resp)
} else {
let e = resp.text().await?;
let e = match serde_json::from_str::<ErrorJson>(&e) {
Ok(ErrorJson { error, args }) => format!("{error}: {args}"),
Err(_) => e,
};
Err(Error::ServerError(e))
}
}
#[derive(Deserialize)]
struct ErrorJson {
error: String,
args: String,
}
/// Errors occurring during the validation or the execution of the MPC protocol.
#[derive(Debug)]
pub enum Error {
/// An error occurred on the server side.
ServerError(String),
/// An error occurred while trying to send a request to the server.
ReqwestError(reqwest::Error),
/// The provided JSON is not a valid Garble literal.
JsonError(String),
/// The provided URL is invalid.
ParseError(url::ParseError),
/// The MPC program or the input is invalid.
ValidationError(ValidationError),
/// An error occurred during the client's execution of the MPC protocol.
TandemError(tandem::Error),
/// A message could not be serialized/deserialized.
BincodeError,
/// The client's message id did not match the server's message id.
MessageOffsetMismatch,
}
impl From<bincode::Error> for Error {
fn from(_: bincode::Error) -> Self {
Self::BincodeError
}
}
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Self {
Self::ReqwestError(e)
}
}
impl From<url::ParseError> for Error {
fn from(e: url::ParseError) -> Self {
Self::ParseError(e)
}
}
impl From<ValidationError> for Error {
fn from(e: ValidationError) -> Self {
Self::ValidationError(e)
}
}
impl From<tandem::Error> for Error {
fn from(e: tandem::Error) -> Self {
Self::TandemError(e)
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::ValidationError(e) => write!(f, "The MPC program or the input is invalid: {e}"),
Error::ServerError(e) => write!(f, "An error occurred on the server side: {e}"),
Error::ReqwestError(e) => write!(
f,
"An error occurred while trying to send a request to the server: {e}"
),
Error::JsonError(e) => {
write!(f, "The provided JSON is not a valid Garble literal: {e}")
}
Error::ParseError(e) => write!(f, "The provided URL is invalid: {e}"),
Error::TandemError(e) => write!(
f,
"An error occurred during the client's execution of the MPC protocol: {e}"
),
Error::BincodeError => write!(f, "A message could not be serialized/deserialized."),
Error::MessageOffsetMismatch => write!(
f,
"The client's message id did not match the server's message id."
),
}
}
}
impl std::error::Error for Error {}
#[cfg(target_arch = "wasm32")]
impl From<Error> for JsValue {
fn from(e: Error) -> Self {
JsValue::from_str(&format!("{e}"))
}
}
/// An error that occurred during validation, before the MPC execution.
#[derive(Debug, PartialEq, Eq)]
pub enum ValidationError {
/// The input does not match the circuit's expected input.
InvalidInput,
/// An error was found while scanning, parsing or type-checking the program.
GarbleCompileTimeError(String),
/// The Garble program has more or fewer than two parameters and thus is not a 2-Party program.
GarbleProgramIsNoTwoPartyFunction,
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
InvalidInput => write!(f, "The input does not match the circuit's expected input."),
GarbleCompileTimeError(e) => write!(f, "Garble compile time error: {e}"),
GarbleProgramIsNoTwoPartyFunction => write!(
f,
"The Garble program has more or fewer than two parameters and thus is not a 2-Party program."
),
}
}
}