Преглед изворни кода

Add debug derives and more serialization test units.

parazyd пре 4 година
родитељ
комит
5aef00247e

+ 7 - 1
src/client.rs

@@ -248,7 +248,13 @@ impl Client {
         notify: Option<async_channel::Sender<(PublicKey, u64)>>,
         notify: Option<async_channel::Sender<(PublicKey, u64)>>,
     ) -> Result<()> {
     ) -> Result<()> {
         debug!("Build tx from slab and update the state");
         debug!("Build tx from slab and update the state");
-        let tx = tx::Transaction::decode(&slab.get_payload()[..])?;
+        let payload = slab.get_payload();
+        /*
+        use std::io::Write;
+        let mut file = std::fs::File::create("/tmp/payload.txt")?;
+        file.write_all(&payload)?;
+        */
+        let tx = tx::Transaction::decode(&payload[..])?;
 
 
         let st = &*state.lock().await;
         let st = &*state.lock().await;
         let update = state_transition(st, tx)?;
         let update = state_transition(st, tx)?;

+ 1 - 2
src/crypto/coin.rs

@@ -31,7 +31,6 @@ impl Decodable for Coin {
     fn decode<D: io::Read>(mut d: D) -> Result<Self> {
     fn decode<D: io::Read>(mut d: D) -> Result<Self> {
         let mut bytes = [0u8; 32];
         let mut bytes = [0u8; 32];
         d.read_slice(&mut bytes)?;
         d.read_slice(&mut bytes)?;
-        let result = Self::from_bytes(&bytes);
-        Ok(result)
+        Ok(Self::from_bytes(&bytes))
     }
     }
 }
 }

+ 50 - 0
src/crypto/keypair.rs

@@ -160,7 +160,57 @@ impl Decodable for PublicKey {
         if result.is_some().into() {
         if result.is_some().into() {
             Ok(PublicKey(result.unwrap()))
             Ok(PublicKey(result.unwrap()))
         } else {
         } else {
+            log::debug!("Failed decoding PublicKey");
             Err(Error::BadOperationType)
             Err(Error::BadOperationType)
         }
         }
     }
     }
 }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::{
+        crypto::util::pedersen_commitment_scalar,
+        serial::{deserialize, serialize},
+    };
+
+    #[test]
+    fn test_pasta_serialization() -> Result<()> {
+        let fifty_five = pallas::Base::from(55);
+        let serialized = serialize(&fifty_five);
+        assert_eq!(
+            serialized,
+            vec![
+                55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                0, 0, 0, 0, 0
+            ]
+        );
+        assert_eq!(deserialize(&serialized).ok(), Some(fifty_five));
+
+        let fourtwenty = pallas::Scalar::from(42069);
+        let serialized = serialize(&fourtwenty);
+        assert_eq!(
+            serialized,
+            vec![
+                85, 164, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                0, 0, 0, 0, 0
+            ]
+        );
+        assert_eq!(deserialize(&serialized).ok(), Some(fourtwenty));
+
+        let a = pallas::Scalar::from(420);
+        let b = pallas::Scalar::from(69);
+        let pc: pallas::Point = pedersen_commitment_scalar(a, b);
+        let serialized = serialize(&pc);
+        assert_eq!(
+            serialized,
+            vec![
+                55, 48, 126, 42, 114, 27, 18, 55, 155, 141, 83, 75, 44, 50, 244, 223, 254, 216, 22,
+                167, 208, 59, 212, 201, 150, 149, 96, 207, 216, 74, 60, 131
+            ]
+        );
+        assert_eq!(deserialize(&serialized).ok(), Some(pc));
+
+        Ok(())
+    }
+}

+ 4 - 2
src/crypto/mint_proof.rs

@@ -8,6 +8,7 @@ use log::debug;
 use pasta_curves::{
 use pasta_curves::{
     arithmetic::{CurveAffine, FieldExt},
     arithmetic::{CurveAffine, FieldExt},
     group::Curve,
     group::Curve,
+    pallas,
 };
 };
 
 
 use crate::{
 use crate::{
@@ -19,10 +20,11 @@ use crate::{
         util::{mod_r_p, pedersen_commitment_scalar, pedersen_commitment_u64},
         util::{mod_r_p, pedersen_commitment_scalar, pedersen_commitment_u64},
     },
     },
     serial::{Decodable, Encodable},
     serial::{Decodable, Encodable},
-    types::*,
+    types::{DrkCoinBlind, DrkSerial, DrkTokenId, DrkValue, DrkValueBlind, DrkValueCommit},
     Result,
     Result,
 };
 };
 
 
+#[derive(Debug)]
 pub struct MintRevealedValues {
 pub struct MintRevealedValues {
     pub value_commit: DrkValueCommit,
     pub value_commit: DrkValueCommit,
     pub token_commit: DrkValueCommit,
     pub token_commit: DrkValueCommit,
@@ -51,7 +53,7 @@ impl MintRevealedValues {
         MintRevealedValues { value_commit, token_commit, coin: Coin(coin) }
         MintRevealedValues { value_commit, token_commit, coin: Coin(coin) }
     }
     }
 
 
-    fn make_outputs(&self) -> [DrkCircuitField; 5] {
+    fn make_outputs(&self) -> [pallas::Base; 5] {
         let value_coords = self.value_commit.to_affine().coordinates().unwrap();
         let value_coords = self.value_commit.to_affine().coordinates().unwrap();
         let token_coords = self.token_commit.to_affine().coordinates().unwrap();
         let token_coords = self.token_commit.to_affine().coordinates().unwrap();
 
 

+ 22 - 20
src/crypto/note.rs

@@ -76,6 +76,7 @@ impl Note {
     }
     }
 }
 }
 
 
+#[derive(Debug)]
 pub struct EncryptedNote {
 pub struct EncryptedNote {
     ciphertext: [u8; ENC_CIPHERTEXT_SIZE],
     ciphertext: [u8; ENC_CIPHERTEXT_SIZE],
     ephem_public: PublicKey,
     ephem_public: PublicKey,
@@ -116,26 +117,27 @@ impl EncryptedNote {
     }
     }
 }
 }
 
 
-#[test]
-fn test_note_encdec() {
-    use crate::{
-        crypto::keypair::Keypair,
-        types::{DrkCoinBlind, DrkSerial, DrkTokenId, DrkValueBlind},
-    };
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::crypto::keypair::Keypair;
     use pasta_curves::arithmetic::Field;
     use pasta_curves::arithmetic::Field;
 
 
-    let note = Note {
-        serial: DrkSerial::random(&mut OsRng),
-        value: 110,
-        token_id: DrkTokenId::random(&mut OsRng),
-        coin_blind: DrkCoinBlind::random(&mut OsRng),
-        value_blind: DrkValueBlind::random(&mut OsRng),
-    };
-
-    let keypair = Keypair::random(&mut OsRng);
-
-    let encrypted_note = note.encrypt(&keypair.public).unwrap();
-    let note2 = encrypted_note.decrypt(&keypair.secret).unwrap();
-    assert_eq!(note.value, note2.value);
-    assert_eq!(note.token_id, note2.token_id);
+    #[test]
+    fn test_note_encdec() {
+        let note = Note {
+            serial: DrkSerial::random(&mut OsRng),
+            value: 110,
+            token_id: DrkTokenId::random(&mut OsRng),
+            coin_blind: DrkCoinBlind::random(&mut OsRng),
+            value_blind: DrkValueBlind::random(&mut OsRng),
+        };
+
+        let keypair = Keypair::random(&mut OsRng);
+
+        let encrypted_note = note.encrypt(&keypair.public).unwrap();
+        let note2 = encrypted_note.decrypt(&keypair.secret).unwrap();
+        assert_eq!(note.value, note2.value);
+        assert_eq!(note.token_id, note2.token_id);
+    }
 }
 }

+ 44 - 4
src/crypto/proof.rs

@@ -10,7 +10,7 @@ use halo2::{
 use pasta_curves::vesta;
 use pasta_curves::vesta;
 
 
 use crate::{
 use crate::{
-    serial::{Decodable, Encodable, ReadExt, VarInt, WriteExt},
+    serial::{encode_with_size, Decodable, Encodable, ReadExt, VarInt},
     types::*,
     types::*,
     Result,
     Result,
 };
 };
@@ -89,9 +89,8 @@ impl Proof {
 }
 }
 
 
 impl Encodable for Proof {
 impl Encodable for Proof {
-    fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
-        s.write_slice(self.as_ref())?;
-        Ok(self.as_ref().len())
+    fn encode<S: io::Write>(&self, s: S) -> Result<usize> {
+        encode_with_size(self.as_ref(), s)
     }
     }
 }
 }
 
 
@@ -103,3 +102,44 @@ impl Decodable for Proof {
         Ok(Proof::new(r))
         Ok(Proof::new(r))
     }
     }
 }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::{
+        circuit::MintContract,
+        crypto::{keypair::PublicKey, mint_proof::create_mint_proof},
+    };
+    use halo2::arithmetic::Field;
+    use rand::rngs::OsRng;
+
+    #[test]
+    fn test_proof_serialization() -> Result<()> {
+        let value = 110_u64;
+        let token_id = DrkTokenId::from(42);
+        let value_blind = DrkValueBlind::random(&mut OsRng);
+        let token_blind = DrkValueBlind::random(&mut OsRng);
+        let serial = DrkSerial::random(&mut OsRng);
+        let coin_blind = DrkCoinBlind::random(&mut OsRng);
+        let public_key = PublicKey::random(&mut OsRng);
+
+        let pk = ProvingKey::build(11, MintContract::default());
+        let (proof, _) = create_mint_proof(
+            &pk,
+            value,
+            token_id,
+            value_blind,
+            token_blind,
+            serial,
+            coin_blind,
+            public_key,
+        )?;
+
+        let mut buf = vec![];
+        proof.encode(&mut buf)?;
+        let deserialized_proof: Proof = Decodable::decode(&mut buf.as_slice())?;
+        assert_eq!(proof.as_ref(), deserialized_proof.as_ref());
+
+        Ok(())
+    }
+}

+ 1 - 0
src/crypto/schnorr.rs

@@ -14,6 +14,7 @@ use crate::{
     Result,
     Result,
 };
 };
 
 
+#[derive(Debug)]
 pub struct Signature {
 pub struct Signature {
     commit: pallas::Point,
     commit: pallas::Point,
     response: pallas::Scalar,
     response: pallas::Scalar,

+ 1 - 0
src/crypto/spend_proof.rs

@@ -28,6 +28,7 @@ use crate::{
     Result,
     Result,
 };
 };
 
 
+#[derive(Debug)]
 pub struct SpendRevealedValues {
 pub struct SpendRevealedValues {
     pub value_commit: DrkValueCommit,
     pub value_commit: DrkValueCommit,
     pub token_commit: DrkValueCommit,
     pub token_commit: DrkValueCommit,

+ 3 - 0
src/tx/mod.rs

@@ -36,6 +36,7 @@ pub struct Transaction {
     pub outputs: Vec<TransactionOutput>,
     pub outputs: Vec<TransactionOutput>,
 }
 }
 
 
+#[derive(Debug)]
 pub struct TransactionClearInput {
 pub struct TransactionClearInput {
     pub value: u64,
     pub value: u64,
     pub token_id: DrkTokenId,
     pub token_id: DrkTokenId,
@@ -45,12 +46,14 @@ pub struct TransactionClearInput {
     pub signature: schnorr::Signature,
     pub signature: schnorr::Signature,
 }
 }
 
 
+#[derive(Debug)]
 pub struct TransactionInput {
 pub struct TransactionInput {
     pub spend_proof: Proof,
     pub spend_proof: Proof,
     pub revealed: SpendRevealedValues,
     pub revealed: SpendRevealedValues,
     pub signature: schnorr::Signature,
     pub signature: schnorr::Signature,
 }
 }
 
 
+#[derive(Debug)]
 pub struct TransactionOutput {
 pub struct TransactionOutput {
     pub mint_proof: Proof,
     pub mint_proof: Proof,
     pub revealed: MintRevealedValues,
     pub revealed: MintRevealedValues,

+ 2 - 3
src/util/parse.rs

@@ -195,11 +195,10 @@ pub fn truncate(amount: u64, decimals: u16, token_decimals: u16) -> Result<u64>
     Ok(amount)
     Ok(amount)
 }
 }
 
 
-#[allow(unused_imports)]
+#[cfg(test)]
 mod tests {
 mod tests {
-    use num_bigint::ToBigUint;
-
     use super::{decode_base10, encode_base10, truncate};
     use super::{decode_base10, encode_base10, truncate};
+    use num_bigint::ToBigUint;
 
 
     #[test]
     #[test]
     fn test_decode_base10() {
     fn test_decode_base10() {

+ 1 - 1
src/util/token_list.rs

@@ -119,7 +119,7 @@ impl DrkTokenList {
     }
     }
 }
 }
 
 
-#[allow(unused_imports)]
+#[cfg(test)]
 mod tests {
 mod tests {
     use super::*;
     use super::*;
     use crate::{
     use crate::{