diff --git a/blockchain/clippy.toml b/blockchain/clippy.toml new file mode 100644 index 0000000000000000000000000000000000000000..2bd93f5e4e2163651a3eaa626e2f5c4ffa201edf --- /dev/null +++ b/blockchain/clippy.toml @@ -0,0 +1 @@ +cyclomatic-complexity-threshold = 36 \ No newline at end of file diff --git a/blockchain/lib.rs b/blockchain/lib.rs index 8710a5214a4064bf7d46218666a320b285cb2113..c2ec0c3033278f4687e1bf4bc6cf350660756d49 100644 --- a/blockchain/lib.rs +++ b/blockchain/lib.rs @@ -16,6 +16,7 @@ //! Module managing the Duniter blockchain. #![cfg_attr(feature = "strict", deny(warnings))] +#![cfg_attr(feature = "cargo-clippy", allow(unused_collect))] #![deny( missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces, @@ -190,12 +191,12 @@ impl BlockchainModule { /// Request chunk from network (chunk = group of blocks) fn request_chunk(&self, req_id: &ModuleReqId, from: u32) -> (ModuleReqId, NetworkRequest) { let req = NetworkRequest::GetBlocks( - ModuleReqFullId(BlockchainModule::id(), req_id.clone()), + ModuleReqFullId(BlockchainModule::id(), *req_id), NodeFullId::default(), *CHUNK_SIZE, from, ); - (self.request_network(req.clone()), req) + (self.request_network(req), req) } /// Requests blocks from current to `to` fn request_blocks_to( @@ -216,10 +217,11 @@ impl BlockchainModule { ); let mut requests_ids = HashMap::new(); if current_blockstamp.id < to { - let mut real_to = to.0; - if (to.0 - current_blockstamp.id.0) > *MAX_BLOCKS_REQUEST { - real_to = current_blockstamp.id.0 + *MAX_BLOCKS_REQUEST; - } + let real_to = if (to.0 - current_blockstamp.id.0) > *MAX_BLOCKS_REQUEST { + current_blockstamp.id.0 + *MAX_BLOCKS_REQUEST + } else { + to.0 + }; while from <= real_to { let mut req_id = ModuleReqId(0); while pending_network_requests.contains_key(&req_id) @@ -238,7 +240,7 @@ impl BlockchainModule { fn request_network(&self, request: NetworkRequest) -> ModuleReqId { for follower in &self.followers { if follower - .send(DuniterMessage::NetworkRequest(request.clone())) + .send(DuniterMessage::NetworkRequest(request)) .is_err() { debug!("BlockchainModule : one follower is unreachable !"); @@ -247,36 +249,40 @@ impl BlockchainModule { request.get_req_id() } /// Send blockchain event - fn send_event(&self, event: DALEvent) { + fn send_event(&self, event: &DALEvent) { for follower in &self.followers { - match follower.send(DuniterMessage::DALEvent(event.clone())) { - Ok(_) => {} - Err(_) => {} + if follower + .send(DuniterMessage::DALEvent(event.clone())) + .is_err() + { + // Handle error } } } - fn send_req_response(&self, response: DALResponse) { + fn send_req_response(&self, response: &DALResponse) { for follower in &self.followers { - match follower.send(DuniterMessage::DALResponse(response.clone())) { - Ok(_) => {} - Err(_) => {} + if follower + .send(DuniterMessage::DALResponse(Box::new(response.clone()))) + .is_err() + { + // Handle error } } } fn receive_network_documents<W: WebOfTrust + Sync>( &self, - network_documents: &Vec<NetworkDocument>, + network_documents: &[NetworkDocument], current_blockstamp: &Blockstamp, forks: &mut Vec<ForkState>, wotb_index: &HashMap<ed25519::PublicKey, NodeId>, wot: &W, ) -> (Blockstamp, Vec<WotEvent>) { let mut blockchain_documents = Vec::new(); - let mut current_blockstamp = current_blockstamp.clone(); + let mut current_blockstamp = *current_blockstamp; let mut wot_events = Vec::new(); for network_document in network_documents { - match network_document { - &NetworkDocument::Block(ref network_block) => { + match *network_document { + NetworkDocument::Block(ref network_block) => { let (success, _new_forks, mut new_wot_events) = self.apply_block( &Block::NetworkBlock(network_block), ¤t_blockstamp, @@ -301,23 +307,23 @@ impl BlockchainModule { forks = new_forks; }*/ } - &NetworkDocument::Identity(ref doc) => blockchain_documents.push( + NetworkDocument::Identity(ref doc) => blockchain_documents.push( BlockchainProtocol::V10(Box::new(V10Document::Identity(doc.deref().clone()))), ), - &NetworkDocument::Membership(ref doc) => blockchain_documents.push( + NetworkDocument::Membership(ref doc) => blockchain_documents.push( BlockchainProtocol::V10(Box::new(V10Document::Membership(doc.deref().clone()))), ), - &NetworkDocument::Certification(ref doc) => { + NetworkDocument::Certification(ref doc) => { blockchain_documents.push(BlockchainProtocol::V10(Box::new( V10Document::Certification(Box::new(doc.deref().clone())), ))) } - &NetworkDocument::Revocation(ref doc) => { + NetworkDocument::Revocation(ref doc) => { blockchain_documents.push(BlockchainProtocol::V10(Box::new( V10Document::Revocation(Box::new(doc.deref().clone())), ))) } - &NetworkDocument::Transaction(ref doc) => { + NetworkDocument::Transaction(ref doc) => { blockchain_documents.push(BlockchainProtocol::V10(Box::new( V10Document::Transaction(Box::new(doc.deref().clone())), ))) @@ -329,31 +335,31 @@ impl BlockchainModule { } (current_blockstamp, wot_events) } - fn receive_documents(&self, documents: &Vec<BlockchainProtocol>) { + fn receive_documents(&self, documents: &[BlockchainProtocol]) { debug!("BlockchainModule : receive_documents()"); for document in documents { trace!("BlockchainModule : Treat one document."); - match document { - &BlockchainProtocol::V10(ref doc_v10) => match doc_v10.deref() { + match *document { + BlockchainProtocol::V10(ref doc_v10) => match doc_v10.deref() { _ => {} }, - _ => self.send_event(DALEvent::RefusedPendingDoc(document.clone())), + _ => self.send_event(&DALEvent::RefusedPendingDoc(document.clone())), } } } fn receive_blocks<W: WebOfTrust + Sync>( &self, - blocks_in_box: &Vec<Box<NetworkBlock>>, + blocks_in_box: &[Box<NetworkBlock>], current_blockstamp: &Blockstamp, - forks: &Vec<ForkState>, + forks: &[ForkState], wotb_index: &HashMap<ed25519::PublicKey, NodeId>, wot: &W, ) -> (Blockstamp, Vec<ForkState>, Vec<WotEvent>) { debug!("BlockchainModule : receive_blocks()"); let blocks: Vec<&NetworkBlock> = blocks_in_box.into_iter().map(|b| b.deref()).collect(); - let mut current_blockstamp = current_blockstamp.clone(); + let mut current_blockstamp = *current_blockstamp; let mut all_wot_events = Vec::new(); - let mut forks = forks.clone(); + let mut forks = forks.to_owned(); let mut wot_copy: W = wot.clone(); let mut wotb_index_copy = wotb_index.clone(); for block in blocks { @@ -418,9 +424,9 @@ impl BlockchainModule { wot: &W, ) -> (bool, Vec<ForkState>, Vec<WotEvent>) { let mut already_have_block = false; - let block_doc = match block { - &Block::NetworkBlock(network_block) => match network_block { - &NetworkBlock::V10(ref network_block_v10) => { + let block_doc = match *block { + Block::NetworkBlock(network_block) => match *network_block { + NetworkBlock::V10(ref network_block_v10) => { let (hashs, _) = DALBlock::get_blocks_hashs_all_forks( &self.db, &network_block_v10.uncompleted_block_doc.number, @@ -434,27 +440,27 @@ impl BlockchainModule { } _ => return (false, Vec::with_capacity(0), Vec::with_capacity(0)), }, - &Block::LocalBlock(block_doc) => { + Block::LocalBlock(block_doc) => { already_have_block = true; block_doc } }; if (block_doc.number.0 == current_blockstamp.id.0 + 1 && block_doc.previous_hash.to_string() == current_blockstamp.hash.0.to_string()) - || (block_doc.number.0 == 0 && current_blockstamp.clone() == Blockstamp::default()) + || (block_doc.number.0 == 0 && *current_blockstamp == Blockstamp::default()) { debug!( "stackable_block : block {} chainable !", block_doc.blockstamp() ); - let (success, db_requests, wot_events) = match block { - &Block::NetworkBlock(network_block) => self.try_stack_up_block( + let (success, db_requests, wot_events) = match *block { + Block::NetworkBlock(network_block) => self.try_stack_up_block( &network_block, wotb_index, wot, SyncVerificationLevel::Cautious(), ), - &Block::LocalBlock(block_doc) => { + Block::LocalBlock(block_doc) => { try_stack_up_completed_block(&block_doc, wotb_index, wot) } }; @@ -469,11 +475,11 @@ impl BlockchainModule { .map(|req| req.apply(&block_doc.currency, &self.db)) .collect::<()>(); info!("StackUpValidBlock({})", block_doc.number.0); - self.send_event(DALEvent::StackUpValidBlock(Box::new(block_doc.clone()))); + self.send_event(&DALEvent::StackUpValidBlock(Box::new(block_doc.clone()))); return (true, Vec::with_capacity(0), wot_events); } else { warn!("RefusedBlock({})", block_doc.number.0); - self.send_event(DALEvent::RefusedPendingDoc(BlockchainProtocol::V10( + self.send_event(&DALEvent::RefusedPendingDoc(BlockchainProtocol::V10( Box::new(V10Document::Block(Box::new(block_doc.clone()))), ))); } @@ -525,9 +531,9 @@ impl BlockchainModule { forks[fork] = ForkState::Isolate(); } } - match block { - &Block::NetworkBlock(network_block) => match network_block { - &NetworkBlock::V10(ref network_block_v10) => { + match *block { + Block::NetworkBlock(network_block) => match *network_block { + NetworkBlock::V10(ref network_block_v10) => { duniter_dal::writers::block::write_network_block( &self.db, &network_block_v10.uncompleted_block_doc, @@ -539,7 +545,7 @@ impl BlockchainModule { } _ => return (false, Vec::with_capacity(0), Vec::with_capacity(0)), }, - &Block::LocalBlock(block_doc) => { + Block::LocalBlock(block_doc) => { duniter_dal::writers::block::write(&self.db, &block_doc, fork, isolate) } }; @@ -564,7 +570,7 @@ impl BlockchainModule { &self.currency.to_string(), Some(&self.db), network_block, - verif_level.clone(), + verif_level, ) { Ok(block_doc) => block_doc, Err(_) => return (false, Vec::with_capacity(0), Vec::with_capacity(0)), @@ -572,7 +578,7 @@ impl BlockchainModule { try_stack_up_completed_block::<W>(&block_doc, wotb_index, wot) } /// Start blockchain module. - pub fn start_blockchain(&mut self, blockchain_receiver: mpsc::Receiver<DuniterMessage>) -> () { + pub fn start_blockchain(&mut self, blockchain_receiver: &mpsc::Receiver<DuniterMessage>) -> () { info!("BlockchainModule::start_blockchain()"); // Get wot path @@ -583,26 +589,10 @@ impl BlockchainModule { DALIdentity::get_wotb_index(&self.db); // Open wot file - let (mut wot, mut _wot_blockstamp): (RustyWebOfTrust, Blockstamp) = if wot_path - .as_path() - .exists() - { - match WOT_FILE_FORMATER.from_file( - wot_path.as_path().to_str().unwrap(), - duniter_dal::constants::G1_PARAMS.sig_stock as usize, - ) { - Ok((wot, binary_blockstamp)) => match str::from_utf8(&binary_blockstamp) { - Ok(str_blockstamp) => (wot, Blockstamp::from_string(str_blockstamp).unwrap()), - Err(e) => panic!("Invalid UTF-8 sequence: {}", e), - }, - Err(e) => panic!("Fatal Error : fail to read wot file : {:?}", e), - } - } else { - ( - RustyWebOfTrust::new(duniter_dal::constants::G1_PARAMS.sig_stock as usize), - Blockstamp::default(), - ) - }; + let (mut wot, mut _wot_blockstamp) = duniter_dal::open_wot_file::< + RustyWebOfTrust, + BinaryFileFormater, + >(&WOT_FILE_FORMATER, &wot_path); // Get forks let mut forks: Vec<ForkState> = duniter_dal::block::get_forks(&self.db); @@ -627,7 +617,7 @@ impl BlockchainModule { BlockchainModule::id(), ModuleReqId(pending_network_requests.len() as u32), )); - let req_id = self.request_network(req.clone()); + let req_id = self.request_network(req); pending_network_requests.insert(req_id, req); // Request Blocks let now = SystemTime::now(); @@ -658,17 +648,17 @@ impl BlockchainModule { } } match blockchain_receiver.recv_timeout(Duration::from_millis(1000)) { - Ok(ref message) => match message { - &DuniterMessage::Followers(ref new_followers) => { + Ok(ref message) => match *message { + DuniterMessage::Followers(ref new_followers) => { info!("Blockchain module receive followers !"); for new_follower in new_followers { self.followers.push(new_follower.clone()); } } - &DuniterMessage::DALRequest(ref dal_request) => match dal_request { - &DALRequest::BlockchainRequest(ref blockchain_req) => { - match blockchain_req { - &DALReqBlockchain::CurrentBlock(ref requester_full_id) => { + DuniterMessage::DALRequest(ref dal_request) => match *dal_request { + DALRequest::BlockchainRequest(ref blockchain_req) => { + match *blockchain_req { + DALReqBlockchain::CurrentBlock(ref requester_full_id) => { debug!("BlockchainModule : receive DALReqBc::CurrentBlock()"); if let Some(current_block) = DALBlock::get_block( @@ -677,44 +667,44 @@ impl BlockchainModule { ¤t_blockstamp, ) { debug!("BlockchainModule : send_req_response(CurrentBlock({}))", current_block.block.blockstamp()); - self.send_req_response(DALResponse::Blockchain( + self.send_req_response(&DALResponse::Blockchain(Box::new( DALResBlockchain::CurrentBlock( - requester_full_id.clone(), - current_block.block, + *requester_full_id, + Box::new(current_block.block), ), - )); + ))); } else { warn!("BlockchainModule : Req : fail to get current_block in bdd !"); } } - &DALReqBlockchain::UIDs(ref pubkeys) => { - self.send_req_response(DALResponse::Blockchain( + DALReqBlockchain::UIDs(ref pubkeys) => { + self.send_req_response(&DALResponse::Blockchain(Box::new( DALResBlockchain::UIDs( pubkeys .iter() .map(|p| { if let Some(wotb_id) = wotb_index.get(p) { ( - p.clone(), + *p, duniter_dal::get_uid( &self.db, *wotb_id, ), ) } else { - (p.clone(), None) + (*p, None) } }) .collect(), ), - )); + ))); } _ => {} } } - _ => {} + DALRequest::PendingsRequest(ref _pending_req) => {} }, - &DuniterMessage::NetworkEvent(ref network_event) => match network_event { - &NetworkEvent::ReceiveDocuments(ref network_docs) => { + DuniterMessage::NetworkEvent(ref network_event) => match *network_event { + NetworkEvent::ReceiveDocuments(ref network_docs) => { let (new_current_blockstamp, mut new_wot_events) = self .receive_network_documents( network_docs, @@ -726,24 +716,24 @@ impl BlockchainModule { current_blockstamp = new_current_blockstamp; wot_events.append(&mut new_wot_events); } - &NetworkEvent::ReqResponse(ref network_response) => { + NetworkEvent::ReqResponse(ref network_response) => { debug!("BlockchainModule : receive NetworkEvent::ReqResponse() !"); if let Some(request) = pending_network_requests.remove(&network_response.get_req_id()) { match request { NetworkRequest::GetConsensus(_) => { - if let &NetworkResponse::Consensus(_, response) = - network_response.deref() + if let NetworkResponse::Consensus(_, response) = + *network_response.deref() { if let Ok(blockstamp) = response { - consensus = blockstamp.clone(); + consensus = blockstamp; } } } NetworkRequest::GetBlocks(_, _, _, _) => { - if let &NetworkResponse::Chunk(_, _, ref blocks) = - network_response.deref() + if let NetworkResponse::Chunk(_, _, ref blocks) = + *network_response.deref() { let ( new_current_blockstamp, @@ -769,10 +759,10 @@ impl BlockchainModule { } _ => {} }, - &DuniterMessage::ReceiveDocsFromClient(ref docs) => { + DuniterMessage::ReceiveDocsFromClient(ref docs) => { self.receive_documents(docs); } - &DuniterMessage::Stop() => break, + DuniterMessage::Stop() => break, _ => {} }, Err(e) => match e { @@ -858,7 +848,7 @@ impl BlockchainModule { } } fn apply_wot_events<W: WebOfTrust + Sync>( - wot_events: &Vec<WotEvent>, + wot_events: &[WotEvent], wot_path: &PathBuf, current_blockstamp: &Blockstamp, wot: &mut W, @@ -866,26 +856,26 @@ impl BlockchainModule { ) { if !wot_events.is_empty() { for wot_event in wot_events { - match wot_event { - &WotEvent::AddNode(pubkey, wotb_id) => { + match *wot_event { + WotEvent::AddNode(pubkey, wotb_id) => { wot.add_node(); - wotb_index.insert(pubkey.clone(), wotb_id.clone()); + wotb_index.insert(pubkey, wotb_id); } - &WotEvent::RemNode(pubkey) => { + WotEvent::RemNode(pubkey) => { wot.rem_node(); wotb_index.remove(&pubkey); } - &WotEvent::AddLink(source, target) => { - wot.add_link(source.clone(), target.clone()); + WotEvent::AddLink(source, target) => { + wot.add_link(source, target); } - &WotEvent::RemLink(source, target) => { - wot.rem_link(source.clone(), target.clone()); + WotEvent::RemLink(source, target) => { + wot.rem_link(source, target); } - &WotEvent::EnableNode(wotb_id) => { - wot.set_enabled(wotb_id.clone(), true); + WotEvent::EnableNode(wotb_id) => { + wot.set_enabled(wotb_id, true); } - &WotEvent::DisableNode(wotb_id) => { - wot.set_enabled(wotb_id.clone(), false); + WotEvent::DisableNode(wotb_id) => { + wot.set_enabled(wotb_id, false); } } } @@ -908,7 +898,7 @@ pub fn complete_network_block( network_block: &NetworkBlock, verif_level: SyncVerificationLevel, ) -> Result<BlockDocument, CompletedBlockError> { - if let &NetworkBlock::V10(ref network_block_v10) = network_block { + if let NetworkBlock::V10(ref network_block_v10) = *network_block { let mut block_doc = network_block_v10.uncompleted_block_doc.clone(); trace!("complete_network_block #{}...", block_doc.number); if verif_level == SyncVerificationLevel::Cautious() { diff --git a/blockchain/stack_up_block.rs b/blockchain/stack_up_block.rs index bcc7b15d316dc45d6afde7600e9d00a4fa84d934..75ed957807597bb6b38d1ee7186d2fc3fbfe0de5 100644 --- a/blockchain/stack_up_block.rs +++ b/blockchain/stack_up_block.rs @@ -55,9 +55,9 @@ pub fn try_stack_up_completed_block<W: WebOfTrust + Sync>( wotb_index_copy.insert(pubkey, wotb_id); db_requests.push(DBWriteRequest::CreateIdentity( wotb_id, - current_blockstamp.clone(), + current_blockstamp, block.median_time, - idty_doc.clone(), + Box::new(idty_doc.clone()), )); } else { // Renewer @@ -168,11 +168,11 @@ pub fn try_stack_up_completed_block<W: WebOfTrust + Sync>( ); }*/ // Write block in bdd - db_requests.push(DBWriteRequest::WriteBlock(DALBlock { + db_requests.push(DBWriteRequest::WriteBlock(Box::new(DALBlock { block: block.clone(), fork: 0, isolate: false, - })); + }))); (true, db_requests, wot_events) } diff --git a/blockchain/sync.rs b/blockchain/sync.rs index 1fca5547cede8bffcc8f03267585b73e4bc96a73..ab073cc99d23fc9b99535dd27a35b76a5ea7b597 100644 --- a/blockchain/sync.rs +++ b/blockchain/sync.rs @@ -66,7 +66,7 @@ pub fn sync_ts( // get profile and currency and current_blockstamp let profile = &conf.profile(); let currency = &conf.currency(); - let mut current_blockstamp = current_blockstamp.clone(); + let mut current_blockstamp = *current_blockstamp; // Copy blockchain db in ramfs let db_path = duniter_conf::get_db_path(profile, currency, false); @@ -192,7 +192,7 @@ pub fn sync_ts( cursor .bind(&[ sqlite::Value::Integer(0), - sqlite::Value::Integer(current_blockstamp.id.0 as i64), + sqlite::Value::Integer(i64::from(current_blockstamp.id.0)), ]) .expect("0"); @@ -249,15 +249,12 @@ pub fn sync_ts( // Apply blocks while let Ok(ParserWorkMess::NetworkBlock(network_block)) = recv_sync_thread.recv() { // Complete block - let block_doc = match complete_network_block( + let block_doc = complete_network_block( &blockchain_module.currency.to_string(), None, &network_block, SyncVerificationLevel::FastSync(), - ) { - Ok(block_doc) => block_doc, - Err(_) => panic!("Receive wrong block, please reset data and resync !"), - }; + ).expect("Receive wrong block, please reset data and resync !"); // Apply block let (success, db_requests, new_wot_events) = try_stack_up_completed_block::<RustyWebOfTrust>(&block_doc, &wotb_index, &wot); @@ -452,7 +449,7 @@ pub fn parse_ts_block(row: &[sqlite::Value]) -> NetworkBlock { Hash::from_hex(row[1].as_string().expect("Fail to parse block inner_hash")) .expect("Fail to parse block inner_hash (2)"), ), - dividend: dividend, + dividend, identities, joiners: duniter_dal::parsers::memberships::parse_memberships( currency, diff --git a/core/lib.rs b/core/lib.rs index ac340eb402005f04855a7925dfec52f2f7f37e7f..4f421f519de988ab70d0b2e7a265e1bf58f8b356 100644 --- a/core/lib.rs +++ b/core/lib.rs @@ -123,7 +123,7 @@ impl DuniterCore { )) } else if let Some(matches) = cli_args.subcommand_matches("sync_ts") { let ts_profile = matches.value_of("TS_PROFILE").unwrap_or("duniter_default"); - sync_ts(conf, ts_profile, matches.is_present("cautious")); + sync_ts(&conf, ts_profile, matches.is_present("cautious")); None } else if let Some(matches) = cli_args.subcommand_matches("reset") { let mut profile_path = match env::home_dir() { @@ -195,19 +195,17 @@ impl DuniterCore { info!("Success to load Blockchain module."); // Start blockchain module in main thread - blockchain_module.start_blockchain(blockchain_receiver); + blockchain_module.start_blockchain(&blockchain_receiver); } } /// Plug a module pub fn plug<M: DuniterModule<ed25519::KeyPair, DuniterMessage>>(&mut self) { if self.start { // Start module in a new thread - let soft_name_clone = self.soft_name.clone(); - let soft_version_clone = self.soft_version.clone(); - let required_keys = DuniterKeyPairs::get_required_keys_content( - M::ask_required_keys(), - self.keypairs.clone(), - ); + let soft_name_clone = &(*self.soft_name); + let soft_version_clone = &(*self.soft_version); + let required_keys = + DuniterKeyPairs::get_required_keys_content(M::ask_required_keys(), self.keypairs); let module_conf = if let Some(module_conf_) = self .conf .clone() @@ -364,7 +362,7 @@ pub fn start( } /// Launch synchronisation from a duniter-ts database -pub fn sync_ts(conf: DuniterConf, ts_profile: &str, cautious: bool) { +pub fn sync_ts(conf: &DuniterConf, ts_profile: &str, cautious: bool) { // Launch sync-ts BlockchainModule::sync_ts(&conf, ts_profile, cautious); } diff --git a/dal/block.rs b/dal/block.rs index 4b2899c6ca9ecdeb0a75c24417464d4a91e26c9f..abdc73a16639fe2a76772b8891f35c1422ea34b7 100644 --- a/dal/block.rs +++ b/dal/block.rs @@ -35,7 +35,7 @@ pub fn blockstamp_to_timestamp(blockstamp: &Blockstamp, db: &DuniterDB) -> Optio cursor .bind(&[ - sqlite::Value::Integer(blockstamp.id.0 as i64), + sqlite::Value::Integer(i64::from(blockstamp.id.0)), sqlite::Value::String(blockstamp.hash.0.to_hex()), ]) .expect("convert blockstamp to timestamp failure at step 1 !"); @@ -135,7 +135,7 @@ impl DALBlock { cursor .bind(&[ - sqlite::Value::Integer(blockstamp.id.0 as i64), + sqlite::Value::Integer(i64::from(blockstamp.id.0)), sqlite::Value::String(blockstamp.hash.0.to_string()), ]) .expect("Fail to get block !"); @@ -154,7 +154,7 @@ impl DALBlock { .cursor(); cursor - .bind(&[sqlite::Value::Integer(block_number.0 as i64)]) + .bind(&[sqlite::Value::Integer(i64::from(block_number.0))]) .expect("Fail to get block !"); if let Some(row) = cursor.next().unwrap() { @@ -177,7 +177,7 @@ impl DALBlock { .cursor(); cursor - .bind(&[sqlite::Value::Integer(block_number.0 as i64)]) + .bind(&[sqlite::Value::Integer(i64::from(block_number.0))]) .expect("Fail to get block !"); let mut hashs = Vec::new(); @@ -249,7 +249,7 @@ impl DALBlock { cursor .bind(&[ - sqlite::Value::Integer(blockstamp.id.0 as i64), + sqlite::Value::Integer(i64::from(blockstamp.id.0)), sqlite::Value::String(blockstamp.hash.0.to_string()), ]) .expect("Fail to get block !"); @@ -288,15 +288,10 @@ impl DALBlock { .as_integer() .expect("dal::get_block() : fail to parse fork !") as usize, - isolate: if row[1] + isolate: !row[1] .as_integer() .expect("dal::get_block() : fail to parse isolate !") - == 0 - { - false - } else { - true - }, + == 0, block: BlockDocument { nonce, number: BlockId( @@ -443,7 +438,7 @@ impl DALBlock { } pub fn get_current_frame(&self, db: &DuniterDB) -> HashMap<keys::ed25519::PublicKey, usize> { - let frame_begin = self.block.number.0 as i64 - (self.block.issuers_frame as i64); + let frame_begin = i64::from(self.block.number.0) - (self.block.issuers_frame as i64); let mut current_frame: HashMap<keys::ed25519::PublicKey, usize> = HashMap::new(); let mut cursor = db .0 diff --git a/dal/clippy.toml b/dal/clippy.toml new file mode 100644 index 0000000000000000000000000000000000000000..32d82dfbf950f5dc319caea82ce84904d3c18b3e --- /dev/null +++ b/dal/clippy.toml @@ -0,0 +1 @@ +cyclomatic-complexity-threshold = 35 \ No newline at end of file diff --git a/dal/dal_requests.rs b/dal/dal_requests.rs index efd50dc2b7b821c160ccfb44552396f63b86d4b5..a16cb3ad6909cd6e9130f152ca324b0395aea49c 100644 --- a/dal/dal_requests.rs +++ b/dal/dal_requests.rs @@ -50,14 +50,14 @@ pub enum DALResPendings { #[derive(Debug, Clone)] pub enum DALResBlockchain { - CurrentBlock(ModuleReqFullId, BlockDocument), - BlockByNumber(ModuleReqFullId, BlockDocument), + CurrentBlock(ModuleReqFullId, Box<BlockDocument>), + BlockByNumber(ModuleReqFullId, Box<BlockDocument>), Chunk(ModuleReqFullId, Vec<BlockDocument>), UIDs(HashMap<ed25519::PublicKey, Option<String>>), } #[derive(Debug, Clone)] pub enum DALResponse { - Blockchain(DALResBlockchain), + Blockchain(Box<DALResBlockchain>), Pendings(ModuleReqFullId, DALResPendings), } diff --git a/dal/identity.rs b/dal/identity.rs index 2486c628b3e9ff9ceeeb17fb42b06b52c6fbae7b..39193d905fe6df37adb887f6b535f72750fde00e 100644 --- a/dal/identity.rs +++ b/dal/identity.rs @@ -46,12 +46,7 @@ impl DALIdentity { cursor .bind(&[ sqlite::Value::Integer(i64::from(state)), - sqlite::Value::String( - expired_on - .clone() - .unwrap_or_else(Blockstamp::default) - .to_string(), - ), + sqlite::Value::String(expired_on.unwrap_or_else(Blockstamp::default).to_string()), sqlite::Value::Integer(wotb_id.0 as i64), ]) .expect("Fail to exclude idty !"); @@ -88,7 +83,7 @@ impl DALIdentity { hash: "0".to_string(), state: 0, joined_on: current_blockstamp, - penultimate_renewed_on: created_on.clone(), + penultimate_renewed_on: created_on, last_renewed_on: created_on, expires_on: created_time + super::constants::G1_PARAMS.ms_validity, revokes_on: created_time + super::constants::G1_PARAMS.ms_validity, @@ -136,11 +131,8 @@ impl DALIdentity { let mut penultimate_renewed_block: Option<DALBlock> = None; let revert_excluding = if revert { penultimate_renewed_block = Some( - DALBlock::get_block( - self.idty_doc.currency(), - db, - &self.penultimate_renewed_on.clone(), - ).expect("renewal_identity: Fail to get penultimate_renewed_block"), + DALBlock::get_block(self.idty_doc.currency(), db, &self.penultimate_renewed_on) + .expect("renewal_identity: Fail to get penultimate_renewed_block"), ); penultimate_renewed_block.clone().unwrap().block.median_time + super::constants::G1_PARAMS.ms_validity < renawal_timestamp diff --git a/dal/lib.rs b/dal/lib.rs index 7c1541dcc352dbe86ff8262f27ae691df90a9b81..ee81c95b5d3f1ac0ffb00a26c63b4663fb556060 100644 --- a/dal/lib.rs +++ b/dal/lib.rs @@ -47,7 +47,8 @@ pub mod writers; use duniter_crypto::keys::{PublicKey, Signature}; use duniter_documents::blockchain::v10::documents::BlockDocument; use duniter_documents::{BlockHash, BlockId, Blockstamp, Hash}; -use duniter_wotb::NodeId; +use duniter_wotb::operations::file::FileFormater; +use duniter_wotb::{NodeId, WebOfTrust}; use std::fmt::Debug; use std::marker; use std::path::PathBuf; @@ -236,6 +237,29 @@ pub fn get_current_block(currency: &str, db: &DuniterDB) -> Option<DALBlock> { } } +pub fn open_wot_file<W: WebOfTrust, WF: FileFormater>( + file_formater: &WF, + wot_path: &PathBuf, +) -> (W, Blockstamp) { + if wot_path.as_path().exists() { + match file_formater.from_file( + wot_path.as_path().to_str().unwrap(), + constants::G1_PARAMS.sig_stock as usize, + ) { + Ok((wot, binary_blockstamp)) => match ::std::str::from_utf8(&binary_blockstamp) { + Ok(str_blockstamp) => (wot, Blockstamp::from_string(str_blockstamp).unwrap()), + Err(e) => panic!("Invalid UTF-8 sequence: {}", e), + }, + Err(e) => panic!("Fatal Error : fail to read wot file : {:?}", e), + } + } else { + ( + W::new(constants::G1_PARAMS.sig_stock as usize), + Blockstamp::default(), + ) + } +} + pub fn register_wot_state(db: &DuniterDB, wot_state: &WotState) { if wot_state.block_number != 1 { db.0 diff --git a/dal/parsers/blocks.rs b/dal/parsers/blocks.rs index 780ff728f3cc4057a26ff2123f7f3f85eef6ff0b..a98fc21cd83c9986b4581f205eef792486f29a6a 100644 --- a/dal/parsers/blocks.rs +++ b/dal/parsers/blocks.rs @@ -7,11 +7,57 @@ use self::duniter_network::{NetworkBlock, NetworkBlockV10}; use super::excluded::parse_exclusions_from_json_value; use super::identities::parse_compact_identity; use super::transactions::parse_transaction; -use duniter_crypto::keys::{PublicKey, Signature}; -use duniter_documents::blockchain::v10::documents::membership::MembershipType; +use duniter_crypto::keys::{ed25519, PublicKey, Signature}; +use duniter_documents::blockchain::v10::documents::membership::{ + MembershipDocument, MembershipType, +}; use duniter_documents::blockchain::v10::documents::BlockDocument; use duniter_documents::{BlockHash, BlockId, Hash}; +fn parse_previous_hash(block_number: &BlockId, source: &serde_json::Value) -> Option<Hash> { + match source.get("previousHash")?.as_str() { + Some(hash_str) => match Hash::from_hex(hash_str) { + Ok(hash) => Some(hash), + Err(_) => None, + }, + None => if block_number.0 > 0 { + None + } else { + Some(Hash::default()) + }, + } +} + +fn parse_previous_issuer(source: &serde_json::Value) -> Option<ed25519::PublicKey> { + match source.get("previousIssuer")?.as_str() { + Some(pubkey_str) => match PublicKey::from_base58(pubkey_str) { + Ok(pubkey) => Some(pubkey), + Err(_) => None, + }, + None => None, + } +} + +fn parse_memberships( + currency: &str, + membership_type: MembershipType, + json_memberships: &serde_json::Value, +) -> Option<Vec<MembershipDocument>> { + let mut memberships = Vec::new(); + for membership in super::memberships::parse_memberships_from_json_value( + currency, + membership_type, + &json_memberships.as_array()?, + ) { + if let Ok(membership) = membership { + memberships.push(membership); + } else { + warn!("dal::parsers::blocks::parse_memberships() : MembershipParseError !") + } + } + Some(memberships) +} + pub fn parse_json_block(source: &serde_json::Value) -> Option<NetworkBlock> { let number = BlockId(source.get("number")?.as_u64()? as u32); let currency = source.get("currency")?.as_str()?.to_string(); @@ -27,28 +73,8 @@ pub fn parse_json_block(source: &serde_json::Value) -> Option<NetworkBlock> { Ok(hash) => hash, Err(_) => return None, }; - let previous_hash = match source.get("previousHash")?.as_str() { - Some(hash_str) => match Hash::from_hex(hash_str) { - Ok(hash) => hash, - Err(_) => return None, - }, - None => if number.0 > 0 { - return None; - } else { - Hash::default() - }, - }; - let previous_issuer = match source.get("previousIssuer")?.as_str() { - Some(pubkey_str) => match PublicKey::from_base58(pubkey_str) { - Ok(pubkey) => Some(pubkey), - Err(_) => return None, - }, - None => if number.0 > 0 { - return None; - } else { - None - }, - }; + let previous_hash = parse_previous_hash(&number, source)?; + let previous_issuer = parse_previous_issuer(source); let inner_hash = match Hash::from_hex(source.get("inner_hash")?.as_str()?) { Ok(hash) => Some(hash), Err(_) => return None, @@ -61,42 +87,9 @@ pub fn parse_json_block(source: &serde_json::Value) -> Option<NetworkBlock> { for raw_idty in source.get("identities")?.as_array()? { identities.push(parse_compact_identity(¤cy, &raw_idty)?); } - let mut joiners = Vec::new(); - for joiner in super::memberships::parse_memberships_from_json_value( - ¤cy, - MembershipType::In(), - &source.get("joiners")?.as_array()?, - ) { - if let Ok(joiner) = joiner { - joiners.push(joiner); - } else { - return None; - } - } - let mut actives = Vec::new(); - for active in super::memberships::parse_memberships_from_json_value( - ¤cy, - MembershipType::In(), - &source.get("actives")?.as_array()?, - ) { - if let Ok(active) = active { - actives.push(active); - } else { - return None; - } - } - let mut leavers = Vec::new(); - for leaver in super::memberships::parse_memberships_from_json_value( - ¤cy, - MembershipType::Out(), - &source.get("leavers")?.as_array()?, - ) { - if let Ok(leaver) = leaver { - leavers.push(leaver); - } else { - return None; - } - } + let joiners = parse_memberships(¤cy, MembershipType::In(), source.get("joiners")?)?; + let actives = parse_memberships(¤cy, MembershipType::In(), source.get("actives")?)?; + let leavers = parse_memberships(¤cy, MembershipType::Out(), source.get("actives")?)?; let mut transactions = Vec::new(); for json_tx in source.get("transactions")?.as_array()? { transactions.push(parse_transaction("g1", &json_tx)?); diff --git a/dal/parsers/certifications.rs b/dal/parsers/certifications.rs index a62b0a4ad73c69b00f27bff8ee42d97574b61048..19ffba84056de64d42d3c2c82810d7dbd3374287 100644 --- a/dal/parsers/certifications.rs +++ b/dal/parsers/certifications.rs @@ -17,7 +17,7 @@ use duniter_documents::{BlockHash, BlockId, Blockstamp, Hash}; use std::collections::HashMap; pub fn parse_certifications_into_compact( - json_certs: &Vec<serde_json::Value>, + json_certs: &[serde_json::Value], ) -> Vec<TextDocumentFormat<CertificationDocument>> { let mut certifications: Vec<TextDocumentFormat<CertificationDocument>> = Vec::new(); for certification in json_certs.iter() { diff --git a/dal/parsers/revoked.rs b/dal/parsers/revoked.rs index 28f12568284da1ef35e2e2583101000737babde5..75ab8c8e988674342927f8078328748d00e80f38 100644 --- a/dal/parsers/revoked.rs +++ b/dal/parsers/revoked.rs @@ -15,7 +15,7 @@ use super::super::DuniterDB; use std::collections::HashMap; pub fn parse_revocations_into_compact( - json_recocations: &Vec<serde_json::Value>, + json_recocations: &[serde_json::Value], ) -> Vec<TextDocumentFormat<RevocationDocument>> { let mut revocations: Vec<TextDocumentFormat<RevocationDocument>> = Vec::new(); for revocation in json_recocations.iter() { diff --git a/dal/writers/block.rs b/dal/writers/block.rs index aeb4d4d87415c38b6330c57d415032b79f03505b..6137156b51fce0ca2c9b0361828c0ce1d767c13d 100644 --- a/dal/writers/block.rs +++ b/dal/writers/block.rs @@ -15,8 +15,8 @@ pub fn write_network_block( block: &BlockDocument, fork: usize, isolate: bool, - revoked: &Vec<serde_json::Value>, - certifications: &Vec<serde_json::Value>, + revoked: &[serde_json::Value], + certifications: &[serde_json::Value], ) { db.0 .execute( diff --git a/dal/writers/certification.rs b/dal/writers/certification.rs index 03ec2db95ec3c77b0a9cdb7fb7acf4148b08342a..f42aac963315b1df527bdc8413db065f0a961921 100644 --- a/dal/writers/certification.rs +++ b/dal/writers/certification.rs @@ -20,7 +20,7 @@ pub fn write_certification( .cursor(); cursor - .bind(&[sqlite::Value::Integer(cert.block_number.0 as i64)]) + .bind(&[sqlite::Value::Integer(i64::from(cert.block_number.0))]) .expect("convert blockstamp to timestamp failure at step 1 !"); let mut created_timestamp: i64 = 0; diff --git a/dal/writers/requests.rs b/dal/writers/requests.rs index c48b36a3e385cd6cc6929fb42bcb248c235ce492..3edb71eeefe58308885e88668f05a976a0e57a4a 100644 --- a/dal/writers/requests.rs +++ b/dal/writers/requests.rs @@ -13,12 +13,13 @@ use self::duniter_wotb::NodeId; use super::super::block::DALBlock; use super::super::identity::DALIdentity; use super::super::DuniterDB; +use std::ops::Deref; #[derive(Debug)] /// Contain a pending write request for blockchain database pub enum DBWriteRequest { /// Newcomer - CreateIdentity(NodeId, Blockstamp, u64, IdentityDocument), + CreateIdentity(NodeId, Blockstamp, u64, Box<IdentityDocument>), /// Active RenewalIdentity(ed25519::PublicKey, Blockstamp, u64), /// Excluded @@ -30,9 +31,9 @@ pub enum DBWriteRequest { /// Certification expiry CertExpiry(NodeId, NodeId, Blockstamp, u64), /// Write block - WriteBlock(DALBlock), + WriteBlock(Box<DALBlock>), /// Revert block - RevertBlock(DALBlock), + RevertBlock(Box<DALBlock>), } impl DBWriteRequest { @@ -45,8 +46,8 @@ impl DBWriteRequest { ref idty_doc, ) => { trace!("DBWriteRequest::CreateIdentity..."); - let idty = DALIdentity::create_identity(db, idty_doc, blockstamp.clone()); - super::identity::write(&idty, wotb_id, db, blockstamp.clone(), *median_time); + let idty = DALIdentity::create_identity(db, idty_doc.deref(), *blockstamp); + super::identity::write(&idty, wotb_id, db, *blockstamp, *median_time); trace!("DBWriteRequest::CreateIdentity...finish."); } DBWriteRequest::RenewalIdentity(ref pubkey, ref blockstamp, ref median_time) => { @@ -67,12 +68,13 @@ impl DBWriteRequest { super::certification::write_certification( compact_cert, db, - blockstamp.clone(), + *blockstamp, *median_time, ); trace!("DBWriteRequest::CreateCert...finish"); } DBWriteRequest::WriteBlock(ref dal_block) => { + let dal_block = dal_block.deref(); trace!("DBWriteRequest::WriteBlock..."); super::block::write(db, &dal_block.block, dal_block.fork, dal_block.isolate); trace!("DBWriteRequest::WriteBlock...finish"); diff --git a/message/lib.rs b/message/lib.rs index f99560f56c18f75c029bdec43ac648b762d5fdd1..b0d3068ed2fc2ff89e6e3c48c4aa4be36f6fa95a 100644 --- a/message/lib.rs +++ b/message/lib.rs @@ -55,7 +55,7 @@ pub enum DuniterMessage { /// Blockchain datas request DALRequest(DALRequest), /// Response of DALRequest - DALResponse(DALResponse), + DALResponse(Box<DALResponse>), /// Blockchain event DALEvent(DALEvent), /// Request to the network module diff --git a/tui/lib.rs b/tui/lib.rs index deaf579464f81fff9f404a9626f0a36c40d351fa..a3d54cca706665d11c6411dddd98158dd5a85acb 100644 --- a/tui/lib.rs +++ b/tui/lib.rs @@ -44,6 +44,7 @@ use duniter_network::network_head::NetworkHead; use duniter_network::{NetworkEvent, NodeFullId}; use std::collections::HashMap; use std::io::{stdout, Write}; +use std::ops::Deref; use std::sync::mpsc; use std::thread; use std::time::{Duration, SystemTime}; @@ -60,7 +61,7 @@ pub struct TuiConf {} /// Format of messages received by the tui module pub enum TuiMess { /// Message from another module - DuniterMessage(DuniterMessage), + DuniterMessage(Box<DuniterMessage>), /// Message from stdin (user event) TermionEvent(Event), } @@ -185,7 +186,9 @@ impl TuiModuleDatas { } else { for (ref node_full_id, ref uid, ref url) in out_established_conns { line += 1; - let mut uid_string = uid.clone().unwrap_or(String::from("----------------")); + let mut uid_string = uid + .clone() + .unwrap_or_else(|| String::from("----------------")); uid_string.truncate(16); write!( stdout, @@ -398,26 +401,24 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for TuiModule { let tui_sender_clone = tui_sender.clone(); thread::spawn(move || { // Send proxy sender to main - match main_sender.send(RooterThreadMessage::ModuleSender(proxy_sender)) { - Ok(_) => { - debug!("Send tui sender to main thread."); - } - Err(_) => panic!("Fatal error : tui module fail to send is sender channel !"), - } + main_sender + .send(RooterThreadMessage::ModuleSender(proxy_sender)) + .expect("Fatal error : tui module fail to send is sender channel !"); + debug!("Send tui sender to main thread."); loop { match proxy_receiver.recv() { - Ok(message) => { - match tui_sender_clone.send(TuiMess::DuniterMessage(message.clone())) { - Ok(_) => { - if let DuniterMessage::Stop() = message { - break; - }; - } - Err(_) => debug!( - "tui proxy : fail to relay DuniterMessage to tui main thread !" - ), + Ok(message) => match tui_sender_clone + .send(TuiMess::DuniterMessage(Box::new(message.clone()))) + { + Ok(_) => { + if let DuniterMessage::Stop() = message { + break; + }; } - } + Err(_) => { + debug!("tui proxy : fail to relay DuniterMessage to tui main thread !") + } + }, Err(e) => { warn!("{}", e); break; @@ -447,16 +448,12 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for TuiModule { let stdin = std::io::stdin(); // Get stdin events for c in stdin.events() { - match tui_sender.send(TuiMess::TermionEvent( - c.expect("error to read stdin event !"), - )) { - Ok(_) => { - trace!("Send stdin event to tui main thread."); - } - Err(_) => { - panic!("Fatal error : tui stdin thread module fail to send message !") - } - } + tui_sender + .send(TuiMess::TermionEvent( + c.expect("error to read stdin event !"), + )) + .expect("Fatal error : tui stdin thread module fail to send message !"); + trace!("Send stdin event to tui main thread."); } }); @@ -465,19 +462,20 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for TuiModule { let mut user_event = false; // Get messages match tui_receiver.recv_timeout(Duration::from_millis(250)) { - Ok(ref message) => match message { - &TuiMess::DuniterMessage(ref duniter_message) => match duniter_message { - &DuniterMessage::Stop() => { - writeln!( - stdout, - "{}{}{}{}{}", - color::Fg(color::Reset), - cursor::Goto(1, 1), - color::Bg(color::Reset), - cursor::Show, - clear::All, - ).unwrap(); - let _result_stop_propagation: Result< + Ok(ref message) => match *message { + TuiMess::DuniterMessage(ref duniter_message) => { + match *duniter_message.deref() { + DuniterMessage::Stop() => { + writeln!( + stdout, + "{}{}{}{}{}", + color::Fg(color::Reset), + cursor::Goto(1, 1), + color::Bg(color::Reset), + cursor::Show, + clear::All, + ).unwrap(); + let _result_stop_propagation: Result< (), mpsc::SendError<DuniterMessage>, > = tui @@ -485,58 +483,62 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for TuiModule { .iter() .map(|f| f.send(DuniterMessage::Stop())) .collect(); - break; - } - &DuniterMessage::Followers(ref new_followers) => { - info!("Tui module receive followers !"); - for new_follower in new_followers { - debug!("TuiModule : push one follower."); - tui.followers.push(new_follower.clone()); - } - } - &DuniterMessage::DALEvent(ref dal_event) => match dal_event { - &DALEvent::StackUpValidBlock(ref _block) => {} - &DALEvent::RevertBlocks(ref _blocks) => {} - _ => {} - }, - &DuniterMessage::NetworkEvent(ref network_event) => match network_event { - &NetworkEvent::ConnectionStateChange( - ref node_full_id, - ref status, - ref uid, - ref url, - ) => { - if let Some(conn) = tui.connections_status.get(&node_full_id) { - if *status == 12 && (*conn).status != 12 { - tui.established_conns_count += 1; - } else if *status != 12 - && (*conn).status == 12 - && tui.established_conns_count > 0 - { - tui.established_conns_count -= 1; - } - }; - tui.connections_status.insert( - *node_full_id, - Connection { - status: *status, - url: url.clone(), - uid: uid.clone(), - }, - ); + break; } - &NetworkEvent::ReceiveHeads(ref heads) => { - heads - .iter() - .map(|h| tui.heads_cache.insert(h.node_full_id(), h.clone())) - .collect::<Vec<Option<NetworkHead>>>(); + DuniterMessage::Followers(ref new_followers) => { + info!("Tui module receive followers !"); + for new_follower in new_followers { + debug!("TuiModule : push one follower."); + tui.followers.push(new_follower.clone()); + } } + DuniterMessage::DALEvent(ref dal_event) => match *dal_event { + DALEvent::StackUpValidBlock(ref _block) => {} + DALEvent::RevertBlocks(ref _blocks) => {} + _ => {} + }, + DuniterMessage::NetworkEvent(ref network_event) => match *network_event + { + NetworkEvent::ConnectionStateChange( + ref node_full_id, + ref status, + ref uid, + ref url, + ) => { + if let Some(conn) = tui.connections_status.get(&node_full_id) { + if *status == 12 && (*conn).status != 12 { + tui.established_conns_count += 1; + } else if *status != 12 + && (*conn).status == 12 + && tui.established_conns_count > 0 + { + tui.established_conns_count -= 1; + } + }; + tui.connections_status.insert( + *node_full_id, + Connection { + status: *status, + url: url.clone(), + uid: uid.clone(), + }, + ); + } + NetworkEvent::ReceiveHeads(ref heads) => { + heads + .iter() + .map(|h| { + tui.heads_cache.insert(h.node_full_id(), h.clone()) + }) + .for_each(drop); + } + _ => {} + }, _ => {} - }, - _ => {} - }, - &TuiMess::TermionEvent(ref term_event) => match term_event { - &Event::Key(Key::Char('q')) => { + } + } + TuiMess::TermionEvent(ref term_event) => match *term_event { + Event::Key(Key::Char('q')) => { // Exit writeln!( stdout, @@ -557,9 +559,9 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for TuiModule { .collect(); break; } - &Event::Mouse(ref me) => match me { - &MouseEvent::Press(ref button, ref _a, ref _b) => match button { - &MouseButton::WheelDown => { + Event::Mouse(ref me) => match *me { + MouseEvent::Press(ref button, ref _a, ref _b) => match *button { + MouseButton::WheelDown => { // Get Terminal size let (_w, h) = termion::terminal_size() .expect("Fail to get terminal size !"); @@ -579,7 +581,7 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for TuiModule { } } } - &MouseButton::WheelUp => { + MouseButton::WheelUp => { // heads_index if tui.heads_index > 0 { tui.heads_index -= 1; @@ -588,8 +590,8 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for TuiModule { } _ => {} }, - &MouseEvent::Release(ref _a, ref _b) - | &MouseEvent::Hold(ref _a, ref _b) => {} + MouseEvent::Release(ref _a, ref _b) + | MouseEvent::Hold(ref _a, ref _b) => {} }, _ => {} }, diff --git a/ws2p/lib.rs b/ws2p/lib.rs index 91f8bf76def013126dc172bf0a11dadaaf4ff15a..2376fcba1c2da2ef8fb63586d4334fc0062eda77 100644 --- a/ws2p/lib.rs +++ b/ws2p/lib.rs @@ -16,6 +16,7 @@ //! Crate containing Duniter-rust core. #![cfg_attr(feature = "strict", deny(warnings))] +#![cfg_attr(feature = "cargo-clippy", allow(cyclomatic_complexity))] #![deny( missing_debug_implementations, missing_copy_implementations, trivial_casts, unsafe_code, unstable_features, unused_import_braces, unused_qualifications @@ -146,7 +147,7 @@ pub struct WS2PModuleDatas { #[derive(Debug)] pub enum WS2PThreadSignal { - DuniterMessage(DuniterMessage), + DuniterMessage(Box<DuniterMessage>), WS2PConnectionMessage(WS2PConnectionMessage), } @@ -160,19 +161,19 @@ pub trait WS2PMessage: Sized { //fn parse_and_verify(v: serde_json::Value, currency: String) -> bool; } -pub fn get_random_connection( - connections: &HashMap<NodeFullId, (NetworkEndpoint, WS2PConnectionState)>, +pub fn get_random_connection<S: ::std::hash::BuildHasher>( + connections: &HashMap<NodeFullId, (NetworkEndpoint, WS2PConnectionState), S>, ) -> NodeFullId { let mut rng = rand::thread_rng(); let mut loop_count = 0; loop { - for (ws2p_full_id, (_ep, state)) in connections.clone() { + for (ws2p_full_id, (_ep, state)) in &(*connections) { if loop_count > 10 { - return ws2p_full_id; + return *ws2p_full_id; } if let WS2PConnectionState::Established = state { if rng.gen::<bool>() { - return ws2p_full_id; + return *ws2p_full_id; } } } @@ -244,7 +245,7 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { ); info!("Load sync endpoint {}", ep.raw()); } - ws2p_module.key_pair = Some(key_pair.clone()); + ws2p_module.key_pair = Some(key_pair); ws2p_module.currency = Some(duniter_conf.currency().to_string()); ws2p_module.conf = Some(conf.clone()); ws2p_module.ws2p_endpoints = ws2p_endpoints; @@ -262,27 +263,22 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { // Launch a proxy thread that transform DuniterMessage to WS2PThreadSignal(DuniterMessage) thread::spawn(move || { // Send proxy sender to main - match rooter_sender.send(RooterThreadMessage::ModuleSender(proxy_sender_clone)) { - Ok(_) => { - debug!("Send ws2p sender to main thread."); - } - Err(_) => panic!("Fatal error : ws2p module fail to send is sender channel !"), - } - //drop(rooter_sender); + rooter_sender + .send(RooterThreadMessage::ModuleSender(proxy_sender_clone)) + .expect("Fatal error : ws2p module fail to send is sender channel !"); + debug!("Send ws2p sender to main thread."); loop { match proxy_receiver.recv() { - Ok(message) => match ws2p_sender_clone - .send(WS2PThreadSignal::DuniterMessage(message.clone())) - { - Ok(_) => { - if let DuniterMessage::Stop() = message { - break; - }; - } - Err(_) => panic!( - "Fatal error : fail to relay DuniterMessage to ws2p main thread !" - ), - }, + Ok(message) => { + ws2p_sender_clone + .send(WS2PThreadSignal::DuniterMessage(Box::new(message.clone()))) + .expect( + "Fatal error : fail to relay DuniterMessage to ws2p main thread !", + ); + if let DuniterMessage::Stop() = message { + break; + }; + } Err(e) => panic!(format!("{}", e)), } } @@ -292,12 +288,12 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { let mut db_path = duniter_conf::datas_path(duniter_conf.profile().as_str(), &duniter_conf.currency()); db_path.push("ws2p.db"); - let db = WS2PModuleDatas::open_db(db_path).expect("Fatal error : fail to open WS2P DB !"); + let db = WS2PModuleDatas::open_db(&db_path).expect("Fatal error : fail to open WS2P DB !"); // Get ws2p endpoints in BDD let mut count = 0; let dal_enpoints = - ws2p_db::get_endpoints_for_api(&db, NetworkEndpointApi(String::from("WS2P"))); + ws2p_db::get_endpoints_for_api(&db, &NetworkEndpointApi(String::from("WS2P"))); for ep in dal_enpoints { if ep.api() == NetworkEndpointApi(String::from("WS2P")) && ep.port() != 443 { count += 1; @@ -332,9 +328,9 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { { Ok(message) => match message { WS2PThreadSignal::DuniterMessage(ref duniter_mesage) => { - match duniter_mesage { - &DuniterMessage::Stop() => break, - &DuniterMessage::Followers(ref new_followers) => { + match *duniter_mesage.deref() { + DuniterMessage::Stop() => break, + DuniterMessage::Followers(ref new_followers) => { info!("WS2P module receive followers !"); for new_follower in new_followers { debug!("WS2PModule : push one follower."); @@ -353,7 +349,7 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { if ws2p_module.my_head.is_none() { ws2p_module.my_head = Some(WS2PModuleDatas::generate_my_head( - &key_pair.clone(), + &key_pair, &conf.clone(), soft_name, soft_version, @@ -369,8 +365,8 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { } } } - &DuniterMessage::NetworkRequest(ref request) => match request { - &NetworkRequest::GetBlocks( + DuniterMessage::NetworkRequest(ref request) => match *request { + NetworkRequest::GetBlocks( ref req_id, ref receiver, ref count, @@ -408,10 +404,7 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { .send_request_to_specific_node( &real_receiver, &NetworkRequest::GetBlocks( - req_id.clone(), - receiver.clone(), - count.clone(), - from.clone(), + *req_id, *receiver, *count, *from, ), ); } else { @@ -422,25 +415,23 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { .send_request_to_specific_node( &receiver, &NetworkRequest::GetBlocks( - req_id.clone(), - receiver.clone(), - count.clone(), - from.clone(), + *req_id, *receiver, *count, *from, ), ); } } + NetworkRequest::GetEndpoints(ref _request) => {} _ => {} }, - &DuniterMessage::DALEvent(ref dal_event) => match dal_event { - &DALEvent::StackUpValidBlock(ref block) => { + DuniterMessage::DALEvent(ref dal_event) => match *dal_event { + DALEvent::StackUpValidBlock(ref block) => { current_blockstamp = block.deref().blockstamp(); debug!( "WS2PModule : current_blockstamp = {}", current_blockstamp ); ws2p_module.my_head = Some(WS2PModuleDatas::generate_my_head( - &key_pair.clone(), + &key_pair, &conf.clone(), soft_name, soft_version, @@ -473,79 +464,86 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { }) .collect(); } + DALEvent::RevertBlocks(ref _blocks) => {} _ => {} }, - &DuniterMessage::DALResponse(ref dal_res) => match dal_res { - &DALResponse::Blockchain(ref dal_res_bc) => match dal_res_bc { - &DALResBlockchain::CurrentBlock( - ref _requester_full_id, - ref current_block, - ) => { - debug!( - "WS2PModule : receive DALResBc::CurrentBlock({})", - current_block.blockstamp() - ); - current_blockstamp = current_block.blockstamp(); - if ws2p_module.my_head.is_none() { - ws2p_module.my_head = - Some(WS2PModuleDatas::generate_my_head( - &key_pair.clone(), - &conf.clone(), - soft_name, - soft_version, - ¤t_blockstamp, - None, - )); + DuniterMessage::DALResponse(ref dal_res) => match *dal_res.deref() { + DALResponse::Blockchain(ref dal_res_bc) => { + match *dal_res_bc.deref() { + DALResBlockchain::CurrentBlock( + ref _requester_full_id, + ref current_block, + ) => { + let current_block = current_block.deref(); + debug!( + "WS2PModule : receive DALResBc::CurrentBlock({})", + current_block.blockstamp() + ); + current_blockstamp = current_block.blockstamp(); + if ws2p_module.my_head.is_none() { + ws2p_module.my_head = + Some(WS2PModuleDatas::generate_my_head( + &key_pair, + &conf.clone(), + soft_name, + soft_version, + ¤t_blockstamp, + None, + )); + } + ws2p_module.send_network_event( + &NetworkEvent::ReceiveHeads(vec![ + ws2p_module.my_head.clone().unwrap(), + ]), + ); } - ws2p_module.send_network_event( - &NetworkEvent::ReceiveHeads(vec![ - ws2p_module.my_head.clone().unwrap(), - ]), - ); - } - &DALResBlockchain::UIDs(ref uids) => { - // Add uids to heads - for (_, head) in ws2p_module.heads_cache.iter_mut() { - if let Some(uid_option) = uids.get(&head.pubkey()) { - if let &Some(ref uid) = uid_option { - head.set_uid(uid); - ws2p_module - .uids_cache - .insert(head.pubkey(), uid.to_string()); - } else { - ws2p_module.uids_cache.remove(&head.pubkey()); + DALResBlockchain::UIDs(ref uids) => { + // Add uids to heads + for head in ws2p_module.heads_cache.values_mut() { + if let Some(uid_option) = uids.get(&head.pubkey()) { + if let Some(ref uid) = *uid_option { + head.set_uid(uid); + ws2p_module + .uids_cache + .insert(head.pubkey(), uid.to_string()); + } else { + ws2p_module + .uids_cache + .remove(&head.pubkey()); + } } } - } - // Resent heads to other modules - ws2p_module.send_network_event( - &NetworkEvent::ReceiveHeads( - ws2p_module - .heads_cache - .values() - .map(|h| h.clone()) - .collect(), - ), - ); - // Resent to other modules connections that match receive uids - for (node_full_id, (ep, conn_state)) in - ws2p_module.ws2p_endpoints.clone() - { - if let Some(uid_option) = uids.get(&node_full_id.1) { - ws2p_module.send_network_event( - &NetworkEvent::ConnectionStateChange( - node_full_id, - conn_state as u32, - uid_option.clone(), - ep.get_url(false), - ), - ); + // Resent heads to other modules + ws2p_module.send_network_event( + &NetworkEvent::ReceiveHeads( + ws2p_module + .heads_cache + .values() + .cloned() + .collect(), + ), + ); + // Resent to other modules connections that match receive uids + for (node_full_id, (ep, conn_state)) in + ws2p_module.ws2p_endpoints.clone() + { + if let Some(uid_option) = uids.get(&node_full_id.1) + { + ws2p_module.send_network_event( + &NetworkEvent::ConnectionStateChange( + node_full_id, + conn_state as u32, + uid_option.clone(), + ep.get_url(false), + ), + ); + } } } + _ => {} } - _ => {} - }, - _ => {} + } + DALResponse::Pendings(_, _) => {} }, _ => {} } @@ -574,12 +572,7 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { ws2p_full_id, WS2PConnectionState::Established as u32, ws2p_module.uids_cache.get(&ws2p_full_id.1).cloned(), - ws2p_module - .ws2p_endpoints - .get(&ws2p_full_id) - .unwrap() - .0 - .get_url(false), + ws2p_module.ws2p_endpoints[&ws2p_full_id].0.get_url(false), )); } WS2PSignal::WSError(ws2p_full_id) => { @@ -588,12 +581,7 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { ws2p_full_id, WS2PConnectionState::WSError as u32, ws2p_module.uids_cache.get(&ws2p_full_id.1).cloned(), - ws2p_module - .ws2p_endpoints - .get(&ws2p_full_id) - .unwrap() - .0 - .get_url(false), + ws2p_module.ws2p_endpoints[&ws2p_full_id].0.get_url(false), )); } WS2PSignal::NegociationTimeout(ws2p_full_id) => { @@ -602,12 +590,7 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { ws2p_full_id, WS2PConnectionState::Denial as u32, ws2p_module.uids_cache.get(&ws2p_full_id.1).cloned(), - ws2p_module - .ws2p_endpoints - .get(&ws2p_full_id) - .unwrap() - .0 - .get_url(false), + ws2p_module.ws2p_endpoints[&ws2p_full_id].0.get_url(false), )); } WS2PSignal::Timeout(ws2p_full_id) => { @@ -616,12 +599,7 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { ws2p_full_id, WS2PConnectionState::Close as u32, ws2p_module.uids_cache.get(&ws2p_full_id.1).cloned(), - ws2p_module - .ws2p_endpoints - .get(&ws2p_full_id) - .unwrap() - .0 - .get_url(false), + ws2p_module.ws2p_endpoints[&ws2p_full_id].0.get_url(false), )); } WS2PSignal::PeerCard(_ws2p_full_id, _peer_card, ws2p_endpoints) => { @@ -643,7 +621,7 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { SystemTime::now(), ); } - ws2p_module.connect_to(ep); + ws2p_module.connect_to(&ep); } }; } @@ -926,7 +904,7 @@ impl DuniterModule<ed25519::KeyPair, DuniterMessage> for WS2PModule { } impl WS2PModuleDatas { - fn open_db(db_path: PathBuf) -> Result<sqlite::Connection, sqlite::Error> { + fn open_db(db_path: &PathBuf) -> Result<sqlite::Connection, sqlite::Error> { let conn: sqlite::Connection; if !db_path.as_path().exists() { conn = sqlite::open(db_path.as_path())?; @@ -1000,9 +978,11 @@ impl WS2PModuleDatas { } pub fn send_dal_request(&self, req: &DALRequest) { for follower in &self.followers { - match follower.send(DuniterMessage::DALRequest(req.clone())) { - Ok(_) => {} - Err(_) => {} + if follower + .send(DuniterMessage::DALRequest(req.clone())) + .is_err() + { + // handle error } } } @@ -1030,7 +1010,7 @@ impl WS2PModuleDatas { api: String::from("WS2POCA"), version: 1, pubkey: network_keypair.pubkey, - blockstamp: my_current_blockstamp.clone(), + blockstamp: *my_current_blockstamp, node_uuid: conf.node_id, software: String::from(soft_name), soft_version: String::from(soft_version), @@ -1042,7 +1022,7 @@ impl WS2PModuleDatas { api: String::from("WS2POCA"), version: 2, pubkey: network_keypair.pubkey, - blockstamp: my_current_blockstamp.clone(), + blockstamp: *my_current_blockstamp, node_uuid: conf.node_id, software: String::from(soft_name), soft_version: String::from(soft_version), @@ -1078,15 +1058,15 @@ impl WS2PModuleDatas { *occurences_mut += 1; if *occurences > dominant_blockstamp_occurences { dominant_blockstamp_occurences = *occurences; - dominant_blockstamp = head.blockstamp().clone(); + dominant_blockstamp = head.blockstamp(); } } None => { - blockstamps_occurences.insert(head.blockstamp().clone(), 0); + blockstamps_occurences.insert(head.blockstamp(), 0); } } if head.blockstamp().id.0 > farthest_blockstamp.id.0 { - farthest_blockstamp = head.blockstamp().clone(); + farthest_blockstamp = head.blockstamp(); } } if count_known_blockstamps < 5 { @@ -1130,11 +1110,11 @@ impl WS2PModuleDatas { } else { break; }; - self.connect_to_without_checking_quotas(ep); + self.connect_to_without_checking_quotas(&ep); free_outcoming_rooms -= 1; } } - pub fn connect_to(&mut self, endpoint: NetworkEndpoint) -> () { + pub fn connect_to(&mut self, endpoint: &NetworkEndpoint) -> () { // Add endpoint to endpoints list (if there isn't already) match self.ws2p_endpoints.get(&endpoint.node_full_id().unwrap()) { Some(_) => { @@ -1151,7 +1131,7 @@ impl WS2PModuleDatas { } }; if self.conf.clone().unwrap().outcoming_quota > self.count_established_connections() { - self.connect_to_without_checking_quotas(endpoint); + self.connect_to_without_checking_quotas(&endpoint); } } fn close_connection(&mut self, ws2p_full_id: &NodeFullId, reason: WS2PCloseConnectionReason) { @@ -1254,14 +1234,13 @@ impl WS2PModuleDatas { let mut applied_heads = Vec::with_capacity(heads.len()); for head in heads { if let Some(head) = NetworkHead::from_json_value(&head) { - if head.verify() { - if (self.my_head.is_none() + if head.verify() + && (self.my_head.is_none() || head.node_full_id() != self.my_head.clone().unwrap().node_full_id()) - && head.apply(&mut self.heads_cache) - { - applied_heads.push(head); - } + && head.apply(&mut self.heads_cache) + { + applied_heads.push(head); } } } @@ -1277,7 +1256,7 @@ impl WS2PModuleDatas { { return WS2PSignal::ReqResponse( req_id, - ws2p_request.clone(), + *ws2p_request, *recipient_fulld_id, response, ); @@ -1353,13 +1332,13 @@ impl WS2PModuleDatas { ) -> Result<(), SendRequestError> { let mut count_successful_sending: usize = 0; let mut errors: Vec<websocket::WebSocketError> = Vec::new(); - match ws2p_request.clone() { + match *ws2p_request { NetworkRequest::GetCurrent(req_full_id, _receiver) => { for (ws2p_full_id, (_ep, state)) in self.ws2p_endpoints.clone() { if let WS2PConnectionState::Established = state { let ws2p_request = NetworkRequest::GetCurrent( ModuleReqFullId( - req_full_id.clone().0, + req_full_id.0, ModuleReqId( (self.requests_awaiting_response.len() + count_successful_sending) @@ -1382,7 +1361,7 @@ impl WS2PModuleDatas { if let WS2PConnectionState::Established = state { let ws2p_request = NetworkRequest::GetRequirementsPending( ModuleReqFullId( - req_full_id.clone().0, + req_full_id.0, ModuleReqId(self.requests_awaiting_response.len() as u32), ), ws2p_full_id, @@ -1420,11 +1399,7 @@ impl WS2PModuleDatas { ))?; self.requests_awaiting_response.insert( ws2p_request.get_req_id(), - ( - ws2p_request.clone(), - *receiver_ws2p_full_id, - SystemTime::now(), - ), + (*ws2p_request, *receiver_ws2p_full_id, SystemTime::now()), ); debug!( "send request {} to {}", @@ -1434,7 +1409,7 @@ impl WS2PModuleDatas { Ok(()) } - fn connect_to_without_checking_quotas(&mut self, endpoint: NetworkEndpoint) -> () { + fn connect_to_without_checking_quotas(&mut self, endpoint: &NetworkEndpoint) -> () { // update connection state self.ws2p_endpoints .get_mut(&endpoint.node_full_id().unwrap()) @@ -1883,7 +1858,7 @@ mod tests { if test_db_path.as_path().exists() { fs::remove_file(&test_db_path).unwrap(); } - let db = WS2PModuleDatas::open_db(test_db_path).unwrap(); + let db = WS2PModuleDatas::open_db(&test_db_path).unwrap(); let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); @@ -1897,14 +1872,14 @@ mod tests { ws2p_db::write_endpoint(&db, &endpoint, 1, current_time.as_secs()); let mut written_endpoints = - ws2p_db::get_endpoints_for_api(&db, NetworkEndpointApi(String::from("WS2P"))); + ws2p_db::get_endpoints_for_api(&db, &NetworkEndpointApi(String::from("WS2P"))); assert_eq!(endpoint, written_endpoints.pop().unwrap()); // Test status update endpoint.set_status(3); ws2p_db::write_endpoint(&db, &endpoint, 3, current_time.as_secs()); let mut written_endpoints = - ws2p_db::get_endpoints_for_api(&db, NetworkEndpointApi(String::from("WS2P"))); + ws2p_db::get_endpoints_for_api(&db, &NetworkEndpointApi(String::from("WS2P"))); assert_eq!(endpoint, written_endpoints.pop().unwrap()); } diff --git a/ws2p/ws2p_connection.rs b/ws2p/ws2p_connection.rs index a36f820971f15c46b5774c90dd338cc2bc570ad3..cad367e93a8b85eaf569f59b14822eb9cb909f08 100644 --- a/ws2p/ws2p_connection.rs +++ b/ws2p/ws2p_connection.rs @@ -183,7 +183,7 @@ impl WS2PConnectionMetaData { response.signature = Some(response.sign(key_pair)); return WS2PConnectionMessagePayload::ValidConnectMessage( serde_json::to_string(&response).unwrap(), - self.state.clone(), + self.state, ); } _ => return WS2PConnectionMessagePayload::InvalidMessage, @@ -216,7 +216,7 @@ impl WS2PConnectionMetaData { response.signature = Some(response.sign(key_pair)); return WS2PConnectionMessagePayload::ValidAckMessage( serde_json::to_string(&response).unwrap(), - self.state.clone(), + self.state, ); } else { warn!("The signature of message ACK is invalid !") @@ -233,9 +233,7 @@ impl WS2PConnectionMetaData { match self.state { WS2PConnectionState::ConnectMessOk => { self.state = WS2PConnectionState::OkMessOkWaitingAckMess; - return WS2PConnectionMessagePayload::ValidOk( - self.state.clone(), - ); + return WS2PConnectionMessagePayload::ValidOk(self.state); } WS2PConnectionState::AckMessOk => { info!( @@ -243,9 +241,7 @@ impl WS2PConnectionMetaData { self.remote_pubkey.expect("fail to get remote pubkey !") ); self.state = WS2PConnectionState::Established; - return WS2PConnectionMessagePayload::ValidOk( - self.state.clone(), - ); + return WS2PConnectionMessagePayload::ValidOk(self.state); } _ => { warn!("WS2P Error : OK message not expected !"); diff --git a/ws2p/ws2p_db.rs b/ws2p/ws2p_db.rs index f487710d74802ccdec80588d990b7285d9fb9697..ea6b9c41a3fbdf8cf962a8cbd93660d501ce8756 100644 --- a/ws2p/ws2p_db.rs +++ b/ws2p/ws2p_db.rs @@ -54,7 +54,7 @@ pub fn api_to_integer(api: &NetworkEndpointApi) -> i64 { pub fn get_endpoints_for_api( db: &sqlite::Connection, - api: NetworkEndpointApi, + api: &NetworkEndpointApi, ) -> Vec<NetworkEndpoint> { let mut cursor:sqlite::Cursor = db .prepare("SELECT hash_full_id, status, node_id, pubkey, api, version, endpoint, last_check FROM endpoints WHERE api=? ORDER BY status DESC;") @@ -119,9 +119,8 @@ pub fn write_endpoint( hash_full_id )).expect("Fail to parse SQL request update endpoint status !"); } - } else { - if let &NetworkEndpoint::V1(ref ep_v1) = endpoint { - db + } else if let NetworkEndpoint::V1(ref ep_v1) = *endpoint { + db .execute( format!( "INSERT INTO endpoints (hash_full_id, status, node_id, pubkey, api, version, endpoint, last_check) VALUES ('{}', {}, {}, '{}', {}, {}, '{}', {});", @@ -131,8 +130,7 @@ pub fn write_endpoint( ) ) .expect("Fail to parse SQL request INSERT endpoint !"); - } else { - panic!("write_endpoint() : Endpoint version is not supported !") - } + } else { + panic!("write_endpoint() : Endpoint version is not supported !") } }