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
use crate::{
block_remover::DeleteBatchResult,
block_synchronizer::{
handler::BlockSynchronizerHandler,
responses::{AvailabilityResponse, CertificateDigestsResponse},
BlockSynchronizer,
},
block_waiter::{BatchMessageError, BatchResult, BlockWaiter},
certificate_waiter::CertificateWaiter,
core::Core,
grpc_server::ConsensusAPIGrpc,
header_waiter::HeaderWaiter,
helper::Helper,
metrics::{initialise_metrics, PrimaryMetrics},
payload_receiver::PayloadReceiver,
proposer::Proposer,
state_handler::StateHandler,
synchronizer::Synchronizer,
BlockCommand, BlockRemover, CertificatesResponse, DeleteBatchMessage,
PayloadAvailabilityResponse,
};
use anemo::{types::PeerInfo, PeerId};
use anemo_tower::{callback::CallbackLayer, trace::TraceLayer};
use async_trait::async_trait;
use config::{Parameters, SharedCommittee, SharedWorkerCache, WorkerId, WorkerInfo};
use consensus::dag::Dag;
use crypto::{KeyPair, NetworkKeyPair, PublicKey};
use fastcrypto::{
traits::{EncodeDecodeBase64, KeyPair as _},
SignatureService,
};
use multiaddr::Protocol;
use network::metrics::MetricsMakeCallbackHandler;
use network::P2pNetwork;
use prometheus::Registry;
use std::{collections::BTreeMap, net::Ipv4Addr, sync::Arc};
use storage::CertificateStore;
use store::Store;
use tokio::sync::oneshot;
use tokio::{sync::watch, task::JoinHandle};
use tower::ServiceBuilder;
use tracing::info;
use types::{
error::DagError,
metered_channel::{channel, Receiver, Sender},
BatchDigest, BatchMessage, Certificate, Header, HeaderDigest, PrimaryToPrimary,
PrimaryToPrimaryServer, ReconfigureNotification, RoundVoteDigestPair, WorkerInfoResponse,
WorkerPrimaryError, WorkerPrimaryMessage, WorkerToPrimary, WorkerToPrimaryServer,
};
pub use types::{PrimaryMessage, PrimaryWorkerMessage};
pub const CHANNEL_CAPACITY: usize = 1_000;
pub type PayloadToken = u8;
pub enum NetworkModel {
PartiallySynchronous,
Asynchronous,
}
pub struct Primary;
impl Primary {
const INADDR_ANY: Ipv4Addr = Ipv4Addr::new(0, 0, 0, 0);
#[allow(clippy::too_many_arguments)]
pub fn spawn(
name: PublicKey,
signer: KeyPair,
network_signer: NetworkKeyPair,
committee: SharedCommittee,
worker_cache: SharedWorkerCache,
parameters: Parameters,
header_store: Store<HeaderDigest, Header>,
certificate_store: CertificateStore,
payload_store: Store<(BatchDigest, WorkerId), PayloadToken>,
vote_digest_store: Store<PublicKey, RoundVoteDigestPair>,
tx_consensus: Sender<Certificate>,
rx_consensus: Receiver<Certificate>,
tx_get_block_commands: Sender<BlockCommand>,
rx_get_block_commands: Receiver<BlockCommand>,
dag: Option<Arc<Dag>>,
network_model: NetworkModel,
tx_reconfigure: watch::Sender<ReconfigureNotification>,
tx_committed_certificates: Sender<Certificate>,
registry: &Registry,
rx_executor_network: Option<oneshot::Sender<P2pNetwork>>,
) -> Vec<JoinHandle<()>> {
parameters.tracing();
let metrics = initialise_metrics(registry);
let endpoint_metrics = metrics.endpoint_metrics.unwrap();
let mut primary_channel_metrics = metrics.primary_channel_metrics.unwrap();
let inbound_network_metrics = Arc::new(metrics.inbound_network_metrics.unwrap());
let outbound_network_metrics = Arc::new(metrics.outbound_network_metrics.unwrap());
let node_metrics = Arc::new(metrics.node_metrics.unwrap());
let (tx_others_digests, rx_others_digests) =
channel(CHANNEL_CAPACITY, &primary_channel_metrics.tx_others_digests);
let (tx_our_digests, rx_our_digests) =
channel(CHANNEL_CAPACITY, &primary_channel_metrics.tx_our_digests);
let (tx_parents, rx_parents) =
channel(CHANNEL_CAPACITY, &primary_channel_metrics.tx_parents);
let (tx_headers, rx_headers) =
channel(CHANNEL_CAPACITY, &primary_channel_metrics.tx_headers);
let (tx_sync_headers, rx_sync_headers) =
channel(CHANNEL_CAPACITY, &primary_channel_metrics.tx_sync_headers);
let (tx_sync_certificates, rx_sync_certificates) = channel(
CHANNEL_CAPACITY,
&primary_channel_metrics.tx_sync_certificates,
);
let (tx_headers_loopback, rx_headers_loopback) = channel(
CHANNEL_CAPACITY,
&primary_channel_metrics.tx_headers_loopback,
);
let (tx_certificates_loopback, rx_certificates_loopback) = channel(
CHANNEL_CAPACITY,
&primary_channel_metrics.tx_certificates_loopback,
);
let (tx_primary_messages, rx_primary_messages) = channel(
CHANNEL_CAPACITY,
&primary_channel_metrics.tx_primary_messages,
);
let (tx_helper_requests, rx_helper_requests) = channel(
CHANNEL_CAPACITY,
&primary_channel_metrics.tx_helper_requests,
);
let (tx_batches, rx_batches) =
channel(CHANNEL_CAPACITY, &primary_channel_metrics.tx_batches);
let (tx_block_removal_commands, rx_block_removal_commands) = channel(
CHANNEL_CAPACITY,
&primary_channel_metrics.tx_block_removal_commands,
);
let (tx_batch_removal, rx_batch_removal) =
channel(CHANNEL_CAPACITY, &primary_channel_metrics.tx_batch_removal);
let (tx_block_synchronizer_commands, rx_block_synchronizer_commands) = channel(
CHANNEL_CAPACITY,
&primary_channel_metrics.tx_block_synchronizer_commands,
);
let (tx_availability_responses, rx_availability_responses) = channel(
CHANNEL_CAPACITY,
&primary_channel_metrics.tx_availability_responses,
);
let (tx_state_handler, rx_state_handler) =
channel(CHANNEL_CAPACITY, &primary_channel_metrics.tx_state_handler);
let committed_certificates_gauge = tx_committed_certificates.gauge().clone();
primary_channel_metrics.replace_registered_committed_certificates_metric(
registry,
Box::new(committed_certificates_gauge),
);
let new_certificates_gauge = tx_consensus.gauge().clone();
primary_channel_metrics
.replace_registered_new_certificates_metric(registry, Box::new(new_certificates_gauge));
let tx_get_block_commands_gauge = tx_get_block_commands.gauge().clone();
primary_channel_metrics.replace_registered_get_block_commands_metric(
registry,
Box::new(tx_get_block_commands_gauge),
);
let (tx_consensus_round_updates, rx_consensus_round_updates) = watch::channel(0u64);
let our_workers = worker_cache
.load()
.workers
.get(&name)
.expect("Our public key is not in the worker cache")
.0
.clone();
let address = committee
.load()
.primary(&name)
.expect("Our public key or worker id is not in the committee");
let address = address
.replace(0, |_protocol| Some(Protocol::Ip4(Primary::INADDR_ANY)))
.unwrap();
let primary_service = PrimaryToPrimaryServer::new(PrimaryReceiverHandler {
tx_primary_messages: tx_primary_messages.clone(),
tx_helper_requests,
tx_availability_responses,
});
let worker_service = WorkerToPrimaryServer::new(WorkerReceiverHandler {
tx_our_digests,
tx_others_digests,
tx_batches,
tx_batch_removal,
tx_state_handler,
our_workers,
metrics: node_metrics.clone(),
});
let addr = network::multiaddr_to_address(&address).unwrap();
let routes = anemo::Router::new()
.add_rpc_service(primary_service)
.add_rpc_service(worker_service);
let service = ServiceBuilder::new()
.layer(TraceLayer::new())
.layer(CallbackLayer::new(MetricsMakeCallbackHandler::new(
inbound_network_metrics,
)))
.service(routes);
let outbound_layer = ServiceBuilder::new()
.layer(TraceLayer::new())
.layer(CallbackLayer::new(MetricsMakeCallbackHandler::new(
outbound_network_metrics,
)))
.into_inner();
let network = anemo::Network::bind(addr.clone())
.server_name("narwhal")
.private_key(network_signer.copy().private().0.to_bytes())
.outbound_request_layer(outbound_layer)
.start(service)
.unwrap_or_else(|_| {
panic!(
"Address {} should be available for the primary Narwhal service",
addr
)
});
info!("Primary {} listening on {}", name.encode_base64(), address);
let primaries = committee
.load()
.others_primaries(&name)
.into_iter()
.map(|(_, address, network_key)| (network_key, address));
let workers = worker_cache.load().all_workers().into_iter();
for (public_key, address) in primaries.chain(workers) {
let peer_id = PeerId(public_key.0.to_bytes());
let address = network::multiaddr_to_address(&address).unwrap();
let peer_info = PeerInfo {
peer_id,
affinity: anemo::types::PeerAffinity::High,
address: vec![address],
};
network.known_peers().insert(peer_info);
}
let synchronizer = Synchronizer::new(
name.clone(),
&committee.load(),
certificate_store.clone(),
payload_store.clone(),
tx_sync_headers,
tx_sync_certificates,
dag.clone(),
);
let signature_service = SignatureService::new(signer);
if let Some(rx_executor_network) = rx_executor_network {
let executor_network = P2pNetwork::new(network.clone());
if rx_executor_network.send(executor_network).is_err() {
panic!("Executor shut down before primary has a chance to start");
}
}
let core_primary_network = P2pNetwork::new(network.clone());
let core_handle = Core::spawn(
name.clone(),
(**committee.load()).clone(),
worker_cache.clone(),
header_store.clone(),
certificate_store.clone(),
vote_digest_store,
synchronizer,
signature_service.clone(),
tx_consensus_round_updates.subscribe(),
parameters.gc_depth,
tx_reconfigure.subscribe(),
rx_primary_messages,
rx_headers_loopback,
rx_certificates_loopback,
rx_headers,
tx_consensus,
tx_parents,
node_metrics.clone(),
core_primary_network,
);
let payload_receiver_handle = PayloadReceiver::spawn(
payload_store.clone(),
rx_others_digests,
);
let block_synchronizer_handler = Arc::new(BlockSynchronizerHandler::new(
tx_block_synchronizer_commands,
tx_primary_messages,
certificate_store.clone(),
parameters
.block_synchronizer
.handler_certificate_deliver_timeout,
));
let block_waiter_primary_network = P2pNetwork::new(network.clone());
let block_waiter_handle = BlockWaiter::spawn(
name.clone(),
(**committee.load()).clone(),
worker_cache.clone(),
tx_reconfigure.subscribe(),
rx_get_block_commands,
rx_batches,
block_synchronizer_handler.clone(),
block_waiter_primary_network,
);
let internal_consensus = dag.is_none();
let block_remover_primary_network = P2pNetwork::new(network.clone());
let block_remover_handle = BlockRemover::spawn(
name.clone(),
(**committee.load()).clone(),
worker_cache.clone(),
certificate_store.clone(),
header_store,
payload_store.clone(),
dag.clone(),
block_remover_primary_network,
tx_reconfigure.subscribe(),
rx_block_removal_commands,
rx_batch_removal,
tx_committed_certificates,
);
let block_synchronizer_network = P2pNetwork::new(network.clone());
let block_synchronizer_handle = BlockSynchronizer::spawn(
name.clone(),
(**committee.load()).clone(),
worker_cache.clone(),
tx_reconfigure.subscribe(),
rx_block_synchronizer_commands,
rx_availability_responses,
block_synchronizer_network,
payload_store.clone(),
certificate_store.clone(),
parameters.clone(),
);
let header_waiter_primary_network = P2pNetwork::new(network.clone());
let header_waiter_handle = HeaderWaiter::spawn(
name.clone(),
(**committee.load()).clone(),
worker_cache.clone(),
certificate_store.clone(),
payload_store.clone(),
tx_consensus_round_updates.subscribe(),
parameters.gc_depth,
parameters.sync_retry_delay,
parameters.sync_retry_nodes,
tx_reconfigure.subscribe(),
rx_sync_headers,
tx_headers_loopback,
node_metrics.clone(),
header_waiter_primary_network,
);
let certificate_waiter_handle = CertificateWaiter::spawn(
(**committee.load()).clone(),
certificate_store.clone(),
rx_consensus_round_updates,
parameters.gc_depth,
tx_reconfigure.subscribe(),
rx_sync_certificates,
tx_certificates_loopback,
node_metrics.clone(),
);
let proposer_handle = Proposer::spawn(
name.clone(),
(**committee.load()).clone(),
signature_service,
parameters.header_size,
parameters.max_header_delay,
network_model,
tx_reconfigure.subscribe(),
rx_parents,
rx_our_digests,
tx_headers,
node_metrics,
);
let helper_primary_network = P2pNetwork::new(network.clone());
let helper_handle = Helper::spawn(
name.clone(),
(**committee.load()).clone(),
certificate_store,
payload_store,
tx_reconfigure.subscribe(),
rx_helper_requests,
helper_primary_network,
);
let state_handler_handle = StateHandler::spawn(
name.clone(),
committee.clone(),
worker_cache,
rx_consensus,
tx_consensus_round_updates,
rx_state_handler,
tx_reconfigure,
P2pNetwork::new(network),
);
let consensus_api_handle = if !internal_consensus {
Some(ConsensusAPIGrpc::spawn(
name.clone(),
parameters.consensus_api_grpc.socket_addr,
tx_get_block_commands,
tx_block_removal_commands,
parameters.consensus_api_grpc.get_collections_timeout,
parameters.consensus_api_grpc.remove_collections_timeout,
block_synchronizer_handler,
dag,
committee.clone(),
endpoint_metrics,
))
} else {
None
};
info!(
"Primary {} successfully booted on {}",
name.encode_base64(),
committee
.load()
.primary(&name)
.expect("Our public key or worker id is not in the committee")
);
let mut handles = vec![
core_handle,
payload_receiver_handle,
block_synchronizer_handle,
block_waiter_handle,
block_remover_handle,
header_waiter_handle,
certificate_waiter_handle,
proposer_handle,
helper_handle,
state_handler_handle,
];
if let Some(h) = consensus_api_handle {
handles.push(h);
}
handles
}
}
#[derive(Clone)]
struct PrimaryReceiverHandler {
tx_primary_messages: Sender<PrimaryMessage>,
tx_helper_requests: Sender<PrimaryMessage>,
tx_availability_responses: Sender<AvailabilityResponse>,
}
#[async_trait]
impl PrimaryToPrimary for PrimaryReceiverHandler {
async fn send_message(
&self,
request: anemo::Request<PrimaryMessage>,
) -> Result<anemo::Response<()>, anemo::rpc::Status> {
let message = request.into_body();
match message {
PrimaryMessage::CertificatesRequest(_, _) => self
.tx_helper_requests
.send(message)
.await
.map_err(|_| DagError::ShuttingDown),
PrimaryMessage::CertificatesRangeResponse {
certificate_ids,
from,
} => self
.tx_availability_responses
.send(AvailabilityResponse::CertificateDigest(
CertificateDigestsResponse {
certificate_ids,
from,
},
))
.await
.map_err(|_| DagError::ShuttingDown),
PrimaryMessage::CertificatesBatchRequest { .. } => self
.tx_helper_requests
.send(message)
.await
.map_err(|_| DagError::ShuttingDown),
PrimaryMessage::CertificatesBatchResponse { certificates, from } => self
.tx_availability_responses
.send(AvailabilityResponse::Certificate(CertificatesResponse {
certificates,
from,
}))
.await
.map_err(|_| DagError::ShuttingDown),
PrimaryMessage::PayloadAvailabilityRequest { .. } => self
.tx_helper_requests
.send(message)
.await
.map_err(|_| DagError::ShuttingDown),
PrimaryMessage::PayloadAvailabilityResponse {
payload_availability,
from,
} => self
.tx_availability_responses
.send(AvailabilityResponse::Payload(PayloadAvailabilityResponse {
block_ids: payload_availability.to_vec(),
from: from.clone(),
}))
.await
.map_err(|_| DagError::ShuttingDown),
_ => self
.tx_primary_messages
.send(message)
.await
.map_err(|_| DagError::ShuttingDown),
}
.map(|_| anemo::Response::new(()))
.map_err(|e| anemo::rpc::Status::internal(e.to_string()))
}
}
#[derive(Clone)]
struct WorkerReceiverHandler {
tx_our_digests: Sender<(BatchDigest, WorkerId)>,
tx_others_digests: Sender<(BatchDigest, WorkerId)>,
tx_batches: Sender<BatchResult>,
tx_batch_removal: Sender<DeleteBatchResult>,
tx_state_handler: Sender<ReconfigureNotification>,
our_workers: BTreeMap<WorkerId, WorkerInfo>,
metrics: Arc<PrimaryMetrics>,
}
#[async_trait]
impl WorkerToPrimary for WorkerReceiverHandler {
async fn send_message(
&self,
request: anemo::Request<types::WorkerPrimaryMessage>,
) -> Result<anemo::Response<()>, anemo::rpc::Status> {
let message = request.into_body();
match message {
WorkerPrimaryMessage::OurBatch(digest, worker_id) => {
self.metrics
.batches_received
.with_label_values(&[&worker_id.to_string(), "our_batch"])
.inc();
self.tx_our_digests
.send((digest, worker_id))
.await
.map_err(|_| DagError::ShuttingDown)
}
WorkerPrimaryMessage::OthersBatch(digest, worker_id) => {
self.metrics
.batches_received
.with_label_values(&[&worker_id.to_string(), "others_batch"])
.inc();
self.tx_others_digests
.send((digest, worker_id))
.await
.map_err(|_| DagError::ShuttingDown)
}
WorkerPrimaryMessage::RequestedBatch(digest, transactions) => self
.tx_batches
.send(Ok(BatchMessage {
id: digest,
transactions,
}))
.await
.map_err(|_| DagError::ShuttingDown),
WorkerPrimaryMessage::DeletedBatches(batch_ids) => self
.tx_batch_removal
.send(Ok(DeleteBatchMessage { ids: batch_ids }))
.await
.map_err(|_| DagError::ShuttingDown),
WorkerPrimaryMessage::Error(error) => match error.clone() {
WorkerPrimaryError::RequestedBatchNotFound(digest) => self
.tx_batches
.send(Err(BatchMessageError { id: digest }))
.await
.map_err(|_| DagError::ShuttingDown),
WorkerPrimaryError::ErrorWhileDeletingBatches(batch_ids) => self
.tx_batch_removal
.send(Err(DeleteBatchMessage { ids: batch_ids }))
.await
.map_err(|_| DagError::ShuttingDown),
},
WorkerPrimaryMessage::Reconfigure(notification) => self
.tx_state_handler
.send(notification)
.await
.map_err(|_| DagError::ShuttingDown),
}
.map(|_| anemo::Response::new(()))
.map_err(|e| anemo::rpc::Status::internal(e.to_string()))
}
async fn worker_info(
&self,
_request: anemo::Request<()>,
) -> Result<anemo::Response<WorkerInfoResponse>, anemo::rpc::Status> {
Ok(anemo::Response::new(WorkerInfoResponse {
workers: self.our_workers.clone(),
}))
}
}