Skip to main content

reth_network/
metrics.rs

1use metrics::Histogram;
2use reth_eth_wire::DisconnectReason;
3use reth_ethereum_primitives::TxType;
4use reth_metrics::{
5    metrics::{Counter, Gauge},
6    Metrics,
7};
8
9/// Scope for monitoring transactions sent from the manager to the tx manager
10pub(crate) const NETWORK_POOL_TRANSACTIONS_SCOPE: &str = "network.pool.transactions";
11
12/// Metrics for the entire network, handled by `NetworkManager`
13#[derive(Metrics)]
14#[metrics(scope = "network")]
15pub struct NetworkMetrics {
16    /// Number of currently connected peers
17    pub(crate) connected_peers: Gauge,
18
19    /// Number of currently backed off peers
20    pub(crate) backed_off_peers: Gauge,
21
22    /// Number of peers known to the node
23    pub(crate) tracked_peers: Gauge,
24
25    /// Number of active incoming connections
26    pub(crate) incoming_connections: Gauge,
27
28    /// Number of active outgoing connections
29    pub(crate) outgoing_connections: Gauge,
30
31    /// Number of currently pending outgoing connections
32    pub(crate) pending_outgoing_connections: Gauge,
33
34    /// Total number of pending connections, incoming and outgoing.
35    pub(crate) total_pending_connections: Gauge,
36
37    /// Total Number of incoming connections handled
38    pub(crate) total_incoming_connections: Counter,
39
40    /// Total Number of outgoing connections established
41    pub(crate) total_outgoing_connections: Counter,
42
43    /// Number of invalid/malformed messages received from peers
44    pub(crate) invalid_messages_received: Counter,
45
46    /// Number of Eth Requests dropped due to channel being at full capacity
47    pub(crate) total_dropped_eth_requests_at_full_capacity: Counter,
48
49    /// Number of transaction events dropped due to the tx manager channel being at full capacity
50    pub(crate) total_dropped_tx_events_at_full_capacity: Counter,
51
52    /* ================ POLL DURATION ================ */
53
54    /* -- Total poll duration of `NetworksManager` future -- */
55    /// Duration in seconds of call to
56    /// [`NetworkManager`](crate::NetworkManager)'s poll function.
57    ///
58    /// True duration of this call, should be sum of the accumulated durations of calling nested
59    // items.
60    pub(crate) duration_poll_network_manager: Gauge,
61
62    /* -- Poll duration of items nested in `NetworkManager` future -- */
63    /// Time spent streaming messages sent over the [`NetworkHandle`](crate::NetworkHandle), which
64    /// can be cloned and shared via [`NetworkManager::handle`](crate::NetworkManager::handle), in
65    /// one call to poll the [`NetworkManager`](crate::NetworkManager) future. At least
66    /// [`TransactionsManager`](crate::transactions::TransactionsManager) holds this handle.
67    ///
68    /// Duration in seconds.
69    pub(crate) acc_duration_poll_network_handle: Gauge,
70    /// Time spent polling [`Swarm`](crate::swarm::Swarm), in one call to poll the
71    /// [`NetworkManager`](crate::NetworkManager) future.
72    ///
73    /// Duration in seconds.
74    pub(crate) acc_duration_poll_swarm: Gauge,
75}
76
77/// Metrics for closed sessions, split by direction.
78#[derive(Debug)]
79pub struct ClosedSessionsMetrics {
80    /// Sessions closed from active (established) connections.
81    pub active: Counter,
82    /// Sessions closed from incoming pending connections.
83    pub incoming_pending: Counter,
84    /// Sessions closed from outgoing pending connections.
85    pub outgoing_pending: Counter,
86}
87
88impl Default for ClosedSessionsMetrics {
89    fn default() -> Self {
90        Self {
91            active: metrics::counter!("network_closed_sessions", "direction" => "active"),
92            incoming_pending: metrics::counter!("network_closed_sessions", "direction" => "incoming_pending"),
93            outgoing_pending: metrics::counter!("network_closed_sessions", "direction" => "outgoing_pending"),
94        }
95    }
96}
97
98/// Metrics for pending session failures, split by direction.
99#[derive(Debug)]
100pub struct PendingSessionFailureMetrics {
101    /// Failures on incoming pending sessions.
102    pub inbound: Counter,
103    /// Failures on outgoing pending sessions.
104    pub outbound: Counter,
105}
106
107impl Default for PendingSessionFailureMetrics {
108    fn default() -> Self {
109        Self {
110            inbound: metrics::counter!("network_pending_session_failures", "direction" => "inbound"),
111            outbound: metrics::counter!("network_pending_session_failures", "direction" => "outbound"),
112        }
113    }
114}
115
116/// Metrics for backed off peers, split by reason.
117#[derive(Metrics)]
118#[metrics(scope = "network.backed_off_peers")]
119pub struct BackedOffPeersMetrics {
120    /// Peers backed off because they reported too many peers.
121    pub too_many_peers: Counter,
122    /// Peers backed off after a graceful session close.
123    pub graceful_close: Counter,
124    /// Peers backed off due to connection or protocol errors.
125    pub connection_error: Counter,
126}
127
128impl BackedOffPeersMetrics {
129    /// Increments the counter for the given backoff reason.
130    pub fn increment_for_reason(&self, reason: crate::peers::BackoffReason) {
131        match reason {
132            crate::peers::BackoffReason::TooManyPeers => self.too_many_peers.increment(1),
133            crate::peers::BackoffReason::GracefulClose => self.graceful_close.increment(1),
134            crate::peers::BackoffReason::ConnectionError => self.connection_error.increment(1),
135        }
136    }
137}
138
139/// Metrics for `SessionManager`
140#[derive(Metrics)]
141#[metrics(scope = "network")]
142pub struct SessionManagerMetrics {
143    /// Number of successful outgoing dial attempts.
144    pub(crate) total_dial_successes: Counter,
145    /// Number of dropped outgoing peer messages.
146    pub(crate) total_outgoing_peer_messages_dropped: Counter,
147    /// Number of queued outgoing messages
148    pub(crate) queued_outgoing_messages: Gauge,
149    /// Total number of broadcast messages sent via the unbounded overflow channel.
150    pub(crate) total_unbounded_broadcast_msgs: Counter,
151}
152
153/// Metrics for the [`TransactionsManager`](crate::transactions::TransactionsManager).
154#[derive(Metrics)]
155#[metrics(scope = "network")]
156pub struct TransactionsManagerMetrics {
157    /* ================ BROADCAST ================ */
158    /// Total number of propagated transactions
159    pub(crate) propagated_transactions: Counter,
160    /// Total number of reported bad transactions
161    pub(crate) reported_bad_transactions: Counter,
162
163    /* -- Freq txns already marked as seen by peer -- */
164    /// Total number of messages from a peer, announcing transactions that have already been
165    /// marked as seen by that peer.
166    pub(crate) messages_with_hashes_already_seen_by_peer: Counter,
167    /// Total number of messages from a peer, with transaction that have already been marked as
168    /// seen by that peer.
169    pub(crate) messages_with_transactions_already_seen_by_peer: Counter,
170    /// Total number of occurrences, of a peer announcing a transaction that has already been
171    /// marked as seen by that peer.
172    pub(crate) occurrences_hash_already_seen_by_peer: Counter,
173    /// Total number of times a transaction is seen from a peer, that has already been marked as
174    /// seen by that peer.
175    pub(crate) occurrences_of_transaction_already_seen_by_peer: Counter,
176
177    /* -- Freq txns already in pool -- */
178    /// Total number of times a hash is announced that is already in the local pool.
179    pub(crate) occurrences_hashes_already_in_pool: Counter,
180    /// Total number of times a transaction is sent that is already in the local pool.
181    pub(crate) occurrences_transactions_already_in_pool: Counter,
182
183    /* ================ POOL IMPORTS ================ */
184    /// Number of transactions about to be imported into the pool.
185    pub(crate) pending_pool_imports: Gauge,
186    /// Encoded byte size of the transactions about to be imported into the pool, including blob
187    /// sidecars.
188    pub(crate) pending_pool_imports_bytes: Gauge,
189    /// Total number of bad imports, imports that fail because the transaction is badly formed
190    /// (i.e. have no chance of passing validation, unlike imports that fail due to e.g. nonce
191    /// gaps).
192    pub(crate) bad_imports: Counter,
193    /// Number of inflight requests at which the
194    /// [`TransactionPool`](reth_transaction_pool::TransactionPool) is considered to be at
195    /// capacity. Note, this is not a limit to the number of inflight requests, but a health
196    /// measure.
197    pub(crate) capacity_pending_pool_imports: Counter,
198    /// Encoded byte size of pending pool imports at which the
199    /// [`TransactionPool`](reth_transaction_pool::TransactionPool) is considered to be at
200    /// capacity. Like [`Self::capacity_pending_pool_imports`], this is a health measure.
201    pub(crate) capacity_pending_pool_imports_bytes: Counter,
202    /// Total number of transactions ignored because pending pool imports are at capacity.
203    pub(crate) skipped_transactions_pending_pool_imports_at_capacity: Counter,
204    /// The time it took to prepare transactions for import. This is mostly sender recovery.
205    pub(crate) pool_import_prepare_duration: Histogram,
206
207    /* ================ POLL DURATION ================ */
208
209    /* -- Total poll duration of `TransactionsManager` future -- */
210    /// Duration in seconds of call to
211    /// [`TransactionsManager`](crate::transactions::TransactionsManager)'s poll function.
212    ///
213    /// Updating metrics could take time, so the true duration of this call could
214    /// be longer than the sum of the accumulated durations of polling nested items.
215    pub(crate) duration_poll_tx_manager: Gauge,
216
217    /* -- Poll duration of items nested in `TransactionsManager` future -- */
218    /// Accumulated time spent streaming session updates and updating peers accordingly, in
219    /// one call to poll the [`TransactionsManager`](crate::transactions::TransactionsManager)
220    /// future.
221    ///
222    /// Duration in seconds.
223    pub(crate) acc_duration_poll_network_events: Gauge,
224    /// Accumulated time spent flushing the queue of batched pending pool imports into pool, in
225    /// one call to poll the [`TransactionsManager`](crate::transactions::TransactionsManager)
226    /// future.
227    ///
228    /// Duration in seconds.
229    pub(crate) acc_duration_poll_pending_pool_imports: Gauge,
230    /// Accumulated time spent streaming transaction and announcement broadcast, queueing for
231    /// pool import or requesting respectively, in one call to poll the
232    /// [`TransactionsManager`](crate::transactions::TransactionsManager) future.
233    ///
234    /// Duration in seconds.
235    pub(crate) acc_duration_poll_transaction_events: Gauge,
236    /// Accumulated time spent streaming fetch events, queueing for pool import on successful
237    /// fetch, in one call to poll the
238    /// [`TransactionsManager`](crate::transactions::TransactionsManager) future.
239    ///
240    /// Duration in seconds.
241    pub(crate) acc_duration_poll_fetch_events: Gauge,
242    /// Accumulated time spent streaming and propagating transactions that were successfully
243    /// imported into the pool, in one call to poll the
244    /// [`TransactionsManager`](crate::transactions::TransactionsManager) future.
245    ///
246    /// Duration in seconds.
247    pub(crate) acc_duration_poll_imported_transactions: Gauge,
248    /// Accumulated time spent assembling and sending requests for hashes fetching pending, in
249    /// one call to poll the [`TransactionsManager`](crate::transactions::TransactionsManager)
250    /// future.
251    ///
252    /// Duration in seconds.
253    pub(crate) acc_duration_fetch_pending_hashes: Gauge,
254    /// Accumulated time spent streaming commands and propagating, fetching and serving
255    /// transactions accordingly, in one call to poll the
256    /// [`TransactionsManager`](crate::transactions::TransactionsManager) future.
257    ///
258    /// Duration in seconds.
259    pub(crate) acc_duration_poll_commands: Gauge,
260}
261
262/// Metrics for the [`TransactionsManager`](crate::transactions::TransactionsManager).
263#[derive(Metrics)]
264#[metrics(scope = "network")]
265pub struct TransactionFetcherMetrics {
266    /// Currently active outgoing [`GetPooledTransactions`](reth_eth_wire::GetPooledTransactions)
267    /// requests.
268    pub(crate) inflight_transaction_requests: Gauge,
269    /// Number of inflight requests at which the
270    /// [`TransactionFetcher`](crate::transactions::TransactionFetcher) is considered to be at
271    /// capacity. Note, this is not a limit to the number of inflight requests, but a health
272    /// measure.
273    pub(crate) capacity_inflight_requests: Counter,
274    /// Hashes in currently active outgoing
275    /// [`GetPooledTransactions`](reth_eth_wire::GetPooledTransactions) requests.
276    pub(crate) hashes_inflight_transaction_requests: Gauge,
277    /// How often we failed to send a request to the peer because the channel was full.
278    pub(crate) egress_peer_channel_full: Counter,
279    /// Total number of hashes pending fetch.
280    pub(crate) hashes_pending_fetch: Gauge,
281    /// Total number of fetched transactions.
282    pub(crate) fetched_transactions: Counter,
283    /// Total number of transactions that were received in
284    /// [`PooledTransactions`](reth_eth_wire::PooledTransactions) responses, that weren't
285    /// requested.
286    pub(crate) unsolicited_transactions: Counter,
287    /// Total number of pending hashes that were evicted for newly announced hashes because the
288    /// fetcher already tracks the maximum number of hashes.
289    pub(crate) hashes_evicted_at_capacity: Counter,
290    /// Total number of announced hashes that were dropped because the fetcher already tracks the
291    /// maximum number of hashes and no pending eviction victim was found within the search budget.
292    pub(crate) announced_hashes_dropped_at_capacity: Counter,
293    /// Total number of announced hashes that were dropped because the announcing peer is already
294    /// a candidate for the maximum number of hashes.
295    pub(crate) announced_hashes_dropped_peer_limit: Counter,
296    /// Total number of tracked hashes dropped because no candidate remains or the bounded
297    /// fetch-attempt budget was exhausted.
298    pub(crate) hashes_dropped_no_candidate_peers: Counter,
299    /// Total number of [`PooledTransactions`](reth_eth_wire::PooledTransactions) responses that
300    /// held a transaction not matching the type or size its peer announced. Each one disconnects
301    /// the peer's session.
302    pub(crate) announcement_mismatches: Counter,
303}
304
305/// Measures the duration of executing the given code block. The duration is added to the given
306/// accumulator value passed as a mutable reference.
307#[macro_export]
308macro_rules! duration_metered_exec {
309    ($code:expr, $acc:expr) => {{
310        let start = reth_primitives_traits::FastInstant::now();
311
312        let res = $code;
313
314        $acc += start.elapsed();
315
316        res
317    }};
318}
319
320/// Direction-aware wrapper for disconnect metrics.
321///
322/// Tracks disconnect reasons for inbound and outbound connections separately, in addition to
323/// the combined (legacy) counters.
324#[derive(Debug, Default)]
325pub(crate) struct DirectionalDisconnectMetrics {
326    /// Combined disconnect metrics (all directions).
327    pub(crate) total: DisconnectMetrics,
328    /// Disconnect metrics for inbound connections only.
329    pub(crate) inbound: InboundDisconnectMetrics,
330    /// Disconnect metrics for outbound connections only.
331    pub(crate) outbound: OutboundDisconnectMetrics,
332}
333
334impl DirectionalDisconnectMetrics {
335    /// Increments disconnect counters for an inbound connection.
336    pub(crate) fn increment_inbound(&self, reason: DisconnectReason) {
337        self.total.increment(reason);
338        self.inbound.increment(reason);
339    }
340
341    /// Increments disconnect counters for an outbound connection.
342    pub(crate) fn increment_outbound(&self, reason: DisconnectReason) {
343        self.total.increment(reason);
344        self.outbound.increment(reason);
345    }
346}
347
348/// Metrics for Disconnection types
349///
350/// These are just counters, and ideally we would implement these metrics on a peer-by-peer basis,
351/// in that we do not double-count peers for `TooManyPeers` if we make an outgoing connection and
352/// get disconnected twice
353#[derive(Metrics)]
354#[metrics(scope = "network")]
355pub struct DisconnectMetrics {
356    /// Number of peer disconnects due to `DisconnectRequested` (0x00)
357    pub(crate) disconnect_requested: Counter,
358
359    /// Number of peer disconnects due to `TcpSubsystemError` (0x01)
360    pub(crate) tcp_subsystem_error: Counter,
361
362    /// Number of peer disconnects due to `ProtocolBreach` (0x02)
363    pub(crate) protocol_breach: Counter,
364
365    /// Number of peer disconnects due to `UselessPeer` (0x03)
366    pub(crate) useless_peer: Counter,
367
368    /// Number of peer disconnects due to `TooManyPeers` (0x04)
369    pub(crate) too_many_peers: Counter,
370
371    /// Number of peer disconnects due to `AlreadyConnected` (0x05)
372    pub(crate) already_connected: Counter,
373
374    /// Number of peer disconnects due to `IncompatibleP2PProtocolVersion` (0x06)
375    pub(crate) incompatible: Counter,
376
377    /// Number of peer disconnects due to `NullNodeIdentity` (0x07)
378    pub(crate) null_node_identity: Counter,
379
380    /// Number of peer disconnects due to `ClientQuitting` (0x08)
381    pub(crate) client_quitting: Counter,
382
383    /// Number of peer disconnects due to `UnexpectedHandshakeIdentity` (0x09)
384    pub(crate) unexpected_identity: Counter,
385
386    /// Number of peer disconnects due to `ConnectedToSelf` (0x0a)
387    pub(crate) connected_to_self: Counter,
388
389    /// Number of peer disconnects due to `PingTimeout` (0x0b)
390    pub(crate) ping_timeout: Counter,
391
392    /// Number of peer disconnects due to `SubprotocolSpecific` (0x10)
393    pub(crate) subprotocol_specific: Counter,
394}
395
396impl DisconnectMetrics {
397    /// Increments the proper counter for the given disconnect reason
398    pub(crate) fn increment(&self, reason: DisconnectReason) {
399        match reason {
400            DisconnectReason::DisconnectRequested => self.disconnect_requested.increment(1),
401            DisconnectReason::TcpSubsystemError => self.tcp_subsystem_error.increment(1),
402            DisconnectReason::ProtocolBreach => self.protocol_breach.increment(1),
403            DisconnectReason::UselessPeer => self.useless_peer.increment(1),
404            DisconnectReason::TooManyPeers => self.too_many_peers.increment(1),
405            DisconnectReason::AlreadyConnected => self.already_connected.increment(1),
406            DisconnectReason::IncompatibleP2PProtocolVersion => self.incompatible.increment(1),
407            DisconnectReason::NullNodeIdentity => self.null_node_identity.increment(1),
408            DisconnectReason::ClientQuitting => self.client_quitting.increment(1),
409            DisconnectReason::UnexpectedHandshakeIdentity => self.unexpected_identity.increment(1),
410            DisconnectReason::ConnectedToSelf => self.connected_to_self.increment(1),
411            DisconnectReason::PingTimeout => self.ping_timeout.increment(1),
412            DisconnectReason::SubprotocolSpecific => self.subprotocol_specific.increment(1),
413        }
414    }
415}
416
417/// Disconnect metrics scoped to inbound connections only.
418///
419/// These counters track disconnect reasons exclusively for sessions that were initiated by
420/// remote peers connecting to this node. This helps operators distinguish between being rejected
421/// by remote peers (outbound) vs rejecting incoming peers (inbound).
422#[derive(Metrics)]
423#[metrics(scope = "network.inbound")]
424pub struct InboundDisconnectMetrics {
425    /// Number of inbound peer disconnects due to `DisconnectRequested` (0x00)
426    pub(crate) disconnect_requested: Counter,
427
428    /// Number of inbound peer disconnects due to `TcpSubsystemError` (0x01)
429    pub(crate) tcp_subsystem_error: Counter,
430
431    /// Number of inbound peer disconnects due to `ProtocolBreach` (0x02)
432    pub(crate) protocol_breach: Counter,
433
434    /// Number of inbound peer disconnects due to `UselessPeer` (0x03)
435    pub(crate) useless_peer: Counter,
436
437    /// Number of inbound peer disconnects due to `TooManyPeers` (0x04)
438    pub(crate) too_many_peers: Counter,
439
440    /// Number of inbound peer disconnects due to `AlreadyConnected` (0x05)
441    pub(crate) already_connected: Counter,
442
443    /// Number of inbound peer disconnects due to `IncompatibleP2PProtocolVersion` (0x06)
444    pub(crate) incompatible: Counter,
445
446    /// Number of inbound peer disconnects due to `NullNodeIdentity` (0x07)
447    pub(crate) null_node_identity: Counter,
448
449    /// Number of inbound peer disconnects due to `ClientQuitting` (0x08)
450    pub(crate) client_quitting: Counter,
451
452    /// Number of inbound peer disconnects due to `UnexpectedHandshakeIdentity` (0x09)
453    pub(crate) unexpected_identity: Counter,
454
455    /// Number of inbound peer disconnects due to `ConnectedToSelf` (0x0a)
456    pub(crate) connected_to_self: Counter,
457
458    /// Number of inbound peer disconnects due to `PingTimeout` (0x0b)
459    pub(crate) ping_timeout: Counter,
460
461    /// Number of inbound peer disconnects due to `SubprotocolSpecific` (0x10)
462    pub(crate) subprotocol_specific: Counter,
463}
464
465impl InboundDisconnectMetrics {
466    /// Increments the proper counter for the given disconnect reason
467    pub(crate) fn increment(&self, reason: DisconnectReason) {
468        match reason {
469            DisconnectReason::DisconnectRequested => self.disconnect_requested.increment(1),
470            DisconnectReason::TcpSubsystemError => self.tcp_subsystem_error.increment(1),
471            DisconnectReason::ProtocolBreach => self.protocol_breach.increment(1),
472            DisconnectReason::UselessPeer => self.useless_peer.increment(1),
473            DisconnectReason::TooManyPeers => self.too_many_peers.increment(1),
474            DisconnectReason::AlreadyConnected => self.already_connected.increment(1),
475            DisconnectReason::IncompatibleP2PProtocolVersion => self.incompatible.increment(1),
476            DisconnectReason::NullNodeIdentity => self.null_node_identity.increment(1),
477            DisconnectReason::ClientQuitting => self.client_quitting.increment(1),
478            DisconnectReason::UnexpectedHandshakeIdentity => self.unexpected_identity.increment(1),
479            DisconnectReason::ConnectedToSelf => self.connected_to_self.increment(1),
480            DisconnectReason::PingTimeout => self.ping_timeout.increment(1),
481            DisconnectReason::SubprotocolSpecific => self.subprotocol_specific.increment(1),
482        }
483    }
484}
485
486/// Disconnect metrics scoped to outbound connections only.
487///
488/// These counters track disconnect reasons exclusively for sessions that this node initiated
489/// by dialing out to remote peers. A high `too_many_peers` count here indicates remote peers
490/// are rejecting our connection attempts because they are full.
491#[derive(Metrics)]
492#[metrics(scope = "network.outbound")]
493pub struct OutboundDisconnectMetrics {
494    /// Number of outbound peer disconnects due to `DisconnectRequested` (0x00)
495    pub(crate) disconnect_requested: Counter,
496
497    /// Number of outbound peer disconnects due to `TcpSubsystemError` (0x01)
498    pub(crate) tcp_subsystem_error: Counter,
499
500    /// Number of outbound peer disconnects due to `ProtocolBreach` (0x02)
501    pub(crate) protocol_breach: Counter,
502
503    /// Number of outbound peer disconnects due to `UselessPeer` (0x03)
504    pub(crate) useless_peer: Counter,
505
506    /// Number of outbound peer disconnects due to `TooManyPeers` (0x04)
507    pub(crate) too_many_peers: Counter,
508
509    /// Number of outbound peer disconnects due to `AlreadyConnected` (0x05)
510    pub(crate) already_connected: Counter,
511
512    /// Number of outbound peer disconnects due to `IncompatibleP2PProtocolVersion` (0x06)
513    pub(crate) incompatible: Counter,
514
515    /// Number of outbound peer disconnects due to `NullNodeIdentity` (0x07)
516    pub(crate) null_node_identity: Counter,
517
518    /// Number of outbound peer disconnects due to `ClientQuitting` (0x08)
519    pub(crate) client_quitting: Counter,
520
521    /// Number of outbound peer disconnects due to `UnexpectedHandshakeIdentity` (0x09)
522    pub(crate) unexpected_identity: Counter,
523
524    /// Number of outbound peer disconnects due to `ConnectedToSelf` (0x0a)
525    pub(crate) connected_to_self: Counter,
526
527    /// Number of outbound peer disconnects due to `PingTimeout` (0x0b)
528    pub(crate) ping_timeout: Counter,
529
530    /// Number of outbound peer disconnects due to `SubprotocolSpecific` (0x10)
531    pub(crate) subprotocol_specific: Counter,
532}
533
534impl OutboundDisconnectMetrics {
535    /// Increments the proper counter for the given disconnect reason
536    pub(crate) fn increment(&self, reason: DisconnectReason) {
537        match reason {
538            DisconnectReason::DisconnectRequested => self.disconnect_requested.increment(1),
539            DisconnectReason::TcpSubsystemError => self.tcp_subsystem_error.increment(1),
540            DisconnectReason::ProtocolBreach => self.protocol_breach.increment(1),
541            DisconnectReason::UselessPeer => self.useless_peer.increment(1),
542            DisconnectReason::TooManyPeers => self.too_many_peers.increment(1),
543            DisconnectReason::AlreadyConnected => self.already_connected.increment(1),
544            DisconnectReason::IncompatibleP2PProtocolVersion => self.incompatible.increment(1),
545            DisconnectReason::NullNodeIdentity => self.null_node_identity.increment(1),
546            DisconnectReason::ClientQuitting => self.client_quitting.increment(1),
547            DisconnectReason::UnexpectedHandshakeIdentity => self.unexpected_identity.increment(1),
548            DisconnectReason::ConnectedToSelf => self.connected_to_self.increment(1),
549            DisconnectReason::PingTimeout => self.ping_timeout.increment(1),
550            DisconnectReason::SubprotocolSpecific => self.subprotocol_specific.increment(1),
551        }
552    }
553}
554
555/// Metrics for the `EthRequestHandler`
556#[derive(Metrics)]
557#[metrics(scope = "network")]
558pub struct EthRequestHandlerMetrics {
559    /// Number of `GetBlockHeaders` requests received
560    pub(crate) eth_headers_requests_received_total: Counter,
561
562    /// Number of `GetReceipts` requests received
563    pub(crate) eth_receipts_requests_received_total: Counter,
564
565    /// Number of `GetBlockBodies` requests received
566    pub(crate) eth_bodies_requests_received_total: Counter,
567
568    /// Number of `GetNodeData` requests received
569    pub(crate) eth_node_data_requests_received_total: Counter,
570
571    /// Number of `GetBlockAccessLists` requests received
572    pub(crate) eth_block_access_lists_requests_received_total: Counter,
573
574    /// Number of `snap/2` (EIP-8189) requests received
575    pub(crate) snap_requests_received_total: Counter,
576
577    /// Number of `snap/2` state range requests answered empty without being served: the queue
578    /// was full, the peer already held a place in it, or the request waited too long
579    pub(crate) snap_state_range_requests_unserved_total: Counter,
580
581    /// Duration in seconds of call to poll
582    /// [`EthRequestHandler`](crate::eth_requests::EthRequestHandler).
583    pub(crate) acc_duration_poll_eth_req_handler: Gauge,
584}
585
586/// Eth67 announcement metrics, track entries by `TxType`
587#[derive(Metrics)]
588#[metrics(scope = "network.transaction_fetcher")]
589pub struct AnnouncedTxTypesMetrics {
590    /// Histogram for tracking frequency of legacy transaction type
591    pub(crate) legacy: Histogram,
592
593    /// Histogram for tracking frequency of EIP-2930 transaction type
594    pub(crate) eip2930: Histogram,
595
596    /// Histogram for tracking frequency of EIP-1559 transaction type
597    pub(crate) eip1559: Histogram,
598
599    /// Histogram for tracking frequency of EIP-4844 transaction type
600    pub(crate) eip4844: Histogram,
601
602    /// Histogram for tracking frequency of EIP-7702 transaction type
603    pub(crate) eip7702: Histogram,
604
605    /// Histogram for tracking frequency of unknown/other transaction types
606    pub(crate) other: Histogram,
607}
608
609/// Counts the number of transactions by their type in a block or collection.
610///
611/// This struct keeps track of the count of different transaction types
612/// as defined by various Ethereum Improvement Proposals (EIPs).
613#[derive(Debug, Default)]
614pub struct TxTypesCounter {
615    /// Count of legacy transactions (pre-EIP-2718).
616    pub(crate) legacy: usize,
617
618    /// Count of transactions conforming to EIP-2930 (Optional access lists).
619    pub(crate) eip2930: usize,
620
621    /// Count of transactions conforming to EIP-1559 (Fee market change).
622    pub(crate) eip1559: usize,
623
624    /// Count of transactions conforming to EIP-4844 (Shard Blob Transactions).
625    pub(crate) eip4844: usize,
626
627    /// Count of transactions conforming to EIP-7702 (Restricted Storage Windows).
628    pub(crate) eip7702: usize,
629
630    /// Count of unknown/other transaction types not matching any known EIP.
631    pub(crate) other: usize,
632}
633
634impl TxTypesCounter {
635    pub(crate) const fn increase_by_tx_type(&mut self, tx_type: TxType) {
636        match tx_type {
637            TxType::Legacy => {
638                self.legacy += 1;
639            }
640            TxType::Eip2930 => {
641                self.eip2930 += 1;
642            }
643            TxType::Eip1559 => {
644                self.eip1559 += 1;
645            }
646            TxType::Eip4844 => {
647                self.eip4844 += 1;
648            }
649            TxType::Eip7702 => {
650                self.eip7702 += 1;
651            }
652        }
653    }
654
655    pub(crate) const fn increase_other(&mut self) {
656        self.other += 1;
657    }
658}
659
660impl AnnouncedTxTypesMetrics {
661    /// Update metrics during announcement validation, by examining each announcement entry based on
662    /// `TxType`
663    pub(crate) fn update_eth68_announcement_metrics(&self, tx_types_counter: TxTypesCounter) {
664        self.legacy.record(tx_types_counter.legacy as f64);
665        self.eip2930.record(tx_types_counter.eip2930 as f64);
666        self.eip1559.record(tx_types_counter.eip1559 as f64);
667        self.eip4844.record(tx_types_counter.eip4844 as f64);
668        self.eip7702.record(tx_types_counter.eip7702 as f64);
669        self.other.record(tx_types_counter.other as f64);
670    }
671}