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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
use router::Router;
use mount::Mount;
use iron::{Chain, Iron};
use toml::Value;
use std::io;
use std::net::SocketAddr;
use std::time::{SystemTime, Duration};
use std::collections::BTreeMap;
use std::thread;
use std::fmt;
use crypto::{self, PublicKey, SecretKey, Hash};
use events::{Events, Reactor, NetworkConfiguration, Event, EventsConfiguration, Channel,
MioChannel, Network, EventLoop, Milliseconds, EventHandler, Result as EventsResult,
Error as EventsError};
use blockchain::{SharedNodeState, Blockchain, Schema, GenesisConfig, Transaction, ApiContext};
use messages::{Connect, RawMessage};
use api::{Api, public, private};
use self::timeout_adjuster::TimeoutAdjuster;
pub use self::state::{State, Round, Height, RequestData, ValidatorId, TxPool, ValidatorState};
pub use self::whitelist::Whitelist;
mod basic;
mod consensus;
mod requests;
mod whitelist;
pub mod state;
pub mod timeout_adjuster;
const PROFILE_ENV_VARIABLE_NAME: &'static str = "EXONUM_PROFILE_FILENAME";
#[derive(Debug)]
pub enum ExternalMessage {
PeerAdd(SocketAddr),
Transaction(Box<Transaction>),
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum NodeTimeout {
Status(Height),
Round(Height, Round),
Request(RequestData, Option<PublicKey>),
Propose(Height, Round),
UpdateApiState,
PeerExchange,
}
#[derive(Clone)]
pub struct ApiSender<S>
where
S: Channel<ApplicationEvent = ExternalMessage, Timeout = NodeTimeout>,
{
inner: S,
}
pub struct NodeHandler<S>
where
S: Channel<ApplicationEvent = ExternalMessage, Timeout = NodeTimeout>,
{
pub state: State,
pub api_state: SharedNodeState,
pub channel: S,
pub blockchain: Blockchain,
pub peer_discovery: Vec<SocketAddr>,
timeout_adjuster: Box<TimeoutAdjuster>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ServiceConfig {
pub service_public_key: PublicKey,
pub service_secret_key: SecretKey,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ListenerConfig {
pub consensus_public_key: PublicKey,
pub consensus_secret_key: SecretKey,
pub whitelist: Whitelist,
pub address: SocketAddr,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NodeApiConfig {
pub state_update_timeout: usize,
pub enable_blockchain_explorer: bool,
pub public_api_address: Option<SocketAddr>,
pub private_api_address: Option<SocketAddr>,
}
impl Default for NodeApiConfig {
fn default() -> NodeApiConfig {
NodeApiConfig {
state_update_timeout: 10000,
enable_blockchain_explorer: true,
public_api_address: None,
private_api_address: None,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MemoryPoolConfig {
pub tx_pool_capacity: usize,
pub events_pool_capacity: usize,
}
impl Default for MemoryPoolConfig {
fn default() -> MemoryPoolConfig {
MemoryPoolConfig {
tx_pool_capacity: 100000,
events_pool_capacity: 400000,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NodeConfig {
pub genesis: GenesisConfig,
pub listen_address: SocketAddr,
pub external_address: Option<SocketAddr>,
pub network: NetworkConfiguration,
pub peers: Vec<SocketAddr>,
pub consensus_public_key: PublicKey,
pub consensus_secret_key: SecretKey,
pub service_public_key: PublicKey,
pub service_secret_key: SecretKey,
pub whitelist: Whitelist,
pub api: NodeApiConfig,
pub mempool: MemoryPoolConfig,
pub services_configs: BTreeMap<String, Value>,
}
#[derive(Debug, Clone)]
pub struct Configuration {
pub listener: ListenerConfig,
pub service: ServiceConfig,
pub events: EventsConfiguration,
pub network: NetworkConfiguration,
pub peer_discovery: Vec<SocketAddr>,
pub mempool: MemoryPoolConfig,
}
pub type NodeChannel = MioChannel<ExternalMessage, NodeTimeout>;
#[derive(Debug)]
pub struct Node {
reactor: Events<NodeHandler<NodeChannel>>,
api_options: NodeApiConfig,
}
impl<S> NodeHandler<S>
where
S: Channel<ApplicationEvent = ExternalMessage, Timeout = NodeTimeout>,
{
pub fn new(
blockchain: Blockchain,
external_address: SocketAddr,
sender: S,
config: Configuration,
api_state: SharedNodeState,
) -> Self {
let (last_hash, last_height) = {
let block = blockchain.last_block();
(block.hash(), block.height() + 1)
};
let snapshot = blockchain.snapshot();
let stored = Schema::new(&snapshot).actual_configuration();
info!("Creating a node with config: {:#?}", stored);
let validator_id = stored
.validator_keys
.iter()
.position(|pk| {
pk.consensus_key == config.listener.consensus_public_key
})
.map(|id| id as ValidatorId);
info!("Validator id = '{:?}'", validator_id);
let connect = Connect::new(
&config.listener.consensus_public_key,
external_address,
sender.get_time(),
&config.listener.consensus_secret_key,
);
let mut whitelist = config.listener.whitelist;
whitelist.set_validators(stored.validator_keys.iter().map(|x| x.consensus_key));
let mut state = State::new(
validator_id,
config.listener.consensus_public_key,
config.listener.consensus_secret_key,
config.service.service_public_key,
config.service.service_secret_key,
config.mempool.tx_pool_capacity,
whitelist,
stored,
connect,
last_hash,
last_height,
sender.get_time(),
);
let mut timeout_adjuster = Box::new(timeout_adjuster::Constant::default());
let timeout = timeout_adjuster.adjust_timeout(&state, &*snapshot);
state.set_propose_timeout(timeout);
NodeHandler {
blockchain,
timeout_adjuster,
api_state,
state,
channel: sender,
peer_discovery: config.peer_discovery,
}
}
pub fn api_state(&self) -> &SharedNodeState {
&self.api_state
}
pub fn set_timeout_adjuster(&mut self, adjuster: Box<timeout_adjuster::TimeoutAdjuster>) {
self.timeout_adjuster = adjuster;
}
pub fn propose_timeout(&self) -> Milliseconds {
self.state().consensus_config().propose_timeout
}
pub fn round_timeout(&self) -> Milliseconds {
self.state().consensus_config().round_timeout
}
pub fn status_timeout(&self) -> Milliseconds {
self.state().consensus_config().status_timeout
}
pub fn peers_timeout(&self) -> Milliseconds {
self.state().consensus_config().peers_timeout
}
pub fn txs_block_limit(&self) -> u32 {
self.state().consensus_config().txs_block_limit
}
pub fn state(&self) -> &State {
&self.state
}
pub fn initialize(&mut self) {
info!("Start listening address={}", self.channel.address());
for address in &self.peer_discovery.clone() {
if address == &self.channel.address() {
continue;
}
self.connect(address);
info!("Trying to connect with peer {}", address);
}
let round = 1;
self.state.jump_round(round);
info!("Jump to round {}", round);
self.add_round_timeout();
self.add_status_timeout();
self.add_peer_exchange_timeout();
self.add_update_api_state_timeout();
}
pub fn send_to_validator(&mut self, id: u32, message: &RawMessage) {
let public_key = self.state.validators()[id as usize].consensus_key;
self.send_to_peer(public_key, message);
}
pub fn send_to_peer(&mut self, public_key: PublicKey, message: &RawMessage) {
if let Some(conn) = self.state.peers().get(&public_key) {
trace!("Send to address: {}", conn.addr());
self.channel.send_to(&conn.addr(), message.clone());
} else {
warn!("Hasn't connection with peer {:?}", public_key);
}
}
pub fn send_to_addr(&mut self, address: &SocketAddr, message: &RawMessage) {
trace!("Send to address: {}", address);
self.channel.send_to(address, message.clone());
}
pub fn broadcast(&mut self, message: &RawMessage) {
for conn in self.state.peers().values() {
trace!("Send to address: {}", conn.addr());
self.channel.send_to(&conn.addr(), message.clone());
}
}
pub fn connect(&mut self, address: &SocketAddr) {
self.channel.connect(address);
}
pub fn request(&mut self, data: RequestData, peer: PublicKey) {
let is_new = self.state.request(data.clone(), peer);
if is_new {
self.add_request_timeout(data, None);
}
}
pub fn add_round_timeout(&mut self) {
let time = self.round_start_time(self.state.round() + 1);
trace!(
"ADD ROUND TIMEOUT: time={:?}, height={}, round={}",
time,
self.state.height(),
self.state.round()
);
let timeout = NodeTimeout::Round(self.state.height(), self.state.round());
self.channel.add_timeout(timeout, time);
}
pub fn add_propose_timeout(&mut self) {
let adjusted_propose_timeout = self.state.propose_timeout();
let time = self.round_start_time(self.state.round()) +
Duration::from_millis(adjusted_propose_timeout);
trace!(
"ADD PROPOSE TIMEOUT: time={:?}, height={}, round={}",
time,
self.state.height(),
self.state.round()
);
let timeout = NodeTimeout::Propose(self.state.height(), self.state.round());
self.channel.add_timeout(timeout, time);
}
pub fn add_status_timeout(&mut self) {
let time = self.channel.get_time() + Duration::from_millis(self.status_timeout());
self.channel.add_timeout(
NodeTimeout::Status(self.state.height()),
time,
);
}
pub fn add_request_timeout(&mut self, data: RequestData, peer: Option<PublicKey>) {
trace!("ADD REQUEST TIMEOUT");
let time = self.channel.get_time() + data.timeout();
self.channel.add_timeout(
NodeTimeout::Request(data, peer),
time,
);
}
pub fn add_peer_exchange_timeout(&mut self) {
trace!("ADD PEER EXCHANGE TIMEOUT");
let time = self.channel.get_time() + Duration::from_millis(self.peers_timeout());
self.channel.add_timeout(NodeTimeout::PeerExchange, time);
}
pub fn add_update_api_state_timeout(&mut self) {
let time = self.channel.get_time() +
Duration::from_millis(self.api_state().state_update_timeout());
self.channel.add_timeout(NodeTimeout::UpdateApiState, time);
}
pub fn last_block_hash(&self) -> Hash {
self.blockchain.last_block().hash()
}
pub fn round_start_time(&self, round: Round) -> SystemTime {
let ms = (round - 1) as u64 * self.round_timeout();
self.state.height_start_time() + Duration::from_millis(ms)
}
}
impl<S> EventHandler for NodeHandler<S>
where
S: Channel<
ApplicationEvent = ExternalMessage,
Timeout = NodeTimeout,
>,
{
type Timeout = NodeTimeout;
type ApplicationEvent = ExternalMessage;
fn handle_event(&mut self, event: Event) {
match event {
Event::Connected(addr) => self.handle_connected(&addr),
Event::Disconnected(addr) => self.handle_disconnected(&addr),
Event::Incoming(raw) => self.handle_message(raw),
Event::Error(_) => {}
}
}
fn handle_application_event(&mut self, event: Self::ApplicationEvent) {
match event {
ExternalMessage::Transaction(tx) => {
self.handle_incoming_tx(tx);
}
ExternalMessage::PeerAdd(address) => {
info!("Send Connect message to {}", address);
self.connect(&address);
}
}
}
fn handle_timeout(&mut self, timeout: Self::Timeout) {
match timeout {
NodeTimeout::Round(height, round) => self.handle_round_timeout(height, round),
NodeTimeout::Request(data, peer) => self.handle_request_timeout(data, peer),
NodeTimeout::Status(height) => self.handle_status_timeout(height),
NodeTimeout::PeerExchange => self.handle_peer_exchange_timeout(),
NodeTimeout::UpdateApiState => self.handle_update_api_state_timeout(),
NodeTimeout::Propose(height, round) => self.handle_propose_timeout(height, round),
}
}
}
impl<S> fmt::Debug for NodeHandler<S>
where
S: Channel<
ApplicationEvent = ExternalMessage,
Timeout = NodeTimeout,
>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"NodeHandler {{ channel: Channel {{ .. }}, blockchain: {:?}, \
peer_discovery: {:?}, timeout_adjuster: Box<TimeoutAdjuster> }}",
self.blockchain,
self.peer_discovery
)
}
}
pub trait TransactionSend: Send + Sync {
fn send(&self, tx: Box<Transaction>) -> EventsResult<()>;
}
impl<S> ApiSender<S>
where
S: Channel<ApplicationEvent = ExternalMessage, Timeout = NodeTimeout>,
{
pub fn new(inner: S) -> ApiSender<S> {
ApiSender { inner: inner }
}
pub fn peer_add(&self, addr: SocketAddr) -> EventsResult<()> {
let msg = ExternalMessage::PeerAdd(addr);
self.inner.post_event(msg)
}
}
impl<S> TransactionSend for ApiSender<S>
where
S: Channel<
ApplicationEvent = ExternalMessage,
Timeout = NodeTimeout,
>,
{
fn send(&self, tx: Box<Transaction>) -> EventsResult<()> {
if !tx.verify() {
return Err(EventsError::new("Unable to verify transaction"));
}
let msg = ExternalMessage::Transaction(tx);
self.inner.post_event(msg)
}
}
impl<T> fmt::Debug for ApiSender<T>
where
T: Channel<
ApplicationEvent = ExternalMessage,
Timeout = NodeTimeout,
>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("ApiSender { .. }")
}
}
impl Node {
pub fn new(mut blockchain: Blockchain, node_cfg: NodeConfig) -> Self {
crypto::init();
if cfg!(feature = "flame_profile") {
::profiler::init_handler(::std::env::var(PROFILE_ENV_VARIABLE_NAME).expect(&format!(
"You compiled exonum with profiling support, but {}",
PROFILE_ENV_VARIABLE_NAME
)))
};
blockchain
.create_genesis_block(node_cfg.genesis.clone())
.unwrap();
let mut events_cfg = EventsConfiguration::default();
events_cfg.notify_capacity(node_cfg.mempool.events_pool_capacity);
let config = Configuration {
listener: ListenerConfig {
consensus_public_key: node_cfg.consensus_public_key,
consensus_secret_key: node_cfg.consensus_secret_key,
whitelist: node_cfg.whitelist,
address: node_cfg.listen_address,
},
service: ServiceConfig {
service_public_key: node_cfg.service_public_key,
service_secret_key: node_cfg.service_secret_key,
},
mempool: node_cfg.mempool,
network: node_cfg.network,
events: events_cfg,
peer_discovery: node_cfg.peers,
};
let external_address = if let Some(v) = node_cfg.external_address {
v
} else {
warn!("Could not find 'external_address' in the config, using 'listen_address'");
node_cfg.listen_address
};
let api_state = SharedNodeState::new(node_cfg.api.state_update_timeout as u64);
let network =
Network::with_config(node_cfg.listen_address, config.network, api_state.clone());
let event_loop = EventLoop::configured(config.events.clone()).unwrap();
let channel = NodeChannel::new(node_cfg.listen_address, event_loop.channel());
let worker = NodeHandler::new(blockchain, external_address, channel, config, api_state);
Node {
reactor: Events::with_event_loop(network, worker, event_loop),
api_options: node_cfg.api,
}
}
pub fn run_handler(&mut self) -> io::Result<()> {
self.reactor.bind()?;
self.reactor.handler_mut().initialize();
self.reactor.run()
}
pub fn run(&mut self) -> io::Result<()> {
let blockchain = self.handler().blockchain.clone();
let channel = self.channel();
let private_config_api_thread = match self.api_options.private_api_address {
Some(listen_address) => {
let api_context = ApiContext::new(self);
let mut mount = Mount::new();
mount.mount("api/services", api_context.mount_private_api());
let shared_api_state = self.handler().api_state().clone();
let mut router = Router::new();
let node_info =
private::NodeInfo::new(blockchain.service_map().iter().map(|(_, s)| s));
let system_api = private::SystemApi::new(
node_info,
blockchain.clone(),
shared_api_state,
channel,
);
system_api.wire(&mut router);
mount.mount("api/system", router);
let thread = thread::spawn(move || {
info!("Private exonum api started on {}", listen_address);
let chain = Chain::new(mount);
Iron::new(chain).http(listen_address).unwrap();
});
Some(thread)
}
None => None,
};
let public_config_api_thread = match self.api_options.public_api_address {
Some(listen_address) => {
let api_context = ApiContext::new(self);
let mut mount = Mount::new();
mount.mount("api/services", api_context.mount_public_api());
let mut router = Router::new();
let pool = self.state().transactions().clone();
let system_api = public::SystemApi::new(pool, blockchain.clone());
system_api.wire(&mut router);
mount.mount("api/system", router);
if self.api_options.enable_blockchain_explorer {
let mut router = Router::new();
let explorer_api = public::ExplorerApi::new(blockchain);
explorer_api.wire(&mut router);
mount.mount("api/explorer", router);
}
let thread = thread::spawn(move || {
info!("Public exonum api started on {}", listen_address);
let chain = Chain::new(mount);
Iron::new(chain).http(listen_address).unwrap();
});
Some(thread)
}
None => None,
};
self.run_handler()?;
if let Some(private_config_api_thread) = private_config_api_thread {
private_config_api_thread.join().unwrap();
}
if let Some(public_config_api_thread) = public_config_api_thread {
public_config_api_thread.join().unwrap();
}
Ok(())
}
pub fn state(&self) -> &State {
self.reactor.handler().state()
}
pub fn handler(&self) -> &NodeHandler<NodeChannel> {
self.reactor.handler()
}
pub fn channel(&self) -> ApiSender<NodeChannel> {
ApiSender::new(self.reactor.handler().channel.clone())
}
}