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
#![warn(
future_incompatible,
nonstandard_style,
rust_2018_idioms,
rust_2021_compatibility
)]
#![allow(clippy::mutable_key_type)]
use arc_swap::ArcSwap;
use crypto::{NetworkPublicKey, PublicKey};
use fastcrypto::traits::EncodeDecodeBase64;
use multiaddr::Multiaddr;
use rand::{rngs::StdRng, seq::SliceRandom, SeedableRng};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::{
collections::{BTreeMap, HashSet},
fs::{self, OpenOptions},
io::{BufWriter, Write as _},
sync::Arc,
time::Duration,
};
use thiserror::Error;
use tracing::info;
use utils::get_available_port;
mod duration_format;
pub mod utils;
pub type Epoch = u64;
#[derive(Error, Debug)]
pub enum ConfigError {
#[error("Node {0} is not in the committee")]
NotInCommittee(String),
#[error("Node {0} is not in the worker cache")]
NotInWorkerCache(String),
#[error("Unknown worker id {0}")]
UnknownWorker(WorkerId),
#[error("Failed to read config file '{file}': {message}")]
ImportError { file: String, message: String },
#[error("Failed to write config file '{file}': {message}")]
ExportError { file: String, message: String },
}
#[derive(Error, Debug)]
pub enum CommitteeUpdateError {
#[error("Node {0} is not in the committee")]
NotInCommittee(String),
#[error("Node {0} was not in the update")]
MissingFromUpdate(String),
#[error("Node {0} has a different stake than expected")]
DifferentStake(String),
}
pub trait Import: DeserializeOwned {
fn import(path: &str) -> Result<Self, ConfigError> {
let reader = || -> Result<Self, std::io::Error> {
let data = fs::read(path)?;
Ok(serde_json::from_slice(data.as_slice())?)
};
reader().map_err(|e| ConfigError::ImportError {
file: path.to_string(),
message: e.to_string(),
})
}
}
impl<D: DeserializeOwned> Import for D {}
pub trait Export: Serialize {
fn export(&self, path: &str) -> Result<(), ConfigError> {
let writer = || -> Result<(), std::io::Error> {
let file = OpenOptions::new().create(true).write(true).open(path)?;
let mut writer = BufWriter::new(file);
let data = serde_json::to_string_pretty(self).unwrap();
writer.write_all(data.as_ref())?;
writer.write_all(b"\n")?;
Ok(())
};
writer().map_err(|e| ConfigError::ExportError {
file: path.to_string(),
message: e.to_string(),
})
}
}
impl<S: Serialize> Export for S {}
pub type Stake = u64;
pub type WorkerId = u32;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Parameters {
pub header_size: usize,
#[serde(with = "duration_format")]
pub max_header_delay: Duration,
pub gc_depth: u64,
#[serde(with = "duration_format")]
pub sync_retry_delay: Duration,
pub sync_retry_nodes: usize,
pub batch_size: usize,
#[serde(with = "duration_format")]
pub max_batch_delay: Duration,
pub block_synchronizer: BlockSynchronizerParameters,
pub consensus_api_grpc: ConsensusAPIGrpcParameters,
pub max_concurrent_requests: usize,
pub prometheus_metrics: PrometheusMetricsParameters,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PrometheusMetricsParameters {
pub socket_addr: Multiaddr,
}
impl Default for PrometheusMetricsParameters {
fn default() -> Self {
let host = "127.0.0.1";
Self {
socket_addr: format!("/ip4/{}/tcp/{}/http", host, get_available_port(host))
.parse()
.unwrap(),
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ConsensusAPIGrpcParameters {
pub socket_addr: Multiaddr,
#[serde(with = "duration_format")]
pub get_collections_timeout: Duration,
#[serde(with = "duration_format")]
pub remove_collections_timeout: Duration,
}
impl Default for ConsensusAPIGrpcParameters {
fn default() -> Self {
let host = "127.0.0.1";
Self {
socket_addr: format!("/ip4/{}/tcp/{}/http", host, get_available_port(host))
.parse()
.unwrap(),
get_collections_timeout: Duration::from_millis(5_000),
remove_collections_timeout: Duration::from_millis(5_000),
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default)]
pub struct BlockSynchronizerParameters {
#[serde(
with = "duration_format",
default = "BlockSynchronizerParameters::default_range_synchronize_timeout"
)]
pub range_synchronize_timeout: Duration,
#[serde(
with = "duration_format",
default = "BlockSynchronizerParameters::default_certificates_synchronize_timeout"
)]
pub certificates_synchronize_timeout: Duration,
#[serde(
with = "duration_format",
default = "BlockSynchronizerParameters::default_payload_synchronize_timeout"
)]
pub payload_synchronize_timeout: Duration,
#[serde(
with = "duration_format",
default = "BlockSynchronizerParameters::default_payload_availability_timeout"
)]
pub payload_availability_timeout: Duration,
#[serde(
with = "duration_format",
default = "BlockSynchronizerParameters::default_handler_certificate_deliver_timeout"
)]
pub handler_certificate_deliver_timeout: Duration,
}
impl BlockSynchronizerParameters {
fn default_range_synchronize_timeout() -> Duration {
Duration::from_secs(30)
}
fn default_certificates_synchronize_timeout() -> Duration {
Duration::from_secs(30)
}
fn default_payload_synchronize_timeout() -> Duration {
Duration::from_secs(30)
}
fn default_payload_availability_timeout() -> Duration {
Duration::from_secs(30)
}
fn default_handler_certificate_deliver_timeout() -> Duration {
Duration::from_secs(30)
}
}
impl Default for BlockSynchronizerParameters {
fn default() -> Self {
Self {
range_synchronize_timeout:
BlockSynchronizerParameters::default_range_synchronize_timeout(),
certificates_synchronize_timeout:
BlockSynchronizerParameters::default_certificates_synchronize_timeout(),
payload_synchronize_timeout:
BlockSynchronizerParameters::default_payload_synchronize_timeout(),
payload_availability_timeout:
BlockSynchronizerParameters::default_payload_availability_timeout(),
handler_certificate_deliver_timeout:
BlockSynchronizerParameters::default_handler_certificate_deliver_timeout(),
}
}
}
impl Default for Parameters {
fn default() -> Self {
Self {
header_size: 1_000,
max_header_delay: Duration::from_millis(100),
gc_depth: 50,
sync_retry_delay: Duration::from_millis(5_000),
sync_retry_nodes: 3,
batch_size: 500_000,
max_batch_delay: Duration::from_millis(100),
block_synchronizer: BlockSynchronizerParameters::default(),
consensus_api_grpc: ConsensusAPIGrpcParameters::default(),
max_concurrent_requests: 500_000,
prometheus_metrics: PrometheusMetricsParameters::default(),
}
}
}
impl Parameters {
pub fn tracing(&self) {
info!("Header size set to {} B", self.header_size);
info!(
"Max header delay set to {} ms",
self.max_header_delay.as_millis()
);
info!("Garbage collection depth set to {} rounds", self.gc_depth);
info!(
"Sync retry delay set to {} ms",
self.sync_retry_delay.as_millis()
);
info!("Sync retry nodes set to {} nodes", self.sync_retry_nodes);
info!("Batch size set to {} B", self.batch_size);
info!(
"Max batch delay set to {} ms",
self.max_batch_delay.as_millis()
);
info!(
"Synchronize range timeout set to {} s",
self.block_synchronizer.range_synchronize_timeout.as_secs()
);
info!(
"Synchronize certificates timeout set to {} s",
self.block_synchronizer
.certificates_synchronize_timeout
.as_secs()
);
info!(
"Payload (batches) availability timeout set to {} s",
self.block_synchronizer
.payload_availability_timeout
.as_secs()
);
info!(
"Synchronize payload (batches) timeout set to {} s",
self.block_synchronizer
.payload_synchronize_timeout
.as_secs()
);
info!(
"Consensus API gRPC Server set to listen on on {}",
self.consensus_api_grpc.socket_addr
);
info!(
"Get collections timeout set to {} ms",
self.consensus_api_grpc.get_collections_timeout.as_millis()
);
info!(
"Remove collections timeout set to {} ms",
self.consensus_api_grpc
.remove_collections_timeout
.as_millis()
);
info!(
"Handler certificate deliver timeout set to {} s",
self.block_synchronizer
.handler_certificate_deliver_timeout
.as_secs()
);
info!(
"Max concurrent requests set to {}",
self.max_concurrent_requests
);
info!(
"Prometheus metrics server will run on {}",
self.prometheus_metrics.socket_addr
);
}
}
#[derive(Clone, Serialize, Deserialize, Eq, Hash, PartialEq, Debug)]
pub struct WorkerInfo {
pub name: NetworkPublicKey,
pub transactions: Multiaddr,
pub worker_address: Multiaddr,
}
pub type SharedWorkerCache = Arc<ArcSwap<WorkerCache>>;
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct WorkerIndex(pub BTreeMap<WorkerId, WorkerInfo>);
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct WorkerCache {
pub workers: BTreeMap<PublicKey, WorkerIndex>,
pub epoch: Epoch,
}
impl From<WorkerCache> for SharedWorkerCache {
fn from(worker_cache: WorkerCache) -> Self {
Arc::new(ArcSwap::from_pointee(worker_cache))
}
}
impl std::fmt::Display for WorkerIndex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"WorkerIndex {:?}",
self.0
.iter()
.map(|(key, value)| { format!("{}:{:?}", key, value) })
.collect::<Vec<_>>()
)
}
}
impl std::fmt::Display for WorkerCache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"WorkerCache E{}: {:?}",
self.epoch(),
self.workers
.iter()
.map(|(k, v)| { format!("{}: {}", k.encode_base64().get(0..16).unwrap(), v) })
.collect::<Vec<_>>()
)
}
}
impl WorkerCache {
pub fn epoch(&self) -> Epoch {
self.epoch
}
pub fn worker(&self, to: &PublicKey, id: &WorkerId) -> Result<WorkerInfo, ConfigError> {
self.workers
.iter()
.find_map(|v| match_opt::match_opt!(v, (name, authority) if name == to => authority))
.ok_or_else(|| {
ConfigError::NotInWorkerCache(ToString::to_string(&(*to).encode_base64()))
})?
.0
.iter()
.find(|(worker_id, _)| worker_id == &id)
.map(|(_, worker)| worker.clone())
.ok_or_else(|| ConfigError::NotInWorkerCache((*to).encode_base64()))
}
pub fn our_workers(&self, myself: &PublicKey) -> Result<Vec<WorkerInfo>, ConfigError> {
let res = self
.workers
.iter()
.find_map(
|v| match_opt::match_opt!(v, (name, authority) if name == myself => authority),
)
.ok_or_else(|| ConfigError::NotInWorkerCache((*myself).encode_base64()))?
.0
.values()
.cloned()
.collect();
Ok(res)
}
pub fn all_workers(&self) -> Vec<(NetworkPublicKey, Multiaddr)> {
self.workers
.iter()
.flat_map(|(_, w)| {
w.0.values()
.map(|w| (w.name.clone(), w.worker_address.clone()))
})
.collect()
}
pub fn others_workers(
&self,
myself: &PublicKey,
id: &WorkerId,
) -> Vec<(PublicKey, WorkerInfo)> {
self.workers
.iter()
.filter(|(name, _)| *name != myself )
.flat_map(
|(name, authority)| authority.0.iter().flat_map(
|v| match_opt::match_opt!(v,(worker_id, addresses) if worker_id == id => (name.clone(), addresses.clone()))))
.collect()
}
pub fn network_diff(&self, keys: Vec<&PublicKey>) -> HashSet<&Multiaddr> {
self.workers
.iter()
.filter(|(name, _)| !keys.contains(name))
.flat_map(|(_, authority)| {
authority
.0
.values()
.map(|address| &address.transactions)
.chain(authority.0.values().map(|address| &address.worker_address))
})
.collect()
}
}
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct Authority {
pub stake: Stake,
pub primary_address: Multiaddr,
pub network_key: NetworkPublicKey,
}
pub type SharedCommittee = Arc<ArcSwap<Committee>>;
#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct Committee {
pub authorities: BTreeMap<PublicKey, Authority>,
pub epoch: Epoch,
}
impl std::fmt::Display for Committee {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Committee E{}: {:?}",
self.epoch(),
self.authorities
.keys()
.map(|x| { x.encode_base64().get(0..16).unwrap().to_string() })
.collect::<Vec<_>>()
)
}
}
impl Committee {
pub fn epoch(&self) -> Epoch {
self.epoch
}
pub fn keys(&self) -> Vec<&PublicKey> {
self.authorities.keys().clone().collect::<Vec<&PublicKey>>()
}
pub fn authorities(&self) -> impl Iterator<Item = (&PublicKey, &Authority)> {
self.authorities.iter()
}
pub fn size(&self) -> usize {
self.authorities.len()
}
pub fn stake(&self, name: &PublicKey) -> Stake {
self.authorities
.get(&name.clone())
.map_or_else(|| 0, |x| x.stake)
}
pub fn quorum_threshold(&self) -> Stake {
let total_votes: Stake = self.authorities.values().map(|x| x.stake).sum();
2 * total_votes / 3 + 1
}
pub fn validity_threshold(&self) -> Stake {
let total_votes: Stake = self.authorities.values().map(|x| x.stake).sum();
(total_votes + 2) / 3
}
pub fn leader(&self, seed: u64) -> PublicKey {
let mut seed_bytes = [0u8; 32];
seed_bytes[32 - 8..].copy_from_slice(&seed.to_le_bytes());
let mut rng = StdRng::from_seed(seed_bytes);
let choices = self
.authorities
.iter()
.map(|(name, authority)| (name, authority.stake as f32))
.collect::<Vec<_>>();
choices
.choose_weighted(&mut rng, |item| item.1)
.expect("Weighted choice error: stake values incorrect!")
.0
.clone()
}
pub fn primary(&self, to: &PublicKey) -> Result<Multiaddr, ConfigError> {
self.authorities
.get(&to.clone())
.map(|x| x.primary_address.clone())
.ok_or_else(|| ConfigError::NotInCommittee((*to).encode_base64()))
}
pub fn network_key(&self, pk: &PublicKey) -> Result<NetworkPublicKey, ConfigError> {
self.authorities
.get(&pk.clone())
.map(|x| x.network_key.clone())
.ok_or_else(|| ConfigError::NotInCommittee((*pk).encode_base64()))
}
pub fn others_primaries(
&self,
myself: &PublicKey,
) -> Vec<(PublicKey, Multiaddr, NetworkPublicKey)> {
self.authorities
.iter()
.filter(|(name, _)| *name != myself)
.map(|(name, authority)| {
(
name.clone(),
authority.primary_address.clone(),
authority.network_key.clone(),
)
})
.collect()
}
fn get_all_network_addresses(&self) -> HashSet<&Multiaddr> {
self.authorities
.values()
.map(|authority| &authority.primary_address)
.collect()
}
pub fn network_diff<'a>(&'a self, other: &'a Self) -> HashSet<&Multiaddr> {
self.get_all_network_addresses()
.difference(&other.get_all_network_addresses())
.cloned()
.collect()
}
pub fn update_primary_network_info(
&mut self,
mut new_info: BTreeMap<PublicKey, (Stake, Multiaddr)>,
) -> Result<(), Vec<CommitteeUpdateError>> {
let mut errors = None;
let table = &self.authorities;
let push_error_and_return = |acc, error| {
let mut error_table = if let Err(errors) = acc {
errors
} else {
Vec::new()
};
error_table.push(error);
Err(error_table)
};
let res = table
.iter()
.fold(Ok(BTreeMap::new()), |acc, (pk, authority)| {
if let Some((stake, address)) = new_info.remove(pk) {
if stake == authority.stake {
match acc {
Ok(mut bmap) => {
let mut res = authority.clone();
res.primary_address = address;
bmap.insert(pk.clone(), res);
Ok(bmap)
}
_ => acc,
}
} else {
push_error_and_return(
acc,
CommitteeUpdateError::DifferentStake(pk.to_string()),
)
}
} else {
push_error_and_return(
acc,
CommitteeUpdateError::MissingFromUpdate(pk.to_string()),
)
}
});
let res = new_info.iter().fold(res, |acc, (pk, _)| {
push_error_and_return(acc, CommitteeUpdateError::NotInCommittee(pk.to_string()))
});
match res {
Ok(new_table) => self.authorities = new_table,
Err(errs) => {
errors = Some(errs);
}
};
errors.map(Err).unwrap_or(Ok(()))
}
}
#[cfg(test)]
mod tests {
use crate::Parameters;
use tracing_test::traced_test;
#[test]
#[traced_test]
fn tracing_should_print_parameters() {
let parameters = Parameters::default();
parameters.tracing();
assert!(logs_contain("Header size set to 1000 B"));
assert!(logs_contain("Max header delay set to 100 ms"));
assert!(logs_contain("Garbage collection depth set to 50 rounds"));
assert!(logs_contain("Sync retry delay set to 5000 ms"));
assert!(logs_contain("Sync retry nodes set to 3 nodes"));
assert!(logs_contain("Batch size set to 500000 B"));
assert!(logs_contain("Max batch delay set to 100 ms"));
assert!(logs_contain("Synchronize certificates timeout set to 30 s"));
assert!(logs_contain(
"Payload (batches) availability timeout set to 30 s"
));
assert!(logs_contain(
"Synchronize payload (batches) timeout set to 30 s"
));
assert!(logs_contain(
"Handler certificate deliver timeout set to 30 s"
));
assert!(logs_contain(
"Consensus API gRPC Server set to listen on on /ip4/127.0.0.1/tcp"
));
assert!(logs_contain("Get collections timeout set to 5000 ms"));
assert!(logs_contain("Remove collections timeout set to 5000 ms"));
assert!(logs_contain("Max concurrent requests set to 500000"));
assert!(logs_contain(
"Prometheus metrics server will run on /ip4/127.0.0.1/tcp"
));
}
}