Procházet zdrojové kódy

zk/proof: Implement VerifyingKey serialization.

parazyd před 3 roky
rodič
revize
db48d24580
4 změnil soubory, kde provedl 226 přidání a 2 odebrání
  1. 1 2
      Cargo.lock
  2. 2 0
      Cargo.toml
  3. 55 0
      src/zk/proof.rs
  4. 168 0
      tests/halo2_vk_ser.rs

+ 1 - 2
Cargo.lock

@@ -2221,8 +2221,7 @@ dependencies = [
 [[package]]
 name = "halo2_proofs"
 version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cff771b9a2445cd2545c9ef26d863c290fbb44ae440c825a20eb7156f67a949a"
+source = "git+https://github.com/parazyd/halo2?branch=vk-ser#aa8efa96150f69dcdea6579c33b63377e23a0c54"
 dependencies = [
  "backtrace",
  "blake2b_simd",

+ 2 - 0
Cargo.toml

@@ -322,3 +322,5 @@ name = "zk-inclusion-proof"
 path = "example/zk-inclusion-proof.rs"
 required-features = ["zk"]
 
+[patch.crates-io]
+halo2_proofs = {git="https://github.com/parazyd/halo2", branch="vk-ser"}

+ 55 - 0
src/zk/proof.rs

@@ -15,6 +15,7 @@
  * 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};
 
 use darkfi_serial::{SerialDecodable, SerialEncodable};
 use halo2_proofs::{
@@ -38,6 +39,60 @@ impl VerifyingKey {
         let vk = plonk::keygen_vk(&params, c).unwrap();
         VerifyingKey { params, vk }
     }
+
+    pub fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
+        // FIXME: This can be optimized.
+        let mut params = vec![];
+        self.params.write(&mut params)?;
+
+        let mut vk = vec![];
+        self.vk.write(&mut vk)?;
+
+        writer.write(&(params.len() as u32).to_le_bytes())?;
+        writer.write(&params)?;
+        writer.write(&(vk.len() as u32).to_le_bytes())?;
+        writer.write(&vk)?;
+
+        Ok(())
+    }
+
+    pub fn read<R: io::Read, ConcreteCircuit: Circuit<pallas::Base>>(
+        reader: &mut R,
+    ) -> io::Result<Self> {
+        // FIXME: This can be optimized
+        // FIXME: Don't assert
+
+        // FIXME: Make sure that the size is legitimate.
+        // 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, &params)?;
+
+        Ok(Self { params, vk })
+    }
 }
 
 #[derive(Clone, Debug)]

+ 168 - 0
tests/halo2_vk_ser.rs

@@ -0,0 +1,168 @@
+/* This file is part of DarkFi (https://dark.fi)
+ *
+ * Copyright (C) 2020-2023 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::Cursor;
+
+use darkfi_sdk::{
+    crypto::{pedersen::pedersen_commitment_u64, util::mod_r_p, MerkleNode, PublicKey, SecretKey},
+    incrementalmerkletree::{bridgetree::BridgeTree, Tree},
+};
+use halo2_gadgets::poseidon::{
+    primitives as poseidon,
+    primitives::{ConstantLength, P128Pow5T3},
+};
+use halo2_proofs::{
+    arithmetic::{CurveAffine, Field},
+    circuit::Value,
+    pasta::{group::Curve, pallas},
+};
+use rand::rngs::OsRng;
+
+use darkfi::{
+    zk::{
+        proof::{ProvingKey, VerifyingKey},
+        vm::ZkCircuit,
+        vm_stack::{empty_witnesses, Witness},
+        Proof,
+    },
+    zkas::ZkBinary,
+    Result,
+};
+
+#[test]
+fn zkvm_opcodes() -> Result<()> {
+    let bincode = include_bytes!("../proof/opcodes.zk.bin");
+    let zkbin = ZkBinary::decode(bincode)?;
+
+    let verifier_witnesses = empty_witnesses(&zkbin);
+
+    println!("Building vk1");
+    let circuit = ZkCircuit::new(verifier_witnesses.clone(), zkbin.clone());
+    let vk1 = VerifyingKey::build(13, &circuit);
+
+    println!("Building vk2");
+    let circuit = ZkCircuit::new(verifier_witnesses.clone(), zkbin.clone());
+    let vk2 = VerifyingKey::build(13, &circuit);
+
+    let mut buf1 = vec![];
+    let mut buf2 = vec![];
+
+    println!("Writing vk1");
+    vk1.write(&mut buf1)?;
+
+    println!("Writing vk2");
+    vk2.write(&mut buf2)?;
+
+    println!("{} kB", buf1.len() / 1024);
+    assert_eq!(buf1, buf2);
+
+    println!("Reading vk3");
+    let mut buf1_c = Cursor::new(buf1);
+    let vk3 = VerifyingKey::read::<Cursor<Vec<u8>>, ZkCircuit>(&mut buf1_c)?;
+
+    println!("Reading vk4");
+    let mut buf2_c = Cursor::new(buf2);
+    let vk4 = VerifyingKey::read::<Cursor<Vec<u8>>, ZkCircuit>(&mut buf2_c)?;
+
+    // Now let's see if we can verify a proof with all four keys.
+    println!("Creating pk");
+    let circuit = ZkCircuit::new(verifier_witnesses.clone(), zkbin.clone());
+    let pk = ProvingKey::build(13, &circuit);
+
+    let value = 666_u64;
+    let value_blind = pallas::Scalar::random(&mut OsRng);
+    let blind = pallas::Base::random(&mut OsRng);
+    let secret = pallas::Base::random(&mut OsRng);
+    let a = pallas::Base::from(42);
+    let b = pallas::Base::from(69);
+
+    let mut tree = BridgeTree::<MerkleNode, 32>::new(100);
+    let c0 = pallas::Base::random(&mut OsRng);
+    let c1 = pallas::Base::random(&mut OsRng);
+    let c3 = pallas::Base::random(&mut OsRng);
+    let c2 = {
+        let messages = [pallas::Base::one(), blind];
+        poseidon::Hash::<_, P128Pow5T3, ConstantLength<2>, 3, 2>::init().hash(messages)
+    };
+
+    tree.append(&MerkleNode::from(c0));
+    tree.witness();
+    tree.append(&MerkleNode::from(c1));
+    tree.append(&MerkleNode::from(c2));
+    let leaf_pos = tree.witness().unwrap();
+    tree.append(&MerkleNode::from(c3));
+    tree.witness();
+
+    let root = tree.root(0).unwrap();
+    let merkle_path = tree.authentication_path(leaf_pos, &root).unwrap();
+    let leaf_pos: u64 = leaf_pos.into();
+
+    let ephem_secret = SecretKey::random(&mut OsRng);
+    let pubkey = PublicKey::from_secret(ephem_secret).inner();
+    let (ephem_x, ephem_y) = PublicKey::from(pubkey * mod_r_p(ephem_secret.inner())).xy();
+    let prover_witnesses = vec![
+        Witness::Base(Value::known(pallas::Base::from(value))),
+        Witness::Scalar(Value::known(value_blind)),
+        Witness::Base(Value::known(blind)),
+        Witness::Base(Value::known(a)),
+        Witness::Base(Value::known(b)),
+        Witness::Base(Value::known(secret)),
+        Witness::EcNiPoint(Value::known(pubkey)),
+        Witness::Base(Value::known(ephem_secret.inner())),
+        Witness::Uint32(Value::known(leaf_pos.try_into().unwrap())),
+        Witness::MerklePath(Value::known(merkle_path.try_into().unwrap())),
+    ];
+
+    let value_commit = pedersen_commitment_u64(value, value_blind);
+    let value_coords = value_commit.to_affine().coordinates().unwrap();
+
+    let d_m = [pallas::Base::one(), blind, *value_coords.x(), *value_coords.y()];
+    let d = poseidon::Hash::<_, P128Pow5T3, ConstantLength<4>, 3, 2>::init().hash(d_m);
+
+    let public = PublicKey::from_secret(SecretKey::from(secret));
+    let (pub_x, pub_y) = public.xy();
+
+    let public_inputs = vec![
+        *value_coords.x(),
+        *value_coords.y(),
+        c2,
+        d,
+        root.inner(),
+        pub_x,
+        pub_y,
+        ephem_x,
+        ephem_y,
+    ];
+
+    println!("Creating proof");
+    let circuit = ZkCircuit::new(prover_witnesses, zkbin);
+    let proof = Proof::create(&pk, &[circuit], &public_inputs, &mut OsRng)?;
+
+    println!("Verifying with vk1");
+    proof.verify(&vk1, &public_inputs)?;
+
+    println!("Verifying with vk2");
+    proof.verify(&vk2, &public_inputs)?;
+
+    println!("Verifying with vk3");
+    proof.verify(&vk3, &public_inputs)?;
+
+    println!("Verifying with vk4");
+    proof.verify(&vk4, &public_inputs)?;
+
+    Ok(())
+}