From bcbe3f4ae2dd42ff14b5b96d7205f2976e5b770c Mon Sep 17 00:00:00 2001 From: rachel-rose Date: Thu, 20 May 2021 16:15:51 +0200 Subject: [PATCH 1/4] cleaned up some unused import warnings --- lisp/lisp.rs | 5 +---- lisp/types.rs | 7 ++----- src/bin/compile-shaders.rs | 3 --- src/bin/dfg.rs | 2 +- src/bin/dfi.rs | 11 +---------- src/bin/mint-classic.rs | 7 +------ src/bin/spend-classic.rs | 3 --- src/bin/tx.rs | 10 +++------- src/crypto/mint_proof.rs | 5 ++--- src/crypto/schnorr.rs | 4 ++-- src/crypto/spend_proof.rs | 5 ++--- src/old/mimc.rs | 6 +++--- src/rpc/adapter.rs | 5 ----- src/rpc/jsonserver.rs | 11 +---------- src/rpc/options.rs | 11 +---------- src/state.rs | 2 +- src/tx/builder.rs | 14 ++------------ src/tx/mod.rs | 12 +++--------- src/tx/partial.rs | 19 ++++--------------- 19 files changed, 30 insertions(+), 112 deletions(-) diff --git a/lisp/lisp.rs b/lisp/lisp.rs index 3407344c1..f85405d87 100644 --- a/lisp/lisp.rs +++ b/lisp/lisp.rs @@ -1,17 +1,14 @@ #![allow(non_snake_case)] use crate::types::LispCircuit; -use bellman::groth16::PreparedVerifyingKey; -use sapvi::{BlsStringConversion, Decodable, Encodable, ZKContract, ZKProof}; -use simplelog::*; +use sapvi::BlsStringConversion; use bellman::groth16; use bls12_381::Bls12; // use fnv::FnvHashMap; use itertools::Itertools; use rand::rngs::OsRng; -use std::borrow::{Borrow, BorrowMut}; use std::rc::Rc; use std::time::Instant; use std::{cell::RefCell, collections::HashMap}; diff --git a/lisp/types.rs b/lisp/types.rs index b19293590..b1a9d5987 100644 --- a/lisp/types.rs +++ b/lisp/types.rs @@ -1,11 +1,8 @@ -use bellman::{gadgets::Assignment, groth16, Circuit, ConstraintSystem, SynthesisError}; +use bellman::{groth16, Circuit, ConstraintSystem, SynthesisError}; use sapvi::bls_extensions::BlsStringConversion; use std::rc::Rc; use std::{cell::RefCell, collections::HashMap}; -use std::{ - ops::{Add, AddAssign, MulAssign, SubAssign}, - time::Instant, -}; +use std::time::Instant; // use fnv::FnvHashMap; use itertools::Itertools; diff --git a/src/bin/compile-shaders.rs b/src/bin/compile-shaders.rs index 3659ba622..339f19506 100644 --- a/src/bin/compile-shaders.rs +++ b/src/bin/compile-shaders.rs @@ -1,8 +1,5 @@ use anyhow::*; -use fs_extra::copy_items; -use fs_extra::dir::CopyOptions; use glob::glob; -use std::env; use std::fs::{read_to_string, write}; use std::path::PathBuf; diff --git a/src/bin/dfg.rs b/src/bin/dfg.rs index c619cbcee..b03d7caba 100644 --- a/src/bin/dfg.rs +++ b/src/bin/dfg.rs @@ -11,7 +11,7 @@ use winit::{ use sapvi::gfx::{camera, model, texture}; -use model::{DrawLight, DrawModel, Vertex}; +use model::{DrawModel, Vertex}; use std::time::Instant; #[macro_use] diff --git a/src/bin/dfi.rs b/src/bin/dfi.rs index b377fa15f..16425cc90 100644 --- a/src/bin/dfi.rs +++ b/src/bin/dfi.rs @@ -2,19 +2,10 @@ extern crate clap; use async_executor::Executor; use sapvi::rpc::options::ProgramOptions; -use async_native_tls::TlsAcceptor; -use async_std::sync::Mutex; use easy_parallel::Parallel; -use http_types::{Request, Response, StatusCode}; -use log::*; use sapvi::rpc::jsonserver; -use sapvi::rpc::jsonserver::RpcInterface; -use sapvi::{net, Result}; +use sapvi::Result; use sapvi::rpc::adapter::RpcAdapter; -use serde_json::json; -use smol::Async; -use std::net::SocketAddr; -use std::net::TcpListener; use std::sync::Arc; diff --git a/src/bin/mint-classic.rs b/src/bin/mint-classic.rs index 708c078bd..f98294746 100644 --- a/src/bin/mint-classic.rs +++ b/src/bin/mint-classic.rs @@ -1,9 +1,5 @@ -use bellman::gadgets::multipack; -use bellman::groth16; -use blake2s_simd::Params as Blake2sParams; -use bls12_381::Bls12; use ff::Field; -use group::{Curve, Group, GroupEncoding}; +use group::Group; use sapvi::crypto::{ create_mint_proof, load_params, save_params, setup_mint_prover, verify_mint_proof, @@ -11,7 +7,6 @@ use sapvi::crypto::{ fn main() { use rand::rngs::OsRng; - use std::time::Instant; let public = jubjub::SubgroupPoint::random(&mut OsRng); diff --git a/src/bin/spend-classic.rs b/src/bin/spend-classic.rs index 71d7af989..04335d141 100644 --- a/src/bin/spend-classic.rs +++ b/src/bin/spend-classic.rs @@ -1,12 +1,9 @@ use bellman::gadgets::multipack; -use bellman::groth16; use bitvec::{order::Lsb0, view::AsBits}; use blake2s_simd::Params as Blake2sParams; -use bls12_381::Bls12; use ff::{Field, PrimeField}; use group::{Curve, GroupEncoding}; -use sapvi::circuit::spend_contract::SpendContract; use sapvi::crypto::{ create_spend_proof, load_params, save_params, setup_spend_prover, verify_spend_proof, }; diff --git a/src/bin/tx.rs b/src/bin/tx.rs index bf4e4a8d6..315b9b13d 100644 --- a/src/bin/tx.rs +++ b/src/bin/tx.rs @@ -1,22 +1,18 @@ use bellman::groth16; use bls12_381::Bls12; use ff::{Field, PrimeField}; -use group::Group; use rand::rngs::OsRng; -use std::io; use std::path::Path; use sapvi::crypto::{ coin::Coin, - create_mint_proof, create_spend_proof, load_params, + load_params, merkle::{CommitmentTree, IncrementalWitness}, nullifier::Nullifier, note::{EncryptedNote, Note}, - save_params, setup_mint_prover, setup_spend_prover, verify_mint_proof, verify_spend_proof, - MintRevealedValues, SpendRevealedValues, + save_params, setup_mint_prover, setup_spend_prover, }; -use sapvi::error::{Error, Result}; -use sapvi::serial::{Decodable, Encodable, VarInt}; +use sapvi::serial::{Decodable, Encodable}; use sapvi::state::{state_transition, ProgramState, StateUpdates}; use sapvi::tx; diff --git a/src/crypto/mint_proof.rs b/src/crypto/mint_proof.rs index 0e2f30c70..11e31f59e 100644 --- a/src/crypto/mint_proof.rs +++ b/src/crypto/mint_proof.rs @@ -2,14 +2,13 @@ use bellman::gadgets::multipack; use bellman::groth16; use blake2s_simd::Params as Blake2sParams; use bls12_381::Bls12; -use ff::Field; -use group::{Curve, Group, GroupEncoding}; +use group::{Curve, GroupEncoding}; use rand::rngs::OsRng; use std::io; use std::time::Instant; use crate::circuit::mint_contract::MintContract; -use crate::error::{Error, Result}; +use crate::error::Result; use crate::serial::{Decodable, Encodable}; pub struct MintRevealedValues { diff --git a/src/crypto/schnorr.rs b/src/crypto/schnorr.rs index 06663492d..4a8fd22df 100644 --- a/src/crypto/schnorr.rs +++ b/src/crypto/schnorr.rs @@ -1,10 +1,10 @@ use ff::Field; -use group::{Group, GroupEncoding}; +use group::GroupEncoding; use rand::rngs::OsRng; use std::io; use super::util::hash_to_scalar; -use crate::error::{Error, Result}; +use crate::error::Result; use crate::serial::{Decodable, Encodable}; pub struct SecretKey(pub jubjub::Fr); diff --git a/src/crypto/spend_proof.rs b/src/crypto/spend_proof.rs index 24e41c561..128a9ed26 100644 --- a/src/crypto/spend_proof.rs +++ b/src/crypto/spend_proof.rs @@ -1,9 +1,8 @@ use bellman::gadgets::multipack; use bellman::groth16; -use bitvec::{order::Lsb0, view::AsBits}; use blake2s_simd::Params as Blake2sParams; use bls12_381::Bls12; -use ff::{Field, PrimeField}; +use ff::PrimeField; use group::{Curve, GroupEncoding}; use rand::rngs::OsRng; use std::io; @@ -11,7 +10,7 @@ use std::time::Instant; use super::coin::merkle_hash; use crate::circuit::spend_contract::SpendContract; -use crate::error::{Error, Result}; +use crate::error::Result; use crate::serial::{Decodable, Encodable}; pub struct SpendRevealedValues { diff --git a/src/old/mimc.rs b/src/old/mimc.rs index baaf9413a..ddc16a91c 100644 --- a/src/old/mimc.rs +++ b/src/old/mimc.rs @@ -1,5 +1,5 @@ // For randomness (during paramgen and proof generation) -use rand::thread_rng; +//use rand::thread_rng; // For benchmarking use std::time::{Duration, Instant}; @@ -8,14 +8,14 @@ use std::time::{Duration, Instant}; use sapvi::bls_extensions::BlsStringConversion; // Bring in some tools for using finite fiels -use ff::{Field, PrimeField}; +use ff::PrimeField; // mimc constants //mod mimc_constants; //use mimc_constants::mimc_constants; // We're going to use the BLS12-381 pairing-friendly elliptic curve. -use bls12_381::{Bls12, Scalar}; +use bls12_381::Bls12; // We'll use these interfaces to construct our circuit. use bellman::{Circuit, ConstraintSystem, SynthesisError}; diff --git a/src/rpc/adapter.rs b/src/rpc/adapter.rs index 6a1162439..5efe3a188 100644 --- a/src/rpc/adapter.rs +++ b/src/rpc/adapter.rs @@ -1,10 +1,5 @@ // Adapter class goes here //use crate::rpc::jsonserver::JsonRpcInterface; -use crate::Result; -use async_executor::Executor; -use async_native_tls::TlsAcceptor; -use smol::Async; -use std::net::TcpListener; use std::sync::Arc; // Dummy adapter for now diff --git a/src/rpc/jsonserver.rs b/src/rpc/jsonserver.rs index 98b47a9f8..352617966 100644 --- a/src/rpc/jsonserver.rs +++ b/src/rpc/jsonserver.rs @@ -1,21 +1,12 @@ -use crate::{net, serial, Error, Result}; +use crate::{net, Error, Result}; use crate::rpc::options::ProgramOptions; use crate::rpc::adapter::RpcAdapter; use async_executor::Executor; use async_native_tls::TlsAcceptor; use async_std::sync::Mutex; -use easy_parallel::Parallel; -use ff::Field; use http_types::{Request, Response, StatusCode}; use log::*; -use rand::rngs::OsRng; -use rusqlite::Connection; -use serde_json::json; use smol::Async; -use std::fs::File; -use std::io::prelude::*; -use std::io::BufReader; -use std::net::SocketAddr; use std::net::TcpListener; use std::sync::Arc; diff --git a/src/rpc/options.rs b/src/rpc/options.rs index 76f7ce466..0e988fd4b 100644 --- a/src/rpc/options.rs +++ b/src/rpc/options.rs @@ -1,15 +1,6 @@ #[macro_use] use std::net::SocketAddr; -use crate::{net, Error, Result}; -use async_executor::Executor; -use async_native_tls::TlsAcceptor; -use async_std::sync::Mutex; -use easy_parallel::Parallel; -use http_types::{Request, Response, StatusCode}; -use log::*; -use smol::Async; -use std::net::TcpListener; -use std::sync::Arc; +use crate::{net, Result}; pub struct ProgramOptions { pub network_settings: net::Settings, diff --git a/src/state.rs b/src/state.rs index fe6fe6a2f..ae2499893 100644 --- a/src/state.rs +++ b/src/state.rs @@ -2,7 +2,7 @@ use bellman::groth16; use bls12_381::Bls12; use std::fmt; -use crate::{crypto::{coin::Coin, note::{EncryptedNote, Note}, nullifier::Nullifier}, error::{Error, Result}, tx}; +use crate::{crypto::{coin::Coin, note::EncryptedNote, nullifier::Nullifier}, tx}; pub trait ProgramState { fn is_valid_cashier_public_key(&self, public: &jubjub::SubgroupPoint) -> bool; diff --git a/src/tx/builder.rs b/src/tx/builder.rs index b0e35c620..7f0cb7eac 100644 --- a/src/tx/builder.rs +++ b/src/tx/builder.rs @@ -1,21 +1,11 @@ use bellman::groth16; use bls12_381::Bls12; use rand::rngs::OsRng; -use std::collections::HashMap; -use std::io; use ff::Field; -use crate::error::{Error, Result}; -use crate::serial::{Decodable, Encodable, VarInt}; +use crate::serial::Encodable; use super::{TransactionClearInput, TransactionInput, TransactionOutput, Transaction, partial::{PartialTransactionClearInput, PartialTransactionInput, PartialTransaction}}; -use crate::crypto::{ - coin::Coin, - create_mint_proof, create_spend_proof, load_params, - merkle::CommitmentTree, - note::{EncryptedNote, Note}, - save_params, schnorr, setup_mint_prover, setup_spend_prover, verify_mint_proof, - verify_spend_proof, MintRevealedValues, SpendRevealedValues, -}; +use crate::crypto::{create_spend_proof, create_mint_proof, note::Note, schnorr}; pub struct TransactionBuilder { pub clear_inputs: Vec, diff --git a/src/tx/mod.rs b/src/tx/mod.rs index cbc061b37..db5dd29d4 100644 --- a/src/tx/mod.rs +++ b/src/tx/mod.rs @@ -3,21 +3,15 @@ pub mod partial; use bellman::groth16; use bls12_381::Bls12; -use ff::Field; use group::Group; -use rand::rngs::OsRng; -use std::collections::HashMap; use std::io; use crate::crypto::{ - coin::Coin, - create_mint_proof, create_spend_proof, load_params, - merkle::CommitmentTree, - note::{EncryptedNote, Note}, - save_params, schnorr, setup_mint_prover, setup_spend_prover, verify_mint_proof, + note::EncryptedNote, + schnorr, verify_mint_proof, verify_spend_proof, MintRevealedValues, SpendRevealedValues, }; -use crate::error::{Error, Result}; +use crate::error::Result; use crate::impl_vec; use crate::serial::{Decodable, Encodable, VarInt}; use crate::state; diff --git a/src/tx/partial.rs b/src/tx/partial.rs index db8559365..5e2512bd2 100644 --- a/src/tx/partial.rs +++ b/src/tx/partial.rs @@ -1,22 +1,12 @@ use bellman::groth16; use bls12_381::Bls12; -use rand::rngs::OsRng; -use std::collections::HashMap; use std::io; -use ff::Field; -use crate::error::{Error, Result}; +use crate::error::Result; use crate::impl_vec; use crate::serial::{Decodable, Encodable, VarInt}; -use super::{TransactionClearInput, TransactionInput, TransactionOutput, Transaction}; -use crate::crypto::{ - coin::Coin, - create_mint_proof, create_spend_proof, load_params, - merkle::CommitmentTree, - note::{EncryptedNote, Note}, - save_params, schnorr, setup_mint_prover, setup_spend_prover, verify_mint_proof, - verify_spend_proof, MintRevealedValues, SpendRevealedValues, -}; +use super::TransactionOutput; +use crate::crypto::SpendRevealedValues; pub struct PartialTransaction { pub clear_inputs: Vec, @@ -63,8 +53,7 @@ impl Encodable for PartialTransactionClearInput { len += self.signature_public.encode(&mut s)?; Ok(len) } -} - +} impl Decodable for PartialTransactionClearInput { fn decode(mut d: D) -> Result { Ok(Self { From 0737809b29e4da3e7802f112bbd45f9542de33b0 Mon Sep 17 00:00:00 2001 From: rachel-rose Date: Thu, 20 May 2021 16:46:56 +0200 Subject: [PATCH 2/4] cleaned up more warnings --- src/bin/dfi.rs | 1 - src/bin/spend-classic.rs | 1 - src/error.rs | 14 +++++++------- src/rpc/jsonserver.rs | 2 +- src/rpc/options.rs | 1 - src/rpc/test.rs | 1 - 6 files changed, 8 insertions(+), 12 deletions(-) diff --git a/src/bin/dfi.rs b/src/bin/dfi.rs index 16425cc90..1c1f89d91 100644 --- a/src/bin/dfi.rs +++ b/src/bin/dfi.rs @@ -1,4 +1,3 @@ -#[macro_use] extern crate clap; use async_executor::Executor; use sapvi::rpc::options::ProgramOptions; diff --git a/src/bin/spend-classic.rs b/src/bin/spend-classic.rs index 04335d141..dd5f73534 100644 --- a/src/bin/spend-classic.rs +++ b/src/bin/spend-classic.rs @@ -167,7 +167,6 @@ impl SpendRevealedValues { fn main() { use rand::rngs::OsRng; - use std::time::Instant; let value = 110; let randomness_value: jubjub::Fr = jubjub::Fr::random(&mut OsRng); diff --git a/src/error.rs b/src/error.rs index 1f0711a82..e81e63c6f 100644 --- a/src/error.rs +++ b/src/error.rs @@ -107,7 +107,7 @@ impl fmt::Display for Error { // TODO: Match statement to parse external errors into strings. impl From for Error { - fn from(err: zeromq::ZmqError) -> Error { + fn from(_err: zeromq::ZmqError) -> Error { Error::ZMQError } } @@ -119,31 +119,31 @@ impl From for Error { } impl From for Error { - fn from(err: rusqlite::Error) -> Error { + fn from(_err: rusqlite::Error) -> Error { Error::RusqliteError } } impl From for Error { - fn from(err: ZKVMError) -> Error { + fn from(_err: ZKVMError) -> Error { Error::VMError } } impl From for Error { - fn from(err: bellman::SynthesisError) -> Error { + fn from(_err: bellman::SynthesisError) -> Error { Error::Groth16Error } } impl From> for Error { - fn from(err: async_channel::SendError) -> Error { + fn from(_err: async_channel::SendError) -> Error { Error::AsyncChannelError } } impl From for Error { - fn from(err: async_channel::RecvError) -> Error { + fn from(_err: async_channel::RecvError) -> Error { Error::AsyncChannelError } } @@ -180,7 +180,7 @@ impl From for Error { } impl From for Error { - fn from(err: state::VerifyFailed) -> Error { + fn from(_err: state::VerifyFailed) -> Error { Error::VerifyFailed } } diff --git a/src/rpc/jsonserver.rs b/src/rpc/jsonserver.rs index 352617966..9c081f531 100644 --- a/src/rpc/jsonserver.rs +++ b/src/rpc/jsonserver.rs @@ -71,7 +71,7 @@ pub async fn listen( } } -pub async fn start(executor: Arc>, options: ProgramOptions, adapter: Arc) -> Result<()> { +pub async fn start(executor: Arc>, options: ProgramOptions, _adapter: Arc) -> Result<()> { let p2p = net::P2p::new(options.network_settings); let rpc = RpcInterface::new(p2p.clone()); diff --git a/src/rpc/options.rs b/src/rpc/options.rs index 0e988fd4b..1d34a8ac4 100644 --- a/src/rpc/options.rs +++ b/src/rpc/options.rs @@ -1,4 +1,3 @@ -#[macro_use] use std::net::SocketAddr; use crate::{net, Result}; diff --git a/src/rpc/test.rs b/src/rpc/test.rs index 8f3b7ef11..e69de29bb 100644 --- a/src/rpc/test.rs +++ b/src/rpc/test.rs @@ -1 +0,0 @@ -fn foo() {} From 2b78f0adb2c0c0d2d309d1cb5708ffcb0ed8d022 Mon Sep 17 00:00:00 2001 From: rachel-rose Date: Thu, 20 May 2021 20:36:45 +0200 Subject: [PATCH 3/4] merged src/net/error.rs with src/error.rs. deleted src/net/error and updated all code in /net to accept change --- src/error.rs | 20 ------------- src/net/acceptor.rs | 25 ++++++++-------- src/net/channel.rs | 35 +++++++++++----------- src/net/connector.rs | 9 +++--- src/net/error.rs | 30 ------------------- src/net/message_subscriber.rs | 17 +++++------ src/net/mod.rs | 3 -- src/net/p2p.rs | 16 +++++----- src/net/protocols/protocol_address.rs | 6 ++-- src/net/protocols/protocol_jobs_manager.rs | 6 ++-- src/net/protocols/protocol_ping.rs | 8 ++--- src/net/protocols/protocol_seed.rs | 6 ++-- src/net/protocols/protocol_version.rs | 12 ++++---- src/net/sessions/inbound_session.rs | 15 +++++----- src/net/sessions/outbound_session.rs | 14 ++++----- src/net/sessions/seed_session.rs | 13 ++++---- src/net/sessions/session.rs | 6 ++-- 17 files changed, 95 insertions(+), 146 deletions(-) delete mode 100644 src/net/error.rs diff --git a/src/error.rs b/src/error.rs index e81e63c6f..4bf82f8f8 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,19 +1,12 @@ use rusqlite; use std::fmt; -use crate::net::error::NetError; use crate::state; use crate::vm::ZKVMError; pub type Result = std::result::Result; #[derive(Debug, Clone)] -//#[derive(Debug, Copy, Clone)] - -// need to be able to copy the errors into theads -// net error has clone and copy attribute -// copy vs clone -//struct Error; pub enum Error { Foo, @@ -160,19 +153,6 @@ impl From for Error { } } -impl From for Error { - fn from(err: NetError) -> Error { - match err { - NetError::OperationFailed => Error::OperationFailed, - NetError::ConnectFailed => Error::ConnectFailed, - NetError::ConnectTimeout => Error::ConnectTimeout, - NetError::ChannelStopped => Error::ChannelStopped, - NetError::ChannelTimeout => Error::ChannelTimeout, - NetError::ServiceStopped => Error::ServiceStopped, - } - } -} - impl From for Error { fn from(_err: std::string::FromUtf8Error) -> Error { Error::Utf8Error diff --git a/src/net/acceptor.rs b/src/net/acceptor.rs index 52131fdb9..153a60a57 100644 --- a/src/net/acceptor.rs +++ b/src/net/acceptor.rs @@ -3,7 +3,8 @@ use smol::{Async, Executor}; use std::net::{SocketAddr, TcpListener}; use std::sync::Arc; -use crate::net::error::{NetError, NetResult}; +use crate::error::{Error, Result}; +//use crate::net::error::{, Result}; use crate::net::{Channel, ChannelPtr}; use crate::system::{StoppableTask, StoppableTaskPtr, Subscriber, SubscriberPtr, Subscription}; @@ -12,7 +13,7 @@ pub type AcceptorPtr = Arc; /// Create inbound socket connections. pub struct Acceptor { - channel_subscriber: SubscriberPtr>, + channel_subscriber: SubscriberPtr>, task: StoppableTaskPtr, } @@ -31,7 +32,7 @@ impl Acceptor { self: Arc, accept_addr: SocketAddr, executor: Arc>, - ) -> NetResult<()> { + ) -> Result<()> { let listener = Self::setup(accept_addr)?; // Start detached task and return instantly @@ -47,24 +48,24 @@ impl Acceptor { } /// Start receiving network messages. - pub async fn subscribe(self: Arc) -> Subscription> { + pub async fn subscribe(self: Arc) -> Subscription> { self.channel_subscriber.clone().subscribe().await } /// Start listening on a local socket address. - fn setup(accept_addr: SocketAddr) -> NetResult> { + fn setup(accept_addr: SocketAddr) -> Result> { let listener = match Async::::bind(accept_addr) { Ok(listener) => listener, Err(err) => { error!("Bind listener failed: {}", err); - return Err(NetError::OperationFailed); + return Err(Error::OperationFailed); } }; let local_addr = match listener.get_ref().local_addr() { Ok(addr) => addr, Err(err) => { error!("Failed to get local address: {}", err); - return Err(NetError::OperationFailed); + return Err(Error::OperationFailed); } }; info!("Listening on {}", local_addr); @@ -78,13 +79,13 @@ impl Acceptor { self.task.clone().start( self.clone().run_accept_loop(listener), |result| self.handle_stop(result), - NetError::ServiceStopped, + Error::ServiceStopped, executor, ); } /// Run the accept loop. - async fn run_accept_loop(self: Arc, listener: Async) -> NetResult<()> { + async fn run_accept_loop(self: Arc, listener: Async) -> Result<()> { loop { let channel = self.tick_accept(&listener).await?; self.channel_subscriber.notify(Ok(channel)).await; @@ -93,7 +94,7 @@ impl Acceptor { /// Handles network errors. Panics if error passes silently, otherwise /// broadcasts the error. - async fn handle_stop(self: Arc, result: NetResult<()>) { + async fn handle_stop(self: Arc, result: Result<()>) { match result { Ok(()) => panic!("Acceptor task should never complete without error status"), Err(err) => { @@ -106,12 +107,12 @@ impl Acceptor { /// Single attempt to accept an incoming connection. Stops after one /// attempt. - async fn tick_accept(&self, listener: &Async) -> NetResult { + async fn tick_accept(&self, listener: &Async) -> Result { let (stream, peer_addr) = match listener.accept().await { Ok((s, a)) => (s, a), Err(err) => { error!("Error listening for connections: {}", err); - return Err(NetError::ServiceStopped); + return Err(Error::ServiceStopped); } }; info!("Accepted client: {}", peer_addr); diff --git a/src/net/channel.rs b/src/net/channel.rs index 3a584c3d5..4871028bd 100644 --- a/src/net/channel.rs +++ b/src/net/channel.rs @@ -9,8 +9,7 @@ use std::net::{SocketAddr, TcpStream}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use crate::error; -use crate::net::error::{NetError, NetResult}; +use crate::error::{Error, Result}; use crate::net::message_subscriber::{MessageSubscription, MessageSubsystem}; use crate::net::messages; use crate::system::{StoppableTask, StoppableTaskPtr, Subscriber, SubscriberPtr, Subscription}; @@ -24,7 +23,7 @@ pub struct Channel { writer: Mutex>>, address: SocketAddr, message_subsystem: MessageSubsystem, - stop_subscriber: SubscriberPtr, + stop_subscriber: SubscriberPtr, receive_task: StoppableTaskPtr, stopped: AtomicBool, } @@ -61,7 +60,7 @@ impl Channel { self.clone().main_receive_loop(), // Ignore stop handler |result| self2.handle_stop(result), - NetError::ServiceStopped, + Error::ServiceStopped, executor, ); debug!(target: "net", "Channel::start() [END, address={}]", self.address()); @@ -75,16 +74,16 @@ impl Channel { assert_eq!(self.stopped.load(Ordering::Relaxed), false); // Changes memory ordering to relaxed. We don't need strict thread locking here. self.stopped.store(false, Ordering::Relaxed); - self.stop_subscriber.notify(NetError::ChannelStopped).await; + self.stop_subscriber.notify(Error::ChannelStopped).await; self.receive_task.stop().await; self.message_subsystem - .trigger_error(NetError::ChannelStopped) + .trigger_error(Error::ChannelStopped) .await; debug!(target: "net", "Channel::stop() [END, address={}]", self.address()); } /// Creates a subscription to a stopped signal. - pub async fn subscribe_stop(&self) -> Subscription { + pub async fn subscribe_stop(&self) -> Subscription { debug!(target: "net", "Channel::subscribe_stop() [START, address={}]", self.address() @@ -102,14 +101,14 @@ impl Channel { /// Sends a message across a channel. Calls function 'send_message' that /// creates a new payload and sends it over the TCP connection as a /// packet. Returns an error if something goes wrong. - pub async fn send(&self, message: M) -> NetResult<()> { + pub async fn send(&self, message: M) -> Result<()> { debug!(target: "net", "Channel::send() [START, command={:?}, address={}]", M::name(), self.address() ); if self.stopped.load(Ordering::Relaxed) { - return Err(NetError::ChannelStopped); + return Err(Error::ChannelStopped); } // Catch failure and stop channel, return a net error @@ -118,7 +117,7 @@ impl Channel { Err(err) => { error!("Channel send error for [{}]: {}", self.address(), err); self.stop().await; - Err(NetError::ChannelStopped) + Err(Error::ChannelStopped) } }; debug!(target: "net", @@ -133,7 +132,7 @@ impl Channel { /// it. Then creates a message packet- the base type of the network- and /// copies the payload into it. Then we send the packet over the TCP /// stream. - async fn send_message(&self, message: M) -> error::Result<()> { + async fn send_message(&self, message: M) -> Result<()> { let mut payload = Vec::new(); message.encode(&mut payload)?; let packet = messages::Packet { @@ -146,7 +145,7 @@ impl Channel { } /// Subscribe to a messages on the message subsystem. - pub async fn subscribe_msg(&self) -> NetResult> { + pub async fn subscribe_msg(&self) -> Result> { debug!(target: "net", "Channel::subscribe_msg() [START, command={:?}, address={}]", M::name(), @@ -167,9 +166,9 @@ impl Channel { } /// End of file error. Triggered when unexpected end of file occurs. - fn is_eof_error(err: &error::Error) -> bool { + fn is_eof_error(err: Error) -> bool { match err { - error::Error::Io(io_err) => io_err.clone() == std::io::ErrorKind::UnexpectedEof, + Error::Io(io_err) => io_err.clone() == std::io::ErrorKind::UnexpectedEof, _ => false, } } @@ -203,7 +202,7 @@ impl Channel { /// Run the receive loop. Start receiving messages or handle network /// failure. - async fn main_receive_loop(self: Arc) -> NetResult<()> { + async fn main_receive_loop(self: Arc) -> Result<()> { debug!(target: "net", "Channel::receive_loop() [START, address={}]", self.address() @@ -215,7 +214,7 @@ impl Channel { let packet = match messages::read_packet(reader).await { Ok(packet) => packet, Err(err) => { - if Self::is_eof_error(&err) { + if Self::is_eof_error(err.clone()) { info!("Channel {} disconnected", self.address()); } else { error!("Read error on channel: {}", err); @@ -225,7 +224,7 @@ impl Channel { self.address() ); self.stop().await; - return Err(NetError::ChannelStopped); + return Err(Error::ChannelStopped); } }; @@ -238,7 +237,7 @@ impl Channel { /// Handle network errors. Panic if error passes silently, otherwise /// broadcast the error. - async fn handle_stop(self: Arc, result: NetResult<()>) { + async fn handle_stop(self: Arc, result: Result<()>) { debug!(target: "net", "Channel::handle_stop() [START, address={}]", self.address()); match result { Ok(()) => panic!("Channel task should never complete without error status"), diff --git a/src/net/connector.rs b/src/net/connector.rs index 0525d8bd0..8db606830 100644 --- a/src/net/connector.rs +++ b/src/net/connector.rs @@ -2,7 +2,8 @@ use futures::FutureExt; use smol::Async; use std::net::{SocketAddr, TcpStream}; -use crate::net::error::{NetError, NetResult}; +use crate::error::{Error, Result}; +//use crate::net::error::{Error, Result}; use crate::net::utility::sleep; use crate::net::{Channel, ChannelPtr, SettingsPtr}; @@ -18,15 +19,15 @@ impl Connector { } /// Establish an outbound connection. - pub async fn connect(&self, hostaddr: SocketAddr) -> NetResult { + pub async fn connect(&self, hostaddr: SocketAddr) -> Result { futures::select! { stream_result = Async::::connect(hostaddr).fuse() => { match stream_result { Ok(stream) => Ok(Channel::new(stream, hostaddr).await), - Err(_) => Err(NetError::ConnectFailed) + Err(_) => Err(Error::ConnectFailed) } } - _ = sleep(self.settings.connect_timeout_seconds).fuse() => Err(NetError::ConnectTimeout) + _ = sleep(self.settings.connect_timeout_seconds).fuse() => Err(Error::ConnectTimeout) } } } diff --git a/src/net/error.rs b/src/net/error.rs deleted file mode 100644 index 1b5e31eb6..000000000 --- a/src/net/error.rs +++ /dev/null @@ -1,30 +0,0 @@ -use std::fmt; - -/// Returns the relevant network error if a program fails. -pub type NetResult = std::result::Result; - -/// An enum representing the main network errors. -#[derive(Debug, Clone)] -pub enum NetError { - OperationFailed, - ConnectFailed, - ConnectTimeout, - ChannelStopped, - ChannelTimeout, - ServiceStopped, -} - -impl std::error::Error for NetError {} - -impl fmt::Display for NetError { - fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result { - match *self { - NetError::OperationFailed => f.write_str("Operation failed"), - NetError::ConnectFailed => f.write_str("Connection failed"), - NetError::ConnectTimeout => f.write_str("Connection timed out"), - NetError::ChannelStopped => f.write_str("Channel stopped"), - NetError::ChannelTimeout => f.write_str("Channel timed out"), - NetError::ServiceStopped => f.write_str("Service stopped"), - } - } -} diff --git a/src/net/message_subscriber.rs b/src/net/message_subscriber.rs index fb6a2e3b2..f2e3365a6 100644 --- a/src/net/message_subscriber.rs +++ b/src/net/message_subscriber.rs @@ -8,14 +8,13 @@ use std::io; use std::io::Cursor; use std::sync::Arc; -use crate::error::Result; -use crate::net::error::{NetError, NetResult}; +use crate::error::{Error, Result}; use crate::net::messages::Message; use crate::serial::{Decodable, Encodable}; /// 64bit identifier for message subscription. pub type MessageSubscriptionID = u64; -type MessageResult = NetResult>; +type MessageResult = Result>; /// Handles message subscriptions through a subscription ID and a receiver /// channel. @@ -47,7 +46,7 @@ impl MessageSubscription { trait MessageDispatcherInterface: Send + Sync { async fn trigger(&self, payload: Vec); - async fn trigger_error(&self, err: NetError); + async fn trigger_error(&self, err: Error); fn as_any(self: Arc) -> Arc; } @@ -155,7 +154,7 @@ impl MessageDispatcherInterface for MessageDispatcher { /// Sends a message to all subscriber channels. Clears any inactive /// channels. - async fn trigger_error(&self, err: NetError) { + async fn trigger_error(&self, err: Error) { self.trigger_all(Err(err)).await; } @@ -188,7 +187,7 @@ impl MessageSubsystem { } /// Add a dispatcher to the list of subscribers. - pub async fn subscribe(&self) -> NetResult> { + pub async fn subscribe(&self) -> Result> { let dispatcher = self.dispatchers.lock().await.get(M::name()).cloned(); let sub = match dispatcher { @@ -203,7 +202,7 @@ impl MessageSubsystem { None => { // normall return failure here // for now panic - return Err(NetError::OperationFailed); + return Err(Error::OperationFailed); } }; @@ -229,7 +228,7 @@ impl MessageSubsystem { } /// Send a message to all subscriber channels. Clear any inactive channels. - pub async fn trigger_error(&self, err: NetError) { + pub async fn trigger_error(&self, err: Error) { // TODO: this could be parallelized for dispatcher in self.dispatchers.lock().await.values() { dispatcher.trigger_error(err.clone()).await; @@ -294,7 +293,7 @@ async fn _do_message_subscriber_test() { assert_eq!(msg2.x, 110); println!("{}", msg2.x); - subsystem.trigger_error(NetError::ChannelStopped).await; + subsystem.trigger_error(Error::ChannelStopped).await; let msg2 = sub.receive().await; assert!(msg2.is_err()); diff --git a/src/net/mod.rs b/src/net/mod.rs index 0567ae927..cec54f85d 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -14,9 +14,6 @@ pub mod channel; /// connection. pub mod connector; -/// Defines a set of common network errors. Used for error handling. -pub mod error; - /// Hosts are a list of network addresses used when establishing an outbound /// connection. Hosts are shared across the network through the address /// protocol. When attempting to connect, a node will loop through addresses in diff --git a/src/net/p2p.rs b/src/net/p2p.rs index 3f6ae4c95..6f178c10b 100644 --- a/src/net/p2p.rs +++ b/src/net/p2p.rs @@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet}; use std::net::SocketAddr; use std::sync::Arc; -use crate::net::error::{NetError, NetResult}; +use crate::error::{Error, Result}; use crate::net::messages::Message; use crate::net::sessions::{InboundSession, OutboundSession, SeedSession}; use crate::net::{Channel, ChannelPtr, Hosts, HostsPtr, Settings, SettingsPtr}; @@ -22,9 +22,9 @@ pub type P2pPtr = Arc; pub struct P2p { pending: PendingChannels, channels: ConnectedChannels, - channel_subscriber: SubscriberPtr>, + channel_subscriber: SubscriberPtr>, // Used both internally and externally - stop_subscriber: SubscriberPtr, + stop_subscriber: SubscriberPtr, hosts: HostsPtr, settings: SettingsPtr, } @@ -44,7 +44,7 @@ impl P2p { } /// Invoke startup and seeding sequence. Call from constructing thread. - pub async fn start(self: Arc, executor: Arc>) -> NetResult<()> { + pub async fn start(self: Arc, executor: Arc>) -> Result<()> { debug!(target: "net", "P2p::start() [BEGIN]"); // Start manual connections @@ -59,7 +59,7 @@ impl P2p { /// Synchronize the blockchain and then begin long running sessions, /// call after start() is invoked. - pub async fn run(self: Arc, executor: Arc>) -> NetResult<()> { + pub async fn run(self: Arc, executor: Arc>) -> Result<()> { debug!(target: "net", "P2p::run() [BEGIN]"); let inbound = InboundSession::new(Arc::downgrade(&self)); @@ -81,7 +81,7 @@ impl P2p { } /// Broadcasts a message across all channels. - pub async fn broadcast(&self, message: M) -> NetResult<()> { + pub async fn broadcast(&self, message: M) -> Result<()> { for channel in self.channels.lock().await.values() { channel.send(message.clone()).await?; } @@ -133,12 +133,12 @@ impl P2p { } /// Subscribe to a channel. - pub async fn subscribe_channel(&self) -> Subscription> { + pub async fn subscribe_channel(&self) -> Subscription> { self.channel_subscriber.clone().subscribe().await } /// Subscribe to a stop signal. - pub async fn subscribe_stop(&self) -> Subscription { + pub async fn subscribe_stop(&self) -> Subscription { self.stop_subscriber.clone().subscribe().await } } diff --git a/src/net/protocols/protocol_address.rs b/src/net/protocols/protocol_address.rs index e6b894856..446495c32 100644 --- a/src/net/protocols/protocol_address.rs +++ b/src/net/protocols/protocol_address.rs @@ -2,7 +2,7 @@ use log::*; use smol::Executor; use std::sync::Arc; -use crate::net::error::NetResult; +use crate::error::Result; use crate::net::message_subscriber::MessageSubscription; use crate::net::messages; use crate::net::protocols::{ProtocolJobsManager, ProtocolJobsManagerPtr}; @@ -68,7 +68,7 @@ impl ProtocolAddress { /// Handles receiving the address message. Loops to continually recieve /// address messages on the address subsciption. Adds the recieved /// addresses to the list of hosts. - async fn handle_receive_addrs(self: Arc) -> NetResult<()> { + async fn handle_receive_addrs(self: Arc) -> Result<()> { debug!(target: "net", "ProtocolAddress::handle_receive_addrs() [START]"); loop { let addrs_msg = self.addrs_sub.receive().await?; @@ -88,7 +88,7 @@ impl ProtocolAddress { /// Handles receiving the get-address message. Continually recieves /// get-address messages on the get-address subsciption. Then replies /// with an address message. - async fn handle_receive_get_addrs(self: Arc) -> NetResult<()> { + async fn handle_receive_get_addrs(self: Arc) -> Result<()> { debug!(target: "net", "ProtocolAddress::handle_receive_get_addrs() [START]"); loop { let _get_addrs = self.get_addrs_sub.receive().await?; diff --git a/src/net/protocols/protocol_jobs_manager.rs b/src/net/protocols/protocol_jobs_manager.rs index 68ef85352..4674ebd50 100644 --- a/src/net/protocols/protocol_jobs_manager.rs +++ b/src/net/protocols/protocol_jobs_manager.rs @@ -4,7 +4,7 @@ use log::*; use smol::Task; use std::sync::Arc; -use crate::net::error::NetResult; +use crate::error::Result; use crate::net::ChannelPtr; use crate::system::ExecutorPtr; @@ -17,7 +17,7 @@ pub type ProtocolJobsManagerPtr = Arc; pub struct ProtocolJobsManager { name: &'static str, channel: ChannelPtr, - tasks: Mutex>>>, + tasks: Mutex>>>, } impl ProtocolJobsManager { @@ -39,7 +39,7 @@ impl ProtocolJobsManager { /// Spawns a new task and adds it to the internal queue. pub async fn spawn<'a, F>(&self, future: F, executor: ExecutorPtr<'a>) where - F: Future> + Send + 'a, + F: Future> + Send + 'a, { self.tasks.lock().await.push(executor.spawn(future)) } diff --git a/src/net/protocols/protocol_ping.rs b/src/net/protocols/protocol_ping.rs index 8cb0bc066..b16251c7e 100644 --- a/src/net/protocols/protocol_ping.rs +++ b/src/net/protocols/protocol_ping.rs @@ -4,7 +4,7 @@ use smol::Executor; use std::sync::Arc; use std::time::Instant; -use crate::net::error::{NetError, NetResult}; +use crate::error::{Error, Result}; use crate::net::messages; use crate::net::protocols::{ProtocolJobsManager, ProtocolJobsManagerPtr}; use crate::net::utility::sleep; @@ -48,7 +48,7 @@ impl ProtocolPing { /// loop. Loop sleeps for the duration of the channel heartbeat, then /// sends a ping message with a random nonce. Loop starts a timer, waits /// for the pong reply and insures the nonce is the same. - async fn run_ping_pong(self: Arc) -> NetResult<()> { + async fn run_ping_pong(self: Arc) -> Result<()> { debug!(target: "net", "ProtocolPing::run_ping_pong() [START]"); // Creates a subscription to pong message. let pong_sub = self @@ -77,7 +77,7 @@ impl ProtocolPing { if pong_msg.nonce != nonce { error!("Wrong nonce for ping reply. Disconnecting from channel."); self.channel.stop().await; - return Err(NetError::ChannelStopped); + return Err(Error::ChannelStopped); } let duration = start.elapsed().as_millis(); debug!(target: "net", "Received Pong message {}ms from [{:?}]", duration, self.channel.address()); @@ -86,7 +86,7 @@ impl ProtocolPing { /// Waits for ping, then replies with pong. Copies ping's nonce into the /// pong reply. - async fn reply_to_ping(self: Arc) -> NetResult<()> { + async fn reply_to_ping(self: Arc) -> Result<()> { debug!(target: "net", "ProtocolPing::reply_to_ping() [START]"); // Creates a subscription to ping message. let ping_sub = self diff --git a/src/net/protocols/protocol_seed.rs b/src/net/protocols/protocol_seed.rs index dfee7b060..f9f432b3e 100644 --- a/src/net/protocols/protocol_seed.rs +++ b/src/net/protocols/protocol_seed.rs @@ -2,7 +2,7 @@ use log::*; use smol::Executor; use std::sync::Arc; -use crate::net::error::NetResult; +use crate::error::Result; use crate::net::messages; use crate::net::{ChannelPtr, HostsPtr, SettingsPtr}; @@ -26,7 +26,7 @@ impl ProtocolSeed { /// Starts the seed protocol. Creates a subscription to the address message, /// then sends our address to the seed server. Sends a get-address /// message and receives an address message. - pub async fn start(self: Arc, _executor: Arc>) -> NetResult<()> { + pub async fn start(self: Arc, _executor: Arc>) -> Result<()> { debug!(target: "net", "ProtocolSeed::start() [START]"); // Create a subscription to address message. let addr_sub = self @@ -55,7 +55,7 @@ impl ProtocolSeed { /// Sends own external address over a channel. Imports own external address /// from settings, then adds that address to an address message and /// sends it out over the channel. - pub async fn send_self_address(&self) -> NetResult<()> { + pub async fn send_self_address(&self) -> Result<()> { match self.settings.external_addr { Some(addr) => { debug!(target: "net", "ProtocolSeed::send_own_address() addr={}", addr); diff --git a/src/net/protocols/protocol_version.rs b/src/net/protocols/protocol_version.rs index 96c873e32..4538bbe4d 100644 --- a/src/net/protocols/protocol_version.rs +++ b/src/net/protocols/protocol_version.rs @@ -3,7 +3,7 @@ use log::*; use smol::Executor; use std::sync::Arc; -use crate::net::error::{NetError, NetResult}; +use crate::error::{Error, Result}; use crate::net::message_subscriber::MessageSubscription; use crate::net::messages; use crate::net::utility::sleep; @@ -47,7 +47,7 @@ impl ProtocolVersion { /// Start version information exchange. Start the timer. Send version info /// and wait for version acknowledgement. Wait for version info and send /// version acknowledgement. - pub async fn run(self: Arc, executor: Arc>) -> NetResult<()> { + pub async fn run(self: Arc, executor: Arc>) -> Result<()> { debug!(target: "net", "ProtocolVersion::run() [START]"); // Start timer // Send version, wait for verack @@ -55,13 +55,13 @@ impl ProtocolVersion { // Fin. let result = futures::select! { _ = self.clone().exchange_versions(executor).fuse() => Ok(()), - _ = sleep(self.settings.channel_handshake_seconds).fuse() => Err(NetError::ChannelTimeout) + _ = sleep(self.settings.channel_handshake_seconds).fuse() => Err(Error::ChannelTimeout) }; debug!(target: "net", "ProtocolVersion::run() [END]"); result } /// Send and recieve version information. - async fn exchange_versions(self: Arc, executor: Arc>) -> NetResult<()> { + async fn exchange_versions(self: Arc, executor: Arc>) -> Result<()> { debug!(target: "net", "ProtocolVersion::exchange_versions() [START]"); let send = executor.spawn(self.clone().send_version()); @@ -72,7 +72,7 @@ impl ProtocolVersion { Ok(()) } /// Send version info and wait for version acknowledgement. - async fn send_version(self: Arc) -> NetResult<()> { + async fn send_version(self: Arc) -> Result<()> { debug!(target: "net", "ProtocolVersion::send_version() [START]"); let version = messages::VersionMessage {}; self.channel.clone().send(version).await?; @@ -85,7 +85,7 @@ impl ProtocolVersion { } /// Recieve version info, check the message is okay and send version /// acknowledgement. - async fn recv_version(self: Arc) -> NetResult<()> { + async fn recv_version(self: Arc) -> Result<()> { debug!(target: "net", "ProtocolVersion::recv_version() [START]"); // Rec let _version_msg = self.version_sub.receive().await?; diff --git a/src/net/sessions/inbound_session.rs b/src/net/sessions/inbound_session.rs index 8bb7598f0..581bf1b97 100644 --- a/src/net/sessions/inbound_session.rs +++ b/src/net/sessions/inbound_session.rs @@ -3,7 +3,8 @@ use log::*; use std::net::SocketAddr; use std::sync::{Arc, Weak}; -use crate::net::error::{NetError, NetResult}; +use crate::error::{Error, Result}; +//use crate::net::error::{Error, Result}; use crate::net::protocols::{ProtocolAddress, ProtocolPing}; use crate::net::sessions::Session; use crate::net::{Acceptor, AcceptorPtr}; @@ -31,7 +32,7 @@ impl InboundSession { /// Starts the inbound session. Begins by accepting connections and fails if /// the address is not configured. Then runs the channel subscription /// loop. - pub fn start(self: Arc, executor: Arc>) -> NetResult<()> { + pub fn start(self: Arc, executor: Arc>) -> Result<()> { match self.p2p().settings().inbound { Some(accept_addr) => { self.clone() @@ -47,7 +48,7 @@ impl InboundSession { self.clone().channel_sub_loop(executor.clone()), // Ignore stop handler |_| async {}, - NetError::ServiceStopped, + Error::ServiceStopped, executor, ); @@ -63,7 +64,7 @@ impl InboundSession { self: Arc, accept_addr: SocketAddr, executor: Arc>, - ) -> NetResult<()> { + ) -> Result<()> { info!("Starting inbound session on {}", accept_addr); let result = self.acceptor.clone().start(accept_addr, executor); if let Err(err) = result.clone() { @@ -74,7 +75,7 @@ impl InboundSession { /// Wait for all new channels created by the acceptor and call /// setup_channel() on them. - async fn channel_sub_loop(self: Arc, executor: Arc>) -> NetResult<()> { + async fn channel_sub_loop(self: Arc, executor: Arc>) -> Result<()> { let channel_sub = self.acceptor.clone().subscribe().await; loop { let channel = channel_sub.receive().await?; @@ -93,7 +94,7 @@ impl InboundSession { self: Arc, channel: ChannelPtr, executor: Arc>, - ) -> NetResult<()> { + ) -> Result<()> { info!("Connected inbound [{}]", channel.address()); self.clone() @@ -108,7 +109,7 @@ impl InboundSession { self: Arc, channel: ChannelPtr, executor: Arc>, - ) -> NetResult<()> { + ) -> Result<()> { let settings = self.p2p().settings().clone(); let hosts = self.p2p().hosts().clone(); diff --git a/src/net/sessions/outbound_session.rs b/src/net/sessions/outbound_session.rs index bf94e8e47..b2368aa72 100644 --- a/src/net/sessions/outbound_session.rs +++ b/src/net/sessions/outbound_session.rs @@ -4,7 +4,7 @@ use log::*; use std::net::SocketAddr; use std::sync::{Arc, Weak}; -use crate::net::error::{NetError, NetResult}; +use crate::error::{Error, Result}; use crate::net::protocols::{ProtocolAddress, ProtocolPing}; use crate::net::sessions::Session; use crate::net::{ChannelPtr, Connector, P2p}; @@ -25,7 +25,7 @@ impl OutboundSession { }) } /// Start the outbound session. Runs the channel connect loop. - pub async fn start(self: Arc, executor: Arc>) -> NetResult<()> { + pub async fn start(self: Arc, executor: Arc>) -> Result<()> { let slots_count = self.p2p().settings().outbound_connections; info!("Starting {} outbound connection slots.", slots_count); // Activate mutex lock on connection slots. @@ -38,7 +38,7 @@ impl OutboundSession { self.clone().channel_connect_loop(i, executor.clone()), // Ignore stop handler |_| async {}, - NetError::ServiceStopped, + Error::ServiceStopped, executor.clone(), ); @@ -66,7 +66,7 @@ impl OutboundSession { self: Arc, slot_number: u32, executor: Arc>, - ) -> NetResult<()> { + ) -> Result<()> { let connector = Connector::new(self.p2p().settings().clone()); loop { @@ -109,7 +109,7 @@ impl OutboundSession { /// our own inbound address, then checks whether it is already connected /// (exists) or connecting (pending). Keeps looping until address is /// found that passes all checks. - async fn load_address(&self, slot_number: u32) -> NetResult { + async fn load_address(&self, slot_number: u32) -> Result { let p2p = self.p2p(); let hosts = p2p.hosts(); let inbound_addr = p2p.settings().inbound; @@ -122,7 +122,7 @@ impl OutboundSession { "Hosts address pool is empty. Closing connect slot #{}", slot_number ); - return Err(NetError::ServiceStopped); + return Err(Error::ServiceStopped); } let addr = addr.unwrap(); @@ -158,7 +158,7 @@ impl OutboundSession { self: Arc, channel: ChannelPtr, executor: Arc>, - ) -> NetResult<()> { + ) -> Result<()> { let settings = self.p2p().settings().clone(); let hosts = self.p2p().hosts().clone(); diff --git a/src/net/sessions/seed_session.rs b/src/net/sessions/seed_session.rs index 43dfdc3f6..778f8eb3c 100644 --- a/src/net/sessions/seed_session.rs +++ b/src/net/sessions/seed_session.rs @@ -4,7 +4,8 @@ use log::*; use std::net::SocketAddr; use std::sync::{Arc, Weak}; -use crate::net::error::{NetError, NetResult}; +use crate::error::{Error, Result}; +//use crate::net::error::{Error, Result}; use crate::net::protocols::{ProtocolPing, ProtocolSeed}; use crate::net::sessions::Session; use crate::net::utility::sleep; @@ -23,7 +24,7 @@ impl SeedSession { /// Start the seed session. Creates a new task for every seed connection and /// starts the seed on each task. - pub async fn start(self: Arc, executor: Arc>) -> NetResult<()> { + pub async fn start(self: Arc, executor: Arc>) -> Result<()> { debug!(target: "net", "SeedSession::start() [START]"); let settings = self.p2p().settings(); @@ -56,14 +57,14 @@ impl SeedSession { } _ = sleep(settings.seed_query_timeout_seconds).fuse() => { error!("Querying seeds timed out"); - return Err(NetError::OperationFailed); + return Err(Error::OperationFailed); } } // Seed process complete if self.p2p().hosts().is_empty().await { error!("Hosts pool still empty after seeding"); - return Err(NetError::OperationFailed); + return Err(Error::OperationFailed); } debug!(target: "net", "SeedSession::start() [END]"); @@ -78,7 +79,7 @@ impl SeedSession { seed_index: usize, seed: SocketAddr, executor: Arc>, - ) -> NetResult<()> { + ) -> Result<()> { debug!(target: "net", "SeedSession::start_seed(i={}) [START]", seed_index); let (hosts, settings) = { let p2p = self.p2p.upgrade().unwrap(); @@ -119,7 +120,7 @@ impl SeedSession { hosts: HostsPtr, settings: SettingsPtr, executor: Arc>, - ) -> NetResult<()> { + ) -> Result<()> { let protocol_ping = ProtocolPing::new(channel.clone(), settings.clone()); protocol_ping.start(executor.clone()).await; diff --git a/src/net/sessions/session.rs b/src/net/sessions/session.rs index d83200c0a..b4822c248 100644 --- a/src/net/sessions/session.rs +++ b/src/net/sessions/session.rs @@ -3,7 +3,7 @@ use log::*; use smol::Executor; use std::sync::Arc; -use crate::net::error::NetResult; +use crate::error::Result; use crate::net::p2p::P2pPtr; use crate::net::protocols::ProtocolVersion; use crate::net::ChannelPtr; @@ -34,7 +34,7 @@ pub trait Session: Sync { self: Arc, channel: ChannelPtr, executor: Arc>, - ) -> NetResult<()> { + ) -> Result<()> { debug!(target: "net", "Session::register_channel() [START]"); let protocol_version = ProtocolVersion::new(channel.clone(), self.p2p().settings()).await; @@ -58,7 +58,7 @@ pub trait Session: Sync { protocol_version: Arc, channel: ChannelPtr, executor: Arc>, - ) -> NetResult<()> { + ) -> Result<()> { // Perform handshake protocol_version.run(executor.clone()).await?; From 6d239458cbb8cb725df5bb590b85ff8952321a7d Mon Sep 17 00:00:00 2001 From: rachel-rose Date: Thu, 20 May 2021 21:01:58 +0200 Subject: [PATCH 4/4] removed unused error types --- src/error.rs | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/src/error.rs b/src/error.rs index 4bf82f8f8..504cc1f8e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -9,15 +9,6 @@ pub type Result = std::result::Result; #[derive(Debug, Clone)] pub enum Error { - Foo, - CommitsDontAdd, - InvalidCredential, - TransactionPedersenCheckFailed, - TokenAlreadySpent, - InputTokenVerifyFailed, - RangeproofPedersenMatchFailed, - ProofsFailed, - MissingProofs, Io(std::io::ErrorKind), /// VarInt was encoded in a non-minimal way NonMinimalVarInt, @@ -54,19 +45,6 @@ impl std::error::Error for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result { match *self { - Error::Foo => f.write_str("foo"), - Error::CommitsDontAdd => f.write_str("Commits don't add up properly"), - Error::InvalidCredential => f.write_str("Credential is invalid"), - Error::TransactionPedersenCheckFailed => { - f.write_str("Transaction pedersens for input and output don't sum up") - } - Error::TokenAlreadySpent => f.write_str("This input token is already spent"), - Error::InputTokenVerifyFailed => f.write_str("Input token verify of credential failed"), - Error::RangeproofPedersenMatchFailed => { - f.write_str("Rangeproof pedersen check for match failed") - } - Error::ProofsFailed => f.write_str("Proof validation failed"), - Error::MissingProofs => f.write_str("Missing proofs"), Error::Io(ref err) => write!(f, "io error:{:?}", err), Error::NonMinimalVarInt => f.write_str("non-minimal varint"), Error::ParseFailed(ref err) => write!(f, "parse failed: {}", err), @@ -164,4 +142,3 @@ impl From for Error { Error::VerifyFailed } } -