-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathconnection.rs
1797 lines (1626 loc) · 78.3 KB
/
connection.rs
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
//! Zebra's per-peer connection state machine.
//!
//! Maps the external Zcash/Bitcoin protocol to Zebra's internal request/response
//! protocol.
//!
//! This module contains a lot of undocumented state, assumptions and invariants.
//! And it's unclear if these assumptions match the `zcashd` implementation.
//! It should be refactored into a cleaner set of request/response pairs (#1515).
use std::{borrow::Cow, collections::HashSet, fmt, pin::Pin, sync::Arc, time::Instant};
use futures::{future::Either, prelude::*};
use rand::{seq::SliceRandom, thread_rng, Rng};
use tokio::time::{sleep, Sleep};
use tower::{Service, ServiceExt};
use tracing_futures::Instrument;
use zebra_chain::{
block::{self, Block},
serialization::SerializationError,
transaction::{UnminedTx, UnminedTxId},
};
use crate::{
constants::{
self, MAX_ADDRS_IN_MESSAGE, MAX_OVERLOAD_DROP_PROBABILITY, MIN_OVERLOAD_DROP_PROBABILITY,
OVERLOAD_PROTECTION_INTERVAL, PEER_ADDR_RESPONSE_LIMIT,
},
meta_addr::MetaAddr,
peer::{
connection::peer_tx::PeerTx, error::AlreadyErrored, ClientRequest, ClientRequestReceiver,
ConnectionInfo, ErrorSlot, InProgressClientRequest, MustUseClientResponseSender, PeerError,
SharedPeerError,
},
peer_set::ConnectionTracker,
protocol::{
external::{types::Nonce, InventoryHash, Message},
internal::{InventoryResponse, Request, Response},
},
BoxError, MAX_TX_INV_IN_SENT_MESSAGE,
};
use InventoryResponse::*;
mod peer_tx;
#[cfg(test)]
mod tests;
#[derive(Debug)]
pub(super) enum Handler {
/// Indicates that the handler has finished processing the request.
/// An error here is scoped to the request.
Finished(Result<Response, PeerError>),
Ping(Nonce),
Peers,
FindBlocks,
FindHeaders,
BlocksByHash {
pending_hashes: HashSet<block::Hash>,
blocks: Vec<Arc<Block>>,
},
TransactionsById {
pending_ids: HashSet<UnminedTxId>,
transactions: Vec<UnminedTx>,
},
MempoolTransactionIds,
}
impl fmt::Display for Handler {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&match self {
Handler::Finished(Ok(response)) => format!("Finished({response})"),
Handler::Finished(Err(error)) => format!("Finished({error})"),
Handler::Ping(_) => "Ping".to_string(),
Handler::Peers => "Peers".to_string(),
Handler::FindBlocks => "FindBlocks".to_string(),
Handler::FindHeaders => "FindHeaders".to_string(),
Handler::BlocksByHash {
pending_hashes,
blocks,
} => format!(
"BlocksByHash {{ pending_hashes: {}, blocks: {} }}",
pending_hashes.len(),
blocks.len()
),
Handler::TransactionsById {
pending_ids,
transactions,
} => format!(
"TransactionsById {{ pending_ids: {}, transactions: {} }}",
pending_ids.len(),
transactions.len()
),
Handler::MempoolTransactionIds => "MempoolTransactionIds".to_string(),
})
}
}
impl Handler {
/// Returns the Zebra internal handler type as a string.
pub fn command(&self) -> Cow<'static, str> {
match self {
Handler::Finished(Ok(response)) => format!("Finished({})", response.command()).into(),
Handler::Finished(Err(error)) => format!("Finished({})", error.kind()).into(),
Handler::Ping(_) => "Ping".into(),
Handler::Peers => "Peers".into(),
Handler::FindBlocks { .. } => "FindBlocks".into(),
Handler::FindHeaders { .. } => "FindHeaders".into(),
Handler::BlocksByHash { .. } => "BlocksByHash".into(),
Handler::TransactionsById { .. } => "TransactionsById".into(),
Handler::MempoolTransactionIds => "MempoolTransactionIds".into(),
}
}
/// Try to handle `msg` as a response to a client request, possibly consuming
/// it in the process.
///
/// This function is where we statefully interpret Bitcoin/Zcash messages
/// into responses to messages in the internal request/response protocol.
/// This conversion is done by a sequence of (request, message) match arms,
/// each of which contains the conversion logic for that pair.
///
/// Taking ownership of the message means that we can pass ownership of its
/// contents to responses without additional copies. If the message is not
/// interpretable as a response, we return ownership to the caller.
///
/// Unexpected messages are left unprocessed, and may be rejected later.
///
/// `addr` responses are limited to avoid peer set takeover. Any excess
/// addresses are stored in `cached_addrs`.
fn process_message(
&mut self,
msg: Message,
cached_addrs: &mut Vec<MetaAddr>,
) -> Option<Message> {
let mut ignored_msg = None;
// TODO: can this be avoided?
let tmp_state = std::mem::replace(self, Handler::Finished(Ok(Response::Nil)));
debug!(handler = %tmp_state, %msg, "received peer response to Zebra request");
*self = match (tmp_state, msg) {
(Handler::Ping(req_nonce), Message::Pong(rsp_nonce)) => {
if req_nonce == rsp_nonce {
Handler::Finished(Ok(Response::Nil))
} else {
Handler::Ping(req_nonce)
}
}
(Handler::Peers, Message::Addr(new_addrs)) => {
// Security: This method performs security-sensitive operations, see its comments
// for details.
let response_addrs =
Handler::update_addr_cache(cached_addrs, &new_addrs, PEER_ADDR_RESPONSE_LIMIT);
debug!(
new_addrs = new_addrs.len(),
response_addrs = response_addrs.len(),
remaining_addrs = cached_addrs.len(),
PEER_ADDR_RESPONSE_LIMIT,
"responding to Peers request using new and cached addresses",
);
Handler::Finished(Ok(Response::Peers(response_addrs)))
}
// `zcashd` returns requested transactions in a single batch of messages.
// Other transaction or non-transaction messages can come before or after the batch.
// After the transaction batch, `zcashd` sends `notfound` if any transactions are missing:
// https://github.com/zcash/zcash/blob/e7b425298f6d9a54810cb7183f00be547e4d9415/src/main.cpp#L5617
(
Handler::TransactionsById {
mut pending_ids,
mut transactions,
},
Message::Tx(transaction),
) => {
// assumptions:
// - the transaction messages are sent in a single continuous batch
// - missing transactions are silently skipped
// (there is no `notfound` message at the end of the batch)
if pending_ids.remove(&transaction.id) {
// we are in the middle of the continuous transaction messages
transactions.push(transaction);
} else {
// We got a transaction we didn't ask for. If the caller doesn't know any of the
// transactions, they should have sent a `notfound` with all the hashes, rather
// than an unsolicited transaction.
//
// So either:
// 1. The peer implements the protocol badly, skipping `notfound`.
// We should cancel the request, so we don't hang waiting for transactions
// that will never arrive.
// 2. The peer sent an unsolicited transaction.
// We should ignore the transaction, and wait for the actual response.
//
// We end the request, so we don't hang on bad peers (case 1). But we keep the
// connection open, so the inbound service can process transactions from good
// peers (case 2).
ignored_msg = Some(Message::Tx(transaction));
}
if ignored_msg.is_some() && transactions.is_empty() {
// If we didn't get anything we wanted, retry the request.
let missing_transaction_ids = pending_ids.into_iter().map(Into::into).collect();
Handler::Finished(Err(PeerError::NotFoundResponse(missing_transaction_ids)))
} else if pending_ids.is_empty() || ignored_msg.is_some() {
// If we got some of what we wanted, let the internal client know.
let available = transactions.into_iter().map(InventoryResponse::Available);
let missing = pending_ids.into_iter().map(InventoryResponse::Missing);
Handler::Finished(Ok(Response::Transactions(
available.chain(missing).collect(),
)))
} else {
// Keep on waiting for more.
Handler::TransactionsById {
pending_ids,
transactions,
}
}
}
// `zcashd` peers actually return this response
(
Handler::TransactionsById {
pending_ids,
transactions,
},
Message::NotFound(missing_invs),
) => {
// assumptions:
// - the peer eventually returns a transaction or a `notfound` entry
// for each hash
// - all `notfound` entries are contained in a single message
// - the `notfound` message comes after the transaction messages
//
// If we're in sync with the peer, then the `notfound` should contain the remaining
// hashes from the handler. If we're not in sync with the peer, we should return
// what we got so far.
let missing_transaction_ids: HashSet<_> = transaction_ids(&missing_invs).collect();
if missing_transaction_ids != pending_ids {
trace!(?missing_invs, ?missing_transaction_ids, ?pending_ids);
// if these errors are noisy, we should replace them with debugs
debug!("unexpected notfound message from peer: all remaining transaction hashes should be listed in the notfound. Using partial received transactions as the peer response");
}
if missing_transaction_ids.len() != missing_invs.len() {
trace!(?missing_invs, ?missing_transaction_ids, ?pending_ids);
debug!("unexpected notfound message from peer: notfound contains duplicate hashes or non-transaction hashes. Using partial received transactions as the peer response");
}
if transactions.is_empty() {
// If we didn't get anything we wanted, retry the request.
let missing_transaction_ids = pending_ids.into_iter().map(Into::into).collect();
Handler::Finished(Err(PeerError::NotFoundResponse(missing_transaction_ids)))
} else {
// If we got some of what we wanted, let the internal client know.
let available = transactions.into_iter().map(InventoryResponse::Available);
let missing = pending_ids.into_iter().map(InventoryResponse::Missing);
Handler::Finished(Ok(Response::Transactions(
available.chain(missing).collect(),
)))
}
}
// `zcashd` returns requested blocks in a single batch of messages.
// Other blocks or non-blocks messages can come before or after the batch.
// `zcashd` silently skips missing blocks, rather than sending a final `notfound` message.
// https://github.com/zcash/zcash/blob/e7b425298f6d9a54810cb7183f00be547e4d9415/src/main.cpp#L5523
(
Handler::BlocksByHash {
mut pending_hashes,
mut blocks,
},
Message::Block(block),
) => {
// assumptions:
// - the block messages are sent in a single continuous batch
// - missing blocks are silently skipped
// (there is no `notfound` message at the end of the batch)
if pending_hashes.remove(&block.hash()) {
// we are in the middle of the continuous block messages
blocks.push(block);
} else {
// We got a block we didn't ask for.
//
// So either:
// 1. The response is for a previously cancelled block request.
// We should treat that block as an inbound gossiped block,
// and wait for the actual response.
// 2. The peer doesn't know any of the blocks we asked for.
// We should cancel the request, so we don't hang waiting for blocks that
// will never arrive.
// 3. The peer sent an unsolicited block.
// We should treat that block as an inbound gossiped block,
// and wait for the actual response.
//
// We ignore the message, so we don't desynchronize with the peer. This happens
// when we cancel a request and send a second different request, but receive a
// response for the first request. If we ended the request then, we could send
// a third request to the peer, and end up having to end that request as well
// when the response for the second request arrives.
//
// Ignoring the message gives us a chance to synchronize back to the correct
// request. If that doesn't happen, this request times out.
//
// In case 2, if peers respond with a `notfound` message,
// the cascading errors don't happen. The `notfound` message cancels our request,
// and we know we are in sync with the peer.
//
// Zebra sends `notfound` in response to block requests, but `zcashd` doesn't.
// So we need this message workaround, and the related inventory workarounds.
ignored_msg = Some(Message::Block(block));
}
if pending_hashes.is_empty() {
// If we got everything we wanted, let the internal client know.
let available = blocks.into_iter().map(InventoryResponse::Available);
Handler::Finished(Ok(Response::Blocks(available.collect())))
} else {
// Keep on waiting for all the blocks we wanted, until we get them or time out.
Handler::BlocksByHash {
pending_hashes,
blocks,
}
}
}
// peers are allowed to return this response, but `zcashd` never does
(
Handler::BlocksByHash {
pending_hashes,
blocks,
},
Message::NotFound(missing_invs),
) => {
// assumptions:
// - the peer eventually returns a block or a `notfound` entry
// for each hash
// - all `notfound` entries are contained in a single message
// - the `notfound` message comes after the block messages
//
// If we're in sync with the peer, then the `notfound` should contain the remaining
// hashes from the handler. If we're not in sync with the peer, we should return
// what we got so far, and log an error.
let missing_blocks: HashSet<_> = block_hashes(&missing_invs).collect();
if missing_blocks != pending_hashes {
trace!(?missing_invs, ?missing_blocks, ?pending_hashes);
// if these errors are noisy, we should replace them with debugs
debug!("unexpected notfound message from peer: all remaining block hashes should be listed in the notfound. Using partial received blocks as the peer response");
}
if missing_blocks.len() != missing_invs.len() {
trace!(?missing_invs, ?missing_blocks, ?pending_hashes);
debug!("unexpected notfound message from peer: notfound contains duplicate hashes or non-block hashes. Using partial received blocks as the peer response");
}
if blocks.is_empty() {
// If we didn't get anything we wanted, retry the request.
let missing_block_hashes = pending_hashes.into_iter().map(Into::into).collect();
Handler::Finished(Err(PeerError::NotFoundResponse(missing_block_hashes)))
} else {
// If we got some of what we wanted, let the internal client know.
let available = blocks.into_iter().map(InventoryResponse::Available);
let missing = pending_hashes.into_iter().map(InventoryResponse::Missing);
Handler::Finished(Ok(Response::Blocks(available.chain(missing).collect())))
}
}
// TODO:
// - use `any(inv)` rather than `all(inv)`?
(Handler::FindBlocks, Message::Inv(items))
if items
.iter()
.all(|item| matches!(item, InventoryHash::Block(_))) =>
{
Handler::Finished(Ok(Response::BlockHashes(
block_hashes(&items[..]).collect(),
)))
}
(Handler::FindHeaders, Message::Headers(headers)) => {
Handler::Finished(Ok(Response::BlockHeaders(headers)))
}
(Handler::MempoolTransactionIds, Message::Inv(items))
if items.iter().all(|item| item.unmined_tx_id().is_some()) =>
{
Handler::Finished(Ok(Response::TransactionIds(
transaction_ids(&items).collect(),
)))
}
// By default, messages are not responses.
(state, msg) => {
trace!(?msg, "did not interpret message as response");
ignored_msg = Some(msg);
state
}
};
ignored_msg
}
/// Adds `new_addrs` to the `cached_addrs` cache, then takes and returns `response_size`
/// addresses from that cache.
///
/// `cached_addrs` can be empty if the cache is empty. `new_addrs` can be empty or `None` if
/// there are no new addresses. `response_size` can be zero or `None` if there is no response
/// needed.
fn update_addr_cache<'new>(
cached_addrs: &mut Vec<MetaAddr>,
new_addrs: impl IntoIterator<Item = &'new MetaAddr>,
response_size: impl Into<Option<usize>>,
) -> Vec<MetaAddr> {
// # Peer Set Reliability
//
// Newly received peers are added to the cache, so that we can use them if the connection
// doesn't respond to our getaddr requests.
//
// Add the new addresses to the end of the cache.
cached_addrs.extend(new_addrs);
// # Security
//
// We limit how many peer addresses we take from each peer, so that our address book
// and outbound connections aren't controlled by a single peer (#1869). We randomly select
// peers, so the remote peer can't control which addresses we choose by changing the order
// in the messages they send.
let response_size = response_size.into().unwrap_or_default();
let mut temp_cache = Vec::new();
std::mem::swap(cached_addrs, &mut temp_cache);
// The response is fully shuffled, remaining is partially shuffled.
let (response, remaining) = temp_cache.partial_shuffle(&mut thread_rng(), response_size);
// # Security
//
// The cache size is limited to avoid memory denial of service.
//
// It's ok to just partially shuffle the cache, because it doesn't actually matter which
// peers we drop. Having excess peers is rare, because most peers only send one large
// unsolicited peer message when they first connect.
*cached_addrs = remaining.to_vec();
cached_addrs.truncate(MAX_ADDRS_IN_MESSAGE);
response.to_vec()
}
}
#[derive(Debug)]
#[must_use = "AwaitingResponse.tx.send() must be called before drop"]
pub(super) enum State {
/// Awaiting a client request or a peer message.
AwaitingRequest,
/// Awaiting a peer message we can interpret as a response to a client request.
AwaitingResponse {
handler: Handler,
tx: MustUseClientResponseSender,
span: tracing::Span,
},
/// A failure has occurred and we are shutting down the connection.
Failed,
}
impl fmt::Display for State {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&match self {
State::AwaitingRequest => "AwaitingRequest".to_string(),
State::AwaitingResponse { handler, .. } => {
format!("AwaitingResponse({handler})")
}
State::Failed => "Failed".to_string(),
})
}
}
impl State {
/// Returns the Zebra internal state as a string.
pub fn command(&self) -> Cow<'static, str> {
match self {
State::AwaitingRequest => "AwaitingRequest".into(),
State::AwaitingResponse { handler, .. } => {
format!("AwaitingResponse({})", handler.command()).into()
}
State::Failed => "Failed".into(),
}
}
}
/// The outcome of mapping an inbound [`Message`] to a [`Request`].
#[derive(Clone, Debug, Eq, PartialEq)]
#[must_use = "inbound messages must be handled"]
pub enum InboundMessage {
/// The message was mapped to an inbound [`Request`].
AsRequest(Request),
/// The message was consumed by the mapping method.
///
/// For example, it could be cached, treated as an error,
/// or an internally handled [`Message::Ping`].
Consumed,
/// The message was not used by the inbound message handler.
Unused,
}
impl From<Request> for InboundMessage {
fn from(request: Request) -> Self {
InboundMessage::AsRequest(request)
}
}
/// The channels, services, and associated state for a peer connection.
pub struct Connection<S, Tx>
where
Tx: Sink<Message, Error = SerializationError> + Unpin,
{
/// The metadata for the connected peer `service`.
///
/// This field is used for debugging.
pub connection_info: Arc<ConnectionInfo>,
/// The state of this connection's current request or response.
pub(super) state: State,
/// A timeout for a client request. This is stored separately from
/// State so that we can move the future out of it independently of
/// other state handling.
pub(super) request_timer: Option<Pin<Box<Sleep>>>,
/// Unused peers from recent `addr` or `addrv2` messages from this peer.
/// Also holds the initial addresses sent in `version` messages, or guessed from the remote IP.
///
/// When peers send solicited or unsolicited peer advertisements, Zebra puts them in this cache.
///
/// When Zebra's components request peers, some cached peers are randomly selected,
/// consumed, and returned as a modified response. This works around `zcashd`'s address
/// response rate-limit.
///
/// The cache size is limited to avoid denial of service attacks.
pub(super) cached_addrs: Vec<MetaAddr>,
/// The `inbound` service, used to answer requests from this connection's peer.
pub(super) svc: S,
/// A channel for requests that Zebra's internal services want to send to remote peers.
///
/// This channel accepts [`Request`]s, and produces [`InProgressClientRequest`]s.
pub(super) client_rx: ClientRequestReceiver,
/// A slot for an error shared between the Connection and the Client that uses it.
///
/// `None` unless the connection or client have errored.
pub(super) error_slot: ErrorSlot,
/// A channel for sending Zcash messages to the connected peer.
///
/// This channel accepts [`Message`]s.
///
/// The corresponding peer message receiver is passed to [`Connection::run`].
pub(super) peer_tx: PeerTx<Tx>,
/// A connection tracker that reduces the open connection count when dropped.
/// Used to limit the number of open connections in Zebra.
///
/// This field does nothing until it is dropped.
///
/// # Security
///
/// If this connection tracker or `Connection`s are leaked,
/// the number of active connections will appear higher than it actually is.
/// If enough connections leak, Zebra will stop making new connections.
#[allow(dead_code)]
pub(super) connection_tracker: ConnectionTracker,
/// The metrics label for this peer. Usually the remote IP and port.
pub(super) metrics_label: String,
/// The state for this peer, when the metrics were last updated.
pub(super) last_metrics_state: Option<Cow<'static, str>>,
/// The time of the last overload error response from the inbound
/// service to a request from this connection,
/// or None if this connection hasn't yet received an overload error.
last_overload_time: Option<Instant>,
}
impl<S, Tx> fmt::Debug for Connection<S, Tx>
where
Tx: Sink<Message, Error = SerializationError> + Unpin,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// skip the channels, they don't tell us anything useful
f.debug_struct(std::any::type_name::<Connection<S, Tx>>())
.field("connection_info", &self.connection_info)
.field("state", &self.state)
.field("request_timer", &self.request_timer)
.field("cached_addrs", &self.cached_addrs.len())
.field("error_slot", &self.error_slot)
.field("metrics_label", &self.metrics_label)
.field("last_metrics_state", &self.last_metrics_state)
.field("last_overload_time", &self.last_overload_time)
.finish()
}
}
impl<S, Tx> Connection<S, Tx>
where
Tx: Sink<Message, Error = SerializationError> + Unpin,
{
/// Return a new connection from its channels, services, shared state, and metadata.
pub(crate) fn new(
inbound_service: S,
client_rx: futures::channel::mpsc::Receiver<ClientRequest>,
error_slot: ErrorSlot,
peer_tx: Tx,
connection_tracker: ConnectionTracker,
connection_info: Arc<ConnectionInfo>,
initial_cached_addrs: Vec<MetaAddr>,
) -> Self {
let metrics_label = connection_info.connected_addr.get_transient_addr_label();
Connection {
connection_info,
state: State::AwaitingRequest,
request_timer: None,
cached_addrs: initial_cached_addrs,
svc: inbound_service,
client_rx: client_rx.into(),
error_slot,
peer_tx: peer_tx.into(),
connection_tracker,
metrics_label,
last_metrics_state: None,
last_overload_time: None,
}
}
}
impl<S, Tx> Connection<S, Tx>
where
S: Service<Request, Response = Response, Error = BoxError>,
S::Error: Into<BoxError>,
Tx: Sink<Message, Error = SerializationError> + Unpin,
{
/// Consume this `Connection` to form a spawnable future containing its event loop.
///
/// `peer_rx` is a channel for receiving Zcash [`Message`]s from the connected peer.
/// The corresponding peer message receiver is [`Connection.peer_tx`].
pub async fn run<Rx>(mut self, mut peer_rx: Rx)
where
Rx: Stream<Item = Result<Message, SerializationError>> + Unpin,
{
// At a high level, the event loop we want is as follows: we check for any
// incoming messages from the remote peer, check if they should be interpreted
// as a response to a pending client request, and if not, interpret them as a
// request from the remote peer to our node.
//
// We also need to handle those client requests in the first place. The client
// requests are received from the corresponding `peer::Client` over a bounded
// channel (with bound 1, to minimize buffering), but there is no relationship
// between the stream of client requests and the stream of peer messages, so we
// cannot ignore one kind while waiting on the other. Moreover, we cannot accept
// a second client request while the first one is still pending.
//
// To do this, we inspect the current request state.
//
// If there is no pending request, we wait on either an incoming peer message or
// an incoming request, whichever comes first.
//
// If there is a pending request, we wait only on an incoming peer message, and
// check whether it can be interpreted as a response to the pending request.
//
// TODO: turn this comment into a module-level comment, after splitting the module.
loop {
self.update_state_metrics(None);
match self.state {
State::AwaitingRequest => {
trace!("awaiting client request or peer message");
// # Correctness
//
// Currently, select prefers the first future if multiple futures are ready.
// We use this behaviour to prioritise messages on each individual peer
// connection in this order:
// - incoming messages from the remote peer, then
// - outgoing messages to the remote peer.
//
// This improves the performance of peer responses to Zebra requests, and new
// peer requests to Zebra's inbound service.
//
// `futures::StreamExt::next()` is cancel-safe:
// <https://docs.rs/tokio/latest/tokio/macro.select.html#cancellation-safety>
// This means that messages from the future that isn't selected stay in the stream,
// and they will be returned next time the future is checked.
//
// If an inbound peer message arrives at a ready peer that also has a pending
// request from Zebra, we want to process the peer's message first.
// If we process the Zebra request first:
// - we could misinterpret the inbound peer message as a response to the Zebra
// request, or
// - if the peer message is a request to Zebra, and we put the peer in the
// AwaitingResponse state, then we'll correctly ignore the simultaneous Zebra
// request. (Zebra services make multiple requests or retry, so this is ok.)
//
// # Security
//
// If a peer sends an uninterrupted series of messages, it will delay any new
// requests from Zebra to that individual peer. This is behaviour we want,
// because:
// - any responses to Zebra's requests to that peer would be slow or timeout,
// - the peer will eventually fail a Zebra keepalive check and get disconnected,
// - if there are too many inbound messages overall, the inbound service will
// return an overload error and the peer will be disconnected.
//
// Messages to other peers will continue to be processed concurrently. Some
// Zebra services might be temporarily delayed until the peer times out, if a
// request to that peer is sent by the service, and the service blocks until
// the request completes (or times out).
match future::select(peer_rx.next(), self.client_rx.next()).await {
Either::Left((None, _)) => {
self.fail_with(PeerError::ConnectionClosed).await;
}
Either::Left((Some(Err(e)), _)) => self.fail_with(e).await,
Either::Left((Some(Ok(msg)), _)) => {
let unhandled_msg = self.handle_message_as_request(msg).await;
if let Some(unhandled_msg) = unhandled_msg {
debug!(
%unhandled_msg,
"ignoring unhandled request while awaiting a request"
);
}
}
Either::Right((None, _)) => {
trace!("client_rx closed, ending connection");
// There are no requests to be flushed,
// but we need to set an error and update metrics.
// (We don't want to log this error, because it's normal behaviour.)
self.shutdown_async(PeerError::ClientDropped).await;
break;
}
Either::Right((Some(req), _)) => {
let span = req.span.clone();
self.handle_client_request(req).instrument(span).await
}
}
}
// Check whether the handler is finished before waiting for a response message,
// because the response might be `Nil` or synthetic.
State::AwaitingResponse {
handler: Handler::Finished(_),
ref span,
..
} => {
// We have to get rid of the span reference so we can tamper with the state.
let span = span.clone();
trace!(
parent: &span,
"returning completed response to client request"
);
// Replace the state with a temporary value,
// so we can take ownership of the response sender.
let tmp_state = std::mem::replace(&mut self.state, State::Failed);
if let State::AwaitingResponse {
handler: Handler::Finished(response),
tx,
..
} = tmp_state
{
if let Ok(response) = response.as_ref() {
debug!(%response, "finished receiving peer response to Zebra request");
// Add a metric for inbound responses to outbound requests.
metrics::counter!(
"zebra.net.in.responses",
"command" => response.command(),
"addr" => self.metrics_label.clone(),
)
.increment(1);
} else {
debug!(error = ?response, "error in peer response to Zebra request");
}
let _ = tx.send(response.map_err(Into::into));
} else {
unreachable!("already checked for AwaitingResponse");
}
self.state = State::AwaitingRequest;
}
// We're awaiting a response to a client request,
// so wait on either a peer message, or on a request cancellation.
State::AwaitingResponse {
ref span,
ref mut tx,
..
} => {
// we have to get rid of the span reference so we can tamper with the state
let span = span.clone();
trace!(parent: &span, "awaiting response to client request");
let timer_ref = self
.request_timer
.as_mut()
.expect("timeout must be set while awaiting response");
// # Security
//
// select() prefers the first future if multiple futures are ready.
//
// If multiple futures are ready, we want the priority for each individual
// connection to be:
// - cancellation, then
// - timeout, then
// - peer responses.
//
// (Messages to other peers are processed concurrently.)
//
// This makes sure a peer can't block disconnection or timeouts by sending too
// many messages. It also avoids doing work to process messages after a
// connection has failed.
let cancel = future::select(tx.cancellation(), timer_ref);
match future::select(cancel, peer_rx.next())
.instrument(span.clone())
.await
{
Either::Right((None, _)) => {
self.fail_with(PeerError::ConnectionClosed).await
}
Either::Right((Some(Err(e)), _)) => self.fail_with(e).await,
Either::Right((Some(Ok(peer_msg)), _cancel)) => {
self.update_state_metrics(format!("Out::Rsp::{}", peer_msg.command()));
// Try to process the message using the handler.
// This extremely awkward construction avoids
// keeping a live reference to handler across the
// call to handle_message_as_request, which takes
// &mut self. This is a sign that we don't properly
// factor the state required for inbound and
// outbound requests.
let request_msg = match self.state {
State::AwaitingResponse {
ref mut handler, ..
} => span.in_scope(|| handler.process_message(peer_msg, &mut self.cached_addrs)),
_ => unreachable!("unexpected state after AwaitingResponse: {:?}, peer_msg: {:?}, client_receiver: {:?}",
self.state,
peer_msg,
self.client_rx,
),
};
self.update_state_metrics(None);
// If the message was not consumed as a response,
// check whether it can be handled as a request.
let unused_msg = if let Some(request_msg) = request_msg {
// do NOT instrument with the request span, this is
// independent work
self.handle_message_as_request(request_msg).await
} else {
None
};
if let Some(unused_msg) = unused_msg {
debug!(
%unused_msg,
%self.state,
"ignoring peer message: not a response or a request",
);
}
}
Either::Left((Either::Right(_), _peer_fut)) => {
trace!(parent: &span, "client request timed out");
let e = PeerError::ConnectionReceiveTimeout;
// Replace the state with a temporary value,
// so we can take ownership of the response sender.
self.state = match std::mem::replace(&mut self.state, State::Failed) {
// Special case: ping timeouts fail the connection.
State::AwaitingResponse {
handler: Handler::Ping(_),
tx,
..
} => {
// We replaced the original state, which means `fail_with` won't see it.
// So we do the state request cleanup manually.
let e = SharedPeerError::from(e);
let _ = tx.send(Err(e.clone()));
self.fail_with(e).await;
State::Failed
}
// Other request timeouts fail the request.
State::AwaitingResponse { tx, .. } => {
let _ = tx.send(Err(e.into()));
State::AwaitingRequest
}
_ => unreachable!(
"unexpected failed connection state while AwaitingResponse: client_receiver: {:?}",
self.client_rx
),
};
}
Either::Left((Either::Left(_), _peer_fut)) => {
// The client receiver was dropped, so we don't need to send on `tx` here.
trace!(parent: &span, "client request was cancelled");
self.state = State::AwaitingRequest;
}
}
}
// This connection has failed: stop the event loop, and complete the future.
State::Failed => break,
}
}
// TODO: close peer_rx here, after changing it from a stream to a channel
let error = self.error_slot.try_get_error();
assert!(
error.is_some(),
"closing connections must call fail_with() or shutdown() to set the error slot"
);
self.update_state_metrics(error.expect("checked is_some").to_string());
}
/// Fail this connection, log the failure, and shut it down.
/// See [`Self::shutdown_async()`] for details.
///
/// Use [`Self::shutdown_async()`] to avoid logging the failure,
/// and [`Self::shutdown()`] from non-async code.
async fn fail_with(&mut self, error: impl Into<SharedPeerError>) {
let error = error.into();
debug!(
%error,
client_receiver = ?self.client_rx,
"failing peer service with error"
);
self.shutdown_async(error).await;
}
/// Handle an internal client request, possibly generating outgoing messages to the
/// remote peer.
///
/// NOTE: the caller should use .instrument(msg.span) to instrument the function.
async fn handle_client_request(&mut self, req: InProgressClientRequest) {
trace!(?req.request);
use Request::*;
use State::*;
let InProgressClientRequest { request, tx, span } = req;
if tx.is_canceled() {
metrics::counter!("peer.canceled").increment(1);
debug!(state = %self.state, %request, "ignoring canceled request");
metrics::counter!(
"zebra.net.out.requests.canceled",
"command" => request.command(),
"addr" => self.metrics_label.clone(),
)
.increment(1);
self.update_state_metrics(format!("Out::Req::Canceled::{}", request.command()));
return;
}
debug!(state = %self.state, %request, "sending request from Zebra to peer");
// Add a metric for outbound requests.
metrics::counter!(
"zebra.net.out.requests",
"command" => request.command(),
"addr" => self.metrics_label.clone(),
)
.increment(1);
self.update_state_metrics(format!("Out::Req::{}", request.command()));
let new_handler = match (&self.state, request) {
(Failed, request) => panic!(
"failed connection cannot handle new request: {:?}, client_receiver: {:?}",
request,
self.client_rx
),
(pending @ AwaitingResponse { .. }, request) => panic!(
"tried to process new request: {:?} while awaiting a response: {:?}, client_receiver: {:?}",