Skip to content

Instantly share code, notes, and snippets.

@GGist
Created August 28, 2017 09:15
Show Gist options
  • Save GGist/7d895e66554eb9fc12c5645ea9aeacfc to your computer and use it in GitHub Desktop.
Save GGist/7d895e66554eb9fc12c5645ea9aeacfc to your computer and use it in GitHub Desktop.
[package]
name = "TrackerWithHandshake"
version = "0.1.0"
authors = ["GGist <amiller4421@gmail.com>"]
[dependencies]
bip_handshake = "0.5"
bip_utracker = "0.3"
futures = "0.1"
tokio-core = "0.1"
extern crate bip_handshake;
extern crate bip_utracker;
extern crate futures;
extern crate tokio_core;
use bip_handshake::{InitiateMessage, HandshakerBuilder, HandshakerSink, DiscoveryInfo, PeerId, HandshakerConfig};
use bip_handshake::transports::TcpTransport;
use bip_utracker::{TrackerClient, ClientMetadata, ClientRequest};
use futures::future::{self, Either};
use futures::{Sink, AsyncSink, StartSend, Poll};
use futures::sync::mpsc::SendError;
use tokio_core::reactor::{Core};
struct MetadataHandshaker {
sink: HandshakerSink
}
impl DiscoveryInfo for MetadataHandshaker {
fn port(&self) -> u16 {
self.sink.port()
}
fn peer_id(&self) -> PeerId {
self.sink.peer_id()
}
}
impl Sink for MetadataHandshaker {
type SinkItem = Either<InitiateMessage, ClientMetadata>;
type SinkError = SendError<InitiateMessage>;
fn start_send(&mut self, item: Either<InitiateMessage, ClientMetadata>) -> StartSend<Self::SinkItem, Self::SinkError> {
match item {
Either::A(init_msg) => {
println!("Sending Initiate Message");
self.sink.start_send(init_msg).map(|res| {
match res {
AsyncSink::NotReady(init_msg) => AsyncSink::NotReady(Either::A(init_msg)),
AsyncSink::Ready => AsyncSink::Ready
}
})
},
Either::B(metadata) => {
println!("Got Metadata: {:?}", metadata);
Ok(AsyncSink::Ready)
}
}
}
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
self.sink.poll_complete()
}
}
fn main() {
let mut core = Core::new().unwrap();
// Only have to set this to a high value if you dont want too much backpressure
// in the tracker (ie, you want all sends to complete so your metadata is sent back faster)
//let mut config = HandshakerConfig::default();
//config.set_sink_buffer_size(20000);
let handshaker = HandshakerBuilder::new()
.build::<TcpTransport>(core.handle())
.unwrap();
let (handshake_send, _handshake_recv) = handshaker.into_parts();
let wrapped_handshaker = MetadataHandshaker{ sink: handshake_send };
let mut client = TrackerClient::new("0.0.0.0:0".parse().unwrap(), wrapped_handshaker).unwrap();
let hash = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].into();
println!("{:?}", client.request("151.80.120.112:2710".parse().unwrap(), ClientRequest::Scrape(hash)));
core.run(future::empty::<(), ()>()).unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment