1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use std::{io, net, error, time};
use std::sync::Arc;
use std::net::SocketAddr;
use parking_lot::RwLock;
use futures::{Future, finished, failed};
use futures::stream::Stream;
use futures_cpupool::CpuPool;
use tokio_io::IoFuture;
use tokio_core::net::{TcpListener, TcpStream};
use tokio_core::reactor::{Handle, Remote, Timeout, Interval};
use abstract_ns::Resolver;
use ns_dns_tokio::DnsResolver;
use message::{Payload, MessageResult, Message};
use message::common::Services;
use message::types::addr::AddressEntry;
use net::{connect, Connections, Channel, Config as NetConfig, accept_connection, ConnectionCounter};
use util::{NodeTable, Node, NodeTableError, Direction};
use session::{SessionFactory, SeednodeSessionFactory, NormalSessionFactory};
use {Config, PeerId};
use protocol::{LocalSyncNodeRef, InboundSyncConnectionRef, OutboundSyncConnectionRef};
use io::DeadlineStatus;
pub type BoxedEmptyFuture = Box<Future<Item=(), Error=()> + Send>;
pub struct Context {
connections: Connections,
connection_counter: ConnectionCounter,
node_table: RwLock<NodeTable>,
pool: CpuPool,
remote: Remote,
local_sync_node: LocalSyncNodeRef,
config: Config,
}
impl Context {
pub fn new(local_sync_node: LocalSyncNodeRef, pool_handle: CpuPool, remote: Remote, config: Config) -> Result<Self, Box<error::Error>> {
let context = Context {
connections: Default::default(),
connection_counter: ConnectionCounter::new(config.inbound_connections, config.outbound_connections),
node_table: RwLock::new(try!(NodeTable::from_file(config.preferable_services, &config.node_table_path))),
pool: pool_handle,
remote: remote,
local_sync_node: local_sync_node,
config: config,
};
Ok(context)
}
pub fn spawn<F>(&self, f: F) where F: Future + Send + 'static, F::Item: Send + 'static, F::Error: Send + 'static {
let pool_work = self.pool.spawn(f);
self.remote.spawn(move |_handle| {
pool_work.then(|_| finished(()))
})
}
pub fn execute_after<F>(&self, duration: time::Duration, f: F) where F: FnOnce() + 'static + Send {
let pool = self.pool.clone();
self.remote.spawn(move |handle| {
let timeout = Timeout::new(duration, handle)
.expect("Expected to schedule timeout")
.then(move |_| {
f();
finished(())
});
pool.spawn(timeout)
});
}
pub fn node_table_entries(&self) -> Vec<Node> {
self.node_table.read().recently_active_nodes(self.config.internet_protocol)
}
pub fn update_node_table(&self, nodes: Vec<AddressEntry>) {
trace!("Updating node table with {} entries", nodes.len());
self.node_table.write().insert_many(nodes);
}
pub fn penalize_node(&self, addr: &SocketAddr) {
trace!("Penalizing node {}", addr);
self.node_table.write().note_failure(addr);
}
pub fn add_node(&self, addr: SocketAddr) -> Result<(), NodeTableError> {
trace!("Adding node {} to node table", &addr);
self.node_table.write().add(addr, self.config.connection.services)
}
pub fn remove_node(&self, addr: SocketAddr) -> Result<(), NodeTableError> {
trace!("Removing node {} from node table", &addr);
self.node_table.write().remove(&addr)
}
pub fn autoconnect(context: Arc<Context>, handle: &Handle) {
let c = context.clone();
let interval: BoxedEmptyFuture = Box::new(Interval::new_at(time::Instant::now(), time::Duration::new(10, 0), handle).expect("Failed to create interval")
.and_then(move |_| {
let ic = context.connection_counter.inbound_connections();
let oc = context.connection_counter.outbound_connections();
info!("Inbound connections: ({}/{})", ic.0, ic.1);
info!("Outbound connections: ({}/{})", oc.0, oc.1);
for channel in context.connections.channels().values() {
channel.session().maintain();
}
let needed = context.connection_counter.outbound_connections_needed() as usize;
if needed != 0 {
let used_addresses = context.connections.addresses();
let peers = context.node_table.read().nodes_with_services(&Services::default(), context.config.internet_protocol, &used_addresses, needed);
let addresses = peers.into_iter()
.map(|peer| peer.address())
.collect::<Vec<_>>();
trace!("Creating {} more outbound connections", addresses.len());
for address in addresses {
Context::connect::<NormalSessionFactory>(context.clone(), address);
}
}
if let Err(_err) = context.node_table.read().save_to_file(&context.config.node_table_path) {
error!("Saving node table to disk failed");
}
Ok(())
})
.for_each(|_| Ok(()))
.then(|_| finished(())));
c.spawn(interval);
}
fn connect_future<T>(context: Arc<Context>, socket: net::SocketAddr, handle: &Handle, config: &NetConfig) -> BoxedEmptyFuture where T: SessionFactory {
trace!("Trying to connect to: {}", socket);
let connection = connect(&socket, handle, config);
Box::new(connection.then(move |result| {
match result {
Ok(DeadlineStatus::Meet(Ok(connection))) => {
trace!("Connected to {}", connection.address);
context.node_table.write().insert(connection.address, connection.services);
let channel = context.connections.store::<T>(context.clone(), connection, Direction::Outbound);
channel.session().initialize();
Context::on_message(context, channel)
},
Ok(DeadlineStatus::Meet(Err(_))) => {
trace!("Handshake with {} failed", socket);
context.node_table.write().note_failure(&socket);
context.connection_counter.note_close_outbound_connection();
Box::new(finished(Ok(())))
},
Ok(DeadlineStatus::Timeout) => {
trace!("Handshake with {} timed out", socket);
context.node_table.write().note_failure(&socket);
context.connection_counter.note_close_outbound_connection();
Box::new(finished(Ok(())))
},
Err(_) => {
trace!("Unable to connect to {}", socket);
context.node_table.write().note_failure(&socket);
context.connection_counter.note_close_outbound_connection();
Box::new(finished(Ok(())))
}
}
})
.then(|_| finished(())))
}
pub fn connect<T>(context: Arc<Context>, socket: net::SocketAddr) where T: SessionFactory {
context.connection_counter.note_new_outbound_connection();
context.remote.clone().spawn(move |handle| {
let config = context.config.clone();
context.pool.clone().spawn(Context::connect_future::<T>(context, socket, handle, &config.connection))
})
}
pub fn connect_normal(context: Arc<Context>, socket: net::SocketAddr) {
Self::connect::<NormalSessionFactory>(context, socket)
}
pub fn accept_connection_future(context: Arc<Context>, stream: TcpStream, socket: net::SocketAddr, handle: &Handle, config: NetConfig) -> BoxedEmptyFuture {
Box::new(accept_connection(stream, handle, &config, socket).then(move |result| {
match result {
Ok(DeadlineStatus::Meet(Ok(connection))) => {
trace!("Accepted connection from {}", connection.address);
context.node_table.write().insert(connection.address, connection.services);
let channel = context.connections.store::<NormalSessionFactory>(context.clone(), connection, Direction::Inbound);
channel.session().initialize();
Context::on_message(context.clone(), channel)
},
Ok(DeadlineStatus::Meet(Err(err))) => {
trace!("Accepting handshake from {} failed with error: {}", socket, err);
context.node_table.write().note_failure(&socket);
context.connection_counter.note_close_inbound_connection();
Box::new(finished(Ok(())))
},
Ok(DeadlineStatus::Timeout) => {
trace!("Accepting handshake from {} timed out", socket);
context.node_table.write().note_failure(&socket);
context.connection_counter.note_close_inbound_connection();
Box::new(finished(Ok(())))
},
Err(_) => {
trace!("Accepting handshake from {} failed with network error", socket);
context.node_table.write().note_failure(&socket);
context.connection_counter.note_close_inbound_connection();
Box::new(finished(Ok(())))
}
}
})
.then(|_| finished(())))
}
pub fn accept_connection(context: Arc<Context>, stream: TcpStream, socket: net::SocketAddr, config: NetConfig) {
context.connection_counter.note_new_inbound_connection();
context.remote.clone().spawn(move |handle| {
context.pool.clone().spawn(Context::accept_connection_future(context, stream, socket, handle, config))
})
}
pub fn listen(context: Arc<Context>, handle: &Handle, config: NetConfig) -> Result<BoxedEmptyFuture, io::Error> {
trace!("Starting tcp server");
let server = try!(TcpListener::bind(&config.local_address, handle));
let server = Box::new(server.incoming()
.and_then(move |(stream, socket)| {
if context.connection_counter.inbound_connections_needed() > 0 {
Context::accept_connection(context.clone(), stream, socket, config.clone());
} else {
let _ = stream.shutdown(net::Shutdown::Both);
}
Ok(())
})
.for_each(|_| Ok(()))
.then(|_| finished(())));
Ok(server)
}
pub fn on_message(context: Arc<Context>, channel: Arc<Channel>) -> IoFuture<MessageResult<()>> {
Box::new(channel.read_message().then(move |result| {
match result {
Ok(Ok((command, payload))) => {
trace!("Received {} message from {}", command, channel.peer_info().address);
match channel.session().on_message(command, payload) {
Ok(_) => {
context.node_table.write().note_used(&channel.peer_info().address);
let on_message = Context::on_message(context.clone(), channel);
context.spawn(on_message);
Box::new(finished(Ok(())))
},
Err(err) => {
context.close_channel_with_error(channel.peer_info().id, &err);
Box::new(finished(Err(err)))
}
}
},
Ok(Err(err)) => {
context.close_channel_with_error(channel.peer_info().id, &err);
Box::new(finished(Err(err)))
},
Err(err) => {
context.close_channel_with_error(channel.peer_info().id, &err);
Box::new(failed(err))
}
}
}))
}
pub fn send_to_peer<T>(context: Arc<Context>, peer: PeerId, payload: &T, serialization_flags: u32) -> IoFuture<()> where T: Payload {
match context.connections.channel(peer) {
Some(channel) => {
let info = channel.peer_info();
let message = Message::with_flags(info.magic, info.version, payload, serialization_flags).expect("failed to create outgoing message");
channel.session().stats().lock().report_send(T::command().into(), message.len());
Context::send(context, channel, message)
},
None => {
Box::new(finished(()))
}
}
}
pub fn send_message_to_peer<T>(context: Arc<Context>, peer: PeerId, message: T) -> IoFuture<()> where T: AsRef<[u8]> + Send + 'static {
match context.connections.channel(peer) {
Some(channel) => Context::send(context, channel, message),
None => {
Box::new(finished(()))
}
}
}
pub fn send<T>(_context: Arc<Context>, channel: Arc<Channel>, message: T) -> IoFuture<()> where T: AsRef<[u8]> + Send + 'static {
Box::new(channel.write_message(message).then(move |result| {
match result {
Ok(_) => {
Box::new(finished(()))
},
Err(err) => {
Box::new(failed(err))
},
}
}))
}
pub fn close_channel(&self, id: PeerId) {
if let Some(channel) = self.connections.remove(id) {
let info = channel.peer_info();
channel.session().on_close();
trace!("Disconnecting from {}", info.address);
channel.shutdown();
match info.direction {
Direction::Inbound => self.connection_counter.note_close_inbound_connection(),
Direction::Outbound => self.connection_counter.note_close_outbound_connection(),
}
}
}
pub fn close_channel_with_error(&self, id: PeerId, error: &error::Error) {
if let Some(channel) = self.connections.remove(id) {
let info = channel.peer_info();
channel.session().on_close();
trace!("Disconnecting from {} caused by {}", info.address, error.description());
channel.shutdown();
self.node_table.write().note_failure(&info.address);
match info.direction {
Direction::Inbound => self.connection_counter.note_close_inbound_connection(),
Direction::Outbound => self.connection_counter.note_close_outbound_connection(),
}
}
}
pub fn create_sync_session(&self, start_height: i32, services: Services, outbound_connection: OutboundSyncConnectionRef) -> InboundSyncConnectionRef {
self.local_sync_node.create_sync_session(start_height, services, outbound_connection)
}
pub fn connections(&self) -> &Connections {
&self.connections
}
pub fn nodes(&self) -> Vec<Node> {
self.node_table.read().nodes()
}
}
pub struct P2P {
event_loop_handle: Handle,
pool: CpuPool,
config: Config,
context: Arc<Context>,
}
impl Drop for P2P {
fn drop(&mut self) {
for channel in &self.context.connections.remove_all() {
channel.shutdown();
}
}
}
impl P2P {
pub fn new(config: Config, local_sync_node: LocalSyncNodeRef, handle: Handle) -> Result<Self, Box<error::Error>> {
let pool = CpuPool::new(config.threads);
let context = try!(Context::new(local_sync_node, pool.clone(), handle.remote().clone(), config.clone()));
let p2p = P2P {
event_loop_handle: handle.clone(),
pool: pool,
context: Arc::new(context),
config: config,
};
Ok(p2p)
}
pub fn run(&self) -> Result<(), Box<error::Error>> {
for peer in &self.config.peers {
self.connect::<NormalSessionFactory>(*peer);
}
let resolver = try!(DnsResolver::system_config(&self.event_loop_handle));
for seed in &self.config.seeds {
self.connect_to_seednode(&resolver, seed);
}
Context::autoconnect(self.context.clone(), &self.event_loop_handle);
try!(self.listen());
Ok(())
}
pub fn connect<T>(&self, addr: net::SocketAddr) where T: SessionFactory {
Context::connect::<T>(self.context.clone(), addr);
}
pub fn connect_to_seednode(&self, resolver: &Resolver, seednode: &str) {
let owned_seednode = seednode.to_owned();
let context = self.context.clone();
let dns_lookup = resolver.resolve(seednode).then(move |result| {
match result {
Ok(address) => match address.pick_one() {
Some(socket) => {
trace!("Dns lookup of seednode {} finished. Connecting to {}", owned_seednode, socket);
Context::connect::<SeednodeSessionFactory>(context, socket);
},
None => {
trace!("Dns lookup of seednode {} resolved with no results", owned_seednode);
}
},
Err(_err) => {
trace!("Dns lookup of seednode {} failed", owned_seednode);
}
}
finished(())
});
let pool_work = self.pool.spawn(dns_lookup);
self.event_loop_handle.spawn(pool_work);
}
fn listen(&self) -> Result<(), Box<error::Error>> {
let server = try!(Context::listen(self.context.clone(), &self.event_loop_handle, self.config.connection.clone()));
self.event_loop_handle.spawn(server);
Ok(())
}
pub fn context(&self) -> &Arc<Context> {
&self.context
}
}