Refactor P2P notification handling

This commit is contained in:
Roman Zeyde 2018-08-15 17:09:53 +03:00
parent 604f7680df
commit 2fad1fb8c9
No known key found for this signature in database
GPG Key ID: 87CAE5FA46917CBB
2 changed files with 50 additions and 36 deletions

View File

@ -10,6 +10,6 @@ fn main() {
let _ = Config::from_args(); let _ = Config::from_args();
let rx = notify::run().into_receiver(); let rx = notify::run().into_receiver();
for blockhash in rx.iter() { for blockhash in rx.iter() {
info!("{:?}", blockhash.be_hex_string()) info!("block {}", blockhash.be_hex_string())
} }
} }

View File

@ -3,24 +3,25 @@ use bitcoin::network::message::NetworkMessage;
use bitcoin::network::message_blockdata::InvType; use bitcoin::network::message_blockdata::InvType;
use bitcoin::network::socket::Socket; use bitcoin::network::socket::Socket;
use bitcoin::util::hash::Sha256dHash; use bitcoin::util::hash::Sha256dHash;
use bitcoin::util::Error;
use std::sync::mpsc::Sender;
use std::thread;
use std::time::Duration;
use util; use util;
pub fn run() -> util::Channel<Sha256dHash> { fn connect() -> Result<Socket, Error> {
let chan = util::Channel::new();
let tx = chan.sender();
util::spawn_thread("p2p", move || loop {
// TODO: support testnet and regtest as well.
let mut sock = Socket::new(Network::Bitcoin); let mut sock = Socket::new(Network::Bitcoin);
if let Err(e) = sock.connect("127.0.0.1", 8333) { sock.connect("127.0.0.1", 8333)?;
warn!("failed to connect to node: {}", e); Ok(sock)
continue;
} }
fn handle(mut sock: Socket, tx: Sender<Sha256dHash>) {
let mut outgoing = vec![sock.version_message(0).unwrap()]; let mut outgoing = vec![sock.version_message(0).unwrap()];
loop { loop {
for msg in outgoing.split_off(0) { for msg in outgoing.split_off(0) {
debug!("send {:?}", msg); trace!("send {:?}", msg);
if let Err(e) = sock.send_message(msg.clone()) { if let Err(e) = sock.send_message(msg.clone()) {
warn!("failed to connect to node: {}", e); warn!("failed to connect to node: {}", e);
break; break;
@ -34,7 +35,7 @@ pub fn run() -> util::Channel<Sha256dHash> {
break; break;
} }
}; };
debug!("recv {:?}", msg); trace!("recv {:?}", msg);
match msg { match msg {
NetworkMessage::Alert(_) => continue, // deprecated NetworkMessage::Alert(_) => continue, // deprecated
NetworkMessage::Version(_) => outgoing.push(NetworkMessage::Verack), NetworkMessage::Version(_) => outgoing.push(NetworkMessage::Verack),
@ -48,6 +49,19 @@ pub fn run() -> util::Channel<Sha256dHash> {
_ => (), _ => (),
}; };
} }
}
pub fn run() -> util::Channel<Sha256dHash> {
let chan = util::Channel::new();
let tx = chan.sender();
util::spawn_thread("p2p", move || loop {
// TODO: support testnet and regtest as well.
match connect() {
Ok(sock) => handle(sock, tx.clone()),
Err(e) => warn!("p2p error: {}", e),
}
thread::sleep(Duration::from_secs(3));
}); });
chan chan