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

Neptune-Crypto / neptune-core / 14082870795

26 Mar 2025 12:07PM UTC coverage: 84.277% (-0.02%) from 84.3%
14082870795

push

github

Sword-Smith
feat(rpc_server): Add command to clear mempool

0 of 24 new or added lines in 3 files covered. (0.0%)

1 existing line in 1 file now uncovered.

50969 of 60478 relevant lines covered (84.28%)

175125.71 hits per line

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

56.32
/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()) {
1✔
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.
×
1405

×
1406
        // Don't run peer discovery immediately at startup since outgoing
×
1407
        // connections started from lib.rs may not have finished yet.
×
1408
        let mut peer_discovery_interval = time::interval_at(
×
1409
            Instant::now() + PEER_DISCOVERY_INTERVAL,
×
1410
            PEER_DISCOVERY_INTERVAL,
×
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::ClearMempool => {
NEW
1732
                info!("Clearing mempool");
×
NEW
1733
                self.global_state_lock
×
NEW
1734
                    .lock_guard_mut()
×
NEW
1735
                    .await
×
NEW
1736
                    .mempool_clear()
×
NEW
1737
                    .await;
×
1738

NEW
1739
                Ok(false)
×
1740
            }
1741
            RPCServerToMain::ProofOfWorkSolution(new_block) => {
×
1742
                info!("Handling PoW solution from RPC call");
×
1743

1744
                self.handle_self_guessed_block(main_loop_state, new_block)
×
1745
                    .await?;
×
1746
                Ok(false)
×
1747
            }
1748
            RPCServerToMain::PauseMiner => {
1749
                info!("Received RPC request to stop miner");
×
1750

1751
                self.main_to_miner_tx.send(MainToMiner::StopMining);
×
1752
                Ok(false)
×
1753
            }
1754
            RPCServerToMain::RestartMiner => {
1755
                info!("Received RPC request to start miner");
×
1756
                self.main_to_miner_tx.send(MainToMiner::StartMining);
×
1757
                Ok(false)
×
1758
            }
1759
            RPCServerToMain::Shutdown => {
1760
                info!("Received RPC shutdown request.");
×
1761

1762
                // shut down
1763
                Ok(true)
×
1764
            }
1765
        }
1766
    }
×
1767

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

1771
        // Stop mining
1772
        self.main_to_miner_tx.send(MainToMiner::Shutdown);
×
1773

×
1774
        // Send 'bye' message to all peers.
×
1775
        let _result = self
×
1776
            .main_to_peer_broadcast_tx
×
1777
            .send(MainToPeerTask::DisconnectAll());
×
1778
        debug!("sent bye");
×
1779

1780
        // Flush all databases
1781
        self.global_state_lock.flush_databases().await?;
×
1782

1783
        tokio::time::sleep(Duration::from_millis(50)).await;
×
1784

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

×
1788
        // wait for all to finish.
×
1789
        futures::future::join_all(task_handles).await;
×
1790

1791
        Ok(())
×
1792
    }
×
1793
}
1794

1795
#[cfg(test)]
1796
mod test {
1797
    use std::str::FromStr;
1798
    use std::time::UNIX_EPOCH;
1799

1800
    use tracing_test::traced_test;
1801

1802
    use super::*;
1803
    use crate::config_models::cli_args;
1804
    use crate::config_models::network::Network;
1805
    use crate::tests::shared::get_dummy_peer_incoming;
1806
    use crate::tests::shared::get_test_genesis_setup;
1807
    use crate::tests::shared::invalid_empty_block;
1808
    use crate::MINER_CHANNEL_CAPACITY;
1809

1810
    struct TestSetup {
1811
        peer_to_main_rx: mpsc::Receiver<PeerTaskToMain>,
1812
        miner_to_main_rx: mpsc::Receiver<MinerToMain>,
1813
        rpc_server_to_main_rx: mpsc::Receiver<RPCServerToMain>,
1814
        task_join_handles: Vec<JoinHandle<()>>,
1815
        main_loop_handler: MainLoopHandler,
1816
        main_to_peer_rx: broadcast::Receiver<MainToPeerTask>,
1817
    }
1818

1819
    async fn setup(num_init_peers_outgoing: u8, num_peers_incoming: u8) -> TestSetup {
8✔
1820
        const CHANNEL_CAPACITY_MINER_TO_MAIN: usize = 10;
1821

1822
        let network = Network::Main;
8✔
1823
        let (
1824
            main_to_peer_tx,
8✔
1825
            main_to_peer_rx,
8✔
1826
            peer_to_main_tx,
8✔
1827
            peer_to_main_rx,
8✔
1828
            mut state,
8✔
1829
            _own_handshake_data,
8✔
1830
        ) = get_test_genesis_setup(network, num_init_peers_outgoing, cli_args::Args::default())
8✔
1831
            .await
8✔
1832
            .unwrap();
8✔
1833
        assert!(
8✔
1834
            state
8✔
1835
                .lock_guard()
8✔
1836
                .await
8✔
1837
                .net
1838
                .peer_map
1839
                .iter()
8✔
1840
                .all(|(_addr, peer)| peer.connection_is_outbound()),
30✔
1841
            "Test assumption: All initial peers must represent outgoing connections."
×
1842
        );
1843

1844
        for i in 0..num_peers_incoming {
8✔
1845
            let peer_address = SocketAddr::from_str(&format!("255.254.253.{i}:8080")).unwrap();
5✔
1846
            state
5✔
1847
                .lock_guard_mut()
5✔
1848
                .await
5✔
1849
                .net
1850
                .peer_map
1851
                .insert(peer_address, get_dummy_peer_incoming(peer_address));
5✔
1852
        }
1853

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

8✔
1856
        let (main_to_miner_tx, _main_to_miner_rx) =
8✔
1857
            mpsc::channel::<MainToMiner>(MINER_CHANNEL_CAPACITY);
8✔
1858
        let (_miner_to_main_tx, miner_to_main_rx) =
8✔
1859
            mpsc::channel::<MinerToMain>(CHANNEL_CAPACITY_MINER_TO_MAIN);
8✔
1860
        let (_rpc_server_to_main_tx, rpc_server_to_main_rx) =
8✔
1861
            mpsc::channel::<RPCServerToMain>(CHANNEL_CAPACITY_MINER_TO_MAIN);
8✔
1862

8✔
1863
        let main_loop_handler = MainLoopHandler::new(
8✔
1864
            incoming_peer_listener,
8✔
1865
            state,
8✔
1866
            main_to_peer_tx,
8✔
1867
            peer_to_main_tx,
8✔
1868
            main_to_miner_tx,
8✔
1869
        );
8✔
1870

8✔
1871
        let task_join_handles = vec![];
8✔
1872

8✔
1873
        TestSetup {
8✔
1874
            miner_to_main_rx,
8✔
1875
            peer_to_main_rx,
8✔
1876
            rpc_server_to_main_rx,
8✔
1877
            task_join_handles,
8✔
1878
            main_loop_handler,
8✔
1879
            main_to_peer_rx,
8✔
1880
        }
8✔
1881
    }
8✔
1882

1883
    #[tokio::test]
1884
    async fn handle_self_guessed_block_new_tip() {
1✔
1885
        // A new tip is registered by main_loop. Verify correct state update.
1✔
1886
        let test_setup = setup(1, 0).await;
1✔
1887
        let TestSetup {
1✔
1888
            task_join_handles,
1✔
1889
            mut main_loop_handler,
1✔
1890
            mut main_to_peer_rx,
1✔
1891
            ..
1✔
1892
        } = test_setup;
1✔
1893
        let network = main_loop_handler.global_state_lock.cli().network;
1✔
1894
        let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
1895

1✔
1896
        let block1 = invalid_empty_block(&Block::genesis(network));
1✔
1897

1✔
1898
        assert!(
1✔
1899
            main_loop_handler
1✔
1900
                .global_state_lock
1✔
1901
                .lock_guard()
1✔
1902
                .await
1✔
1903
                .chain
1✔
1904
                .light_state()
1✔
1905
                .header()
1✔
1906
                .height
1✔
1907
                .is_genesis(),
1✔
1908
            "Tip must be genesis prior to handling of new block"
1✔
1909
        );
1✔
1910

1✔
1911
        let block1 = Box::new(block1);
1✔
1912
        main_loop_handler
1✔
1913
            .handle_self_guessed_block(&mut mutable_main_loop_state, block1.clone())
1✔
1914
            .await
1✔
1915
            .unwrap();
1✔
1916
        let new_block_height: u64 = main_loop_handler
1✔
1917
            .global_state_lock
1✔
1918
            .lock_guard()
1✔
1919
            .await
1✔
1920
            .chain
1✔
1921
            .light_state()
1✔
1922
            .header()
1✔
1923
            .height
1✔
1924
            .into();
1✔
1925
        assert_eq!(
1✔
1926
            1u64, new_block_height,
1✔
1927
            "Tip height must be 1 after handling of new block"
1✔
1928
        );
1✔
1929
        let msg_to_peer_loops = main_to_peer_rx.recv().await.unwrap();
1✔
1930
        if let MainToPeerTask::Block(block_to_peers) = msg_to_peer_loops {
1✔
1931
            assert_eq!(
1✔
1932
                block1, block_to_peers,
1✔
1933
                "Peer loops must have received block 1"
1✔
1934
            );
1✔
1935
        } else {
1✔
1936
            panic!("Must have sent block notification to peer loops")
1✔
1937
        }
1✔
1938
    }
1✔
1939

1940
    mod sync_mode {
1941
        use tasm_lib::twenty_first::util_types::mmr::mmr_accumulator::MmrAccumulator;
1942
        use test_strategy::proptest;
1943

1944
        use super::*;
1945
        use crate::tests::shared::get_dummy_socket_address;
1946

1947
        #[proptest]
256✔
1948
        fn batch_request_heights_prop(#[strategy(0u64..100_000_000_000)] own_height: u64) {
1✔
1949
            batch_request_heights_sanity(own_height);
1950
        }
1951

1952
        #[test]
1953
        fn batch_request_heights_unit() {
1✔
1954
            let own_height = 1_000_000u64;
1✔
1955
            batch_request_heights_sanity(own_height);
1✔
1956
        }
1✔
1957

1958
        fn batch_request_heights_sanity(own_height: u64) {
257✔
1959
            let heights = MainLoopHandler::batch_request_uca_candidate_heights(own_height.into());
257✔
1960

257✔
1961
            let mut heights_rev = heights.clone();
257✔
1962
            heights_rev.reverse();
257✔
1963
            assert!(
257✔
1964
                heights_rev.is_sorted(),
257✔
1965
                "Heights must be sorted from high-to-low"
×
1966
            );
1967

1968
            heights_rev.dedup();
257✔
1969
            assert_eq!(heights_rev.len(), heights.len(), "duplicates");
257✔
1970

1971
            assert_eq!(heights[0], own_height.into(), "starts with own tip height");
257✔
1972
            assert!(
257✔
1973
                heights.last().unwrap().is_genesis(),
257✔
1974
                "ends with genesis block"
×
1975
            );
1976
        }
257✔
1977

1978
        #[tokio::test]
1979
        #[traced_test]
×
1980
        async fn sync_mode_abandoned_on_global_timeout() {
1✔
1981
            let num_outgoing_connections = 0;
1✔
1982
            let num_incoming_connections = 0;
1✔
1983
            let test_setup = setup(num_outgoing_connections, num_incoming_connections).await;
1✔
1984
            let TestSetup {
1985
                task_join_handles,
1✔
1986
                mut main_loop_handler,
1✔
1987
                ..
1✔
1988
            } = test_setup;
1✔
1989

1✔
1990
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
1991

1✔
1992
            main_loop_handler
1✔
1993
                .block_sync(&mut mutable_main_loop_state)
1✔
1994
                .await
1✔
1995
                .expect("Must return OK when no sync mode is set");
1✔
1996

1✔
1997
            // Mock that we are in a valid sync state
1✔
1998
            let claimed_max_height = 1_000u64.into();
1✔
1999
            let claimed_max_pow = ProofOfWork::new([100; 6]);
1✔
2000
            main_loop_handler
1✔
2001
                .global_state_lock
1✔
2002
                .lock_guard_mut()
1✔
2003
                .await
1✔
2004
                .net
1✔
2005
                .sync_anchor = Some(SyncAnchor::new(
1✔
2006
                claimed_max_pow,
1✔
2007
                MmrAccumulator::new_from_leafs(vec![]),
1✔
2008
            ));
1✔
2009
            mutable_main_loop_state.sync_state.peer_sync_states.insert(
1✔
2010
                get_dummy_socket_address(0),
1✔
2011
                PeerSynchronizationState::new(claimed_max_height, claimed_max_pow),
1✔
2012
            );
1✔
2013

2014
            let sync_start_time = main_loop_handler
1✔
2015
                .global_state_lock
1✔
2016
                .lock_guard()
1✔
2017
                .await
1✔
2018
                .net
2019
                .sync_anchor
2020
                .as_ref()
1✔
2021
                .unwrap()
1✔
2022
                .updated;
1✔
2023
            main_loop_handler
1✔
2024
                .block_sync(&mut mutable_main_loop_state)
1✔
2025
                .await
1✔
2026
                .expect("Must return OK when sync mode has not timed out yet");
1✔
2027
            assert!(
1✔
2028
                main_loop_handler
1✔
2029
                    .global_state_lock
1✔
2030
                    .lock_guard()
1✔
2031
                    .await
1✔
2032
                    .net
2033
                    .sync_anchor
2034
                    .is_some(),
1✔
2035
                "Sync mode must still be set before timeout has occurred"
×
2036
            );
2037

2038
            assert_eq!(
1✔
2039
                sync_start_time,
1✔
2040
                main_loop_handler
1✔
2041
                    .global_state_lock
1✔
2042
                    .lock_guard()
1✔
2043
                    .await
1✔
2044
                    .net
2045
                    .sync_anchor
2046
                    .as_ref()
1✔
2047
                    .unwrap()
1✔
2048
                    .updated,
2049
                "timestamp may not be updated without state change"
×
2050
            );
2051

2052
            // Mock that sync-mode has timed out
2053
            main_loop_handler = main_loop_handler.with_mocked_time(
1✔
2054
                SystemTime::now() + GLOBAL_SYNCHRONIZATION_TIMEOUT + Duration::from_secs(1),
1✔
2055
            );
1✔
2056

1✔
2057
            main_loop_handler
1✔
2058
                .block_sync(&mut mutable_main_loop_state)
1✔
2059
                .await
1✔
2060
                .expect("Must return OK when sync mode has timed out");
1✔
2061
            assert!(
1✔
2062
                main_loop_handler
1✔
2063
                    .global_state_lock
1✔
2064
                    .lock_guard()
1✔
2065
                    .await
1✔
2066
                    .net
1✔
2067
                    .sync_anchor
1✔
2068
                    .is_none(),
1✔
2069
                "Sync mode must be unset on timeout"
1✔
2070
            );
1✔
2071
        }
1✔
2072
    }
2073

2074
    mod proof_upgrader {
2075
        use super::*;
2076
        use crate::job_queue::triton_vm::TritonVmJobQueue;
2077
        use crate::models::blockchain::transaction::Transaction;
2078
        use crate::models::blockchain::transaction::TransactionProof;
2079
        use crate::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
2080
        use crate::models::peer::transfer_transaction::TransactionProofQuality;
2081
        use crate::models::proof_abstractions::timestamp::Timestamp;
2082
        use crate::models::state::wallet::utxo_notification::UtxoNotificationMedium;
2083

2084
        async fn tx_no_outputs(
1✔
2085
            global_state_lock: &GlobalStateLock,
1✔
2086
            tx_proof_type: TxProvingCapability,
1✔
2087
            fee: NativeCurrencyAmount,
1✔
2088
        ) -> Transaction {
1✔
2089
            let change_key = global_state_lock
1✔
2090
                .lock_guard()
1✔
2091
                .await
1✔
2092
                .wallet_state
2093
                .wallet_entropy
2094
                .nth_generation_spending_key_for_tests(0);
1✔
2095
            let in_seven_months = global_state_lock
1✔
2096
                .lock_guard()
1✔
2097
                .await
1✔
2098
                .chain
2099
                .light_state()
1✔
2100
                .header()
1✔
2101
                .timestamp
1✔
2102
                + Timestamp::months(7);
1✔
2103

2104
            let global_state = global_state_lock.lock_guard().await;
1✔
2105
            global_state
1✔
2106
                .create_transaction_with_prover_capability(
1✔
2107
                    vec![].into(),
1✔
2108
                    change_key.into(),
1✔
2109
                    UtxoNotificationMedium::OffChain,
1✔
2110
                    fee,
1✔
2111
                    in_seven_months,
1✔
2112
                    tx_proof_type,
1✔
2113
                    &TritonVmJobQueue::dummy(),
1✔
2114
                )
1✔
2115
                .await
1✔
2116
                .unwrap()
1✔
2117
                .0
1✔
2118
        }
1✔
2119

2120
        #[tokio::test]
2121
        #[traced_test]
×
2122
        async fn upgrade_proof_collection_to_single_proof_foreign_tx() {
1✔
2123
            let num_outgoing_connections = 0;
1✔
2124
            let num_incoming_connections = 0;
1✔
2125
            let test_setup = setup(num_outgoing_connections, num_incoming_connections).await;
1✔
2126
            let TestSetup {
2127
                peer_to_main_rx,
1✔
2128
                miner_to_main_rx,
1✔
2129
                rpc_server_to_main_rx,
1✔
2130
                task_join_handles,
1✔
2131
                mut main_loop_handler,
1✔
2132
                mut main_to_peer_rx,
1✔
2133
            } = test_setup;
1✔
2134

1✔
2135
            // Force instance to create SingleProofs, otherwise CI and other
1✔
2136
            // weak machines fail.
1✔
2137
            let mocked_cli = cli_args::Args {
1✔
2138
                tx_proving_capability: Some(TxProvingCapability::SingleProof),
1✔
2139
                tx_proof_upgrade_interval: 100, // seconds
1✔
2140
                ..Default::default()
1✔
2141
            };
1✔
2142

1✔
2143
            main_loop_handler
1✔
2144
                .global_state_lock
1✔
2145
                .set_cli(mocked_cli)
1✔
2146
                .await;
1✔
2147
            let mut main_loop_handler = main_loop_handler.with_mocked_time(SystemTime::now());
1✔
2148
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
2149

1✔
2150
            assert!(
1✔
2151
                main_loop_handler
1✔
2152
                    .proof_upgrader(&mut mutable_main_loop_state)
1✔
2153
                    .await
1✔
2154
                    .is_ok(),
1✔
2155
                "Scheduled task returns OK when run on empty mempool"
×
2156
            );
2157

2158
            let fee = NativeCurrencyAmount::coins(1);
1✔
2159
            let proof_collection_tx = tx_no_outputs(
1✔
2160
                &main_loop_handler.global_state_lock,
1✔
2161
                TxProvingCapability::ProofCollection,
1✔
2162
                fee,
1✔
2163
            )
1✔
2164
            .await;
1✔
2165

2166
            main_loop_handler
1✔
2167
                .global_state_lock
1✔
2168
                .lock_guard_mut()
1✔
2169
                .await
1✔
2170
                .mempool_insert(proof_collection_tx.clone(), TransactionOrigin::Foreign)
1✔
2171
                .await;
1✔
2172

2173
            assert!(
1✔
2174
                main_loop_handler
1✔
2175
                    .proof_upgrader(&mut mutable_main_loop_state)
1✔
2176
                    .await
1✔
2177
                    .is_ok(),
1✔
2178
                "Scheduled task returns OK when it's not yet time to upgrade"
×
2179
            );
2180

2181
            assert!(
1✔
2182
                matches!(
×
2183
                    main_loop_handler
1✔
2184
                        .global_state_lock
1✔
2185
                        .lock_guard()
1✔
2186
                        .await
1✔
2187
                        .mempool
2188
                        .get(proof_collection_tx.kernel.txid())
1✔
2189
                        .unwrap()
1✔
2190
                        .proof,
2191
                    TransactionProof::ProofCollection(_)
2192
                ),
2193
                "Proof in mempool must still be of type proof collection"
×
2194
            );
2195

2196
            // Mock that enough time has passed to perform the upgrade. Then
2197
            // perform the upgrade.
2198
            let mut main_loop_handler =
1✔
2199
                main_loop_handler.with_mocked_time(SystemTime::now() + Duration::from_secs(300));
1✔
2200
            assert!(
1✔
2201
                main_loop_handler
1✔
2202
                    .proof_upgrader(&mut mutable_main_loop_state)
1✔
2203
                    .await
1✔
2204
                    .is_ok(),
1✔
2205
                "Scheduled task must return OK when it's time to upgrade"
×
2206
            );
2207

2208
            // Wait for upgrade task to finish.
2209
            let handle = mutable_main_loop_state.proof_upgrader_task.unwrap().await;
1✔
2210
            assert!(
1✔
2211
                handle.is_ok(),
1✔
2212
                "Proof-upgrade task must finish successfully."
×
2213
            );
2214

2215
            // At this point there should be one transaction in the mempool,
2216
            // which is (if all is well) the merger of the ProofCollection
2217
            // transaction inserted above and one of the upgrader's fee
2218
            // gobblers. The point is that this transaction is a SingleProof
2219
            // transaction, so test that.
2220

2221
            let (merged_txid, _) = main_loop_handler
1✔
2222
                .global_state_lock
1✔
2223
                .lock_guard()
1✔
2224
                .await
1✔
2225
                .mempool
2226
                .get_sorted_iter()
1✔
2227
                .next_back()
1✔
2228
                .expect("mempool should contain one item here");
1✔
2229

1✔
2230
            assert!(
1✔
2231
                matches!(
×
2232
                    main_loop_handler
1✔
2233
                        .global_state_lock
1✔
2234
                        .lock_guard()
1✔
2235
                        .await
1✔
2236
                        .mempool
2237
                        .get(merged_txid)
1✔
2238
                        .unwrap()
1✔
2239
                        .proof,
2240
                    TransactionProof::SingleProof(_)
2241
                ),
2242
                "Proof in mempool must now be of type single proof"
×
2243
            );
2244

2245
            match main_to_peer_rx.recv().await {
1✔
2246
                Ok(MainToPeerTask::TransactionNotification(tx_noti)) => {
1✔
2247
                    assert_eq!(merged_txid, tx_noti.txid);
1✔
2248
                    assert_eq!(TransactionProofQuality::SingleProof, tx_noti.proof_quality);
1✔
2249
                },
2250
                other => panic!("Must have sent transaction notification to peer loop after successful proof upgrade. Got:\n{other:?}"),
×
2251
            }
2252

2253
            // These values are kept alive as the transmission-counterpart will
2254
            // otherwise fail on `send`.
2255
            drop(peer_to_main_rx);
1✔
2256
            drop(miner_to_main_rx);
1✔
2257
            drop(rpc_server_to_main_rx);
1✔
2258
            drop(main_to_peer_rx);
1✔
2259
        }
1✔
2260
    }
2261

2262
    mod peer_discovery {
2263
        use super::*;
2264

2265
        #[tokio::test]
2266
        #[traced_test]
×
2267
        async fn prune_peers_too_many_connections() {
1✔
2268
            let num_init_peers_outgoing = 10;
1✔
2269
            let num_init_peers_incoming = 4;
1✔
2270
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2271
            let TestSetup {
2272
                mut main_to_peer_rx,
1✔
2273
                mut main_loop_handler,
1✔
2274
                ..
1✔
2275
            } = test_setup;
1✔
2276

1✔
2277
            let mocked_cli = cli_args::Args {
1✔
2278
                max_num_peers: num_init_peers_outgoing as usize,
1✔
2279
                ..Default::default()
1✔
2280
            };
1✔
2281

1✔
2282
            main_loop_handler
1✔
2283
                .global_state_lock
1✔
2284
                .set_cli(mocked_cli)
1✔
2285
                .await;
1✔
2286

2287
            main_loop_handler.prune_peers().await.unwrap();
1✔
2288
            assert_eq!(4, main_to_peer_rx.len());
1✔
2289
            for _ in 0..4 {
5✔
2290
                let peer_msg = main_to_peer_rx.recv().await.unwrap();
4✔
2291
                assert!(matches!(peer_msg, MainToPeerTask::Disconnect(_)))
4✔
2292
            }
1✔
2293
        }
1✔
2294

2295
        #[tokio::test]
2296
        #[traced_test]
×
2297
        async fn prune_peers_not_too_many_connections() {
1✔
2298
            let num_init_peers_outgoing = 10;
1✔
2299
            let num_init_peers_incoming = 1;
1✔
2300
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2301
            let TestSetup {
2302
                main_to_peer_rx,
1✔
2303
                mut main_loop_handler,
1✔
2304
                ..
1✔
2305
            } = test_setup;
1✔
2306

1✔
2307
            let mocked_cli = cli_args::Args {
1✔
2308
                max_num_peers: 200,
1✔
2309
                ..Default::default()
1✔
2310
            };
1✔
2311

1✔
2312
            main_loop_handler
1✔
2313
                .global_state_lock
1✔
2314
                .set_cli(mocked_cli)
1✔
2315
                .await;
1✔
2316

2317
            main_loop_handler.prune_peers().await.unwrap();
1✔
2318
            assert!(main_to_peer_rx.is_empty());
1✔
2319
        }
1✔
2320

2321
        #[tokio::test]
2322
        #[traced_test]
1✔
2323
        async fn skip_peer_discovery_if_peer_limit_is_exceeded() {
1✔
2324
            let num_init_peers_outgoing = 2;
1✔
2325
            let num_init_peers_incoming = 0;
1✔
2326
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2327
            let TestSetup {
2328
                task_join_handles,
1✔
2329
                mut main_loop_handler,
1✔
2330
                ..
1✔
2331
            } = test_setup;
1✔
2332

1✔
2333
            let mocked_cli = cli_args::Args {
1✔
2334
                max_num_peers: 0,
1✔
2335
                ..Default::default()
1✔
2336
            };
1✔
2337
            main_loop_handler
1✔
2338
                .global_state_lock
1✔
2339
                .set_cli(mocked_cli)
1✔
2340
                .await;
1✔
2341
            main_loop_handler
1✔
2342
                .discover_peers(&mut MutableMainLoopState::new(task_join_handles))
1✔
2343
                .await
1✔
2344
                .unwrap();
1✔
2345

1✔
2346
            assert!(logs_contain("Skipping peer discovery."));
1✔
2347
        }
1✔
2348

2349
        #[tokio::test]
2350
        #[traced_test]
1✔
2351
        async fn performs_peer_discovery_on_few_connections() {
1✔
2352
            let num_init_peers_outgoing = 2;
1✔
2353
            let num_init_peers_incoming = 0;
1✔
2354
            let TestSetup {
2355
                task_join_handles,
1✔
2356
                mut main_loop_handler,
1✔
2357
                mut main_to_peer_rx,
1✔
2358
                peer_to_main_rx: _keep_channel_open,
1✔
2359
                ..
2360
            } = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2361

2362
            // Set CLI to attempt to make more connections
2363
            let mocked_cli = cli_args::Args {
1✔
2364
                max_num_peers: 10,
1✔
2365
                ..Default::default()
1✔
2366
            };
1✔
2367
            main_loop_handler
1✔
2368
                .global_state_lock
1✔
2369
                .set_cli(mocked_cli)
1✔
2370
                .await;
1✔
2371
            main_loop_handler
1✔
2372
                .discover_peers(&mut MutableMainLoopState::new(task_join_handles))
1✔
2373
                .await
1✔
2374
                .unwrap();
1✔
2375

1✔
2376
            let peer_discovery_sent_messages_on_peer_channel = main_to_peer_rx.try_recv().is_ok();
1✔
2377
            assert!(peer_discovery_sent_messages_on_peer_channel);
1✔
2378
            assert!(logs_contain("Performing peer discovery"));
1✔
2379
        }
1✔
2380
    }
2381

2382
    #[test]
2383
    fn older_systemtime_ranks_first() {
1✔
2384
        let start = UNIX_EPOCH;
1✔
2385
        let other = UNIX_EPOCH + Duration::from_secs(1000);
1✔
2386
        let mut instants = [start, other];
1✔
2387

1✔
2388
        assert_eq!(
1✔
2389
            start,
1✔
2390
            instants.iter().copied().min_by(|l, r| l.cmp(r)).unwrap()
1✔
2391
        );
1✔
2392

2393
        instants.reverse();
1✔
2394

1✔
2395
        assert_eq!(
1✔
2396
            start,
1✔
2397
            instants.iter().copied().min_by(|l, r| l.cmp(r)).unwrap()
1✔
2398
        );
1✔
2399
    }
1✔
2400
    mod bootstrapper_mode {
2401

2402
        use rand::Rng;
2403

2404
        use super::*;
2405
        use crate::models::peer::PeerMessage;
2406
        use crate::models::peer::TransferConnectionStatus;
2407
        use crate::tests::shared::get_dummy_peer_connection_data_genesis;
2408
        use crate::tests::shared::to_bytes;
2409

2410
        #[tokio::test]
2411
        #[traced_test]
×
2412
        async fn disconnect_from_oldest_peer_upon_connection_request() {
1✔
2413
            // Set up a node in bootstrapper mode and connected to a given
1✔
2414
            // number of peers, which is one less than the maximum. Initiate a
1✔
2415
            // connection request. Verify that the oldest of the existing
1✔
2416
            // connections is dropped.
1✔
2417

1✔
2418
            let network = Network::Main;
1✔
2419
            let num_init_peers_outgoing = 5;
1✔
2420
            let num_init_peers_incoming = 0;
1✔
2421
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2422
            let TestSetup {
2423
                mut peer_to_main_rx,
1✔
2424
                miner_to_main_rx: _,
1✔
2425
                rpc_server_to_main_rx: _,
1✔
2426
                task_join_handles,
1✔
2427
                mut main_loop_handler,
1✔
2428
                mut main_to_peer_rx,
1✔
2429
            } = test_setup;
1✔
2430

1✔
2431
            let mocked_cli = cli_args::Args {
1✔
2432
                max_num_peers: usize::from(num_init_peers_outgoing) + 1,
1✔
2433
                bootstrap: true,
1✔
2434
                network,
1✔
2435
                ..Default::default()
1✔
2436
            };
1✔
2437
            main_loop_handler
1✔
2438
                .global_state_lock
1✔
2439
                .set_cli(mocked_cli)
1✔
2440
                .await;
1✔
2441

2442
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
2443

1✔
2444
            // check sanity: at startup, we are connected to the initial number of peers
1✔
2445
            assert_eq!(
1✔
2446
                usize::from(num_init_peers_outgoing),
1✔
2447
                main_loop_handler
1✔
2448
                    .global_state_lock
1✔
2449
                    .lock_guard()
1✔
2450
                    .await
1✔
2451
                    .net
2452
                    .peer_map
2453
                    .len()
1✔
2454
            );
2455

2456
            // randomize "connection established" timestamps
2457
            let mut rng = rand::rng();
1✔
2458
            let now = SystemTime::now();
1✔
2459
            let now_as_unix_timestamp = now.duration_since(UNIX_EPOCH).unwrap();
1✔
2460
            main_loop_handler
1✔
2461
                .global_state_lock
1✔
2462
                .lock_guard_mut()
1✔
2463
                .await
1✔
2464
                .net
2465
                .peer_map
2466
                .iter_mut()
1✔
2467
                .for_each(|(_socket_address, peer_info)| {
5✔
2468
                    peer_info.set_connection_established(
5✔
2469
                        UNIX_EPOCH
5✔
2470
                            + Duration::from_millis(
5✔
2471
                                rng.random_range(0..(now_as_unix_timestamp.as_millis() as u64)),
5✔
2472
                            ),
5✔
2473
                    );
5✔
2474
                });
5✔
2475

2476
            // compute which peer will be dropped, for later reference
2477
            let expected_drop_peer_socket_address = main_loop_handler
1✔
2478
                .global_state_lock
1✔
2479
                .lock_guard()
1✔
2480
                .await
1✔
2481
                .net
2482
                .peer_map
2483
                .iter()
1✔
2484
                .min_by(|l, r| {
4✔
2485
                    l.1.connection_established()
4✔
2486
                        .cmp(&r.1.connection_established())
4✔
2487
                })
4✔
2488
                .map(|(socket_address, _peer_info)| socket_address)
1✔
2489
                .copied()
1✔
2490
                .unwrap();
1✔
2491

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

2546
            // `answer_peer_wrapper` should send a
2547
            // `DisconnectFromLongestLivedPeer` message to main
2548
            let peer_to_main_message = peer_to_main_rx.recv().await.unwrap();
1✔
2549
            assert!(matches!(
1✔
2550
                peer_to_main_message,
1✔
2551
                PeerTaskToMain::DisconnectFromLongestLivedPeer,
2552
            ));
2553

2554
            // process this message
2555
            main_loop_handler
1✔
2556
                .handle_peer_task_message(peer_to_main_message, &mut mutable_main_loop_state)
1✔
2557
                .await
1✔
2558
                .unwrap();
1✔
2559

2560
            // main loop should send a `Disconnect` message
2561
            let main_to_peers_message = main_to_peer_rx.recv().await.unwrap();
1✔
2562
            let MainToPeerTask::Disconnect(observed_drop_peer_socket_address) =
1✔
2563
                main_to_peers_message
1✔
2564
            else {
2565
                panic!("Expected disconnect, got {main_to_peers_message:?}");
×
2566
            };
2567

2568
            // matched observed droppee against expectation
2569
            assert_eq!(
1✔
2570
                expected_drop_peer_socket_address,
1✔
2571
                observed_drop_peer_socket_address,
1✔
2572
            );
1✔
2573
            println!("Dropped connection with {expected_drop_peer_socket_address}.");
1✔
2574

1✔
2575
            // don't forget to terminate the peer task, which is still running
1✔
2576
            incoming_peer_task_handle.abort();
1✔
2577
        }
1✔
2578
    }
2579
}
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