Ver Fonte

cargo fmt & clean up

ghassmo há 5 anos atrás
pai
commit
1a6bccd8e9
10 ficheiros alterados com 58 adições e 77 exclusões
  1. 10 3
      src/bin/demowallet.rs
  2. 1 1
      src/bin/gatewayd.rs
  3. 1 1
      src/crypto/mod.rs
  4. 2 4
      src/error.rs
  5. 1 1
      src/lib.rs
  6. 5 5
      src/rpc/adapter.rs
  7. 3 9
      src/service/gateway.rs
  8. 22 24
      src/service/reqrep.rs
  9. 11 28
      src/slabstore.rs
  10. 2 1
      src/tx/builder.rs

+ 10 - 3
src/bin/demowallet.rs

@@ -15,13 +15,20 @@ async fn start(executor: Arc<Executor<'_>>) -> Result<()> {
 
     let subscriber = client.subscribe("127.0.0.1:4444".parse()?).await?;
 
-    println!("subscription ready");
+    println!("subscriber ready");
 
     let fetch_loop_task = executor.spawn(fetch_slabs_loop(subscriber.clone(), slabs.clone()));
 
+    println!("send put slab");
     client.put_slab(vec![0, 0, 0, 0]).await?;
-    client.put_slab(vec![0, 0, 0, 0]).await?;
-    client.put_slab(vec![0, 0, 0, 0]).await?;
+
+    println!("send get last index");
+    let index = client.get_last_index().await?;
+    println!("index: {}", index);
+
+    println!("send get slab");
+    let x = client.get_slab(index).await?;
+    println!("{:?}", x);
 
     fetch_loop_task.cancel().await;
 

+ 1 - 1
src/bin/gatewayd.rs

@@ -20,7 +20,7 @@ async fn start(executor: Arc<Executor<'_>>, options: ProgramOptions) -> Result<(
     let accept_addr: SocketAddr = setup_addr(options.accept_addr, "127.0.0.1:3333".parse()?);
     let pub_addr: SocketAddr = setup_addr(options.pub_addr, "127.0.0.1:4444".parse()?);
 
-    let gateway = GatewayService::new(accept_addr, pub_addr);
+    let gateway = GatewayService::new(accept_addr, pub_addr)?;
 
     gateway.start(executor.clone()).await?;
     Ok(())

+ 1 - 1
src/crypto/mod.rs

@@ -2,8 +2,8 @@ pub mod coin;
 pub mod diffie_hellman;
 pub mod fr_serial;
 pub mod merkle;
-pub mod mint_proof;
 pub mod merkle_node;
+pub mod mint_proof;
 pub mod note;
 pub mod nullifier;
 pub mod schnorr;

+ 2 - 4
src/error.rs

@@ -71,16 +71,14 @@ impl fmt::Display for Error {
             Error::Utf8Error => f.write_str("Malformed UTF8"),
             Error::NoteDecryptionFailed => f.write_str("Unable to decrypt mint note"),
             Error::ServicesError(ref err) => write!(f, "Services error: {}", err),
-            Error::ZMQError(ref err) =>  write!(f, "ZMQError: {}", err),
+            Error::ZMQError(ref err) => write!(f, "ZMQError: {}", err),
             Error::VerifyFailed => f.write_str("Verify failed"),
             Error::TryIntoError => f.write_str("TryInto get an error"),
-            Error::RocksdbError(ref err) => write!(f, "Rocksdb Error: {}", err)
+            Error::RocksdbError(ref err) => write!(f, "Rocksdb Error: {}", err),
         }
     }
 }
 
-
-
 // TODO: Match statement to parse external errors into strings.
 impl From<zeromq::ZmqError> for Error {
     fn from(err: zeromq::ZmqError) -> Error {

+ 1 - 1
src/lib.rs

@@ -16,12 +16,12 @@ pub mod net;
 pub mod rpc;
 pub mod serial;
 pub mod service;
+pub mod slabstore;
 pub mod state;
 pub mod system;
 pub mod tx;
 pub mod vm;
 pub mod vm_serial;
-pub mod slabstore;
 
 pub use crate::bls_extensions::BlsStringConversion;
 pub use crate::error::{Error, Result};

+ 5 - 5
src/rpc/adapter.rs

@@ -1,13 +1,13 @@
 #[macro_use]
 use std::sync::Arc;
-use rusqlite::Connection;
+use crate::serial;
+use crate::Result;
 use ff::Field;
 use rand::rngs::OsRng;
+use rusqlite::Connection;
+use smol::Async;
 use std::fs::File;
 use std::io::prelude::*;
-use crate::serial;
-use crate::Result;
-use smol::Async;
 
 // Dummy adapter for now
 pub struct RpcAdapter {}
@@ -47,7 +47,7 @@ impl RpcAdapter {
         println!("New wallet created");
         Ok(conn.execute_batch(&mut contents)?)
     }
-    
+
     //pub async fn decrypt(conn: &Connection, password: )
     // TODO: getting an error when i call this function- does not implement send
     pub async fn save_key(conn: &Connection, pubkey: Vec<u8>, privkey: Vec<u8>) -> Result<()> {

+ 3 - 9
src/service/gateway.rs

@@ -1,10 +1,10 @@
 use async_std::sync::{Arc, Mutex};
+use std::convert::From;
 use std::net::SocketAddr;
 use std::path::Path;
-use std::convert::From;
 
 use super::reqrep::{Publisher, RepProtocol, Reply, ReqProtocol, Request, Subscriber};
-use crate::{Error, Result, slabstore::SlabStore, serial::serialize, serial::deserialize};
+use crate::{serial::deserialize, serial::serialize, slabstore::SlabStore, Error, Result};
 
 use async_executor::Executor;
 use log::*;
@@ -26,7 +26,6 @@ pub struct GatewayService {
 
 impl GatewayService {
     pub fn new(addr: SocketAddr, pub_addr: SocketAddr) -> Result<Arc<GatewayService>> {
-
         let publisher = Mutex::new(Publisher::new(pub_addr));
 
         let slabstore = SlabStore::new(Path::new("../slabstore.db"))?;
@@ -39,8 +38,7 @@ impl GatewayService {
     }
 
     pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-
-        let mut protocol = RepProtocol::new(String::from("GATEWAY"),self.addr.clone());
+        let mut protocol = RepProtocol::new(String::from("GATEWAY"), self.addr.clone());
 
         let (send, recv) = protocol.start().await?;
 
@@ -54,7 +52,6 @@ impl GatewayService {
         Ok(())
     }
 
-
     async fn handle_request(
         self: Arc<Self>,
         send_queue: async_channel::Sender<Reply>,
@@ -83,7 +80,6 @@ impl GatewayService {
                             info!("received putslab msg");
                         }
                         1 => {
-
                             let index = request.get_payload();
                             let slab = self.slabstore.get(index)?;
 
@@ -162,7 +158,6 @@ impl GatewayClient {
     }
 }
 
-
 pub async fn fetch_slabs_loop(
     subscriber: Arc<Mutex<Subscriber>>,
     slabs: Arc<Mutex<Slabs>>,
@@ -177,4 +172,3 @@ pub async fn fetch_slabs_loop(
         slabs.lock().await.push(slab);
     }
 }
-

+ 22 - 24
src/service/reqrep.rs

@@ -5,20 +5,18 @@ use std::net::SocketAddr;
 use crate::serial::{deserialize, serialize};
 use crate::{Decodable, Encodable, Result};
 
+use async_executor::Executor;
 use bytes::Bytes;
 use futures::FutureExt;
+use log::*;
 use rand::Rng;
+use signal_hook::{consts::SIGINT, iterator::Signals};
 use zeromq::*;
-use signal_hook::{iterator::Signals, consts::SIGINT};
-use async_executor::Executor;
-use log::*;
-
-
 
 enum NetEvent {
     Receive(zeromq::ZmqMessage),
     Send(Reply),
-    Stop
+    Stop,
 }
 
 pub fn addr_to_string(addr: SocketAddr) -> String {
@@ -58,8 +56,8 @@ impl RepProtocol {
     pub async fn start(
         &mut self,
     ) -> Result<(
-    async_channel::Sender<Reply>,
-    async_channel::Receiver<Request>,
+        async_channel::Sender<Reply>,
+        async_channel::Receiver<Request>,
     )> {
         let addr = addr_to_string(self.addr);
         self.socket.bind(addr.as_str()).await?;
@@ -68,7 +66,6 @@ impl RepProtocol {
     }
 
     pub async fn run(&mut self, executor: Arc<Executor<'_>>) -> Result<()> {
-
         info!("{} SERVICE: running", self.service_name);
 
         let (stop_s, stop_r) = async_channel::unbounded::<()>();
@@ -93,19 +90,18 @@ impl RepProtocol {
             match event {
                 NetEvent::Receive(request) => {
                     if let Some(req) = request.get(0) {
-                        let request: Vec<u8> = req.to_vec();
-                        let req: Request = deserialize(&request)?;
+                        let req: Vec<u8> = req.to_vec();
+                        let req: Request = deserialize(&req)?;
                         self.send_queue.send(req).await?;
                     }
                 }
                 NetEvent::Send(reply) => {
                     let reply: Vec<u8> = serialize(&reply);
                     let reply = Bytes::from(reply);
-                    self.socket.send(reply.into()).await?;
-                }
-                NetEvent::Stop => {
-                    break
+                    let reply: zeromq::ZmqMessage = reply.into();
+                    self.socket.send(reply).await?;
                 }
+                NetEvent::Stop => break,
             }
         }
         let _ = stop_task.cancel().await;
@@ -135,14 +131,15 @@ impl ReqProtocol {
         let request = Request::new(command, data);
         let req = serialize(&request);
         let req = bytes::Bytes::from(req);
+        let req: zeromq::ZmqMessage = req.into();
 
-        self.socket.send(req.into()).await?;
+        self.socket.send(req).await?;
 
         let rep: zeromq::ZmqMessage = self.socket.recv().await?;
-        if let Some(rep) = rep.get(0) {
-            let rep: Vec<u8> = rep.to_vec();
+        if let Some(reply) = rep.get(0) {
+            let reply: Vec<u8> = reply.to_vec();
 
-            let reply: Reply = deserialize(&rep)?;
+            let reply: Reply = deserialize(&reply)?;
 
             if reply.has_error() {
                 return Err(crate::Error::ServicesError("response has an error"));
@@ -152,7 +149,9 @@ impl ReqProtocol {
 
             Ok(reply.get_payload())
         } else {
-            Err(crate::Error::ZMQError("Couldn't parse ZmqMessage".to_string()))
+            Err(crate::Error::ZMQError(
+                "Couldn't parse ZmqMessage".to_string(),
+            ))
         }
     }
 }
@@ -207,11 +206,10 @@ impl Subscriber {
                 let data = d.to_vec();
                 Ok(data)
             }
-            None => {
-                Err(crate::Error::ZMQError("Couldn't parse ZmqMessage".to_string()))
-            }
+            None => Err(crate::Error::ZMQError(
+                "Couldn't parse ZmqMessage".to_string(),
+            )),
         }
-
     }
 }
 

+ 11 - 28
src/slabstore.rs

@@ -1,20 +1,19 @@
 use std::path::Path;
 use std::sync::Arc;
 
+use crate::serial::{deserialize, serialize, Decodable, Encodable};
 use crate::Result;
-use crate::serial::{serialize, deserialize, Encodable, Decodable};
 
-use rocksdb::{DB, Options, IteratorMode};
+use rocksdb::{IteratorMode, Options, DB};
 
 pub struct SlabStore {
     db: DB,
     opt: Options,
-    path: Arc<Path>
+    path: Arc<Path>,
 }
 
 impl SlabStore {
     pub fn new(path: &Path) -> Result<Self> {
-
         let mut opt = Options::default();
         opt.create_if_missing(true);
 
@@ -22,26 +21,20 @@ impl SlabStore {
 
         let path = Arc::from(path);
 
-        Ok(SlabStore {
-            db,
-            opt,
-            path
-        })
+        Ok(SlabStore { db, opt, path })
     }
 
-
-    pub fn get(&self, key: Vec<u8>) -> Result<Option<Vec<u8>>>{
+    pub fn get(&self, key: Vec<u8>) -> Result<Option<Vec<u8>>> {
         let value = self.db.get(key)?;
         Ok(value)
     }
 
-    pub fn put(&self, value: Vec<u8>) -> Result<()>{
+    pub fn put(&self, value: Vec<u8>) -> Result<()> {
         let key = self.increase_index()?;
         self.db.put(key, value)?;
         Ok(())
     }
 
-
     pub fn get_value_deserialized<T: Decodable>(&self, key: Vec<u8>) -> Result<Option<T>> {
         let value = self.db.get(key)?;
         match value {
@@ -49,9 +42,7 @@ impl SlabStore {
                 let v = deserialize(&v)?;
                 Ok(Some(v))
             }
-            None => {
-                Ok(None)
-            }
+            None => Ok(None),
         }
     }
 
@@ -65,20 +56,16 @@ impl SlabStore {
     pub fn get_last_index(&self) -> Result<u64> {
         let last_index = self.db.iterator(IteratorMode::End).next();
         match last_index {
-            Some((index, _)) => {
-                Ok(deserialize(&index)?)
-            }
-            None => Ok(0)
+            Some((index, _)) => Ok(deserialize(&index)?),
+            None => Ok(0),
         }
     }
 
     pub fn get_last_index_as_bytes(&self) -> Result<Vec<u8>> {
         let last_index = self.db.iterator(IteratorMode::End).next();
         match last_index {
-            Some((index, _)) => {
-                Ok(index.to_vec())
-            }
-            None => Ok(serialize::<u64>(&0))
+            Some((index, _)) => Ok(index.to_vec()),
+            None => Ok(serialize::<u64>(&0)),
         }
     }
 
@@ -89,12 +76,8 @@ impl SlabStore {
         Ok(key)
     }
 
-
     pub fn destroy(&self) -> Result<()> {
         DB::destroy(&self.opt, self.path.clone())?;
         Ok(())
     }
-
 }
-
-

+ 2 - 1
src/tx/builder.rs

@@ -8,7 +8,8 @@ use super::{
     Transaction, TransactionClearInput, TransactionInput, TransactionOutput,
 };
 use crate::crypto::{
-    create_mint_proof, create_spend_proof, merkle::MerklePath, merkle_node::MerkleNode, note::Note, schnorr,
+    create_mint_proof, create_spend_proof, merkle::MerklePath, merkle_node::MerkleNode, note::Note,
+    schnorr,
 };
 use crate::serial::Encodable;