• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Neptune-Crypto / neptune-core / 13975417391

20 Mar 2025 05:18PM UTC coverage: 84.259% (+0.005%) from 84.254%
13975417391

push

github

Sword-Smith
fix(peer_discovery): Wait interval before running from main_loop

If this runs immediately on startup, it will contact the same peers
twice, as the outgoing connections initiated from lib.rs have not been
established yet.

0 of 7 new or added lines in 1 file covered. (0.0%)

2 existing lines in 2 files now uncovered.

50757 of 60239 relevant lines covered (84.26%)

175830.84 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

56.54
/src/main_loop.rs
1
pub mod proof_upgrader;
2

3
use std::collections::HashMap;
4
use std::net::SocketAddr;
5
use std::time::Duration;
6
use std::time::SystemTime;
7

8
use anyhow::Result;
9
use itertools::Itertools;
10
use proof_upgrader::get_upgrade_task_from_mempool;
11
use proof_upgrader::UpdateMutatorSetDataJob;
12
use proof_upgrader::UpgradeJob;
13
use rand::prelude::IteratorRandom;
14
use rand::seq::IndexedRandom;
15
use tokio::net::TcpListener;
16
use tokio::select;
17
use tokio::signal;
18
use tokio::sync::broadcast;
19
use tokio::sync::mpsc;
20
use tokio::task::JoinHandle;
21
use tokio::time;
22
use tokio::time::Instant;
23
use tokio::time::MissedTickBehavior;
24
use tracing::debug;
25
use tracing::error;
26
use tracing::info;
27
use tracing::trace;
28
use tracing::warn;
29

30
use crate::connect_to_peers::answer_peer;
31
use crate::connect_to_peers::call_peer;
32
use crate::job_queue::triton_vm::TritonVmJobPriority;
33
use crate::job_queue::triton_vm::TritonVmJobQueue;
34
use crate::macros::fn_name;
35
use crate::macros::log_slow_scope;
36
use crate::models::blockchain::block::block_header::BlockHeader;
37
use crate::models::blockchain::block::block_height::BlockHeight;
38
use crate::models::blockchain::block::difficulty_control::ProofOfWork;
39
use crate::models::blockchain::block::Block;
40
use crate::models::blockchain::transaction::Transaction;
41
use crate::models::blockchain::transaction::TransactionProof;
42
use crate::models::channel::MainToMiner;
43
use crate::models::channel::MainToPeerTask;
44
use crate::models::channel::MainToPeerTaskBatchBlockRequest;
45
use crate::models::channel::MinerToMain;
46
use crate::models::channel::PeerTaskToMain;
47
use crate::models::channel::RPCServerToMain;
48
use crate::models::peer::handshake_data::HandshakeData;
49
use crate::models::peer::peer_info::PeerInfo;
50
use crate::models::peer::transaction_notification::TransactionNotification;
51
use crate::models::peer::PeerSynchronizationState;
52
use crate::models::proof_abstractions::tasm::program::TritonVmProofJobOptions;
53
use crate::models::state::block_proposal::BlockProposal;
54
use crate::models::state::mempool::TransactionOrigin;
55
use crate::models::state::networking_state::SyncAnchor;
56
use crate::models::state::tx_proving_capability::TxProvingCapability;
57
use crate::models::state::GlobalState;
58
use crate::models::state::GlobalStateLock;
59
use crate::SUCCESS_EXIT_CODE;
60

61
const PEER_DISCOVERY_INTERVAL: Duration = Duration::from_secs(2 * 60);
62
const SYNC_REQUEST_INTERVAL: Duration = Duration::from_secs(3);
63
const MEMPOOL_PRUNE_INTERVAL: Duration = Duration::from_secs(30 * 60);
64
const MP_RESYNC_INTERVAL: Duration = Duration::from_secs(59);
65
const EXPECTED_UTXOS_PRUNE_INTERVAL: Duration = Duration::from_secs(19 * 60);
66

67
/// Interval for when transaction-upgrade checker is run. Note that this does
68
/// *not* define how often a transaction-proof upgrade is actually performed.
69
/// Only how often we check if we're ready to perform an upgrade.
70
const TRANSACTION_UPGRADE_CHECK_INTERVAL: Duration = Duration::from_secs(60);
71

72
const SANCTION_PEER_TIMEOUT_FACTOR: u64 = 40;
73

74
/// Number of seconds within which an individual peer is expected to respond
75
/// to a synchronization request.
76
const INDIVIDUAL_PEER_SYNCHRONIZATION_TIMEOUT: Duration =
77
    Duration::from_secs(SYNC_REQUEST_INTERVAL.as_secs() * SANCTION_PEER_TIMEOUT_FACTOR);
78

79
/// Number of seconds that a synchronization may run without any progress.
80
const GLOBAL_SYNCHRONIZATION_TIMEOUT: Duration =
81
    Duration::from_secs(INDIVIDUAL_PEER_SYNCHRONIZATION_TIMEOUT.as_secs() * 4);
82

83
const POTENTIAL_PEER_MAX_COUNT_AS_A_FACTOR_OF_MAX_PEERS: usize = 20;
84
pub(crate) const MAX_NUM_DIGESTS_IN_BATCH_REQUEST: usize = 200;
85
const TX_UPDATER_CHANNEL_CAPACITY: usize = 1;
86

87
/// Wraps a transmission channel.
88
///
89
/// To be used for the transmission channel to the miner, because
90
///  a) the miner might not exist in which case there would be no-one to empty
91
///     the channel; and
92
///  b) contrary to other channels, transmission failures here are not critical.
93
#[derive(Debug)]
94
struct MainToMinerChannel(Option<mpsc::Sender<MainToMiner>>);
95

96
impl MainToMinerChannel {
97
    /// Send a message to the miner task (if any).
98
    fn send(&self, message: MainToMiner) {
×
99
        // Do no use the async `send` function because it blocks until there
100
        // is spare capacity on the channel. Messages to the miner are not
101
        // critical so if there is no capacity left, just log an error
102
        // message.
103
        if let Some(channel) = &self.0 {
×
104
            if let Err(e) = channel.try_send(message) {
×
105
                error!("Failed to send pause message to miner thread:\n{e}");
×
106
            }
×
107
        }
×
108
    }
×
109
}
110

111
/// MainLoop is the immutable part of the input for the main loop function
112
#[derive(Debug)]
113
pub struct MainLoopHandler {
114
    incoming_peer_listener: TcpListener,
115
    global_state_lock: GlobalStateLock,
116

117
    // note: broadcast::Sender::send() does not block
118
    main_to_peer_broadcast_tx: broadcast::Sender<MainToPeerTask>,
119

120
    // note: mpsc::Sender::send() blocks if channel full.
121
    // locks should not be held across it.
122
    peer_task_to_main_tx: mpsc::Sender<PeerTaskToMain>,
123

124
    // note: MainToMinerChannel::send() does not block.  might log error.
125
    main_to_miner_tx: MainToMinerChannel,
126

127
    #[cfg(test)]
128
    mock_now: Option<SystemTime>,
129
}
130

131
/// The mutable part of the main loop function
132
struct MutableMainLoopState {
133
    /// Information used to batch-download blocks.
134
    sync_state: SyncState,
135

136
    /// Information about potential peers for new connections.
137
    potential_peers: PotentialPeersState,
138

139
    /// A list of join-handles to spawned tasks.
140
    task_handles: Vec<JoinHandle<()>>,
141

142
    /// A join-handle to a task performing transaction-proof upgrades.
143
    proof_upgrader_task: Option<JoinHandle<()>>,
144

145
    /// A join-handle to a task running the update of the mempool transactions.
146
    update_mempool_txs_handle: Option<JoinHandle<()>>,
147

148
    /// A channel that the task updating mempool transactions can use to
149
    /// communicate its result.
150
    update_mempool_receiver: mpsc::Receiver<Vec<Transaction>>,
151
}
152

153
impl MutableMainLoopState {
154
    fn new(task_handles: Vec<JoinHandle<()>>) -> Self {
6✔
155
        let (_dummy_sender, dummy_receiver) =
6✔
156
            mpsc::channel::<Vec<Transaction>>(TX_UPDATER_CHANNEL_CAPACITY);
6✔
157
        Self {
6✔
158
            sync_state: SyncState::default(),
6✔
159
            potential_peers: PotentialPeersState::default(),
6✔
160
            task_handles,
6✔
161
            proof_upgrader_task: None,
6✔
162
            update_mempool_txs_handle: None,
6✔
163
            update_mempool_receiver: dummy_receiver,
6✔
164
        }
6✔
165
    }
6✔
166
}
167

168
/// handles batch-downloading of blocks if we are more than n blocks behind
169
#[derive(Default, Debug)]
170
struct SyncState {
171
    peer_sync_states: HashMap<SocketAddr, PeerSynchronizationState>,
172
    last_sync_request: Option<(SystemTime, BlockHeight, SocketAddr)>,
173
}
174

175
impl SyncState {
176
    fn record_request(
1✔
177
        &mut self,
1✔
178
        requested_block_height: BlockHeight,
1✔
179
        peer: SocketAddr,
1✔
180
        now: SystemTime,
1✔
181
    ) {
1✔
182
        self.last_sync_request = Some((now, requested_block_height, peer));
1✔
183
    }
1✔
184

185
    /// Return a list of peers that have reported to be in possession of blocks
186
    /// with a PoW above a threshold.
187
    fn get_potential_peers_for_sync_request(&self, threshold_pow: ProofOfWork) -> Vec<SocketAddr> {
2✔
188
        self.peer_sync_states
2✔
189
            .iter()
2✔
190
            .filter(|(_sa, sync_state)| sync_state.claimed_max_pow > threshold_pow)
2✔
191
            .map(|(sa, _)| *sa)
2✔
192
            .collect()
2✔
193
    }
2✔
194

195
    /// Determine if a peer should be sanctioned for failing to respond to a
196
    /// synchronization request fast enough. Also determine if a new request
197
    /// should be made or the previous one should be allowed to run for longer.
198
    ///
199
    /// Returns (peer to be sanctioned, attempt new request).
200
    fn get_status_of_last_request(
1✔
201
        &self,
1✔
202
        current_block_height: BlockHeight,
1✔
203
        now: SystemTime,
1✔
204
    ) -> (Option<SocketAddr>, bool) {
1✔
205
        // A peer is sanctioned if no answer has been received after N times the sync request
1✔
206
        // interval.
1✔
207
        match self.last_sync_request {
1✔
208
            None => {
209
                // No sync request has been made since startup of program
210
                (None, true)
1✔
211
            }
212
            Some((req_time, requested_height, peer_sa)) => {
×
213
                if requested_height < current_block_height {
×
214
                    // The last sync request updated the state
215
                    (None, true)
×
216
                } else if req_time + INDIVIDUAL_PEER_SYNCHRONIZATION_TIMEOUT < now {
×
217
                    // The last sync request was not answered, sanction peer
218
                    // and make a new sync request.
219
                    (Some(peer_sa), true)
×
220
                } else {
221
                    // The last sync request has not yet been answered. But it has
222
                    // not timed out yet.
223
                    (None, false)
×
224
                }
225
            }
226
        }
227
    }
1✔
228
}
229

230
/// holds information about a potential peer in the process of peer discovery
231
struct PotentialPeerInfo {
232
    _reported: SystemTime,
233
    _reported_by: SocketAddr,
234
    instance_id: u128,
235
    distance: u8,
236
}
237

238
impl PotentialPeerInfo {
239
    fn new(reported_by: SocketAddr, instance_id: u128, distance: u8, now: SystemTime) -> Self {
×
240
        Self {
×
241
            _reported: now,
×
242
            _reported_by: reported_by,
×
243
            instance_id,
×
244
            distance,
×
245
        }
×
246
    }
×
247
}
248

249
/// holds information about a set of potential peers in the process of peer discovery
250
struct PotentialPeersState {
251
    potential_peers: HashMap<SocketAddr, PotentialPeerInfo>,
252
}
253

254
impl PotentialPeersState {
255
    fn default() -> Self {
6✔
256
        Self {
6✔
257
            potential_peers: HashMap::new(),
6✔
258
        }
6✔
259
    }
6✔
260

261
    fn add(
×
262
        &mut self,
×
263
        reported_by: SocketAddr,
×
264
        potential_peer: (SocketAddr, u128),
×
265
        max_peers: usize,
×
266
        distance: u8,
×
267
        now: SystemTime,
×
268
    ) {
×
269
        let potential_peer_socket_address = potential_peer.0;
×
270
        let potential_peer_instance_id = potential_peer.1;
×
271

×
272
        // This check *should* make it likely that a potential peer is always
×
273
        // registered with the lowest observed distance.
×
274
        if self
×
275
            .potential_peers
×
276
            .contains_key(&potential_peer_socket_address)
×
277
        {
278
            return;
×
279
        }
×
280

×
281
        // If this data structure is full, remove a random entry. Then add this.
×
282
        if self.potential_peers.len()
×
283
            > max_peers * POTENTIAL_PEER_MAX_COUNT_AS_A_FACTOR_OF_MAX_PEERS
×
284
        {
×
285
            let mut rng = rand::rng();
×
286
            let random_potential_peer = self
×
287
                .potential_peers
×
288
                .keys()
×
289
                .choose(&mut rng)
×
290
                .unwrap()
×
291
                .to_owned();
×
292
            self.potential_peers.remove(&random_potential_peer);
×
293
        }
×
294

295
        let insert_value =
×
296
            PotentialPeerInfo::new(reported_by, potential_peer_instance_id, distance, now);
×
297
        self.potential_peers
×
298
            .insert(potential_peer_socket_address, insert_value);
×
299
    }
×
300

301
    /// Return a peer from the potential peer list that we aren't connected to
302
    /// and  that isn't our own address.
303
    ///
304
    /// Favors peers with a high distance and with IPs that we are not already
305
    /// connected to.
306
    ///
307
    /// Returns (socket address, peer distance)
308
    fn get_candidate(
1✔
309
        &self,
1✔
310
        connected_clients: &[PeerInfo],
1✔
311
        own_instance_id: u128,
1✔
312
    ) -> Option<(SocketAddr, u8)> {
1✔
313
        let peers_instance_ids: Vec<u128> =
1✔
314
            connected_clients.iter().map(|x| x.instance_id()).collect();
2✔
315

1✔
316
        // Only pick those peers that report a listening port
1✔
317
        let peers_listen_addresses: Vec<SocketAddr> = connected_clients
1✔
318
            .iter()
1✔
319
            .filter_map(|x| x.listen_address())
2✔
320
            .collect();
1✔
321

1✔
322
        // Find the appropriate candidates
1✔
323
        let candidates = self
1✔
324
            .potential_peers
1✔
325
            .iter()
1✔
326
            // Prevent connecting to self. Note that we *only* use instance ID to prevent this,
1✔
327
            // meaning this will allow multiple nodes e.g. running on the same computer to form
1✔
328
            // a complete graph.
1✔
329
            .filter(|pp| pp.1.instance_id != own_instance_id)
1✔
330
            // Prevent connecting to peer we already are connected to
1✔
331
            .filter(|potential_peer| !peers_instance_ids.contains(&potential_peer.1.instance_id))
1✔
332
            .filter(|potential_peer| !peers_listen_addresses.contains(potential_peer.0))
1✔
333
            .collect::<Vec<_>>();
1✔
334

1✔
335
        // Prefer candidates with IPs that we are not already connected to but
1✔
336
        // connect to repeated IPs in case we don't have other options, as
1✔
337
        // repeated IPs may just be multiple machines on the same NAT'ed IPv4
1✔
338
        // address.
1✔
339
        let mut connected_ips = peers_listen_addresses.into_iter().map(|x| x.ip());
1✔
340
        let candidates = if candidates
1✔
341
            .iter()
1✔
342
            .any(|candidate| !connected_ips.contains(&candidate.0.ip()))
1✔
343
        {
344
            candidates
×
345
                .into_iter()
×
346
                .filter(|candidate| !connected_ips.contains(&candidate.0.ip()))
×
347
                .collect()
×
348
        } else {
349
            candidates
1✔
350
        };
351

352
        // Get the candidate list with the highest distance
353
        let max_distance_candidates = candidates.iter().max_by_key(|pp| pp.1.distance);
1✔
354

1✔
355
        // Pick a random candidate from the appropriate candidates
1✔
356
        let mut rng = rand::rng();
1✔
357
        max_distance_candidates
1✔
358
            .iter()
1✔
359
            .choose(&mut rng)
1✔
360
            .map(|x| (x.0.to_owned(), x.1.distance))
1✔
361
    }
1✔
362
}
363

364
/// Return a boolean indicating if synchronization mode should be left
365
fn stay_in_sync_mode(
×
366
    own_block_tip_header: &BlockHeader,
×
367
    sync_state: &SyncState,
×
368
    sync_mode_threshold: usize,
×
369
) -> bool {
×
370
    let max_claimed_pow = sync_state
×
371
        .peer_sync_states
×
372
        .values()
×
373
        .max_by_key(|x| x.claimed_max_pow);
×
374
    match max_claimed_pow {
×
375
        None => false, // No peer have passed the sync challenge phase.
×
376

377
        // Synchronization is left when the remaining number of block is half of what has
378
        // been indicated to fit into RAM
379
        Some(max_claim) => {
×
380
            own_block_tip_header.cumulative_proof_of_work < max_claim.claimed_max_pow
×
381
                && max_claim.claimed_max_height - own_block_tip_header.height
×
382
                    > sync_mode_threshold as i128 / 2
×
383
        }
384
    }
385
}
×
386

387
impl MainLoopHandler {
388
    pub(crate) fn new(
8✔
389
        incoming_peer_listener: TcpListener,
8✔
390
        global_state_lock: GlobalStateLock,
8✔
391
        main_to_peer_broadcast_tx: broadcast::Sender<MainToPeerTask>,
8✔
392
        peer_task_to_main_tx: mpsc::Sender<PeerTaskToMain>,
8✔
393
        main_to_miner_tx: mpsc::Sender<MainToMiner>,
8✔
394
    ) -> Self {
8✔
395
        let maybe_main_to_miner_tx = if global_state_lock.cli().mine() {
8✔
396
            Some(main_to_miner_tx)
×
397
        } else {
398
            None
8✔
399
        };
400
        Self {
8✔
401
            incoming_peer_listener,
8✔
402
            global_state_lock,
8✔
403
            main_to_miner_tx: MainToMinerChannel(maybe_main_to_miner_tx),
8✔
404
            main_to_peer_broadcast_tx,
8✔
405
            peer_task_to_main_tx,
8✔
406
            #[cfg(test)]
8✔
407
            mock_now: None,
8✔
408
        }
8✔
409
    }
8✔
410

411
    /// Allows for mocked timestamps such that time dependencies may be tested.
412
    #[cfg(test)]
413
    fn with_mocked_time(mut self, mocked_time: SystemTime) -> Self {
3✔
414
        self.mock_now = Some(mocked_time);
3✔
415
        self
3✔
416
    }
3✔
417

418
    fn now(&self) -> SystemTime {
7✔
419
        #[cfg(not(test))]
7✔
420
        {
7✔
421
            SystemTime::now()
7✔
422
        }
7✔
423
        #[cfg(test)]
7✔
424
        {
7✔
425
            self.mock_now.unwrap_or(SystemTime::now())
7✔
426
        }
7✔
427
    }
7✔
428

429
    /// Run a list of Triton VM prover jobs that update the mutator set state
430
    /// for transactions.
431
    ///
432
    /// Sends the result back through the provided channel.
433
    async fn update_mempool_jobs(
×
434
        update_jobs: Vec<UpdateMutatorSetDataJob>,
×
435
        job_queue: &TritonVmJobQueue,
×
436
        transaction_update_sender: mpsc::Sender<Vec<Transaction>>,
×
437
        proof_job_options: TritonVmProofJobOptions,
×
438
    ) {
×
439
        debug!(
×
440
            "Attempting to update transaction proofs of {} transactions",
×
441
            update_jobs.len()
×
442
        );
443
        let mut result = vec![];
×
444
        for job in update_jobs {
×
445
            // Jobs for updating txs in the mempool have highest priority since
446
            // they block the composer from continuing.
447
            // TODO: Handle errors better here.
448
            let job_result = job
×
449
                .upgrade(job_queue, proof_job_options.clone())
×
450
                .await
×
451
                .unwrap();
×
452
            result.push(job_result);
×
453
        }
454

455
        transaction_update_sender
×
456
            .send(result)
×
457
            .await
×
458
            .expect("Receiver for updated txs in main loop must still exist");
×
459
    }
×
460

461
    /// Handles a list of transactions whose proof has been updated with new
462
    /// mutator set data.
463
    async fn handle_updated_mempool_txs(&mut self, updated_txs: Vec<Transaction>) {
×
464
        // Update mempool with updated transactions
465
        {
466
            let mut state = self.global_state_lock.lock_guard_mut().await;
×
467
            for updated in &updated_txs {
×
468
                let txid = updated.kernel.txid();
×
469
                if let Some(tx) = state.mempool.get_mut(txid) {
×
470
                    *tx = updated.to_owned();
×
471
                } else {
×
472
                    warn!("Updated transaction which is no longer in mempool");
×
473
                }
474
            }
475
        }
476

477
        // Then notify all peers
478
        for updated in updated_txs {
×
479
            self.main_to_peer_broadcast_tx
×
480
                .send(MainToPeerTask::TransactionNotification(
×
481
                    (&updated).try_into().unwrap(),
×
482
                ))
×
483
                .unwrap();
×
484
        }
×
485

486
        // Tell miner that it can now start composing next block.
487
        self.main_to_miner_tx.send(MainToMiner::Continue);
×
488
    }
×
489

490
    /// Process a block whose PoW solution was solved by this client (or an
491
    /// external program) and has not been seen by the rest of the network yet.
492
    ///
493
    /// Shares block with all connected peers, updates own state, and updates
494
    /// any mempool transactions to be valid under this new block.
495
    ///
496
    /// Locking:
497
    ///  * acquires `global_state_lock` for write
498
    async fn handle_self_guessed_block(
1✔
499
        &mut self,
1✔
500
        main_loop_state: &mut MutableMainLoopState,
1✔
501
        new_block: Box<Block>,
1✔
502
    ) -> Result<()> {
1✔
503
        let mut global_state_mut = self.global_state_lock.lock_guard_mut().await;
1✔
504

505
        if !global_state_mut.incoming_block_is_more_canonical(&new_block) {
1✔
506
            drop(global_state_mut); // don't hold across send()
×
507
            warn!("Got new block from miner that was not child of tip. Discarding.");
×
508
            self.main_to_miner_tx.send(MainToMiner::Continue);
×
509
            return Ok(());
×
510
        }
1✔
511
        info!("Locally-mined block is new tip: {}", new_block.hash());
1✔
512

513
        // Share block with peers first thing.
514
        info!("broadcasting new block to peers");
1✔
515
        self.main_to_peer_broadcast_tx
1✔
516
            .send(MainToPeerTask::Block(new_block.clone()))
1✔
517
            .expect("Peer handler broadcast channel prematurely closed.");
1✔
518

519
        let update_jobs = global_state_mut.set_new_tip(*new_block).await?;
1✔
520
        drop(global_state_mut);
1✔
521

1✔
522
        self.spawn_mempool_txs_update_job(main_loop_state, update_jobs);
1✔
523

1✔
524
        Ok(())
1✔
525
    }
1✔
526

527
    /// Locking:
528
    ///   * acquires `global_state_lock` for write
529
    async fn handle_miner_task_message(
×
530
        &mut self,
×
531
        msg: MinerToMain,
×
532
        main_loop_state: &mut MutableMainLoopState,
×
533
    ) -> Result<Option<i32>> {
×
534
        match msg {
×
535
            MinerToMain::NewBlockFound(new_block_info) => {
×
536
                log_slow_scope!(fn_name!() + "::MinerToMain::NewBlockFound");
×
537

×
538
                let new_block = new_block_info.block;
×
539

×
540
                info!("Miner found new block: {}", new_block.kernel.header.height);
×
541
                self.handle_self_guessed_block(main_loop_state, new_block)
×
542
                    .await?;
×
543
            }
544
            MinerToMain::BlockProposal(boxed_proposal) => {
×
545
                let (block, expected_utxos) = *boxed_proposal;
×
546

547
                // If block proposal from miner does not build on current tip,
548
                // don't broadcast it. This check covers reorgs as well.
549
                let current_tip = self
×
550
                    .global_state_lock
×
551
                    .lock_guard()
×
552
                    .await
×
553
                    .chain
554
                    .light_state()
×
555
                    .clone();
×
556
                if block.header().prev_block_digest != current_tip.hash() {
×
557
                    warn!(
×
558
                        "Got block proposal from miner that does not build on current tip. \
×
559
                           Rejecting. If this happens a lot, then maybe this machine is too \
×
560
                           slow to competitively compose blocks. Consider running the client only \
×
561
                           with the guesser flag set and not the compose flag."
×
562
                    );
563
                    self.main_to_miner_tx.send(MainToMiner::Continue);
×
564
                    return Ok(None);
×
565
                }
×
566

×
567
                // Ensure proposal validity before sharing
×
568
                if !block.is_valid(&current_tip, block.header().timestamp).await {
×
569
                    error!("Own block proposal invalid. This should not happen.");
×
570
                    self.main_to_miner_tx.send(MainToMiner::Continue);
×
571
                    return Ok(None);
×
572
                }
×
573

×
574
                if !self.global_state_lock.cli().secret_compositions {
×
575
                    self.main_to_peer_broadcast_tx
×
576
                    .send(MainToPeerTask::BlockProposalNotification((&block).into()))
×
577
                    .expect(
×
578
                        "Peer handler broadcast channel prematurely closed. This should never happen.",
×
579
                    );
×
580
                }
×
581

582
                {
583
                    // Use block proposal and add expected UTXOs from this
584
                    // proposal.
585
                    let mut state = self.global_state_lock.lock_guard_mut().await;
×
586
                    state.mining_state.block_proposal =
×
587
                        BlockProposal::own_proposal(block.clone(), expected_utxos.clone());
×
588
                    state.wallet_state.add_expected_utxos(expected_utxos).await;
×
589
                }
590

591
                // Indicate to miner that block proposal was successfully
592
                // received by main-loop.
593
                self.main_to_miner_tx.send(MainToMiner::Continue);
×
594
            }
595
            MinerToMain::Shutdown(exit_code) => {
×
596
                return Ok(Some(exit_code));
×
597
            }
598
        }
599

600
        Ok(None)
×
601
    }
×
602

603
    /// Locking:
604
    ///   * acquires `global_state_lock` for write
605
    async fn handle_peer_task_message(
1✔
606
        &mut self,
1✔
607
        msg: PeerTaskToMain,
1✔
608
        main_loop_state: &mut MutableMainLoopState,
1✔
609
    ) -> Result<()> {
1✔
610
        debug!("Received {} from a peer task", msg.get_type());
1✔
611
        let cli_args = self.global_state_lock.cli().clone();
1✔
612
        match msg {
1✔
613
            PeerTaskToMain::NewBlocks(blocks) => {
×
614
                log_slow_scope!(fn_name!() + "::PeerTaskToMain::NewBlocks");
×
615

×
616
                let last_block = blocks.last().unwrap().to_owned();
×
617
                let update_jobs = {
×
618
                    // The peer tasks also check this condition, if block is more canonical than current
619
                    // tip, but we have to check it again since the block update might have already been applied
620
                    // through a message from another peer (or from own miner).
621
                    let mut global_state_mut = self.global_state_lock.lock_guard_mut().await;
×
622
                    let new_canonical =
×
623
                        global_state_mut.incoming_block_is_more_canonical(&last_block);
×
624

×
625
                    if !new_canonical {
×
626
                        // The blocks are not canonical, but: if we are in sync
627
                        // mode and these blocks beat our current champion, then
628
                        // we store them anyway, without marking them as tip.
629
                        let Some(sync_anchor) = global_state_mut.net.sync_anchor.as_mut() else {
×
630
                            warn!(
×
631
                                "Blocks were not new, and we're not syncing. Not storing blocks."
×
632
                            );
633
                            return Ok(());
×
634
                        };
635
                        if sync_anchor
×
636
                            .champion
×
637
                            .is_some_and(|(height, _)| height >= last_block.header().height)
×
638
                        {
639
                            warn!("Repeated blocks received in sync mode, not storing");
×
640
                            return Ok(());
×
641
                        }
×
642

×
643
                        sync_anchor.catch_up(last_block.header().height, last_block.hash());
×
644

645
                        for block in blocks {
×
646
                            global_state_mut.store_block_not_tip(block).await?;
×
647
                        }
648

649
                        return Ok(());
×
650
                    }
×
651

×
652
                    info!(
×
653
                        "Last block from peer is new canonical tip: {}; height: {}",
×
654
                        last_block.hash(),
×
655
                        last_block.header().height
×
656
                    );
657

658
                    // Ask miner to stop work until state update is completed
659
                    self.main_to_miner_tx.send(MainToMiner::WaitForContinue);
×
660

×
661
                    // Get out of sync mode if needed
×
662
                    if global_state_mut.net.sync_anchor.is_some() {
×
663
                        let stay_in_sync_mode = stay_in_sync_mode(
×
664
                            &last_block.kernel.header,
×
665
                            &main_loop_state.sync_state,
×
666
                            cli_args.sync_mode_threshold,
×
667
                        );
×
668
                        if !stay_in_sync_mode {
×
669
                            info!("Exiting sync mode");
×
670
                            global_state_mut.net.sync_anchor = None;
×
671
                            self.main_to_miner_tx.send(MainToMiner::StopSyncing);
×
672
                        }
×
673
                    }
×
674

675
                    let mut update_jobs: Vec<UpdateMutatorSetDataJob> = vec![];
×
676
                    for new_block in blocks {
×
677
                        debug!(
×
678
                            "Storing block {} in database. Height: {}, Mined: {}",
×
679
                            new_block.hash(),
×
680
                            new_block.kernel.header.height,
×
681
                            new_block.kernel.header.timestamp.standard_format()
×
682
                        );
683

684
                        // Potential race condition here.
685
                        // What if last block is new and canonical, but first
686
                        // block is already known then we'll store the same block
687
                        // twice. That should be OK though, as the appropriate
688
                        // database entries are simply overwritten with the new
689
                        // block info. See the
690
                        // [GlobalState::test::setting_same_tip_twice_is_allowed]
691
                        // test for a test of this phenomenon.
692

693
                        let update_jobs_ = global_state_mut.set_new_tip(new_block).await?;
×
694
                        update_jobs.extend(update_jobs_);
×
695
                    }
696

697
                    update_jobs
×
698
                };
×
699

×
700
                // Inform all peers about new block
×
701
                self.main_to_peer_broadcast_tx
×
702
                    .send(MainToPeerTask::Block(Box::new(last_block.clone())))
×
703
                    .expect("Peer handler broadcast was closed. This should never happen");
×
704

×
705
                // Spawn task to handle mempool tx-updating after new blocks.
×
706
                // TODO: Do clever trick to collapse all jobs relating to the same transaction,
×
707
                //       identified by transaction-ID, into *one* update job.
×
708
                self.spawn_mempool_txs_update_job(main_loop_state, update_jobs);
×
709

×
710
                // Inform miner about new block.
×
711
                self.main_to_miner_tx.send(MainToMiner::NewBlock);
×
712
            }
713
            PeerTaskToMain::AddPeerMaxBlockHeight {
714
                peer_address,
×
715
                claimed_height,
×
716
                claimed_cumulative_pow,
×
717
                claimed_block_mmra,
×
718
            } => {
×
719
                log_slow_scope!(fn_name!() + "::PeerTaskToMain::AddPeerMaxBlockHeight");
×
720

×
721
                let claimed_state =
×
722
                    PeerSynchronizationState::new(claimed_height, claimed_cumulative_pow);
×
723
                main_loop_state
×
724
                    .sync_state
×
725
                    .peer_sync_states
×
726
                    .insert(peer_address, claimed_state);
×
727

728
                // Check if synchronization mode should be activated.
729
                // Synchronization mode is entered if accumulated PoW exceeds
730
                // our tip and if the height difference is positive and beyond
731
                // a threshold value.
732
                let mut global_state_mut = self.global_state_lock.lock_guard_mut().await;
×
733
                if global_state_mut.sync_mode_criterion(claimed_height, claimed_cumulative_pow)
×
734
                    && global_state_mut
×
735
                        .net
×
736
                        .sync_anchor
×
737
                        .as_ref()
×
738
                        .is_none_or(|sa| sa.cumulative_proof_of_work < claimed_cumulative_pow)
×
739
                {
740
                    info!(
×
741
                        "Entering synchronization mode due to peer {} indicating tip height {}; cumulative pow: {:?}",
×
742
                        peer_address, claimed_height, claimed_cumulative_pow
743
                    );
744
                    global_state_mut.net.sync_anchor =
×
745
                        Some(SyncAnchor::new(claimed_cumulative_pow, claimed_block_mmra));
×
746
                    self.main_to_miner_tx.send(MainToMiner::StartSyncing);
×
747
                }
×
748
            }
749
            PeerTaskToMain::RemovePeerMaxBlockHeight(socket_addr) => {
×
750
                log_slow_scope!(fn_name!() + "::PeerTaskToMain::RemovePeerMaxBlockHeight");
×
751

×
752
                debug!(
×
753
                    "Removing max block height from sync data structure for peer {}",
×
754
                    socket_addr
755
                );
756
                main_loop_state
×
757
                    .sync_state
×
758
                    .peer_sync_states
×
759
                    .remove(&socket_addr);
×
760

761
                // Get out of sync mode if needed.
762
                let mut global_state_mut = self.global_state_lock.lock_guard_mut().await;
×
763

764
                if global_state_mut.net.sync_anchor.is_some() {
×
765
                    let stay_in_sync_mode = stay_in_sync_mode(
×
766
                        global_state_mut.chain.light_state().header(),
×
767
                        &main_loop_state.sync_state,
×
768
                        cli_args.sync_mode_threshold,
×
769
                    );
×
770
                    if !stay_in_sync_mode {
×
771
                        info!("Exiting sync mode");
×
772
                        global_state_mut.net.sync_anchor = None;
×
773
                    }
×
774
                }
×
775
            }
776
            PeerTaskToMain::PeerDiscoveryAnswer((pot_peers, reported_by, distance)) => {
×
777
                log_slow_scope!(fn_name!() + "::PeerTaskToMain::PeerDiscoveryAnswer");
×
778

×
779
                let max_peers = self.global_state_lock.cli().max_num_peers;
×
780
                for pot_peer in pot_peers {
×
781
                    main_loop_state.potential_peers.add(
×
782
                        reported_by,
×
783
                        pot_peer,
×
784
                        max_peers,
×
785
                        distance,
×
786
                        self.now(),
×
787
                    );
×
788
                }
×
789
            }
790
            PeerTaskToMain::Transaction(pt2m_transaction) => {
×
791
                log_slow_scope!(fn_name!() + "::PeerTaskToMain::Transaction");
×
792

×
793
                debug!(
×
794
                    "`peer_loop` received following transaction from peer. {} inputs, {} outputs. Synced to mutator set hash: {}",
×
795
                    pt2m_transaction.transaction.kernel.inputs.len(),
×
796
                    pt2m_transaction.transaction.kernel.outputs.len(),
×
797
                    pt2m_transaction.transaction.kernel.mutator_set_hash
×
798
                );
799

800
                {
801
                    let mut global_state_mut = self.global_state_lock.lock_guard_mut().await;
×
802
                    if pt2m_transaction.confirmable_for_block
×
803
                        != global_state_mut.chain.light_state().hash()
×
804
                    {
805
                        warn!("main loop got unmined transaction with bad mutator set data, discarding transaction");
×
806
                        return Ok(());
×
807
                    }
×
808

×
809
                    // Insert into mempool
×
810
                    global_state_mut
×
811
                        .mempool_insert(
×
812
                            pt2m_transaction.transaction.to_owned(),
×
813
                            TransactionOrigin::Foreign,
×
814
                        )
×
815
                        .await;
×
816
                }
817

818
                // send notification to peers
819
                let transaction_notification: TransactionNotification =
×
820
                    (&pt2m_transaction.transaction).try_into()?;
×
821
                self.main_to_peer_broadcast_tx
×
822
                    .send(MainToPeerTask::TransactionNotification(
×
823
                        transaction_notification,
×
824
                    ))?;
×
825
            }
826
            PeerTaskToMain::BlockProposal(block) => {
×
827
                log_slow_scope!(fn_name!() + "::PeerTaskToMain::BlockProposal");
×
828

×
829
                debug!("main loop received block proposal from peer loop");
×
830

831
                // Due to race-conditions, we need to verify that this
832
                // block proposal is still the immediate child of tip. If it is,
833
                // and it has a higher guesser fee than what we're currently
834
                // working on, then we switch to this, and notify the miner to
835
                // mine on this new block. We don't need to verify the block's
836
                // validity, since that was done in peer loop.
837
                // To ensure atomicity, a write-lock must be held over global
838
                // state while we check if this proposal is favorable.
839
                {
840
                    info!("Received new favorable block proposal for mining operation.");
×
841
                    let mut global_state_mut = self.global_state_lock.lock_guard_mut().await;
×
842
                    let verdict = global_state_mut.favor_incoming_block_proposal(
×
843
                        block.header().height,
×
844
                        block.total_guesser_reward(),
×
845
                    );
×
846
                    if let Err(reject_reason) = verdict {
×
847
                        warn!("main loop got unfavorable block proposal. Reason: {reject_reason}");
×
848
                        return Ok(());
×
849
                    }
×
850

×
851
                    global_state_mut.mining_state.block_proposal =
×
852
                        BlockProposal::foreign_proposal(*block.clone());
×
853
                }
×
854

×
855
                // Notify all peers of the block proposal we just accepted
×
856
                self.main_to_peer_broadcast_tx
×
857
                    .send(MainToPeerTask::BlockProposalNotification((&*block).into()))?;
×
858

859
                self.main_to_miner_tx.send(MainToMiner::NewBlockProposal);
×
860
            }
861
            PeerTaskToMain::DisconnectFromLongestLivedPeer => {
862
                let global_state = self.global_state_lock.lock_guard().await;
1✔
863

864
                // get all peers
865
                let all_peers = global_state.net.peer_map.iter();
1✔
866

1✔
867
                // filter out CLI peers
1✔
868
                let disconnect_candidates =
1✔
869
                    all_peers.filter(|p| !global_state.cli_peers().contains(p.0));
5✔
870

1✔
871
                // find the one with the oldest connection
1✔
872
                let longest_lived_peer = disconnect_candidates.min_by(
1✔
873
                    |(_socket_address_left, peer_info_left),
1✔
874
                     (_socket_address_right, peer_info_right)| {
4✔
875
                        peer_info_left
4✔
876
                            .connection_established()
4✔
877
                            .cmp(&peer_info_right.connection_established())
4✔
878
                    },
4✔
879
                );
1✔
880

881
                // tell to disconnect
882
                if let Some((peer_socket, _peer_info)) = longest_lived_peer {
1✔
883
                    self.main_to_peer_broadcast_tx
1✔
884
                        .send(MainToPeerTask::Disconnect(peer_socket.to_owned()))?;
1✔
885
                }
×
886
            }
887
        }
888

889
        Ok(())
1✔
890
    }
1✔
891

892
    /// If necessary, disconnect from peers.
893
    ///
894
    /// While a reasonable effort is made to never have more connections than
895
    /// [`max_num_peers`](crate::config_models::cli_args::Args::max_num_peers),
896
    /// this is not guaranteed. For example, bootstrap nodes temporarily allow a
897
    /// surplus of incoming connections to provide their service more reliably.
898
    ///
899
    /// Never disconnects peers listed as CLI arguments.
900
    ///
901
    /// Locking:
902
    ///   * acquires `global_state_lock` for read
903
    async fn prune_peers(&self) -> Result<()> {
2✔
904
        // fetch all relevant info from global state; don't hold the lock
2✔
905
        let cli_args = self.global_state_lock.cli();
2✔
906
        let connected_peers = self
2✔
907
            .global_state_lock
2✔
908
            .lock_guard()
2✔
909
            .await
2✔
910
            .net
911
            .peer_map
912
            .values()
2✔
913
            .cloned()
2✔
914
            .collect_vec();
2✔
915

2✔
916
        let num_peers = connected_peers.len();
2✔
917
        let max_num_peers = cli_args.max_num_peers;
2✔
918
        if num_peers <= max_num_peers {
2✔
919
            debug!("No need to prune any peer connections.");
1✔
920
            return Ok(());
1✔
921
        }
1✔
922
        warn!("Connected to {num_peers} peers, which exceeds the maximum ({max_num_peers}).");
1✔
923

924
        // If all connections are outbound, it's OK to exceed the max.
925
        if connected_peers.iter().all(|p| p.connection_is_outbound()) {
4✔
926
            warn!("Not disconnecting from any peer because all connections are outbound.");
×
927
            return Ok(());
×
928
        }
1✔
929

1✔
930
        let num_peers_to_disconnect = num_peers - max_num_peers;
1✔
931
        let peers_to_disconnect = connected_peers
1✔
932
            .into_iter()
1✔
933
            .filter(|peer| !cli_args.peers.contains(&peer.connected_address()))
14✔
934
            .choose_multiple(&mut rand::rng(), num_peers_to_disconnect);
1✔
935
        match peers_to_disconnect.len() {
1✔
936
            0 => warn!("Not disconnecting from any peer because of manual override."),
×
937
            i => info!("Disconnecting from {i} peers."),
1✔
938
        }
939
        for peer in peers_to_disconnect {
5✔
940
            self.main_to_peer_broadcast_tx
4✔
941
                .send(MainToPeerTask::Disconnect(peer.connected_address()))?;
4✔
942
        }
943

944
        Ok(())
1✔
945
    }
2✔
946

947
    /// If necessary, reconnect to the peers listed as CLI arguments.
948
    ///
949
    /// Locking:
950
    ///   * acquires `global_state_lock` for read
951
    async fn reconnect(&self, main_loop_state: &mut MutableMainLoopState) -> Result<()> {
×
952
        let connected_peers = self
×
953
            .global_state_lock
×
954
            .lock_guard()
×
955
            .await
×
956
            .net
957
            .peer_map
958
            .keys()
×
959
            .copied()
×
960
            .collect_vec();
×
961
        let peers_with_lost_connection = self
×
962
            .global_state_lock
×
963
            .cli()
×
964
            .peers
×
965
            .iter()
×
966
            .filter(|peer| !connected_peers.contains(peer));
×
967

×
968
        // If no connection was lost, there's nothing to do.
×
969
        if peers_with_lost_connection.clone().count() == 0 {
×
970
            return Ok(());
×
971
        }
×
972

973
        // Else, try to reconnect.
974
        let own_handshake_data = self
×
975
            .global_state_lock
×
976
            .lock_guard()
×
977
            .await
×
978
            .get_own_handshakedata();
×
979
        for &peer_with_lost_connection in peers_with_lost_connection {
×
980
            // Disallow reconnection if peer is in bad standing
981
            let peer_standing = self
×
982
                .global_state_lock
×
983
                .lock_guard()
×
984
                .await
×
985
                .net
986
                .get_peer_standing_from_database(peer_with_lost_connection.ip())
×
987
                .await;
×
988
            if peer_standing.is_some_and(|standing| standing.is_bad()) {
×
989
                info!("Not reconnecting to peer in bad standing: {peer_with_lost_connection}");
×
990
                continue;
×
991
            }
×
992

×
993
            info!("Attempting to reconnect to peer: {peer_with_lost_connection}");
×
994
            let global_state_lock = self.global_state_lock.clone();
×
995
            let main_to_peer_broadcast_rx = self.main_to_peer_broadcast_tx.subscribe();
×
996
            let peer_task_to_main_tx = self.peer_task_to_main_tx.to_owned();
×
997
            let own_handshake_data = own_handshake_data.clone();
×
998
            let outgoing_connection_task = tokio::task::Builder::new()
×
999
                .name("call_peer_wrapper_1")
×
1000
                .spawn(async move {
×
1001
                    call_peer(
×
1002
                        peer_with_lost_connection,
×
1003
                        global_state_lock,
×
1004
                        main_to_peer_broadcast_rx,
×
1005
                        peer_task_to_main_tx,
×
1006
                        own_handshake_data,
×
1007
                        1, // All CLI-specified peers have distance 1
×
1008
                    )
×
1009
                    .await;
×
1010
                })?;
×
1011
            main_loop_state.task_handles.push(outgoing_connection_task);
×
1012
            main_loop_state.task_handles.retain(|th| !th.is_finished());
×
1013
        }
×
1014

1015
        Ok(())
×
1016
    }
×
1017

1018
    /// Perform peer discovery.
1019
    ///
1020
    /// Peer discovery involves finding potential peers from connected peers
1021
    /// and attempts to establish a connection with one of them.
1022
    ///
1023
    /// Locking:
1024
    ///   * acquires `global_state_lock` for read
1025
    async fn discover_peers(&self, main_loop_state: &mut MutableMainLoopState) -> Result<()> {
2✔
1026
        // fetch all relevant info from global state, then release the lock
2✔
1027
        let cli_args = self.global_state_lock.cli();
2✔
1028
        let global_state = self.global_state_lock.lock_guard().await;
2✔
1029
        let connected_peers = global_state.net.peer_map.values().cloned().collect_vec();
2✔
1030
        let own_instance_id = global_state.net.instance_id;
2✔
1031
        let own_handshake_data = global_state.get_own_handshakedata();
2✔
1032
        drop(global_state);
2✔
1033

2✔
1034
        let num_peers = connected_peers.len();
2✔
1035
        let max_num_peers = cli_args.max_num_peers;
2✔
1036

2✔
1037
        // Don't make an outgoing connection if
2✔
1038
        // - the peer limit is reached (or exceeded), or
2✔
1039
        // - the peer limit is _almost_ reached; reserve the last slot for an
2✔
1040
        //   incoming connection.
2✔
1041
        if num_peers >= max_num_peers || num_peers > 2 && num_peers - 1 == max_num_peers {
2✔
1042
            info!("Connected to {num_peers} peers. The configured max is {max_num_peers} peers.");
1✔
1043
            info!("Skipping peer discovery.");
1✔
1044
            return Ok(());
1✔
1045
        }
1✔
1046

1✔
1047
        info!("Performing peer discovery");
1✔
1048

1049
        // Ask all peers for their peer lists. This will eventually – once the
1050
        // responses have come in – update the list of potential peers.
1051
        self.main_to_peer_broadcast_tx
1✔
1052
            .send(MainToPeerTask::MakePeerDiscoveryRequest)?;
1✔
1053

1054
        // Get a peer candidate from the list of potential peers. Generally,
1055
        // the peer lists requested in the previous step will not have come in
1056
        // yet. Therefore, the new candidate is selected based on somewhat
1057
        // (but not overly) old information.
1058
        let Some((peer_candidate, candidate_distance)) = main_loop_state
1✔
1059
            .potential_peers
1✔
1060
            .get_candidate(&connected_peers, own_instance_id)
1✔
1061
        else {
1062
            info!("Found no peer candidate to connect to. Not making new connection.");
1✔
1063
            return Ok(());
1✔
1064
        };
1065

1066
        // Try to connect to the selected candidate.
1067
        info!("Connecting to peer {peer_candidate} with distance {candidate_distance}");
×
1068
        let global_state_lock = self.global_state_lock.clone();
×
1069
        let main_to_peer_broadcast_rx = self.main_to_peer_broadcast_tx.subscribe();
×
1070
        let peer_task_to_main_tx = self.peer_task_to_main_tx.to_owned();
×
1071
        let outgoing_connection_task = tokio::task::Builder::new()
×
1072
            .name("call_peer_wrapper_2")
×
1073
            .spawn(async move {
×
1074
                call_peer(
×
1075
                    peer_candidate,
×
1076
                    global_state_lock,
×
1077
                    main_to_peer_broadcast_rx,
×
1078
                    peer_task_to_main_tx,
×
1079
                    own_handshake_data,
×
1080
                    candidate_distance,
×
1081
                )
×
1082
                .await;
×
1083
            })?;
×
1084
        main_loop_state.task_handles.push(outgoing_connection_task);
×
1085
        main_loop_state.task_handles.retain(|th| !th.is_finished());
×
1086

×
1087
        // Immediately request the new peer's peer list. This allows
×
1088
        // incorporating the new peer's peers into the list of potential peers,
×
1089
        // to be used in the next round of peer discovery.
×
1090
        self.main_to_peer_broadcast_tx
×
1091
            .send(MainToPeerTask::MakeSpecificPeerDiscoveryRequest(
×
1092
                peer_candidate,
×
1093
            ))?;
×
1094

1095
        Ok(())
×
1096
    }
2✔
1097

1098
    /// Return a list of block heights for a block-batch request.
1099
    ///
1100
    /// Returns an ordered list of the heights of *most preferred block*
1101
    /// to build on, where current tip is always the most preferred block.
1102
    ///
1103
    /// Uses a factor to ensure that the peer will always have something to
1104
    /// build on top of by providing potential starting points all the way
1105
    /// back to genesis.
1106
    fn batch_request_uca_candidate_heights(own_tip_height: BlockHeight) -> Vec<BlockHeight> {
258✔
1107
        const FACTOR: f64 = 1.07f64;
1108

1109
        let mut look_behind = 0;
258✔
1110
        let mut ret = vec![];
258✔
1111

1112
        // A factor of 1.07 can look back ~1m blocks in 200 digests.
1113
        while ret.len() < MAX_NUM_DIGESTS_IN_BATCH_REQUEST - 1 {
51,374✔
1114
            let height = match own_tip_height.checked_sub(look_behind) {
51,118✔
1115
                None => break,
1✔
1116
                Some(height) if height.is_genesis() => break,
51,117✔
1117
                Some(height) => height,
51,116✔
1118
            };
51,116✔
1119

51,116✔
1120
            ret.push(height);
51,116✔
1121
            look_behind = ((look_behind as f64 + 1.0) * FACTOR).floor() as u64;
51,116✔
1122
        }
1123

1124
        ret.push(BlockHeight::genesis());
258✔
1125

258✔
1126
        ret
258✔
1127
    }
258✔
1128

1129
    /// Logic for requesting the batch-download of blocks from peers
1130
    ///
1131
    /// Locking:
1132
    ///   * acquires `global_state_lock` for read
1133
    async fn block_sync(&mut self, main_loop_state: &mut MutableMainLoopState) -> Result<()> {
3✔
1134
        let global_state = self.global_state_lock.lock_guard().await;
3✔
1135

1136
        // Check if we are in sync mode
1137
        let Some(anchor) = &global_state.net.sync_anchor else {
3✔
1138
            return Ok(());
1✔
1139
        };
1140

1141
        info!("Running sync");
2✔
1142

1143
        let (own_tip_hash, own_tip_height, own_cumulative_pow) = (
2✔
1144
            global_state.chain.light_state().hash(),
2✔
1145
            global_state.chain.light_state().kernel.header.height,
2✔
1146
            global_state
2✔
1147
                .chain
2✔
1148
                .light_state()
2✔
1149
                .kernel
2✔
1150
                .header
2✔
1151
                .cumulative_proof_of_work,
2✔
1152
        );
2✔
1153

2✔
1154
        // Check if sync mode has timed out entirely, in which case it should
2✔
1155
        // be abandoned.
2✔
1156
        let anchor = anchor.to_owned();
2✔
1157
        if self.now().duration_since(anchor.updated)? > GLOBAL_SYNCHRONIZATION_TIMEOUT {
2✔
1158
            warn!("Sync mode has timed out. Abandoning sync mode.");
1✔
1159

1160
            // Abandon attempt, and punish all peers claiming to serve these
1161
            // blocks.
1162
            drop(global_state);
1✔
1163
            self.global_state_lock
1✔
1164
                .lock_guard_mut()
1✔
1165
                .await
1✔
1166
                .net
1✔
1167
                .sync_anchor = None;
1✔
1168

1169
            let peers_to_punish = main_loop_state
1✔
1170
                .sync_state
1✔
1171
                .get_potential_peers_for_sync_request(own_cumulative_pow);
1✔
1172

1173
            for peer in peers_to_punish {
2✔
1174
                self.main_to_peer_broadcast_tx
1✔
1175
                    .send(MainToPeerTask::PeerSynchronizationTimeout(peer))?;
1✔
1176
            }
1177

1178
            return Ok(());
1✔
1179
        }
1✔
1180

1✔
1181
        let (peer_to_sanction, try_new_request): (Option<SocketAddr>, bool) = main_loop_state
1✔
1182
            .sync_state
1✔
1183
            .get_status_of_last_request(own_tip_height, self.now());
1✔
1184

1185
        // Sanction peer if they failed to respond
1186
        if let Some(peer) = peer_to_sanction {
1✔
1187
            self.main_to_peer_broadcast_tx
×
1188
                .send(MainToPeerTask::PeerSynchronizationTimeout(peer))?;
×
1189
        }
1✔
1190

1191
        if !try_new_request {
1✔
1192
            info!("Waiting for last sync to complete.");
×
1193
            return Ok(());
×
1194
        }
1✔
1195

1✔
1196
        // Create the next request from the reported
1✔
1197
        info!("Creating new sync request");
1✔
1198

1199
        // Pick a random peer that has reported to have relevant blocks
1200
        let candidate_peers = main_loop_state
1✔
1201
            .sync_state
1✔
1202
            .get_potential_peers_for_sync_request(own_cumulative_pow);
1✔
1203
        let mut rng = rand::rng();
1✔
1204
        let chosen_peer = candidate_peers.choose(&mut rng);
1✔
1205
        assert!(
1✔
1206
            chosen_peer.is_some(),
1✔
1207
            "A synchronization candidate must be available for a request. \
×
1208
            Otherwise, the data structure is in an invalid state and syncing should not be active"
×
1209
        );
1210

1211
        let ordered_preferred_block_digests = match anchor.champion {
1✔
1212
            Some((_height, digest)) => vec![digest],
×
1213
            None => {
1214
                // Find candidate-UCA digests based on a sparse distribution of
1215
                // block heights skewed towards own tip height
1216
                let request_heights = Self::batch_request_uca_candidate_heights(own_tip_height);
1✔
1217
                let mut ordered_preferred_block_digests = vec![];
1✔
1218
                for height in request_heights {
2✔
1219
                    let digest = global_state
1✔
1220
                        .chain
1✔
1221
                        .archival_state()
1✔
1222
                        .archival_block_mmr
1✔
1223
                        .ammr()
1✔
1224
                        .get_leaf_async(height.into())
1✔
1225
                        .await;
1✔
1226
                    ordered_preferred_block_digests.push(digest);
1✔
1227
                }
1228
                ordered_preferred_block_digests
1✔
1229
            }
1230
        };
1231

1232
        // Send message to the relevant peer loop to request the blocks
1233
        let chosen_peer = chosen_peer.unwrap();
1✔
1234
        info!(
1✔
1235
            "Sending block batch request to {}\nrequesting blocks descending from {}\n height {}",
×
1236
            chosen_peer, own_tip_hash, own_tip_height
1237
        );
1238
        self.main_to_peer_broadcast_tx
1✔
1239
            .send(MainToPeerTask::RequestBlockBatch(
1✔
1240
                MainToPeerTaskBatchBlockRequest {
1✔
1241
                    peer_addr_target: *chosen_peer,
1✔
1242
                    known_blocks: ordered_preferred_block_digests,
1✔
1243
                    anchor_mmr: anchor.block_mmr.clone(),
1✔
1244
                },
1✔
1245
            ))
1✔
1246
            .expect("Sending message to peers must succeed");
1✔
1247

1✔
1248
        // Record that this request was sent to the peer
1✔
1249
        let requested_block_height = own_tip_height.next();
1✔
1250
        main_loop_state
1✔
1251
            .sync_state
1✔
1252
            .record_request(requested_block_height, *chosen_peer, self.now());
1✔
1253

1✔
1254
        Ok(())
1✔
1255
    }
3✔
1256

1257
    /// Scheduled task for upgrading the proofs of transactions in the mempool.
1258
    ///
1259
    /// Will either perform a merge of two transactions supported with single
1260
    /// proofs, or will upgrade a transaction proof of the type
1261
    /// `ProofCollection` to `SingleProof`.
1262
    ///
1263
    /// All proving takes place in a spawned task such that it doesn't block
1264
    /// the main loop. The MutableMainLoopState gets the JoinHandle of the
1265
    /// spawned upgrade task such that its status can be expected.
1266
    async fn proof_upgrader(&mut self, main_loop_state: &mut MutableMainLoopState) -> Result<()> {
3✔
1267
        fn attempt_upgrade(
3✔
1268
            global_state: &GlobalState,
3✔
1269
            now: SystemTime,
3✔
1270
            tx_upgrade_interval: Option<Duration>,
3✔
1271
            main_loop_state: &MutableMainLoopState,
3✔
1272
        ) -> Result<bool> {
3✔
1273
            let duration_since_last_upgrade =
3✔
1274
                now.duration_since(global_state.net.last_tx_proof_upgrade_attempt)?;
3✔
1275
            let previous_upgrade_task_is_still_running = main_loop_state
3✔
1276
                .proof_upgrader_task
3✔
1277
                .as_ref()
3✔
1278
                .is_some_and(|x| !x.is_finished());
3✔
1279
            Ok(global_state.net.sync_anchor.is_none()
3✔
1280
                && global_state.proving_capability() == TxProvingCapability::SingleProof
3✔
1281
                && !previous_upgrade_task_is_still_running
3✔
1282
                && tx_upgrade_interval
3✔
1283
                    .is_some_and(|upgrade_interval| duration_since_last_upgrade > upgrade_interval))
3✔
1284
        }
3✔
1285

1286
        trace!("Running proof upgrader scheduled task");
3✔
1287

1288
        // Check if it's time to run the proof-upgrader, and if we're capable
1289
        // of upgrading a transaction proof.
1290
        let tx_upgrade_interval = self.global_state_lock.cli().tx_upgrade_interval();
3✔
1291
        let (upgrade_candidate, tx_origin) = {
1✔
1292
            let global_state = self.global_state_lock.lock_guard().await;
3✔
1293
            let now = self.now();
3✔
1294
            if !attempt_upgrade(&global_state, now, tx_upgrade_interval, main_loop_state)? {
3✔
1295
                trace!("Not attempting upgrade.");
2✔
1296
                return Ok(());
2✔
1297
            }
1✔
1298

1✔
1299
            debug!("Attempting to run transaction-proof-upgrade");
1✔
1300

1301
            // Find a candidate for proof upgrade
1302
            let Some((upgrade_candidate, tx_origin)) = get_upgrade_task_from_mempool(&global_state)
1✔
1303
            else {
1304
                debug!("Found no transaction-proof to upgrade");
×
1305
                return Ok(());
×
1306
            };
1307

1308
            (upgrade_candidate, tx_origin)
1✔
1309
        };
1✔
1310

1✔
1311
        info!(
1✔
1312
            "Attempting to upgrade transaction proofs of: {}",
×
1313
            upgrade_candidate.affected_txids().iter().join("; ")
×
1314
        );
1315

1316
        // Perform the upgrade, if we're not using the prover for anything else,
1317
        // like mining, or proving our own transaction. Running the prover takes
1318
        // a long time (minutes), so we spawn a task for this such that we do
1319
        // not block the main loop.
1320
        let vm_job_queue = self.global_state_lock.vm_job_queue().clone();
1✔
1321
        let perform_ms_update_if_needed =
1✔
1322
            self.global_state_lock.cli().proving_capability() == TxProvingCapability::SingleProof;
1✔
1323

1✔
1324
        let global_state_lock_clone = self.global_state_lock.clone();
1✔
1325
        let main_to_peer_broadcast_tx_clone = self.main_to_peer_broadcast_tx.clone();
1✔
1326
        let proof_upgrader_task =
1✔
1327
            tokio::task::Builder::new()
1✔
1328
                .name("proof_upgrader")
1✔
1329
                .spawn(async move {
1✔
1330
                    upgrade_candidate
1✔
1331
                        .handle_upgrade(
1✔
1332
                            &vm_job_queue,
1✔
1333
                            tx_origin,
1✔
1334
                            perform_ms_update_if_needed,
1✔
1335
                            global_state_lock_clone,
1✔
1336
                            main_to_peer_broadcast_tx_clone,
1✔
1337
                        )
1✔
1338
                        .await
1✔
1339
                })?;
1✔
1340

1341
        main_loop_state.proof_upgrader_task = Some(proof_upgrader_task);
1✔
1342

1✔
1343
        Ok(())
1✔
1344
    }
3✔
1345

1346
    /// Post-processing when new block has arrived. Spawn a task to update
1347
    /// transactions in the mempool. Only when the spawned task has completed,
1348
    /// should the miner continue.
1349
    fn spawn_mempool_txs_update_job(
1✔
1350
        &self,
1✔
1351
        main_loop_state: &mut MutableMainLoopState,
1✔
1352
        update_jobs: Vec<UpdateMutatorSetDataJob>,
1✔
1353
    ) {
1✔
1354
        // job completion of the spawned task is communicated through the
1✔
1355
        // `update_mempool_txs_handle` channel.
1✔
1356
        let vm_job_queue = self.global_state_lock.vm_job_queue().clone();
1✔
1357
        if let Some(handle) = main_loop_state.update_mempool_txs_handle.as_ref() {
1✔
1358
            handle.abort();
×
1359
        }
1✔
1360
        let (update_sender, update_receiver) =
1✔
1361
            mpsc::channel::<Vec<Transaction>>(TX_UPDATER_CHANNEL_CAPACITY);
1✔
1362

1✔
1363
        // note: if this task is cancelled, the job will continue
1✔
1364
        // because TritonVmJobOptions::cancel_job_rx is None.
1✔
1365
        // see how compose_task handles cancellation in mine_loop.
1✔
1366
        let job_options = self
1✔
1367
            .global_state_lock
1✔
1368
            .cli()
1✔
1369
            .proof_job_options(TritonVmJobPriority::Highest);
1✔
1370
        main_loop_state.update_mempool_txs_handle = Some(
1✔
1371
            tokio::task::Builder::new()
1✔
1372
                .name("mempool tx ms-updater")
1✔
1373
                .spawn(async move {
1✔
1374
                    Self::update_mempool_jobs(
×
1375
                        update_jobs,
×
1376
                        &vm_job_queue,
×
1377
                        update_sender,
×
1378
                        job_options,
×
1379
                    )
×
1380
                    .await
×
1381
                })
1✔
1382
                .unwrap(),
1✔
1383
        );
1✔
1384
        main_loop_state.update_mempool_receiver = update_receiver;
1✔
1385
    }
1✔
1386

1387
    pub(crate) async fn run(
×
1388
        &mut self,
×
1389
        mut peer_task_to_main_rx: mpsc::Receiver<PeerTaskToMain>,
×
1390
        mut miner_to_main_rx: mpsc::Receiver<MinerToMain>,
×
1391
        mut rpc_server_to_main_rx: mpsc::Receiver<RPCServerToMain>,
×
1392
        task_handles: Vec<JoinHandle<()>>,
×
1393
    ) -> Result<i32> {
×
1394
        // Handle incoming connections, messages from peer tasks, and messages from the mining task
×
1395
        let mut main_loop_state = MutableMainLoopState::new(task_handles);
×
1396

×
1397
        // Set up various timers.
×
1398
        //
×
1399
        // The `MissedTickBehavior::Delay` is appropriate for tasks that don't
×
1400
        // do anything meaningful if executed in quick succession. For example,
×
1401
        // pruning stale information immediately after pruning stale information
×
1402
        // is almost certainly a no-op.
×
1403
        // Similarly, tasks performing network operations (e.g., peer discovery)
×
1404
        // should probably not try to “catch up” if some ticks were missed.
×
NEW
1405

×
NEW
1406
        // Don't run peer discovery immediately at startup since outgoing
×
NEW
1407
        // connections started from lib.rs may not have finished yet.
×
NEW
1408
        let mut peer_discovery_interval = time::interval_at(
×
NEW
1409
            Instant::now() + PEER_DISCOVERY_INTERVAL,
×
NEW
1410
            PEER_DISCOVERY_INTERVAL,
×
NEW
1411
        );
×
1412
        peer_discovery_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
×
1413

×
1414
        let mut block_sync_interval = time::interval(SYNC_REQUEST_INTERVAL);
×
1415
        block_sync_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
×
1416

×
1417
        let mut mempool_cleanup_interval = time::interval(MEMPOOL_PRUNE_INTERVAL);
×
1418
        mempool_cleanup_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
×
1419

×
1420
        let mut utxo_notification_cleanup_interval = time::interval(EXPECTED_UTXOS_PRUNE_INTERVAL);
×
1421
        utxo_notification_cleanup_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
×
1422

×
1423
        let mut mp_resync_interval = time::interval(MP_RESYNC_INTERVAL);
×
1424
        mp_resync_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
×
1425

×
1426
        let mut tx_proof_upgrade_interval = time::interval(TRANSACTION_UPGRADE_CHECK_INTERVAL);
×
1427
        tx_proof_upgrade_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
×
1428

×
1429
        // Spawn tasks to monitor for SIGTERM, SIGINT, and SIGQUIT. These
×
1430
        // signals are only used on Unix systems.
×
1431
        let (tx_term, mut rx_term) = mpsc::channel::<()>(2);
×
1432
        let (tx_int, mut rx_int) = mpsc::channel::<()>(2);
×
1433
        let (tx_quit, mut rx_quit) = mpsc::channel::<()>(2);
×
1434
        #[cfg(unix)]
1435
        {
×
1436
            use tokio::signal::unix::signal;
×
1437
            use tokio::signal::unix::SignalKind;
×
1438

1439
            // Monitor for SIGTERM
1440
            let mut sigterm = signal(SignalKind::terminate())?;
×
1441
            tokio::task::Builder::new()
×
1442
                .name("sigterm_handler")
×
1443
                .spawn(async move {
×
1444
                    if sigterm.recv().await.is_some() {
×
1445
                        info!("Received SIGTERM");
×
1446
                        tx_term.send(()).await.unwrap();
×
1447
                    }
×
1448
                })?;
×
1449

1450
            // Monitor for SIGINT
1451
            let mut sigint = signal(SignalKind::interrupt())?;
×
1452
            tokio::task::Builder::new()
×
1453
                .name("sigint_handler")
×
1454
                .spawn(async move {
×
1455
                    if sigint.recv().await.is_some() {
×
1456
                        info!("Received SIGINT");
×
1457
                        tx_int.send(()).await.unwrap();
×
1458
                    }
×
1459
                })?;
×
1460

1461
            // Monitor for SIGQUIT
1462
            let mut sigquit = signal(SignalKind::quit())?;
×
1463
            tokio::task::Builder::new()
×
1464
                .name("sigquit_handler")
×
1465
                .spawn(async move {
×
1466
                    if sigquit.recv().await.is_some() {
×
1467
                        info!("Received SIGQUIT");
×
1468
                        tx_quit.send(()).await.unwrap();
×
1469
                    }
×
1470
                })?;
×
1471
        }
1472

1473
        #[cfg(not(unix))]
1474
        drop((tx_term, tx_int, tx_quit));
1475

1476
        let exit_code: i32 = loop {
×
1477
            select! {
×
1478
                Ok(()) = signal::ctrl_c() => {
×
1479
                    info!("Detected Ctrl+c signal.");
×
1480
                    break SUCCESS_EXIT_CODE;
×
1481
                }
1482

1483
                // Monitor for SIGTERM, SIGINT, and SIGQUIT.
1484
                Some(_) = rx_term.recv() => {
×
1485
                    info!("Detected SIGTERM signal.");
×
1486
                    break SUCCESS_EXIT_CODE;
×
1487
                }
1488
                Some(_) = rx_int.recv() => {
×
1489
                    info!("Detected SIGINT signal.");
×
1490
                    break SUCCESS_EXIT_CODE;
×
1491
                }
1492
                Some(_) = rx_quit.recv() => {
×
1493
                    info!("Detected SIGQUIT signal.");
×
1494
                    break SUCCESS_EXIT_CODE;
×
1495
                }
1496

1497
                // Handle incoming connections from peer
1498
                Ok((stream, peer_address)) = self.incoming_peer_listener.accept() => {
×
1499
                    // Return early if no incoming connections are accepted. Do
1500
                    // not send application-handshake.
1501
                    if self.global_state_lock.cli().disallow_all_incoming_peer_connections() {
×
1502
                        warn!("Got incoming connection despite not accepting any. Ignoring");
×
1503
                        continue;
×
1504
                    }
×
1505

1506
                    let state = self.global_state_lock.lock_guard().await;
×
1507
                    let main_to_peer_broadcast_rx_clone: broadcast::Receiver<MainToPeerTask> = self.main_to_peer_broadcast_tx.subscribe();
×
1508
                    let peer_task_to_main_tx_clone: mpsc::Sender<PeerTaskToMain> = self.peer_task_to_main_tx.clone();
×
1509
                    let own_handshake_data: HandshakeData = state.get_own_handshakedata();
×
1510
                    let global_state_lock = self.global_state_lock.clone(); // bump arc refcount.
×
1511
                    let incoming_peer_task_handle = tokio::task::Builder::new()
×
1512
                        .name("answer_peer_wrapper")
×
1513
                        .spawn(async move {
×
1514
                        match answer_peer(
×
1515
                            stream,
×
1516
                            global_state_lock,
×
1517
                            peer_address,
×
1518
                            main_to_peer_broadcast_rx_clone,
×
1519
                            peer_task_to_main_tx_clone,
×
1520
                            own_handshake_data,
×
1521
                        ).await {
×
1522
                            Ok(()) => (),
×
1523
                            Err(err) => error!("Got error: {:?}", err),
×
1524
                        }
1525
                    })?;
×
1526
                    main_loop_state.task_handles.push(incoming_peer_task_handle);
×
1527
                    main_loop_state.task_handles.retain(|th| !th.is_finished());
×
1528
                }
×
1529

1530
                // Handle messages from peer tasks
1531
                Some(msg) = peer_task_to_main_rx.recv() => {
×
1532
                    debug!("Received message sent to main task.");
×
1533
                    self.handle_peer_task_message(
×
1534
                        msg,
×
1535
                        &mut main_loop_state,
×
1536
                    )
×
1537
                    .await?
×
1538
                }
1539

1540
                // Handle messages from miner task
1541
                Some(main_message) = miner_to_main_rx.recv() => {
×
1542
                    let exit_code = self.handle_miner_task_message(main_message, &mut main_loop_state).await?;
×
1543

1544
                    if let Some(exit_code) = exit_code {
×
1545
                        break exit_code;
×
1546
                    }
×
1547

1548
                }
1549

1550
                // Handle the completion of mempool tx-update jobs after new block.
1551
                Some(ms_updated_transactions) = main_loop_state.update_mempool_receiver.recv() => {
×
1552
                    self.handle_updated_mempool_txs(ms_updated_transactions).await;
×
1553
                }
1554

1555
                // Handle messages from rpc server task
1556
                Some(rpc_server_message) = rpc_server_to_main_rx.recv() => {
×
1557
                    let shutdown_after_execution = self.handle_rpc_server_message(rpc_server_message.clone(), &mut main_loop_state).await?;
×
1558
                    if shutdown_after_execution {
×
1559
                        break SUCCESS_EXIT_CODE
×
1560
                    }
×
1561
                }
1562

1563
                // Handle peer discovery
1564
                _ = peer_discovery_interval.tick() => {
×
1565
                    log_slow_scope!(fn_name!() + "::select::peer_discovery_interval");
×
1566

×
1567
                    // Check number of peers we are connected to and connect to
×
1568
                    // more peers if needed.
×
1569
                    debug!("Timer: peer discovery job");
×
1570
                    self.prune_peers().await?;
×
1571
                    self.reconnect(&mut main_loop_state).await?;
×
1572
                    self.discover_peers(&mut main_loop_state).await?;
×
1573
                }
1574

1575
                // Handle synchronization (i.e. batch-downloading of blocks)
1576
                _ = block_sync_interval.tick() => {
×
1577
                    log_slow_scope!(fn_name!() + "::select::block_sync_interval");
×
1578

×
1579
                    trace!("Timer: block-synchronization job");
×
1580
                    self.block_sync(&mut main_loop_state).await?;
×
1581
                }
1582

1583
                // Clean up mempool: remove stale / too old transactions
1584
                _ = mempool_cleanup_interval.tick() => {
×
1585
                    log_slow_scope!(fn_name!() + "::select::mempool_cleanup_interval");
×
1586

×
1587
                    debug!("Timer: mempool-cleaner job");
×
1588
                    self
×
1589
                        .global_state_lock
×
1590
                        .lock_guard_mut()
×
1591
                        .await
×
1592
                        .mempool_prune_stale_transactions()
×
1593
                        .await;
×
1594
                }
1595

1596
                // Clean up incoming UTXO notifications: remove stale / too old
1597
                // UTXO notifications from pool
1598
                _ = utxo_notification_cleanup_interval.tick() => {
×
1599
                    log_slow_scope!(fn_name!() + "::select::utxo_notification_cleanup_interval");
×
1600

×
1601
                    debug!("Timer: UTXO notification pool cleanup job");
×
1602

1603
                    // Danger: possible loss of funds.
1604
                    //
1605
                    // See description of prune_stale_expected_utxos().
1606
                    //
1607
                    // This call is disabled until such time as a thorough
1608
                    // evaluation and perhaps reimplementation determines that
1609
                    // it can be called safely without possible loss of funds.
1610
                    // self.global_state_lock.lock_mut(|s| s.wallet_state.prune_stale_expected_utxos()).await;
1611
                }
1612

1613
                // Handle membership proof resynchronization
1614
                _ = mp_resync_interval.tick() => {
×
1615
                    log_slow_scope!(fn_name!() + "::select::mp_resync_interval");
×
1616

×
1617
                    debug!("Timer: Membership proof resync job");
×
1618
                    self.global_state_lock.resync_membership_proofs().await?;
×
1619
                }
1620

1621
                // run the proof upgrader
1622
                _ = tx_proof_upgrade_interval.tick() => {
×
1623
                    log_slow_scope!(fn_name!() + "::select::tx_proof_upgrade_interval");
×
1624

×
1625
                    trace!("Timer: tx-proof-upgrader");
×
1626
                    self.proof_upgrader(&mut main_loop_state).await?;
×
1627
                }
1628

1629
            }
1630
        };
1631

1632
        self.graceful_shutdown(main_loop_state.task_handles).await?;
×
1633
        info!("Shutdown completed.");
×
1634

1635
        Ok(exit_code)
×
1636
    }
×
1637

1638
    /// Handle messages from the RPC server. Returns `true` iff the client should shut down
1639
    /// after handling this message.
1640
    async fn handle_rpc_server_message(
×
1641
        &mut self,
×
1642
        msg: RPCServerToMain,
×
1643
        main_loop_state: &mut MutableMainLoopState,
×
1644
    ) -> Result<bool> {
×
1645
        match msg {
×
1646
            RPCServerToMain::BroadcastTx(transaction) => {
×
1647
                debug!(
×
1648
                    "`main` received following transaction from RPC Server. {} inputs, {} outputs. Synced to mutator set hash: {}",
×
1649
                    transaction.kernel.inputs.len(),
×
1650
                    transaction.kernel.outputs.len(),
×
1651
                    transaction.kernel.mutator_set_hash
×
1652
                );
1653

1654
                // insert transaction into mempool
1655
                self.global_state_lock
×
1656
                    .lock_guard_mut()
×
1657
                    .await
×
1658
                    .mempool_insert(*transaction.clone(), TransactionOrigin::Own)
×
1659
                    .await;
×
1660

1661
                // Is this a transaction we can share with peers? If so, share
1662
                // it immediately.
1663
                if let Ok(notification) = transaction.as_ref().try_into() {
×
1664
                    self.main_to_peer_broadcast_tx
×
1665
                        .send(MainToPeerTask::TransactionNotification(notification))?;
×
1666
                } else {
1667
                    // Otherwise, upgrade its proof quality, and share it by
1668
                    // spinning up the proof upgrader.
1669
                    let TransactionProof::Witness(primitive_witness) = transaction.proof else {
×
1670
                        panic!("Expected Primitive witness. Got: {:?}", transaction.proof);
×
1671
                    };
1672

1673
                    let vm_job_queue = self.global_state_lock.vm_job_queue().clone();
×
1674

×
1675
                    let proving_capability = self.global_state_lock.cli().proving_capability();
×
1676
                    let upgrade_job =
×
1677
                        UpgradeJob::from_primitive_witness(proving_capability, primitive_witness);
×
1678

×
1679
                    // note: handle_upgrade() hands off proving to the
×
1680
                    //       triton-vm job queue and waits for job completion.
×
1681
                    // note: handle_upgrade() broadcasts to peers on success.
×
1682

×
1683
                    let global_state_lock_clone = self.global_state_lock.clone();
×
1684
                    let main_to_peer_broadcast_tx_clone = self.main_to_peer_broadcast_tx.clone();
×
1685
                    let _proof_upgrader_task = tokio::task::Builder::new()
×
1686
                        .name("proof_upgrader")
×
1687
                        .spawn(async move {
×
1688
                        upgrade_job
×
1689
                            .handle_upgrade(
×
1690
                                &vm_job_queue,
×
1691
                                TransactionOrigin::Own,
×
1692
                                true,
×
1693
                                global_state_lock_clone,
×
1694
                                main_to_peer_broadcast_tx_clone,
×
1695
                            )
×
1696
                            .await
×
1697
                    })?;
×
1698

1699
                    // main_loop_state.proof_upgrader_task = Some(proof_upgrader_task);
1700
                    // If transaction could not be shared immediately because
1701
                    // it contains secret data, upgrade its proof-type.
1702
                }
1703

1704
                // do not shut down
1705
                Ok(false)
×
1706
            }
1707
            RPCServerToMain::BroadcastMempoolTransactions => {
1708
                info!("Broadcasting transaction notifications for all shareable transactions in mempool");
×
1709
                let state = self.global_state_lock.lock_guard().await;
×
1710
                let txs = state.mempool.get_sorted_iter().collect_vec();
×
1711
                for (txid, _) in txs {
×
1712
                    // Since a read-lock is held over global state, the
1713
                    // transaction must exist in the mempool.
1714
                    let tx = state
×
1715
                        .mempool
×
1716
                        .get(txid)
×
1717
                        .expect("Transaction from iter must exist in mempool");
×
1718
                    let notification = TransactionNotification::try_from(tx);
×
1719
                    match notification {
×
1720
                        Ok(notification) => {
×
1721
                            self.main_to_peer_broadcast_tx
×
1722
                                .send(MainToPeerTask::TransactionNotification(notification))?;
×
1723
                        }
1724
                        Err(error) => {
×
1725
                            warn!("{error}");
×
1726
                        }
1727
                    };
1728
                }
1729
                Ok(false)
×
1730
            }
1731
            RPCServerToMain::ProofOfWorkSolution(new_block) => {
×
1732
                info!("Handling PoW solution from RPC call");
×
1733

1734
                self.handle_self_guessed_block(main_loop_state, new_block)
×
1735
                    .await?;
×
1736
                Ok(false)
×
1737
            }
1738
            RPCServerToMain::PauseMiner => {
1739
                info!("Received RPC request to stop miner");
×
1740

1741
                self.main_to_miner_tx.send(MainToMiner::StopMining);
×
1742
                Ok(false)
×
1743
            }
1744
            RPCServerToMain::RestartMiner => {
1745
                info!("Received RPC request to start miner");
×
1746
                self.main_to_miner_tx.send(MainToMiner::StartMining);
×
1747
                Ok(false)
×
1748
            }
1749
            RPCServerToMain::Shutdown => {
1750
                info!("Received RPC shutdown request.");
×
1751

1752
                // shut down
1753
                Ok(true)
×
1754
            }
1755
        }
1756
    }
×
1757

1758
    async fn graceful_shutdown(&mut self, task_handles: Vec<JoinHandle<()>>) -> Result<()> {
×
1759
        info!("Shutdown initiated.");
×
1760

1761
        // Stop mining
1762
        self.main_to_miner_tx.send(MainToMiner::Shutdown);
×
1763

×
1764
        // Send 'bye' message to all peers.
×
1765
        let _result = self
×
1766
            .main_to_peer_broadcast_tx
×
1767
            .send(MainToPeerTask::DisconnectAll());
×
1768
        debug!("sent bye");
×
1769

1770
        // Flush all databases
1771
        self.global_state_lock.flush_databases().await?;
×
1772

1773
        tokio::time::sleep(Duration::from_millis(50)).await;
×
1774

1775
        // Child processes should have finished by now. If not, abort them violently.
1776
        task_handles.iter().for_each(|jh| jh.abort());
×
1777

×
1778
        // wait for all to finish.
×
1779
        futures::future::join_all(task_handles).await;
×
1780

1781
        Ok(())
×
1782
    }
×
1783
}
1784

1785
#[cfg(test)]
1786
mod test {
1787
    use std::str::FromStr;
1788
    use std::time::UNIX_EPOCH;
1789

1790
    use tracing_test::traced_test;
1791

1792
    use super::*;
1793
    use crate::config_models::cli_args;
1794
    use crate::config_models::network::Network;
1795
    use crate::tests::shared::get_dummy_peer_incoming;
1796
    use crate::tests::shared::get_test_genesis_setup;
1797
    use crate::tests::shared::invalid_empty_block;
1798
    use crate::MINER_CHANNEL_CAPACITY;
1799

1800
    struct TestSetup {
1801
        peer_to_main_rx: mpsc::Receiver<PeerTaskToMain>,
1802
        miner_to_main_rx: mpsc::Receiver<MinerToMain>,
1803
        rpc_server_to_main_rx: mpsc::Receiver<RPCServerToMain>,
1804
        task_join_handles: Vec<JoinHandle<()>>,
1805
        main_loop_handler: MainLoopHandler,
1806
        main_to_peer_rx: broadcast::Receiver<MainToPeerTask>,
1807
    }
1808

1809
    async fn setup(num_init_peers_outgoing: u8, num_peers_incoming: u8) -> TestSetup {
8✔
1810
        const CHANNEL_CAPACITY_MINER_TO_MAIN: usize = 10;
1811

1812
        let network = Network::Main;
8✔
1813
        let (
1814
            main_to_peer_tx,
8✔
1815
            main_to_peer_rx,
8✔
1816
            peer_to_main_tx,
8✔
1817
            peer_to_main_rx,
8✔
1818
            mut state,
8✔
1819
            _own_handshake_data,
8✔
1820
        ) = get_test_genesis_setup(network, num_init_peers_outgoing, cli_args::Args::default())
8✔
1821
            .await
8✔
1822
            .unwrap();
8✔
1823
        assert!(
8✔
1824
            state
8✔
1825
                .lock_guard()
8✔
1826
                .await
8✔
1827
                .net
1828
                .peer_map
1829
                .iter()
8✔
1830
                .all(|(_addr, peer)| peer.connection_is_outbound()),
30✔
1831
            "Test assumption: All initial peers must represent outgoing connections."
×
1832
        );
1833

1834
        for i in 0..num_peers_incoming {
8✔
1835
            let peer_address = SocketAddr::from_str(&format!("255.254.253.{i}:8080")).unwrap();
5✔
1836
            state
5✔
1837
                .lock_guard_mut()
5✔
1838
                .await
5✔
1839
                .net
1840
                .peer_map
1841
                .insert(peer_address, get_dummy_peer_incoming(peer_address));
5✔
1842
        }
1843

1844
        let incoming_peer_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
8✔
1845

8✔
1846
        let (main_to_miner_tx, _main_to_miner_rx) =
8✔
1847
            mpsc::channel::<MainToMiner>(MINER_CHANNEL_CAPACITY);
8✔
1848
        let (_miner_to_main_tx, miner_to_main_rx) =
8✔
1849
            mpsc::channel::<MinerToMain>(CHANNEL_CAPACITY_MINER_TO_MAIN);
8✔
1850
        let (_rpc_server_to_main_tx, rpc_server_to_main_rx) =
8✔
1851
            mpsc::channel::<RPCServerToMain>(CHANNEL_CAPACITY_MINER_TO_MAIN);
8✔
1852

8✔
1853
        let main_loop_handler = MainLoopHandler::new(
8✔
1854
            incoming_peer_listener,
8✔
1855
            state,
8✔
1856
            main_to_peer_tx,
8✔
1857
            peer_to_main_tx,
8✔
1858
            main_to_miner_tx,
8✔
1859
        );
8✔
1860

8✔
1861
        let task_join_handles = vec![];
8✔
1862

8✔
1863
        TestSetup {
8✔
1864
            miner_to_main_rx,
8✔
1865
            peer_to_main_rx,
8✔
1866
            rpc_server_to_main_rx,
8✔
1867
            task_join_handles,
8✔
1868
            main_loop_handler,
8✔
1869
            main_to_peer_rx,
8✔
1870
        }
8✔
1871
    }
8✔
1872

1873
    #[tokio::test]
1874
    async fn handle_self_guessed_block_new_tip() {
1✔
1875
        // A new tip is registered by main_loop. Verify correct state update.
1✔
1876
        let test_setup = setup(1, 0).await;
1✔
1877
        let TestSetup {
1✔
1878
            task_join_handles,
1✔
1879
            mut main_loop_handler,
1✔
1880
            mut main_to_peer_rx,
1✔
1881
            ..
1✔
1882
        } = test_setup;
1✔
1883
        let network = main_loop_handler.global_state_lock.cli().network;
1✔
1884
        let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
1885

1✔
1886
        let block1 = invalid_empty_block(&Block::genesis(network));
1✔
1887

1✔
1888
        assert!(
1✔
1889
            main_loop_handler
1✔
1890
                .global_state_lock
1✔
1891
                .lock_guard()
1✔
1892
                .await
1✔
1893
                .chain
1✔
1894
                .light_state()
1✔
1895
                .header()
1✔
1896
                .height
1✔
1897
                .is_genesis(),
1✔
1898
            "Tip must be genesis prior to handling of new block"
1✔
1899
        );
1✔
1900

1✔
1901
        let block1 = Box::new(block1);
1✔
1902
        main_loop_handler
1✔
1903
            .handle_self_guessed_block(&mut mutable_main_loop_state, block1.clone())
1✔
1904
            .await
1✔
1905
            .unwrap();
1✔
1906
        let new_block_height: u64 = main_loop_handler
1✔
1907
            .global_state_lock
1✔
1908
            .lock_guard()
1✔
1909
            .await
1✔
1910
            .chain
1✔
1911
            .light_state()
1✔
1912
            .header()
1✔
1913
            .height
1✔
1914
            .into();
1✔
1915
        assert_eq!(
1✔
1916
            1u64, new_block_height,
1✔
1917
            "Tip height must be 1 after handling of new block"
1✔
1918
        );
1✔
1919
        let msg_to_peer_loops = main_to_peer_rx.recv().await.unwrap();
1✔
1920
        if let MainToPeerTask::Block(block_to_peers) = msg_to_peer_loops {
1✔
1921
            assert_eq!(
1✔
1922
                block1, block_to_peers,
1✔
1923
                "Peer loops must have received block 1"
1✔
1924
            );
1✔
1925
        } else {
1✔
1926
            panic!("Must have sent block notification to peer loops")
1✔
1927
        }
1✔
1928
    }
1✔
1929

1930
    mod sync_mode {
1931
        use tasm_lib::twenty_first::util_types::mmr::mmr_accumulator::MmrAccumulator;
1932
        use test_strategy::proptest;
1933

1934
        use super::*;
1935
        use crate::tests::shared::get_dummy_socket_address;
1936

1937
        #[proptest]
256✔
1938
        fn batch_request_heights_prop(#[strategy(0u64..100_000_000_000)] own_height: u64) {
1✔
1939
            batch_request_heights_sanity(own_height);
1940
        }
1941

1942
        #[test]
1943
        fn batch_request_heights_unit() {
1✔
1944
            let own_height = 1_000_000u64;
1✔
1945
            batch_request_heights_sanity(own_height);
1✔
1946
        }
1✔
1947

1948
        fn batch_request_heights_sanity(own_height: u64) {
257✔
1949
            let heights = MainLoopHandler::batch_request_uca_candidate_heights(own_height.into());
257✔
1950

257✔
1951
            let mut heights_rev = heights.clone();
257✔
1952
            heights_rev.reverse();
257✔
1953
            assert!(
257✔
1954
                heights_rev.is_sorted(),
257✔
1955
                "Heights must be sorted from high-to-low"
×
1956
            );
1957

1958
            heights_rev.dedup();
257✔
1959
            assert_eq!(heights_rev.len(), heights.len(), "duplicates");
257✔
1960

1961
            assert_eq!(heights[0], own_height.into(), "starts with own tip height");
257✔
1962
            assert!(
257✔
1963
                heights.last().unwrap().is_genesis(),
257✔
1964
                "ends with genesis block"
×
1965
            );
1966
        }
257✔
1967

1968
        #[tokio::test]
1969
        #[traced_test]
×
1970
        async fn sync_mode_abandoned_on_global_timeout() {
1✔
1971
            let num_outgoing_connections = 0;
1✔
1972
            let num_incoming_connections = 0;
1✔
1973
            let test_setup = setup(num_outgoing_connections, num_incoming_connections).await;
1✔
1974
            let TestSetup {
1975
                task_join_handles,
1✔
1976
                mut main_loop_handler,
1✔
1977
                ..
1✔
1978
            } = test_setup;
1✔
1979

1✔
1980
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
1981

1✔
1982
            main_loop_handler
1✔
1983
                .block_sync(&mut mutable_main_loop_state)
1✔
1984
                .await
1✔
1985
                .expect("Must return OK when no sync mode is set");
1✔
1986

1✔
1987
            // Mock that we are in a valid sync state
1✔
1988
            let claimed_max_height = 1_000u64.into();
1✔
1989
            let claimed_max_pow = ProofOfWork::new([100; 6]);
1✔
1990
            main_loop_handler
1✔
1991
                .global_state_lock
1✔
1992
                .lock_guard_mut()
1✔
1993
                .await
1✔
1994
                .net
1✔
1995
                .sync_anchor = Some(SyncAnchor::new(
1✔
1996
                claimed_max_pow,
1✔
1997
                MmrAccumulator::new_from_leafs(vec![]),
1✔
1998
            ));
1✔
1999
            mutable_main_loop_state.sync_state.peer_sync_states.insert(
1✔
2000
                get_dummy_socket_address(0),
1✔
2001
                PeerSynchronizationState::new(claimed_max_height, claimed_max_pow),
1✔
2002
            );
1✔
2003

2004
            let sync_start_time = main_loop_handler
1✔
2005
                .global_state_lock
1✔
2006
                .lock_guard()
1✔
2007
                .await
1✔
2008
                .net
2009
                .sync_anchor
2010
                .as_ref()
1✔
2011
                .unwrap()
1✔
2012
                .updated;
1✔
2013
            main_loop_handler
1✔
2014
                .block_sync(&mut mutable_main_loop_state)
1✔
2015
                .await
1✔
2016
                .expect("Must return OK when sync mode has not timed out yet");
1✔
2017
            assert!(
1✔
2018
                main_loop_handler
1✔
2019
                    .global_state_lock
1✔
2020
                    .lock_guard()
1✔
2021
                    .await
1✔
2022
                    .net
2023
                    .sync_anchor
2024
                    .is_some(),
1✔
2025
                "Sync mode must still be set before timeout has occurred"
×
2026
            );
2027

2028
            assert_eq!(
1✔
2029
                sync_start_time,
1✔
2030
                main_loop_handler
1✔
2031
                    .global_state_lock
1✔
2032
                    .lock_guard()
1✔
2033
                    .await
1✔
2034
                    .net
2035
                    .sync_anchor
2036
                    .as_ref()
1✔
2037
                    .unwrap()
1✔
2038
                    .updated,
2039
                "timestamp may not be updated without state change"
×
2040
            );
2041

2042
            // Mock that sync-mode has timed out
2043
            main_loop_handler = main_loop_handler.with_mocked_time(
1✔
2044
                SystemTime::now() + GLOBAL_SYNCHRONIZATION_TIMEOUT + Duration::from_secs(1),
1✔
2045
            );
1✔
2046

1✔
2047
            main_loop_handler
1✔
2048
                .block_sync(&mut mutable_main_loop_state)
1✔
2049
                .await
1✔
2050
                .expect("Must return OK when sync mode has timed out");
1✔
2051
            assert!(
1✔
2052
                main_loop_handler
1✔
2053
                    .global_state_lock
1✔
2054
                    .lock_guard()
1✔
2055
                    .await
1✔
2056
                    .net
1✔
2057
                    .sync_anchor
1✔
2058
                    .is_none(),
1✔
2059
                "Sync mode must be unset on timeout"
1✔
2060
            );
1✔
2061
        }
1✔
2062
    }
2063

2064
    mod proof_upgrader {
2065
        use super::*;
2066
        use crate::job_queue::triton_vm::TritonVmJobQueue;
2067
        use crate::models::blockchain::transaction::Transaction;
2068
        use crate::models::blockchain::transaction::TransactionProof;
2069
        use crate::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
2070
        use crate::models::peer::transfer_transaction::TransactionProofQuality;
2071
        use crate::models::proof_abstractions::timestamp::Timestamp;
2072
        use crate::models::state::wallet::utxo_notification::UtxoNotificationMedium;
2073

2074
        async fn tx_no_outputs(
1✔
2075
            global_state_lock: &GlobalStateLock,
1✔
2076
            tx_proof_type: TxProvingCapability,
1✔
2077
            fee: NativeCurrencyAmount,
1✔
2078
        ) -> Transaction {
1✔
2079
            let change_key = global_state_lock
1✔
2080
                .lock_guard()
1✔
2081
                .await
1✔
2082
                .wallet_state
2083
                .wallet_entropy
2084
                .nth_generation_spending_key_for_tests(0);
1✔
2085
            let in_seven_months = global_state_lock
1✔
2086
                .lock_guard()
1✔
2087
                .await
1✔
2088
                .chain
2089
                .light_state()
1✔
2090
                .header()
1✔
2091
                .timestamp
1✔
2092
                + Timestamp::months(7);
1✔
2093

2094
            let global_state = global_state_lock.lock_guard().await;
1✔
2095
            global_state
1✔
2096
                .create_transaction_with_prover_capability(
1✔
2097
                    vec![].into(),
1✔
2098
                    change_key.into(),
1✔
2099
                    UtxoNotificationMedium::OffChain,
1✔
2100
                    fee,
1✔
2101
                    in_seven_months,
1✔
2102
                    tx_proof_type,
1✔
2103
                    &TritonVmJobQueue::dummy(),
1✔
2104
                )
1✔
2105
                .await
1✔
2106
                .unwrap()
1✔
2107
                .0
1✔
2108
        }
1✔
2109

2110
        #[tokio::test]
2111
        #[traced_test]
×
2112
        async fn upgrade_proof_collection_to_single_proof_foreign_tx() {
1✔
2113
            let num_outgoing_connections = 0;
1✔
2114
            let num_incoming_connections = 0;
1✔
2115
            let test_setup = setup(num_outgoing_connections, num_incoming_connections).await;
1✔
2116
            let TestSetup {
2117
                peer_to_main_rx,
1✔
2118
                miner_to_main_rx,
1✔
2119
                rpc_server_to_main_rx,
1✔
2120
                task_join_handles,
1✔
2121
                mut main_loop_handler,
1✔
2122
                mut main_to_peer_rx,
1✔
2123
            } = test_setup;
1✔
2124

1✔
2125
            // Force instance to create SingleProofs, otherwise CI and other
1✔
2126
            // weak machines fail.
1✔
2127
            let mocked_cli = cli_args::Args {
1✔
2128
                tx_proving_capability: Some(TxProvingCapability::SingleProof),
1✔
2129
                tx_proof_upgrade_interval: 100, // seconds
1✔
2130
                ..Default::default()
1✔
2131
            };
1✔
2132

1✔
2133
            main_loop_handler
1✔
2134
                .global_state_lock
1✔
2135
                .set_cli(mocked_cli)
1✔
2136
                .await;
1✔
2137
            let mut main_loop_handler = main_loop_handler.with_mocked_time(SystemTime::now());
1✔
2138
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
2139

1✔
2140
            assert!(
1✔
2141
                main_loop_handler
1✔
2142
                    .proof_upgrader(&mut mutable_main_loop_state)
1✔
2143
                    .await
1✔
2144
                    .is_ok(),
1✔
2145
                "Scheduled task returns OK when run on empty mempool"
×
2146
            );
2147

2148
            let fee = NativeCurrencyAmount::coins(1);
1✔
2149
            let proof_collection_tx = tx_no_outputs(
1✔
2150
                &main_loop_handler.global_state_lock,
1✔
2151
                TxProvingCapability::ProofCollection,
1✔
2152
                fee,
1✔
2153
            )
1✔
2154
            .await;
1✔
2155

2156
            main_loop_handler
1✔
2157
                .global_state_lock
1✔
2158
                .lock_guard_mut()
1✔
2159
                .await
1✔
2160
                .mempool_insert(proof_collection_tx.clone(), TransactionOrigin::Foreign)
1✔
2161
                .await;
1✔
2162

2163
            assert!(
1✔
2164
                main_loop_handler
1✔
2165
                    .proof_upgrader(&mut mutable_main_loop_state)
1✔
2166
                    .await
1✔
2167
                    .is_ok(),
1✔
2168
                "Scheduled task returns OK when it's not yet time to upgrade"
×
2169
            );
2170

2171
            assert!(
1✔
2172
                matches!(
×
2173
                    main_loop_handler
1✔
2174
                        .global_state_lock
1✔
2175
                        .lock_guard()
1✔
2176
                        .await
1✔
2177
                        .mempool
2178
                        .get(proof_collection_tx.kernel.txid())
1✔
2179
                        .unwrap()
1✔
2180
                        .proof,
2181
                    TransactionProof::ProofCollection(_)
2182
                ),
2183
                "Proof in mempool must still be of type proof collection"
×
2184
            );
2185

2186
            // Mock that enough time has passed to perform the upgrade. Then
2187
            // perform the upgrade.
2188
            let mut main_loop_handler =
1✔
2189
                main_loop_handler.with_mocked_time(SystemTime::now() + Duration::from_secs(300));
1✔
2190
            assert!(
1✔
2191
                main_loop_handler
1✔
2192
                    .proof_upgrader(&mut mutable_main_loop_state)
1✔
2193
                    .await
1✔
2194
                    .is_ok(),
1✔
2195
                "Scheduled task must return OK when it's time to upgrade"
×
2196
            );
2197

2198
            // Wait for upgrade task to finish.
2199
            let handle = mutable_main_loop_state.proof_upgrader_task.unwrap().await;
1✔
2200
            assert!(
1✔
2201
                handle.is_ok(),
1✔
2202
                "Proof-upgrade task must finish successfully."
×
2203
            );
2204

2205
            // At this point there should be one transaction in the mempool,
2206
            // which is (if all is well) the merger of the ProofCollection
2207
            // transaction inserted above and one of the upgrader's fee
2208
            // gobblers. The point is that this transaction is a SingleProof
2209
            // transaction, so test that.
2210

2211
            let (merged_txid, _) = main_loop_handler
1✔
2212
                .global_state_lock
1✔
2213
                .lock_guard()
1✔
2214
                .await
1✔
2215
                .mempool
2216
                .get_sorted_iter()
1✔
2217
                .next_back()
1✔
2218
                .expect("mempool should contain one item here");
1✔
2219

1✔
2220
            assert!(
1✔
2221
                matches!(
×
2222
                    main_loop_handler
1✔
2223
                        .global_state_lock
1✔
2224
                        .lock_guard()
1✔
2225
                        .await
1✔
2226
                        .mempool
2227
                        .get(merged_txid)
1✔
2228
                        .unwrap()
1✔
2229
                        .proof,
2230
                    TransactionProof::SingleProof(_)
2231
                ),
2232
                "Proof in mempool must now be of type single proof"
×
2233
            );
2234

2235
            match main_to_peer_rx.recv().await {
1✔
2236
                Ok(MainToPeerTask::TransactionNotification(tx_noti)) => {
1✔
2237
                    assert_eq!(merged_txid, tx_noti.txid);
1✔
2238
                    assert_eq!(TransactionProofQuality::SingleProof, tx_noti.proof_quality);
1✔
2239
                },
2240
                other => panic!("Must have sent transaction notification to peer loop after successful proof upgrade. Got:\n{other:?}"),
×
2241
            }
2242

2243
            // These values are kept alive as the transmission-counterpart will
2244
            // otherwise fail on `send`.
2245
            drop(peer_to_main_rx);
1✔
2246
            drop(miner_to_main_rx);
1✔
2247
            drop(rpc_server_to_main_rx);
1✔
2248
            drop(main_to_peer_rx);
1✔
2249
        }
1✔
2250
    }
2251

2252
    mod peer_discovery {
2253
        use super::*;
2254

2255
        #[tokio::test]
2256
        #[traced_test]
×
2257
        async fn prune_peers_too_many_connections() {
1✔
2258
            let num_init_peers_outgoing = 10;
1✔
2259
            let num_init_peers_incoming = 4;
1✔
2260
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2261
            let TestSetup {
2262
                mut main_to_peer_rx,
1✔
2263
                mut main_loop_handler,
1✔
2264
                ..
1✔
2265
            } = test_setup;
1✔
2266

1✔
2267
            let mocked_cli = cli_args::Args {
1✔
2268
                max_num_peers: num_init_peers_outgoing as usize,
1✔
2269
                ..Default::default()
1✔
2270
            };
1✔
2271

1✔
2272
            main_loop_handler
1✔
2273
                .global_state_lock
1✔
2274
                .set_cli(mocked_cli)
1✔
2275
                .await;
1✔
2276

2277
            main_loop_handler.prune_peers().await.unwrap();
1✔
2278
            assert_eq!(4, main_to_peer_rx.len());
1✔
2279
            for _ in 0..4 {
5✔
2280
                let peer_msg = main_to_peer_rx.recv().await.unwrap();
4✔
2281
                assert!(matches!(peer_msg, MainToPeerTask::Disconnect(_)))
4✔
2282
            }
1✔
2283
        }
1✔
2284

2285
        #[tokio::test]
2286
        #[traced_test]
×
2287
        async fn prune_peers_not_too_many_connections() {
1✔
2288
            let num_init_peers_outgoing = 10;
1✔
2289
            let num_init_peers_incoming = 1;
1✔
2290
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2291
            let TestSetup {
2292
                main_to_peer_rx,
1✔
2293
                mut main_loop_handler,
1✔
2294
                ..
1✔
2295
            } = test_setup;
1✔
2296

1✔
2297
            let mocked_cli = cli_args::Args {
1✔
2298
                max_num_peers: 200,
1✔
2299
                ..Default::default()
1✔
2300
            };
1✔
2301

1✔
2302
            main_loop_handler
1✔
2303
                .global_state_lock
1✔
2304
                .set_cli(mocked_cli)
1✔
2305
                .await;
1✔
2306

2307
            main_loop_handler.prune_peers().await.unwrap();
1✔
2308
            assert!(main_to_peer_rx.is_empty());
1✔
2309
        }
1✔
2310

2311
        #[tokio::test]
2312
        #[traced_test]
1✔
2313
        async fn skip_peer_discovery_if_peer_limit_is_exceeded() {
1✔
2314
            let num_init_peers_outgoing = 2;
1✔
2315
            let num_init_peers_incoming = 0;
1✔
2316
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2317
            let TestSetup {
2318
                task_join_handles,
1✔
2319
                mut main_loop_handler,
1✔
2320
                ..
1✔
2321
            } = test_setup;
1✔
2322

1✔
2323
            let mocked_cli = cli_args::Args {
1✔
2324
                max_num_peers: 0,
1✔
2325
                ..Default::default()
1✔
2326
            };
1✔
2327
            main_loop_handler
1✔
2328
                .global_state_lock
1✔
2329
                .set_cli(mocked_cli)
1✔
2330
                .await;
1✔
2331
            main_loop_handler
1✔
2332
                .discover_peers(&mut MutableMainLoopState::new(task_join_handles))
1✔
2333
                .await
1✔
2334
                .unwrap();
1✔
2335

1✔
2336
            assert!(logs_contain("Skipping peer discovery."));
1✔
2337
        }
1✔
2338

2339
        #[tokio::test]
2340
        #[traced_test]
1✔
2341
        async fn performs_peer_discovery_on_few_connections() {
1✔
2342
            let num_init_peers_outgoing = 2;
1✔
2343
            let num_init_peers_incoming = 0;
1✔
2344
            let TestSetup {
2345
                task_join_handles,
1✔
2346
                mut main_loop_handler,
1✔
2347
                mut main_to_peer_rx,
1✔
2348
                peer_to_main_rx: _keep_channel_open,
1✔
2349
                ..
2350
            } = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2351

2352
            // Set CLI to attempt to make more connections
2353
            let mocked_cli = cli_args::Args {
1✔
2354
                max_num_peers: 10,
1✔
2355
                ..Default::default()
1✔
2356
            };
1✔
2357
            main_loop_handler
1✔
2358
                .global_state_lock
1✔
2359
                .set_cli(mocked_cli)
1✔
2360
                .await;
1✔
2361
            main_loop_handler
1✔
2362
                .discover_peers(&mut MutableMainLoopState::new(task_join_handles))
1✔
2363
                .await
1✔
2364
                .unwrap();
1✔
2365

1✔
2366
            let peer_discovery_sent_messages_on_peer_channel = main_to_peer_rx.try_recv().is_ok();
1✔
2367
            assert!(peer_discovery_sent_messages_on_peer_channel);
1✔
2368
            assert!(logs_contain("Performing peer discovery"));
1✔
2369
        }
1✔
2370
    }
2371

2372
    #[test]
2373
    fn older_systemtime_ranks_first() {
1✔
2374
        let start = UNIX_EPOCH;
1✔
2375
        let other = UNIX_EPOCH + Duration::from_secs(1000);
1✔
2376
        let mut instants = [start, other];
1✔
2377

1✔
2378
        assert_eq!(
1✔
2379
            start,
1✔
2380
            instants.iter().copied().min_by(|l, r| l.cmp(r)).unwrap()
1✔
2381
        );
1✔
2382

2383
        instants.reverse();
1✔
2384

1✔
2385
        assert_eq!(
1✔
2386
            start,
1✔
2387
            instants.iter().copied().min_by(|l, r| l.cmp(r)).unwrap()
1✔
2388
        );
1✔
2389
    }
1✔
2390
    mod bootstrapper_mode {
2391

2392
        use rand::Rng;
2393

2394
        use super::*;
2395
        use crate::models::peer::PeerMessage;
2396
        use crate::models::peer::TransferConnectionStatus;
2397
        use crate::tests::shared::get_dummy_peer_connection_data_genesis;
2398
        use crate::tests::shared::to_bytes;
2399

2400
        #[tokio::test]
2401
        #[traced_test]
×
2402
        async fn disconnect_from_oldest_peer_upon_connection_request() {
1✔
2403
            // Set up a node in bootstrapper mode and connected to a given
1✔
2404
            // number of peers, which is one less than the maximum. Initiate a
1✔
2405
            // connection request. Verify that the oldest of the existing
1✔
2406
            // connections is dropped.
1✔
2407

1✔
2408
            let network = Network::Main;
1✔
2409
            let num_init_peers_outgoing = 5;
1✔
2410
            let num_init_peers_incoming = 0;
1✔
2411
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2412
            let TestSetup {
2413
                mut peer_to_main_rx,
1✔
2414
                miner_to_main_rx: _,
1✔
2415
                rpc_server_to_main_rx: _,
1✔
2416
                task_join_handles,
1✔
2417
                mut main_loop_handler,
1✔
2418
                mut main_to_peer_rx,
1✔
2419
            } = test_setup;
1✔
2420

1✔
2421
            let mocked_cli = cli_args::Args {
1✔
2422
                max_num_peers: usize::from(num_init_peers_outgoing) + 1,
1✔
2423
                bootstrap: true,
1✔
2424
                network,
1✔
2425
                ..Default::default()
1✔
2426
            };
1✔
2427
            main_loop_handler
1✔
2428
                .global_state_lock
1✔
2429
                .set_cli(mocked_cli)
1✔
2430
                .await;
1✔
2431

2432
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
2433

1✔
2434
            // check sanity: at startup, we are connected to the initial number of peers
1✔
2435
            assert_eq!(
1✔
2436
                usize::from(num_init_peers_outgoing),
1✔
2437
                main_loop_handler
1✔
2438
                    .global_state_lock
1✔
2439
                    .lock_guard()
1✔
2440
                    .await
1✔
2441
                    .net
2442
                    .peer_map
2443
                    .len()
1✔
2444
            );
2445

2446
            // randomize "connection established" timestamps
2447
            let mut rng = rand::rng();
1✔
2448
            let now = SystemTime::now();
1✔
2449
            let now_as_unix_timestamp = now.duration_since(UNIX_EPOCH).unwrap();
1✔
2450
            main_loop_handler
1✔
2451
                .global_state_lock
1✔
2452
                .lock_guard_mut()
1✔
2453
                .await
1✔
2454
                .net
2455
                .peer_map
2456
                .iter_mut()
1✔
2457
                .for_each(|(_socket_address, peer_info)| {
5✔
2458
                    peer_info.set_connection_established(
5✔
2459
                        UNIX_EPOCH
5✔
2460
                            + Duration::from_millis(
5✔
2461
                                rng.random_range(0..(now_as_unix_timestamp.as_millis() as u64)),
5✔
2462
                            ),
5✔
2463
                    );
5✔
2464
                });
5✔
2465

2466
            // compute which peer will be dropped, for later reference
2467
            let expected_drop_peer_socket_address = main_loop_handler
1✔
2468
                .global_state_lock
1✔
2469
                .lock_guard()
1✔
2470
                .await
1✔
2471
                .net
2472
                .peer_map
2473
                .iter()
1✔
2474
                .min_by(|l, r| {
4✔
2475
                    l.1.connection_established()
4✔
2476
                        .cmp(&r.1.connection_established())
4✔
2477
                })
4✔
2478
                .map(|(socket_address, _peer_info)| socket_address)
1✔
2479
                .copied()
1✔
2480
                .unwrap();
1✔
2481

1✔
2482
            // simulate incoming connection
1✔
2483
            let (peer_handshake_data, peer_socket_address) =
1✔
2484
                get_dummy_peer_connection_data_genesis(network, 1);
1✔
2485
            let own_handshake_data = main_loop_handler
1✔
2486
                .global_state_lock
1✔
2487
                .lock_guard()
1✔
2488
                .await
1✔
2489
                .get_own_handshakedata();
1✔
2490
            assert_eq!(peer_handshake_data.network, own_handshake_data.network,);
1✔
2491
            assert_eq!(peer_handshake_data.version, own_handshake_data.version,);
1✔
2492
            let mock_stream = tokio_test::io::Builder::new()
1✔
2493
                .read(
1✔
2494
                    &to_bytes(&PeerMessage::Handshake(Box::new((
1✔
2495
                        crate::MAGIC_STRING_REQUEST.to_vec(),
1✔
2496
                        peer_handshake_data.clone(),
1✔
2497
                    ))))
1✔
2498
                    .unwrap(),
1✔
2499
                )
1✔
2500
                .write(
1✔
2501
                    &to_bytes(&PeerMessage::Handshake(Box::new((
1✔
2502
                        crate::MAGIC_STRING_RESPONSE.to_vec(),
1✔
2503
                        own_handshake_data.clone(),
1✔
2504
                    ))))
1✔
2505
                    .unwrap(),
1✔
2506
                )
1✔
2507
                .write(
1✔
2508
                    &to_bytes(&PeerMessage::ConnectionStatus(
1✔
2509
                        TransferConnectionStatus::Accepted,
1✔
2510
                    ))
1✔
2511
                    .unwrap(),
1✔
2512
                )
1✔
2513
                .build();
1✔
2514
            let peer_to_main_tx_clone = main_loop_handler.peer_task_to_main_tx.clone();
1✔
2515
            let global_state_lock_clone = main_loop_handler.global_state_lock.clone();
1✔
2516
            let (_main_to_peer_tx_mock, main_to_peer_rx_mock) = tokio::sync::broadcast::channel(10);
1✔
2517
            let incoming_peer_task_handle = tokio::task::Builder::new()
1✔
2518
                .name("answer_peer_wrapper")
1✔
2519
                .spawn(async move {
1✔
2520
                    match answer_peer(
1✔
2521
                        mock_stream,
1✔
2522
                        global_state_lock_clone,
1✔
2523
                        peer_socket_address,
1✔
2524
                        main_to_peer_rx_mock,
1✔
2525
                        peer_to_main_tx_clone,
1✔
2526
                        own_handshake_data,
1✔
2527
                    )
1✔
2528
                    .await
1✔
2529
                    {
2530
                        Ok(()) => (),
×
2531
                        Err(err) => error!("Got error: {:?}", err),
×
2532
                    }
2533
                })
1✔
2534
                .unwrap();
1✔
2535

2536
            // `answer_peer_wrapper` should send a
2537
            // `DisconnectFromLongestLivedPeer` message to main
2538
            let peer_to_main_message = peer_to_main_rx.recv().await.unwrap();
1✔
2539
            assert!(matches!(
1✔
2540
                peer_to_main_message,
1✔
2541
                PeerTaskToMain::DisconnectFromLongestLivedPeer,
2542
            ));
2543

2544
            // process this message
2545
            main_loop_handler
1✔
2546
                .handle_peer_task_message(peer_to_main_message, &mut mutable_main_loop_state)
1✔
2547
                .await
1✔
2548
                .unwrap();
1✔
2549

2550
            // main loop should send a `Disconnect` message
2551
            let main_to_peers_message = main_to_peer_rx.recv().await.unwrap();
1✔
2552
            let MainToPeerTask::Disconnect(observed_drop_peer_socket_address) =
1✔
2553
                main_to_peers_message
1✔
2554
            else {
2555
                panic!("Expected disconnect, got {main_to_peers_message:?}");
×
2556
            };
2557

2558
            // matched observed droppee against expectation
2559
            assert_eq!(
1✔
2560
                expected_drop_peer_socket_address,
1✔
2561
                observed_drop_peer_socket_address,
1✔
2562
            );
1✔
2563
            println!("Dropped connection with {expected_drop_peer_socket_address}.");
1✔
2564

1✔
2565
            // don't forget to terminate the peer task, which is still running
1✔
2566
            incoming_peer_task_handle.abort();
1✔
2567
        }
1✔
2568
    }
2569
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc