boo-hoo 0.2.0

An implementation of ZKBoo
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
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
use std::fmt;
use std::io::Read;
use std::io::Write;

use crate::bits::*;
use crate::commitment;
use crate::commitment::Commitment;
use crate::commitment::Decommitment;
use crate::constants::{CHALLENGE_CONTEXT, REPETITIONS};
use crate::program::*;
use crate::rng::{BitPRNG, Seed};
use bincode::decode_from_std_read;
use bincode::encode_into_slice;
use bincode::encode_to_vec;
use bincode::error::DecodeError;
use bincode::error::EncodeError;
use bincode::Decode;
use bincode::Encode;
use bincode::{config, encode_into_std_write};
use rand_core::{CryptoRng, RngCore};

/// Split a BitBuf into 3 shares which xor to form the original input.
fn split<R: RngCore + CryptoRng>(rng: &mut R, input: BitBuf) -> [BitBuf; 3] {
    let len = input.len();
    let len_bytes = (7 + len) / 8;
    let mut bytes = vec![0u8; len_bytes];

    rng.fill_bytes(&mut bytes);
    let mut buf0 = BitBuf::from_bytes(&bytes);
    buf0.resize(input.len());

    rng.fill_bytes(&mut bytes);
    let mut buf1 = BitBuf::from_bytes(&bytes);
    buf1.resize(input.len());

    // Now, as a result, some of the upper bits in buf2 may be different,
    // but our program has been validated, and will never access these.
    let mut buf2 = input;
    buf2.xor(&buf0);
    buf2.xor(&buf1);

    [buf0, buf1, buf2]
}

/// The and function between two parties.
///
/// When computing an and operation, each party needs the input from the party
/// adjacent to them, and the mask bit from the party adjacent to them. This
/// results in their secret share of the and operation.
fn and(input_a: (Bit, Bit), input_b: (Bit, Bit), mask_a: Bit, mask_b: Bit) -> Bit {
    (input_a.0 & input_a.1) ^ (input_a.0 & input_b.1) ^ (input_b.0 & input_a.1) ^ mask_a ^ mask_b
}

/// Represents the view of a single party in the MPC protocol.
#[derive(Clone, Default, Debug, Encode, Decode)]
struct View {
    seed: Seed,
    input: BitBuf,
    messages: BitBuf,
}

/// The result of running the simulation on three parties.
struct TriSimulation {
    views: [View; 3],
    outputs: [BitBuf; 3],
}

/// A simulator running the MPC protocol over three virtual parties.
struct TriSimulator {
    seeds: [Seed; 3],
    rngs: [BitPRNG; 3],
    machines: [Machine; 3],
    messages: [BitBuf; 3],
}

impl TriSimulator {
    /// Create a new trisimulator, initialized with some secret input.
    pub fn create<R: RngCore + CryptoRng>(rng: &mut R, input: BitBuf) -> Self {
        let seeds = [(); 3].map(|_| Seed::random(rng));
        let rngs = [0, 1, 2].map(|i| BitPRNG::seeded(&seeds[i]));
        let inputs = split(rng, input);
        let machines = inputs.map(Machine::new);
        let messages = [(); 3].map(|_| BitBuf::new());
        Self {
            seeds,
            rngs,
            machines,
            messages,
        }
    }

    fn and(&mut self) {
        let mask_bits = [0, 1, 2].map(|i| self.rngs[i].next_bit());
        let inputs = [0, 1, 2].map(|i| {
            let machine = &mut self.machines[i];
            let bit0 = machine.pop();
            let bit1 = machine.pop();
            (bit0, bit1)
        });

        for i0 in 0..3 {
            let i1 = (i0 + 1) % 3;

            let res = and(inputs[i0], inputs[i1], mask_bits[i0], mask_bits[i1]);

            // Since this involves "communication" between the simulated parties,
            // we record having received this message
            self.messages[i0].push(res);
            self.machines[i0].push(res);
        }
    }

    fn op(&mut self, op: Operation) {
        match op {
            Operation::Not => {
                for machine in &mut self.machines {
                    machine.not();
                }
            }
            Operation::And => self.and(),
            Operation::Xor => {
                for machine in &mut self.machines {
                    machine.xor();
                }
            }
            Operation::PushArg(i) => {
                let i_usize = i as usize;
                for machine in &mut self.machines {
                    machine.push_arg(i_usize);
                }
            }
            Operation::PushLocal(i) => {
                let i_usize = i as usize;
                for machine in &mut self.machines {
                    machine.push_local(i_usize);
                }
            }
            Operation::PopOutput => {
                for machine in &mut self.machines {
                    machine.pop_output();
                }
            }
        }
    }

    /// Run the simulation, producing the result.
    ///
    /// The result contains the views of each party, along with the outputs.
    pub fn run(mut self, program: &ValidatedProgram) -> TriSimulation {
        for op in &program.operations {
            self.op(*op);
        }
        let mut views = Vec::with_capacity(3);
        let mut outputs = Vec::with_capacity(3);
        for ((seed, machine), messages) in self
            .seeds
            .into_iter()
            .zip(self.machines.into_iter())
            .zip(self.messages.into_iter())
        {
            let (input, output) = machine.input_output();
            views.push(View {
                seed,
                input: input,
                messages,
            });
            outputs.push(output);
        }
        let views = views.try_into().unwrap();
        let outputs = outputs.try_into().unwrap();
        TriSimulation { views, outputs }
    }
}

/// Represents a proof of knowledge of a pre-image of some arbitrary program.
///
/// This is generated through the `prove` function, and should be treated as
/// an opaque blob which can be verified through the `verify` function.
///
/// For serialization and deserialization, the Encode and Decode traits are provided,
/// which can be combined with [bincode](https://docs.rs/bincode/2.0.0-rc.1/bincode/index.html)
/// in order to serialize to bytes, or an arbitrary IO object.
///
/// This object also provides wrapper methods to implement those functions.
#[derive(Clone, Encode, Decode)]
pub struct Proof {
    commitments: Vec<Commitment>,
    outputs: Vec<BitBuf>,
    decommitments: Vec<Decommitment>,
    views: Vec<View>,
}

impl Proof {
    /// Encode this proof into a vector of bytes.
    ///
    /// In principle, this method shouldn't fail.
    pub fn encode_to_vec(&self) -> Result<Vec<u8>, EncodeError> {
        encode_to_vec(self, config::standard())
    }

    /// Encode this proof into an arbitrary object implementing `Write`.
    ///
    /// This will return the number of bytes written.
    pub fn encode_to_write<W: Write>(&self, dst: &mut W) -> Result<usize, EncodeError> {
        encode_into_std_write(self, dst, config::standard())
    }

    /// Decode this proof from an arbitrary object implementing `Read`.
    ///
    /// Note that this function will also work with `&[u8]`, since that implements `Read`.
    pub fn decode_from_read<R: Read>(src: &mut R) -> Result<Self, DecodeError> {
        decode_from_std_read(src, config::standard())
    }
}

/// Our challenge is a series of trits, which we draw from a PRNG.
fn challenge(
    ctx: &[u8],
    program: &ValidatedProgram,
    output: &BitBuf,
    commitments: &Vec<Commitment>,
    outputs: &Vec<BitBuf>,
) -> BitPRNG {
    fn update<E: Encode>(hasher: &mut blake3::Hasher, e: E) {
        encode_into_std_write(e, hasher, config::standard()).unwrap();
    }

    let mut hasher = blake3::Hasher::new_derive_key(CHALLENGE_CONTEXT);
    update(&mut hasher, ctx);
    update(&mut hasher, &program.operations);
    update(&mut hasher, output);
    update(&mut hasher, REPETITIONS);
    update(&mut hasher, commitments);
    update(&mut hasher, outputs);

    BitPRNG::from_hasher(hasher)
}

/// An internal function for creating a proof, after validkkoating inputs.
///
/// The buffers for input and output must have the exact right length for the program.
fn do_prove<R: RngCore + CryptoRng>(
    rng: &mut R,
    ctx: &[u8],
    program: &ValidatedProgram,
    input: &BitBuf,
    output: &BitBuf,
) -> Proof {
    let mut commitments = Vec::with_capacity(REPETITIONS * 3);
    let mut outputs = Vec::with_capacity(REPETITIONS * 3);
    let mut all_decommitments = Vec::with_capacity(REPETITIONS * 3);
    let mut all_views = Vec::with_capacity(REPETITIONS * 3);

    for _ in 0..REPETITIONS {
        let simulation = TriSimulator::create(rng, input.clone()).run(program);

        for output in simulation.outputs {
            outputs.push(output);
        }

        for view in simulation.views {
            let (com, decom) = commitment::commit(rng, &view);
            commitments.push(com);
            all_decommitments.push(decom);
            all_views.push(view);
        }
    }

    let mut bit_rng = challenge(ctx, program, output, &commitments, &outputs);

    let mut decommitments = Vec::with_capacity(REPETITIONS * 2);
    let mut views = Vec::with_capacity(REPETITIONS * 2);

    for i in (0..REPETITIONS).map(|i| i * 3) {
        let trit = bit_rng.next_trit() as usize;
        let i0 = i + trit;
        let i1 = i + ((trit + 1) % 3);
        for ij in [i0, i1] {
            decommitments.push(std::mem::take(&mut all_decommitments[ij]));
            views.push(std::mem::take(&mut all_views[ij]));
        }
    }

    Proof {
        commitments,
        outputs,
        decommitments,
        views,
    }
}

/// Represents the partial simulation over the two revealed parties of the protocol.
struct ReSimulation {
    primary_messages: BitBuf,
    outputs: [BitBuf; 2],
}

/// The ReSimulator partially simulates the MPC protocol over only two parties.
/// 
/// Since we have only two parties, we can't do a full simulation. Instead, we trust
/// the claimed messages for the second party, and re-simulate the behavior of the first
/// party given those messages.
struct ReSimulator<'a> {
    /// The new messages reproduced for the first party.
    primary_messages: BitBuf,
    /// The claimed messages for the second party.
    secondary_messages: &'a BitBuf,
    /// The current index into those messages.
    secondary_messages_i: usize,
    /// The RNGs for each party.
    rngs: [BitPRNG; 2],
    /// The machine for the state of each party.
    machines: [Machine; 2],
}

impl<'a> ReSimulator<'a> {
    /// Create a new ReSimulator given the inputs, seeds, and the messages of the second party.
    fn new(inputs: [&'a BitBuf; 2], seeds: [&'a Seed; 2], secondary_messages: &'a BitBuf) -> Self {
        Self {
            primary_messages: BitBuf::new(),
            secondary_messages,
            secondary_messages_i: 0,
            rngs: seeds.map(BitPRNG::seeded),
            machines: inputs.map(|input| Machine::new(input.clone())),
        }
    }

    fn next_secondary_message(&mut self) -> Option<Bit> {
        let out = self.secondary_messages.get(self.secondary_messages_i);
        self.secondary_messages_i += 1;
        out
    }

    fn and(&mut self) -> Option<()> {
        let masks = [0, 1].map(|i| self.rngs[i].next_bit());
        let inputs = [0, 1].map(|i| {
            let machine = &mut self.machines[i];
            let bit0 = machine.pop();
            let bit1 = machine.pop();
            (bit0, bit1)
        });

        let res = and(inputs[0], inputs[1], masks[0], masks[1]);
        self.machines[0].push(res);
        self.primary_messages.push(res);
        // We just trust the secondary messages to be correct
        let next_message = self.next_secondary_message()?;
        self.machines[1].push(next_message);
        Some(())
    }

    fn op(&mut self, op: Operation) -> Option<()> {
        match op {
            Operation::Not => {
                for machine in &mut self.machines {
                    machine.not();
                }
            }
            Operation::And => self.and()?,
            Operation::Xor => {
                for machine in &mut self.machines {
                    machine.xor();
                }
            }
            Operation::PushArg(i) => {
                for machine in &mut self.machines {
                    machine.push_arg(i as usize)
                }
            }
            Operation::PushLocal(i) => {
                for machine in &mut self.machines {
                    machine.push_local(i as usize)
                }
            }
            Operation::PopOutput => {
                for machine in &mut self.machines {
                    machine.pop_output();
                }
            }
        }
        Some(())
    }

    /// Run the resimulation on a given program.
    ///
    /// This can potentially fail, if not enough messages are passed to the simulator.
    /// This indicates a bad proof.
    pub fn run(mut self, program: &ValidatedProgram) -> Option<ReSimulation> {
        for op in &program.operations {
            self.op(*op)?;
        }

        let primary_messages = self.primary_messages;
        let outputs = self.machines.map(|machine| machine.input_output().1);
        Some(ReSimulation {
            primary_messages,
            outputs,
        })
    }
}

/// Verify a single repetition of the proof.
///
/// The slices `commitments` and `outputs` should have 3 elements, and
/// `decommitments` and `views` should have 2 elements.
fn verify_repetition(
    program: &ValidatedProgram,
    output: &BitBuf,
    commitments: &[Commitment],
    outputs: &[BitBuf],
    trit: u8,
    decommitments: &[Decommitment],
    views: &[View],
) -> bool {
    // Check that the output is correct
    let mut actual_output = outputs[0].clone();
    actual_output.xor(&outputs[1]);
    actual_output.xor(&outputs[2]);

    if actual_output != *output {
        return false;
    }
    // Check input lengths
    if !(0..2).all(|i| views[i].input.len() == program.input_count) {
        return false;
    }

    let i = [trit as usize, ((trit + 1) % 3) as usize];

    // Check that the commitments are valid
    if !(0..2).all(|j| {
        let i_j = i[j];
        commitment::decommit(&views[j], &commitments[i_j], &decommitments[j])
    }) {
        return false;
    }

    // Check that the views are coherent, and produce the right output
    let re_simulation_result = ReSimulator::new(
        [&views[0].input, &views[1].input],
        [&views[0].seed, &views[1].seed],
        &views[1].messages,
    )
    .run(program);
    let re_simulation = match re_simulation_result {
        Some(x) => x,
        None => return false,
    };

    if re_simulation.primary_messages != views[0].messages {
        return false;
    }
    (0..2).all(|j| re_simulation.outputs[j] == outputs[i[j]])
}

fn do_verify(ctx: &[u8], program: &ValidatedProgram, output: &BitBuf, proof: &Proof) -> bool {
    // Check that the proof has enough content
    if proof.commitments.len() != 3 * REPETITIONS {
        return false;
    }
    if proof.outputs.len() != 3 * REPETITIONS {
        return false;
    }
    if proof.decommitments.len() != 2 * REPETITIONS {
        return false;
    }
    if proof.views.len() != 2 * REPETITIONS {
        return false;
    }

    let mut bit_rng = challenge(ctx, program, output, &proof.commitments, &proof.outputs);

    (0..REPETITIONS).all(|i| {
        let trit = bit_rng.next_trit();
        verify_repetition(
            program,
            output,
            &proof.commitments[3 * i..3 * (i + 1)],
            &proof.outputs[3 * i..3 * (i + 1)],
            trit,
            &proof.decommitments[2 * i..2 * (i + 1)],
            &proof.views[2 * i..2 * (i + 1)],
        )
    })
}

/// Represents an error that can happen when proving or verifying.
///
/// At the moment, errors only happen because the size of the input or the output
/// was insufficient for what the program expected. If too little input our output
/// is provided, then proving and verifying will fail.
#[derive(Clone, Debug, PartialEq)]
pub enum Error {
    InsufficientInput(usize),
    InsufficientOutput(usize),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::InsufficientInput(i) => write!(f, "insufficient input of size {}", i),
            Error::InsufficientOutput(i) => write!(f, "insufficient output of size {}", i),
        }
    }
}

impl std::error::Error for Error {}

/// Create a proof that running a program on an input produces the provided output.
///
/// This proof will let other people independently verify that we know an input producing
/// that output after running the program, without revealing what that secret input is.
///
/// This proof also commits to the program. A proof will only verify with the exact
/// program used to create the proof. Any modification to the program, even if it
/// results in equivalent functionality, will fail to verify.
///
/// This proving function takes an additional context, which can be used to bind
/// the proof to a given context. The verifier will need to pass in the same context,
/// and will fail to verify if their context is different. Among other things,
/// this allows you to potentially turn these proofs into a signature scheme, by using
/// a message as a context.
///
/// The program needs to be validated, to make sure that it isn't malformed. Furthermore,
/// this proving can fail if the input or output doesn't match the size of the proof.
/// Providing additional input or output will work, and any extra data beyond the number
/// of bits used by the program is ignored completely. Bits are read from least to
/// most significant.
pub fn prove<R: RngCore + CryptoRng>(
    rng: &mut R,
    ctx: &[u8],
    program: &ValidatedProgram,
    input: &[u8],
    output: &[u8],
) -> Result<Proof, Error> {
    let mut input_buf = BitBuf::from_bytes(input);
    let mut output_buf = BitBuf::from_bytes(output);
    if input_buf.len() < program.input_count {
        return Err(Error::InsufficientInput(input_buf.len()));
    }
    if output_buf.len() < program.output_count {
        return Err(Error::InsufficientOutput(output_buf.len()));
    }
    input_buf.resize(program.input_count);
    output_buf.resize(program.output_count);
    Ok(do_prove(rng, ctx, program, &input_buf, &output_buf))
}

/// Verify a proof, demonstrating knowledge of some input for which the program returns this output.
///
/// This function returns `true` if the proof is correct.
///
/// For the proof to successfully verify, the prover needs to have known an input which
/// produces this exact output when used to run the program. Furthermore, the program
/// needs to exactly match the program used to create the proof. Finally, the context
/// data used to produce the proof needs to be the exact same as passed to verify.
///
/// Note that the output needs to be at least as long as the output produced by the program.
/// Any additional bits in the output will be ignored. Bits are read from least significant
/// to most significant. If the output isn't large enough, this function will fail.
pub fn verify(
    ctx: &[u8],
    program: &ValidatedProgram,
    output: &[u8],
    proof: &Proof,
) -> Result<bool, Error> {
    let mut output_buf = BitBuf::from_bytes(output);
    if output_buf.len() < program.output_count {
        return Err(Error::InsufficientOutput(output_buf.len()));
    }
    output_buf.resize(program.output_count);

    Ok(do_verify(ctx, program, &output_buf, proof))
}

#[cfg(test)]
mod test {
    use rand_core::OsRng;

    use super::*;
    use crate::program::generators::arb_program_and_inputs;
    use proptest::prelude::*;

    fn simple_program() -> ValidatedProgram {
        use Operation::*;

        Program::new([
            PushArg(0),
            PushArg(1),
            PushArg(2),
            PushArg(3),
            Xor,
            Xor,
            Xor,
            PushArg(4),
            PushArg(5),
            PushArg(6),
            PushArg(7),
            Xor,
            Xor,
            Xor,
            And,
            PopOutput,
        ])
        .validate()
        .unwrap()
    }

    const TEST_CTX: &[u8] = b"test context";

    #[test]
    fn test_simple_program_proof_succeeds() {
        let input = &[0b0111_1110];
        let output = &[1];
        let program = simple_program();
        let proof = prove(&mut OsRng, TEST_CTX, &program, input, output);
        assert!(proof.is_ok());
        assert_eq!(
            Ok(true),
            verify(TEST_CTX, &program, output, &proof.unwrap())
        );
    }

    proptest! {
        // This test is slow, so should be run with --include-ignore
        #[test]
        #[ignore]
        fn test_program_proofs_succeed((program, input, output) in arb_program_and_inputs()) {
            let proof = prove(&mut OsRng, TEST_CTX, &program, &input, &[output]);
            assert!(proof.is_ok());
            assert_eq!(Ok(true), verify(TEST_CTX, &program, &[output], &proof.unwrap()));
        }
    }
}