narodnik 5 лет назад
Родитель
Сommit
fb78f88e3e

+ 3 - 12
src/bin/demowallet.rs

@@ -1,12 +1,10 @@
-
 //! cargo run --example request --features="rt-tokio" --no-default-features
 
 use async_zmq::zmq;
-use sapvi::service::reqrep::{Request, Reply};
 use sapvi::serial;
+use sapvi::service::reqrep::{Reply, Request};
 
-
-fn connect () {
+fn connect() {
     let context = zmq::Context::new();
     let requester = context.socket(zmq::REQ).unwrap();
     requester
@@ -19,16 +17,10 @@ fn connect () {
         requester.send(req, 0).unwrap();
         let message = requester.recv_msg(0).unwrap();
         let rep: Reply = serial::deserialize(&message).unwrap();
-        println!(
-            "Received reply {:?} {:?}",
-            request_nbr,
-            rep
-        );
+        println!("Received reply {:?} {:?}", request_nbr, rep);
     }
 }
 fn main() {
-
-
     let mut thread_pools = vec![];
     for _ in 0..20 {
         let t = std::thread::spawn(connect);
@@ -38,5 +30,4 @@ fn main() {
     for t in thread_pools {
         t.join().unwrap();
     }
-
 }

+ 1 - 7
src/bin/services.rs

@@ -7,15 +7,12 @@ use sapvi::Result;
 use sapvi::service::{gateway, reqrep};
 
 async fn start(executor: Arc<Executor<'_>>) -> Result<()> {
-    
     executor.clone().spawn(reqrep::ReqRepAPI::start()).detach();
 
-    gateway::GatewayService::start(executor.clone()).await; 
+    gateway::GatewayService::start(executor.clone()).await;
     Ok(())
 }
 
-
-
 fn main() -> Result<()> {
     let ex = Arc::new(Executor::new());
     let (signal, shutdown) = async_channel::unbounded::<()>();
@@ -35,6 +32,3 @@ fn main() -> Result<()> {
 
     result
 }
-
-
-

+ 1 - 1
src/bin/spend-classic.rs

@@ -203,7 +203,7 @@ fn main() {
         randomness_coin,
         secret,
         merkle_path,
-        signature_secret
+        signature_secret,
     );
 
     assert!(verify_spend_proof(&pvk, &proof, &revealed));

+ 25 - 11
src/bin/tx.rs

@@ -1,19 +1,20 @@
-use std::io;
 use bellman::groth16;
 use bls12_381::Bls12;
 use ff::{Field, PrimeField};
 use group::Group;
 use rand::rngs::OsRng;
+use std::io;
 
 use sapvi::crypto::{
-    create_mint_proof, load_params, save_params, setup_mint_prover, verify_mint_proof,
-    MintRevealedValues,
-    note::Note,
-    merkle::{IncrementalWitness, CommitmentTree},
     coin::Coin,
+    create_mint_proof, create_spend_proof, load_params,
+    merkle::{CommitmentTree, IncrementalWitness},
+    note::Note,
+    save_params, setup_mint_prover, setup_spend_prover, verify_mint_proof, verify_spend_proof,
+    MintRevealedValues, SpendRevealedValues,
 };
-use sapvi::serial::{Decodable, Encodable, VarInt};
 use sapvi::error::{Error, Result};
+use sapvi::serial::{Decodable, Encodable, VarInt};
 use sapvi::tx;
 
 fn txbuilding() {
@@ -21,7 +22,12 @@ fn txbuilding() {
         let params = setup_mint_prover();
         save_params("mint.params", &params);
     }
+    {
+        let params = setup_spend_prover();
+        save_params("spend.params", &params);
+    }
     let (mint_params, mint_pvk) = load_params("mint.params").expect("params should load");
+    let (spend_params, spend_pvk) = load_params("spend.params").expect("params should load");
 
     let public = jubjub::SubgroupPoint::random(&mut OsRng);
 
@@ -32,7 +38,7 @@ fn txbuilding() {
 
     let mut tx_data = vec![];
     {
-        let tx = builder.build(&mint_params);
+        let tx = builder.build(&mint_params, &spend_params);
         tx.encode(&mut tx_data).expect("encode tx");
     }
     let mut tree = CommitmentTree::empty();
@@ -43,7 +49,8 @@ fn txbuilding() {
     {
         let tx = tx::Transaction::decode(&tx_data[..]).unwrap();
         assert!(tx.verify(&mint_pvk));
-        tree.append(Coin::new(tx.outputs[0].revealed.coin)).expect("append merkle");
+        tree.append(Coin::new(tx.outputs[0].revealed.coin))
+            .expect("append merkle");
     }
     let mut witness = IncrementalWitness::from_tree(&tree);
     assert_eq!(witness.position(), 5);
@@ -56,10 +63,14 @@ fn txbuilding() {
         witness.append(cmu);
         assert_eq!(tree.root(), witness.root());
     }
-}
 
-fn main() {
-    txbuilding();
+    let merkle_path = witness.path().unwrap();
+    let auth_path: Vec<Option<(bls12_381::Scalar, bool)>> = merkle_path
+        .auth_path
+        .iter()
+        .map(|(node, b)| Some(((*node).into(), *b)))
+        .collect();
+
     /*let note = Note {
         serial: jubjub::Fr::random(&mut OsRng),
         value: 110,
@@ -75,3 +86,6 @@ fn main() {
     assert_eq!(note.value, note2.value);*/
 }
 
+fn main() {
+    txbuilding();
+}

+ 0 - 1
src/bin/wallet/test.rs

@@ -84,4 +84,3 @@ fn test_db(db: &DB) {
 
 // TODO: macro to load file as a string. load wallet tables in sqlite at run
 // Table includes: maintain a list of coins and whether they are spent
-

+ 9 - 4
src/crypto/coin.rs

@@ -1,8 +1,8 @@
-use std::io;
-use group::Curve;
 use bitvec::{order::Lsb0, view::AsBits};
-use lazy_static::lazy_static;
 use ff::PrimeField;
+use group::Curve;
+use lazy_static::lazy_static;
+use std::io;
 
 use super::merkle::Hashable;
 
@@ -85,6 +85,12 @@ impl Hashable for Coin {
     }
 }
 
+impl From<Coin> for bls12_381::Scalar {
+    fn from(coin: Coin) -> Self {
+        bls12_381::Scalar::from_repr(coin.repr).expect("Tree nodes should be in the prime field")
+    }
+}
+
 lazy_static! {
     static ref EMPTY_ROOTS: Vec<Coin> = {
         let mut v = vec![Coin::blank()];
@@ -95,4 +101,3 @@ lazy_static! {
         v
     };
 }
-

+ 2 - 3
src/crypto/fr_serial.rs

@@ -1,8 +1,8 @@
-use std::io;
 use group::GroupEncoding;
+use std::io;
 
-use crate::serial::{Encodable, Decodable, ReadExt, WriteExt};
 use crate::error::{Error, Result};
+use crate::serial::{Decodable, Encodable, ReadExt, WriteExt};
 
 impl Encodable for jubjub::Fr {
     fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
@@ -43,4 +43,3 @@ impl Decodable for jubjub::SubgroupPoint {
         }
     }
 }
-

+ 0 - 1
src/crypto/merkle.rs

@@ -498,4 +498,3 @@ impl<Node: Hashable> MerklePath<Node> {
             )
     }
 }
-

+ 2 - 2
src/crypto/mint_proof.rs

@@ -3,9 +3,9 @@ use bellman::groth16;
 use blake2s_simd::Params as Blake2sParams;
 use bls12_381::Bls12;
 use ff::Field;
-use std::io;
 use group::{Curve, Group, GroupEncoding};
 use rand::rngs::OsRng;
+use std::io;
 use std::time::Instant;
 
 use crate::circuit::mint_contract::MintContract;
@@ -89,7 +89,7 @@ impl Decodable for MintRevealedValues {
     fn decode<D: io::Read>(mut d: D) -> Result<Self> {
         Ok(Self {
             value_commit: Decodable::decode(&mut d)?,
-            coin: Decodable::decode(d)?
+            coin: Decodable::decode(d)?,
         })
     }
 }

+ 7 - 9
src/crypto/note.rs

@@ -1,14 +1,13 @@
 use crypto_api_chachapoly::ChachaPolyIetf;
 use ff::Field;
-use std::io;
 use rand::rngs::OsRng;
+use std::io;
 
-use crate::serial::{Encodable, Decodable, ReadExt, WriteExt};
+use super::diffie_hellman::{kdf_sapling, sapling_ka_agree};
 use crate::error::{Error, Result};
-use super::diffie_hellman::{sapling_ka_agree, kdf_sapling};
+use crate::serial::{Decodable, Encodable, ReadExt, WriteExt};
 
-pub const NOTE_PLAINTEXT_SIZE: usize =
-    32 + // serial
+pub const NOTE_PLAINTEXT_SIZE: usize = 32 + // serial
     8 + // value
     32 + // coin_blind
     32; // valcom_blind
@@ -39,7 +38,7 @@ impl Decodable for Note {
             serial: Decodable::decode(&mut d)?,
             value: Decodable::decode(&mut d)?,
             coin_blind: Decodable::decode(&mut d)?,
-            valcom_blind: Decodable::decode(d)?
+            valcom_blind: Decodable::decode(d)?,
         })
     }
 }
@@ -64,14 +63,14 @@ impl Note {
 
         Ok(EncryptedNote {
             ciphertext,
-            ephem_public
+            ephem_public,
         })
     }
 }
 
 pub struct EncryptedNote {
     ciphertext: [u8; ENC_CIPHERTEXT_SIZE],
-    ephem_public: jubjub::SubgroupPoint
+    ephem_public: jubjub::SubgroupPoint,
 }
 
 impl EncryptedNote {
@@ -113,4 +112,3 @@ fn test_note_encdec() {
     let note2 = encrypted_note.decrypt(&secret).unwrap();
     assert_eq!(note.value, note2.value);
 }
-

+ 0 - 1
src/crypto/schnorr.rs

@@ -52,4 +52,3 @@ fn test_schnorr() {
     let public = secret.public_key();
     assert!(public.verify(&message[..], &signature));
 }
-

+ 6 - 5
src/crypto/spend_proof.rs

@@ -8,8 +8,8 @@ use group::{Curve, GroupEncoding};
 use rand::rngs::OsRng;
 use std::time::Instant;
 
-use crate::circuit::spend_contract::SpendContract;
 use super::coin::merkle_hash;
+use crate::circuit::spend_contract::SpendContract;
 use crate::error::Result;
 
 pub struct SpendRevealedValues {
@@ -18,7 +18,7 @@ pub struct SpendRevealedValues {
     // This should not be here, we just have it for debugging
     //coin: [u8; 32],
     pub merkle_root: bls12_381::Scalar,
-    pub signature_public: jubjub::SubgroupPoint
+    pub signature_public: jubjub::SubgroupPoint,
 }
 
 impl SpendRevealedValues {
@@ -49,7 +49,8 @@ impl SpendRevealedValues {
         );
 
         let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
-        let signature_public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * signature_secret;
+        let signature_public =
+            zcash_primitives::constants::SPENDING_KEY_GENERATOR * signature_secret;
 
         let mut coin = [0; 32];
         coin.copy_from_slice(
@@ -85,7 +86,7 @@ impl SpendRevealedValues {
             value_commit,
             nullifier,
             merkle_root,
-            signature_public
+            signature_public,
         }
     }
 
@@ -213,7 +214,7 @@ pub fn create_spend_proof(
         &randomness_coin,
         &secret,
         &merkle_path,
-        &signature_secret
+        &signature_secret,
     );
 
     (proof, revealed)

+ 1 - 1
src/lib.rs

@@ -12,11 +12,11 @@ pub mod gfx;
 pub mod gui;
 pub mod net;
 pub mod serial;
+pub mod service;
 pub mod system;
 pub mod tx;
 pub mod vm;
 pub mod vm_serial;
-pub mod service;
 
 pub use crate::bls_extensions::BlsStringConversion;
 pub use crate::error::{Error, Result};

+ 20 - 24
src/service/gateway.rs

@@ -1,31 +1,27 @@
 use image::EncodableLayout;
 
+use super::reqrep::{Reply, Request};
+use crate::serial::{deserialize, serialize};
 use crate::Result;
-use crate::serial::{serialize, deserialize};
-use super::reqrep::{Request, Reply};
 
-use async_zmq;
-use async_std::sync::Arc;
 use async_executor::Executor;
+use async_std::sync::Arc;
+use async_zmq;
 use futures::FutureExt;
 
-
-
 pub struct GatewayService;
 
-
-enum NetEvent{
+enum NetEvent {
     RECEIVE(async_zmq::Multipart),
-    SEND(async_zmq::Multipart)
+    SEND(async_zmq::Multipart),
 }
 
-
 impl GatewayService {
-
-    pub async fn start(
-        executor: Arc<Executor<'_>>,
-    ) {
-        let mut worker = async_zmq::reply("tcp://127.0.0.1:4444").unwrap().connect().unwrap();
+    pub async fn start(executor: Arc<Executor<'_>>) {
+        let mut worker = async_zmq::reply("tcp://127.0.0.1:4444")
+            .unwrap()
+            .connect()
+            .unwrap();
 
         let (send_queue_s, send_queue_r) = async_channel::unbounded::<async_zmq::Multipart>();
 
@@ -38,17 +34,20 @@ impl GatewayService {
 
             match event {
                 NetEvent::RECEIVE(request) => {
-                    ex2.spawn(Self::handle_request(send_queue_s.clone(), request)).detach();
-                },
+                    ex2.spawn(Self::handle_request(send_queue_s.clone(), request))
+                        .detach();
+                }
                 NetEvent::SEND(reply) => {
                     worker.send(reply).await.unwrap();
-                },
+                }
             }
         }
-
     }
 
-    async fn handle_request(send_queue: async_channel::Sender<async_zmq::Multipart>, request: async_zmq::Multipart) -> Result<()> {
+    async fn handle_request(
+        send_queue: async_channel::Sender<async_zmq::Multipart>,
+        request: async_zmq::Multipart,
+    ) -> Result<()> {
         let mut messages = vec![];
         for req in request.iter() {
             let req = req.as_bytes();
@@ -69,14 +68,11 @@ impl GatewayService {
     }
 }
 
-
 struct GatewayClient;
 
-
 #[repr(u8)]
-enum GatewayCommand{
+enum GatewayCommand {
     PUTSLAB,
     GETSLAB,
     GETLASTINDEX,
 }
-

+ 1 - 3
src/service/mod.rs

@@ -1,4 +1,2 @@
-
-pub mod reqrep;
 pub mod gateway;
-
+pub mod reqrep;

+ 18 - 25
src/service/reqrep.rs

@@ -7,20 +7,18 @@ use rand::Rng;
 
 pub struct ReqRepAPI;
 
-
-
 impl ReqRepAPI {
-    pub async fn start()  {
-
+    pub async fn start() {
         let context = zmq::Context::new();
         let frontend = context.socket(zmq::ROUTER).unwrap();
         let backend = context.socket(zmq::DEALER).unwrap();
 
-
         frontend
-            .bind("tcp://127.0.0.1:3333") .expect("failed binding frontend");
+            .bind("tcp://127.0.0.1:3333")
+            .expect("failed binding frontend");
         backend
-            .bind("tcp://127.0.0.1:4444") .expect("failed binding backend");
+            .bind("tcp://127.0.0.1:4444")
+            .expect("failed binding backend");
 
         loop {
             let mut items = [
@@ -35,9 +33,10 @@ impl ReqRepAPI {
                     let message = frontend.recv_msg(0).unwrap();
                     let more = message.get_more();
                     backend
-                        .send(message, if more { zmq::SNDMORE } else { 0 }).unwrap();
+                        .send(message, if more { zmq::SNDMORE } else { 0 })
+                        .unwrap();
                     if !more {
-                        break
+                        break;
                     }
                 }
             }
@@ -46,9 +45,10 @@ impl ReqRepAPI {
                     let message = backend.recv_msg(0).unwrap();
                     let more = message.get_more();
                     frontend
-                        .send(message, if more { zmq::SNDMORE } else { 0 }).unwrap();
+                        .send(message, if more { zmq::SNDMORE } else { 0 })
+                        .unwrap();
                     if !more {
-                        break
+                        break;
                     }
                 }
             }
@@ -56,7 +56,6 @@ impl ReqRepAPI {
     }
 }
 
-
 #[derive(Debug, PartialEq)]
 pub struct Request {
     command: u8,
@@ -95,13 +94,11 @@ impl Reply {
         Reply {
             id: request.get_id(),
             error,
-            payload
+            payload,
         }
     }
 }
 
-
-
 impl Encodable for Request {
     fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
         let mut len = 0;
@@ -142,17 +139,14 @@ impl Decodable for Reply {
     }
 }
 
-
-
-
 #[cfg(test)]
 mod tests {
+    use super::{Reply, Request, Result};
     use crate::serial::{deserialize, serialize};
-    use super::{Request, Reply, Result};
 
     #[test]
-    fn serialize_and_deserialize_request_test(){
-        let request = Request::new(2, vec![2,3,4,6,4]);
+    fn serialize_and_deserialize_request_test() {
+        let request = Request::new(2, vec![2, 3, 4, 6, 4]);
         let serialized_request = serialize(&request);
         assert!((deserialize(&serialized_request) as Result<bool>).is_err());
         let deserialized_request = deserialize(&serialized_request).ok();
@@ -160,13 +154,12 @@ mod tests {
     }
 
     #[test]
-    fn serialize_and_deserialize_reply_test(){
-        let request = Request::new(2, vec![2,3,4,6,4]);
-        let reply = Reply::from(&request, 0, vec![2,3,4,6,4]);
+    fn serialize_and_deserialize_reply_test() {
+        let request = Request::new(2, vec![2, 3, 4, 6, 4]);
+        let reply = Reply::from(&request, 0, vec![2, 3, 4, 6, 4]);
         let serialized_reply = serialize(&reply);
         assert!((deserialize(&serialized_reply) as Result<bool>).is_err());
         let deserialized_reply = deserialize(&serialized_reply).ok();
         assert_eq!(deserialized_reply, Some(reply));
     }
-
 }

+ 11 - 9
src/tx.rs

@@ -1,18 +1,17 @@
-use std::io;
 use bellman::groth16;
 use bls12_381::Bls12;
 use ff::Field;
 use group::Group;
 use rand::rngs::OsRng;
+use std::io;
 
 use crate::crypto::{
-    create_mint_proof, load_params, save_params, setup_mint_prover, verify_mint_proof,
+    create_mint_proof, load_params, note::Note, save_params, setup_mint_prover, verify_mint_proof,
     MintRevealedValues,
-    note::Note
 };
-use crate::serial::{Decodable, Encodable, VarInt};
 use crate::error::{Error, Result};
 use crate::impl_vec;
+use crate::serial::{Decodable, Encodable, VarInt};
 
 pub struct TransactionBuilder {
     pub clear_inputs: Vec<TransactionBuilderClearInputInfo>,
@@ -37,7 +36,11 @@ impl TransactionBuilder {
         lhs_total - rhs_total
     }
 
-    pub fn build(self, mint_params: &groth16::Parameters<Bls12>) -> Transaction {
+    pub fn build(
+        self,
+        mint_params: &groth16::Parameters<Bls12>,
+        spend_params: &groth16::Parameters<Bls12>,
+    ) -> Transaction {
         let mut clear_inputs = vec![];
         for input in &self.clear_inputs {
             let valcom_blind: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
@@ -115,7 +118,7 @@ impl Decodable for Transaction {
     fn decode<D: io::Read>(mut d: D) -> Result<Self> {
         Ok(Self {
             clear_inputs: Decodable::decode(&mut d)?,
-            outputs: Decodable::decode(d)?
+            outputs: Decodable::decode(d)?,
         })
     }
 }
@@ -164,7 +167,7 @@ impl Decodable for TransactionClearInput {
     fn decode<D: io::Read>(mut d: D) -> Result<Self> {
         Ok(Self {
             value: Decodable::decode(&mut d)?,
-            valcom_blind: Decodable::decode(d)?
+            valcom_blind: Decodable::decode(d)?,
         })
     }
 }
@@ -189,8 +192,7 @@ impl Decodable for TransactionOutput {
     fn decode<D: io::Read>(mut d: D) -> Result<Self> {
         Ok(Self {
             mint_proof: Decodable::decode(&mut d)?,
-            revealed: Decodable::decode(d)?
+            revealed: Decodable::decode(d)?,
         })
     }
 }
-