clean up & cargo fmt

This commit is contained in:
ghassmo
2021-05-22 16:55:35 +03:00
parent ef56e87322
commit 851978ed3a
14 changed files with 51 additions and 93 deletions

View File

@@ -1,37 +0,0 @@
use async_executor::Executor;
use easy_parallel::Parallel;
use std::sync::Arc;
use sapvi::Result;
use sapvi::service::GatewayService;
async fn start(executor: Arc<Executor<'_>>) -> Result<()> {
let gateway = GatewayService::new(
String::from("tcp://127.0.0.1:3333"),
String::from("tcp://127.0.0.1:4444"),
);
gateway.start(executor.clone()).await?;
Ok(())
}
fn main() -> Result<()> {
let ex = Arc::new(Executor::new());
let (signal, shutdown) = async_channel::unbounded::<()>();
let ex2 = ex.clone();
let (_, result) = Parallel::new()
// Run four executor threads.
.each(0..3, |_| smol::future::block_on(ex.run(shutdown.recv())))
// Run the main future on the current thread.
.finish(|| {
smol::future::block_on(async move {
start(ex2).await?;
drop(signal);
Ok::<(), sapvi::Error>(())
})
});
result
}

View File

@@ -13,9 +13,7 @@ async fn start(executor: Arc<Executor<'_>>) -> Result<()> {
let slabs = Arc::new(Mutex::new(vec![]));
let subscriber = client
.subscribe("127.0.0.1:4444".parse()?)
.await?;
let subscriber = client.subscribe("127.0.0.1:4444".parse()?).await?;
println!("subscription ready");

View File

@@ -1,5 +1,5 @@
use std::sync::Arc;
use std::net::SocketAddr;
use std::sync::Arc;
extern crate clap;
use async_executor::Executor;
@@ -9,24 +9,18 @@ use sapvi::Result;
use sapvi::service::{GatewayService, ProgramOptions};
fn setup_addr(address: Option<SocketAddr>, default: SocketAddr ) -> SocketAddr{
fn setup_addr(address: Option<SocketAddr>, default: SocketAddr) -> SocketAddr {
match address {
Some(addr) => {
addr
},
None => default
Some(addr) => addr,
None => default,
}
}
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 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(())
@@ -38,7 +32,6 @@ fn main() -> Result<()> {
let ex = Arc::new(Executor::new());
let (signal, shutdown) = async_channel::unbounded::<()>();
let options = ProgramOptions::load()?;
let logger_config = ConfigBuilder::new().set_time_format_str("%T%.6f").build();
@@ -57,14 +50,10 @@ fn main() -> Result<()> {
std::fs::File::create(options.log_path.as_path()).unwrap(),
),
])
.unwrap();
.unwrap();
let ex2 = ex.clone();
let (_, result) = Parallel::new()
// Run four executor threads.
.each(0..3, |_| smol::future::block_on(ex.run(shutdown.recv())))

View File

@@ -71,18 +71,14 @@ impl MemoryState {
for (coin, enc_note) in update.coins.into_iter().zip(update.enc_notes.into_iter()) {
// Add the new coins to the merkle tree
let node = Node::from_coin(&coin);
self.tree
.append(node)
.expect("Append to merkle tree");
self.tree.append(node).expect("Append to merkle tree");
// Keep track of all merkle roots that have existed
self.merkle_roots.push(self.tree.root());
// Also update all the coin witnesses
for (_, _, _, witness) in self.own_coins.iter_mut() {
witness
.append(node)
.expect("append to witness");
witness.append(node).expect("append to witness");
}
if let Some((note, secret)) = self.try_decrypt_note(enc_note) {
@@ -296,4 +292,3 @@ fn main() {
state.apply(update);
}
}

View File

@@ -264,7 +264,9 @@ impl Circuit<bls12_381::Scalar> for SpendContract {
// Line 180: conditionally_reverse left right current branch is_right
let (left, right) = num::AllocatedNum::conditionally_reverse(
cs.namespace(|| "Line 180: conditionally_reverse left right current branch is_right"),
cs.namespace(|| {
"Line 180: conditionally_reverse left right current branch is_right"
}),
&current,
&branch,
&is_right,
@@ -274,7 +276,8 @@ impl Circuit<bls12_381::Scalar> for SpendContract {
let left = left.to_bits_le(cs.namespace(|| "Line 183: scalar_as_binary left left"))?;
// Line 184: scalar_as_binary right right
let right = right.to_bits_le(cs.namespace(|| "Line 184: scalar_as_binary right right"))?;
let right =
right.to_bits_le(cs.namespace(|| "Line 184: scalar_as_binary right right"))?;
// Line 185: alloc_binary preimage
let mut preimage = vec![];

View File

@@ -1,6 +1,9 @@
use std::io;
use crate::{error::Result, serial::{Decodable, Encodable}};
use crate::{
error::Result,
serial::{Decodable, Encodable},
};
pub struct Coin {
pub repr: [u8; 32],
@@ -25,4 +28,3 @@ impl Decodable for Coin {
})
}
}

View File

@@ -5,7 +5,10 @@ use lazy_static::lazy_static;
use std::io;
use super::{coin::Coin, merkle::Hashable};
use crate::{error::Result, serial::{Decodable, Encodable}};
use crate::{
error::Result,
serial::{Decodable, Encodable},
};
pub const SAPLING_COMMITMENT_TREE_DEPTH: usize = 6;
@@ -72,7 +75,9 @@ impl Node {
}
pub fn from_coin(coin: &Coin) -> Self {
Self { repr: hash_coin(&coin.repr).to_repr() }
Self {
repr: hash_coin(&coin.repr).to_repr(),
}
}
}

View File

@@ -1,6 +1,9 @@
use std::io;
use crate::{error::Result, serial::{Decodable, Encodable}};
use crate::{
error::Result,
serial::{Decodable, Encodable},
};
pub struct Nullifier {
pub repr: [u8; 32],

View File

@@ -8,11 +8,11 @@ use rand::rngs::OsRng;
use std::io;
use std::time::Instant;
use super::node::{SAPLING_COMMITMENT_TREE_DEPTH, merkle_hash, Node};
use super::node::{merkle_hash, Node, SAPLING_COMMITMENT_TREE_DEPTH};
use super::nullifier::Nullifier;
use crate::circuit::spend_contract::SpendContract;
use crate::error::Result;
use crate::serial::{Decodable, Encodable};
use super::nullifier::Nullifier;
pub struct SpendRevealedValues {
pub value_commit: jubjub::SubgroupPoint,
@@ -206,10 +206,7 @@ pub fn create_spend_proof(
merkle_path: Vec<(bls12_381::Scalar, bool)>,
signature_secret: jubjub::Fr,
) -> (groth16::Proof<Bls12>, SpendRevealedValues) {
assert_eq!(
merkle_path.len(),
SAPLING_COMMITMENT_TREE_DEPTH
);
assert_eq!(merkle_path.len(), SAPLING_COMMITMENT_TREE_DEPTH);
let mut branch: [_; SAPLING_COMMITMENT_TREE_DEPTH] = Default::default();
let mut is_right: [_; SAPLING_COMMITMENT_TREE_DEPTH] = Default::default();
for (i, (branch_i, is_right_i)) in merkle_path.iter().enumerate() {

View File

@@ -1,12 +1,14 @@
use async_std::sync::{Arc, Mutex};
use std::convert::TryInto;
use std::net::SocketAddr;
use std::net::SocketAddr;
use super::reqrep::{Publisher, RepProtocol, Reply, ReqProtocol, Request, Subscriber};
use crate::{Error, Result};
use async_executor::Executor;
use log::*;
pub type Slabs = Vec<Vec<u8>>;
#[repr(u8)]
@@ -37,11 +39,11 @@ impl GatewayService {
let mut socket = RepProtocol::new(self.addr.clone());
let (send, recv) = socket.start().await?;
println!("server started");
info!("server started: bind to {}", self.addr.to_string());
self.publisher.lock().await.start().await?;
println!("publisher started");
info!("publisher started");
let handle_request_task = executor.spawn(self.handle_request(send.clone(), recv.clone()));
@@ -70,15 +72,15 @@ impl GatewayService {
// publish to all subscribes
self.publisher.lock().await.publish(slab).await?;
println!("received putslab msg");
info!("received putslab msg");
}
1 => {
// GETSLAB
println!("received getslab msg");
info!("received getslab msg");
}
2 => {
// GETLASTINDEX
println!("received getlastindex msg");
info!("received getlastindex msg");
}
_ => {
return Err(Error::ServicesError("wrong command"));
@@ -145,7 +147,7 @@ pub async fn fetch_slabs_loop(
let mut subscriber = subscriber.lock().await;
slab = subscriber.fetch().await?;
}
println!("received new slab from subscriber");
info!("received new slab from subscriber");
slabs.lock().await.push(slab);
}
}

View File

@@ -1,6 +1,6 @@
pub mod gateway;
pub mod reqrep;
pub mod options;
pub mod reqrep;
pub use gateway::{fetch_slabs_loop, GatewayClient, GatewayService};
pub use options::ProgramOptions;

View File

@@ -8,7 +8,6 @@ pub struct ProgramOptions {
pub log_path: Box<std::path::PathBuf>,
}
impl ProgramOptions {
pub fn load() -> Result<ProgramOptions> {
let app = clap_app!(dfi =>
@@ -20,7 +19,7 @@ impl ProgramOptions {
(@arg VERBOSE: -v --verbose "Increase verbosity")
(@arg LOG_PATH: --log +takes_value "Logfile path")
)
.get_matches();
.get_matches();
let accept_addr = if let Some(accept_addr) = app.value_of("ACCEPT") {
Some(accept_addr.parse()?)
@@ -49,7 +48,7 @@ impl ProgramOptions {
accept_addr,
pub_addr,
verbose,
log_path
log_path,
})
}
}

View File

@@ -14,8 +14,7 @@ enum NetEvent {
Send(Reply),
}
pub fn addr_to_string (addr: SocketAddr) -> String {
pub fn addr_to_string(addr: SocketAddr) -> String {
format!("tcp://{}", addr.to_string())
}

View File

@@ -7,7 +7,9 @@ use super::{
partial::{PartialTransaction, PartialTransactionClearInput, PartialTransactionInput},
Transaction, TransactionClearInput, TransactionInput, TransactionOutput,
};
use crate::crypto::{merkle::MerklePath, node::Node, create_mint_proof, create_spend_proof, note::Note, schnorr};
use crate::crypto::{
create_mint_proof, create_spend_proof, merkle::MerklePath, node::Node, note::Note, schnorr,
};
use crate::serial::Encodable;
pub struct TransactionBuilder {
@@ -85,7 +87,8 @@ impl TransactionBuilder {
// make proof
// TODO: Some stupid glue code. Need to sort this out
let auth_path: Vec<(bls12_381::Scalar, bool)> = input.merkle_path
let auth_path: Vec<(bls12_381::Scalar, bool)> = input
.merkle_path
.auth_path
.iter()
.map(|(node, b)| ((*node).into(), *b))