Files
aho_corasick
ansi_term
atty
backtrace
backtrace_sys
bitflags
blindbid
block_buffer
block_padding
bulletproofs
byte_tools
byteorder
cfg_if
chrono
clap
clear_on_drop
curve25519_dalek
digest
dusk_blindbidproof
dusk_tlv
dusk_uds
env_logger
failure
failure_derive
fake_simd
futures
futures_channel
futures_core
futures_executor
futures_io
futures_macro
futures_sink
futures_task
futures_util
async_await
future
io
lock
sink
stream
task
generic_array
humantime
keccak
lazy_static
libc
log
memchr
merlin
num_cpus
num_integer
num_traits
opaque_debug
packed_simd
pin_utils
proc_macro2
proc_macro_hack
proc_macro_nested
quick_error
quote
rand
rand_chacha
rand_core
rand_hc
rand_isaac
rand_jitter
rand_os
rand_pcg
rand_xorshift
regex
regex_syntax
rustc_demangle
serde
serde_derive
sha2
sha3
slab
strsim
subtle
syn
synstructure
termcolor
textwrap
thread_local
time
typenum
unicode_width
unicode_xid
vec_map
  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
use super::{generate_cs_transcript, CONSTANTS};
use crate::gadgets::proof_gadget;
use crate::Error;

use std::convert::{TryFrom, TryInto};
use std::io::{Read, Write};

use bulletproofs::r1cs::Prover;
use bulletproofs::r1cs::{LinearCombination, R1CSProof};
use curve25519_dalek::ristretto::CompressedRistretto;
use curve25519_dalek::scalar::Scalar;
use dusk_tlv::{TlvReader, TlvWriter};
use rand::thread_rng;
use serde::Deserialize;

#[derive(Debug, Clone)]
pub struct Proof {
    pub proof: R1CSProof,
    pub commitments: Vec<CompressedRistretto>,
    pub t_c: Vec<CompressedRistretto>,
}

impl Proof {
    pub fn new(
        proof: R1CSProof,
        commitments: Vec<CompressedRistretto>,
        t_c: Vec<CompressedRistretto>,
    ) -> Self {
        Proof {
            proof,
            commitments,
            t_c,
        }
    }

    pub fn prove(
        d: Scalar,
        k: Scalar,
        y: Scalar,
        y_inv: Scalar,
        q: Scalar,
        z_img: Scalar,
        seed: Scalar,
        pub_list: Vec<Scalar>,
        toggle: u64,
    ) -> Result<Self, Error> {
        let (pc_gens, bp_gens, mut transcript) = generate_cs_transcript();

        // 1. Create a prover
        let mut prover = Prover::new(&pc_gens, &mut transcript);

        // 2. Commit high-level variables
        let mut blinding_rng = rand::thread_rng();

        let (commitments, vars): (Vec<_>, Vec<_>) = [d, k, y, y_inv]
            .iter()
            .map(|v| prover.commit(*v, Scalar::random(&mut blinding_rng)))
            .unzip();

        let (t_c, t_v): (Vec<_>, Vec<_>) = (0..pub_list.len())
            .map(|x| {
                prover.commit(
                    Scalar::from((x as u64 == toggle) as u8),
                    Scalar::random(&mut thread_rng()),
                )
            })
            .unzip();

        // public list of numbers
        let l_v: Vec<LinearCombination> = pub_list.iter().map(|&x| x.into()).collect::<Vec<_>>();

        // 3. Build a CS
        proof_gadget(
            &mut prover,
            vars[0].into(),
            vars[1].into(),
            vars[3].into(),
            q.into(),
            z_img.into(),
            seed.into(),
            &CONSTANTS,
            t_v,
            l_v,
        );

        // 4. Make a proof
        let proof = prover.prove(&bp_gens)?;

        Ok(Proof::new(proof, commitments, t_c))
    }

    /// Perform the deserialization of a request.
    ///
    /// Currently the recommended method from TlvReaderis read_list instead of standard list
    /// deserialization
    pub fn try_from_reader_variables<R: Read>(reader: R) -> Result<Self, Error> {
        let mut reader = TlvReader::new(reader);

        let d = Deserialize::deserialize(&mut reader)?;
        let k = Deserialize::deserialize(&mut reader)?;
        let y = Deserialize::deserialize(&mut reader)?;
        let y_inv = Deserialize::deserialize(&mut reader)?;
        let q = Deserialize::deserialize(&mut reader)?;
        let z_img = Deserialize::deserialize(&mut reader)?;
        let seed = Deserialize::deserialize(&mut reader)?;

        let mut pub_list = vec![];
        for bytes in reader.read_list::<Vec<u8>>()? {
            if bytes.len() != 32 {
                return Err(Error::io_invalid_data(
                    "Scalars Ristrettos can only be created from 32 bytes slices",
                ));
            }

            let mut p = [0x00u8; 32];
            p.copy_from_slice(bytes.as_slice());

            let p = Scalar::from_bits(p);
            pub_list.push(p);
        }

        let toggle = Deserialize::deserialize(&mut reader)?;

        Proof::prove(d, k, y, y_inv, q, z_img, seed, pub_list, toggle)
    }
}

impl TryInto<Vec<u8>> for Proof {
    type Error = Error;

    fn try_into(self) -> Result<Vec<u8>, Self::Error> {
        let buf = vec![];
        let mut buf = TlvWriter::new(buf);

        buf.write(self.proof.to_bytes().as_slice())?;
        buf.write_list(
            self.commitments
                .iter()
                .map(|c| c.to_bytes()[..].to_vec())
                .collect::<Vec<Vec<u8>>>()
                .as_slice(),
        )?;
        buf.write_list(
            self.t_c
                .iter()
                .map(|c| c.to_bytes()[..].to_vec())
                .collect::<Vec<Vec<u8>>>()
                .as_slice(),
        )?;

        Ok(buf.into_inner())
    }
}

impl TryFrom<Vec<u8>> for Proof {
    type Error = Error;

    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
        let mut reader = TlvReader::new(bytes.as_slice());

        let proof = reader
            .next()
            .ok_or(Error::io_unexpected_eof("The proof was not supplied"))??;
        let proof = R1CSProof::from_bytes(proof.as_slice())?;

        let mut commitments = vec![];
        for c in reader.read_list::<Vec<u8>>()? {
            if c.len() != 32 {
                return Err(Error::io_invalid_data(
                    "Compressed Ristrettos can only be created from 32 bytes slices",
                ));
            }

            // This function panics if the size is different from 32
            let cr = CompressedRistretto::from_slice(c.as_slice());
            commitments.push(cr);
        }

        let mut t_c = vec![];
        for t in reader.read_list::<Vec<u8>>()? {
            if t.len() != 32 {
                return Err(Error::io_invalid_data(
                    "Compressed Ristrettos can only be created from 32 bytes slices",
                ));
            }

            // This function panics if the size is different from 32
            let cr = CompressedRistretto::from_slice(t.as_slice());
            t_c.push(cr);
        }

        Ok(Proof::new(proof, commitments, t_c))
    }
}