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

Neptune-Crypto / neptune-core / 13969181582

20 Mar 2025 08:44AM UTC coverage: 84.289% (+0.01%) from 84.278%
13969181582

push

github

jan-ferdinand
refactor: Use `tokio::interval` over `sleep`

Also, use `Duration` over `u64` in constant contexts if appropriate.

3 of 52 new or added lines in 1 file covered. (5.77%)

4 existing lines in 3 files now uncovered.

50749 of 60208 relevant lines covered (84.29%)

176058.19 hits per line

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

56.74
/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::MissedTickBehavior;
23
use tracing::debug;
24
use tracing::error;
25
use tracing::info;
26
use tracing::trace;
27
use tracing::warn;
28

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

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

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

71
const SANCTION_PEER_TIMEOUT_FACTOR: u64 = 40;
72

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
537
                let new_block = new_block_info.block;
×
538

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

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

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

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

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

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

599
        Ok(None)
×
600
    }
×
601

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

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

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

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

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

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

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

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

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

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

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

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

696
                    update_jobs
×
697
                };
×
698

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1014
        Ok(())
×
1015
    }
×
1016

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

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

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

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

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

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

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

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

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

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

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

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

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

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

258✔
1125
        ret
258✔
1126
    }
258✔
1127

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
NEW
1407
        let mut block_sync_interval = time::interval(SYNC_REQUEST_INTERVAL);
×
NEW
1408
        block_sync_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
×
NEW
1409

×
NEW
1410
        let mut mempool_cleanup_interval = time::interval(MEMPOOL_PRUNE_INTERVAL);
×
NEW
1411
        mempool_cleanup_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
×
NEW
1412

×
NEW
1413
        let mut utxo_notification_cleanup_interval = time::interval(EXPECTED_UTXOS_PRUNE_INTERVAL);
×
NEW
1414
        utxo_notification_cleanup_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
×
NEW
1415

×
NEW
1416
        let mut mp_resync_interval = time::interval(MP_RESYNC_INTERVAL);
×
NEW
1417
        mp_resync_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
×
NEW
1418

×
NEW
1419
        let mut tx_proof_upgrade_interval = time::interval(TRANSACTION_UPGRADE_CHECK_INTERVAL);
×
NEW
1420
        tx_proof_upgrade_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
×
1421

×
1422
        // Spawn tasks to monitor for SIGTERM, SIGINT, and SIGQUIT. These
×
1423
        // signals are only used on Unix systems.
×
NEW
1424
        let (tx_term, mut rx_term) = mpsc::channel::<()>(2);
×
NEW
1425
        let (tx_int, mut rx_int) = mpsc::channel::<()>(2);
×
NEW
1426
        let (tx_quit, mut rx_quit) = mpsc::channel::<()>(2);
×
1427
        #[cfg(unix)]
1428
        {
×
1429
            use tokio::signal::unix::signal;
×
1430
            use tokio::signal::unix::SignalKind;
×
1431

1432
            // Monitor for SIGTERM
1433
            let mut sigterm = signal(SignalKind::terminate())?;
×
1434
            tokio::task::Builder::new()
×
1435
                .name("sigterm_handler")
×
1436
                .spawn(async move {
×
1437
                    if sigterm.recv().await.is_some() {
×
1438
                        info!("Received SIGTERM");
×
1439
                        tx_term.send(()).await.unwrap();
×
1440
                    }
×
1441
                })?;
×
1442

1443
            // Monitor for SIGINT
1444
            let mut sigint = signal(SignalKind::interrupt())?;
×
1445
            tokio::task::Builder::new()
×
1446
                .name("sigint_handler")
×
1447
                .spawn(async move {
×
1448
                    if sigint.recv().await.is_some() {
×
1449
                        info!("Received SIGINT");
×
1450
                        tx_int.send(()).await.unwrap();
×
1451
                    }
×
1452
                })?;
×
1453

1454
            // Monitor for SIGQUIT
1455
            let mut sigquit = signal(SignalKind::quit())?;
×
1456
            tokio::task::Builder::new()
×
1457
                .name("sigquit_handler")
×
1458
                .spawn(async move {
×
1459
                    if sigquit.recv().await.is_some() {
×
1460
                        info!("Received SIGQUIT");
×
1461
                        tx_quit.send(()).await.unwrap();
×
1462
                    }
×
1463
                })?;
×
1464
        }
1465

1466
        #[cfg(not(unix))]
1467
        drop((tx_term, tx_int, tx_quit));
1468

1469
        let exit_code: i32 = loop {
×
1470
            select! {
×
1471
                Ok(()) = signal::ctrl_c() => {
×
1472
                    info!("Detected Ctrl+c signal.");
×
1473
                    break SUCCESS_EXIT_CODE;
×
1474
                }
1475

1476
                // Monitor for SIGTERM, SIGINT, and SIGQUIT.
1477
                Some(_) = rx_term.recv() => {
×
1478
                    info!("Detected SIGTERM signal.");
×
1479
                    break SUCCESS_EXIT_CODE;
×
1480
                }
1481
                Some(_) = rx_int.recv() => {
×
1482
                    info!("Detected SIGINT signal.");
×
1483
                    break SUCCESS_EXIT_CODE;
×
1484
                }
1485
                Some(_) = rx_quit.recv() => {
×
1486
                    info!("Detected SIGQUIT signal.");
×
1487
                    break SUCCESS_EXIT_CODE;
×
1488
                }
1489

1490
                // Handle incoming connections from peer
1491
                Ok((stream, peer_address)) = self.incoming_peer_listener.accept() => {
×
1492
                    // Return early if no incoming connections are accepted. Do
1493
                    // not send application-handshake.
1494
                    if self.global_state_lock.cli().disallow_all_incoming_peer_connections() {
×
1495
                        warn!("Got incoming connection despite not accepting any. Ignoring");
×
1496
                        continue;
×
1497
                    }
×
1498

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

1523
                // Handle messages from peer tasks
1524
                Some(msg) = peer_task_to_main_rx.recv() => {
×
1525
                    debug!("Received message sent to main task.");
×
1526
                    self.handle_peer_task_message(
×
1527
                        msg,
×
1528
                        &mut main_loop_state,
×
1529
                    )
×
1530
                    .await?
×
1531
                }
1532

1533
                // Handle messages from miner task
1534
                Some(main_message) = miner_to_main_rx.recv() => {
×
1535
                    let exit_code = self.handle_miner_task_message(main_message, &mut main_loop_state).await?;
×
1536

1537
                    if let Some(exit_code) = exit_code {
×
1538
                        break exit_code;
×
1539
                    }
×
1540

1541
                }
1542

1543
                // Handle the completion of mempool tx-update jobs after new block.
1544
                Some(ms_updated_transactions) = main_loop_state.update_mempool_receiver.recv() => {
×
1545
                    self.handle_updated_mempool_txs(ms_updated_transactions).await;
×
1546
                }
1547

1548
                // Handle messages from rpc server task
1549
                Some(rpc_server_message) = rpc_server_to_main_rx.recv() => {
×
1550
                    let shutdown_after_execution = self.handle_rpc_server_message(rpc_server_message.clone(), &mut main_loop_state).await?;
×
1551
                    if shutdown_after_execution {
×
1552
                        break SUCCESS_EXIT_CODE
×
1553
                    }
×
1554
                }
1555

1556
                // Handle peer discovery
NEW
1557
                _ = peer_discovery_interval.tick() => {
×
NEW
1558
                    log_slow_scope!(fn_name!() + "::select::peer_discovery_interval");
×
1559

×
NEW
1560
                    // Check number of peers we are connected to and connect to
×
NEW
1561
                    // more peers if needed.
×
1562
                    debug!("Timer: peer discovery job");
×
1563
                    self.prune_peers().await?;
×
1564
                    self.reconnect(&mut main_loop_state).await?;
×
1565
                    self.discover_peers(&mut main_loop_state).await?;
×
1566
                }
1567

1568
                // Handle synchronization (i.e. batch-downloading of blocks)
NEW
1569
                _ = block_sync_interval.tick() => {
×
NEW
1570
                    log_slow_scope!(fn_name!() + "::select::block_sync_interval");
×
1571

×
1572
                    trace!("Timer: block-synchronization job");
×
1573
                    self.block_sync(&mut main_loop_state).await?;
×
1574
                }
1575

1576
                // Clean up mempool: remove stale / too old transactions
NEW
1577
                _ = mempool_cleanup_interval.tick() => {
×
NEW
1578
                    log_slow_scope!(fn_name!() + "::select::mempool_cleanup_interval");
×
1579

×
1580
                    debug!("Timer: mempool-cleaner job");
×
NEW
1581
                    self
×
NEW
1582
                        .global_state_lock
×
NEW
1583
                        .lock_guard_mut()
×
NEW
1584
                        .await
×
NEW
1585
                        .mempool_prune_stale_transactions()
×
NEW
1586
                        .await;
×
1587
                }
1588

1589
                // Clean up incoming UTXO notifications: remove stale / too old
1590
                // UTXO notifications from pool
NEW
1591
                _ = utxo_notification_cleanup_interval.tick() => {
×
NEW
1592
                    log_slow_scope!(fn_name!() + "::select::utxo_notification_cleanup_interval");
×
1593

×
1594
                    debug!("Timer: UTXO notification pool cleanup job");
×
1595

1596
                    // Danger: possible loss of funds.
1597
                    //
1598
                    // See description of prune_stale_expected_utxos().
1599
                    //
1600
                    // This call is disabled until such time as a thorough
1601
                    // evaluation and perhaps reimplementation determines that
1602
                    // it can be called safely without possible loss of funds.
1603
                    // self.global_state_lock.lock_mut(|s| s.wallet_state.prune_stale_expected_utxos()).await;
1604
                }
1605

1606
                // Handle membership proof resynchronization
NEW
1607
                _ = mp_resync_interval.tick() => {
×
NEW
1608
                    log_slow_scope!(fn_name!() + "::select::mp_resync_interval");
×
1609

×
1610
                    debug!("Timer: Membership proof resync job");
×
1611
                    self.global_state_lock.resync_membership_proofs().await?;
×
1612
                }
1613

1614
                // run the proof upgrader
NEW
1615
                _ = tx_proof_upgrade_interval.tick() => {
×
NEW
1616
                    log_slow_scope!(fn_name!() + "::select::tx_proof_upgrade_interval");
×
1617

×
1618
                    trace!("Timer: tx-proof-upgrader");
×
1619
                    self.proof_upgrader(&mut main_loop_state).await?;
×
1620
                }
1621

1622
            }
1623
        };
1624

1625
        self.graceful_shutdown(main_loop_state.task_handles).await?;
×
1626
        info!("Shutdown completed.");
×
1627

1628
        Ok(exit_code)
×
1629
    }
×
1630

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

1647
                // insert transaction into mempool
1648
                self.global_state_lock
×
1649
                    .lock_guard_mut()
×
1650
                    .await
×
1651
                    .mempool_insert(*transaction.clone(), TransactionOrigin::Own)
×
1652
                    .await;
×
1653

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

1666
                    let vm_job_queue = self.global_state_lock.vm_job_queue().clone();
×
1667

×
1668
                    let proving_capability = self.global_state_lock.cli().proving_capability();
×
1669
                    let upgrade_job =
×
1670
                        UpgradeJob::from_primitive_witness(proving_capability, primitive_witness);
×
1671

×
1672
                    // note: handle_upgrade() hands off proving to the
×
1673
                    //       triton-vm job queue and waits for job completion.
×
1674
                    // note: handle_upgrade() broadcasts to peers on success.
×
1675

×
1676
                    let global_state_lock_clone = self.global_state_lock.clone();
×
1677
                    let main_to_peer_broadcast_tx_clone = self.main_to_peer_broadcast_tx.clone();
×
1678
                    let _proof_upgrader_task = tokio::task::Builder::new()
×
1679
                        .name("proof_upgrader")
×
1680
                        .spawn(async move {
×
1681
                        upgrade_job
×
1682
                            .handle_upgrade(
×
1683
                                &vm_job_queue,
×
1684
                                TransactionOrigin::Own,
×
1685
                                true,
×
1686
                                global_state_lock_clone,
×
1687
                                main_to_peer_broadcast_tx_clone,
×
1688
                            )
×
1689
                            .await
×
1690
                    })?;
×
1691

1692
                    // main_loop_state.proof_upgrader_task = Some(proof_upgrader_task);
1693
                    // If transaction could not be shared immediately because
1694
                    // it contains secret data, upgrade its proof-type.
1695
                }
1696

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

1727
                self.handle_self_guessed_block(main_loop_state, new_block)
×
1728
                    .await?;
×
1729
                Ok(false)
×
1730
            }
1731
            RPCServerToMain::PauseMiner => {
1732
                info!("Received RPC request to stop miner");
×
1733

1734
                self.main_to_miner_tx.send(MainToMiner::StopMining);
×
1735
                Ok(false)
×
1736
            }
1737
            RPCServerToMain::RestartMiner => {
1738
                info!("Received RPC request to start miner");
×
1739
                self.main_to_miner_tx.send(MainToMiner::StartMining);
×
1740
                Ok(false)
×
1741
            }
1742
            RPCServerToMain::Shutdown => {
1743
                info!("Received RPC shutdown request.");
×
1744

1745
                // shut down
1746
                Ok(true)
×
1747
            }
1748
        }
1749
    }
×
1750

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

1754
        // Stop mining
1755
        self.main_to_miner_tx.send(MainToMiner::Shutdown);
×
1756

×
1757
        // Send 'bye' message to all peers.
×
1758
        let _result = self
×
1759
            .main_to_peer_broadcast_tx
×
1760
            .send(MainToPeerTask::DisconnectAll());
×
1761
        debug!("sent bye");
×
1762

1763
        // Flush all databases
1764
        self.global_state_lock.flush_databases().await?;
×
1765

1766
        tokio::time::sleep(Duration::from_millis(50)).await;
×
1767

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

×
1771
        // wait for all to finish.
×
1772
        futures::future::join_all(task_handles).await;
×
1773

1774
        Ok(())
×
1775
    }
×
1776
}
1777

1778
#[cfg(test)]
1779
mod test {
1780
    use std::str::FromStr;
1781
    use std::time::UNIX_EPOCH;
1782

1783
    use tracing_test::traced_test;
1784

1785
    use super::*;
1786
    use crate::config_models::cli_args;
1787
    use crate::config_models::network::Network;
1788
    use crate::tests::shared::get_dummy_peer_incoming;
1789
    use crate::tests::shared::get_test_genesis_setup;
1790
    use crate::tests::shared::invalid_empty_block;
1791
    use crate::MINER_CHANNEL_CAPACITY;
1792

1793
    struct TestSetup {
1794
        peer_to_main_rx: mpsc::Receiver<PeerTaskToMain>,
1795
        miner_to_main_rx: mpsc::Receiver<MinerToMain>,
1796
        rpc_server_to_main_rx: mpsc::Receiver<RPCServerToMain>,
1797
        task_join_handles: Vec<JoinHandle<()>>,
1798
        main_loop_handler: MainLoopHandler,
1799
        main_to_peer_rx: broadcast::Receiver<MainToPeerTask>,
1800
    }
1801

1802
    async fn setup(num_init_peers_outgoing: u8, num_peers_incoming: u8) -> TestSetup {
8✔
1803
        const CHANNEL_CAPACITY_MINER_TO_MAIN: usize = 10;
1804

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

1827
        for i in 0..num_peers_incoming {
8✔
1828
            let peer_address = SocketAddr::from_str(&format!("255.254.253.{i}:8080")).unwrap();
5✔
1829
            state
5✔
1830
                .lock_guard_mut()
5✔
1831
                .await
5✔
1832
                .net
1833
                .peer_map
1834
                .insert(peer_address, get_dummy_peer_incoming(peer_address));
5✔
1835
        }
1836

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

8✔
1839
        let (main_to_miner_tx, _main_to_miner_rx) =
8✔
1840
            mpsc::channel::<MainToMiner>(MINER_CHANNEL_CAPACITY);
8✔
1841
        let (_miner_to_main_tx, miner_to_main_rx) =
8✔
1842
            mpsc::channel::<MinerToMain>(CHANNEL_CAPACITY_MINER_TO_MAIN);
8✔
1843
        let (_rpc_server_to_main_tx, rpc_server_to_main_rx) =
8✔
1844
            mpsc::channel::<RPCServerToMain>(CHANNEL_CAPACITY_MINER_TO_MAIN);
8✔
1845

8✔
1846
        let main_loop_handler = MainLoopHandler::new(
8✔
1847
            incoming_peer_listener,
8✔
1848
            state,
8✔
1849
            main_to_peer_tx,
8✔
1850
            peer_to_main_tx,
8✔
1851
            main_to_miner_tx,
8✔
1852
        );
8✔
1853

8✔
1854
        let task_join_handles = vec![];
8✔
1855

8✔
1856
        TestSetup {
8✔
1857
            miner_to_main_rx,
8✔
1858
            peer_to_main_rx,
8✔
1859
            rpc_server_to_main_rx,
8✔
1860
            task_join_handles,
8✔
1861
            main_loop_handler,
8✔
1862
            main_to_peer_rx,
8✔
1863
        }
8✔
1864
    }
8✔
1865

1866
    #[tokio::test]
1867
    async fn handle_self_guessed_block_new_tip() {
1✔
1868
        // A new tip is registered by main_loop. Verify correct state update.
1✔
1869
        let test_setup = setup(1, 0).await;
1✔
1870
        let TestSetup {
1✔
1871
            task_join_handles,
1✔
1872
            mut main_loop_handler,
1✔
1873
            mut main_to_peer_rx,
1✔
1874
            ..
1✔
1875
        } = test_setup;
1✔
1876
        let network = main_loop_handler.global_state_lock.cli().network;
1✔
1877
        let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
1878

1✔
1879
        let block1 = invalid_empty_block(&Block::genesis(network));
1✔
1880

1✔
1881
        assert!(
1✔
1882
            main_loop_handler
1✔
1883
                .global_state_lock
1✔
1884
                .lock_guard()
1✔
1885
                .await
1✔
1886
                .chain
1✔
1887
                .light_state()
1✔
1888
                .header()
1✔
1889
                .height
1✔
1890
                .is_genesis(),
1✔
1891
            "Tip must be genesis prior to handling of new block"
1✔
1892
        );
1✔
1893

1✔
1894
        let block1 = Box::new(block1);
1✔
1895
        main_loop_handler
1✔
1896
            .handle_self_guessed_block(&mut mutable_main_loop_state, block1.clone())
1✔
1897
            .await
1✔
1898
            .unwrap();
1✔
1899
        let new_block_height: u64 = 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
            .into();
1✔
1908
        assert_eq!(
1✔
1909
            1u64, new_block_height,
1✔
1910
            "Tip height must be 1 after handling of new block"
1✔
1911
        );
1✔
1912
        let msg_to_peer_loops = main_to_peer_rx.recv().await.unwrap();
1✔
1913
        if let MainToPeerTask::Block(block_to_peers) = msg_to_peer_loops {
1✔
1914
            assert_eq!(
1✔
1915
                block1, block_to_peers,
1✔
1916
                "Peer loops must have received block 1"
1✔
1917
            );
1✔
1918
        } else {
1✔
1919
            panic!("Must have sent block notification to peer loops")
1✔
1920
        }
1✔
1921
    }
1✔
1922

1923
    mod sync_mode {
1924
        use tasm_lib::twenty_first::util_types::mmr::mmr_accumulator::MmrAccumulator;
1925
        use test_strategy::proptest;
1926

1927
        use super::*;
1928
        use crate::tests::shared::get_dummy_socket_address;
1929

1930
        #[proptest]
256✔
1931
        fn batch_request_heights_prop(#[strategy(0u64..100_000_000_000)] own_height: u64) {
1✔
1932
            batch_request_heights_sanity(own_height);
1933
        }
1934

1935
        #[test]
1936
        fn batch_request_heights_unit() {
1✔
1937
            let own_height = 1_000_000u64;
1✔
1938
            batch_request_heights_sanity(own_height);
1✔
1939
        }
1✔
1940

1941
        fn batch_request_heights_sanity(own_height: u64) {
257✔
1942
            let heights = MainLoopHandler::batch_request_uca_candidate_heights(own_height.into());
257✔
1943

257✔
1944
            let mut heights_rev = heights.clone();
257✔
1945
            heights_rev.reverse();
257✔
1946
            assert!(
257✔
1947
                heights_rev.is_sorted(),
257✔
1948
                "Heights must be sorted from high-to-low"
×
1949
            );
1950

1951
            heights_rev.dedup();
257✔
1952
            assert_eq!(heights_rev.len(), heights.len(), "duplicates");
257✔
1953

1954
            assert_eq!(heights[0], own_height.into(), "starts with own tip height");
257✔
1955
            assert!(
257✔
1956
                heights.last().unwrap().is_genesis(),
257✔
1957
                "ends with genesis block"
×
1958
            );
1959
        }
257✔
1960

1961
        #[tokio::test]
1962
        #[traced_test]
×
1963
        async fn sync_mode_abandoned_on_global_timeout() {
1✔
1964
            let num_outgoing_connections = 0;
1✔
1965
            let num_incoming_connections = 0;
1✔
1966
            let test_setup = setup(num_outgoing_connections, num_incoming_connections).await;
1✔
1967
            let TestSetup {
1968
                task_join_handles,
1✔
1969
                mut main_loop_handler,
1✔
1970
                ..
1✔
1971
            } = test_setup;
1✔
1972

1✔
1973
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
1974

1✔
1975
            main_loop_handler
1✔
1976
                .block_sync(&mut mutable_main_loop_state)
1✔
1977
                .await
1✔
1978
                .expect("Must return OK when no sync mode is set");
1✔
1979

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

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

2021
            assert_eq!(
1✔
2022
                sync_start_time,
1✔
2023
                main_loop_handler
1✔
2024
                    .global_state_lock
1✔
2025
                    .lock_guard()
1✔
2026
                    .await
1✔
2027
                    .net
2028
                    .sync_anchor
2029
                    .as_ref()
1✔
2030
                    .unwrap()
1✔
2031
                    .updated,
2032
                "timestamp may not be updated without state change"
×
2033
            );
2034

2035
            // Mock that sync-mode has timed out
2036
            main_loop_handler = main_loop_handler.with_mocked_time(
1✔
2037
                SystemTime::now() + GLOBAL_SYNCHRONIZATION_TIMEOUT + Duration::from_secs(1),
1✔
2038
            );
1✔
2039

1✔
2040
            main_loop_handler
1✔
2041
                .block_sync(&mut mutable_main_loop_state)
1✔
2042
                .await
1✔
2043
                .expect("Must return OK when sync mode has timed out");
1✔
2044
            assert!(
1✔
2045
                main_loop_handler
1✔
2046
                    .global_state_lock
1✔
2047
                    .lock_guard()
1✔
2048
                    .await
1✔
2049
                    .net
1✔
2050
                    .sync_anchor
1✔
2051
                    .is_none(),
1✔
2052
                "Sync mode must be unset on timeout"
1✔
2053
            );
1✔
2054
        }
1✔
2055
    }
2056

2057
    mod proof_upgrader {
2058
        use super::*;
2059
        use crate::job_queue::triton_vm::TritonVmJobQueue;
2060
        use crate::models::blockchain::transaction::Transaction;
2061
        use crate::models::blockchain::transaction::TransactionProof;
2062
        use crate::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
2063
        use crate::models::peer::transfer_transaction::TransactionProofQuality;
2064
        use crate::models::proof_abstractions::timestamp::Timestamp;
2065
        use crate::models::state::wallet::utxo_notification::UtxoNotificationMedium;
2066

2067
        async fn tx_no_outputs(
1✔
2068
            global_state_lock: &GlobalStateLock,
1✔
2069
            tx_proof_type: TxProvingCapability,
1✔
2070
            fee: NativeCurrencyAmount,
1✔
2071
        ) -> Transaction {
1✔
2072
            let change_key = global_state_lock
1✔
2073
                .lock_guard()
1✔
2074
                .await
1✔
2075
                .wallet_state
2076
                .wallet_entropy
2077
                .nth_generation_spending_key_for_tests(0);
1✔
2078
            let in_seven_months = global_state_lock
1✔
2079
                .lock_guard()
1✔
2080
                .await
1✔
2081
                .chain
2082
                .light_state()
1✔
2083
                .header()
1✔
2084
                .timestamp
1✔
2085
                + Timestamp::months(7);
1✔
2086

2087
            let global_state = global_state_lock.lock_guard().await;
1✔
2088
            global_state
1✔
2089
                .create_transaction_with_prover_capability(
1✔
2090
                    vec![].into(),
1✔
2091
                    change_key.into(),
1✔
2092
                    UtxoNotificationMedium::OffChain,
1✔
2093
                    fee,
1✔
2094
                    in_seven_months,
1✔
2095
                    tx_proof_type,
1✔
2096
                    &TritonVmJobQueue::dummy(),
1✔
2097
                )
1✔
2098
                .await
1✔
2099
                .unwrap()
1✔
2100
                .0
1✔
2101
        }
1✔
2102

2103
        #[tokio::test]
2104
        #[traced_test]
×
2105
        async fn upgrade_proof_collection_to_single_proof_foreign_tx() {
1✔
2106
            let num_outgoing_connections = 0;
1✔
2107
            let num_incoming_connections = 0;
1✔
2108
            let test_setup = setup(num_outgoing_connections, num_incoming_connections).await;
1✔
2109
            let TestSetup {
2110
                peer_to_main_rx,
1✔
2111
                miner_to_main_rx,
1✔
2112
                rpc_server_to_main_rx,
1✔
2113
                task_join_handles,
1✔
2114
                mut main_loop_handler,
1✔
2115
                mut main_to_peer_rx,
1✔
2116
            } = test_setup;
1✔
2117

1✔
2118
            // Force instance to create SingleProofs, otherwise CI and other
1✔
2119
            // weak machines fail.
1✔
2120
            let mocked_cli = cli_args::Args {
1✔
2121
                tx_proving_capability: Some(TxProvingCapability::SingleProof),
1✔
2122
                tx_proof_upgrade_interval: 100, // seconds
1✔
2123
                ..Default::default()
1✔
2124
            };
1✔
2125

1✔
2126
            main_loop_handler
1✔
2127
                .global_state_lock
1✔
2128
                .set_cli(mocked_cli)
1✔
2129
                .await;
1✔
2130
            let mut main_loop_handler = main_loop_handler.with_mocked_time(SystemTime::now());
1✔
2131
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
2132

1✔
2133
            assert!(
1✔
2134
                main_loop_handler
1✔
2135
                    .proof_upgrader(&mut mutable_main_loop_state)
1✔
2136
                    .await
1✔
2137
                    .is_ok(),
1✔
2138
                "Scheduled task returns OK when run on empty mempool"
×
2139
            );
2140

2141
            let fee = NativeCurrencyAmount::coins(1);
1✔
2142
            let proof_collection_tx = tx_no_outputs(
1✔
2143
                &main_loop_handler.global_state_lock,
1✔
2144
                TxProvingCapability::ProofCollection,
1✔
2145
                fee,
1✔
2146
            )
1✔
2147
            .await;
1✔
2148

2149
            main_loop_handler
1✔
2150
                .global_state_lock
1✔
2151
                .lock_guard_mut()
1✔
2152
                .await
1✔
2153
                .mempool_insert(proof_collection_tx.clone(), TransactionOrigin::Foreign)
1✔
2154
                .await;
1✔
2155

2156
            assert!(
1✔
2157
                main_loop_handler
1✔
2158
                    .proof_upgrader(&mut mutable_main_loop_state)
1✔
2159
                    .await
1✔
2160
                    .is_ok(),
1✔
2161
                "Scheduled task returns OK when it's not yet time to upgrade"
×
2162
            );
2163

2164
            assert!(
1✔
2165
                matches!(
×
2166
                    main_loop_handler
1✔
2167
                        .global_state_lock
1✔
2168
                        .lock_guard()
1✔
2169
                        .await
1✔
2170
                        .mempool
2171
                        .get(proof_collection_tx.kernel.txid())
1✔
2172
                        .unwrap()
1✔
2173
                        .proof,
2174
                    TransactionProof::ProofCollection(_)
2175
                ),
2176
                "Proof in mempool must still be of type proof collection"
×
2177
            );
2178

2179
            // Mock that enough time has passed to perform the upgrade. Then
2180
            // perform the upgrade.
2181
            let mut main_loop_handler =
1✔
2182
                main_loop_handler.with_mocked_time(SystemTime::now() + Duration::from_secs(300));
1✔
2183
            assert!(
1✔
2184
                main_loop_handler
1✔
2185
                    .proof_upgrader(&mut mutable_main_loop_state)
1✔
2186
                    .await
1✔
2187
                    .is_ok(),
1✔
2188
                "Scheduled task must return OK when it's time to upgrade"
×
2189
            );
2190

2191
            // Wait for upgrade task to finish.
2192
            let handle = mutable_main_loop_state.proof_upgrader_task.unwrap().await;
1✔
2193
            assert!(
1✔
2194
                handle.is_ok(),
1✔
2195
                "Proof-upgrade task must finish successfully."
×
2196
            );
2197

2198
            // At this point there should be one transaction in the mempool,
2199
            // which is (if all is well) the merger of the ProofCollection
2200
            // transaction inserted above and one of the upgrader's fee
2201
            // gobblers. The point is that this transaction is a SingleProof
2202
            // transaction, so test that.
2203

2204
            let (merged_txid, _) = main_loop_handler
1✔
2205
                .global_state_lock
1✔
2206
                .lock_guard()
1✔
2207
                .await
1✔
2208
                .mempool
2209
                .get_sorted_iter()
1✔
2210
                .next_back()
1✔
2211
                .expect("mempool should contain one item here");
1✔
2212

1✔
2213
            assert!(
1✔
2214
                matches!(
×
2215
                    main_loop_handler
1✔
2216
                        .global_state_lock
1✔
2217
                        .lock_guard()
1✔
2218
                        .await
1✔
2219
                        .mempool
2220
                        .get(merged_txid)
1✔
2221
                        .unwrap()
1✔
2222
                        .proof,
2223
                    TransactionProof::SingleProof(_)
2224
                ),
2225
                "Proof in mempool must now be of type single proof"
×
2226
            );
2227

2228
            match main_to_peer_rx.recv().await {
1✔
2229
                Ok(MainToPeerTask::TransactionNotification(tx_noti)) => {
1✔
2230
                    assert_eq!(merged_txid, tx_noti.txid);
1✔
2231
                    assert_eq!(TransactionProofQuality::SingleProof, tx_noti.proof_quality);
1✔
2232
                },
2233
                other => panic!("Must have sent transaction notification to peer loop after successful proof upgrade. Got:\n{other:?}"),
×
2234
            }
2235

2236
            // These values are kept alive as the transmission-counterpart will
2237
            // otherwise fail on `send`.
2238
            drop(peer_to_main_rx);
1✔
2239
            drop(miner_to_main_rx);
1✔
2240
            drop(rpc_server_to_main_rx);
1✔
2241
            drop(main_to_peer_rx);
1✔
2242
        }
1✔
2243
    }
2244

2245
    mod peer_discovery {
2246
        use super::*;
2247

2248
        #[tokio::test]
2249
        #[traced_test]
×
2250
        async fn prune_peers_too_many_connections() {
1✔
2251
            let num_init_peers_outgoing = 10;
1✔
2252
            let num_init_peers_incoming = 4;
1✔
2253
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2254
            let TestSetup {
2255
                mut main_to_peer_rx,
1✔
2256
                mut main_loop_handler,
1✔
2257
                ..
1✔
2258
            } = test_setup;
1✔
2259

1✔
2260
            let mocked_cli = cli_args::Args {
1✔
2261
                max_num_peers: num_init_peers_outgoing as usize,
1✔
2262
                ..Default::default()
1✔
2263
            };
1✔
2264

1✔
2265
            main_loop_handler
1✔
2266
                .global_state_lock
1✔
2267
                .set_cli(mocked_cli)
1✔
2268
                .await;
1✔
2269

2270
            main_loop_handler.prune_peers().await.unwrap();
1✔
2271
            assert_eq!(4, main_to_peer_rx.len());
1✔
2272
            for _ in 0..4 {
5✔
2273
                let peer_msg = main_to_peer_rx.recv().await.unwrap();
4✔
2274
                assert!(matches!(peer_msg, MainToPeerTask::Disconnect(_)))
4✔
2275
            }
1✔
2276
        }
1✔
2277

2278
        #[tokio::test]
2279
        #[traced_test]
×
2280
        async fn prune_peers_not_too_many_connections() {
1✔
2281
            let num_init_peers_outgoing = 10;
1✔
2282
            let num_init_peers_incoming = 1;
1✔
2283
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2284
            let TestSetup {
2285
                main_to_peer_rx,
1✔
2286
                mut main_loop_handler,
1✔
2287
                ..
1✔
2288
            } = test_setup;
1✔
2289

1✔
2290
            let mocked_cli = cli_args::Args {
1✔
2291
                max_num_peers: 200,
1✔
2292
                ..Default::default()
1✔
2293
            };
1✔
2294

1✔
2295
            main_loop_handler
1✔
2296
                .global_state_lock
1✔
2297
                .set_cli(mocked_cli)
1✔
2298
                .await;
1✔
2299

2300
            main_loop_handler.prune_peers().await.unwrap();
1✔
2301
            assert!(main_to_peer_rx.is_empty());
1✔
2302
        }
1✔
2303

2304
        #[tokio::test]
2305
        #[traced_test]
1✔
2306
        async fn skip_peer_discovery_if_peer_limit_is_exceeded() {
1✔
2307
            let num_init_peers_outgoing = 2;
1✔
2308
            let num_init_peers_incoming = 0;
1✔
2309
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2310
            let TestSetup {
2311
                task_join_handles,
1✔
2312
                mut main_loop_handler,
1✔
2313
                ..
1✔
2314
            } = test_setup;
1✔
2315

1✔
2316
            let mocked_cli = cli_args::Args {
1✔
2317
                max_num_peers: 0,
1✔
2318
                ..Default::default()
1✔
2319
            };
1✔
2320
            main_loop_handler
1✔
2321
                .global_state_lock
1✔
2322
                .set_cli(mocked_cli)
1✔
2323
                .await;
1✔
2324
            main_loop_handler
1✔
2325
                .discover_peers(&mut MutableMainLoopState::new(task_join_handles))
1✔
2326
                .await
1✔
2327
                .unwrap();
1✔
2328

1✔
2329
            assert!(logs_contain("Skipping peer discovery."));
1✔
2330
        }
1✔
2331

2332
        #[tokio::test]
2333
        #[traced_test]
1✔
2334
        async fn performs_peer_discovery_on_few_connections() {
1✔
2335
            let num_init_peers_outgoing = 2;
1✔
2336
            let num_init_peers_incoming = 0;
1✔
2337
            let TestSetup {
2338
                task_join_handles,
1✔
2339
                mut main_loop_handler,
1✔
2340
                mut main_to_peer_rx,
1✔
2341
                peer_to_main_rx: _keep_channel_open,
1✔
2342
                ..
2343
            } = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2344

2345
            // Set CLI to attempt to make more connections
2346
            let mocked_cli = cli_args::Args {
1✔
2347
                max_num_peers: 10,
1✔
2348
                ..Default::default()
1✔
2349
            };
1✔
2350
            main_loop_handler
1✔
2351
                .global_state_lock
1✔
2352
                .set_cli(mocked_cli)
1✔
2353
                .await;
1✔
2354
            main_loop_handler
1✔
2355
                .discover_peers(&mut MutableMainLoopState::new(task_join_handles))
1✔
2356
                .await
1✔
2357
                .unwrap();
1✔
2358

1✔
2359
            let peer_discovery_sent_messages_on_peer_channel = main_to_peer_rx.try_recv().is_ok();
1✔
2360
            assert!(peer_discovery_sent_messages_on_peer_channel);
1✔
2361
            assert!(logs_contain("Performing peer discovery"));
1✔
2362
        }
1✔
2363
    }
2364

2365
    #[test]
2366
    fn older_systemtime_ranks_first() {
1✔
2367
        let start = UNIX_EPOCH;
1✔
2368
        let other = UNIX_EPOCH + Duration::from_secs(1000);
1✔
2369
        let mut instants = [start, other];
1✔
2370

1✔
2371
        assert_eq!(
1✔
2372
            start,
1✔
2373
            instants.iter().copied().min_by(|l, r| l.cmp(r)).unwrap()
1✔
2374
        );
1✔
2375

2376
        instants.reverse();
1✔
2377

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

2385
        use rand::Rng;
2386

2387
        use super::*;
2388
        use crate::models::peer::PeerMessage;
2389
        use crate::models::peer::TransferConnectionStatus;
2390
        use crate::tests::shared::get_dummy_peer_connection_data_genesis;
2391
        use crate::tests::shared::to_bytes;
2392

2393
        #[tokio::test]
2394
        #[traced_test]
×
2395
        async fn disconnect_from_oldest_peer_upon_connection_request() {
1✔
2396
            // Set up a node in bootstrapper mode and connected to a given
1✔
2397
            // number of peers, which is one less than the maximum. Initiate a
1✔
2398
            // connection request. Verify that the oldest of the existing
1✔
2399
            // connections is dropped.
1✔
2400

1✔
2401
            let network = Network::Main;
1✔
2402
            let num_init_peers_outgoing = 5;
1✔
2403
            let num_init_peers_incoming = 0;
1✔
2404
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2405
            let TestSetup {
2406
                mut peer_to_main_rx,
1✔
2407
                miner_to_main_rx: _,
1✔
2408
                rpc_server_to_main_rx: _,
1✔
2409
                task_join_handles,
1✔
2410
                mut main_loop_handler,
1✔
2411
                mut main_to_peer_rx,
1✔
2412
            } = test_setup;
1✔
2413

1✔
2414
            let mocked_cli = cli_args::Args {
1✔
2415
                max_num_peers: usize::from(num_init_peers_outgoing) + 1,
1✔
2416
                bootstrap: true,
1✔
2417
                network,
1✔
2418
                ..Default::default()
1✔
2419
            };
1✔
2420
            main_loop_handler
1✔
2421
                .global_state_lock
1✔
2422
                .set_cli(mocked_cli)
1✔
2423
                .await;
1✔
2424

2425
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
2426

1✔
2427
            // check sanity: at startup, we are connected to the initial number of peers
1✔
2428
            assert_eq!(
1✔
2429
                usize::from(num_init_peers_outgoing),
1✔
2430
                main_loop_handler
1✔
2431
                    .global_state_lock
1✔
2432
                    .lock_guard()
1✔
2433
                    .await
1✔
2434
                    .net
2435
                    .peer_map
2436
                    .len()
1✔
2437
            );
2438

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

2459
            // compute which peer will be dropped, for later reference
2460
            let expected_drop_peer_socket_address = main_loop_handler
1✔
2461
                .global_state_lock
1✔
2462
                .lock_guard()
1✔
2463
                .await
1✔
2464
                .net
2465
                .peer_map
2466
                .iter()
1✔
2467
                .min_by(|l, r| {
4✔
2468
                    l.1.connection_established()
4✔
2469
                        .cmp(&r.1.connection_established())
4✔
2470
                })
4✔
2471
                .map(|(socket_address, _peer_info)| socket_address)
1✔
2472
                .copied()
1✔
2473
                .unwrap();
1✔
2474

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

2529
            // `answer_peer_wrapper` should send a
2530
            // `DisconnectFromLongestLivedPeer` message to main
2531
            let peer_to_main_message = peer_to_main_rx.recv().await.unwrap();
1✔
2532
            assert!(matches!(
1✔
2533
                peer_to_main_message,
1✔
2534
                PeerTaskToMain::DisconnectFromLongestLivedPeer,
2535
            ));
2536

2537
            // process this message
2538
            main_loop_handler
1✔
2539
                .handle_peer_task_message(peer_to_main_message, &mut mutable_main_loop_state)
1✔
2540
                .await
1✔
2541
                .unwrap();
1✔
2542

2543
            // main loop should send a `Disconnect` message
2544
            let main_to_peers_message = main_to_peer_rx.recv().await.unwrap();
1✔
2545
            let MainToPeerTask::Disconnect(observed_drop_peer_socket_address) =
1✔
2546
                main_to_peers_message
1✔
2547
            else {
2548
                panic!("Expected disconnect, got {main_to_peers_message:?}");
×
2549
            };
2550

2551
            // matched observed droppee against expectation
2552
            assert_eq!(
1✔
2553
                expected_drop_peer_socket_address,
1✔
2554
                observed_drop_peer_socket_address,
1✔
2555
            );
1✔
2556
            println!("Dropped connection with {expected_drop_peer_socket_address}.");
1✔
2557

1✔
2558
            // don't forget to terminate the peer task, which is still running
1✔
2559
            incoming_peer_task_handle.abort();
1✔
2560
        }
1✔
2561
    }
2562
}
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