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

Neptune-Crypto / neptune-core / 13860309462

14 Mar 2025 03:49PM UTC coverage: 84.226% (+0.05%) from 84.172%
13860309462

Pull #503

github

web-flow
Merge e38c78b24 into d55ef2e4a
Pull Request #503: feat: Allow restriction of number of inputs per tx

310 of 327 new or added lines in 10 files covered. (94.8%)

3 existing lines in 2 files now uncovered.

50923 of 60460 relevant lines covered (84.23%)

176374.24 hits per line

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

56.35
/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
                let mut global_state_mut = self.global_state_lock.lock_guard_mut().await;
×
802
                if pt2m_transaction.confirmable_for_block
×
803
                    != global_state_mut.chain.light_state().hash()
×
804
                {
805
                    warn!("main loop got unmined transaction with bad mutator set data, discarding transaction");
×
806
                    return Ok(());
×
807
                }
×
808

809
                // Insert into mempool, if allowed.
NEW
810
                if let Err(err) = global_state_mut
×
811
                    .mempool_insert(
×
812
                        pt2m_transaction.transaction.to_owned(),
×
813
                        TransactionOrigin::Foreign,
×
814
                    )
×
NEW
815
                    .await
×
816
                {
NEW
817
                    warn!("cannot add transaction into mempool: {err}");
×
NEW
818
                    return Ok(());
×
NEW
819
                }
×
820

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

×
832
                debug!("main loop received block proposal from peer loop");
×
833

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

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

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

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

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

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

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

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

892
        Ok(())
1✔
893
    }
1✔
894

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

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

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

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

947
        Ok(())
1✔
948
    }
2✔
949

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

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

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

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

1018
        Ok(())
×
1019
    }
×
1020

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

2✔
1037
        let num_peers = connected_peers.len();
2✔
1038
        let max_num_peers = cli_args.max_num_peers;
2✔
1039

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

1✔
1050
        info!("Performing peer discovery");
1✔
1051

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

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

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

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

1098
        Ok(())
×
1099
    }
2✔
1100

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

1112
        let mut look_behind = 0;
258✔
1113
        let mut ret = vec![];
258✔
1114

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

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

1127
        ret.push(BlockHeight::genesis());
258✔
1128

258✔
1129
        ret
258✔
1130
    }
258✔
1131

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

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

1144
        info!("Running sync");
2✔
1145

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

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

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

1174
            let peers_to_punish = main_loop_state
1✔
1175
                .sync_state
1✔
1176
                .get_potential_peers_for_sync_request(own_cumulative_pow);
1✔
1177

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

1183
            return Ok(());
1✔
1184
        }
1✔
1185

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

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

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

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

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

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

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

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

1✔
1259
        Ok(())
1✔
1260
    }
3✔
1261

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

1291
        trace!("Running proof upgrader scheduled task");
3✔
1292

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

1✔
1304
            debug!("Attempting to run transaction-proof-upgrade");
1✔
1305

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

1313
            (upgrade_candidate, tx_origin)
1✔
1314
        };
1✔
1315

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

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

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

1346
        main_loop_state.proof_upgrader_task = Some(proof_upgrader_task);
1✔
1347

1✔
1348
        Ok(())
1✔
1349
    }
3✔
1350

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

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

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

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

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

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

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

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

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

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

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

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

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

1482
        #[cfg(not(unix))]
1483
        drop((tx_term, tx_int, tx_quit));
1484

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

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

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

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

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

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

1553
                    if let Some(exit_code) = exit_code {
×
1554
                        break exit_code;
×
1555
                    }
×
1556

1557
                }
1558

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

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

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

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

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

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

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

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

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

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

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

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

×
1613
                    debug!("Timer: UTXO notification pool cleanup job");
×
1614

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

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

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

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

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

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

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

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

1647
            }
1648
        };
1649

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

1653
        Ok(exit_code)
×
1654
    }
×
1655

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

1672
                // insert transaction into mempool
1673
                self.global_state_lock
×
1674
                    .lock_guard_mut()
×
1675
                    .await
×
1676
                    .mempool_insert(*transaction.clone(), TransactionOrigin::Own)
×
NEW
1677
                    .await
×
NEW
1678
                    .unwrap();
×
1679

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

1692
                    let vm_job_queue = self.global_state_lock.vm_job_queue().clone();
×
1693

×
1694
                    let proving_capability = self.global_state_lock.cli().proving_capability();
×
1695
                    let upgrade_job =
×
1696
                        UpgradeJob::from_primitive_witness(proving_capability, primitive_witness);
×
1697

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

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

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

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

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

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

1771
                // shut down
1772
                Ok(true)
×
1773
            }
1774
        }
1775
    }
×
1776

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

1780
        // Stop mining
1781
        self.main_to_miner_tx.send(MainToMiner::Shutdown);
×
1782

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

1789
        // Flush all databases
1790
        self.global_state_lock.flush_databases().await?;
×
1791

1792
        tokio::time::sleep(Duration::from_millis(50)).await;
×
1793

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

×
1797
        // wait for all to finish.
×
1798
        futures::future::join_all(task_handles).await;
×
1799

1800
        Ok(())
×
1801
    }
×
1802
}
1803

1804
#[cfg(test)]
1805
mod test {
1806
    use std::str::FromStr;
1807
    use std::time::UNIX_EPOCH;
1808

1809
    use tracing_test::traced_test;
1810

1811
    use super::*;
1812
    use crate::config_models::cli_args;
1813
    use crate::config_models::network::Network;
1814
    use crate::tests::shared::get_dummy_peer_incoming;
1815
    use crate::tests::shared::get_test_genesis_setup;
1816
    use crate::tests::shared::invalid_empty_block;
1817
    use crate::MINER_CHANNEL_CAPACITY;
1818

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

1828
    async fn setup(num_init_peers_outgoing: u8, num_peers_incoming: u8) -> TestSetup {
8✔
1829
        const CHANNEL_CAPACITY_MINER_TO_MAIN: usize = 10;
1830

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

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

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

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

8✔
1873
        let main_loop_handler = MainLoopHandler::new(
8✔
1874
            incoming_peer_listener,
8✔
1875
            state,
8✔
1876
            main_to_peer_tx,
8✔
1877
            peer_to_main_tx,
8✔
1878
            main_to_miner_tx,
8✔
1879
        );
8✔
1880

8✔
1881
        let task_join_handles = vec![];
8✔
1882

8✔
1883
        TestSetup {
8✔
1884
            miner_to_main_rx,
8✔
1885
            peer_to_main_rx,
8✔
1886
            rpc_server_to_main_rx,
8✔
1887
            task_join_handles,
8✔
1888
            main_loop_handler,
8✔
1889
            main_to_peer_rx,
8✔
1890
        }
8✔
1891
    }
8✔
1892

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

1✔
1906
        let block1 = invalid_empty_block(&Block::genesis(network));
1✔
1907

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

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

1950
    mod sync_mode {
1951
        use tasm_lib::twenty_first::util_types::mmr::mmr_accumulator::MmrAccumulator;
1952
        use test_strategy::proptest;
1953

1954
        use super::*;
1955
        use crate::tests::shared::get_dummy_socket_address;
1956

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

1962
        #[test]
1963
        fn batch_request_heights_unit() {
1✔
1964
            let own_height = 1_000_000u64;
1✔
1965
            batch_request_heights_sanity(own_height);
1✔
1966
        }
1✔
1967

1968
        fn batch_request_heights_sanity(own_height: u64) {
257✔
1969
            let heights = MainLoopHandler::batch_request_uca_candidate_heights(own_height.into());
257✔
1970

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

1978
            heights_rev.dedup();
257✔
1979
            assert_eq!(heights_rev.len(), heights.len(), "duplicates");
257✔
1980

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

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

1✔
2000
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
2001

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2177
            main_loop_handler
1✔
2178
                .global_state_lock
1✔
2179
                .lock_guard_mut()
1✔
2180
                .await
1✔
2181
                .mempool_insert(proof_collection_tx.clone(), TransactionOrigin::Foreign)
1✔
2182
                .await
1✔
2183
                .unwrap();
1✔
2184

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

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

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

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

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

2233
            let (merged_txid, _) = main_loop_handler
1✔
2234
                .global_state_lock
1✔
2235
                .lock_guard()
1✔
2236
                .await
1✔
2237
                .mempool
2238
                .get_sorted_iter()
1✔
2239
                .next_back()
1✔
2240
                .expect("mempool should contain one item here");
1✔
2241

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

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

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

2274
    mod peer_discovery {
2275
        use super::*;
2276

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

1✔
2289
            let mocked_cli = cli_args::Args {
1✔
2290
                max_num_peers: num_init_peers_outgoing as usize,
1✔
2291
                ..Default::default()
1✔
2292
            };
1✔
2293

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

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

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

1✔
2319
            let mocked_cli = cli_args::Args {
1✔
2320
                max_num_peers: 200,
1✔
2321
                ..Default::default()
1✔
2322
            };
1✔
2323

1✔
2324
            main_loop_handler
1✔
2325
                .global_state_lock
1✔
2326
                .set_cli(mocked_cli)
1✔
2327
                .await;
1✔
2328

2329
            main_loop_handler.prune_peers().await.unwrap();
1✔
2330
            assert!(main_to_peer_rx.is_empty());
1✔
2331
        }
1✔
2332

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

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

1✔
2358
            assert!(logs_contain("Skipping peer discovery."));
1✔
2359
        }
1✔
2360

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

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

1✔
2388
            let peer_discovery_sent_messages_on_peer_channel = main_to_peer_rx.try_recv().is_ok();
1✔
2389
            assert!(peer_discovery_sent_messages_on_peer_channel);
1✔
2390
            assert!(logs_contain("Performing peer discovery"));
1✔
2391
        }
1✔
2392
    }
2393

2394
    #[test]
2395
    fn older_systemtime_ranks_first() {
1✔
2396
        let start = UNIX_EPOCH;
1✔
2397
        let other = UNIX_EPOCH + Duration::from_secs(1000);
1✔
2398
        let mut instants = [start, other];
1✔
2399

1✔
2400
        assert_eq!(
1✔
2401
            start,
1✔
2402
            instants.iter().copied().min_by(|l, r| l.cmp(r)).unwrap()
1✔
2403
        );
1✔
2404

2405
        instants.reverse();
1✔
2406

1✔
2407
        assert_eq!(
1✔
2408
            start,
1✔
2409
            instants.iter().copied().min_by(|l, r| l.cmp(r)).unwrap()
1✔
2410
        );
1✔
2411
    }
1✔
2412
    mod bootstrapper_mode {
2413

2414
        use rand::Rng;
2415

2416
        use super::*;
2417
        use crate::models::peer::PeerMessage;
2418
        use crate::models::peer::TransferConnectionStatus;
2419
        use crate::tests::shared::get_dummy_peer_connection_data_genesis;
2420
        use crate::tests::shared::to_bytes;
2421

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

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

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

2454
            let mut mutable_main_loop_state = MutableMainLoopState::new(task_join_handles);
1✔
2455

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

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

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

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

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

2566
            // process this message
2567
            main_loop_handler
1✔
2568
                .handle_peer_task_message(peer_to_main_message, &mut mutable_main_loop_state)
1✔
2569
                .await
1✔
2570
                .unwrap();
1✔
2571

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

2580
            // matched observed droppee against expectation
2581
            assert_eq!(
1✔
2582
                expected_drop_peer_socket_address,
1✔
2583
                observed_drop_peer_socket_address,
1✔
2584
            );
1✔
2585
            println!("Dropped connection with {expected_drop_peer_socket_address}.");
1✔
2586

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