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

Neptune-Crypto / neptune-core / 13935087865

18 Mar 2025 10:51PM UTC coverage: 84.269% (-0.01%) from 84.279%
13935087865

push

github

Sword-Smith
perf: Reduce time write-lock is held on new transaction

I'm seeing some hanging when new incoming transactions are received. So
let's reduce the time the lock is held as much as possible.

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

7 existing lines in 4 files now uncovered.

50751 of 60225 relevant lines covered (84.27%)

175101.21 hits per line

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

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

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

59
const PEER_DISCOVERY_INTERVAL_IN_SECONDS: u64 = 120;
60
const SYNC_REQUEST_INTERVAL_IN_SECONDS: u64 = 3;
61
const MEMPOOL_PRUNE_INTERVAL_IN_SECS: u64 = 30 * 60; // 30mins
62
const MP_RESYNC_INTERVAL_IN_SECS: u64 = 59;
63
const EXPECTED_UTXOS_PRUNE_INTERVAL_IN_SECS: u64 = 19 * 60; // 19 mins
64

65
/// Interval for when transaction-upgrade checker is run. Note that this does
66
/// *not* define how often a transaction-proof upgrade is actually performed.
67
/// Only how often we check if we're ready to perform an upgrade.
68
const TRANSACTION_UPGRADE_CHECK_INTERVAL_IN_SECONDS: u64 = 60; // 1 minute
69

70
const SANCTION_PEER_TIMEOUT_FACTOR: u64 = 40;
71

72
/// Number of seconds within which an individual peer is expected to respond
73
/// to a synchronization request.
74
const INDIVIDUAL_PEER_SYNCHRONIZATION_TIMEOUT_IN_SECONDS: u64 =
75
    SANCTION_PEER_TIMEOUT_FACTOR * SYNC_REQUEST_INTERVAL_IN_SECONDS;
76

77
/// Number of seconds that a synchronization may run without any progress.
78
const GLOBAL_SYNCHRONIZATION_TIMEOUT_IN_SECONDS: u64 =
79
    INDIVIDUAL_PEER_SYNCHRONIZATION_TIMEOUT_IN_SECONDS * 4;
80

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

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

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

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

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

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

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

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

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

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

137
    /// A list of joinhandles to spawned tasks.
138
    task_handles: Vec<JoinHandle<()>>,
139

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

143
    /// A joinhandle to a task running the update of the mempool transactions.
144
    update_mempool_txs_handle: Option<JoinHandle<()>>,
145

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
539
                let new_block = new_block_info.block;
×
540

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

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

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

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

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

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

601
        Ok(None)
×
602
    }
×
603

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

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

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

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

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

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

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

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

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

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

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

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

698
                    update_jobs
×
699
                };
×
700

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1016
        Ok(())
×
1017
    }
×
1018

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

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

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

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

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

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

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

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

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

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

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

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

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

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

258✔
1127
        ret
258✔
1128
    }
258✔
1129

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

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

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

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

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

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

1172
            let peers_to_punish = main_loop_state
1✔
1173
                .sync_state
1✔
1174
                .get_potential_peers_for_sync_request(own_cumulative_pow);
1✔
1175

1176
            for peer in peers_to_punish {
2✔
1177
                self.main_to_peer_broadcast_tx
1✔
1178
                    .send(MainToPeerTask::PeerSynchronizationTimeout(peer))?;
1✔
1179
            }
1180

1181
            return Ok(());
1✔
1182
        }
1✔
1183

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

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

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

1✔
1199
        // Create the next request from the reported
1✔
1200
        info!("Creating new sync request");
1✔
1201

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

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

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

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

1✔
1257
        Ok(())
1✔
1258
    }
3✔
1259

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

1289
        trace!("Running proof upgrader scheduled task");
3✔
1290

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

1✔
1302
            debug!("Attempting to run transaction-proof-upgrade");
1✔
1303

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

1311
            (upgrade_candidate, tx_origin)
1✔
1312
        };
1✔
1313

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

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

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

1344
        main_loop_state.proof_upgrader_task = Some(proof_upgrader_task);
1✔
1345

1✔
1346
        Ok(())
1✔
1347
    }
3✔
1348

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

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

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

×
1400
        // Set peer discovery to run every N seconds. All timers must be reset
×
1401
        // every time they have run.
×
1402
        let peer_discovery_timer_interval = Duration::from_secs(PEER_DISCOVERY_INTERVAL_IN_SECONDS);
×
1403
        let peer_discovery_timer = time::sleep(peer_discovery_timer_interval);
×
1404
        tokio::pin!(peer_discovery_timer);
×
1405

×
1406
        // Set synchronization to run every M seconds.
×
1407
        let block_sync_interval = Duration::from_secs(SYNC_REQUEST_INTERVAL_IN_SECONDS);
×
1408
        let block_sync_timer = time::sleep(block_sync_interval);
×
1409
        tokio::pin!(block_sync_timer);
×
1410

×
1411
        // Set removal of transactions from mempool.
×
1412
        let mempool_cleanup_interval = Duration::from_secs(MEMPOOL_PRUNE_INTERVAL_IN_SECS);
×
1413
        let mempool_cleanup_timer = time::sleep(mempool_cleanup_interval);
×
1414
        tokio::pin!(mempool_cleanup_timer);
×
1415

×
1416
        // Set removal of stale notifications for incoming UTXOs.
×
1417
        let utxo_notification_cleanup_interval =
×
1418
            Duration::from_secs(EXPECTED_UTXOS_PRUNE_INTERVAL_IN_SECS);
×
1419
        let utxo_notification_cleanup_timer = time::sleep(utxo_notification_cleanup_interval);
×
1420
        tokio::pin!(utxo_notification_cleanup_timer);
×
1421

×
1422
        // Set restoration of membership proofs to run every Q seconds.
×
1423
        let mp_resync_interval = Duration::from_secs(MP_RESYNC_INTERVAL_IN_SECS);
×
1424
        let mp_resync_timer = time::sleep(mp_resync_interval);
×
1425
        tokio::pin!(mp_resync_timer);
×
1426

×
1427
        // Set transasction-proof-upgrade-checker to run every R secnods.
×
1428
        let tx_proof_upgrade_interval =
×
1429
            Duration::from_secs(TRANSACTION_UPGRADE_CHECK_INTERVAL_IN_SECONDS);
×
1430
        let tx_proof_upgrade_timer = time::sleep(tx_proof_upgrade_interval);
×
1431
        tokio::pin!(tx_proof_upgrade_timer);
×
1432

×
1433
        // Spawn tasks to monitor for SIGTERM, SIGINT, and SIGQUIT. These
×
1434
        // signals are only used on Unix systems.
×
1435
        let (tx_term, mut rx_term): (mpsc::Sender<()>, mpsc::Receiver<()>) =
×
1436
            tokio::sync::mpsc::channel(2);
×
1437
        let (tx_int, mut rx_int): (mpsc::Sender<()>, mpsc::Receiver<()>) =
×
1438
            tokio::sync::mpsc::channel(2);
×
1439
        let (tx_quit, mut rx_quit): (mpsc::Sender<()>, mpsc::Receiver<()>) =
×
1440
            tokio::sync::mpsc::channel(2);
×
1441
        #[cfg(unix)]
1442
        {
×
1443
            use tokio::signal::unix::signal;
×
1444
            use tokio::signal::unix::SignalKind;
×
1445

1446
            // Monitor for SIGTERM
1447
            let mut sigterm = signal(SignalKind::terminate())?;
×
1448
            tokio::task::Builder::new()
×
1449
                .name("sigterm_handler")
×
1450
                .spawn(async move {
×
1451
                    if sigterm.recv().await.is_some() {
×
1452
                        info!("Received SIGTERM");
×
1453
                        tx_term.send(()).await.unwrap();
×
1454
                    }
×
1455
                })?;
×
1456

1457
            // Monitor for SIGINT
1458
            let mut sigint = signal(SignalKind::interrupt())?;
×
1459
            tokio::task::Builder::new()
×
1460
                .name("sigint_handler")
×
1461
                .spawn(async move {
×
1462
                    if sigint.recv().await.is_some() {
×
1463
                        info!("Received SIGINT");
×
1464
                        tx_int.send(()).await.unwrap();
×
1465
                    }
×
1466
                })?;
×
1467

1468
            // Monitor for SIGQUIT
1469
            let mut sigquit = signal(SignalKind::quit())?;
×
1470
            tokio::task::Builder::new()
×
1471
                .name("sigquit_handler")
×
1472
                .spawn(async move {
×
1473
                    if sigquit.recv().await.is_some() {
×
1474
                        info!("Received SIGQUIT");
×
1475
                        tx_quit.send(()).await.unwrap();
×
1476
                    }
×
1477
                })?;
×
1478
        }
1479

1480
        #[cfg(not(unix))]
1481
        drop((tx_term, tx_int, tx_quit));
1482

1483
        let exit_code: i32 = loop {
×
1484
            select! {
×
1485
                Ok(()) = signal::ctrl_c() => {
×
1486
                    info!("Detected Ctrl+c signal.");
×
1487
                    break SUCCESS_EXIT_CODE;
×
1488
                }
1489

1490
                // Monitor for SIGTERM, SIGINT, and SIGQUIT.
1491
                Some(_) = rx_term.recv() => {
×
1492
                    info!("Detected SIGTERM signal.");
×
1493
                    break SUCCESS_EXIT_CODE;
×
1494
                }
1495
                Some(_) = rx_int.recv() => {
×
1496
                    info!("Detected SIGINT signal.");
×
1497
                    break SUCCESS_EXIT_CODE;
×
1498
                }
1499
                Some(_) = rx_quit.recv() => {
×
1500
                    info!("Detected SIGQUIT signal.");
×
1501
                    break SUCCESS_EXIT_CODE;
×
1502
                }
1503

1504
                // Handle incoming connections from peer
1505
                Ok((stream, peer_address)) = self.incoming_peer_listener.accept() => {
×
1506
                    // Return early if no incoming connections are accepted. Do
1507
                    // not send application-handshake.
1508
                    if self.global_state_lock.cli().disallow_all_incoming_peer_connections() {
×
1509
                        warn!("Got incoming connection despite not accepting any. Ignoring");
×
1510
                        continue;
×
1511
                    }
×
1512

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

1537
                // Handle messages from peer tasks
1538
                Some(msg) = peer_task_to_main_rx.recv() => {
×
1539
                    debug!("Received message sent to main task.");
×
1540
                    self.handle_peer_task_message(
×
1541
                        msg,
×
1542
                        &mut main_loop_state,
×
1543
                    )
×
1544
                    .await?
×
1545
                }
1546

1547
                // Handle messages from miner task
1548
                Some(main_message) = miner_to_main_rx.recv() => {
×
1549
                    let exit_code = self.handle_miner_task_message(main_message, &mut main_loop_state).await?;
×
1550

1551
                    if let Some(exit_code) = exit_code {
×
1552
                        break exit_code;
×
1553
                    }
×
1554

1555
                }
1556

1557
                // Handle the completion of mempool tx-update jobs after new block.
1558
                Some(ms_updated_transactions) = main_loop_state.update_mempool_receiver.recv() => {
×
1559
                    self.handle_updated_mempool_txs(ms_updated_transactions).await;
×
1560
                }
1561

1562
                // Handle messages from rpc server task
1563
                Some(rpc_server_message) = rpc_server_to_main_rx.recv() => {
×
1564
                    let shutdown_after_execution = self.handle_rpc_server_message(rpc_server_message.clone(), &mut main_loop_state).await?;
×
1565
                    if shutdown_after_execution {
×
1566
                        break SUCCESS_EXIT_CODE
×
1567
                    }
×
1568
                }
1569

1570
                // Handle peer discovery
1571
                _ = &mut peer_discovery_timer => {
×
1572
                    log_slow_scope!(fn_name!() + "::select::peer_discovery_timer");
×
1573

×
1574
                    // Check number of peers we are connected to and connect to more peers
×
1575
                    // if needed.
×
1576
                    debug!("Timer: peer discovery job");
×
1577
                    self.prune_peers().await?;
×
1578
                    self.reconnect(&mut main_loop_state).await?;
×
1579
                    self.discover_peers(&mut main_loop_state).await?;
×
1580

1581
                    // Reset the timer to run this branch again in N seconds
1582
                    peer_discovery_timer.as_mut().reset(tokio::time::Instant::now() + peer_discovery_timer_interval);
×
1583
                }
1584

1585
                // Handle synchronization (i.e. batch-downloading of blocks)
1586
                _ = &mut block_sync_timer => {
×
1587
                    log_slow_scope!(fn_name!() + "::select::block_sync_timer");
×
1588

×
1589
                    trace!("Timer: block-synchronization job");
×
1590
                    self.block_sync(&mut main_loop_state).await?;
×
1591

1592
                    // Reset the timer to run this branch again in M seconds
1593
                    block_sync_timer.as_mut().reset(tokio::time::Instant::now() + block_sync_interval);
×
1594
                }
1595

1596
                // Handle mempool cleanup, i.e. removing stale/too old txs from mempool
1597
                _ = &mut mempool_cleanup_timer => {
×
1598
                    log_slow_scope!(fn_name!() + "::select::mempool_cleanup_timer");
×
1599

×
1600
                    debug!("Timer: mempool-cleaner job");
×
1601
                    self.global_state_lock.lock_guard_mut().await.mempool_prune_stale_transactions().await;
×
1602

1603
                    // Reset the timer to run this branch again in P seconds
1604
                    mempool_cleanup_timer.as_mut().reset(tokio::time::Instant::now() + mempool_cleanup_interval);
×
1605
                }
1606

1607
                // Handle incoming UTXO notification cleanup, i.e. removing stale/too old UTXO notification from pool
1608
                _ = &mut utxo_notification_cleanup_timer => {
×
1609
                    log_slow_scope!(fn_name!() + "::select::utxo_notification_cleanup_timer");
×
1610

×
1611
                    debug!("Timer: UTXO notification pool cleanup job");
×
1612

1613
                    // Danger: possible loss of funds.
1614
                    //
1615
                    // See description of prune_stale_expected_utxos().
1616
                    //
1617
                    // This call is disabled until such time as a thorough
1618
                    // evaluation and perhaps reimplementation determines that
1619
                    // it can be called safely without possible loss of funds.
1620
                    // self.global_state_lock.lock_mut(|s| s.wallet_state.prune_stale_expected_utxos()).await;
1621

1622
                    utxo_notification_cleanup_timer.as_mut().reset(tokio::time::Instant::now() + utxo_notification_cleanup_interval);
×
1623
                }
1624

1625
                // Handle membership proof resynchronization
1626
                _ = &mut mp_resync_timer => {
×
1627
                    log_slow_scope!(fn_name!() + "::select::mp_resync_timer");
×
1628

×
1629
                    debug!("Timer: Membership proof resync job");
×
1630
                    self.global_state_lock.resync_membership_proofs().await?;
×
1631

1632
                    mp_resync_timer.as_mut().reset(tokio::time::Instant::now() + mp_resync_interval);
×
1633
                }
1634

1635
                // Check if it's time to run the proof upgrader
1636
                _ = &mut tx_proof_upgrade_timer => {
×
1637
                    log_slow_scope!(fn_name!() + "::select::tx_upgrade_proof_timer");
×
1638

×
1639
                    trace!("Timer: tx-proof-upgrader");
×
1640
                    self.proof_upgrader(&mut main_loop_state).await?;
×
1641

1642
                    tx_proof_upgrade_timer.as_mut().reset(tokio::time::Instant::now() + tx_proof_upgrade_interval);
×
1643
                }
1644

1645
            }
1646
        };
1647

1648
        self.graceful_shutdown(main_loop_state.task_handles).await?;
×
1649
        info!("Shutdown completed.");
×
1650

1651
        Ok(exit_code)
×
1652
    }
×
1653

1654
    /// Handle messages from the RPC server. Returns `true` iff the client should shut down
1655
    /// after handling this message.
1656
    async fn handle_rpc_server_message(
×
1657
        &mut self,
×
1658
        msg: RPCServerToMain,
×
1659
        main_loop_state: &mut MutableMainLoopState,
×
1660
    ) -> Result<bool> {
×
1661
        match msg {
×
1662
            RPCServerToMain::BroadcastTx(transaction) => {
×
1663
                debug!(
×
1664
                    "`main` received following transaction from RPC Server. {} inputs, {} outputs. Synced to mutator set hash: {}",
×
1665
                    transaction.kernel.inputs.len(),
×
1666
                    transaction.kernel.outputs.len(),
×
1667
                    transaction.kernel.mutator_set_hash
×
1668
                );
1669

1670
                // insert transaction into mempool
1671
                self.global_state_lock
×
1672
                    .lock_guard_mut()
×
1673
                    .await
×
1674
                    .mempool_insert(*transaction.clone(), TransactionOrigin::Own)
×
1675
                    .await;
×
1676

1677
                // Is this a transaction we can share with peers? If so, share
1678
                // it immediately.
1679
                if let Ok(notification) = transaction.as_ref().try_into() {
×
1680
                    self.main_to_peer_broadcast_tx
×
1681
                        .send(MainToPeerTask::TransactionNotification(notification))?;
×
1682
                } else {
1683
                    // Otherwise, upgrade its proof quality, and share it by
1684
                    // spinning up the proof upgrader.
1685
                    let TransactionProof::Witness(primitive_witness) = transaction.proof else {
×
1686
                        panic!("Expected Primitive witness. Got: {:?}", transaction.proof);
×
1687
                    };
1688

1689
                    let vm_job_queue = self.global_state_lock.vm_job_queue().clone();
×
1690

×
1691
                    let proving_capability = self.global_state_lock.cli().proving_capability();
×
1692
                    let upgrade_job =
×
1693
                        UpgradeJob::from_primitive_witness(proving_capability, primitive_witness);
×
1694

×
1695
                    // note: handle_upgrade() hands off proving to the
×
1696
                    //       triton-vm job queue and waits for job completion.
×
1697
                    // note: handle_upgrade() broadcasts to peers on success.
×
1698

×
1699
                    let global_state_lock_clone = self.global_state_lock.clone();
×
1700
                    let main_to_peer_broadcast_tx_clone = self.main_to_peer_broadcast_tx.clone();
×
1701
                    let _proof_upgrader_task = tokio::task::Builder::new()
×
1702
                        .name("proof_upgrader")
×
1703
                        .spawn(async move {
×
1704
                        upgrade_job
×
1705
                            .handle_upgrade(
×
1706
                                &vm_job_queue,
×
1707
                                TransactionOrigin::Own,
×
1708
                                true,
×
1709
                                global_state_lock_clone,
×
1710
                                main_to_peer_broadcast_tx_clone,
×
1711
                            )
×
1712
                            .await
×
1713
                    })?;
×
1714

1715
                    // main_loop_state.proof_upgrader_task = Some(proof_upgrader_task);
1716
                    // If transaction could not be shared immediately because
1717
                    // it contains secret data, upgrade its proof-type.
1718
                }
1719

1720
                // do not shut down
1721
                Ok(false)
×
1722
            }
1723
            RPCServerToMain::BroadcastMempoolTransactions => {
1724
                info!("Broadcasting transaction notifications for all shareable transactions in mempool");
×
1725
                let state = self.global_state_lock.lock_guard().await;
×
1726
                let txs = state.mempool.get_sorted_iter().collect_vec();
×
1727
                for (txid, _) in txs {
×
1728
                    // Since a read-lock is held over global state, the
1729
                    // transaction must exist in the mempool.
1730
                    let tx = state
×
1731
                        .mempool
×
1732
                        .get(txid)
×
1733
                        .expect("Transaction from iter must exist in mempool");
×
1734
                    let notification = TransactionNotification::try_from(tx);
×
1735
                    match notification {
×
1736
                        Ok(notification) => {
×
1737
                            self.main_to_peer_broadcast_tx
×
1738
                                .send(MainToPeerTask::TransactionNotification(notification))?;
×
1739
                        }
1740
                        Err(error) => {
×
1741
                            warn!("{error}");
×
1742
                        }
1743
                    };
1744
                }
1745
                Ok(false)
×
1746
            }
1747
            RPCServerToMain::ProofOfWorkSolution(new_block) => {
×
1748
                info!("Handling PoW solution from RPC call");
×
1749

1750
                self.handle_self_guessed_block(main_loop_state, new_block)
×
1751
                    .await?;
×
1752
                Ok(false)
×
1753
            }
1754
            RPCServerToMain::PauseMiner => {
1755
                info!("Received RPC request to stop miner");
×
1756

1757
                self.main_to_miner_tx.send(MainToMiner::StopMining);
×
1758
                Ok(false)
×
1759
            }
1760
            RPCServerToMain::RestartMiner => {
1761
                info!("Received RPC request to start miner");
×
1762
                self.main_to_miner_tx.send(MainToMiner::StartMining);
×
1763
                Ok(false)
×
1764
            }
1765
            RPCServerToMain::Shutdown => {
1766
                info!("Received RPC shutdown request.");
×
1767

1768
                // shut down
1769
                Ok(true)
×
1770
            }
1771
        }
1772
    }
×
1773

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

1777
        // Stop mining
1778
        self.main_to_miner_tx.send(MainToMiner::Shutdown);
×
1779

×
1780
        // Send 'bye' message to all peers.
×
1781
        let _result = self
×
1782
            .main_to_peer_broadcast_tx
×
1783
            .send(MainToPeerTask::DisconnectAll());
×
1784
        debug!("sent bye");
×
1785

1786
        // Flush all databases
1787
        self.global_state_lock.flush_databases().await?;
×
1788

1789
        tokio::time::sleep(Duration::from_millis(50)).await;
×
1790

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

×
1794
        // wait for all to finish.
×
1795
        futures::future::join_all(task_handles).await;
×
1796

1797
        Ok(())
×
1798
    }
×
1799
}
1800

1801
#[cfg(test)]
1802
mod test {
1803
    use std::str::FromStr;
1804
    use std::time::UNIX_EPOCH;
1805

1806
    use tracing_test::traced_test;
1807

1808
    use super::*;
1809
    use crate::config_models::cli_args;
1810
    use crate::config_models::network::Network;
1811
    use crate::tests::shared::get_dummy_peer_incoming;
1812
    use crate::tests::shared::get_test_genesis_setup;
1813
    use crate::tests::shared::invalid_empty_block;
1814
    use crate::MINER_CHANNEL_CAPACITY;
1815

1816
    struct TestSetup {
1817
        peer_to_main_rx: mpsc::Receiver<PeerTaskToMain>,
1818
        miner_to_main_rx: mpsc::Receiver<MinerToMain>,
1819
        rpc_server_to_main_rx: mpsc::Receiver<RPCServerToMain>,
1820
        task_join_handles: Vec<JoinHandle<()>>,
1821
        main_loop_handler: MainLoopHandler,
1822
        main_to_peer_rx: broadcast::Receiver<MainToPeerTask>,
1823
    }
1824

1825
    async fn setup(num_init_peers_outgoing: u8, num_peers_incoming: u8) -> TestSetup {
8✔
1826
        const CHANNEL_CAPACITY_MINER_TO_MAIN: usize = 10;
1827

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

1850
        for i in 0..num_peers_incoming {
8✔
1851
            let peer_address =
5✔
1852
                std::net::SocketAddr::from_str(&format!("255.254.253.{}:8080", i)).unwrap();
5✔
1853
            state
5✔
1854
                .lock_guard_mut()
5✔
1855
                .await
5✔
1856
                .net
1857
                .peer_map
1858
                .insert(peer_address, get_dummy_peer_incoming(peer_address));
5✔
1859
        }
1860

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

8✔
1863
        let (main_to_miner_tx, _main_to_miner_rx) =
8✔
1864
            mpsc::channel::<MainToMiner>(MINER_CHANNEL_CAPACITY);
8✔
1865
        let (_miner_to_main_tx, miner_to_main_rx) =
8✔
1866
            mpsc::channel::<MinerToMain>(CHANNEL_CAPACITY_MINER_TO_MAIN);
8✔
1867
        let (_rpc_server_to_main_tx, rpc_server_to_main_rx) =
8✔
1868
            mpsc::channel::<RPCServerToMain>(CHANNEL_CAPACITY_MINER_TO_MAIN);
8✔
1869

8✔
1870
        let main_loop_handler = MainLoopHandler::new(
8✔
1871
            incoming_peer_listener,
8✔
1872
            state,
8✔
1873
            main_to_peer_tx,
8✔
1874
            peer_to_main_tx,
8✔
1875
            main_to_miner_tx,
8✔
1876
        );
8✔
1877

8✔
1878
        let task_join_handles = vec![];
8✔
1879

8✔
1880
        TestSetup {
8✔
1881
            miner_to_main_rx,
8✔
1882
            peer_to_main_rx,
8✔
1883
            rpc_server_to_main_rx,
8✔
1884
            task_join_handles,
8✔
1885
            main_loop_handler,
8✔
1886
            main_to_peer_rx,
8✔
1887
        }
8✔
1888
    }
8✔
1889

1890
    #[tokio::test]
1891
    async fn handle_self_guessed_block_new_tip() {
1✔
1892
        // A new tip is registered by main_loop. Verify correct state update.
1✔
1893
        let test_setup = setup(1, 0).await;
1✔
1894
        let TestSetup {
1✔
1895
            task_join_handles,
1✔
1896
            mut main_loop_handler,
1✔
1897
            mut main_to_peer_rx,
1✔
1898
            ..
1✔
1899
        } = test_setup;
1✔
1900
        let network = main_loop_handler.global_state_lock.cli().network;
1✔
1901
        let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
1902

1✔
1903
        let block1 = invalid_empty_block(&Block::genesis(network));
1✔
1904

1✔
1905
        assert!(
1✔
1906
            main_loop_handler
1✔
1907
                .global_state_lock
1✔
1908
                .lock_guard()
1✔
1909
                .await
1✔
1910
                .chain
1✔
1911
                .light_state()
1✔
1912
                .header()
1✔
1913
                .height
1✔
1914
                .is_genesis(),
1✔
1915
            "Tip must be genesis prior to handling of new block"
1✔
1916
        );
1✔
1917

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

1947
    mod sync_mode {
1948
        use tasm_lib::twenty_first::util_types::mmr::mmr_accumulator::MmrAccumulator;
1949
        use test_strategy::proptest;
1950

1951
        use super::*;
1952
        use crate::tests::shared::get_dummy_socket_address;
1953

1954
        #[proptest]
256✔
1955
        fn batch_request_heights_prop(#[strategy(0u64..100_000_000_000)] own_height: u64) {
1✔
1956
            batch_request_heights_sanity(own_height);
1957
        }
1958

1959
        #[test]
1960
        fn batch_request_heights_unit() {
1✔
1961
            let own_height = 1_000_000u64;
1✔
1962
            batch_request_heights_sanity(own_height);
1✔
1963
        }
1✔
1964

1965
        fn batch_request_heights_sanity(own_height: u64) {
257✔
1966
            let heights = MainLoopHandler::batch_request_uca_candidate_heights(own_height.into());
257✔
1967

257✔
1968
            let mut heights_rev = heights.clone();
257✔
1969
            heights_rev.reverse();
257✔
1970
            assert!(
257✔
1971
                heights_rev.is_sorted(),
257✔
1972
                "Heights must be sorted from high-to-low"
×
1973
            );
1974

1975
            heights_rev.dedup();
257✔
1976
            assert_eq!(heights_rev.len(), heights.len(), "duplicates");
257✔
1977

1978
            assert_eq!(heights[0], own_height.into(), "starts with own tip height");
257✔
1979
            assert!(
257✔
1980
                heights.last().unwrap().is_genesis(),
257✔
1981
                "ends with genesis block"
×
1982
            );
1983
        }
257✔
1984

1985
        #[tokio::test]
1986
        #[traced_test]
×
1987
        async fn sync_mode_abandoned_on_global_timeout() {
1✔
1988
            let num_outgoing_connections = 0;
1✔
1989
            let num_incoming_connections = 0;
1✔
1990
            let test_setup = setup(num_outgoing_connections, num_incoming_connections).await;
1✔
1991
            let TestSetup {
1992
                task_join_handles,
1✔
1993
                mut main_loop_handler,
1✔
1994
                ..
1✔
1995
            } = test_setup;
1✔
1996

1✔
1997
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
1998

1✔
1999
            main_loop_handler
1✔
2000
                .block_sync(&mut mutable_main_loop_state)
1✔
2001
                .await
1✔
2002
                .expect("Must return OK when no sync mode is set");
1✔
2003

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

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

2045
            assert_eq!(
1✔
2046
                sync_start_time,
1✔
2047
                main_loop_handler
1✔
2048
                    .global_state_lock
1✔
2049
                    .lock_guard()
1✔
2050
                    .await
1✔
2051
                    .net
2052
                    .sync_anchor
2053
                    .as_ref()
1✔
2054
                    .unwrap()
1✔
2055
                    .updated,
2056
                "timestamp may not be updated without state change"
×
2057
            );
2058

2059
            // Mock that sync-mode has timed out
2060
            main_loop_handler = main_loop_handler.with_mocked_time(
1✔
2061
                SystemTime::now()
1✔
2062
                    + Duration::from_secs(GLOBAL_SYNCHRONIZATION_TIMEOUT_IN_SECONDS + 1),
1✔
2063
            );
1✔
2064

1✔
2065
            main_loop_handler
1✔
2066
                .block_sync(&mut mutable_main_loop_state)
1✔
2067
                .await
1✔
2068
                .expect("Must return OK when sync mode has timed out");
1✔
2069
            assert!(
1✔
2070
                main_loop_handler
1✔
2071
                    .global_state_lock
1✔
2072
                    .lock_guard()
1✔
2073
                    .await
1✔
2074
                    .net
1✔
2075
                    .sync_anchor
1✔
2076
                    .is_none(),
1✔
2077
                "Sync mode must be unset on timeout"
1✔
2078
            );
1✔
2079
        }
1✔
2080
    }
2081

2082
    mod proof_upgrader {
2083
        use super::*;
2084
        use crate::job_queue::triton_vm::TritonVmJobQueue;
2085
        use crate::models::blockchain::transaction::Transaction;
2086
        use crate::models::blockchain::transaction::TransactionProof;
2087
        use crate::models::blockchain::type_scripts::native_currency_amount::NativeCurrencyAmount;
2088
        use crate::models::peer::transfer_transaction::TransactionProofQuality;
2089
        use crate::models::proof_abstractions::timestamp::Timestamp;
2090
        use crate::models::state::wallet::utxo_notification::UtxoNotificationMedium;
2091

2092
        async fn tx_no_outputs(
1✔
2093
            global_state_lock: &GlobalStateLock,
1✔
2094
            tx_proof_type: TxProvingCapability,
1✔
2095
            fee: NativeCurrencyAmount,
1✔
2096
        ) -> Transaction {
1✔
2097
            let change_key = global_state_lock
1✔
2098
                .lock_guard()
1✔
2099
                .await
1✔
2100
                .wallet_state
2101
                .wallet_entropy
2102
                .nth_generation_spending_key_for_tests(0);
1✔
2103
            let in_seven_months = global_state_lock
1✔
2104
                .lock_guard()
1✔
2105
                .await
1✔
2106
                .chain
2107
                .light_state()
1✔
2108
                .header()
1✔
2109
                .timestamp
1✔
2110
                + Timestamp::months(7);
1✔
2111

2112
            let global_state = global_state_lock.lock_guard().await;
1✔
2113
            global_state
1✔
2114
                .create_transaction_with_prover_capability(
1✔
2115
                    vec![].into(),
1✔
2116
                    change_key.into(),
1✔
2117
                    UtxoNotificationMedium::OffChain,
1✔
2118
                    fee,
1✔
2119
                    in_seven_months,
1✔
2120
                    tx_proof_type,
1✔
2121
                    &TritonVmJobQueue::dummy(),
1✔
2122
                )
1✔
2123
                .await
1✔
2124
                .unwrap()
1✔
2125
                .0
1✔
2126
        }
1✔
2127

2128
        #[tokio::test]
2129
        #[traced_test]
×
2130
        async fn upgrade_proof_collection_to_single_proof_foreign_tx() {
1✔
2131
            let num_outgoing_connections = 0;
1✔
2132
            let num_incoming_connections = 0;
1✔
2133
            let test_setup = setup(num_outgoing_connections, num_incoming_connections).await;
1✔
2134
            let TestSetup {
2135
                peer_to_main_rx,
1✔
2136
                miner_to_main_rx,
1✔
2137
                rpc_server_to_main_rx,
1✔
2138
                task_join_handles,
1✔
2139
                mut main_loop_handler,
1✔
2140
                mut main_to_peer_rx,
1✔
2141
            } = test_setup;
1✔
2142

1✔
2143
            // Force instance to create SingleProofs, otherwise CI and other
1✔
2144
            // weak machines fail.
1✔
2145
            let mocked_cli = cli_args::Args {
1✔
2146
                tx_proving_capability: Some(TxProvingCapability::SingleProof),
1✔
2147
                tx_proof_upgrade_interval: 100, // seconds
1✔
2148
                ..Default::default()
1✔
2149
            };
1✔
2150

1✔
2151
            main_loop_handler
1✔
2152
                .global_state_lock
1✔
2153
                .set_cli(mocked_cli)
1✔
2154
                .await;
1✔
2155
            let mut main_loop_handler = main_loop_handler.with_mocked_time(SystemTime::now());
1✔
2156
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
2157

1✔
2158
            assert!(
1✔
2159
                main_loop_handler
1✔
2160
                    .proof_upgrader(&mut mutable_main_loop_state)
1✔
2161
                    .await
1✔
2162
                    .is_ok(),
1✔
2163
                "Scheduled task returns OK when run on empty mempool"
×
2164
            );
2165

2166
            let fee = NativeCurrencyAmount::coins(1);
1✔
2167
            let proof_collection_tx = tx_no_outputs(
1✔
2168
                &main_loop_handler.global_state_lock,
1✔
2169
                TxProvingCapability::ProofCollection,
1✔
2170
                fee,
1✔
2171
            )
1✔
2172
            .await;
1✔
2173

2174
            main_loop_handler
1✔
2175
                .global_state_lock
1✔
2176
                .lock_guard_mut()
1✔
2177
                .await
1✔
2178
                .mempool_insert(proof_collection_tx.clone(), TransactionOrigin::Foreign)
1✔
2179
                .await;
1✔
2180

2181
            assert!(
1✔
2182
                main_loop_handler
1✔
2183
                    .proof_upgrader(&mut mutable_main_loop_state)
1✔
2184
                    .await
1✔
2185
                    .is_ok(),
1✔
2186
                "Scheduled task returns OK when it's not yet time to upgrade"
×
2187
            );
2188

2189
            assert!(
1✔
2190
                matches!(
×
2191
                    main_loop_handler
1✔
2192
                        .global_state_lock
1✔
2193
                        .lock_guard()
1✔
2194
                        .await
1✔
2195
                        .mempool
2196
                        .get(proof_collection_tx.kernel.txid())
1✔
2197
                        .unwrap()
1✔
2198
                        .proof,
2199
                    TransactionProof::ProofCollection(_)
2200
                ),
2201
                "Proof in mempool must still be of type proof collection"
×
2202
            );
2203

2204
            // Mock that enough time has passed to perform the upgrade. Then
2205
            // perform the upgrade.
2206
            let mut main_loop_handler =
1✔
2207
                main_loop_handler.with_mocked_time(SystemTime::now() + Duration::from_secs(300));
1✔
2208
            assert!(
1✔
2209
                main_loop_handler
1✔
2210
                    .proof_upgrader(&mut mutable_main_loop_state)
1✔
2211
                    .await
1✔
2212
                    .is_ok(),
1✔
2213
                "Scheduled task must return OK when it's time to upgrade"
×
2214
            );
2215

2216
            // Wait for upgrade task to finish.
2217
            let handle = mutable_main_loop_state.proof_upgrader_task.unwrap().await;
1✔
2218
            assert!(
1✔
2219
                handle.is_ok(),
1✔
2220
                "Proof-upgrade task must finish successfully."
×
2221
            );
2222

2223
            // At this point there should be one transaction in the mempool,
2224
            // which is (if all is well) the merger of the ProofCollection
2225
            // transaction inserted above and one of the upgrader's fee
2226
            // gobblers. The point is that this transaction is a SingleProof
2227
            // transaction, so test that.
2228

2229
            let (merged_txid, _) = main_loop_handler
1✔
2230
                .global_state_lock
1✔
2231
                .lock_guard()
1✔
2232
                .await
1✔
2233
                .mempool
2234
                .get_sorted_iter()
1✔
2235
                .next_back()
1✔
2236
                .expect("mempool should contain one item here");
1✔
2237

1✔
2238
            assert!(
1✔
2239
                matches!(
×
2240
                    main_loop_handler
1✔
2241
                        .global_state_lock
1✔
2242
                        .lock_guard()
1✔
2243
                        .await
1✔
2244
                        .mempool
2245
                        .get(merged_txid)
1✔
2246
                        .unwrap()
1✔
2247
                        .proof,
2248
                    TransactionProof::SingleProof(_)
2249
                ),
2250
                "Proof in mempool must now be of type single proof"
×
2251
            );
2252

2253
            match main_to_peer_rx.recv().await {
1✔
2254
                Ok(MainToPeerTask::TransactionNotification(tx_noti)) => {
1✔
2255
                    assert_eq!(merged_txid, tx_noti.txid);
1✔
2256
                    assert_eq!(TransactionProofQuality::SingleProof, tx_noti.proof_quality);
1✔
2257
                },
2258
                other => panic!("Must have sent transaction notification to peer loop after successful proof upgrade. Got:\n{other:?}"),
×
2259
            }
2260

2261
            // These values are kept alive as the transmission-counterpart will
2262
            // otherwise fail on `send`.
2263
            drop(peer_to_main_rx);
1✔
2264
            drop(miner_to_main_rx);
1✔
2265
            drop(rpc_server_to_main_rx);
1✔
2266
            drop(main_to_peer_rx);
1✔
2267
        }
1✔
2268
    }
2269

2270
    mod peer_discovery {
2271
        use super::*;
2272

2273
        #[tokio::test]
2274
        #[traced_test]
×
2275
        async fn prune_peers_too_many_connections() {
1✔
2276
            let num_init_peers_outgoing = 10;
1✔
2277
            let num_init_peers_incoming = 4;
1✔
2278
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2279
            let TestSetup {
2280
                mut main_to_peer_rx,
1✔
2281
                mut main_loop_handler,
1✔
2282
                ..
1✔
2283
            } = test_setup;
1✔
2284

1✔
2285
            let mocked_cli = cli_args::Args {
1✔
2286
                max_num_peers: num_init_peers_outgoing as usize,
1✔
2287
                ..Default::default()
1✔
2288
            };
1✔
2289

1✔
2290
            main_loop_handler
1✔
2291
                .global_state_lock
1✔
2292
                .set_cli(mocked_cli)
1✔
2293
                .await;
1✔
2294

2295
            main_loop_handler.prune_peers().await.unwrap();
1✔
2296
            assert_eq!(4, main_to_peer_rx.len());
1✔
2297
            for _ in 0..4 {
5✔
2298
                let peer_msg = main_to_peer_rx.recv().await.unwrap();
4✔
2299
                assert!(matches!(peer_msg, MainToPeerTask::Disconnect(_)))
4✔
2300
            }
1✔
2301
        }
1✔
2302

2303
        #[tokio::test]
2304
        #[traced_test]
×
2305
        async fn prune_peers_not_too_many_connections() {
1✔
2306
            let num_init_peers_outgoing = 10;
1✔
2307
            let num_init_peers_incoming = 1;
1✔
2308
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2309
            let TestSetup {
2310
                main_to_peer_rx,
1✔
2311
                mut main_loop_handler,
1✔
2312
                ..
1✔
2313
            } = test_setup;
1✔
2314

1✔
2315
            let mocked_cli = cli_args::Args {
1✔
2316
                max_num_peers: 200,
1✔
2317
                ..Default::default()
1✔
2318
            };
1✔
2319

1✔
2320
            main_loop_handler
1✔
2321
                .global_state_lock
1✔
2322
                .set_cli(mocked_cli)
1✔
2323
                .await;
1✔
2324

2325
            main_loop_handler.prune_peers().await.unwrap();
1✔
2326
            assert!(main_to_peer_rx.is_empty());
1✔
2327
        }
1✔
2328

2329
        #[tokio::test]
2330
        #[traced_test]
1✔
2331
        async fn skip_peer_discovery_if_peer_limit_is_exceeded() {
1✔
2332
            let num_init_peers_outgoing = 2;
1✔
2333
            let num_init_peers_incoming = 0;
1✔
2334
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2335
            let TestSetup {
2336
                task_join_handles,
1✔
2337
                mut main_loop_handler,
1✔
2338
                ..
1✔
2339
            } = test_setup;
1✔
2340

1✔
2341
            let mocked_cli = cli_args::Args {
1✔
2342
                max_num_peers: 0,
1✔
2343
                ..Default::default()
1✔
2344
            };
1✔
2345
            main_loop_handler
1✔
2346
                .global_state_lock
1✔
2347
                .set_cli(mocked_cli)
1✔
2348
                .await;
1✔
2349
            main_loop_handler
1✔
2350
                .discover_peers(&mut MutableMainLoopState::new(task_join_handles))
1✔
2351
                .await
1✔
2352
                .unwrap();
1✔
2353

1✔
2354
            assert!(logs_contain("Skipping peer discovery."));
1✔
2355
        }
1✔
2356

2357
        #[tokio::test]
2358
        #[traced_test]
1✔
2359
        async fn performs_peer_discovery_on_few_connections() {
1✔
2360
            let num_init_peers_outgoing = 2;
1✔
2361
            let num_init_peers_incoming = 0;
1✔
2362
            let TestSetup {
2363
                task_join_handles,
1✔
2364
                mut main_loop_handler,
1✔
2365
                mut main_to_peer_rx,
1✔
2366
                peer_to_main_rx: _keep_channel_open,
1✔
2367
                ..
2368
            } = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2369

2370
            // Set CLI to attempt to make more connections
2371
            let mocked_cli = cli_args::Args {
1✔
2372
                max_num_peers: 10,
1✔
2373
                ..Default::default()
1✔
2374
            };
1✔
2375
            main_loop_handler
1✔
2376
                .global_state_lock
1✔
2377
                .set_cli(mocked_cli)
1✔
2378
                .await;
1✔
2379
            main_loop_handler
1✔
2380
                .discover_peers(&mut MutableMainLoopState::new(task_join_handles))
1✔
2381
                .await
1✔
2382
                .unwrap();
1✔
2383

1✔
2384
            let peer_discovery_sent_messages_on_peer_channel = main_to_peer_rx.try_recv().is_ok();
1✔
2385
            assert!(peer_discovery_sent_messages_on_peer_channel);
1✔
2386
            assert!(logs_contain("Performing peer discovery"));
1✔
2387
        }
1✔
2388
    }
2389

2390
    #[test]
2391
    fn older_systemtime_ranks_first() {
1✔
2392
        let start = UNIX_EPOCH;
1✔
2393
        let other = UNIX_EPOCH + Duration::from_secs(1000);
1✔
2394
        let mut instants = [start, other];
1✔
2395

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

2401
        instants.reverse();
1✔
2402

1✔
2403
        assert_eq!(
1✔
2404
            start,
1✔
2405
            instants.iter().copied().min_by(|l, r| l.cmp(r)).unwrap()
1✔
2406
        );
1✔
2407
    }
1✔
2408
    mod bootstrapper_mode {
2409

2410
        use rand::Rng;
2411

2412
        use super::*;
2413
        use crate::models::peer::PeerMessage;
2414
        use crate::models::peer::TransferConnectionStatus;
2415
        use crate::tests::shared::get_dummy_peer_connection_data_genesis;
2416
        use crate::tests::shared::to_bytes;
2417

2418
        #[tokio::test]
2419
        #[traced_test]
×
2420
        async fn disconnect_from_oldest_peer_upon_connection_request() {
1✔
2421
            // Set up a node in bootstrapper mode and connected to a given
1✔
2422
            // number of peers, which is one less than the maximum. Initiate a
1✔
2423
            // connection request. Verify that the oldest of the existing
1✔
2424
            // connections is dropped.
1✔
2425

1✔
2426
            let network = Network::Main;
1✔
2427
            let num_init_peers_outgoing = 5;
1✔
2428
            let num_init_peers_incoming = 0;
1✔
2429
            let test_setup = setup(num_init_peers_outgoing, num_init_peers_incoming).await;
1✔
2430
            let TestSetup {
2431
                mut peer_to_main_rx,
1✔
2432
                miner_to_main_rx: _,
1✔
2433
                rpc_server_to_main_rx: _,
1✔
2434
                task_join_handles,
1✔
2435
                mut main_loop_handler,
1✔
2436
                mut main_to_peer_rx,
1✔
2437
            } = test_setup;
1✔
2438

1✔
2439
            let mocked_cli = cli_args::Args {
1✔
2440
                max_num_peers: usize::from(num_init_peers_outgoing) + 1,
1✔
2441
                bootstrap: true,
1✔
2442
                network,
1✔
2443
                ..Default::default()
1✔
2444
            };
1✔
2445
            main_loop_handler
1✔
2446
                .global_state_lock
1✔
2447
                .set_cli(mocked_cli)
1✔
2448
                .await;
1✔
2449

2450
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
2451

1✔
2452
            // check sanity: at startup, we are connected to the initial number of peers
1✔
2453
            assert_eq!(
1✔
2454
                usize::from(num_init_peers_outgoing),
1✔
2455
                main_loop_handler
1✔
2456
                    .global_state_lock
1✔
2457
                    .lock_guard()
1✔
2458
                    .await
1✔
2459
                    .net
2460
                    .peer_map
2461
                    .len()
1✔
2462
            );
2463

2464
            // randomize "connection established" timestamps
2465
            let mut rng = rand::rng();
1✔
2466
            let now = SystemTime::now();
1✔
2467
            let now_as_unix_timestamp = now.duration_since(UNIX_EPOCH).unwrap();
1✔
2468
            main_loop_handler
1✔
2469
                .global_state_lock
1✔
2470
                .lock_guard_mut()
1✔
2471
                .await
1✔
2472
                .net
2473
                .peer_map
2474
                .iter_mut()
1✔
2475
                .for_each(|(_socket_address, peer_info)| {
5✔
2476
                    peer_info.set_connection_established(
5✔
2477
                        UNIX_EPOCH
5✔
2478
                            + Duration::from_millis(
5✔
2479
                                rng.random_range(0..(now_as_unix_timestamp.as_millis() as u64)),
5✔
2480
                            ),
5✔
2481
                    );
5✔
2482
                });
5✔
2483

2484
            // compute which peer will be dropped, for later reference
2485
            let expected_drop_peer_socket_address = main_loop_handler
1✔
2486
                .global_state_lock
1✔
2487
                .lock_guard()
1✔
2488
                .await
1✔
2489
                .net
2490
                .peer_map
2491
                .iter()
1✔
2492
                .min_by(|l, r| {
4✔
2493
                    l.1.connection_established()
4✔
2494
                        .cmp(&r.1.connection_established())
4✔
2495
                })
4✔
2496
                .map(|(socket_address, _peer_info)| socket_address)
1✔
2497
                .copied()
1✔
2498
                .unwrap();
1✔
2499

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

2554
            // `answer_peer_wrapper` should send a
2555
            // `DisconnectFromLongestLivedPeer` message to main
2556
            let peer_to_main_message = peer_to_main_rx.recv().await.unwrap();
1✔
2557
            assert!(matches!(
1✔
2558
                peer_to_main_message,
1✔
2559
                PeerTaskToMain::DisconnectFromLongestLivedPeer,
2560
            ));
2561

2562
            // process this message
2563
            main_loop_handler
1✔
2564
                .handle_peer_task_message(peer_to_main_message, &mut mutable_main_loop_state)
1✔
2565
                .await
1✔
2566
                .unwrap();
1✔
2567

2568
            // main loop should send a `Disconnect` message
2569
            let main_to_peers_message = main_to_peer_rx.recv().await.unwrap();
1✔
2570
            let MainToPeerTask::Disconnect(observed_drop_peer_socket_address) =
1✔
2571
                main_to_peers_message
1✔
2572
            else {
2573
                panic!("Expected disconnect, got {main_to_peers_message:?}");
×
2574
            };
2575

2576
            // matched observed droppee against expectation
2577
            assert_eq!(
1✔
2578
                expected_drop_peer_socket_address,
1✔
2579
                observed_drop_peer_socket_address,
1✔
2580
            );
1✔
2581
            println!("Dropped connection with {expected_drop_peer_socket_address}.");
1✔
2582

1✔
2583
            // don't forget to terminate the peer task, which is still running
1✔
2584
            incoming_peer_task_handle.abort();
1✔
2585
        }
1✔
2586
    }
2587
}
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