From be8d9633e4ac14fa88d92afb6c00b4e78180a410 Mon Sep 17 00:00:00 2001 From: Ignotus Peverell Date: Sun, 4 Mar 2018 00:19:54 +0000 Subject: [PATCH] rustfmt all the things --- api/src/client.rs | 22 +- api/src/handlers.rs | 26 +- api/src/lib.rs | 4 +- api/src/types.rs | 145 +++++---- chain/src/chain.rs | 110 +++---- chain/src/pipe.rs | 133 +++++--- chain/src/store.rs | 29 +- chain/src/sumtree.rs | 152 ++++----- chain/src/types.rs | 53 ++-- chain/tests/data_file_integrity.rs | 47 ++- chain/tests/mine_simple_chain.rs | 98 ++++-- chain/tests/store_indices.rs | 11 +- chain/tests/test_coinbase_maturity.rs | 51 +-- config/src/config.rs | 11 +- config/src/lib.rs | 1 - config/src/types.rs | 3 +- core/benches/sumtree.rs | 4 +- core/src/consensus.rs | 20 +- core/src/core/block.rs | 213 ++++++------- core/src/core/build.rs | 174 ++++++----- core/src/core/hash.rs | 13 +- core/src/core/id.rs | 24 +- core/src/core/mod.rs | 40 ++- core/src/core/pmmr.rs | 217 ++++++------- core/src/core/target.rs | 25 +- core/src/core/transaction.rs | 181 ++++++----- core/src/genesis.rs | 29 +- core/src/global.rs | 42 +-- core/src/ser.rs | 16 +- core/tests/consensus.rs | 86 ++++-- grin/src/adapters.rs | 148 ++++----- grin/src/miner.rs | 56 ++-- grin/src/seed.rs | 21 +- grin/src/server.rs | 40 +-- grin/src/sync.rs | 104 +++---- grin/tests/api.rs | 217 +++++++++---- grin/tests/framework/mod.rs | 156 +++++----- grin/tests/simulnet.rs | 34 +- grin/tests/wallet.rs | 85 +++-- keychain/src/blind.rs | 9 +- keychain/src/extkey.rs | 10 +- keychain/src/keychain.rs | 428 ++++++++++++++------------ keychain/src/lib.rs | 4 +- p2p/src/conn.rs | 112 ++++--- p2p/src/handshake.rs | 44 ++- p2p/src/lib.rs | 6 +- p2p/src/msg.rs | 75 +++-- p2p/src/peer.rs | 137 ++++++--- p2p/src/peers.rs | 28 +- p2p/src/protocol.rs | 71 +++-- p2p/src/serv.rs | 42 ++- p2p/src/store.rs | 5 +- p2p/src/types.rs | 15 +- p2p/tests/peer_handshake.rs | 24 +- pool/src/blockchain.rs | 8 +- pool/src/graph.rs | 30 +- pool/src/pool.rs | 280 ++++++++--------- pool/src/types.rs | 17 +- pow/src/cuckoo.rs | 209 ++----------- pow/src/lib.rs | 50 +-- pow/src/plugin.rs | 28 +- pow/src/types.rs | 2 +- src/bin/client.rs | 8 +- src/bin/grin.rs | 42 +-- store/src/lib.rs | 1 - store/src/pmmr.rs | 61 ++-- store/src/types.rs | 15 +- store/tests/pmmr.rs | 87 +++--- util/src/lib.rs | 6 +- util/src/secp_static.rs | 6 +- util/src/zip.rs | 19 +- util/tests/zip.rs | 6 +- wallet/src/checker.rs | 96 +++--- wallet/src/client.rs | 31 +- wallet/src/handlers.rs | 24 +- wallet/src/info.rs | 25 +- wallet/src/lib.rs | 13 +- wallet/src/outputs.rs | 27 +- wallet/src/receiver.rs | 205 ++++++------ wallet/src/restore.rs | 58 ++-- wallet/src/sender.rs | 138 ++++++--- wallet/src/server.rs | 1 - wallet/src/types.rs | 244 ++++++++------- 83 files changed, 2981 insertions(+), 2607 deletions(-) diff --git a/api/src/client.rs b/api/src/client.rs index 286f7f7fb..e7a17d8f3 100644 --- a/api/src/client.rs +++ b/api/src/client.rs @@ -32,9 +32,8 @@ where { let client = hyper::Client::new(); let res = check_error(client.get(url).send())?; - serde_json::from_reader(res).map_err(|e| { - Error::Internal(format!("Server returned invalid JSON: {}", e)) - }) + serde_json::from_reader(res) + .map_err(|e| Error::Internal(format!("Server returned invalid JSON: {}", e))) } /// Helper function to easily issue a HTTP POST request with the provided JSON @@ -45,9 +44,8 @@ pub fn post<'a, IN>(url: &'a str, input: &IN) -> Result<(), Error> where IN: Serialize, { - let in_json = serde_json::to_string(input).map_err(|e| { - Error::Internal(format!("Could not serialize data to JSON: {}", e)) - })?; + let in_json = serde_json::to_string(input) + .map_err(|e| Error::Internal(format!("Could not serialize data to JSON: {}", e)))?; let client = hyper::Client::new(); let _res = check_error(client.post(url).body(&mut in_json.as_bytes()).send())?; Ok(()) @@ -61,13 +59,17 @@ fn check_error(res: hyper::Result) -> Result { let mut response = res.unwrap(); match response.status.class() { StatusClass::Success => Ok(response), - StatusClass::ServerError => { - Err(Error::Internal(format!("Server error: {}", err_msg(&mut response)))) - } + StatusClass::ServerError => Err(Error::Internal(format!( + "Server error: {}", + err_msg(&mut response) + ))), StatusClass::ClientError => if response.status == StatusCode::NotFound { Err(Error::NotFound) } else { - Err(Error::Argument(format!("Argument error: {}", err_msg(&mut response)))) + Err(Error::Argument(format!( + "Argument error: {}", + err_msg(&mut response) + ))) }, _ => Err(Error::Internal(format!("Unrecognized error."))), } diff --git a/api/src/handlers.rs b/api/src/handlers.rs index e8d579a02..8f0cecbfb 100644 --- a/api/src/handlers.rs +++ b/api/src/handlers.rs @@ -13,7 +13,7 @@ // limitations under the License. use std::io::Read; -use std::sync::{Arc, Weak, RwLock}; +use std::sync::{Arc, RwLock, Weak}; use std::thread; use iron::prelude::*; @@ -24,7 +24,7 @@ use serde::Serialize; use serde_json; use chain; -use core::core::{OutputIdentifier, Transaction, OutputFeatures}; +use core::core::{OutputFeatures, OutputIdentifier, Transaction}; use core::core::hash::{Hash, Hashed}; use core::ser; use pool; @@ -43,7 +43,6 @@ fn w(weak: &Weak) -> Arc { weak.upgrade().unwrap() } - // RESTful index of available api endpoints // GET /v1/ struct IndexHandler { @@ -74,15 +73,16 @@ impl UtxoHandler { // We need the features here to be able to generate the necessary hash // to compare against the hash in the output MMR. - // For now we can just try both (but this probably needs to be part of the api params) + // For now we can just try both (but this probably needs to be part of the api + // params) let outputs = [ OutputIdentifier::new(OutputFeatures::DEFAULT_OUTPUT, &commit), - OutputIdentifier::new(OutputFeatures::COINBASE_OUTPUT, &commit) + OutputIdentifier::new(OutputFeatures::COINBASE_OUTPUT, &commit), ]; for x in outputs.iter() { if let Ok(_) = w(&self.chain).is_unspent(&x) { - return Ok(Utxo::new(&commit)) + return Ok(Utxo::new(&commit)); } } Err(Error::NotFound) @@ -117,16 +117,12 @@ impl UtxoHandler { commitments: Vec, include_proof: bool, ) -> BlockOutputs { - let header = w(&self.chain) - .get_header_by_height(block_height) - .unwrap(); + let header = w(&self.chain).get_header_by_height(block_height).unwrap(); let block = w(&self.chain).get_block(&header.hash()).unwrap(); let outputs = block .outputs .iter() - .filter(|output| { - commitments.is_empty() || commitments.contains(&output.commit) - }) + .filter(|output| commitments.is_empty() || commitments.contains(&output.commit)) .map(|output| { OutputPrintable::from_output(output, w(&self.chain), &block, include_proof) }) @@ -406,11 +402,7 @@ pub struct BlockHandler { impl BlockHandler { fn get_block(&self, h: &Hash) -> Result { let block = w(&self.chain).get_block(h).map_err(|_| Error::NotFound)?; - Ok(BlockPrintable::from_block( - &block, - w(&self.chain), - false, - )) + Ok(BlockPrintable::from_block(&block, w(&self.chain), false)) } fn get_compact_block(&self, h: &Hash) -> Result { diff --git a/api/src/lib.rs b/api/src/lib.rs index 3aec1a205..e18eac7a1 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -14,15 +14,15 @@ extern crate grin_chain as chain; extern crate grin_core as core; -extern crate grin_pool as pool; extern crate grin_p2p as p2p; +extern crate grin_pool as pool; extern crate grin_store as store; extern crate grin_util as util; extern crate hyper; +extern crate iron; #[macro_use] extern crate lazy_static; -extern crate iron; extern crate mount; extern crate regex; #[macro_use] diff --git a/api/src/types.rs b/api/src/types.rs index 0ecfaf70b..cb8ebad19 100644 --- a/api/src/types.rs +++ b/api/src/types.rs @@ -163,7 +163,9 @@ pub struct Utxo { impl Utxo { pub fn new(commit: &pedersen::Commitment) -> Utxo { - Utxo { commit: PrintableCommitment(commit.clone()) } + Utxo { + commit: PrintableCommitment(commit.clone()), + } } } @@ -182,15 +184,19 @@ impl PrintableCommitment { } impl serde::ser::Serialize for PrintableCommitment { - fn serialize(&self, serializer: S) -> Result where - S: serde::ser::Serializer { + fn serialize(&self, serializer: S) -> Result + where + S: serde::ser::Serializer, + { serializer.serialize_str(&util::to_hex(self.to_vec())) } } impl<'de> serde::de::Deserialize<'de> for PrintableCommitment { - fn deserialize(deserializer: D) -> Result where - D: serde::de::Deserializer<'de> { + fn deserialize(deserializer: D) -> Result + where + D: serde::de::Deserializer<'de>, + { deserializer.deserialize_str(PrintableCommitmentVisitor) } } @@ -204,9 +210,13 @@ impl<'de> serde::de::Visitor<'de> for PrintableCommitmentVisitor { formatter.write_str("a Pedersen commitment") } - fn visit_str(self, v: &str) -> Result where - E: serde::de::Error, { - Ok(PrintableCommitment(pedersen::Commitment::from_vec(util::from_hex(String::from(v)).unwrap()))) + fn visit_str(self, v: &str) -> Result + where + E: serde::de::Error, + { + Ok(PrintableCommitment(pedersen::Commitment::from_vec( + util::from_hex(String::from(v)).unwrap(), + ))) } } @@ -237,12 +247,14 @@ impl OutputPrintable { block: &core::Block, include_proof: bool, ) -> OutputPrintable { - let output_type = - if output.features.contains(core::transaction::OutputFeatures::COINBASE_OUTPUT) { - OutputType::Coinbase - } else { - OutputType::Transaction - }; + let output_type = if output + .features + .contains(core::transaction::OutputFeatures::COINBASE_OUTPUT) + { + OutputType::Coinbase + } else { + OutputType::Transaction + }; let out_id = core::OutputIdentifier::from_output(&output); let spent = chain.is_unspent(&out_id).is_err(); @@ -253,13 +265,14 @@ impl OutputPrintable { None }; - // Get the Merkle proof for all unspent coinbase outputs (to verify maturity on spend). - // We obtain the Merkle proof by rewinding the PMMR. - // We require the rewind() to be stable even after the PMMR is pruned and compacted - // so we can still recreate the necessary proof. + // Get the Merkle proof for all unspent coinbase outputs (to verify maturity on + // spend). We obtain the Merkle proof by rewinding the PMMR. + // We require the rewind() to be stable even after the PMMR is pruned and + // compacted so we can still recreate the necessary proof. let mut merkle_proof = None; - if output.features.contains(core::transaction::OutputFeatures::COINBASE_OUTPUT) - && !spent + if output + .features + .contains(core::transaction::OutputFeatures::COINBASE_OUTPUT) && !spent { merkle_proof = chain.get_merkle_proof(&out_id, &block).ok() }; @@ -285,13 +298,17 @@ impl OutputPrintable { } pub fn range_proof(&self) -> Result { - self.proof.clone().ok_or_else(|| ser::Error::HexError(format!("output range_proof missing"))) + self.proof + .clone() + .ok_or_else(|| ser::Error::HexError(format!("output range_proof missing"))) } } impl serde::ser::Serialize for OutputPrintable { - fn serialize(&self, serializer: S) -> Result where - S: serde::ser::Serializer { + fn serialize(&self, serializer: S) -> Result + where + S: serde::ser::Serializer, + { let mut state = serializer.serialize_struct("OutputPrintable", 7)?; state.serialize_field("output_type", &self.output_type)?; state.serialize_field("commit", &util::to_hex(self.commit.0.to_vec()))?; @@ -308,8 +325,10 @@ impl serde::ser::Serialize for OutputPrintable { } impl<'de> serde::de::Deserialize<'de> for OutputPrintable { - fn deserialize(deserializer: D) -> Result where - D: serde::de::Deserializer<'de> { + fn deserialize(deserializer: D) -> Result + where + D: serde::de::Deserializer<'de>, + { #[derive(Deserialize)] #[serde(field_identifier, rename_all = "snake_case")] enum Field { @@ -319,7 +338,7 @@ impl<'de> serde::de::Deserialize<'de> for OutputPrintable { Spent, Proof, ProofHash, - MerkleProof + MerkleProof, } struct OutputPrintableVisitor; @@ -331,8 +350,10 @@ impl<'de> serde::de::Deserialize<'de> for OutputPrintable { formatter.write_str("a print able Output") } - fn visit_map(self, mut map: A) -> Result where - A: MapAccess<'de>, { + fn visit_map(self, mut map: A) -> Result + where + A: MapAccess<'de>, + { let mut output_type = None; let mut commit = None; let mut switch_commit_hash = None; @@ -346,15 +367,15 @@ impl<'de> serde::de::Deserialize<'de> for OutputPrintable { Field::OutputType => { no_dup!(output_type); output_type = Some(map.next_value()?) - }, + } Field::Commit => { no_dup!(commit); let val: String = map.next_value()?; - let vec = util::from_hex(val.clone()) - .map_err(serde::de::Error::custom)?; + let vec = + util::from_hex(val.clone()).map_err(serde::de::Error::custom)?; commit = Some(pedersen::Commitment::from_vec(vec)); - }, + } Field::SwitchCommitHash => { no_dup!(switch_commit_hash); @@ -362,11 +383,11 @@ impl<'de> serde::de::Deserialize<'de> for OutputPrintable { let hash = core::SwitchCommitHash::from_hex(&val.clone()) .map_err(serde::de::Error::custom)?; switch_commit_hash = Some(hash) - }, + } Field::Spent => { no_dup!(spent); spent = Some(map.next_value()?) - }, + } Field::Proof => { no_dup!(proof); @@ -380,13 +401,16 @@ impl<'de> serde::de::Deserialize<'de> for OutputPrintable { bytes[i] = vec[i]; } - proof = Some(pedersen::RangeProof { proof: bytes, plen: vec.len() }) + proof = Some(pedersen::RangeProof { + proof: bytes, + plen: vec.len(), + }) } - }, + } Field::ProofHash => { no_dup!(proof_hash); proof_hash = Some(map.next_value()?) - }, + } Field::MerkleProof => { no_dup!(merkle_proof); if let Some(hex) = map.next_value::>()? { @@ -412,7 +436,14 @@ impl<'de> serde::de::Deserialize<'de> for OutputPrintable { } } - const FIELDS: &'static [&'static str] = &["output_type", "commit", "switch_commit_hash", "spent", "proof", "proof_hash"]; + const FIELDS: &'static [&'static str] = &[ + "output_type", + "commit", + "switch_commit_hash", + "spent", + "proof", + "proof_hash", + ]; deserializer.deserialize_struct("OutputPrintable", FIELDS, OutputPrintableVisitor) } } @@ -523,14 +554,17 @@ impl BlockPrintable { chain: Arc, include_proof: bool, ) -> BlockPrintable { - let inputs = block.inputs + let inputs = block + .inputs .iter() .map(|x| util::to_hex(x.commitment().0.to_vec())) .collect(); let outputs = block .outputs .iter() - .map(|output| OutputPrintable::from_output(output, chain.clone(), &block, include_proof)) + .map(|output| { + OutputPrintable::from_output(output, chain.clone(), &block, include_proof) + }) .collect(); let kernels = block .kernels @@ -559,19 +593,18 @@ pub struct CompactBlockPrintable { } impl CompactBlockPrintable { - /// Convert a compact block into a printable representation suitable for api response + /// Convert a compact block into a printable representation suitable for + /// api response pub fn from_compact_block( cb: &core::CompactBlock, chain: Arc, ) -> CompactBlockPrintable { let block = chain.get_block(&cb.hash()).unwrap(); - let out_full = cb - .out_full + let out_full = cb.out_full .iter() .map(|x| OutputPrintable::from_output(x, chain.clone(), &block, false)) .collect(); - let kern_full = cb - .kern_full + let kern_full = cb.kern_full .iter() .map(|x| TxKernelPrintable::from_txkernel(x)) .collect(); @@ -611,15 +644,16 @@ mod test { #[test] fn serialize_output() { - let hex_output = "{\ - \"output_type\":\"Coinbase\",\ - \"commit\":\"083eafae5d61a85ab07b12e1a51b3918d8e6de11fc6cde641d54af53608aa77b9f\",\ - \"switch_commit_hash\":\"85daaf11011dc11e52af84ebe78e2f2d19cbdc76000000000000000000000000\",\ - \"spent\":false,\ - \"proof\":null,\ - \"proof_hash\":\"ed6ba96009b86173bade6a9227ed60422916593fa32dd6d78b25b7a4eeef4946\",\ - \"merkle_proof\":null\ - }"; + let hex_output = + "{\ + \"output_type\":\"Coinbase\",\ + \"commit\":\"083eafae5d61a85ab07b12e1a51b3918d8e6de11fc6cde641d54af53608aa77b9f\",\ + \"switch_commit_hash\":\"85daaf11011dc11e52af84ebe78e2f2d19cbdc76000000000000000000000000\",\ + \"spent\":false,\ + \"proof\":null,\ + \"proof_hash\":\"ed6ba96009b86173bade6a9227ed60422916593fa32dd6d78b25b7a4eeef4946\",\ + \"merkle_proof\":null\ + }"; let deserialized: OutputPrintable = serde_json::from_str(&hex_output).unwrap(); let serialized = serde_json::to_string(&deserialized).unwrap(); assert_eq!(serialized, hex_output); @@ -627,7 +661,8 @@ mod test { #[test] fn serialize_utxo() { - let hex_commit = "{\"commit\":\"083eafae5d61a85ab07b12e1a51b3918d8e6de11fc6cde641d54af53608aa77b9f\"}"; + let hex_commit = + "{\"commit\":\"083eafae5d61a85ab07b12e1a51b3918d8e6de11fc6cde641d54af53608aa77b9f\"}"; let deserialized: Utxo = serde_json::from_str(&hex_commit).unwrap(); let serialized = serde_json::to_string(&deserialized).unwrap(); assert_eq!(serialized, hex_commit); diff --git a/chain/src/chain.rs b/chain/src/chain.rs index c0a393b79..fa012fdb0 100644 --- a/chain/src/chain.rs +++ b/chain/src/chain.rs @@ -20,7 +20,8 @@ use std::fs::File; use std::sync::{Arc, Mutex, RwLock}; use std::time::{Duration, Instant}; -use core::core::{Block, BlockHeader, Input, OutputFeatures, OutputIdentifier, OutputStoreable, TxKernel}; +use core::core::{Block, BlockHeader, Input, OutputFeatures, OutputIdentifier, OutputStoreable, + TxKernel}; use core::core::hash::{Hash, Hashed}; use core::core::pmmr::MerkleProof; use core::core::target::Difficulty; @@ -33,7 +34,6 @@ use types::*; use util::secp::pedersen::RangeProof; use util::LOGGER; - const MAX_ORPHAN_AGE_SECS: u64 = 30; #[derive(Debug, Clone)] @@ -75,7 +75,9 @@ impl OrphanBlockPool { { let mut orphans = self.orphans.write().unwrap(); let mut prev_idx = self.prev_idx.write().unwrap(); - orphans.retain(|_, ref mut x| x.added.elapsed() < Duration::from_secs(MAX_ORPHAN_AGE_SECS)); + orphans.retain(|_, ref mut x| { + x.added.elapsed() < Duration::from_secs(MAX_ORPHAN_AGE_SECS) + }); prev_idx.retain(|_, &mut x| orphans.contains_key(&x)); } } @@ -155,9 +157,7 @@ impl Chain { // check if we have a head in store, otherwise the genesis block is it let head = store.head(); let sumtree_md = match head { - Ok(h) => { - Some(store.get_block_pmmr_file_metadata(&h.last_block_h)?) - }, + Ok(h) => Some(store.get_block_pmmr_file_metadata(&h.last_block_h)?), Err(NotFoundErr) => None, Err(e) => return Err(Error::StoreErr(e, "chain init load head".to_owned())), }; @@ -172,9 +172,7 @@ impl Chain { store.save_block(&genesis)?; store.setup_height(&genesis.header, &tip)?; if genesis.kernels.len() > 0 { - sumtree::extending(&mut sumtrees, |extension| { - extension.apply_block(&genesis) - })?; + sumtree::extending(&mut sumtrees, |extension| extension.apply_block(&genesis))?; } // saving a new tip based on genesis @@ -211,30 +209,32 @@ impl Chain { /// Processes a single block, then checks for orphans, processing /// those as well if they're found - pub fn process_block(&self, b: Block, opts: Options) - -> Result<(Option, Option), Error> - { - let res = self.process_block_no_orphans(b, opts); - match res { - Ok((t, b)) => { - // We accepted a block, so see if we can accept any orphans - if let Some(ref b) = b { - self.check_orphans(b.hash()); - } - Ok((t, b)) - }, - Err(e) => { - Err(e) + pub fn process_block( + &self, + b: Block, + opts: Options, + ) -> Result<(Option, Option), Error> { + let res = self.process_block_no_orphans(b, opts); + match res { + Ok((t, b)) => { + // We accepted a block, so see if we can accept any orphans + if let Some(ref b) = b { + self.check_orphans(b.hash()); } + Ok((t, b)) } + Err(e) => Err(e), } + } /// Attempt to add a new block to the chain. Returns the new chain tip if it /// has been added to the longest chain, None if it's added to an (as of /// now) orphan chain. - pub fn process_block_no_orphans(&self, b: Block, opts: Options) - -> Result<(Option, Option), Error> - { + pub fn process_block_no_orphans( + &self, + b: Block, + opts: Options, + ) -> Result<(Option, Option), Error> { let head = self.store .head() .map_err(|e| Error::StoreErr(e, "chain load head".to_owned()))?; @@ -258,7 +258,7 @@ impl Chain { adapter.block_accepted(&b, opts); } Ok((Some(tip.clone()), Some(b.clone()))) - }, + } Ok(None) => { // block got accepted but we did not extend the head // so its on a fork (or is the start of a new fork) @@ -267,7 +267,8 @@ impl Chain { // TODO - This opens us to an amplification attack on blocks // mined at a low difficulty. We should suppress really old blocks // or less relevant blocks somehow. - // We should also probably consider banning nodes that send us really old blocks. + // We should also probably consider banning nodes that send us really old + // blocks. // if !opts.contains(Options::SYNC) { // broadcast the block @@ -275,7 +276,7 @@ impl Chain { adapter.block_accepted(&b, opts); } Ok((None, Some(b.clone()))) - }, + } Err(Error::Orphan) => { let block_hash = b.hash(); let orphan = Orphan { @@ -297,7 +298,7 @@ impl Chain { self.orphans.len(), ); Err(Error::Orphan) - }, + } Err(Error::Unfit(ref msg)) => { debug!( LOGGER, @@ -334,11 +335,7 @@ impl Chain { /// Attempt to add a new header to the header chain. /// This is only ever used during sync and uses sync_head. - pub fn sync_block_header( - &self, - bh: &BlockHeader, - opts: Options, - ) -> Result, Error> { + pub fn sync_block_header(&self, bh: &BlockHeader, opts: Options) -> Result, Error> { let sync_head = self.get_sync_head()?; let header_head = self.get_header_head()?; let sync_ctx = self.ctx_from_head(sync_head, opts); @@ -361,7 +358,6 @@ impl Chain { self.orphans.contains(hash) } - /// Check for orphans, once a block is successfully added pub fn check_orphans(&self, mut last_block_hash: Hash) { debug!( @@ -384,10 +380,10 @@ impl Chain { } else { break; } - }, + } Err(_) => { break; - }, + } }; } else { break; @@ -408,9 +404,7 @@ impl Chain { pub fn validate(&self) -> Result<(), Error> { let header = self.store.head_header()?; let mut sumtrees = self.sumtrees.write().unwrap(); - sumtree::extending(&mut sumtrees, |extension| { - extension.validate(&header) - }) + sumtree::extending(&mut sumtrees, |extension| extension.validate(&header)) } /// Check if the input has matured sufficiently for the given block height. @@ -466,13 +460,7 @@ impl Chain { } /// Returns current sumtree roots - pub fn get_sumtree_roots( - &self, - ) -> ( - Hash, - Hash, - Hash, - ) { + pub fn get_sumtree_roots(&self) -> (Hash, Hash, Hash) { let mut sumtrees = self.sumtrees.write().unwrap(); sumtrees.roots() } @@ -507,9 +495,8 @@ impl Chain { h: Hash, rewind_to_output: u64, rewind_to_kernel: u64, - sumtree_data: File + sumtree_data: File, ) -> Result<(), Error> { - let head = self.head().unwrap(); let header_head = self.get_header_head().unwrap(); if header_head.height - head.height < global::cut_through_horizon() as u64 { @@ -610,17 +597,17 @@ impl Chain { /// Gets the block header at the provided height pub fn get_header_by_height(&self, height: u64) -> Result { - self.store.get_header_by_height(height).map_err(|e| { - Error::StoreErr(e, "chain get header by height".to_owned()) - }) + self.store + .get_header_by_height(height) + .map_err(|e| Error::StoreErr(e, "chain get header by height".to_owned())) } /// Verifies the given block header is actually on the current chain. /// Checks the header_by_height index to verify the header is where we say it is pub fn is_on_current_chain(&self, header: &BlockHeader) -> Result<(), Error> { - self.store.is_on_current_chain(header).map_err(|e| { - Error::StoreErr(e, "chain is_on_current_chain".to_owned()) - }) + self.store + .is_on_current_chain(header) + .map_err(|e| Error::StoreErr(e, "chain is_on_current_chain".to_owned())) } /// Get the tip of the current "sync" header chain. @@ -648,13 +635,18 @@ impl Chain { /// Check whether we have a block without reading it pub fn block_exists(&self, h: Hash) -> Result { - self.store.block_exists(&h) + self.store + .block_exists(&h) .map_err(|e| Error::StoreErr(e, "chain block exists".to_owned())) } /// Retrieve the file index metadata for a given block - pub fn get_block_pmmr_file_metadata(&self, h: &Hash) -> Result { - self.store.get_block_pmmr_file_metadata(h) + pub fn get_block_pmmr_file_metadata( + &self, + h: &Hash, + ) -> Result { + self.store + .get_block_pmmr_file_metadata(h) .map_err(|e| Error::StoreErr(e, "retrieve block pmmr metadata".to_owned())) } } diff --git a/chain/src/pipe.rs b/chain/src/pipe.rs index d0c7b047e..1843ec38e 100644 --- a/chain/src/pipe.rs +++ b/chain/src/pipe.rs @@ -64,25 +64,27 @@ pub fn process_block(b: &Block, mut ctx: BlockContext) -> Result, Er validate_header(&b.header, &mut ctx)?; - // valid header, now check we actually have the previous block in the store + // valid header, now check we actually have the previous block in the store // not just the header but the block itself // short circuit the test first both for performance (in-mem vs db access) // but also for the specific case of the first fast sync full block if b.header.previous != ctx.head.last_block_h { - // we cannot assume we can use the chain head for this as we may be dealing with a fork - // we cannot use heights here as the fork may have jumped in height + // we cannot assume we can use the chain head for this as we may be dealing + // with a fork we cannot use heights here as the fork may have jumped in + // height match ctx.store.block_exists(&b.header.previous) { - Ok(true) => {}, + Ok(true) => {} Ok(false) => { return Err(Error::Orphan); - }, + } Err(e) => { return Err(Error::StoreErr(e, "pipe get previous".to_owned())); } } } - // valid header and we have a previous block, time to take the lock on the sum trees + // valid header and we have a previous block, time to take the lock on the sum + // trees let local_sumtrees = ctx.sumtrees.clone(); let mut sumtrees = local_sumtrees.write().unwrap(); @@ -112,15 +114,19 @@ pub fn process_block(b: &Block, mut ctx: BlockContext) -> Result, Er match result { Ok(t) => { - save_pmmr_metadata(&Tip::from_block(&b.header), &sumtrees, ctx.store.clone())?; + save_pmmr_metadata(&Tip::from_block(&b.header), &sumtrees, ctx.store.clone())?; Ok(t) - }, + } Err(e) => Err(e), } } /// Save pmmr index location for a given block -pub fn save_pmmr_metadata(t: &Tip, sumtrees: &sumtree::SumTrees, store: Arc) -> Result<(), Error> { +pub fn save_pmmr_metadata( + t: &Tip, + sumtrees: &sumtree::SumTrees, + store: Arc, +) -> Result<(), Error> { // Save pmmr file metadata for this block let block_file_md = sumtrees.last_file_metadata(); store @@ -136,7 +142,12 @@ pub fn sync_block_header( mut sync_ctx: BlockContext, mut header_ctx: BlockContext, ) -> Result, Error> { - debug!(LOGGER, "pipe: sync_block_header: {} at {}", bh.hash(), bh.height); + debug!( + LOGGER, + "pipe: sync_block_header: {} at {}", + bh.hash(), + bh.height + ); validate_header(&bh, &mut sync_ctx)?; add_block_header(bh, &mut sync_ctx)?; @@ -146,17 +157,20 @@ pub fn sync_block_header( // just taking the shared lock let _ = header_ctx.sumtrees.write().unwrap(); - // now update the header_head (if new header with most work) and the sync_head (always) + // now update the header_head (if new header with most work) and the sync_head + // (always) update_header_head(bh, &mut header_ctx)?; update_sync_head(bh, &mut sync_ctx) } /// Process block header as part of "header first" block propagation. -pub fn process_block_header( - bh: &BlockHeader, - mut ctx: BlockContext, -) -> Result, Error> { - debug!(LOGGER, "pipe: process_block_header: {} at {}", bh.hash(), bh.height); +pub fn process_block_header(bh: &BlockHeader, mut ctx: BlockContext) -> Result, Error> { + debug!( + LOGGER, + "pipe: process_block_header: {} at {}", + bh.hash(), + bh.height + ); check_header_known(bh.hash(), &mut ctx)?; validate_header(&bh, &mut ctx)?; @@ -214,13 +228,11 @@ fn check_known(bh: Hash, ctx: &mut BlockContext) -> Result<(), Error> { /// arranged by order of cost to have as little DoS surface as possible. /// TODO require only the block header (with length information) fn validate_header(header: &BlockHeader, ctx: &mut BlockContext) -> Result<(), Error> { - // 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(Error::InvalidBlockVersion(header.version)); } @@ -236,11 +248,17 @@ fn validate_header(header: &BlockHeader, ctx: &mut BlockContext) -> Result<(), E if !ctx.opts.contains(Options::SKIP_POW) { let n = global::sizeshift() as u32; if !(ctx.pow_verifier)(header, n) { - error!(LOGGER, "pipe: validate_header failed for cuckoo shift size {}", n); + error!( + LOGGER, + "pipe: validate_header failed for cuckoo shift size {}", n + ); return Err(Error::InvalidPow); } if header.height % 500 == 0 { - debug!(LOGGER, "Validating header validated, using cuckoo shift size {}", n); + debug!( + LOGGER, + "Validating header validated, using cuckoo shift size {}", n + ); } } @@ -248,9 +266,10 @@ fn validate_header(header: &BlockHeader, ctx: &mut BlockContext) -> Result<(), E let prev = match ctx.store.get_block_header(&header.previous) { Ok(prev) => Ok(prev), Err(grin_store::Error::NotFoundErr) => Err(Error::Orphan), - Err(e) =>{ - Err(Error::StoreErr(e, format!("previous header {}", header.previous))) - } + Err(e) => Err(Error::StoreErr( + e, + format!("previous header {}", header.previous), + )), }?; if header.height != prev.height + 1 { @@ -312,7 +331,6 @@ fn validate_block( ctx: &mut BlockContext, ext: &mut sumtree::Extension, ) -> Result<(), Error> { - // main isolated block validation, checks all commitment sums and sigs b.validate().map_err(&Error::InvalidBlockProof)?; @@ -331,9 +349,7 @@ fn validate_block( debug!( LOGGER, - "validate_block: utxo roots - {:?}, {:?}", - roots.utxo_root, - b.header.utxo_root, + "validate_block: utxo roots - {:?}, {:?}", roots.utxo_root, b.header.utxo_root, ); debug!( LOGGER, @@ -343,9 +359,7 @@ fn validate_block( ); debug!( LOGGER, - "validate_block: kernel roots - {:?}, {:?}", - roots.kernel_root, - b.header.kernel_root, + "validate_block: kernel roots - {:?}, {:?}", roots.kernel_root, b.header.kernel_root, ); return Err(Error::InvalidRoot); @@ -395,11 +409,21 @@ fn update_head(b: &Block, ctx: &mut BlockContext) -> Result, Error> } ctx.head = tip.clone(); if b.header.height % 100 == 0 { - info!(LOGGER, "pipe: chain head reached {} @ {} [{}]", - b.header.height, b.header.difficulty, b.hash()); + info!( + LOGGER, + "pipe: chain head reached {} @ {} [{}]", + b.header.height, + b.header.difficulty, + b.hash() + ); } else { - debug!(LOGGER, "pipe: chain head reached {} @ {} [{}]", - b.header.height, b.header.difficulty, b.hash()); + debug!( + LOGGER, + "pipe: chain head reached {} @ {} [{}]", + b.header.height, + b.header.difficulty, + b.hash() + ); } Ok(Some(tip)) } else { @@ -415,9 +439,21 @@ fn update_sync_head(bh: &BlockHeader, ctx: &mut BlockContext) -> Result Result