MCPcopy Create free account
hub / github.com/PacktPublishing/Rust-for-Blockchain-Application-Development / serve

Function serve

chapter 4/server.rs:179–328  ·  view source on GitHub ↗
(blockchain: Blockchain, stream: TcpStream)

Source from the content-addressed store, hash-verified

177}
178
179fn serve(blockchain: Blockchain, stream: TcpStream) -> Result<(), Box<dyn Error>> {
180 let peer_addr = stream.peer_addr()?;
181 let reader = BufReader::new(&stream);
182 let pkg_reader = Deserializer::from_reader(reader).into_iter::<Package>();
183 for pkg in pkg_reader {
184 let pkg = pkg?;
185 info!("Receive request from {}: {:?}", peer_addr, pkg);
186 match pkg {
187 Package::Block { addr_from, block } => {
188 let block = Block::deserialize(block.as_slice());
189 blockchain.add_block(&block);
190 info!("Added block {}", block.get_hash());
191
192 if GLOBAL_BLOCKS_IN_TRANSIT.len() > 0 {
193
194 let block_hash = GLOBAL_BLOCKS_IN_TRANSIT.first().unwrap();
195 send_get_data(addr_from.as_str(), OpType::Block, &block_hash);
196
197 GLOBAL_BLOCKS_IN_TRANSIT.remove(block_hash.as_slice());
198 } else {
199
200 let utxo_set = UTXOSet::new(blockchain.clone());
201 utxo_set.reindex();
202 }
203 }
204 Package::GetBlocks { addr_from } => {
205 let blocks = blockchain.get_block_hashes();
206 send_inv(addr_from.as_str(), OpType::Block, &blocks);
207 }
208 Package::GetData {
209 addr_from,
210 op_type,
211 id,
212 } => match op_type {
213 OpType::Block => {
214 if let Some(block) = blockchain.get_block(id.as_slice()) {
215 send_block(addr_from.as_str(), &block);
216 }
217 }
218 OpType::Tx => {
219 let txid_hex = HEXLOWER.encode(id.as_slice());
220 if let Some(tx) = GLOBAL_MEMORY_POOL.get(txid_hex.as_str()) {
221 send_tx(addr_from.as_str(), &tx);
222 }
223 }
224 },
225 Package::Inv {
226 addr_from,
227 op_type,
228 items,
229 } => match op_type {
230
231 OpType::Block => {
232
233 GLOBAL_BLOCKS_IN_TRANSIT.add_blocks(items.as_slice());
234
235
236 let block_hash = items.get(0).unwrap();

Callers

nothing calls this directly

Calls 15

send_get_dataFunction · 0.70
send_invFunction · 0.70
send_blockFunction · 0.70
send_txFunction · 0.70
send_get_blocksFunction · 0.70
send_versionFunction · 0.70
add_blockMethod · 0.45
lenMethod · 0.45
firstMethod · 0.45
removeMethod · 0.45
reindexMethod · 0.45
get_block_hashesMethod · 0.45

Tested by

no test coverage detected