├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md └── src ├── main.rs └── p2p.rs /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | 13 | # Added by cargo 14 | 15 | /target 16 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust-blockchain-example" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | chrono = "0.4" 10 | sha2 = "0.9.8" 11 | serde = {version = "1.0", features = ["derive"] } 12 | serde_json = "1.0" 13 | libp2p = { version = "0.39", features = ["tcp-tokio", "mdns"] } 14 | tokio = { version = "1.0", features = ["io-util", "io-std", "macros", "rt", "rt-multi-thread", "sync", "time"] } 15 | hex = "0.4" 16 | once_cell = "1.5" 17 | log = "0.4" 18 | pretty_env_logger = "0.4" 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rust-blockchain-example 2 | 3 | Simple example for building a blockchain in Rust 4 | 5 | Start using 6 | 7 | ```bash 8 | RUST_LOG=info cargo run 9 | ``` 10 | 11 | This starts the client locally. The blockchain is not persisted anywhere. 12 | 13 | You can start it in multiple terminals to get multiple connected peer-to-peer clients. 14 | 15 | In each client, you can enter the following commands: 16 | 17 | * `ls p` - list peers 18 | * `ls c` - print local chain 19 | * `create b $data` - `$data` is just a string here - this creates (mines) a new block with the data entry `$data` and broadcasts it 20 | 21 | Once a block is created by a node, it's broadcasted and the blockchain in all other nodes is updated (if it's a valid block). 22 | 23 | On startup, a node asks another node on the network for their blockchain and, if it's valid and longer than the current local blockchain, it updates it's own chain to the longest one it receives. 24 | 25 | 26 | This is a VERY overly simplified, offline-running, highly inefficient and insecure blockchain implementation. If a node gets out of sync, it's broken. This is an example for showing some of the concepts behind building a blockchain system in Rust, so it shouldn't be used anywhere near a production scenario, but you can have fun with it and learn something. :) 27 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use chrono::prelude::*; 2 | use libp2p::{ 3 | core::upgrade, 4 | futures::StreamExt, 5 | mplex, 6 | noise::{Keypair, NoiseConfig, X25519Spec}, 7 | swarm::{Swarm, SwarmBuilder}, 8 | tcp::TokioTcpConfig, 9 | Transport, 10 | }; 11 | use log::{error, info, warn}; 12 | use serde::{Deserialize, Serialize}; 13 | use sha2::{Digest, Sha256}; 14 | use std::time::Duration; 15 | use tokio::{ 16 | io::{stdin, AsyncBufReadExt, BufReader}, 17 | select, spawn, 18 | sync::mpsc, 19 | time::sleep, 20 | }; 21 | 22 | const DIFFICULTY_PREFIX: &str = "00"; 23 | 24 | mod p2p; 25 | 26 | pub struct App { 27 | pub blocks: Vec, 28 | } 29 | 30 | #[derive(Serialize, Deserialize, Debug, Clone)] 31 | pub struct Block { 32 | pub id: u64, 33 | pub hash: String, 34 | pub previous_hash: String, 35 | pub timestamp: i64, 36 | pub data: String, 37 | pub nonce: u64, 38 | } 39 | 40 | impl Block { 41 | pub fn new(id: u64, previous_hash: String, data: String) -> Self { 42 | let now = Utc::now(); 43 | let (nonce, hash) = mine_block(id, now.timestamp(), &previous_hash, &data); 44 | Self { 45 | id, 46 | hash, 47 | timestamp: now.timestamp(), 48 | previous_hash, 49 | data, 50 | nonce, 51 | } 52 | } 53 | } 54 | 55 | fn calculate_hash(id: u64, timestamp: i64, previous_hash: &str, data: &str, nonce: u64) -> Vec { 56 | let data = serde_json::json!({ 57 | "id": id, 58 | "previous_hash": previous_hash, 59 | "data": data, 60 | "timestamp": timestamp, 61 | "nonce": nonce 62 | }); 63 | let mut hasher = Sha256::new(); 64 | hasher.update(data.to_string().as_bytes()); 65 | hasher.finalize().as_slice().to_owned() 66 | } 67 | 68 | fn mine_block(id: u64, timestamp: i64, previous_hash: &str, data: &str) -> (u64, String) { 69 | info!("mining block..."); 70 | let mut nonce = 0; 71 | 72 | loop { 73 | if nonce % 100000 == 0 { 74 | info!("nonce: {}", nonce); 75 | } 76 | let hash = calculate_hash(id, timestamp, previous_hash, data, nonce); 77 | let binary_hash = hash_to_binary_representation(&hash); 78 | if binary_hash.starts_with(DIFFICULTY_PREFIX) { 79 | info!( 80 | "mined! nonce: {}, hash: {}, binary hash: {}", 81 | nonce, 82 | hex::encode(&hash), 83 | binary_hash 84 | ); 85 | return (nonce, hex::encode(hash)); 86 | } 87 | nonce += 1; 88 | } 89 | } 90 | 91 | fn hash_to_binary_representation(hash: &[u8]) -> String { 92 | let mut res: String = String::default(); 93 | for c in hash { 94 | res.push_str(&format!("{:b}", c)); 95 | } 96 | res 97 | } 98 | 99 | impl App { 100 | fn new() -> Self { 101 | Self { blocks: vec![] } 102 | } 103 | 104 | fn genesis(&mut self) { 105 | let genesis_block = Block { 106 | id: 0, 107 | timestamp: Utc::now().timestamp(), 108 | previous_hash: String::from("genesis"), 109 | data: String::from("genesis!"), 110 | nonce: 2836, 111 | hash: "0000f816a87f806bb0073dcf026a64fb40c946b5abee2573702828694d5b4c43".to_string(), 112 | }; 113 | self.blocks.push(genesis_block); 114 | } 115 | 116 | fn try_add_block(&mut self, block: Block) { 117 | let latest_block = self.blocks.last().expect("there is at least one block"); 118 | if self.is_block_valid(&block, latest_block) { 119 | self.blocks.push(block); 120 | } else { 121 | error!("could not add block - invalid"); 122 | } 123 | } 124 | 125 | fn is_block_valid(&self, block: &Block, previous_block: &Block) -> bool { 126 | if block.previous_hash != previous_block.hash { 127 | warn!("block with id: {} has wrong previous hash", block.id); 128 | return false; 129 | } else if !hash_to_binary_representation( 130 | &hex::decode(&block.hash).expect("can decode from hex"), 131 | ) 132 | .starts_with(DIFFICULTY_PREFIX) 133 | { 134 | warn!("block with id: {} has invalid difficulty", block.id); 135 | return false; 136 | } else if block.id != previous_block.id + 1 { 137 | warn!( 138 | "block with id: {} is not the next block after the latest: {}", 139 | block.id, previous_block.id 140 | ); 141 | return false; 142 | } else if hex::encode(calculate_hash( 143 | block.id, 144 | block.timestamp, 145 | &block.previous_hash, 146 | &block.data, 147 | block.nonce, 148 | )) != block.hash 149 | { 150 | warn!("block with id: {} has invalid hash", block.id); 151 | return false; 152 | } 153 | true 154 | } 155 | 156 | fn is_chain_valid(&self, chain: &[Block]) -> bool { 157 | for i in 0..chain.len() { 158 | if i == 0 { 159 | continue; 160 | } 161 | let first = chain.get(i - 1).expect("has to exist"); 162 | let second = chain.get(i).expect("has to exist"); 163 | if !self.is_block_valid(second, first) { 164 | return false; 165 | } 166 | } 167 | true 168 | } 169 | 170 | // We always choose the longest valid chain 171 | fn choose_chain(&mut self, local: Vec, remote: Vec) -> Vec { 172 | let is_local_valid = self.is_chain_valid(&local); 173 | let is_remote_valid = self.is_chain_valid(&remote); 174 | 175 | if is_local_valid && is_remote_valid { 176 | if local.len() >= remote.len() { 177 | local 178 | } else { 179 | remote 180 | } 181 | } else if is_remote_valid && !is_local_valid { 182 | remote 183 | } else if !is_remote_valid && is_local_valid { 184 | local 185 | } else { 186 | panic!("local and remote chains are both invalid"); 187 | } 188 | } 189 | } 190 | 191 | #[tokio::main] 192 | async fn main() { 193 | pretty_env_logger::init(); 194 | 195 | info!("Peer Id: {}", p2p::PEER_ID.clone()); 196 | let (response_sender, mut response_rcv) = mpsc::unbounded_channel(); 197 | let (init_sender, mut init_rcv) = mpsc::unbounded_channel(); 198 | 199 | let auth_keys = Keypair::::new() 200 | .into_authentic(&p2p::KEYS) 201 | .expect("can create auth keys"); 202 | 203 | let transp = TokioTcpConfig::new() 204 | .upgrade(upgrade::Version::V1) 205 | .authenticate(NoiseConfig::xx(auth_keys).into_authenticated()) 206 | .multiplex(mplex::MplexConfig::new()) 207 | .boxed(); 208 | 209 | let behaviour = p2p::AppBehaviour::new(App::new(), response_sender, init_sender.clone()).await; 210 | 211 | let mut swarm = SwarmBuilder::new(transp, behaviour, *p2p::PEER_ID) 212 | .executor(Box::new(|fut| { 213 | spawn(fut); 214 | })) 215 | .build(); 216 | 217 | let mut stdin = BufReader::new(stdin()).lines(); 218 | 219 | Swarm::listen_on( 220 | &mut swarm, 221 | "/ip4/0.0.0.0/tcp/0" 222 | .parse() 223 | .expect("can get a local socket"), 224 | ) 225 | .expect("swarm can be started"); 226 | 227 | spawn(async move { 228 | sleep(Duration::from_secs(1)).await; 229 | info!("sending init event"); 230 | init_sender.send(true).expect("can send init event"); 231 | }); 232 | 233 | loop { 234 | let evt = { 235 | select! { 236 | line = stdin.next_line() => Some(p2p::EventType::Input(line.expect("can get line").expect("can read line from stdin"))), 237 | response = response_rcv.recv() => { 238 | Some(p2p::EventType::LocalChainResponse(response.expect("response exists"))) 239 | }, 240 | _init = init_rcv.recv() => { 241 | Some(p2p::EventType::Init) 242 | } 243 | event = swarm.select_next_some() => { 244 | info!("Unhandled Swarm Event: {:?}", event); 245 | None 246 | }, 247 | } 248 | }; 249 | 250 | if let Some(event) = evt { 251 | match event { 252 | p2p::EventType::Init => { 253 | let peers = p2p::get_list_peers(&swarm); 254 | swarm.behaviour_mut().app.genesis(); 255 | 256 | info!("connected nodes: {}", peers.len()); 257 | if !peers.is_empty() { 258 | let req = p2p::LocalChainRequest { 259 | from_peer_id: peers 260 | .iter() 261 | .last() 262 | .expect("at least one peer") 263 | .to_string(), 264 | }; 265 | 266 | let json = serde_json::to_string(&req).expect("can jsonify request"); 267 | swarm 268 | .behaviour_mut() 269 | .floodsub 270 | .publish(p2p::CHAIN_TOPIC.clone(), json.as_bytes()); 271 | } 272 | } 273 | p2p::EventType::LocalChainResponse(resp) => { 274 | let json = serde_json::to_string(&resp).expect("can jsonify response"); 275 | swarm 276 | .behaviour_mut() 277 | .floodsub 278 | .publish(p2p::CHAIN_TOPIC.clone(), json.as_bytes()); 279 | } 280 | p2p::EventType::Input(line) => match line.as_str() { 281 | "ls p" => p2p::handle_print_peers(&swarm), 282 | cmd if cmd.starts_with("ls c") => p2p::handle_print_chain(&swarm), 283 | cmd if cmd.starts_with("create b") => p2p::handle_create_block(cmd, &mut swarm), 284 | _ => error!("unknown command"), 285 | }, 286 | } 287 | } 288 | } 289 | } 290 | -------------------------------------------------------------------------------- /src/p2p.rs: -------------------------------------------------------------------------------- 1 | use super::{App, Block}; 2 | use libp2p::{ 3 | floodsub::{Floodsub, FloodsubEvent, Topic}, 4 | identity, 5 | mdns::{Mdns, MdnsEvent}, 6 | swarm::{NetworkBehaviourEventProcess, Swarm}, 7 | NetworkBehaviour, PeerId, 8 | }; 9 | use log::{error, info}; 10 | use once_cell::sync::Lazy; 11 | use serde::{Deserialize, Serialize}; 12 | use std::collections::HashSet; 13 | use tokio::sync::mpsc; 14 | 15 | pub static KEYS: Lazy = Lazy::new(identity::Keypair::generate_ed25519); 16 | pub static PEER_ID: Lazy = Lazy::new(|| PeerId::from(KEYS.public())); 17 | pub static CHAIN_TOPIC: Lazy = Lazy::new(|| Topic::new("chains")); 18 | pub static BLOCK_TOPIC: Lazy = Lazy::new(|| Topic::new("blocks")); 19 | 20 | #[derive(Debug, Serialize, Deserialize)] 21 | pub struct ChainResponse { 22 | pub blocks: Vec, 23 | pub receiver: String, 24 | } 25 | 26 | #[derive(Debug, Serialize, Deserialize)] 27 | pub struct LocalChainRequest { 28 | pub from_peer_id: String, 29 | } 30 | 31 | pub enum EventType { 32 | LocalChainResponse(ChainResponse), 33 | Input(String), 34 | Init, 35 | } 36 | 37 | #[derive(NetworkBehaviour)] 38 | pub struct AppBehaviour { 39 | pub floodsub: Floodsub, 40 | pub mdns: Mdns, 41 | #[behaviour(ignore)] 42 | pub response_sender: mpsc::UnboundedSender, 43 | #[behaviour(ignore)] 44 | pub init_sender: mpsc::UnboundedSender, 45 | #[behaviour(ignore)] 46 | pub app: App, 47 | } 48 | 49 | impl AppBehaviour { 50 | pub async fn new( 51 | app: App, 52 | response_sender: mpsc::UnboundedSender, 53 | init_sender: mpsc::UnboundedSender, 54 | ) -> Self { 55 | let mut behaviour = Self { 56 | app, 57 | floodsub: Floodsub::new(*PEER_ID), 58 | mdns: Mdns::new(Default::default()) 59 | .await 60 | .expect("can create mdns"), 61 | response_sender, 62 | init_sender, 63 | }; 64 | behaviour.floodsub.subscribe(CHAIN_TOPIC.clone()); 65 | behaviour.floodsub.subscribe(BLOCK_TOPIC.clone()); 66 | 67 | behaviour 68 | } 69 | } 70 | 71 | // incoming event handler 72 | impl NetworkBehaviourEventProcess for AppBehaviour { 73 | fn inject_event(&mut self, event: FloodsubEvent) { 74 | if let FloodsubEvent::Message(msg) = event { 75 | if let Ok(resp) = serde_json::from_slice::(&msg.data) { 76 | if resp.receiver == PEER_ID.to_string() { 77 | info!("Response from {}:", msg.source); 78 | resp.blocks.iter().for_each(|r| info!("{:?}", r)); 79 | 80 | self.app.blocks = self.app.choose_chain(self.app.blocks.clone(), resp.blocks); 81 | } 82 | } else if let Ok(resp) = serde_json::from_slice::(&msg.data) { 83 | info!("sending local chain to {}", msg.source.to_string()); 84 | let peer_id = resp.from_peer_id; 85 | if PEER_ID.to_string() == peer_id { 86 | if let Err(e) = self.response_sender.send(ChainResponse { 87 | blocks: self.app.blocks.clone(), 88 | receiver: msg.source.to_string(), 89 | }) { 90 | error!("error sending response via channel, {}", e); 91 | } 92 | } 93 | } else if let Ok(block) = serde_json::from_slice::(&msg.data) { 94 | info!("received new block from {}", msg.source.to_string()); 95 | self.app.try_add_block(block); 96 | } 97 | } 98 | } 99 | } 100 | 101 | impl NetworkBehaviourEventProcess for AppBehaviour { 102 | fn inject_event(&mut self, event: MdnsEvent) { 103 | match event { 104 | MdnsEvent::Discovered(discovered_list) => { 105 | for (peer, _addr) in discovered_list { 106 | self.floodsub.add_node_to_partial_view(peer); 107 | } 108 | } 109 | MdnsEvent::Expired(expired_list) => { 110 | for (peer, _addr) in expired_list { 111 | if !self.mdns.has_node(&peer) { 112 | self.floodsub.remove_node_from_partial_view(&peer); 113 | } 114 | } 115 | } 116 | } 117 | } 118 | } 119 | 120 | pub fn get_list_peers(swarm: &Swarm) -> Vec { 121 | info!("Discovered Peers:"); 122 | let nodes = swarm.behaviour().mdns.discovered_nodes(); 123 | let mut unique_peers = HashSet::new(); 124 | for peer in nodes { 125 | unique_peers.insert(peer); 126 | } 127 | unique_peers.iter().map(|p| p.to_string()).collect() 128 | } 129 | 130 | pub fn handle_print_peers(swarm: &Swarm) { 131 | let peers = get_list_peers(swarm); 132 | peers.iter().for_each(|p| info!("{}", p)); 133 | } 134 | 135 | pub fn handle_print_chain(swarm: &Swarm) { 136 | info!("Local Blockchain:"); 137 | let pretty_json = 138 | serde_json::to_string_pretty(&swarm.behaviour().app.blocks).expect("can jsonify blocks"); 139 | info!("{}", pretty_json); 140 | } 141 | 142 | pub fn handle_create_block(cmd: &str, swarm: &mut Swarm) { 143 | if let Some(data) = cmd.strip_prefix("create b") { 144 | let behaviour = swarm.behaviour_mut(); 145 | let latest_block = behaviour 146 | .app 147 | .blocks 148 | .last() 149 | .expect("there is at least one block"); 150 | let block = Block::new( 151 | latest_block.id + 1, 152 | latest_block.hash.clone(), 153 | data.to_owned(), 154 | ); 155 | let json = serde_json::to_string(&block).expect("can jsonify request"); 156 | behaviour.app.blocks.push(block); 157 | info!("broadcasting new block"); 158 | behaviour 159 | .floodsub 160 | .publish(BLOCK_TOPIC.clone(), json.as_bytes()); 161 | } 162 | } 163 | --------------------------------------------------------------------------------