-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathgateway.rs
More file actions
2085 lines (1882 loc) · 90 KB
/
Copy pathgateway.rs
File metadata and controls
2085 lines (1882 loc) · 90 KB
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019-2026 Provable Inc.
// This file is part of the snarkOS library.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(feature = "telemetry")]
use crate::helpers::Telemetry;
use crate::{
CONTEXT,
MAX_BATCH_DELAY,
MEMORY_POOL_PORT,
Worker,
events::{DisconnectReason, EventCodec, PrimaryPing},
helpers::{Cache, PrimarySender, Storage, SyncSender, WorkerSender, assign_to_worker},
spawn_blocking,
};
use smol_str::SmolStr;
use snarkos_account::Account;
use snarkos_node_bft_events::{
BlockRequest,
BlockResponse,
CertificateRequest,
CertificateResponse,
ChallengeRequest,
ChallengeResponse,
DataBlocks,
Event,
EventTrait,
TransmissionRequest,
TransmissionResponse,
ValidatorsRequest,
ValidatorsResponse,
};
use snarkos_node_bft_ledger_service::LedgerService;
use snarkos_node_network::{
ConnectionMode,
NodeType,
Peer,
PeerPoolHandling,
Resolver,
bootstrap_peers,
get_repo_commit_hash,
log_repo_sha_comparison,
shorten_snarkos_sha,
};
use snarkos_node_sync::{MAX_BLOCKS_BEHIND, communication_service::CommunicationService};
use snarkos_node_tcp::{
Config,
ConnectError,
Connection,
ConnectionSide,
P2P,
Tcp,
connections::DisconnectOrigin,
protocols::{Disconnect, Handshake, OnConnect, Reading, Writing},
};
use snarkos_utilities::NodeDataDir;
use snarkvm::{
console::prelude::*,
ledger::{
committee::Committee,
narwhal::{BatchHeader, Data},
},
prelude::{Address, Field},
utilities::flatten_error,
};
use colored::Colorize;
use futures::{SinkExt, future::join_all};
use indexmap::IndexMap;
#[cfg(feature = "locktick")]
use locktick::parking_lot::{Mutex, RwLock};
#[cfg(not(feature = "locktick"))]
use parking_lot::{Mutex, RwLock};
use rand::seq::{IteratorRandom, SliceRandom};
use std::{
collections::{HashMap, HashSet},
future::Future,
io,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
sync::Arc,
time::Duration,
};
use tokio::{
net::TcpStream,
sync::{OnceCell, oneshot},
task::{self, JoinHandle},
};
use tokio_stream::StreamExt;
use tokio_util::codec::Framed;
/// The maximum interval of events to cache.
const CACHE_EVENTS_INTERVAL: i64 = (MAX_BATCH_DELAY.as_secs()) as i64; // seconds
/// The maximum interval of requests to cache.
const CACHE_REQUESTS_INTERVAL: i64 = (MAX_BATCH_DELAY.as_secs()) as i64; // seconds
/// The maximum number of connection attempts in an interval.
#[cfg(not(test))]
const MAX_CONNECTION_ATTEMPTS: usize = 10;
/// The maximum number of validators to send in a validators response event.
pub const MAX_VALIDATORS_TO_SEND: usize = 200;
/// The minimum permitted interval between connection attempts for an IP; anything shorter is considered malicious.
#[cfg(not(test))]
const CONNECTION_ATTEMPTS_SINCE_SECS: i64 = 10;
/// The amount of time an IP address is prohibited from connecting.
const IP_BAN_TIME_IN_SECS: u64 = 300;
/// Part of the Gateway API that deals with networking.
/// This is a separate trait to allow for easier testing/mocking.
#[async_trait]
pub trait Transport<N: Network>: Send + Sync {
async fn send(&self, peer_ip: SocketAddr, event: Event<N>) -> Option<oneshot::Receiver<io::Result<()>>>;
fn broadcast(&self, event: Event<N>);
}
/// The gateway maintains connections to other validators.
/// For connections with clients and provers, the Router logic is used.
#[derive(Clone)]
pub struct Gateway<N: Network>(Arc<InnerGateway<N>>);
impl<N: Network> Deref for Gateway<N> {
type Target = Arc<InnerGateway<N>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub struct InnerGateway<N: Network> {
/// The account of the node.
account: Account<N>,
/// The storage.
storage: Storage<N>,
/// The ledger service.
ledger: Arc<dyn LedgerService<N>>,
/// The TCP stack.
tcp: Tcp,
/// The cache.
cache: Cache<N>,
/// The resolver.
resolver: RwLock<Resolver<N>>,
/// The collection of both candidate and connected peers.
peer_pool: RwLock<HashMap<SocketAddr, Peer<N>>>,
#[cfg(feature = "telemetry")]
validator_telemetry: Telemetry<N>,
/// The primary sender.
primary_sender: OnceCell<PrimarySender<N>>,
/// The worker senders.
worker_senders: OnceCell<IndexMap<u8, WorkerSender<N>>>,
/// The sync sender.
sync_sender: OnceCell<SyncSender<N>>,
/// The spawned handles.
handles: Mutex<Vec<JoinHandle<()>>>,
/// The storage mode.
node_data_dir: NodeDataDir,
/// If the flag is set, the node will only connect to trusted peers.
trusted_peers_only: bool,
/// The development mode.
dev: Option<u16>,
}
impl<N: Network> PeerPoolHandling<N> for Gateway<N> {
const MAXIMUM_POOL_SIZE: usize = 200;
const OWNER: &str = CONTEXT;
const PEER_SLASHING_COUNT: usize = 20;
fn peer_pool(&self) -> &RwLock<HashMap<SocketAddr, Peer<N>>> {
&self.peer_pool
}
fn resolver(&self) -> &RwLock<Resolver<N>> {
&self.resolver
}
fn is_dev(&self) -> bool {
self.dev.is_some()
}
fn trusted_peers_only(&self) -> bool {
self.trusted_peers_only
}
fn node_type(&self) -> NodeType {
NodeType::Validator
}
}
impl<N: Network> Gateway<N> {
/// Initializes a new gateway.
#[allow(clippy::too_many_arguments)]
pub fn new(
account: Account<N>,
storage: Storage<N>,
ledger: Arc<dyn LedgerService<N>>,
ip: Option<SocketAddr>,
trusted_validators: &[SocketAddr],
trusted_peers_only: bool,
node_data_dir: NodeDataDir,
dev: Option<u16>,
) -> Result<Self> {
// Initialize the gateway IP.
let ip = match (ip, dev) {
(None, Some(dev)) => SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, MEMORY_POOL_PORT + dev)),
(None, None) => SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, MEMORY_POOL_PORT)),
(Some(ip), _) => ip,
};
// Initialize the TCP stack.
//
// The 10x multiplier allows for more TCP connections than the maximum
// committee size to prevent "connection refused" errors when two nodes
// simultaneous attempt to connect to each other. Note, that later,
// during handshake, the Gateway applies its own limit to the number of
// active connections and removes duplicates.
let tcp = Tcp::new(Config::new(ip, Committee::<N>::max_committee_size() * 10));
// Prepare the collection of the initial peers.
let mut initial_peers = HashMap::new();
// Load entries from the validator cache (if present and if we are not in trusted peers only mode).
if !trusted_peers_only {
let cached_peers = Self::load_cached_peers(&node_data_dir.gateway_peer_cache_path())?;
for addr in cached_peers {
initial_peers.insert(addr, Peer::new_candidate(addr, false));
}
}
// Add the trusted peers to the list of the initial peers; this may promote
// some of the cached validators to trusted ones.
initial_peers.extend(trusted_validators.iter().copied().map(|addr| (addr, Peer::new_candidate(addr, true))));
// Return the gateway.
Ok(Self(Arc::new(InnerGateway {
account,
storage,
ledger,
tcp,
cache: Default::default(),
resolver: Default::default(),
peer_pool: RwLock::new(initial_peers),
#[cfg(feature = "telemetry")]
validator_telemetry: Default::default(),
primary_sender: Default::default(),
worker_senders: Default::default(),
sync_sender: Default::default(),
handles: Default::default(),
node_data_dir,
trusted_peers_only,
dev,
})))
}
/// Run the gateway.
pub async fn run(
&self,
primary_sender: PrimarySender<N>,
worker_senders: IndexMap<u8, WorkerSender<N>>,
sync_sender: Option<SyncSender<N>>,
) {
debug!("Starting the gateway for the memory pool...");
// Set the primary sender.
self.primary_sender.set(primary_sender).expect("Primary sender already set in gateway");
// Set the worker senders.
self.worker_senders.set(worker_senders).expect("The worker senders are already set");
// If the sync sender was provided, set the sync sender.
if let Some(sync_sender) = sync_sender {
self.sync_sender.set(sync_sender).expect("Sync sender already set in gateway");
}
// Enable the TCP protocols.
self.enable_handshake().await;
self.enable_reading().await;
self.enable_writing().await;
self.enable_disconnect().await;
self.enable_on_connect().await;
// Spawn a loop for periodic metrics.
#[cfg(feature = "metrics")]
{
let gateway = self.clone();
self.spawn(async move {
loop {
tokio::time::sleep(Duration::from_secs(1)).await;
gateway.update_metrics();
}
});
}
// Enable the TCP listener. Note: This must be called after the above protocols.
let listen_addr = self.tcp.enable_listener().await.expect("Failed to enable the TCP listener");
debug!("Listening for validator connections at address {listen_addr:?}");
// Initialize the heartbeat.
self.initialize_heartbeat();
info!("Started the gateway for the memory pool at '{}'", self.local_ip());
}
}
// Dynamic rate limiting.
impl<N: Network> Gateway<N> {
/// The current maximum committee size.
fn max_committee_size(&self) -> usize {
self.ledger
.current_committee()
.map_or_else(|_e| Committee::<N>::max_committee_size() as usize, |committee| committee.num_members())
}
/// The maximum number of events to cache.
fn max_cache_events(&self) -> usize {
self.max_cache_transmissions()
}
/// The maximum number of certificate requests to cache.
fn max_cache_certificates(&self) -> usize {
2 * BatchHeader::<N>::MAX_GC_ROUNDS * self.max_committee_size()
}
/// The maximum number of transmission requests to cache.
fn max_cache_transmissions(&self) -> usize {
self.max_cache_certificates() * BatchHeader::<N>::MAX_TRANSMISSIONS_PER_BATCH
}
/// The maximum number of duplicates for any particular request.
fn max_cache_duplicates(&self) -> usize {
self.max_committee_size().pow(2)
}
}
#[async_trait]
impl<N: Network> CommunicationService for Gateway<N> {
/// The message type.
type Message = Event<N>;
/// Prepares a block request to be sent.
fn prepare_block_request(start_height: u32, end_height: u32) -> Self::Message {
debug_assert!(start_height < end_height, "Invalid block request format");
Event::BlockRequest(BlockRequest { start_height, end_height })
}
/// Sends the given message to specified peer.
///
/// This function returns as soon as the message is queued to be sent,
/// without waiting for the actual delivery; instead, the caller is provided with a [`oneshot::Receiver`]
/// which can be used to determine when and whether the message has been delivered.
async fn send(&self, peer_ip: SocketAddr, message: Self::Message) -> Option<oneshot::Receiver<io::Result<()>>> {
Transport::send(self, peer_ip, message).await
}
}
impl<N: Network> Gateway<N> {
/// Returns the account of the node.
pub fn account(&self) -> &Account<N> {
&self.account
}
/// Returns the dev identifier of the node.
pub fn dev(&self) -> Option<u16> {
self.dev
}
/// Returns a reference to the ledger.
pub fn ledger(&self) -> &Arc<dyn LedgerService<N>> {
&self.ledger
}
/// Returns the resolver.
pub fn resolver(&self) -> &RwLock<Resolver<N>> {
&self.resolver
}
/// Returns the listener IP address from the (ambiguous) peer address.
pub fn resolve_to_listener(&self, connected_addr: &SocketAddr) -> Option<SocketAddr> {
self.resolver.read().get_listener(*connected_addr)
}
/// Returns the validator telemetry.
#[cfg(feature = "telemetry")]
pub fn validator_telemetry(&self) -> &Telemetry<N> {
&self.validator_telemetry
}
/// Returns the primary sender.
pub fn primary_sender(&self) -> &PrimarySender<N> {
self.primary_sender.get().expect("Primary sender not set in gateway")
}
/// Returns the number of workers.
pub fn num_workers(&self) -> u8 {
u8::try_from(self.worker_senders.get().expect("Missing worker senders in gateway").len())
.expect("Too many workers")
}
/// Returns the worker sender for the given worker ID.
pub fn get_worker_sender(&self, worker_id: u8) -> Option<&WorkerSender<N>> {
self.worker_senders.get().and_then(|senders| senders.get(&worker_id))
}
/// Returns `true` if the given peer IP is an authorized validator.
pub fn is_authorized_validator_ip(&self, ip: SocketAddr) -> bool {
// If the peer IP is in the trusted validators, return early.
if self.trusted_peers().contains(&ip) {
return true;
}
// Retrieve the Aleo address of the peer IP.
match self.resolve_to_aleo_addr(ip) {
// Determine if the peer IP is an authorized validator.
Some(address) => self.is_authorized_validator_address(address),
None => {
warn!("{CONTEXT} Could not resolve the Aleo address for '{ip}'");
false
}
}
}
/// Returns `true` if the given address is an authorized validator.
pub fn is_authorized_validator_address(&self, validator_address: Address<N>) -> bool {
// Determine if the validator address is a member of the committee lookback,
// the current committee, or the previous committee lookbacks.
// We allow leniency in this validation check in order to accommodate these two scenarios:
// 1. New validators should be able to connect immediately once bonded as a committee member.
// 2. Existing validators must remain connected until they are no longer bonded as a committee member.
// (i.e. meaning they must stay online until the next block has been produced)
// Determine if the validator is in the current committee with lookback.
if self
.ledger
.get_committee_lookback_for_round(self.storage.current_round())
.is_ok_and(|committee| committee.is_committee_member(validator_address))
{
return true;
}
// Determine if the validator is in the latest committee on the ledger.
if self.ledger.current_committee().is_ok_and(|committee| committee.is_committee_member(validator_address)) {
return true;
}
// Retrieve the previous block height to consider from the sync tolerance.
let previous_block_height = self.ledger.latest_block_height().saturating_sub(MAX_BLOCKS_BEHIND);
// Determine if the validator is in any of the previous committee lookbacks.
match self.ledger.get_block_round(previous_block_height) {
Ok(block_round) => (block_round..self.storage.current_round()).step_by(2).any(|round| {
self.ledger
.get_committee_lookback_for_round(round)
.is_ok_and(|committee| committee.is_committee_member(validator_address))
}),
Err(_) => false,
}
}
/// Returns the list of connected addresses.
pub fn connected_addresses(&self) -> HashSet<Address<N>> {
self.get_connected_peers().into_iter().map(|peer| peer.aleo_addr).collect()
}
/// Ensure the peer is allowed to connect.
fn ensure_peer_is_allowed(&self, listener_addr: SocketAddr) -> Result<(), DisconnectReason> {
// Ensure the peer IP is not this node.
if self.is_local_ip(listener_addr) {
return Err(DisconnectReason::SelfConnect);
}
Ok(())
}
/// Updates the connection metrics for the gateway. Ignores the bootstrap clients.
#[cfg(feature = "metrics")]
fn update_metrics(&self) {
if let Some(count) = self.number_of_connected_validators() {
metrics::gauge(metrics::bft::CONNECTED, count as f64);
}
if let Some(count) = self.number_of_connecting_peers() {
metrics::gauge(metrics::bft::CONNECTING, count as f64);
}
}
/// Inserts the given peer into the connected peers. This is only used in testing.
#[cfg(test)]
pub fn insert_connected_peer(&self, peer_ip: SocketAddr, peer_addr: SocketAddr, address: Address<N>) {
// Adds a bidirectional map between the listener address and (ambiguous) peer address.
self.resolver.write().insert_peer(peer_ip, peer_addr, Some(address));
// Add a transmission for this peer in the connected peers.
self.peer_pool.write().insert(peer_ip, Peer::new_connecting(peer_ip, false));
if let Some(peer) = self.peer_pool.write().get_mut(&peer_ip) {
peer.upgrade_to_connected(
peer_addr,
peer_ip.port(),
address,
NodeType::Validator,
0,
get_repo_commit_hash(),
ConnectionMode::Gateway,
);
}
}
/// Sends the given event to specified peer.
///
/// This function returns as soon as the event is queued to be sent,
/// without waiting for the actual delivery; instead, the caller is provided with a [`oneshot::Receiver`]
/// which can be used to determine when and whether the event has been delivered.
fn send_inner(&self, peer_ip: SocketAddr, event: Event<N>) -> Option<oneshot::Receiver<io::Result<()>>> {
// Resolve the listener IP to the (ambiguous) peer address.
let Some(peer_addr) = self.resolve_to_ambiguous(peer_ip) else {
warn!("Unable to resolve the listener IP address '{peer_ip}'");
return None;
};
// Retrieve the event name.
let name = event.name();
// Send the event to the peer.
trace!("{CONTEXT} Sending '{name}' to '{peer_ip}'");
let result = self.unicast(peer_addr, event);
// If the event was unable to be sent, disconnect.
if let Err(err) = &result {
warn!("{CONTEXT} Failed to send '{name}' to '{peer_ip}': {err:?}");
debug!("{CONTEXT} Disconnecting from '{peer_ip}' (unable to send)");
self.disconnect(peer_ip);
}
result.ok()
}
/// Handles the inbound event from the peer. The returned value indicates whether
/// the connection is still active, and errors cause a disconnect once they are
/// propagated to the caller.
async fn inbound(&self, peer_addr: SocketAddr, event: Event<N>) -> Result<bool> {
// Retrieve the listener IP for the peer.
let Some(peer_ip) = self.resolver.read().get_listener(peer_addr) else {
// No longer connected to the peer.
trace!("Dropping a {} from {peer_addr} - no longer connected.", event.name());
return Ok(false);
};
// Ensure that the peer is an authorized committee member or a bootstrapper.
if !(self.is_authorized_validator_ip(peer_ip)
|| self
.get_connected_peer(peer_ip)
.map(|peer| peer.node_type == NodeType::BootstrapClient)
.unwrap_or(false))
{
bail!("{CONTEXT} Dropping '{}' from '{peer_ip}' (not authorized)", event.name())
}
// Drop the peer, if they have exceeded the rate limit (i.e. they are requesting too much from us).
let num_events = self.cache.insert_inbound_event(peer_ip, CACHE_EVENTS_INTERVAL);
if num_events >= self.max_cache_events() {
bail!("Dropping '{peer_ip}' for spamming events (num_events = {num_events})")
}
// Rate limit for duplicate requests.
match event {
Event::CertificateRequest(_) | Event::CertificateResponse(_) => {
// Retrieve the certificate ID.
let certificate_id = match &event {
Event::CertificateRequest(CertificateRequest { certificate_id }) => *certificate_id,
Event::CertificateResponse(CertificateResponse { certificate }) => certificate.id(),
_ => unreachable!(),
};
// Skip processing this certificate if the rate limit was exceed (i.e. someone is spamming a specific certificate).
let num_events = self.cache.insert_inbound_certificate(certificate_id, CACHE_REQUESTS_INTERVAL);
if num_events >= self.max_cache_duplicates() {
return Ok(true);
}
}
Event::TransmissionRequest(TransmissionRequest { transmission_id })
| Event::TransmissionResponse(TransmissionResponse { transmission_id, .. }) => {
// Skip processing this certificate if the rate limit was exceeded (i.e. someone is spamming a specific certificate).
let num_events = self.cache.insert_inbound_transmission(transmission_id, CACHE_REQUESTS_INTERVAL);
if num_events >= self.max_cache_duplicates() {
return Ok(true);
}
}
Event::BlockRequest(_) => {
let num_events = self.cache.insert_inbound_block_request(peer_ip, CACHE_REQUESTS_INTERVAL);
if num_events >= self.max_cache_duplicates() {
return Ok(true);
}
}
_ => {}
}
trace!("{CONTEXT} Received '{}' from '{peer_ip}'", event.name());
// This match statement handles the inbound event by deserializing the event,
// checking the event is valid, and then calling the appropriate (trait) handler.
match event {
Event::BatchPropose(batch_propose) => {
// Send the batch propose to the primary.
let _ = self.primary_sender().tx_batch_propose.send((peer_ip, batch_propose)).await;
Ok(true)
}
Event::BatchSignature(batch_signature) => {
// Send the batch signature to the primary.
let _ = self.primary_sender().tx_batch_signature.send((peer_ip, batch_signature)).await;
Ok(true)
}
Event::BatchCertified(batch_certified) => {
// Send the batch certificate to the primary.
let _ = self.primary_sender().tx_batch_certified.send((peer_ip, batch_certified.certificate)).await;
Ok(true)
}
Event::BlockRequest(block_request) => {
let BlockRequest { start_height, end_height } = block_request;
// Ensure the block request is well-formed.
if start_height >= end_height {
bail!("Block request from '{peer_ip}' has an invalid range ({start_height}..{end_height})")
}
// Ensure that the block request is within the allowed bounds.
if end_height - start_height > DataBlocks::<N>::MAXIMUM_NUMBER_OF_BLOCKS as u32 {
bail!("Block request from '{peer_ip}' has an excessive range ({start_height}..{end_height})")
}
// End height is exclusive.
let latest_consensus_version = N::CONSENSUS_VERSION(end_height - 1)?;
let self_ = self.clone();
let blocks = match task::spawn_blocking(move || {
// Retrieve the blocks within the requested range.
match self_.ledger.get_blocks(start_height..end_height) {
Ok(blocks) => Ok(DataBlocks(blocks)),
Err(error) => bail!("Missing blocks {start_height} to {end_height} from ledger - {error}"),
}
})
.await
{
Ok(Ok(blocks)) => blocks,
Ok(Err(error)) => return Err(error),
Err(error) => return Err(anyhow!("[BlockRequest] {error}")),
};
let self_ = self.clone();
tokio::spawn(async move {
// Send the `BlockResponse` message to the peer.
let event =
Event::BlockResponse(BlockResponse::new(block_request, blocks, latest_consensus_version));
Transport::send(&self_, peer_ip, event).await;
});
Ok(true)
}
Event::BlockResponse(BlockResponse { request, latest_consensus_version, blocks, .. }) => {
// Process the block response. Except for some tests, there is always a sync sender.
if let Some(sync_sender) = self.sync_sender.get() {
// Check the response corresponds to a request.
if !self.cache.remove_outbound_block_request(peer_ip, &request) {
bail!("Unsolicited block response from '{peer_ip}'")
}
// Perform the deferred non-blocking deserialization of the blocks.
// The deserialization can take a long time (minutes). We should not be running
// this on a blocking task, but on a rayon thread pool.
let (send, recv) = tokio::sync::oneshot::channel();
rayon::spawn_fifo(move || {
let blocks = blocks.deserialize_blocking().map_err(|error| anyhow!("[BlockResponse] {error}"));
let _ = send.send(blocks);
});
let blocks = match recv.await {
Ok(Ok(blocks)) => blocks,
Ok(Err(error)) => bail!("Peer '{peer_ip}' sent an invalid block response - {error}"),
Err(error) => bail!("Peer '{peer_ip}' sent an invalid block response - {error}"),
};
// Ensure the block response is well-formed.
blocks.ensure_response_is_well_formed(peer_ip, request.start_height, request.end_height)?;
// Send the blocks to the sync module.
match sync_sender.insert_block_response(peer_ip, blocks.0, latest_consensus_version).await {
Ok(_) => Ok(true),
Err(err) if err.is_benign() => {
let err: anyhow::Error = err.into();
let err = err.context(format!("Ignoring block response from peer '{peer_ip}'"));
debug!("{}", flatten_error(err));
Ok(true)
}
Err(err) if err.is_invalid_consensus_version() => {
let err: anyhow::Error = err.into();
let err = err.context(format!("Peer sent an invalid block response '{peer_ip}'"));
let msg = flatten_error(&err);
error!("{msg}");
self.ip_ban_peer(peer_ip, Some(&msg));
Err(err)
}
Err(err) => {
let err: anyhow::Error = err.into();
let err = err.context(format!("Peer '{peer_ip}' sent an invalid block response"));
warn!("{}", flatten_error(err));
// TODO(kaimast): This needs more testing to ensure disconnect is the correct action.
Ok(true)
}
}
} else {
debug!("Ignoring block response from '{peer_ip}' - no sync sender");
Ok(true)
}
}
Event::CertificateRequest(certificate_request) => {
// Send the certificate request to the sync module.
// Except for some tests, there is always a sync sender.
if let Some(sync_sender) = self.sync_sender.get() {
// Send the certificate request to the sync module.
let _ = sync_sender.tx_certificate_request.send((peer_ip, certificate_request)).await;
}
Ok(true)
}
Event::CertificateResponse(certificate_response) => {
// Send the certificate response to the sync module.
// Except for some tests, there is always a sync sender.
if let Some(sync_sender) = self.sync_sender.get() {
// Send the certificate response to the sync module.
let _ = sync_sender.tx_certificate_response.send((peer_ip, certificate_response)).await;
}
Ok(true)
}
Event::ChallengeRequest(..) | Event::ChallengeResponse(..) => {
// Disconnect as the peer is not following the protocol.
bail!("{CONTEXT} Peer '{peer_ip}' is not following the protocol")
}
Event::Disconnect(message) => {
// The peer informs us that they had disconnected. Disconnect from them too.
debug!("Peer '{peer_ip}' decided to disconnect due to '{}'", message.reason);
self.disconnect(peer_ip);
Ok(false)
}
Event::PrimaryPing(ping) => {
let PrimaryPing { version, block_locators, primary_certificate } = ping;
// Ensure the event version is not outdated.
if version < Event::<N>::VERSION {
bail!("Dropping '{peer_ip}' on event version {version} (outdated)");
}
// Log the validator's height.
debug!("Validator '{peer_ip}' is at height {}", block_locators.latest_locator_height());
// Update the peer locators. Except for some tests, there is always a sync sender.
if let Some(sync_sender) = self.sync_sender.get() {
// Check the block locators are valid, and update the validators in the sync module.
if let Err(error) = sync_sender.update_peer_locators(peer_ip, block_locators).await {
bail!("Validator '{peer_ip}' sent invalid block locators - {error}");
}
}
// Send the batch certificates to the primary.
let _ = self.primary_sender().tx_primary_ping.send((peer_ip, primary_certificate)).await;
Ok(true)
}
Event::TransmissionRequest(request) => {
// TODO (howardwu): Add rate limiting checks on this event, on a per-peer basis.
// Determine the worker ID.
let Ok(worker_id) = assign_to_worker(request.transmission_id, self.num_workers()) else {
warn!("{CONTEXT} Unable to assign transmission ID '{}' to a worker", request.transmission_id);
return Ok(true);
};
// Send the transmission request to the worker.
if let Some(sender) = self.get_worker_sender(worker_id) {
// Send the transmission request to the worker.
let _ = sender.tx_transmission_request.send((peer_ip, request)).await;
}
Ok(true)
}
Event::TransmissionResponse(response) => {
// Determine the worker ID.
let Ok(worker_id) = assign_to_worker(response.transmission_id, self.num_workers()) else {
warn!("{CONTEXT} Unable to assign transmission ID '{}' to a worker", response.transmission_id);
return Ok(true);
};
// Send the transmission response to the worker.
if let Some(sender) = self.get_worker_sender(worker_id) {
// Send the transmission response to the worker.
let _ = sender.tx_transmission_response.send((peer_ip, response)).await;
}
Ok(true)
}
Event::ValidatorsRequest(_) => {
let mut connected_peers = self.get_best_connected_peers(Some(MAX_VALIDATORS_TO_SEND));
connected_peers.shuffle(&mut rand::rng());
let self_ = self.clone();
tokio::spawn(async move {
// Initialize the validators.
let mut validators = IndexMap::with_capacity(MAX_VALIDATORS_TO_SEND);
// Iterate over the validators.
for validator in connected_peers.into_iter() {
// Add the validator to the list of validators.
validators.insert(validator.listener_addr, validator.aleo_addr);
}
// Send the validators response to the peer.
let event = Event::ValidatorsResponse(ValidatorsResponse { validators });
Transport::send(&self_, peer_ip, event).await;
});
Ok(true)
}
Event::ValidatorsResponse(response) => {
if self.trusted_peers_only {
bail!("{CONTEXT} Not accepting validators response from '{peer_ip}' (trusted peers only)");
}
let ValidatorsResponse { validators } = response;
// Ensure the number of validators is not too large.
ensure!(validators.len() <= MAX_VALIDATORS_TO_SEND, "{CONTEXT} Received too many validators");
// Ensure the cache contains a validators request for this peer.
if !self.cache.contains_outbound_validators_request(peer_ip) {
bail!("{CONTEXT} Received validators response from '{peer_ip}' without a validators request")
}
// Decrement the number of validators requests for this peer.
self.cache.decrement_outbound_validators_requests(peer_ip);
// Add valid validators as candidates to the peer pool; only validator-related
// filters need to be applied, the rest is handled by `PeerPoolHandling`.
let valid_addrs = validators
.into_iter()
.filter_map(|(listener_addr, aleo_addr)| {
(self.account.address() != aleo_addr
&& !self.is_connected_address(aleo_addr)
&& self.is_authorized_validator_address(aleo_addr))
.then_some((listener_addr, None))
})
.collect::<Vec<_>>();
if !valid_addrs.is_empty() {
self.insert_candidate_peers(valid_addrs);
}
Ok(true)
}
Event::WorkerPing(ping) => {
// Ensure the number of transmissions is not too large.
ensure!(
ping.transmission_ids.len() <= Worker::<N>::MAX_TRANSMISSIONS_PER_WORKER_PING,
"{CONTEXT} Received too many transmissions"
);
// Retrieve the number of workers.
let num_workers = self.num_workers();
// Iterate over the transmission IDs.
for transmission_id in ping.transmission_ids.into_iter() {
// Determine the worker ID.
let Ok(worker_id) = assign_to_worker(transmission_id, num_workers) else {
warn!("{CONTEXT} Unable to assign transmission ID '{transmission_id}' to a worker");
continue;
};
// Send the transmission ID to the worker.
if let Some(sender) = self.get_worker_sender(worker_id) {
// Send the transmission ID to the worker.
let _ = sender.tx_worker_ping.send((peer_ip, transmission_id)).await;
}
}
Ok(true)
}
}
}
/// Initialize a new instance of the heartbeat.
fn initialize_heartbeat(&self) {
let self_clone = self.clone();
self.spawn(async move {
// Sleep briefly to ensure the other nodes are ready to connect.
tokio::time::sleep(Duration::from_millis(1000)).await;
info!("Starting the heartbeat of the gateway...");
loop {
// Process a heartbeat in the gateway.
self_clone.heartbeat().await;
// Sleep for the heartbeat interval.
tokio::time::sleep(Duration::from_secs(15)).await;
}
});
}
/// Spawns a task with the given future; it should only be used for long-running tasks.
#[allow(dead_code)]
fn spawn<T: Future<Output = ()> + Send + 'static>(&self, future: T) {
self.handles.lock().push(tokio::spawn(future));
}
/// Shuts down the gateway.
pub async fn shut_down(&self) {
info!("Shutting down the gateway...");
// Save the best peers for future use.
if let Err(e) = self.save_best_peers(&self.node_data_dir.gateway_peer_cache_path(), None, true) {
warn!("Failed to persist best validators to disk: {e}");
}
// Abort the tasks.
self.handles.lock().iter().for_each(|handle| handle.abort());
// Close the listener.
self.tcp.shut_down().await;
}
}
impl<N: Network> Gateway<N> {
/// The minimum time between connection attempts to a peer.
const MINIMUM_TIME_BETWEEN_CONNECTION_ATTEMPTS: Duration = Duration::from_secs(10);
/// The uptime after which nodes log a warning about missing validator connections.
const MISSING_VALIDATOR_CONNECTIONS_GRACE_PERIOD: Duration = Duration::from_secs(60);
/// Handles the heartbeat request.
async fn heartbeat(&self) {
// Log the connected validators.
self.log_connected_validators();
// Log the validator participation scores.
#[cfg(feature = "telemetry")]
self.log_participation_scores();
// Keep the trusted validators connected.
self.handle_trusted_validators();
// Keep the bootstrap peers within the allowed range.
self.handle_bootstrap_peers().await;
// Removes any validators that not in the current committee.
self.handle_unauthorized_validators();
// If the number of connected validators is less than the minimum, send a `ValidatorsRequest`.
self.handle_min_connected_validators().await;
// Unban any addresses whose ban time has expired.
self.handle_banned_ips();
}
/// Logs the connected validators.
fn log_connected_validators(&self) {
// Retrieve the connected validators and current committee.
// The gatway may also be connected to bootstrap clients, which we should not log as connected validators.
let connected_validators = self.filter_connected_peers(|peer| peer.node_type == NodeType::Validator);
let committee = match self.ledger.current_committee() {
Ok(c) => c,
Err(err) => {
error!("Failed to get current committee: {err}");
return;
}
};
// Resolve the total number of connectable validators.
let validators_total = committee.num_members().saturating_sub(1);
// Format the total validators message.
let total_validators = format!("(of {validators_total} bonded validators)").dimmed();
// Construct the connections message.
let connections_msg = match connected_validators.len() {
0 => "No connected validators".to_string(),
num_connected => format!("Connected to {num_connected} validators {total_validators}"),
};
info!("{connections_msg}");
// Collect the connected validator addresses and stake.
let mut connected_validator_addresses = HashSet::with_capacity(connected_validators.len());
let mut connected_validator_shas: HashMap<SmolStr, u64> = HashMap::with_capacity(connected_validators.len());
// Insert our sha.
let our_sha = shorten_snarkos_sha(&get_repo_commit_hash());
let our_stake = committee.get_stake(self.account.address());
connected_validator_shas.insert(our_sha.clone(), our_stake);
// Include our own address.
connected_validator_addresses.insert(self.account.address());
// Include and log the connected validators.
for peer in &connected_validators {
// Register the Aleo address.
let address = peer.aleo_addr;
connected_validator_addresses.insert(address);
// Register the snarkOS commit SHA and the associated stake.
let address_stake = committee.get_stake(address);
let short_peer_sha = shorten_snarkos_sha(&peer.snarkos_sha);
*connected_validator_shas.entry(short_peer_sha.clone()).or_default() += address_stake;
debug!(
"{}",
format!(
" Connected to: {} - {} (connection age {:?})",
peer.listener_addr,
peer.aleo_addr,
peer.first_seen.elapsed()
)
.dimmed()
);
}
// Log how much of the stake uses our git commit hash.
if let Some(combined_stake) = connected_validator_shas.get(&our_sha) {
let percentage = *combined_stake as f64 / committee.total_stake() as f64 * 100.0;
debug!("{}", format!(" Combined stake @ {our_sha}: {percentage:.2}%").dimmed());
#[cfg(feature = "metrics")]
metrics::gauge(metrics::bft::CONNECTED_STAKE_WITH_MATCHING_SHA, percentage);
}
// Log the validators that are not connected.
let num_not_connected = validators_total.saturating_sub(connected_validators.len());
if num_not_connected > 0 && self.tcp().uptime() > Self::MISSING_VALIDATOR_CONNECTIONS_GRACE_PERIOD {
// Cache the total stake for computing percentages.
let total_stake = committee.total_stake();
let total_stake_f64 = total_stake as f64;
// Collect the committee members.
let committee_members: HashSet<_> =
self.ledger.current_committee().map(|c| c.members().keys().copied().collect()).unwrap_or_default();
let not_connected_stake: u64 = committee_members
.difference(&connected_validator_addresses)
.map(|address| {