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
/* This file is part of DarkFi (https://dark.fi)
 *
 * Copyright (C) 2020-2024 Dyne.org foundation
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
use std::{io, io::Cursor};

#[cfg(feature = "async-serial")]
use darkfi_serial::async_trait;

use darkfi_sdk::pasta::{pallas, vesta};
use darkfi_serial::{SerialDecodable, SerialEncodable};
use halo2_proofs::{
    helpers::SerdeFormat,
    plonk,
    plonk::{Circuit, SingleVerifier},
    poly::commitment::Params,
    transcript::{Blake2bRead, Blake2bWrite},
};
use rand::RngCore;

#[derive(Clone, Debug)]
pub struct VerifyingKey {
    pub params: Params<vesta::Affine>,
    pub vk: plonk::VerifyingKey<vesta::Affine>,
}

impl VerifyingKey {
    pub fn build(k: u32, c: &impl Circuit<pallas::Base>) -> Self {
        let params = Params::new(k);
        let vk = plonk::keygen_vk(&params, c).unwrap();
        VerifyingKey { params, vk }
    }

    pub fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
        let mut params = vec![];
        self.params.write(&mut params)?;

        let mut vk = vec![];
        self.vk.write(&mut vk, SerdeFormat::RawBytes)?;

        let _ = writer.write(&(params.len() as u32).to_le_bytes())?;
        let _ = writer.write(&params)?;
        let _ = writer.write(&(vk.len() as u32).to_le_bytes())?;
        let _ = writer.write(&vk)?;

        Ok(())
    }

    pub fn read<R: io::Read, ConcreteCircuit: Circuit<pallas::Base>>(
        reader: &mut R,
        circuit: ConcreteCircuit,
    ) -> io::Result<Self> {
        // The format chosen in write():
        // [params.len()<u32>, params..., vk.len()<u32>, vk...]

        let mut params_len = [0u8; 4];
        reader.read_exact(&mut params_len)?;
        let params_len = u32::from_le_bytes(params_len) as usize;

        let mut params_buf = vec![0u8; params_len];
        reader.read_exact(&mut params_buf)?;

        assert!(params_buf.len() == params_len);

        let mut vk_len = [0u8; 4];
        reader.read_exact(&mut vk_len)?;
        let vk_len = u32::from_le_bytes(vk_len) as usize;

        let mut vk_buf = vec![0u8; vk_len];
        reader.read_exact(&mut vk_buf)?;

        assert!(vk_buf.len() == vk_len);

        let mut params_c = Cursor::new(params_buf);
        let params: Params<vesta::Affine> = Params::read(&mut params_c)?;

        let mut vk_c = Cursor::new(vk_buf);
        let vk: plonk::VerifyingKey<vesta::Affine> =
            plonk::VerifyingKey::read::<Cursor<Vec<u8>>, ConcreteCircuit>(
                &mut vk_c,
                SerdeFormat::RawBytes,
                circuit.params(),
            )?;

        Ok(Self { params, vk })
    }
}

#[derive(Clone, Debug)]
pub struct ProvingKey {
    pub params: Params<vesta::Affine>,
    pub pk: plonk::ProvingKey<vesta::Affine>,
}

impl ProvingKey {
    pub fn build(k: u32, c: &impl Circuit<pallas::Base>) -> Self {
        let params = Params::new(k);
        let vk = plonk::keygen_vk(&params, c).unwrap();
        let pk = plonk::keygen_pk(&params, vk, c).unwrap();
        ProvingKey { params, pk }
    }

    pub fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
        let mut params = vec![];
        self.params.write(&mut params)?;

        let mut pk = vec![];
        self.pk.write(&mut pk, SerdeFormat::RawBytes)?;

        let _ = writer.write(&(params.len() as u32).to_le_bytes())?;
        let _ = writer.write(&params)?;
        let _ = writer.write(&(pk.len() as u32).to_le_bytes())?;
        let _ = writer.write(&pk)?;

        Ok(())
    }

    pub fn read<R: io::Read, ConcreteCircuit: Circuit<pallas::Base>>(
        reader: &mut R,
        circuit: ConcreteCircuit,
    ) -> io::Result<Self> {
        let mut params_len = [0u8; 4];
        reader.read_exact(&mut params_len)?;
        let params_len = u32::from_le_bytes(params_len) as usize;

        let mut params_buf = vec![0u8; params_len];
        reader.read_exact(&mut params_buf)?;

        assert!(params_buf.len() == params_len);

        let mut pk_len = [0u8; 4];
        reader.read_exact(&mut pk_len)?;
        let pk_len = u32::from_le_bytes(pk_len) as usize;

        let mut pk_buf = vec![0u8; pk_len];
        reader.read_exact(&mut pk_buf)?;

        assert!(pk_buf.len() == pk_len);

        let mut params_c = Cursor::new(params_buf);
        let params: Params<vesta::Affine> = Params::read(&mut params_c)?;

        let mut pk_c = Cursor::new(pk_buf);
        let pk: plonk::ProvingKey<vesta::Affine> =
            plonk::ProvingKey::read::<Cursor<Vec<u8>>, ConcreteCircuit>(
                &mut pk_c,
                SerdeFormat::RawBytes,
                circuit.params(),
            )?;

        Ok(Self { params, pk })
    }
}

#[derive(Clone, Default, PartialEq, Eq, SerialEncodable, SerialDecodable)]
pub struct Proof(Vec<u8>);

impl AsRef<[u8]> for Proof {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl core::fmt::Debug for Proof {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Proof({:?})", self.0)
    }
}

impl Proof {
    pub fn create(
        pk: &ProvingKey,
        circuits: &[impl Circuit<pallas::Base>],
        instances: &[pallas::Base],
        mut rng: impl RngCore,
    ) -> std::result::Result<Self, plonk::Error> {
        let mut transcript = Blake2bWrite::<_, vesta::Affine, _>::init(vec![]);
        plonk::create_proof(
            &pk.params,
            &pk.pk,
            circuits,
            &[&[instances]],
            &mut rng,
            &mut transcript,
        )?;

        Ok(Proof(transcript.finalize()))
    }

    pub fn verify(
        &self,
        vk: &VerifyingKey,
        instances: &[pallas::Base],
    ) -> std::result::Result<(), plonk::Error> {
        let strategy = SingleVerifier::new(&vk.params);
        let mut transcript = Blake2bRead::init(&self.0[..]);

        plonk::verify_proof(&vk.params, &vk.vk, strategy, &[&[instances]], &mut transcript)
    }

    pub fn new(bytes: Vec<u8>) -> Self {
        Proof(bytes)
    }
}