From 422b98030f6bcb5e7217bd047f13de625df022a4 Mon Sep 17 00:00:00 2001 From: hashmap Date: Fri, 19 Oct 2018 10:50:59 +0200 Subject: [PATCH 01/24] Add wallet TLS setup doc (#1786) Add wallet TLS setup doc --- doc/wallet/tls-setup.md | 68 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 doc/wallet/tls-setup.md diff --git a/doc/wallet/tls-setup.md b/doc/wallet/tls-setup.md new file mode 100644 index 00000000..ae4ab344 --- /dev/null +++ b/doc/wallet/tls-setup.md @@ -0,0 +1,68 @@ +# Wallet TLS setup + +## What you need +* A server with a static IP address (eg `3.3.3.3`) +* A domain name ownership (`example.com`) +* DNS configuration for this IP (`grin1.example.com` -> `3.3.3.3`) + +If you don't have a static IP you may want to consider using services like DynDNS which support dynamic IP resolving, this case is not covered by this guide, but all the next steps are equally applicable. + +If you don't have a domain name there is a possibility to get a TLS certificate for your IP, but you have to pay for that (so perhaps it's cheaper to buy a domain name) and it's rarely supported by certificate providers. + +## I have a TLS certificate already +Uncomment and update the following lines in wallet config (by default `~/.grin/grin-wallet.toml`): + +``` +tls_certificate_file = "/path/to/my/cerificate/fullchain.pem" +tls_certificate_key = "/path/to/my/cerificate/privkey.pem" +``` + +Make sure your user has read access to the files (see below for how to do it). Restart wallet. When you (or someone else) send grins to this wallet the destination (`-d` option) must start with `https://`, not with `http://`. + +## I don't have a TLS certificate +You can get it for free from [Let's Encrypt](https://letsencrypt.org/). To simplify the process we need `certbot`. + +### Install certbot +Go to [Certbot home page](https://certbot.eff.org/), choose I'm using `None of the above` and your OS (eg `Ubuntu 18.04` which will be used as an example). You will be redirected to a page with instructions like [steps for Ubuntu](https://certbot.eff.org/lets-encrypt/ubuntubionic-other). Follow instructions from `Install` section. As result you should have `certbot` installed. + +### Obtain certificate +If you have experince with `certboot` feel free to use any type of challenge. This guide covers the simplest case of HTTP challenge. For this you need to have a web server listening on port `80`, which requires running it as root in the simplest case. We will use the server provided by certbot. **Make sure you have port 80 open** + +``` + sudo certbot certonly --standalone -d grin1.example.com +``` + +It will ask you some questions, as result you should see something like: + +``` + Congratulations! Your certificate and chain have been saved at: + /etc/letsencrypt/live/grin1.example.com/fullchain.pem + Your key file has been saved at: + /etc/letsencrypt/live/grin1.example.com/privkey.pem + Your cert will expire on 2019-01-16. To obtain a new or tweaked + version of this certificate in the future, simply run certbot + again. To non-interactively renew *all* of your certificates, run + "certbot renew" +``` + +### Change permissions +Now you have the certificate files but only root user can read it. We run grin as `ubuntu` user. There are different scenarios how to fix it, the simplest one is to create a group which will have access to `/etc/letsencrypt` directory and add our user to this group. + +``` +$ sudo groupadd tls-cert` +$ sudo usermod -a -G tls-cert ubuntu` +$ chgrp -R tls-cert /etc/letsencrypt` +$ chmod -R g=rX /etc/letsencrypt` +$ sudo chmod 2755 /etc/letsencrypt` +``` + +The last step is needed for renewal, it makes sure that all new files will have the same group ownership. + +### Update wallet config +Refer to `I have a TLS certificate already` because you have it now. Use the folowing values: + +``` +tls_certificate_file = "/etc/letsencrypt/live/grin1.example.com/fullchain.pem" +tls_certificate_key = "/etc/letsencrypt/live/grin1.example.com/privkey.pem" +``` + From f2949efbfd3ffdb32f835774ce252b672a8c1f30 Mon Sep 17 00:00:00 2001 From: RJ Rybarczyk Date: Fri, 19 Oct 2018 03:12:34 -0700 Subject: [PATCH 02/24] Make check_api_secret_file fn private (#1792) --- config/src/config.rs | 2 +- config/src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/config/src/config.rs b/config/src/config.rs index 90f04d2c..b07b3790 100644 --- a/config/src/config.rs +++ b/config/src/config.rs @@ -107,7 +107,7 @@ fn check_api_secret(api_secret_path: &PathBuf) -> Result<(), ConfigError> { } /// Check that the api secret file exists and is valid -pub fn check_api_secret_file() -> Result<(), ConfigError> { +fn check_api_secret_file() -> Result<(), ConfigError> { let grin_path = get_grin_path()?; let mut api_secret_path = grin_path.clone(); api_secret_path.push(API_SECRET_FILE_NAME); diff --git a/config/src/lib.rs b/config/src/lib.rs index 22b6a509..a482dee9 100644 --- a/config/src/lib.rs +++ b/config/src/lib.rs @@ -35,5 +35,5 @@ mod comments; pub mod config; pub mod types; -pub use config::{check_api_secret_file, initial_setup_server, initial_setup_wallet}; +pub use config::{initial_setup_server, initial_setup_wallet}; pub use types::{ConfigError, ConfigMembers, GlobalConfig, GlobalWalletConfig}; From 0d06561a9182fb4083093b66fa7c2640d86573cd Mon Sep 17 00:00:00 2001 From: Gary Yu Date: Sat, 20 Oct 2018 08:13:07 +0800 Subject: [PATCH 03/24] replace stdlib RwLock and Mutex with parking_lot (#1793) * replace all stdlib RwLock with parking_lot RwLock * replace stdlib Mutex with parking_lot Mutex * rustfmt --- Cargo.lock | 1 + api/src/handlers.rs | 7 ++-- chain/src/chain.rs | 57 ++++++++++++++------------- chain/src/pipe.rs | 5 ++- chain/src/store.rs | 27 +++++++------ chain/tests/data_file_integrity.rs | 3 +- chain/tests/mine_simple_chain.rs | 3 +- chain/tests/test_coinbase_maturity.rs | 4 +- core/src/core/block.rs | 5 ++- core/src/core/committed.rs | 8 ++-- core/src/core/transaction.rs | 17 ++++---- core/src/global.rs | 26 ++++++------ core/tests/block.rs | 3 +- core/tests/core.rs | 5 ++- core/tests/verifier_cache.rs | 9 +++-- keychain/src/types.rs | 2 +- p2p/src/conn.rs | 11 +++--- p2p/src/handshake.rs | 7 ++-- p2p/src/peer.rs | 29 +++++++------- p2p/src/peers.rs | 26 ++++++------ p2p/src/types.rs | 11 +++--- pool/src/pool.rs | 3 +- pool/src/transaction_pool.rs | 3 +- pool/tests/block_building.rs | 9 +++-- pool/tests/block_reconciliation.rs | 9 +++-- pool/tests/coinbase_maturity.rs | 5 ++- pool/tests/common/mod.rs | 7 ++-- pool/tests/transaction_pool.rs | 23 +++++------ servers/src/common/adapters.rs | 9 +++-- servers/src/common/stats.rs | 3 +- servers/src/common/types.rs | 17 ++++---- servers/src/grin/dandelion_monitor.rs | 13 +++--- servers/src/grin/server.rs | 7 ++-- servers/src/grin/sync/state_sync.rs | 2 +- servers/src/mining/mine_block.rs | 9 ++--- servers/src/mining/stratumserver.rs | 23 +++++------ servers/src/mining/test_miner.rs | 3 +- servers/tests/api.rs | 5 ++- servers/tests/dandelion.rs | 11 +++--- servers/tests/framework/mod.rs | 7 ++-- servers/tests/simulnet.rs | 3 +- servers/tests/wallet.rs | 11 +++--- src/bin/cmd/wallet.rs | 3 +- util/Cargo.toml | 1 + util/src/lib.rs | 10 +++-- util/src/logger.rs | 18 ++++----- util/src/secp_static.rs | 5 ++- wallet/src/libtx/build.rs | 3 +- wallet/src/libtx/reward.rs | 2 +- wallet/src/libtx/slate.rs | 3 +- wallet/src/libwallet/api.rs | 39 +++++++++--------- wallet/src/libwallet/controller.rs | 3 +- wallet/src/libwallet/internal/tx.rs | 3 +- wallet/tests/accounts.rs | 16 ++++---- wallet/tests/common/mod.rs | 17 ++++---- wallet/tests/common/testclient.rs | 25 ++++++------ wallet/tests/restore.rs | 8 ++-- 57 files changed, 324 insertions(+), 280 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d4e128d6..2a76a600 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -888,6 +888,7 @@ dependencies = [ "base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)", "byteorder 1.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", "secp256k1zkp 0.7.1 (git+https://github.com/mimblewimble/rust-secp256k1-zkp?tag=grin_integration_28)", "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/api/src/handlers.rs b/api/src/handlers.rs index e2960ddf..8d4c08df 100644 --- a/api/src/handlers.rs +++ b/api/src/handlers.rs @@ -14,7 +14,8 @@ use std::collections::HashMap; use std::net::SocketAddr; -use std::sync::{Arc, RwLock, Weak}; +use std::sync::{Arc, Weak}; +use util::RwLock; use failure::ResultExt; use futures::future::ok; @@ -695,7 +696,7 @@ struct PoolInfoHandler { impl Handler for PoolInfoHandler { fn get(&self, _req: Request) -> ResponseFuture { let pool_arc = w(&self.tx_pool); - let pool = pool_arc.read().unwrap(); + let pool = pool_arc.read(); json_response(&PoolInfo { pool_size: pool.total_size(), @@ -753,7 +754,7 @@ impl PoolPushHandler { ); // Push to tx pool. - let mut tx_pool = pool_arc.write().unwrap(); + let mut tx_pool = pool_arc.write(); let header = tx_pool.blockchain.chain_head().unwrap(); tx_pool .add_to_pool(source, tx, !fluff, &header) diff --git a/chain/src/chain.rs b/chain/src/chain.rs index e36ea528..e2a144e4 100644 --- a/chain/src/chain.rs +++ b/chain/src/chain.rs @@ -18,8 +18,9 @@ use std::collections::HashMap; use std::fs::File; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use std::time::{Duration, Instant}; +use util::RwLock; use lmdb; use lru_cache::LruCache; @@ -75,7 +76,7 @@ impl OrphanBlockPool { } fn len(&self) -> usize { - let orphans = self.orphans.read().unwrap(); + let orphans = self.orphans.read(); orphans.len() } @@ -84,8 +85,8 @@ impl OrphanBlockPool { } fn add(&self, orphan: Orphan) { - let mut orphans = self.orphans.write().unwrap(); - let mut height_idx = self.height_idx.write().unwrap(); + let mut orphans = self.orphans.write(); + let mut height_idx = self.height_idx.write(); { let height_hashes = height_idx .entry(orphan.block.header.height) @@ -125,15 +126,15 @@ impl OrphanBlockPool { /// Get an orphan from the pool indexed by the hash of its parent, removing /// it at the same time, preventing clone fn remove_by_height(&self, height: &u64) -> Option> { - let mut orphans = self.orphans.write().unwrap(); - let mut height_idx = self.height_idx.write().unwrap(); + let mut orphans = self.orphans.write(); + let mut height_idx = self.height_idx.write(); height_idx .remove(height) .map(|hs| hs.iter().filter_map(|h| orphans.remove(h)).collect()) } pub fn contains(&self, hash: &Hash) -> bool { - let orphans = self.orphans.read().unwrap(); + let orphans = self.orphans.read(); orphans.contains_key(hash) } } @@ -221,7 +222,7 @@ impl Chain { fn process_block_single(&self, b: Block, opts: Options) -> Result, Error> { let maybe_new_head: Result, Error>; { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); let batch = self.store.batch()?; let mut ctx = self.new_ctx(opts, batch, &mut txhashset)?; @@ -235,7 +236,7 @@ impl Chain { let add_to_hash_cache = |hash: Hash| { // only add to hash cache below if block is definitively accepted // or rejected - let mut cache = self.block_hashes_cache.write().unwrap(); + let mut cache = self.block_hashes_cache.write(); cache.insert(hash, true); }; @@ -299,7 +300,7 @@ impl Chain { /// Process a block header received during "header first" propagation. pub fn process_block_header(&self, bh: &BlockHeader, opts: Options) -> Result<(), Error> { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); let batch = self.store.batch()?; let mut ctx = self.new_ctx(opts, batch, &mut txhashset)?; pipe::process_block_header(bh, &mut ctx)?; @@ -315,7 +316,7 @@ impl Chain { headers: &Vec, opts: Options, ) -> Result<(), Error> { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); let batch = self.store.batch()?; let mut ctx = self.new_ctx(opts, batch, &mut txhashset)?; @@ -417,7 +418,7 @@ impl Chain { /// current chain state, specifically the current winning (valid, most /// work) fork. pub fn is_unspent(&self, output_ref: &OutputIdentifier) -> Result { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); let res = txhashset.is_unspent(output_ref); match res { Err(e) => Err(e), @@ -427,7 +428,7 @@ impl Chain { /// Validate the tx against the current UTXO set. pub fn validate_tx(&self, tx: &Transaction) -> Result<(), Error> { - let txhashset = self.txhashset.read().unwrap(); + let txhashset = self.txhashset.read(); txhashset::utxo_view(&txhashset, |utxo| { utxo.validate_tx(tx)?; Ok(()) @@ -443,7 +444,7 @@ impl Chain { /// that has not yet sufficiently matured. pub fn verify_coinbase_maturity(&self, tx: &Transaction) -> Result<(), Error> { let height = self.next_block_height()?; - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); txhashset::extending_readonly(&mut txhashset, |extension| { extension.verify_coinbase_maturity(&tx.inputs(), height)?; Ok(()) @@ -470,7 +471,7 @@ impl Chain { return Ok(()); } - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); // Now create an extension from the txhashset and validate against the // latest block header. Rewind the extension to the specified header to @@ -485,7 +486,7 @@ impl Chain { /// Sets the txhashset roots on a brand new block by applying the block on /// the current txhashset state. pub fn set_txhashset_roots(&self, b: &mut Block, is_fork: bool) -> Result<(), Error> { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); let (prev_root, roots, sizes) = txhashset::extending_readonly(&mut txhashset, |extension| { if is_fork { @@ -526,7 +527,7 @@ impl Chain { output: &OutputIdentifier, block_header: &BlockHeader, ) -> Result { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); let merkle_proof = txhashset::extending_readonly(&mut txhashset, |extension| { extension.rewind(&block_header)?; @@ -539,13 +540,13 @@ impl Chain { /// Return a merkle proof valid for the current output pmmr state at the /// given pos pub fn get_merkle_proof_for_pos(&self, commit: Commitment) -> Result { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); txhashset.merkle_proof(commit) } /// Returns current txhashset roots pub fn get_txhashset_roots(&self) -> TxHashSetRoots { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); txhashset.roots() } @@ -560,7 +561,7 @@ impl Chain { // to rewind after receiving the txhashset zip. let header = self.get_block_header(&h)?; { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); txhashset::extending_readonly(&mut txhashset, |extension| { extension.rewind(&header)?; extension.snapshot()?; @@ -617,7 +618,7 @@ impl Chain { /// have an MMR we can safely rewind based on the headers received from a peer. /// TODO - think about how to optimize this. pub fn rebuild_sync_mmr(&self, head: &Tip) -> Result<(), Error> { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); let mut batch = self.store.batch()?; txhashset::sync_extending(&mut txhashset, &mut batch, |extension| { extension.rebuild(head, &self.genesis)?; @@ -733,7 +734,7 @@ impl Chain { // Replace the chain txhashset with the newly built one. { - let mut txhashset_ref = self.txhashset.write().unwrap(); + let mut txhashset_ref = self.txhashset.write(); *txhashset_ref = txhashset; } @@ -772,7 +773,7 @@ impl Chain { debug!(LOGGER, "Starting blockchain compaction."); // Compact the txhashset via the extension. { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); txhashset.compact()?; // print out useful debug info after compaction @@ -836,19 +837,19 @@ impl Chain { /// returns the last n nodes inserted into the output sum tree pub fn get_last_n_output(&self, distance: u64) -> Vec<(Hash, OutputIdentifier)> { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); txhashset.last_n_output(distance) } /// as above, for rangeproofs pub fn get_last_n_rangeproof(&self, distance: u64) -> Vec<(Hash, RangeProof)> { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); txhashset.last_n_rangeproof(distance) } /// as above, for kernels pub fn get_last_n_kernel(&self, distance: u64) -> Vec<(Hash, TxKernel)> { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); txhashset.last_n_kernel(distance) } @@ -858,7 +859,7 @@ impl Chain { start_index: u64, max: u64, ) -> Result<(u64, u64, Vec), Error> { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); let max_index = txhashset.highest_output_insertion_index(); let outputs = txhashset.outputs_by_insertion_index(start_index, max); let rangeproofs = txhashset.rangeproofs_by_insertion_index(start_index, max); @@ -945,7 +946,7 @@ impl Chain { &self, output_ref: &OutputIdentifier, ) -> Result { - let mut txhashset = self.txhashset.write().unwrap(); + let mut txhashset = self.txhashset.write(); let (_, pos) = txhashset.is_unspent(output_ref)?; let mut min = 1; let mut max = { diff --git a/chain/src/pipe.rs b/chain/src/pipe.rs index 060a0bb5..82e1e143 100644 --- a/chain/src/pipe.rs +++ b/chain/src/pipe.rs @@ -14,7 +14,8 @@ //! Implementation of the chain block acceptance (or refusal) pipeline. -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use chrono::prelude::Utc; use chrono::Duration; @@ -288,7 +289,7 @@ fn check_known_head(header: &BlockHeader, ctx: &mut BlockContext) -> Result<(), /// Keeps duplicates from the network in check. /// Checks against the cache of recently processed block hashes. fn check_known_cache(header: &BlockHeader, ctx: &mut BlockContext) -> Result<(), Error> { - let mut cache = ctx.block_hashes_cache.write().unwrap(); + let mut cache = ctx.block_hashes_cache.write(); if cache.contains_key(&header.hash()) { return Err(ErrorKind::Unfit("already known in cache".to_string()).into()); } diff --git a/chain/src/store.rs b/chain/src/store.rs index 42383381..0b91eb2f 100644 --- a/chain/src/store.rs +++ b/chain/src/store.rs @@ -14,7 +14,8 @@ //! Implements storage primitives required by the chain -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use croaring::Bitmap; use lmdb; @@ -96,7 +97,7 @@ impl ChainStore { pub fn get_block_sums(&self, h: &Hash) -> Result { { - let mut block_sums_cache = self.block_sums_cache.write().unwrap(); + let mut block_sums_cache = self.block_sums_cache.write(); // cache hit - return the value from the cache if let Some(block_sums) = block_sums_cache.get_mut(h) { @@ -112,7 +113,7 @@ impl ChainStore { // cache miss - so adding to the cache for next time if let Ok(block_sums) = block_sums { { - let mut block_sums_cache = self.block_sums_cache.write().unwrap(); + let mut block_sums_cache = self.block_sums_cache.write(); block_sums_cache.insert(*h, block_sums.clone()); } Ok(block_sums) @@ -123,7 +124,7 @@ impl ChainStore { pub fn get_block_header(&self, h: &Hash) -> Result { { - let mut header_cache = self.header_cache.write().unwrap(); + let mut header_cache = self.header_cache.write(); // cache hit - return the value from the cache if let Some(header) = header_cache.get_mut(h) { @@ -140,7 +141,7 @@ impl ChainStore { // cache miss - so adding to the cache for next time if let Ok(header) = header { { - let mut header_cache = self.header_cache.write().unwrap(); + let mut header_cache = self.header_cache.write(); header_cache.insert(*h, header.clone()); } Ok(header) @@ -310,7 +311,7 @@ impl<'a> Batch<'a> { let hash = header.hash(); { - let mut header_cache = self.header_cache.write().unwrap(); + let mut header_cache = self.header_cache.write(); header_cache.insert(hash, header.clone()); } @@ -350,7 +351,7 @@ impl<'a> Batch<'a> { pub fn get_block_header(&self, h: &Hash) -> Result { { - let mut header_cache = self.header_cache.write().unwrap(); + let mut header_cache = self.header_cache.write(); // cache hit - return the value from the cache if let Some(header) = header_cache.get_mut(h) { @@ -367,7 +368,7 @@ impl<'a> Batch<'a> { // cache miss - so adding to the cache for next time if let Ok(header) = header { { - let mut header_cache = self.header_cache.write().unwrap(); + let mut header_cache = self.header_cache.write(); header_cache.insert(*h, header.clone()); } Ok(header) @@ -390,7 +391,7 @@ impl<'a> Batch<'a> { pub fn save_block_sums(&self, h: &Hash, sums: &BlockSums) -> Result<(), Error> { { - let mut block_sums_cache = self.block_sums_cache.write().unwrap(); + let mut block_sums_cache = self.block_sums_cache.write(); block_sums_cache.insert(*h, sums.clone()); } @@ -400,7 +401,7 @@ impl<'a> Batch<'a> { pub fn get_block_sums(&self, h: &Hash) -> Result { { - let mut block_sums_cache = self.block_sums_cache.write().unwrap(); + let mut block_sums_cache = self.block_sums_cache.write(); // cache hit - return the value from the cache if let Some(block_sums) = block_sums_cache.get_mut(h) { @@ -416,7 +417,7 @@ impl<'a> Batch<'a> { // cache miss - so adding to the cache for next time if let Ok(block_sums) = block_sums { { - let mut block_sums_cache = self.block_sums_cache.write().unwrap(); + let mut block_sums_cache = self.block_sums_cache.write(); block_sums_cache.insert(*h, block_sums.clone()); } Ok(block_sums) @@ -511,7 +512,7 @@ impl<'a> Batch<'a> { self.save_block_input_bitmap(&block.hash(), &bitmap)?; // Finally cache it locally for use later. - let mut cache = self.block_input_bitmap_cache.write().unwrap(); + let mut cache = self.block_input_bitmap_cache.write(); cache.insert(block.hash(), bitmap.serialize()); Ok(bitmap) @@ -519,7 +520,7 @@ impl<'a> Batch<'a> { pub fn get_block_input_bitmap(&self, bh: &Hash) -> Result { { - let mut cache = self.block_input_bitmap_cache.write().unwrap(); + let mut cache = self.block_input_bitmap_cache.write(); // cache hit - return the value from the cache if let Some(bytes) = cache.get_mut(bh) { diff --git a/chain/tests/data_file_integrity.rs b/chain/tests/data_file_integrity.rs index f80a8738..88088cdb 100644 --- a/chain/tests/data_file_integrity.rs +++ b/chain/tests/data_file_integrity.rs @@ -24,7 +24,8 @@ extern crate rand; use chrono::Duration; use std::fs; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use chain::types::NoopAdapter; use chain::Chain; diff --git a/chain/tests/mine_simple_chain.rs b/chain/tests/mine_simple_chain.rs index 095d89db..3c3ad121 100644 --- a/chain/tests/mine_simple_chain.rs +++ b/chain/tests/mine_simple_chain.rs @@ -23,7 +23,8 @@ extern crate rand; use chrono::Duration; use std::fs; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use chain::types::NoopAdapter; use chain::Chain; diff --git a/chain/tests/test_coinbase_maturity.rs b/chain/tests/test_coinbase_maturity.rs index ef7fef95..ceeab4df 100644 --- a/chain/tests/test_coinbase_maturity.rs +++ b/chain/tests/test_coinbase_maturity.rs @@ -18,12 +18,14 @@ extern crate grin_chain as chain; extern crate grin_core as core; extern crate grin_keychain as keychain; extern crate grin_store as store; +extern crate grin_util as util; extern crate grin_wallet as wallet; extern crate rand; use chrono::Duration; use std::fs; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use chain::types::NoopAdapter; use chain::ErrorKind; diff --git a/core/src/core/block.rs b/core/src/core/block.rs index 4089235d..c9640ac7 100644 --- a/core/src/core/block.rs +++ b/core/src/core/block.rs @@ -20,7 +20,8 @@ use std::collections::HashSet; use std::fmt; use std::iter::FromIterator; use std::mem; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use consensus::{self, reward, REWARD}; use core::committed::{self, Committed}; @@ -648,7 +649,7 @@ impl Block { { let secp = static_secp_instance(); - let secp = secp.lock().unwrap(); + let secp = secp.lock(); let over_commit = secp.commit_value(reward(self.total_fees()))?; let out_adjust_sum = secp.commit_sum( diff --git a/core/src/core/committed.rs b/core/src/core/committed.rs index 3982c433..03745adb 100644 --- a/core/src/core/committed.rs +++ b/core/src/core/committed.rs @@ -66,7 +66,7 @@ pub trait Committed { // commit to zero built from the offset let kernel_sum_plus_offset = { let secp = static_secp_instance(); - let secp = secp.lock().unwrap(); + let secp = secp.lock(); let mut commits = vec![kernel_sum]; if *offset != BlindingFactor::zero() { let key = offset.secret_key(&secp)?; @@ -90,7 +90,7 @@ pub trait Committed { if overage != 0 { let over_commit = { let secp = static_secp_instance(); - let secp = secp.lock().unwrap(); + let secp = secp.lock(); let overage_abs = overage.checked_abs().ok_or_else(|| Error::InvalidValue)? as u64; secp.commit_value(overage_abs).unwrap() }; @@ -144,7 +144,7 @@ pub fn sum_commits( positive.retain(|x| *x != zero_commit); negative.retain(|x| *x != zero_commit); let secp = static_secp_instance(); - let secp = secp.lock().unwrap(); + let secp = secp.lock(); Ok(secp.commit_sum(positive, negative)?) } @@ -156,7 +156,7 @@ pub fn sum_kernel_offsets( negative: Vec, ) -> Result { let secp = static_secp_instance(); - let secp = secp.lock().unwrap(); + let secp = secp.lock(); let positive = to_secrets(positive, &secp); let negative = to_secrets(negative, &secp); diff --git a/core/src/core/transaction.rs b/core/src/core/transaction.rs index 37bdce30..aedbeeb7 100644 --- a/core/src/core/transaction.rs +++ b/core/src/core/transaction.rs @@ -17,8 +17,9 @@ use std::cmp::max; use std::cmp::Ordering; use std::collections::HashSet; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use std::{error, fmt}; +use util::RwLock; use consensus::{self, VerifySortOrder}; use core::hash::Hashed; @@ -197,7 +198,7 @@ impl TxKernel { pub fn verify(&self) -> Result<(), secp::Error> { let msg = Message::from_slice(&kernel_sig_msg(self.fee, self.lock_height))?; let secp = static_secp_instance(); - let secp = secp.lock().unwrap(); + let secp = secp.lock(); let sig = &self.excess_sig; // Verify aggsig directly in libsecp let pubkey = &self.excess.to_pubkey(&secp)?; @@ -553,7 +554,7 @@ impl TransactionBody { // Find all the outputs that have not had their rangeproofs verified. let outputs = { - let mut verifier = verifier.write().unwrap(); + let mut verifier = verifier.write(); verifier.filter_rangeproof_unverified(&self.outputs) }; @@ -570,7 +571,7 @@ impl TransactionBody { // Find all the kernels that have not yet been verified. let kernels = { - let mut verifier = verifier.write().unwrap(); + let mut verifier = verifier.write(); verifier.filter_kernel_sig_unverified(&self.kernels) }; @@ -583,7 +584,7 @@ impl TransactionBody { // Cache the successful verification results for the new outputs and kernels. { - let mut verifier = verifier.write().unwrap(); + let mut verifier = verifier.write(); verifier.add_rangeproof_verified(outputs); verifier.add_kernel_sig_verified(kernels); } @@ -911,7 +912,7 @@ pub fn deaggregate(mk_tx: Transaction, txs: Vec) -> Result Result<(), secp::Error> { let secp = static_secp_instance(); - let secp = secp.lock().unwrap(); + let secp = secp.lock(); match secp.verify_bullet_proof(self.commit, self.proof, None) { Ok(_) => Ok(()), Err(e) => Err(e), @@ -1105,7 +1106,7 @@ impl Output { proofs: &Vec, ) -> Result<(), secp::Error> { let secp = static_secp_instance(); - let secp = secp.lock().unwrap(); + let secp = secp.lock(); match secp.verify_bullet_proof_multi(commits.clone(), proofs.clone(), None) { Ok(_) => Ok(()), Err(e) => Err(e), diff --git a/core/src/global.rs b/core/src/global.rs index bb1e6baa..dc0c9a0a 100644 --- a/core/src/global.rs +++ b/core/src/global.rs @@ -26,7 +26,7 @@ use pow::{self, CuckatooContext, EdgeType, PoWContext}; /// code wherever mining is needed. This should allow for /// different sets of parameters for different purposes, /// e.g. CI, User testing, production values -use std::sync::RwLock; +use util::RwLock; /// Define these here, as they should be developer-set, not really tweakable /// by users @@ -125,7 +125,7 @@ lazy_static!{ /// Set the mining mode pub fn set_mining_mode(mode: ChainTypes) { - let mut param_ref = CHAIN_TYPE.write().unwrap(); + let mut param_ref = CHAIN_TYPE.write(); *param_ref = mode; } @@ -149,7 +149,7 @@ pub fn pow_type() -> PoWContextTypes { /// The minimum acceptable edge_bits pub fn min_edge_bits() -> u8 { - let param_ref = CHAIN_TYPE.read().unwrap(); + let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => AUTOMATED_TESTING_MIN_EDGE_BITS, ChainTypes::UserTesting => USER_TESTING_MIN_EDGE_BITS, @@ -162,7 +162,7 @@ pub fn min_edge_bits() -> u8 { /// while the min_edge_bits can be changed on a soft fork, changing /// base_edge_bits is a hard fork. pub fn base_edge_bits() -> u8 { - let param_ref = CHAIN_TYPE.read().unwrap(); + let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => AUTOMATED_TESTING_MIN_EDGE_BITS, ChainTypes::UserTesting => USER_TESTING_MIN_EDGE_BITS, @@ -173,7 +173,7 @@ pub fn base_edge_bits() -> u8 { /// The proofsize pub fn proofsize() -> usize { - let param_ref = CHAIN_TYPE.read().unwrap(); + let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => AUTOMATED_TESTING_PROOF_SIZE, ChainTypes::UserTesting => USER_TESTING_PROOF_SIZE, @@ -183,7 +183,7 @@ pub fn proofsize() -> usize { /// Coinbase maturity for coinbases to be spent pub fn coinbase_maturity() -> u64 { - let param_ref = CHAIN_TYPE.read().unwrap(); + let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => AUTOMATED_TESTING_COINBASE_MATURITY, ChainTypes::UserTesting => USER_TESTING_COINBASE_MATURITY, @@ -193,7 +193,7 @@ pub fn coinbase_maturity() -> u64 { /// Initial mining difficulty pub fn initial_block_difficulty() -> u64 { - let param_ref = CHAIN_TYPE.read().unwrap(); + let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => TESTING_INITIAL_DIFFICULTY, ChainTypes::UserTesting => TESTING_INITIAL_DIFFICULTY, @@ -206,7 +206,7 @@ pub fn initial_block_difficulty() -> u64 { } /// Initial mining secondary scale pub fn initial_graph_weight() -> u32 { - let param_ref = CHAIN_TYPE.read().unwrap(); + let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => TESTING_INITIAL_GRAPH_WEIGHT, ChainTypes::UserTesting => TESTING_INITIAL_GRAPH_WEIGHT, @@ -220,7 +220,7 @@ pub fn initial_graph_weight() -> u32 { /// Horizon at which we can cut-through and do full local pruning pub fn cut_through_horizon() -> u32 { - let param_ref = CHAIN_TYPE.read().unwrap(); + let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => TESTING_CUT_THROUGH_HORIZON, ChainTypes::UserTesting => TESTING_CUT_THROUGH_HORIZON, @@ -230,19 +230,19 @@ pub fn cut_through_horizon() -> u32 { /// Are we in automated testing mode? pub fn is_automated_testing_mode() -> bool { - let param_ref = CHAIN_TYPE.read().unwrap(); + let param_ref = CHAIN_TYPE.read(); ChainTypes::AutomatedTesting == *param_ref } /// Are we in user testing mode? pub fn is_user_testing_mode() -> bool { - let param_ref = CHAIN_TYPE.read().unwrap(); + let param_ref = CHAIN_TYPE.read(); ChainTypes::UserTesting == *param_ref } /// Are we in production mode (a live public network)? pub fn is_production_mode() -> bool { - let param_ref = CHAIN_TYPE.read().unwrap(); + let param_ref = CHAIN_TYPE.read(); ChainTypes::Testnet1 == *param_ref || ChainTypes::Testnet2 == *param_ref || ChainTypes::Testnet3 == *param_ref @@ -255,7 +255,7 @@ pub fn is_production_mode() -> bool { /// as the genesis block POW solution turns out to be the same for every new /// block chain at the moment pub fn get_genesis_nonce() -> u64 { - let param_ref = CHAIN_TYPE.read().unwrap(); + let param_ref = CHAIN_TYPE.read(); match *param_ref { // won't make a difference ChainTypes::AutomatedTesting => 0, diff --git a/core/tests/block.rs b/core/tests/block.rs index 108aec1e..2e2e891d 100644 --- a/core/tests/block.rs +++ b/core/tests/block.rs @@ -18,8 +18,9 @@ extern crate grin_keychain as keychain; extern crate grin_util as util; extern crate grin_wallet as wallet; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use std::time::Instant; +use util::RwLock; pub mod common; diff --git a/core/tests/core.rs b/core/tests/core.rs index 17aa2f0d..0f891662 100644 --- a/core/tests/core.rs +++ b/core/tests/core.rs @@ -18,7 +18,8 @@ extern crate grin_keychain as keychain; extern crate grin_util as util; extern crate grin_wallet as wallet; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; pub mod common; @@ -350,7 +351,7 @@ fn blind_tx() { let Output { proof, .. } = btx.outputs()[0]; let secp = static_secp_instance(); - let secp = secp.lock().unwrap(); + let secp = secp.lock(); let info = secp.range_proof_info(proof); assert!(info.min == 0); diff --git a/core/tests/verifier_cache.rs b/core/tests/verifier_cache.rs index 948fb7de..ff8d237a 100644 --- a/core/tests/verifier_cache.rs +++ b/core/tests/verifier_cache.rs @@ -18,7 +18,8 @@ extern crate grin_keychain as keychain; extern crate grin_util as util; extern crate grin_wallet as wallet; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; pub mod common; @@ -48,20 +49,20 @@ fn test_verifier_cache_rangeproofs() { // Check our output is not verified according to the cache. { - let mut cache = cache.write().unwrap(); + let mut cache = cache.write(); let unverified = cache.filter_rangeproof_unverified(&vec![out]); assert_eq!(unverified, vec![out]); } // Add our output to the cache. { - let mut cache = cache.write().unwrap(); + let mut cache = cache.write(); cache.add_rangeproof_verified(vec![out]); } // Check it shows as verified according to the cache. { - let mut cache = cache.write().unwrap(); + let mut cache = cache.write(); let unverified = cache.filter_rangeproof_unverified(&vec![out]); assert_eq!(unverified, vec![]); } diff --git a/keychain/src/types.rs b/keychain/src/types.rs index b9c13197..4fbfa72b 100644 --- a/keychain/src/types.rs +++ b/keychain/src/types.rs @@ -244,7 +244,7 @@ impl Add for BlindingFactor { // fn add(self, other: BlindingFactor) -> Self::Output { let secp = static_secp_instance(); - let secp = secp.lock().unwrap(); + let secp = secp.lock(); let keys = vec![self, other] .into_iter() .filter(|x| *x != BlindingFactor::zero()) diff --git a/p2p/src/conn.rs b/p2p/src/conn.rs index cbe6e938..a0608b65 100644 --- a/p2p/src/conn.rs +++ b/p2p/src/conn.rs @@ -24,8 +24,9 @@ use std::fs::File; use std::io::{self, Read, Write}; use std::mem::size_of; use std::net::TcpStream; -use std::sync::{mpsc, Arc, RwLock}; +use std::sync::{mpsc, Arc}; use std::{cmp, thread, time}; +use util::RwLock; use core::ser; use msg::{read_body, read_exact, read_header, write_all, write_to_buf, MsgHeader, Type}; @@ -168,9 +169,8 @@ impl Tracker { self.send_channel.try_send(buf)?; // Increase sent bytes counter - if let Ok(mut sent_bytes) = self.sent_bytes.write() { - *sent_bytes += buf_len as u64; - } + let mut sent_bytes = self.sent_bytes.write(); + *sent_bytes += buf_len as u64; Ok(()) } @@ -241,7 +241,8 @@ fn poll( ); // Increase received bytes counter - if let Ok(mut received_bytes) = received_bytes.write() { + { + let mut received_bytes = received_bytes.write(); let header_size = size_of::() as u64; *received_bytes += header_size + msg.header.msg_len; } diff --git a/p2p/src/handshake.rs b/p2p/src/handshake.rs index c384356b..54cb0743 100644 --- a/p2p/src/handshake.rs +++ b/p2p/src/handshake.rs @@ -14,7 +14,8 @@ use std::collections::VecDeque; use std::net::{SocketAddr, TcpStream}; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use chrono::prelude::*; use rand::{thread_rng, Rng}; @@ -146,7 +147,7 @@ impl Handshake { }); } else { // check the nonce to see if we are trying to connect to ourselves - let nonces = self.nonces.read().unwrap(); + let nonces = self.nonces.read(); if nonces.contains(&hand.nonce) { return Err(Error::PeerWithSelf); } @@ -195,7 +196,7 @@ impl Handshake { fn next_nonce(&self) -> u64 { let nonce = thread_rng().gen(); - let mut nonces = self.nonces.write().unwrap(); + let mut nonces = self.nonces.write(); nonces.push_back(nonce); if nonces.len() >= NONCES_CAP { nonces.pop_front(); diff --git a/p2p/src/peer.rs b/p2p/src/peer.rs index da1fabd9..d6e4b7e6 100644 --- a/p2p/src/peer.rs +++ b/p2p/src/peer.rs @@ -14,7 +14,8 @@ use std::fs::File; use std::net::{SocketAddr, TcpStream}; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use chrono::prelude::{DateTime, Utc}; use conn; @@ -137,12 +138,12 @@ impl Peer { /// Whether this peer has been banned. pub fn is_banned(&self) -> bool { - State::Banned == *self.state.read().unwrap() + State::Banned == *self.state.read() } /// Whether this peer is stuck on sync. pub fn is_stuck(&self) -> (bool, Difficulty) { - let peer_live_info = self.info.live_info.read().unwrap(); + let peer_live_info = self.info.live_info.read(); let now = Utc::now().timestamp_millis(); // if last updated difficulty is 2 hours ago, we're sure this peer is a stuck node. if now > peer_live_info.stuck_detector.timestamp_millis() + global::STUCK_PEER_KICK_TIME { @@ -155,9 +156,8 @@ impl Peer { /// Number of bytes sent to the peer pub fn sent_bytes(&self) -> Option { if let Some(ref tracker) = self.connection { - if let Ok(sent_bytes) = tracker.sent_bytes.read() { - return Some(*sent_bytes); - } + let sent_bytes = tracker.sent_bytes.read(); + return Some(*sent_bytes); } None } @@ -165,16 +165,15 @@ impl Peer { /// Number of bytes received from the peer pub fn received_bytes(&self) -> Option { if let Some(ref tracker) = self.connection { - if let Ok(received_bytes) = tracker.received_bytes.read() { - return Some(*received_bytes); - } + let received_bytes = tracker.received_bytes.read(); + return Some(*received_bytes); } None } /// Set this peer status to banned pub fn set_banned(&self) { - *self.state.write().unwrap() = State::Banned; + *self.state.write() = State::Banned; } /// Send a ping to the remote peer, providing our local difficulty and @@ -369,7 +368,7 @@ impl Peer { match self.connection.as_ref().unwrap().error_channel.try_recv() { Ok(Error::Serialization(e)) => { let need_stop = { - let mut state = self.state.write().unwrap(); + let mut state = self.state.write(); if State::Banned != *state { *state = State::Disconnected; true @@ -388,7 +387,7 @@ impl Peer { } Ok(e) => { let need_stop = { - let mut state = self.state.write().unwrap(); + let mut state = self.state.write(); if State::Disconnected != *state { *state = State::Disconnected; true @@ -403,7 +402,7 @@ impl Peer { false } Err(_) => { - let state = self.state.read().unwrap(); + let state = self.state.read(); State::Connected == *state } } @@ -427,14 +426,14 @@ impl TrackingAdapter { } fn has(&self, hash: Hash) -> bool { - let known = self.known.read().unwrap(); + let known = self.known.read(); // may become too slow, an ordered set (by timestamp for eviction) may // end up being a better choice known.contains(&hash) } fn push(&self, hash: Hash) { - let mut known = self.known.write().unwrap(); + let mut known = self.known.write(); if known.len() > MAX_TRACK_SIZE { known.truncate(MAX_TRACK_SIZE); } diff --git a/p2p/src/peers.rs b/p2p/src/peers.rs index 5dde96c5..f1c39171 100644 --- a/p2p/src/peers.rs +++ b/p2p/src/peers.rs @@ -15,7 +15,8 @@ use std::collections::HashMap; use std::fs::File; use std::net::SocketAddr; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use rand::{thread_rng, Rng}; @@ -74,7 +75,7 @@ impl Peers { self.save_peer(&peer_data)?; { - let mut peers = self.peers.write().unwrap(); + let mut peers = self.peers.write(); peers.insert(addr, peer.clone()); } Ok(()) @@ -88,10 +89,9 @@ impl Peers { Some(peer) => { // Clear the map and add new relay let dandelion_relay = &self.dandelion_relay; - dandelion_relay.write().unwrap().clear(); + dandelion_relay.write().clear(); dandelion_relay .write() - .unwrap() .insert(Utc::now().timestamp(), peer.clone()); debug!( LOGGER, @@ -104,11 +104,11 @@ impl Peers { // Get the dandelion relay pub fn get_dandelion_relay(&self) -> HashMap> { - self.dandelion_relay.read().unwrap().clone() + self.dandelion_relay.read().clone() } pub fn is_known(&self, addr: &SocketAddr) -> bool { - self.peers.read().unwrap().contains_key(addr) + self.peers.read().contains_key(addr) } /// Get vec of peers we are currently connected to. @@ -116,7 +116,6 @@ impl Peers { let mut res = self .peers .read() - .unwrap() .values() .filter(|p| p.is_connected()) .cloned() @@ -136,14 +135,13 @@ impl Peers { /// Get a peer we're connected to by address. pub fn get_connected_peer(&self, addr: &SocketAddr) -> Option> { - self.peers.read().unwrap().get(addr).map(|p| p.clone()) + self.peers.read().get(addr).map(|p| p.clone()) } /// Number of peers we're currently connected to. pub fn peer_count(&self) -> u32 { self.peers .read() - .unwrap() .values() .filter(|x| x.is_connected()) .count() as u32 @@ -370,7 +368,7 @@ impl Peers { /// Ping all our connected peers. Always automatically expects a pong back /// or disconnects. This acts as a liveness test. pub fn check_all(&self, total_difficulty: Difficulty, height: u64) { - let peers_map = self.peers.read().unwrap(); + let peers_map = self.peers.read(); for p in peers_map.values() { if p.is_connected() { let _ = p.send_ping(total_difficulty, height); @@ -417,7 +415,7 @@ impl Peers { let mut rm = vec![]; // build a list of peers to be cleaned up - for peer in self.peers.read().unwrap().values() { + for peer in self.peers.read().values() { if peer.is_banned() { debug!(LOGGER, "clean_peers {:?}, peer banned", peer.info.addr); rm.push(peer.clone()); @@ -437,7 +435,7 @@ impl Peers { // now clean up peer map based on the list to remove { - let mut peers = self.peers.write().unwrap(); + let mut peers = self.peers.write(); for p in rm { peers.remove(&p.info.addr); } @@ -463,13 +461,13 @@ impl Peers { // now remove them taking a short-lived write lock each time // maybe better to take write lock once and remove them all? for x in addrs.iter().take(excess_count) { - let mut peers = self.peers.write().unwrap(); + let mut peers = self.peers.write(); peers.remove(x); } } pub fn stop(&self) { - let mut peers = self.peers.write().unwrap(); + let mut peers = self.peers.write(); for (_, peer) in peers.drain() { peer.stop(); } diff --git a/p2p/src/types.rs b/p2p/src/types.rs index f7e94d17..84d307a0 100644 --- a/p2p/src/types.rs +++ b/p2p/src/types.rs @@ -17,7 +17,8 @@ use std::fs::File; use std::io; use std::net::{IpAddr, SocketAddr}; use std::sync::mpsc; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use chrono::prelude::*; @@ -258,23 +259,23 @@ pub struct PeerInfo { impl PeerInfo { /// The current total_difficulty of the peer. pub fn total_difficulty(&self) -> Difficulty { - self.live_info.read().unwrap().total_difficulty + self.live_info.read().total_difficulty } /// The current height of the peer. pub fn height(&self) -> u64 { - self.live_info.read().unwrap().height + self.live_info.read().height } /// Time of last_seen for this peer (via ping/pong). pub fn last_seen(&self) -> DateTime { - self.live_info.read().unwrap().last_seen + self.live_info.read().last_seen } /// Update the total_difficulty, height and last_seen of the peer. /// Takes a write lock on the live_info. pub fn update(&self, height: u64, total_difficulty: Difficulty) { - let mut live_info = self.live_info.write().unwrap(); + let mut live_info = self.live_info.write(); if total_difficulty != live_info.total_difficulty { live_info.stuck_detector = Utc::now(); } diff --git a/pool/src/pool.rs b/pool/src/pool.rs index c320216c..0d021256 100644 --- a/pool/src/pool.rs +++ b/pool/src/pool.rs @@ -16,7 +16,8 @@ //! Used for both the txpool and stempool layers in the pool. use std::collections::{HashMap, HashSet}; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use core::consensus; use core::core::hash::{Hash, Hashed}; diff --git a/pool/src/transaction_pool.rs b/pool/src/transaction_pool.rs index 218e0294..899acab4 100644 --- a/pool/src/transaction_pool.rs +++ b/pool/src/transaction_pool.rs @@ -17,7 +17,8 @@ //! resulting tx pool can be added to the current chain state to produce a //! valid chain state. -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use chrono::prelude::Utc; diff --git a/pool/tests/block_building.rs b/pool/tests/block_building.rs index 4ffc54cd..5f464c72 100644 --- a/pool/tests/block_building.rs +++ b/pool/tests/block_building.rs @@ -25,7 +25,8 @@ extern crate rand; pub mod common; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use core::core::verifier_cache::LruVerifierCache; use core::core::{Block, BlockHeader, Transaction}; @@ -80,7 +81,7 @@ fn test_transaction_pool_block_building() { let child_tx_2 = test_transaction(&keychain, vec![38], vec![32]); { - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); // Add the three root txs to the pool. write_pool @@ -105,7 +106,7 @@ fn test_transaction_pool_block_building() { } let txs = { - let read_pool = pool.read().unwrap(); + let read_pool = pool.read(); read_pool.prepare_mineable_transactions().unwrap() }; // children should have been aggregated into parents @@ -123,7 +124,7 @@ fn test_transaction_pool_block_building() { // Now reconcile the transaction pool with the new block // and check the resulting contents of the pool are what we expect. { - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); write_pool.reconcile_block(&block).unwrap(); assert_eq!(write_pool.total_size(), 0); diff --git a/pool/tests/block_reconciliation.rs b/pool/tests/block_reconciliation.rs index e204efa5..6d85ffeb 100644 --- a/pool/tests/block_reconciliation.rs +++ b/pool/tests/block_reconciliation.rs @@ -25,7 +25,8 @@ extern crate rand; pub mod common; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use core::core::{Block, BlockHeader}; @@ -127,7 +128,7 @@ fn test_transaction_pool_block_reconciliation() { // First we add the above transactions to the pool. // All should be accepted. { - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); assert_eq!(write_pool.total_size(), 0); for tx in &txs_to_add { @@ -165,13 +166,13 @@ fn test_transaction_pool_block_reconciliation() { // Check the pool still contains everything we expect at this point. { - let write_pool = pool.write().unwrap(); + let write_pool = pool.write(); assert_eq!(write_pool.total_size(), txs_to_add.len()); } // And reconcile the pool with this latest block. { - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); write_pool.reconcile_block(&block).unwrap(); assert_eq!(write_pool.total_size(), 4); diff --git a/pool/tests/coinbase_maturity.rs b/pool/tests/coinbase_maturity.rs index 5edba639..3085674c 100644 --- a/pool/tests/coinbase_maturity.rs +++ b/pool/tests/coinbase_maturity.rs @@ -25,7 +25,8 @@ extern crate rand; pub mod common; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use common::*; use core::core::hash::Hash; @@ -83,7 +84,7 @@ fn test_coinbase_maturity() { let pool = RwLock::new(test_setup(chain, verifier_cache)); { - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); let tx = test_transaction(&keychain, vec![50], vec![49]); match write_pool.add_to_pool(test_source(), tx.clone(), true, &BlockHeader::default()) { Err(PoolError::ImmatureCoinbase) => {} diff --git a/pool/tests/common/mod.rs b/pool/tests/common/mod.rs index 01f07954..36f7fc0d 100644 --- a/pool/tests/common/mod.rs +++ b/pool/tests/common/mod.rs @@ -28,7 +28,8 @@ extern crate rand; use std::collections::HashSet; use std::fs; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use core::core::hash::{Hash, Hashed}; use core::core::verifier_cache::VerifierCache; @@ -98,7 +99,7 @@ impl ChainAdapter { batch.commit().unwrap(); { - let mut utxo = self.utxo.write().unwrap(); + let mut utxo = self.utxo.write(); for x in block.inputs() { utxo.remove(&x.commitment()); } @@ -129,7 +130,7 @@ impl BlockChain for ChainAdapter { } fn validate_tx(&self, tx: &Transaction) -> Result<(), pool::PoolError> { - let utxo = self.utxo.read().unwrap(); + let utxo = self.utxo.read(); for x in tx.outputs() { if utxo.contains(&x.commitment()) { diff --git a/pool/tests/transaction_pool.rs b/pool/tests/transaction_pool.rs index eced1590..e8a803c6 100644 --- a/pool/tests/transaction_pool.rs +++ b/pool/tests/transaction_pool.rs @@ -25,7 +25,8 @@ extern crate rand; pub mod common; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use common::*; use core::core::verifier_cache::LruVerifierCache; @@ -72,7 +73,7 @@ fn test_the_transaction_pool() { // Add this tx to the pool (stem=false, direct to txpool). { - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); write_pool .add_to_pool(test_source(), initial_tx, false, &header) .unwrap(); @@ -86,7 +87,7 @@ fn test_the_transaction_pool() { // Take a write lock and add a couple of tx entries to the pool. { - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); // Check we have a single initial tx in the pool. assert_eq!(write_pool.total_size(), 1); @@ -110,7 +111,7 @@ fn test_the_transaction_pool() { // This will fail during tx aggregation due to duplicate outputs and duplicate // kernels. { - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); assert!( write_pool .add_to_pool(test_source(), tx1.clone(), true, &header) @@ -122,7 +123,7 @@ fn test_the_transaction_pool() { // tx). { let tx1a = test_transaction(&keychain, vec![500, 600], vec![499, 599]); - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); assert!( write_pool .add_to_pool(test_source(), tx1a, true, &header) @@ -133,7 +134,7 @@ fn test_the_transaction_pool() { // Test adding a tx attempting to spend a non-existent output. { let bad_tx = test_transaction(&keychain, vec![10_001], vec![10_000]); - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); assert!( write_pool .add_to_pool(test_source(), bad_tx, true, &header) @@ -147,7 +148,7 @@ fn test_the_transaction_pool() { // to be immediately stolen via a "replay" tx. { let tx = test_transaction(&keychain, vec![900], vec![498]); - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); assert!( write_pool .add_to_pool(test_source(), tx, true, &header) @@ -157,7 +158,7 @@ fn test_the_transaction_pool() { // Confirm the tx pool correctly identifies an invalid tx (already spent). { - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); let tx3 = test_transaction(&keychain, vec![500], vec![497]); assert!( write_pool @@ -171,7 +172,7 @@ fn test_the_transaction_pool() { // Check we can take some entries from the stempool and "fluff" them into the // txpool. This also exercises multi-kernel txs. { - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); let agg_tx = write_pool .stempool .aggregate_transaction() @@ -189,7 +190,7 @@ fn test_the_transaction_pool() { // We will do this be adding a new tx to the pool // that is a superset of a tx already in the pool. { - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); let tx4 = test_transaction(&keychain, vec![800], vec![799]); // tx1 and tx2 are already in the txpool (in aggregated form) @@ -210,7 +211,7 @@ fn test_the_transaction_pool() { // Check we cannot "double spend" an output spent in a previous block. // We use the initial coinbase output here for convenience. { - let mut write_pool = pool.write().unwrap(); + let mut write_pool = pool.write(); let double_spend_tx = { test_transaction_spending_coinbase(&keychain, &header, vec![1000]) }; diff --git a/servers/src/common/adapters.rs b/servers/src/common/adapters.rs index 4b4998a3..251f1e09 100644 --- a/servers/src/common/adapters.rs +++ b/servers/src/common/adapters.rs @@ -17,9 +17,10 @@ use std::fs::File; use std::net::SocketAddr; -use std::sync::{Arc, RwLock, Weak}; +use std::sync::{Arc, Weak}; use std::thread; use std::time::Instant; +use util::RwLock; use chain::{self, ChainAdapter, Options}; use chrono::prelude::{DateTime, Utc}; @@ -82,7 +83,7 @@ impl p2p::ChainAdapter for NetToChainAdapter { ); let res = { - let mut tx_pool = self.tx_pool.write().unwrap(); + let mut tx_pool = self.tx_pool.write(); tx_pool.add_to_pool(source, tx, stem, &header) }; @@ -139,7 +140,7 @@ impl p2p::ChainAdapter for NetToChainAdapter { } let (txs, missing_short_ids) = { - let tx_pool = self.tx_pool.read().unwrap(); + let tx_pool = self.tx_pool.read(); tx_pool.retrieve_transactions(cb.hash(), cb.nonce, cb.kern_ids()) }; @@ -640,7 +641,7 @@ impl ChainAdapter for ChainToPoolAndNetAdapter { debug!(LOGGER, "adapter: block_accepted: {:?}", b.hash()); - if let Err(e) = self.tx_pool.write().unwrap().reconcile_block(b) { + if let Err(e) = self.tx_pool.write().reconcile_block(b) { error!( LOGGER, "Pool could not update itself at block {}: {:?}", diff --git a/servers/src/common/stats.rs b/servers/src/common/stats.rs index 13afd316..e3f8c880 100644 --- a/servers/src/common/stats.rs +++ b/servers/src/common/stats.rs @@ -16,8 +16,9 @@ //! to collect information about server status use std::sync::atomic::AtomicBool; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use std::time::SystemTime; +use util::RwLock; use core::pow::Difficulty; diff --git a/servers/src/common/types.rs b/servers/src/common/types.rs index 50d44610..bba9bada 100644 --- a/servers/src/common/types.rs +++ b/servers/src/common/types.rs @@ -14,7 +14,8 @@ //! Server types use std::convert::From; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use api; use chain; @@ -297,12 +298,12 @@ impl SyncState { /// Whether the current state matches any active syncing operation. /// Note: This includes our "initial" state. pub fn is_syncing(&self) -> bool { - *self.current.read().unwrap() != SyncStatus::NoSync + *self.current.read() != SyncStatus::NoSync } /// Current syncing status pub fn status(&self) -> SyncStatus { - *self.current.read().unwrap() + *self.current.read() } /// Update the syncing status @@ -311,7 +312,7 @@ impl SyncState { return; } - let mut status = self.current.write().unwrap(); + let mut status = self.current.write(); debug!( LOGGER, @@ -324,7 +325,7 @@ impl SyncState { /// Update txhashset downloading progress pub fn update_txhashset_download(&self, new_status: SyncStatus) -> bool { if let SyncStatus::TxHashsetDownload { .. } = new_status { - let mut status = self.current.write().unwrap(); + let mut status = self.current.write(); *status = new_status; true } else { @@ -334,7 +335,7 @@ impl SyncState { /// Communicate sync error pub fn set_sync_error(&self, error: Error) { - *self.sync_error.write().unwrap() = Some(error); + *self.sync_error.write() = Some(error); } /// Get sync error @@ -344,7 +345,7 @@ impl SyncState { /// Clear sync error pub fn clear_sync_error(&self) { - *self.sync_error.write().unwrap() = None; + *self.sync_error.write() = None; } } @@ -354,7 +355,7 @@ impl chain::TxHashsetWriteStatus for SyncState { } fn on_validation(&self, vkernels: u64, vkernel_total: u64, vrproofs: u64, vrproof_total: u64) { - let mut status = self.current.write().unwrap(); + let mut status = self.current.write(); match *status { SyncStatus::TxHashsetValidation { kernels, diff --git a/servers/src/grin/dandelion_monitor.rs b/servers/src/grin/dandelion_monitor.rs index f4cd4a7c..ff30ae3f 100644 --- a/servers/src/grin/dandelion_monitor.rs +++ b/servers/src/grin/dandelion_monitor.rs @@ -15,9 +15,10 @@ use chrono::prelude::Utc; use rand::{thread_rng, Rng}; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use std::thread; use std::time::Duration; +use util::RwLock; use core::core::hash::Hashed; use core::core::transaction; @@ -86,7 +87,7 @@ fn process_stem_phase( tx_pool: Arc>, verifier_cache: Arc>, ) -> Result<(), PoolError> { - let mut tx_pool = tx_pool.write().unwrap(); + let mut tx_pool = tx_pool.write(); let header = tx_pool.chain_head()?; @@ -133,7 +134,7 @@ fn process_fluff_phase( tx_pool: Arc>, verifier_cache: Arc>, ) -> Result<(), PoolError> { - let mut tx_pool = tx_pool.write().unwrap(); + let mut tx_pool = tx_pool.write(); let header = tx_pool.chain_head()?; @@ -172,7 +173,7 @@ fn process_fresh_entries( dandelion_config: DandelionConfig, tx_pool: Arc>, ) -> Result<(), PoolError> { - let mut tx_pool = tx_pool.write().unwrap(); + let mut tx_pool = tx_pool.write(); let mut rng = thread_rng(); @@ -212,7 +213,7 @@ fn process_expired_entries( let mut expired_entries = vec![]; { - let tx_pool = tx_pool.read().unwrap(); + let tx_pool = tx_pool.read(); for entry in tx_pool .stempool .entries @@ -236,7 +237,7 @@ fn process_expired_entries( ); { - let mut tx_pool = tx_pool.write().unwrap(); + let mut tx_pool = tx_pool.write(); let header = tx_pool.chain_head()?; for entry in expired_entries { diff --git a/servers/src/grin/server.rs b/servers/src/grin/server.rs index eed82a87..5be8a151 100644 --- a/servers/src/grin/server.rs +++ b/servers/src/grin/server.rs @@ -18,8 +18,9 @@ use std::net::SocketAddr; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use std::{thread, time}; +use util::RwLock; use api; use chain; @@ -79,7 +80,7 @@ impl Server { if let Some(s) = enable_stratum_server { if s { { - let mut stratum_stats = serv.state_info.stratum_stats.write().unwrap(); + let mut stratum_stats = serv.state_info.stratum_stats.write(); stratum_stats.is_enabled = true; } serv.start_stratum_server(c.clone()); @@ -388,7 +389,7 @@ impl Server { /// other /// consumers pub fn get_server_stats(&self) -> Result { - let stratum_stats = self.state_info.stratum_stats.read().unwrap().clone(); + let stratum_stats = self.state_info.stratum_stats.read().clone(); let awaiting_peers = self.state_info.awaiting_peers.load(Ordering::Relaxed); // Fill out stats on our current difficulty calculation diff --git a/servers/src/grin/sync/state_sync.rs b/servers/src/grin/sync/state_sync.rs index a1e38cc5..96779ce6 100644 --- a/servers/src/grin/sync/state_sync.rs +++ b/servers/src/grin/sync/state_sync.rs @@ -76,7 +76,7 @@ impl StateSync { // check sync error { let clone = self.sync_state.sync_error(); - if let Some(ref sync_error) = *clone.read().unwrap() { + if let Some(ref sync_error) = *clone.read() { error!( LOGGER, "fast_sync: error = {:?}. restart fast sync", sync_error diff --git a/servers/src/mining/mine_block.rs b/servers/src/mining/mine_block.rs index b9823451..9f996a40 100644 --- a/servers/src/mining/mine_block.rs +++ b/servers/src/mining/mine_block.rs @@ -17,9 +17,10 @@ use chrono::prelude::{DateTime, NaiveDateTime, Utc}; use rand::{thread_rng, Rng}; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; use std::thread; use std::time::Duration; +use util::RwLock; use chain; use common::types::Error; @@ -110,11 +111,7 @@ fn build_block( // extract current transaction from the pool // TODO - we have a lot of unwrap() going on in this fn... - let txs = tx_pool - .read() - .unwrap() - .prepare_mineable_transactions() - .unwrap(); + let txs = tx_pool.read().prepare_mineable_transactions().unwrap(); // build the coinbase and the block itself let fees = txs.iter().map(|tx| tx.fee()).sum(); diff --git a/servers/src/mining/stratumserver.rs b/servers/src/mining/stratumserver.rs index 2979765b..e84d16ea 100644 --- a/servers/src/mining/stratumserver.rs +++ b/servers/src/mining/stratumserver.rs @@ -21,9 +21,10 @@ use serde_json::Value; use std::error::Error; use std::io::{BufRead, ErrorKind, Write}; use std::net::{TcpListener, TcpStream}; -use std::sync::{Arc, Mutex, RwLock}; +use std::sync::Arc; use std::time::{Duration, SystemTime}; use std::{cmp, thread}; +use util::{Mutex, RwLock}; use chain; use common::stats::{StratumStats, WorkerStats}; @@ -122,14 +123,14 @@ fn accept_workers( .set_nonblocking(true) .expect("set_nonblocking call failed"); let mut worker = Worker::new(worker_id.to_string(), BufStream::new(stream)); - workers.lock().unwrap().push(worker); + workers.lock().push(worker); // stats for this worker (worker stat objects are added and updated but never // removed) let mut worker_stats = WorkerStats::default(); worker_stats.is_connected = true; worker_stats.id = worker_id.to_string(); worker_stats.pow_difficulty = 1; // XXX TODO - let mut stratum_stats = stratum_stats.write().unwrap(); + let mut stratum_stats = stratum_stats.write(); stratum_stats.worker_stats.push(worker_stats); worker_id = worker_id + 1; } @@ -285,7 +286,7 @@ impl StratumServer { // Handle an RPC request message from the worker(s) fn handle_rpc_requests(&mut self, stratum_stats: &mut Arc>) { - let mut workers_l = self.workers.lock().unwrap(); + let mut workers_l = self.workers.lock(); for num in 0..workers_l.len() { match workers_l[num].read_message() { Some(the_message) => { @@ -306,7 +307,7 @@ impl StratumServer { } }; - let mut stratum_stats = stratum_stats.write().unwrap(); + let mut stratum_stats = stratum_stats.write(); let worker_stats_id = stratum_stats .worker_stats .iter() @@ -582,7 +583,7 @@ impl StratumServer { // Purge dead/sick workers - remove all workers marked in error state fn clean_workers(&mut self, stratum_stats: &mut Arc>) -> usize { let mut start = 0; - let mut workers_l = self.workers.lock().unwrap(); + let mut workers_l = self.workers.lock(); loop { for num in start..workers_l.len() { if workers_l[num].error == true { @@ -593,7 +594,7 @@ impl StratumServer { workers_l[num].id; ); // Update worker stats - let mut stratum_stats = stratum_stats.write().unwrap(); + let mut stratum_stats = stratum_stats.write(); let worker_stats_id = stratum_stats .worker_stats .iter() @@ -607,7 +608,7 @@ impl StratumServer { start = num + 1; } if start >= workers_l.len() { - let mut stratum_stats = stratum_stats.write().unwrap(); + let mut stratum_stats = stratum_stats.write(); stratum_stats.num_workers = workers_l.len(); return stratum_stats.num_workers; } @@ -639,7 +640,7 @@ impl StratumServer { // Push the new block to all connected clients // NOTE: We do not give a unique nonce (should we?) so miners need // to choose one for themselves - let mut workers_l = self.workers.lock().unwrap(); + let mut workers_l = self.workers.lock(); for num in 0..workers_l.len() { workers_l[num].write_message(job_request_json.clone()); } @@ -691,7 +692,7 @@ impl StratumServer { // We have started { - let mut stratum_stats = stratum_stats.write().unwrap(); + let mut stratum_stats = stratum_stats.write(); stratum_stats.is_running = true; stratum_stats.edge_bits = edge_bits as u16; } @@ -753,7 +754,7 @@ impl StratumServer { deadline = Utc::now().timestamp() + attempt_time_per_block as i64; { - let mut stratum_stats = stratum_stats.write().unwrap(); + let mut stratum_stats = stratum_stats.write(); stratum_stats.block_height = new_block.header.height; stratum_stats.network_difficulty = self.current_difficulty; } diff --git a/servers/src/mining/test_miner.rs b/servers/src/mining/test_miner.rs index f328dc48..fa5253e4 100644 --- a/servers/src/mining/test_miner.rs +++ b/servers/src/mining/test_miner.rs @@ -19,7 +19,8 @@ use chrono::prelude::Utc; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use chain; use common::types::StratumServerConfig; diff --git a/servers/tests/api.rs b/servers/tests/api.rs index aa12317b..8490115c 100644 --- a/servers/tests/api.rs +++ b/servers/tests/api.rs @@ -26,8 +26,9 @@ extern crate grin_wallet as wallet; mod framework; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::{thread, time}; +use util::Mutex; use core::global::{self, ChainTypes}; @@ -52,7 +53,7 @@ fn simple_server_wallet() { )); let _ = thread::spawn(move || { - let mut w = coinbase_wallet.lock().unwrap(); + let mut w = coinbase_wallet.lock(); w.run_wallet(0); }); diff --git a/servers/tests/dandelion.rs b/servers/tests/dandelion.rs index 1e24a404..08606f12 100644 --- a/servers/tests/dandelion.rs +++ b/servers/tests/dandelion.rs @@ -27,8 +27,9 @@ extern crate grin_wallet as wallet; mod framework; use framework::{LocalServerContainer, LocalServerContainerConfig}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::{thread, time}; +use util::Mutex; use util::LOGGER; @@ -56,12 +57,12 @@ fn test_dandelion_timeout() { let coinbase_wallet = Arc::new(Mutex::new( LocalServerContainer::new(coinbase_config).unwrap(), )); - let coinbase_wallet_config = { coinbase_wallet.lock().unwrap().wallet_config.clone() }; + let coinbase_wallet_config = { coinbase_wallet.lock().wallet_config.clone() }; let coinbase_seed = LocalServerContainer::get_wallet_seed(&coinbase_wallet_config); let _ = thread::spawn(move || { - let mut w = coinbase_wallet.lock().unwrap(); + let mut w = coinbase_wallet.lock(); w.run_wallet(0); }); @@ -71,12 +72,12 @@ fn test_dandelion_timeout() { recp_config.wallet_port = 20002; let target_wallet = Arc::new(Mutex::new(LocalServerContainer::new(recp_config).unwrap())); let target_wallet_cloned = target_wallet.clone(); - let recp_wallet_config = { target_wallet.lock().unwrap().wallet_config.clone() }; + let recp_wallet_config = { target_wallet.lock().wallet_config.clone() }; let recp_seed = LocalServerContainer::get_wallet_seed(&recp_wallet_config); //Start up a second wallet, to receive let _ = thread::spawn(move || { - let mut w = target_wallet_cloned.lock().unwrap(); + let mut w = target_wallet_cloned.lock(); w.run_wallet(0); }); diff --git a/servers/tests/framework/mod.rs b/servers/tests/framework/mod.rs index 28c0f206..0df8f417 100644 --- a/servers/tests/framework/mod.rs +++ b/servers/tests/framework/mod.rs @@ -25,8 +25,9 @@ extern crate blake2_rfc as blake2; use std::default::Default; use std::ops::Deref; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::{fs, thread, time}; +use util::Mutex; use framework::keychain::Keychain; use wallet::{HTTPWalletClient, LMDBBackend, WalletConfig}; @@ -532,7 +533,7 @@ impl LocalServerContainerPool { thread::sleep(time::Duration::from_millis(2000)); } let server_ref = s.run_server(run_length); - return_container_ref.lock().unwrap().push(server_ref); + return_container_ref.lock().push(server_ref); }); // Not a big fan of sleeping hack here, but there appears to be a // concurrency issue when creating files in rocksdb that causes @@ -575,7 +576,7 @@ impl LocalServerContainerPool { } pub fn stop_all_servers(servers: Arc>>) { - let locked_servs = servers.lock().unwrap(); + let locked_servs = servers.lock(); for s in locked_servs.deref() { s.stop(); } diff --git a/servers/tests/simulnet.rs b/servers/tests/simulnet.rs index 09ac4710..fb274ae7 100644 --- a/servers/tests/simulnet.rs +++ b/servers/tests/simulnet.rs @@ -27,8 +27,9 @@ mod framework; use std::default::Default; use std::sync::atomic::AtomicBool; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::{thread, time}; +use util::Mutex; use core::core::hash::Hashed; use core::global::{self, ChainTypes}; diff --git a/servers/tests/wallet.rs b/servers/tests/wallet.rs index 884bbc17..47a622e2 100644 --- a/servers/tests/wallet.rs +++ b/servers/tests/wallet.rs @@ -27,8 +27,9 @@ extern crate grin_wallet as wallet; mod framework; use framework::{LocalServerContainer, LocalServerContainerConfig}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::{thread, time}; +use util::Mutex; use util::LOGGER; @@ -55,11 +56,11 @@ fn basic_wallet_transactions() { let coinbase_wallet = Arc::new(Mutex::new( LocalServerContainer::new(coinbase_config).unwrap(), )); - let coinbase_wallet_config = { coinbase_wallet.lock().unwrap().wallet_config.clone() }; + let coinbase_wallet_config = { coinbase_wallet.lock().wallet_config.clone() }; let coinbase_seed = LocalServerContainer::get_wallet_seed(&coinbase_wallet_config); let _ = thread::spawn(move || { - let mut w = coinbase_wallet.lock().unwrap(); + let mut w = coinbase_wallet.lock(); w.run_wallet(0); }); @@ -69,11 +70,11 @@ fn basic_wallet_transactions() { recp_config.wallet_port = 20002; let target_wallet = Arc::new(Mutex::new(LocalServerContainer::new(recp_config).unwrap())); let target_wallet_cloned = target_wallet.clone(); - let recp_wallet_config = { target_wallet.lock().unwrap().wallet_config.clone() }; + let recp_wallet_config = { target_wallet.lock().wallet_config.clone() }; let recp_seed = LocalServerContainer::get_wallet_seed(&recp_wallet_config); //Start up a second wallet, to receive let _ = thread::spawn(move || { - let mut w = target_wallet_cloned.lock().unwrap(); + let mut w = target_wallet_cloned.lock(); w.run_wallet(0); }); diff --git a/src/bin/cmd/wallet.rs b/src/bin/cmd/wallet.rs index b4512df2..7196b484 100644 --- a/src/bin/cmd/wallet.rs +++ b/src/bin/cmd/wallet.rs @@ -18,9 +18,10 @@ use std::io::Read; use std::path::PathBuf; /// Wallet commands processing use std::process::exit; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::time::Duration; use std::{process, thread}; +use util::Mutex; use clap::ArgMatches; diff --git a/util/Cargo.toml b/util/Cargo.toml index 878f68a6..87f10005 100644 --- a/util/Cargo.toml +++ b/util/Cargo.toml @@ -18,6 +18,7 @@ slog-term = "~2.4" slog-async = "~2.3" walkdir = "2" zip = "0.4" +parking_lot = {version = "0.6"} [dependencies.secp256k1zkp] git = "https://github.com/mimblewimble/rust-secp256k1-zkp" diff --git a/util/src/lib.rs b/util/src/lib.rs index d8d72178..7f4323a1 100644 --- a/util/src/lib.rs +++ b/util/src/lib.rs @@ -38,6 +38,10 @@ extern crate serde; extern crate serde_derive; extern crate walkdir; extern crate zip as zip_rs; +// Re-export so only has to be included once +extern crate parking_lot; +pub use parking_lot::Mutex; +pub use parking_lot::RwLock; // Re-export so only has to be included once pub extern crate secp256k1zkp as secp; @@ -59,7 +63,7 @@ pub mod macros; use byteorder::{BigEndian, ByteOrder}; #[allow(unused_imports)] use std::ops::Deref; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; mod hex; pub use hex::*; @@ -93,7 +97,7 @@ where /// Initializes the OneTime, should only be called once after construction. /// Will panic (via assert) if called more than once. pub fn init(&self, value: T) { - let mut inner = self.inner.write().unwrap(); + let mut inner = self.inner.write(); assert!(inner.is_none()); *inner = Some(value); } @@ -101,7 +105,7 @@ where /// Borrows the OneTime, should only be called after initialization. /// Will panic (via expect) if called before initialization. pub fn borrow(&self) -> T { - let inner = self.inner.read().unwrap(); + let inner = self.inner.read(); inner .clone() .expect("Cannot borrow one_time before initialization.") diff --git a/util/src/logger.rs b/util/src/logger.rs index 1afaf05d..a36d1f93 100644 --- a/util/src/logger.rs +++ b/util/src/logger.rs @@ -17,7 +17,7 @@ use slog_async; use slog_term; use std::fs::OpenOptions; use std::ops::Deref; -use std::sync::Mutex; +use Mutex; use backtrace::Backtrace; use std::{panic, thread}; @@ -46,12 +46,12 @@ lazy_static! { /// And a static reference to the logger itself, accessible from all crates pub static ref LOGGER: Logger = { - let was_init = WAS_INIT.lock().unwrap().clone(); - let config = LOGGING_CONFIG.lock().unwrap(); + let was_init = WAS_INIT.lock().clone(); + let config = LOGGING_CONFIG.lock(); let slog_level_stdout = convert_log_level(&config.stdout_log_level); let slog_level_file = convert_log_level(&config.file_log_level); if config.tui_running.is_some() && config.tui_running.unwrap() { - let mut tui_running_ref = TUI_RUNNING.lock().unwrap(); + let mut tui_running_ref = TUI_RUNNING.lock(); *tui_running_ref = true; } @@ -91,10 +91,10 @@ lazy_static! { /// Initialize the logger with the given configuration pub fn init_logger(config: Option) { if let Some(c) = config { - let mut config_ref = LOGGING_CONFIG.lock().unwrap(); + let mut config_ref = LOGGING_CONFIG.lock(); *config_ref = c.clone(); // Logger configuration successfully injected into LOGGING_CONFIG... - let mut was_init_ref = WAS_INIT.lock().unwrap(); + let mut was_init_ref = WAS_INIT.lock(); *was_init_ref = true; // .. allow logging, having ensured that paths etc are immutable } @@ -103,14 +103,14 @@ pub fn init_logger(config: Option) { /// Initializes the logger for unit and integration tests pub fn init_test_logger() { - let mut was_init_ref = WAS_INIT.lock().unwrap(); + let mut was_init_ref = WAS_INIT.lock(); if *was_init_ref.deref() { return; } let mut logger = LoggingConfig::default(); logger.log_to_file = false; logger.stdout_log_level = LogLevel::Debug; - let mut config_ref = LOGGING_CONFIG.lock().unwrap(); + let mut config_ref = LOGGING_CONFIG.lock(); *config_ref = logger; *was_init_ref = true; } @@ -149,7 +149,7 @@ fn send_panic_to_log() { ), } //also print to stderr - let tui_running = TUI_RUNNING.lock().unwrap().clone(); + let tui_running = TUI_RUNNING.lock().clone(); if !tui_running { eprintln!( "Thread '{}' panicked with message:\n\"{}\"\nSee grin.log for further details.", diff --git a/util/src/secp_static.rs b/util/src/secp_static.rs index 43832acb..5aec24f6 100644 --- a/util/src/secp_static.rs +++ b/util/src/secp_static.rs @@ -17,7 +17,8 @@ use rand::thread_rng; use secp; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +use Mutex; lazy_static! { /// Static reference to secp instance @@ -28,7 +29,7 @@ lazy_static! { /// Returns the static instance, but calls randomize on it as well /// (Recommended to avoid side channel attacks pub fn static_secp_instance() -> Arc> { - let mut secp_inst = SECP256K1.lock().unwrap(); + let mut secp_inst = SECP256K1.lock(); secp_inst.randomize(&mut thread_rng()); SECP256K1.clone() } diff --git a/wallet/src/libtx/build.rs b/wallet/src/libtx/build.rs index 041ee25c..fec353d7 100644 --- a/wallet/src/libtx/build.rs +++ b/wallet/src/libtx/build.rs @@ -255,7 +255,8 @@ where // Just a simple test, most exhaustive tests in the core mod.rs. #[cfg(test)] mod test { - use std::sync::{Arc, RwLock}; + use std::sync::Arc; + use util::RwLock; use super::*; use core::core::verifier_cache::{LruVerifierCache, VerifierCache}; diff --git a/wallet/src/libtx/reward.rs b/wallet/src/libtx/reward.rs index cf3c7572..2fa0ab0f 100644 --- a/wallet/src/libtx/reward.rs +++ b/wallet/src/libtx/reward.rs @@ -47,7 +47,7 @@ where }; let secp = static_secp_instance(); - let secp = secp.lock().unwrap(); + let secp = secp.lock(); let over_commit = secp.commit_value(reward(fees))?; let out_commit = output.commitment(); let excess = secp.commit_sum(vec![out_commit], vec![over_commit])?; diff --git a/wallet/src/libtx/slate.rs b/wallet/src/libtx/slate.rs index 92494fd2..fd6dea7c 100644 --- a/wallet/src/libtx/slate.rs +++ b/wallet/src/libtx/slate.rs @@ -16,7 +16,8 @@ //! around during an interactive wallet exchange use rand::thread_rng; -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use uuid::Uuid; use core::core::committed::Committed; diff --git a/wallet/src/libwallet/api.rs b/wallet/src/libwallet/api.rs index 56d6c7a8..87ebd8a5 100644 --- a/wallet/src/libwallet/api.rs +++ b/wallet/src/libwallet/api.rs @@ -20,7 +20,8 @@ use std::fs::File; use std::io::{Read, Write}; use std::marker::PhantomData; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +use util::Mutex; use serde_json as json; @@ -77,7 +78,7 @@ where refresh_from_node: bool, tx_id: Option, ) -> Result<(bool, Vec<(OutputData, pedersen::Commitment)>), Error> { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let parent_key_id = w.parent_key_id(); @@ -102,7 +103,7 @@ where refresh_from_node: bool, tx_id: Option, ) -> Result<(bool, Vec), Error> { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let parent_key_id = w.parent_key_id(); @@ -125,7 +126,7 @@ where &mut self, refresh_from_node: bool, ) -> Result<(bool, WalletInfo), Error> { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let parent_key_id = w.parent_key_id(); @@ -143,13 +144,13 @@ where /// Return list of existing account -> Path mappings pub fn accounts(&mut self) -> Result, Error> { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); keys::accounts(&mut **w) } /// Create a new account path pub fn new_account_path(&mut self, label: &str) -> Result { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); keys::new_acct_path(&mut **w, label) } @@ -163,7 +164,7 @@ where num_change_outputs: usize, selection_strategy_is_use_all: bool, ) -> Result { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let parent_key_id = w.parent_key_id(); @@ -216,7 +217,7 @@ where num_change_outputs: usize, selection_strategy_is_use_all: bool, ) -> Result { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let parent_key_id = w.parent_key_id(); @@ -254,7 +255,7 @@ where /// Builds the complete transaction and sends it to a grin node for /// propagation. pub fn finalize_tx(&mut self, slate: &mut Slate) -> Result<(), Error> { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let context = w.get_private_context(slate.id.as_bytes())?; @@ -275,7 +276,7 @@ where /// with the transaction used when a transaction is created but never /// posted pub fn cancel_tx(&mut self, tx_id: u32) -> Result<(), Error> { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let parent_key_id = w.parent_key_id(); if !self.update_outputs(&mut w) { @@ -295,7 +296,7 @@ where minimum_confirmations: u64, max_outputs: usize, ) -> Result<(), Error> { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let parent_key_id = w.parent_key_id(); let tx_burn = tx::issue_burn_tx( @@ -315,7 +316,7 @@ where pub fn post_tx(&self, slate: &Slate, fluff: bool) -> Result<(), Error> { let tx_hex = util::to_hex(ser::ser_vec(&slate.tx).unwrap()); let client = { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.client().clone() }; let res = client.post_tx(&TxWrapper { tx_hex: tx_hex }, fluff); @@ -341,7 +342,7 @@ where dest: &str, ) -> Result { let (confirmed, tx_hex) = { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let parent_key_id = w.parent_key_id(); let res = tx::retrieve_tx_hex(&mut **w, &parent_key_id, tx_id)?; @@ -375,7 +376,7 @@ where pub fn post_stored_tx(&self, tx_id: u32, fluff: bool) -> Result<(), Error> { let client; let (confirmed, tx_hex) = { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let parent_key_id = w.parent_key_id(); client = w.client().clone(); @@ -418,7 +419,7 @@ where /// Attempt to restore contents of wallet pub fn restore(&mut self) -> Result<(), Error> { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let res = w.restore(); w.close()?; @@ -428,7 +429,7 @@ where /// Retrieve current height from node pub fn node_height(&mut self) -> Result<(u64, bool), Error> { let res = { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; w.client().get_chain_height() }; @@ -487,7 +488,7 @@ where /// Build a new (potential) coinbase transaction in the wallet pub fn build_coinbase(&mut self, block_fees: &BlockFees) -> Result { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let res = updater::build_coinbase(&mut **w, block_fees); w.close()?; @@ -503,7 +504,7 @@ where pub_tx_f.read_to_string(&mut content)?; let mut slate: Slate = json::from_str(&content).map_err(|_| ErrorKind::Format)?; - let mut wallet = self.wallet.lock().unwrap(); + let mut wallet = self.wallet.lock(); wallet.open_with_credentials()?; let parent_key_id = wallet.parent_key_id(); @@ -533,7 +534,7 @@ where /// Receive a transaction from a sender pub fn receive_tx(&mut self, slate: &mut Slate) -> Result<(), Error> { - let mut w = self.wallet.lock().unwrap(); + let mut w = self.wallet.lock(); w.open_with_credentials()?; let parent_key_id = w.parent_key_id(); let res = tx::receive_tx(&mut **w, slate, &parent_key_id); diff --git a/wallet/src/libwallet/controller.rs b/wallet/src/libwallet/controller.rs index f3ce438b..0a5d3858 100644 --- a/wallet/src/libwallet/controller.rs +++ b/wallet/src/libwallet/controller.rs @@ -33,9 +33,10 @@ use serde_json; use std::collections::HashMap; use std::marker::PhantomData; use std::net::SocketAddr; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use url::form_urlencoded; use util::secp::pedersen; +use util::Mutex; use util::{to_base64, LOGGER}; /// Instantiate wallet Owner API for a single-use (command line) call diff --git a/wallet/src/libwallet/internal/tx.rs b/wallet/src/libwallet/internal/tx.rs index 5bf105e7..b570aa28 100644 --- a/wallet/src/libwallet/internal/tx.rs +++ b/wallet/src/libwallet/internal/tx.rs @@ -14,7 +14,8 @@ //! Transaction building functions -use std::sync::{Arc, RwLock}; +use std::sync::Arc; +use util::RwLock; use core::core::verifier_cache::LruVerifierCache; use core::core::Transaction; diff --git a/wallet/tests/accounts.rs b/wallet/tests/accounts.rs index 57c50ca6..e7a6dfe2 100644 --- a/wallet/tests/accounts.rs +++ b/wallet/tests/accounts.rs @@ -108,20 +108,20 @@ fn accounts_test_impl(test_dir: &str) -> Result<(), libwallet::Error> { // Default wallet 2 to listen on that account { - let mut w = wallet2.lock().unwrap(); + let mut w = wallet2.lock(); w.set_parent_key_id_by_name("listener_account")?; } // Mine into two different accounts in the same wallet { - let mut w = wallet1.lock().unwrap(); + let mut w = wallet1.lock(); w.set_parent_key_id_by_name("account1")?; assert_eq!(w.parent_key_id(), ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); } let _ = common::award_blocks_to_wallet(&chain, wallet1.clone(), 7); { - let mut w = wallet1.lock().unwrap(); + let mut w = wallet1.lock(); w.set_parent_key_id_by_name("account2")?; assert_eq!(w.parent_key_id(), ExtKeychain::derive_key_id(2, 2, 0, 0, 0)); } @@ -141,7 +141,7 @@ fn accounts_test_impl(test_dir: &str) -> Result<(), libwallet::Error> { })?; // now check second account { - let mut w = wallet1.lock().unwrap(); + let mut w = wallet1.lock(); w.set_parent_key_id_by_name("account1")?; } wallet::controller::owner_single_use(wallet1.clone(), |api| { @@ -161,7 +161,7 @@ fn accounts_test_impl(test_dir: &str) -> Result<(), libwallet::Error> { // should be nothing in default account { - let mut w = wallet1.lock().unwrap(); + let mut w = wallet1.lock(); w.set_parent_key_id_by_name("default")?; } wallet::controller::owner_single_use(wallet1.clone(), |api| { @@ -180,7 +180,7 @@ fn accounts_test_impl(test_dir: &str) -> Result<(), libwallet::Error> { // Send a tx to another wallet { - let mut w = wallet1.lock().unwrap(); + let mut w = wallet1.lock(); w.set_parent_key_id_by_name("account1")?; } @@ -208,7 +208,7 @@ fn accounts_test_impl(test_dir: &str) -> Result<(), libwallet::Error> { // other account should be untouched { - let mut w = wallet1.lock().unwrap(); + let mut w = wallet1.lock(); w.set_parent_key_id_by_name("account2")?; } wallet::controller::owner_single_use(wallet1.clone(), |api| { @@ -233,7 +233,7 @@ fn accounts_test_impl(test_dir: &str) -> Result<(), libwallet::Error> { })?; // Default account on wallet 2 should be untouched { - let mut w = wallet2.lock().unwrap(); + let mut w = wallet2.lock(); w.set_parent_key_id_by_name("default")?; } wallet::controller::owner_single_use(wallet2.clone(), |api| { diff --git a/wallet/tests/common/mod.rs b/wallet/tests/common/mod.rs index 07cf75ff..8b39a898 100644 --- a/wallet/tests/common/mod.rs +++ b/wallet/tests/common/mod.rs @@ -22,7 +22,8 @@ extern crate grin_wallet as wallet; extern crate serde_json; use chrono::Duration; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +use util::Mutex; use chain::Chain; use core::core::{OutputFeatures, OutputIdentifier, Transaction}; @@ -38,13 +39,13 @@ use util::secp::pedersen; pub mod testclient; /// types of backends tests should iterate through -#[derive(Clone)] -pub enum BackendType { - /// File - FileBackend, - /// LMDB - LMDBBackend, -} +//#[derive(Clone)] +//pub enum BackendType { +// /// File +// FileBackend, +// /// LMDB +// LMDBBackend, +//} /// Get an output from the chain locally and present it back as an API output fn get_output_local(chain: &chain::Chain, commit: &pedersen::Commitment) -> Option { diff --git a/wallet/tests/common/testclient.rs b/wallet/tests/common/testclient.rs index 55458292..499b4f90 100644 --- a/wallet/tests/common/testclient.rs +++ b/wallet/tests/common/testclient.rs @@ -20,9 +20,10 @@ use std::collections::HashMap; use std::marker::PhantomData; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{channel, Receiver, Sender}; -use std::sync::{Arc, Mutex, RwLock}; +use std::sync::Arc; use std::thread; use std::time::Duration; +use util::{Mutex, RwLock}; use common::api; use common::serde_json; @@ -306,7 +307,7 @@ impl LocalWalletClient { /// get an instance of the send queue for other senders pub fn get_send_instance(&self) -> Sender { - self.tx.lock().unwrap().clone() + self.tx.lock().clone() } } @@ -338,11 +339,11 @@ impl WalletClient for LocalWalletClient { body: serde_json::to_string(slate).unwrap(), }; { - let p = self.proxy_tx.lock().unwrap(); + let p = self.proxy_tx.lock(); p.send(m) .context(libwallet::ErrorKind::ClientCallback("Send TX Slate"))?; } - let r = self.rx.lock().unwrap(); + let r = self.rx.lock(); let m = r.recv().unwrap(); trace!(LOGGER, "Received send_tx_slate response: {:?}", m.clone()); Ok( @@ -362,11 +363,11 @@ impl WalletClient for LocalWalletClient { body: serde_json::to_string(tx).unwrap(), }; { - let p = self.proxy_tx.lock().unwrap(); + let p = self.proxy_tx.lock(); p.send(m) .context(libwallet::ErrorKind::ClientCallback("post_tx send"))?; } - let r = self.rx.lock().unwrap(); + let r = self.rx.lock(); let m = r.recv().unwrap(); trace!(LOGGER, "Received post_tx response: {:?}", m.clone()); Ok(()) @@ -381,12 +382,12 @@ impl WalletClient for LocalWalletClient { body: "".to_owned(), }; { - let p = self.proxy_tx.lock().unwrap(); + let p = self.proxy_tx.lock(); p.send(m).context(libwallet::ErrorKind::ClientCallback( "Get chain height send", ))?; } - let r = self.rx.lock().unwrap(); + let r = self.rx.lock(); let m = r.recv().unwrap(); trace!( LOGGER, @@ -417,12 +418,12 @@ impl WalletClient for LocalWalletClient { body: query_str, }; { - let p = self.proxy_tx.lock().unwrap(); + let p = self.proxy_tx.lock(); p.send(m).context(libwallet::ErrorKind::ClientCallback( "Get outputs from node send", ))?; } - let r = self.rx.lock().unwrap(); + let r = self.rx.lock(); let m = r.recv().unwrap(); let outputs: Vec = serde_json::from_str(&m.body).unwrap(); let mut api_outputs: HashMap = HashMap::new(); @@ -456,13 +457,13 @@ impl WalletClient for LocalWalletClient { body: query_str, }; { - let p = self.proxy_tx.lock().unwrap(); + let p = self.proxy_tx.lock(); p.send(m).context(libwallet::ErrorKind::ClientCallback( "Get outputs from node by PMMR index send", ))?; } - let r = self.rx.lock().unwrap(); + let r = self.rx.lock(); let m = r.recv().unwrap(); let o: api::OutputListing = serde_json::from_str(&m.body).unwrap(); diff --git a/wallet/tests/restore.rs b/wallet/tests/restore.rs index bd6b9c2b..059c7c87 100644 --- a/wallet/tests/restore.rs +++ b/wallet/tests/restore.rs @@ -109,12 +109,12 @@ fn compare_wallet_restore( ); { - let mut w = wallet_source.lock().unwrap(); + let mut w = wallet_source.lock(); w.set_parent_key_id(account_path.clone()); } { - let mut w = wallet_dest.lock().unwrap(); + let mut w = wallet_dest.lock(); w.set_parent_key_id(account_path.clone()); } @@ -206,7 +206,7 @@ fn setup_restore(test_dir: &str) -> Result<(), libwallet::Error> { // Default wallet 2 to listen on that account { - let mut w = wallet2.lock().unwrap(); + let mut w = wallet2.lock(); w.set_parent_key_id_by_name("account1")?; } @@ -281,7 +281,7 @@ fn setup_restore(test_dir: &str) -> Result<(), libwallet::Error> { // Another listener account on wallet 2 { - let mut w = wallet2.lock().unwrap(); + let mut w = wallet2.lock(); w.set_parent_key_id_by_name("account2")?; } From 0852b0c4cf394e91092e338ea2be2f4209c9dce2 Mon Sep 17 00:00:00 2001 From: Quentin Le Sceller Date: Sun, 21 Oct 2018 22:26:35 +0200 Subject: [PATCH 04/24] Expose post_tx in OwnerAPI Post (#1795) * Add POST post_tx in wallet_owner_api * Add docs for post_tx --- doc/api/wallet_foreign_api.md | 4 -- doc/api/wallet_owner_api.md | 93 +++++++++++++++++++++++++----- wallet/src/libwallet/controller.rs | 30 ++++++++++ 3 files changed, 107 insertions(+), 20 deletions(-) diff --git a/doc/api/wallet_foreign_api.md b/doc/api/wallet_foreign_api.md index f37a90cb..634349d2 100644 --- a/doc/api/wallet_foreign_api.md +++ b/doc/api/wallet_foreign_api.md @@ -170,10 +170,6 @@ Receives a transaction, modifying the slate accordingly (which can then be sent * **Sample Call:** ```javascript - var coinbase_data = { - fees: 0, - height: 123456 - } $.ajax({ url: "/v1/wallet/foreign/build_coinbase", dataType: "json", diff --git a/doc/api/wallet_owner_api.md b/doc/api/wallet_owner_api.md index 3538a82d..85dd7abe 100644 --- a/doc/api/wallet_owner_api.md +++ b/doc/api/wallet_owner_api.md @@ -390,10 +390,6 @@ Send a transaction either directly by http or file (then display the slate) * **Sample Call:** ```javascript - var coinbase_data = { - fees: 0, - height: 123456 - } $.ajax({ url: "/v1/wallet/owner/issue_send_tx", dataType: "json", @@ -506,10 +502,6 @@ Builds the complete transaction and sends it to a grin node for propagation. * **Sample Call:** ```javascript - var coinbase_data = { - fees: 0, - height: 123456 - } $.ajax({ url: "/v1/wallet/owner/finalize_tx", dataType: "json", @@ -555,10 +547,6 @@ Roll back a transaction and all associated outputs with a given transaction id T * **Sample Call:** ```javascript - var coinbase_data = { - fees: 0, - height: 123456 - } $.ajax({ url: "/v1/wallet/owner/cancel_tx?id=3", dataType: "json", @@ -569,6 +557,83 @@ Roll back a transaction and all associated outputs with a given transaction id T }); ``` +### POST Post Tx + +Push new transaction to the connected node transaction pool. Add `?fluff` at the end of the URL to bypass Dandelion relay. + +* **URL** + + /v1/wallet/owner/post_tx + +* **Method:** + + `POST` + +* **URL Params** + + None + +* **Data Params** + + **Required:** A transaction slate in JSON. + + | Field | Type | Description | + |:----------------------|:---------|:--------------------------------------------------------------------------| + | num_participants | number | The number of participants intended to take part in this transaction | + | id | number | Unique transaction ID, selected by sender | + | tx | object | The core transaction data (inputs, outputs, kernels and kernel offset) | + | - offset | []number | The kernel "offset" k2, excess is k1G after splitting the key k = k1 + k2 | + | - body | object | The transaction body - inputs/outputs/kernels | + | - - inputs | []object | List of inputs spent by the transaction | + | - - - features | object | The features of the output being spent | + | - - - - bits | number | Representation of the features in bits | + | - - - commit | []number | The commit referencing the output being spent | + | - - outputs | []object | List of outputs the transaction produces | + | - - - features | object | Options for an output's structure or use | + | - - - - bits | number | Representation of the features in bits | + | - - - commit | []number | The homomorphic commitment representing the output amount | + | - - - proof | []number | A proof that the commitment is in the right range | + | - - kernels | []object | List of kernels that make up this transaction (usually a single kernel) | + | - - - features | object | Options for a kernel's structure or use | + | - - - - bits | number | Representation of the features in bits | + | - - - fee | number | Fee originally included in the transaction this proof is for | + | - - - lock_height | number | The max lock_height of all inputs to this transaction | + | - - - excess | []number | Remainder of the sum of all transaction commitments | + | - - - excess_sig | []number | The signature proving the excess is a valid public key (signs the tx fee) | + | amount | number | Base amount (excluding fee) | + | fee | number | Fee amount | + | height | number | Block height for the transaction | + | lock_height | number | Lock height | + | participant_data | object | Participant data | + | - id | number | Id of participant in the transaction. (For now, 0=sender, 1=rec) | + | - public_blind_excess | []number | Public key corresponding to private blinding factor | + | - public_nonce | []number | Public key corresponding to private nonce | + | - part_sig | []number | Public partial signature | + +* **Success Response:** + + * **Code:** 200 + +* **Error Response:** + + * **Code:** 400 + +* **Sample Call:** + + ```javascript + $.ajax({ + url: "/v1/wallet/owner/post_tx", + dataType: "json", + type : "POST", + success : function(r) { + console.log(r); + }, + data: { + file: tx.json + }, + }); + ``` + ### POST Issue Burn Tx Issue a burn TX. @@ -600,10 +665,6 @@ Issue a burn TX. * **Sample Call:** ```javascript - var coinbase_data = { - fees: 0, - height: 123456 - } $.ajax({ url: "/v1/wallet/owner/issue_burn_tx", dataType: "json", diff --git a/wallet/src/libwallet/controller.rs b/wallet/src/libwallet/controller.rs index 0a5d3858..a98f236d 100644 --- a/wallet/src/libwallet/controller.rs +++ b/wallet/src/libwallet/controller.rs @@ -358,6 +358,32 @@ where } } + fn post_tx( + &self, + req: Request, + api: APIOwner, + ) -> Box + Send> { + let params = match req.uri().query() { + Some(query_string) => form_urlencoded::parse(query_string.as_bytes()) + .into_owned() + .fold(HashMap::new(), |mut hm, (k, v)| { + hm.entry(k).or_insert(vec![]).push(v); + hm + }), + None => HashMap::new(), + }; + let fluff = params.get("fluff").is_some(); + Box::new( + parse_body(req).and_then(move |slate| match api.post_tx(&slate, fluff) { + Ok(_) => ok(()), + Err(e) => { + error!(LOGGER, "post_tx: failed with error: {}", e); + err(e) + } + }), + ) + } + fn issue_burn_tx( &self, _req: Request, @@ -392,6 +418,10 @@ where self.cancel_tx(req, api) .and_then(|_| ok(response(StatusCode::OK, ""))), ), + "post_tx" => Box::new( + self.post_tx(req, api) + .and_then(|_| ok(response(StatusCode::OK, ""))), + ), "issue_burn_tx" => Box::new( self.issue_burn_tx(req, api) .and_then(|_| ok(response(StatusCode::OK, ""))), From 1195071f5bd94a501d926aa01acb3d68d41686ce Mon Sep 17 00:00:00 2001 From: eupn <36292692+eupn@users.noreply.github.com> Date: Sun, 21 Oct 2018 23:30:56 +0300 Subject: [PATCH 05/24] Replace logging backend to log4rs and add log rotation (#1789) * Replace logging backend to flexi-logger and add log rotation * Changed flexi_logger to log4rs * Disable logging level filtering in Root logger * Support different logging levels for file and stdout * Don't log messages from modules other than Grin-related * Fix formatting * Place backed up compressed log copies into log file directory * Increase default log file size to 16 MiB * Add comment to config file on log_max_size option --- Cargo.toml | 2 +- api/Cargo.toml | 2 +- api/src/handlers.rs | 12 +- api/src/lib.rs | 2 +- api/src/rest.rs | 10 +- chain/Cargo.toml | 2 +- chain/src/chain.rs | 49 ++---- chain/src/lib.rs | 2 +- chain/src/pipe.rs | 31 ++-- chain/src/txhashset/txhashset.rs | 116 +++++--------- config/src/comments.rs | 12 +- core/Cargo.toml | 2 +- core/src/core/block.rs | 9 +- core/src/core/pmmr/pmmr.rs | 13 +- core/src/core/verifier_cache.rs | 3 - core/src/lib.rs | 2 +- keychain/Cargo.toml | 2 +- keychain/src/lib.rs | 2 +- p2p/Cargo.toml | 2 +- p2p/src/conn.rs | 3 - p2p/src/handshake.rs | 4 +- p2p/src/lib.rs | 2 +- p2p/src/msg.rs | 5 +- p2p/src/peer.rs | 63 +++----- p2p/src/peers.rs | 59 +++---- p2p/src/protocol.rs | 52 +++--- p2p/src/serv.rs | 37 ++--- p2p/src/store.rs | 3 +- pool/Cargo.toml | 2 +- pool/src/lib.rs | 2 +- pool/src/pool.rs | 2 - servers/Cargo.toml | 2 +- servers/src/common/adapters.rs | 97 ++++------- servers/src/common/types.rs | 6 +- servers/src/grin/dandelion_monitor.rs | 48 ++---- servers/src/grin/seed.rs | 33 ++-- servers/src/grin/server.rs | 21 +-- servers/src/grin/sync/body_sync.rs | 7 +- servers/src/grin/sync/header_sync.rs | 13 +- servers/src/grin/sync/state_sync.rs | 18 +-- servers/src/grin/sync/syncer.rs | 5 +- servers/src/lib.rs | 2 +- servers/src/mining/mine_block.rs | 18 +-- servers/src/mining/stratumserver.rs | 66 +++----- servers/src/mining/test_miner.rs | 28 ++-- servers/src/webwallet/server.rs | 7 +- servers/tests/api.rs | 21 +-- servers/tests/dandelion.rs | 6 +- servers/tests/simulnet.rs | 8 +- servers/tests/stratum.rs | 23 ++- servers/tests/wallet.rs | 11 +- src/bin/cmd/server.rs | 15 +- src/bin/cmd/wallet.rs | 46 +++--- src/bin/grin.rs | 14 +- src/bin/tui/ui.rs | 3 +- store/Cargo.toml | 2 +- store/src/leaf_set.rs | 8 +- store/src/lib.rs | 2 +- store/src/pmmr.rs | 10 +- store/src/prune_list.rs | 4 +- store/src/types.rs | 5 +- util/Cargo.toml | 5 +- util/src/lib.rs | 8 +- util/src/logger.rs | 178 ++++++++++++++------- util/src/types.rs | 7 +- wallet/Cargo.toml | 2 +- wallet/src/client.rs | 28 ++-- wallet/src/file_wallet.rs | 17 +- wallet/src/lib.rs | 2 +- wallet/src/libtx/build.rs | 12 +- wallet/src/libtx/reward.rs | 4 +- wallet/src/libtx/slate.rs | 6 +- wallet/src/libwallet/api.rs | 31 ++-- wallet/src/libwallet/controller.rs | 26 +-- wallet/src/libwallet/internal/restore.rs | 16 +- wallet/src/libwallet/internal/selection.rs | 12 +- wallet/src/libwallet/internal/tx.rs | 3 +- wallet/src/libwallet/internal/updater.rs | 13 +- wallet/src/types.rs | 6 +- wallet/tests/accounts.rs | 5 +- wallet/tests/common/testclient.rs | 14 +- wallet/tests/restore.rs | 9 +- wallet/tests/transaction.rs | 17 +- 83 files changed, 582 insertions(+), 897 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 98a50ecc..e28069ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,7 @@ humansize = "1.1.0" daemonize = "0.3" serde = "1" serde_json = "1" -slog = { version = "~2.3", features = ["max_level_trace", "release_max_level_trace"] } +log = "0.4" term = "0.5" grin_api = { path = "./api" } diff --git a/api/Cargo.toml b/api/Cargo.toml index a944eb7a..10cbadce 100644 --- a/api/Cargo.toml +++ b/api/Cargo.toml @@ -15,7 +15,7 @@ ring = "0.13" serde = "1" serde_derive = "1" serde_json = "1" -slog = { version = "~2.3", features = ["max_level_trace", "release_max_level_trace"] } +log = "0.4" tokio = "0.1.7" tokio-core = "0.1.17" tokio-tcp = "0.1" diff --git a/api/src/handlers.rs b/api/src/handlers.rs index 8d4c08df..d684d426 100644 --- a/api/src/handlers.rs +++ b/api/src/handlers.rs @@ -37,7 +37,6 @@ use types::*; use url::form_urlencoded; use util; use util::secp::pedersen::Commitment; -use util::LOGGER; use web::*; // All handlers use `Weak` references instead of `Arc` to avoid cycles that @@ -206,12 +205,8 @@ impl OutputHandler { } debug!( - LOGGER, "outputs_block_batch: {}-{}, {:?}, {:?}", - start_height, - end_height, - commitments, - include_rp, + start_height, end_height, commitments, include_rp, ); let mut return_vec = vec![]; @@ -745,7 +740,6 @@ impl PoolPushHandler { identifier: "?.?.?.?".to_string(), }; info!( - LOGGER, "Pushing transaction {} to pool (inputs: {}, outputs: {}, kernels: {})", tx.hash(), tx.inputs().len(), @@ -759,7 +753,7 @@ impl PoolPushHandler { tx_pool .add_to_pool(source, tx, !fluff, &header) .map_err(|e| { - error!(LOGGER, "update_pool: failed with error: {:?}", e); + error!("update_pool: failed with error: {:?}", e); ErrorKind::Internal(format!("Failed to update pool: {:?}", e)).into() }) }), @@ -808,7 +802,7 @@ pub fn start_rest_apis( router.add_middleware(basic_auth_middleware); } - info!(LOGGER, "Starting HTTP API server at {}.", addr); + info!("Starting HTTP API server at {}.", addr); let socket_addr: SocketAddr = addr.parse().expect("unable to parse socket address"); apis.start(socket_addr, router, tls_config).is_ok() } diff --git a/api/src/lib.rs b/api/src/lib.rs index 5df900aa..cde0399e 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -33,7 +33,7 @@ extern crate serde; extern crate serde_derive; extern crate serde_json; #[macro_use] -extern crate slog; +extern crate log; extern crate futures; extern crate http; extern crate hyper_rustls; diff --git a/api/src/rest.rs b/api/src/rest.rs index f7738d0a..54e7d244 100644 --- a/api/src/rest.rs +++ b/api/src/rest.rs @@ -33,7 +33,6 @@ use std::sync::Arc; use std::{io, thread}; use tokio_rustls::ServerConfigExt; use tokio_tcp; -use util::LOGGER; /// Errors that can be returned by an ApiEndpoint implementation. #[derive(Debug)] @@ -243,13 +242,10 @@ impl ApiServer { // TODO re-enable stop after investigation //let tx = mem::replace(&mut self.shutdown_sender, None).unwrap(); //tx.send(()).expect("Failed to stop API server"); - info!(LOGGER, "API server has been stoped"); + info!("API server has been stoped"); true } else { - error!( - LOGGER, - "Can't stop API server, it's not running or doesn't spport stop operation" - ); + error!("Can't stop API server, it's not running or doesn't spport stop operation"); false } } @@ -263,7 +259,7 @@ impl Handler for LoggingMiddleware { req: Request, mut handlers: Box>, ) -> ResponseFuture { - debug!(LOGGER, "REST call: {} {}", req.method(), req.uri().path()); + debug!("REST call: {} {}", req.method(), req.uri().path()); handlers.next().unwrap().call(req, handlers) } } diff --git a/chain/Cargo.toml b/chain/Cargo.toml index c59bc55c..ff9456ed 100644 --- a/chain/Cargo.toml +++ b/chain/Cargo.toml @@ -12,7 +12,7 @@ lmdb-zero = "0.4.4" failure = "0.1" failure_derive = "0.1" croaring = "0.3" -slog = { version = "~2.3", features = ["max_level_trace", "release_max_level_trace"] } +log = "0.4" serde = "1" serde_derive = "1" chrono = "0.4.4" diff --git a/chain/src/chain.rs b/chain/src/chain.rs index e2a144e4..1f637afc 100644 --- a/chain/src/chain.rs +++ b/chain/src/chain.rs @@ -38,7 +38,6 @@ use store; use txhashset; use types::{ChainAdapter, NoStatus, Options, Tip, TxHashSetRoots, TxHashsetWriteStatus}; use util::secp::pedersen::{Commitment, RangeProof}; -use util::LOGGER; /// Orphan pool size is limited by MAX_ORPHAN_SIZE pub const MAX_ORPHAN_SIZE: usize = 200; @@ -184,7 +183,6 @@ impl Chain { let head = store.head()?; debug!( - LOGGER, "Chain init: {} @ {} [{}]", head.total_difficulty.to_num(), head.height, @@ -261,7 +259,6 @@ impl Chain { &self.orphans.add(orphan); debug!( - LOGGER, "process_block: orphan: {:?}, # orphans {}{}", block_hash, self.orphans.len(), @@ -275,7 +272,6 @@ impl Chain { } ErrorKind::Unfit(ref msg) => { debug!( - LOGGER, "Block {} at {} is unfit at this time: {}", b.hash(), b.header.height, @@ -285,7 +281,6 @@ impl Chain { } _ => { info!( - LOGGER, "Rejected block {} at {}: {:?}", b.hash(), b.header.height, @@ -360,7 +355,6 @@ impl Chain { // Is there an orphan in our orphans that we can now process? loop { trace!( - LOGGER, "check_orphans: at {}, # orphans {}", height, self.orphans.len(), @@ -373,7 +367,6 @@ impl Chain { let orphans_len = orphans.len(); for (i, orphan) in orphans.into_iter().enumerate() { debug!( - LOGGER, "check_orphans: get block {} at {}{}", orphan.block.hash(), height, @@ -402,7 +395,6 @@ impl Chain { if initial_height != height { debug!( - LOGGER, "check_orphans: {} blocks accepted since height {}, remaining # orphans {}", height - initial_height, initial_height, @@ -589,7 +581,6 @@ impl Chain { txhashset: &txhashset::TxHashSet, ) -> Result<(), Error> { debug!( - LOGGER, "chain: validate_kernel_history: rewinding and validating kernel history (readonly)" ); @@ -606,8 +597,8 @@ impl Chain { })?; debug!( - LOGGER, - "chain: validate_kernel_history: validated kernel root on {} headers", count, + "chain: validate_kernel_history: validated kernel root on {} headers", + count, ); Ok(()) @@ -682,10 +673,7 @@ impl Chain { self.validate_kernel_history(&header, &txhashset)?; // all good, prepare a new batch and update all the required records - debug!( - LOGGER, - "chain: txhashset_write: rewinding a 2nd time (writeable)" - ); + debug!("chain: txhashset_write: rewinding a 2nd time (writeable)"); let mut batch = self.store.batch()?; @@ -709,10 +697,7 @@ impl Chain { Ok(()) })?; - debug!( - LOGGER, - "chain: txhashset_write: finished validating and rebuilding" - ); + debug!("chain: txhashset_write: finished validating and rebuilding"); status.on_save(); @@ -727,10 +712,7 @@ impl Chain { // Commit all the changes to the db. batch.commit()?; - debug!( - LOGGER, - "chain: txhashset_write: finished committing the batch (head etc.)" - ); + debug!("chain: txhashset_write: finished committing the batch (head etc.)"); // Replace the chain txhashset with the newly built one. { @@ -738,10 +720,7 @@ impl Chain { *txhashset_ref = txhashset; } - debug!( - LOGGER, - "chain: txhashset_write: replaced our txhashset with the new one" - ); + debug!("chain: txhashset_write: replaced our txhashset with the new one"); // Check for any orphan blocks and process them based on the new chain state. self.check_orphans(header.height + 1); @@ -763,14 +742,11 @@ impl Chain { /// therefore be called judiciously. pub fn compact(&self) -> Result<(), Error> { if self.archive_mode { - debug!( - LOGGER, - "Blockchain compaction disabled, node running in archive mode." - ); + debug!("Blockchain compaction disabled, node running in archive mode."); return Ok(()); } - debug!(LOGGER, "Starting blockchain compaction."); + debug!("Starting blockchain compaction."); // Compact the txhashset via the extension. { let mut txhashset = self.txhashset.write(); @@ -785,7 +761,7 @@ impl Chain { // Now check we can still successfully validate the chain state after // compacting, shouldn't be necessary once all of this is well-oiled - debug!(LOGGER, "Validating state after compaction."); + debug!("Validating state after compaction."); self.validate(true)?; // we need to be careful here in testing as 20 blocks is not that long @@ -798,7 +774,6 @@ impl Chain { } debug!( - LOGGER, "Compaction remove blocks older than {}.", head.height - horizon ); @@ -831,7 +806,7 @@ impl Chain { } } batch.commit()?; - debug!(LOGGER, "Compaction removed {} blocks, done.", count); + debug!("Compaction removed {} blocks, done.", count); Ok(()) } @@ -1052,7 +1027,6 @@ fn setup_head( if header.height > 0 && extension.batch.get_block_sums(&header.hash()).is_err() { debug!( - LOGGER, "chain: init: building (missing) block sums for {} @ {}", header.height, header.hash() @@ -1073,7 +1047,6 @@ fn setup_head( } debug!( - LOGGER, "chain: init: rewinding and validating before we start... {} at {}", header.hash(), header.height, @@ -1110,7 +1083,7 @@ fn setup_head( // Save the block_sums to the db for use later. batch.save_block_sums(&genesis.hash(), &BlockSums::default())?; - info!(LOGGER, "chain: init: saved genesis: {:?}", genesis.hash()); + info!("chain: init: saved genesis: {:?}", genesis.hash()); } Err(e) => return Err(ErrorKind::StoreErr(e, "chain init load head".to_owned()))?, }; diff --git a/chain/src/lib.rs b/chain/src/lib.rs index 83fc8faa..82db548f 100644 --- a/chain/src/lib.rs +++ b/chain/src/lib.rs @@ -30,7 +30,7 @@ extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] -extern crate slog; +extern crate log; extern crate chrono; extern crate failure; #[macro_use] diff --git a/chain/src/pipe.rs b/chain/src/pipe.rs index 82e1e143..1eae38b5 100644 --- a/chain/src/pipe.rs +++ b/chain/src/pipe.rs @@ -35,7 +35,6 @@ use grin_store; use store; use txhashset; use types::{Options, Tip}; -use util::LOGGER; /// Contextual information required to process a new block and either reject or /// accept it. @@ -71,7 +70,6 @@ pub fn process_block(b: &Block, ctx: &mut BlockContext) -> Result, E // spend resources reading the full block when its header is invalid debug!( - LOGGER, "pipe: process_block {} at {} with {} inputs, {} outputs, {} kernels", b.hash(), b.header.height, @@ -168,7 +166,6 @@ pub fn process_block(b: &Block, ctx: &mut BlockContext) -> Result, E })?; trace!( - LOGGER, "pipe: process_block: {} at {} is valid, save and append.", b.hash(), b.header.height, @@ -190,7 +187,6 @@ pub fn sync_block_headers( ) -> Result, Error> { if let Some(header) = headers.first() { debug!( - LOGGER, "pipe: sync_block_headers: {} headers from {} at {}", headers.len(), header.hash(), @@ -251,7 +247,6 @@ pub fn sync_block_headers( /// it. pub fn process_block_header(header: &BlockHeader, ctx: &mut BlockContext) -> Result<(), Error> { debug!( - LOGGER, "pipe: process_block_header: {} at {}", header.hash(), header.height, @@ -356,8 +351,8 @@ fn validate_header(header: &BlockHeader, ctx: &mut BlockContext) -> Result<(), E // check version, enforces scheduled hard fork if !consensus::valid_header_version(header.height, header.version) { error!( - LOGGER, - "Invalid block header version received ({}), maybe update Grin?", header.version + "Invalid block header version received ({}), maybe update Grin?", + header.version ); return Err(ErrorKind::InvalidBlockVersion(header.version).into()); } @@ -378,8 +373,8 @@ fn validate_header(header: &BlockHeader, ctx: &mut BlockContext) -> Result<(), E let edge_bits = header.pow.edge_bits(); if !(ctx.pow_verifier)(header, edge_bits).is_ok() { error!( - LOGGER, - "pipe: error validating header with cuckoo edge_bits {}", edge_bits + "pipe: error validating header with cuckoo edge_bits {}", + edge_bits ); return Err(ErrorKind::InvalidPow.into()); } @@ -434,7 +429,6 @@ fn validate_header(header: &BlockHeader, ctx: &mut BlockContext) -> Result<(), E let next_header_info = consensus::next_difficulty(header.height, diff_iter); if target_difficulty != next_header_info.difficulty { info!( - LOGGER, "validate_header: header target difficulty {} != {}", target_difficulty.to_num(), next_header_info.difficulty.to_num() @@ -548,8 +542,8 @@ fn update_head(b: &Block, ctx: &BlockContext) -> Result, Error> { .map_err(|e| ErrorKind::StoreErr(e, "pipe save body".to_owned()))?; debug!( - LOGGER, - "pipe: head updated to {} at {}", tip.last_block_h, tip.height + "pipe: head updated to {} at {}", + tip.last_block_h, tip.height ); Ok(Some(tip)) @@ -569,7 +563,7 @@ fn update_sync_head(bh: &BlockHeader, batch: &mut store::Batch) -> Result<(), Er batch .save_sync_head(&tip) .map_err(|e| ErrorKind::StoreErr(e, "pipe save sync head".to_owned()))?; - debug!(LOGGER, "sync head {} @ {}", bh.hash(), bh.height); + debug!("sync head {} @ {}", bh.hash(), bh.height); Ok(()) } @@ -583,8 +577,8 @@ fn update_header_head(bh: &BlockHeader, ctx: &mut BlockContext) -> Result