dusk-node 1.7.0

An implementation of dusk-blockchain node in pure Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

mod admission;
pub mod conf;
mod prequeue;

use std::sync::Arc;
use std::time::Duration;

use anyhow::anyhow;
use async_trait::async_trait;
use conf::{
    DEFAULT_DOWNLOAD_REDUNDANCY, DEFAULT_EXPIRY_TIME, DEFAULT_IDLE_INTERVAL,
};
use dusk_consensus::errors::BlobError;
use dusk_core::TxPreconditionError;
use dusk_core::transfer::TransactionFormat;
use node_data::events::{Event, TransactionEvent};
use node_data::get_current_timestamp;
use node_data::ledger::{CanonicalTransaction, LedgerTransaction};
use node_data::message::{AsyncQueue, Payload, Topics, payload};
pub use prequeue::FutureNonceRetryHandle;
use prequeue::{
    RETRY_POLL_INTERVAL, drain_unblocked_chain, handle_enqueue_outcome,
    process_due_retries,
};
use rkyv::Infallible;
use rkyv::ser::Serializer;
use rkyv::ser::serializers::{
    BufferScratch, BufferSerializer, BufferSerializerError,
    CompositeSerializer, CompositeSerializerError,
};
use thiserror::Error;
use tokio::sync::RwLock;
use tokio::sync::mpsc::Sender;
use tokio::time::Instant;
use tracing::{error, info, warn};

use self::admission::{TxAdmission, apply_mempool_admission};
use crate::database::{Ledger, Mempool};
use crate::mempool::conf::Params;
use crate::{LongLivedService, Message, Network, database, vm};

const TOPICS: &[u8] = &[Topics::Tx as u8];

pub(super) fn should_replace_conflicting_tx(
    existing: &LedgerTransaction,
    incoming: &LedgerTransaction,
) -> bool {
    incoming.gas_price() > existing.gas_price()
}

#[derive(Debug, Error)]
pub enum TxAcceptanceError {
    #[error("this transaction exists in the mempool")]
    AlreadyExistsInMempool,
    #[error("this transaction exists in the ledger")]
    AlreadyExistsInLedger,
    #[error("Transaction blob id {} is missing sidecar", hex::encode(.0))]
    BlobMissingSidecar([u8; 32]),
    #[error("No blobs provided")]
    BlobEmpty,
    #[error("Transaction has too many blobs: {0}")]
    BlobTooMany(usize),
    #[error("Invalid blob: {0}")]
    BlobInvalid(String),
    #[error("this transaction's spendId exists in the mempool")]
    SpendIdExistsInMempool,
    #[error("this transaction is invalid {0}")]
    VerificationFailed(String),
    #[error("gas price lower than minimum {0}")]
    GasPriceTooLow(u64),
    #[error("gas limit lower than minimum {0}")]
    GasLimitTooLow(u64),
    #[error(
        "transaction format {actual:?} is not supported for live ingress; minimum supported format is {minimum:?}"
    )]
    UnsupportedIngressFormat {
        actual: TransactionFormat,
        minimum: TransactionFormat,
    },
    #[error("Maximum count of transactions exceeded {0}")]
    MaxTxnCountExceeded(usize),
    #[error("Missing intermediate nonce {0}")]
    MissingIntermediateNonce(u64),
    #[error("Maximum future nonce retry queue size exceeded {0}")]
    MaxFutureNonceQueueExceeded(usize),
    #[error(
        "Maximum queued future Moonlight transactions per account exceeded {0}"
    )]
    MaxMoonlightFutureNoncePerAccountExceeded(usize),
    #[error("this transaction is too large to be serialized")]
    TooLarge,
    #[error("Maximum transaction size exceeded {0}")]
    MaxSizeExceeded(usize),
    #[error("A generic error occurred {0}")]
    Generic(anyhow::Error),
}

impl From<anyhow::Error> for TxAcceptanceError {
    fn from(err: anyhow::Error) -> Self {
        Self::Generic(err)
    }
}

impl From<BlobError> for TxAcceptanceError {
    fn from(err: BlobError) -> Self {
        match err {
            BlobError::MissingSidecar(id) => {
                TxAcceptanceError::BlobMissingSidecar(id)
            }
            BlobError::BlobEmpty => TxAcceptanceError::BlobEmpty,
            BlobError::BlobTooMany(n) => TxAcceptanceError::BlobTooMany(n),
            BlobError::BlobInvalid(msg) => TxAcceptanceError::BlobInvalid(msg),
        }
    }
}

impl From<TxPreconditionError> for TxAcceptanceError {
    fn from(err: TxPreconditionError) -> Self {
        match err {
            TxPreconditionError::BlobLowLimit(min) => {
                TxAcceptanceError::GasLimitTooLow(min)
            }
            TxPreconditionError::DeployChargeOverflow => {
                TxAcceptanceError::VerificationFailed(
                    "deploy charge overflow".into(),
                )
            }
            TxPreconditionError::BlobChargeOverflow => {
                TxAcceptanceError::VerificationFailed(
                    "blob charge overflow".into(),
                )
            }
            TxPreconditionError::DeployLowLimit(min) => {
                TxAcceptanceError::GasLimitTooLow(min)
            }
            TxPreconditionError::DeployLowPrice(min) => {
                TxAcceptanceError::GasPriceTooLow(min)
            }
            TxPreconditionError::BlobEmpty => TxAcceptanceError::BlobEmpty,
            TxPreconditionError::BlobTooMany(n) => {
                TxAcceptanceError::BlobTooMany(n)
            }
            TxPreconditionError::PhoenixFeeOverflow => {
                TxAcceptanceError::VerificationFailed(
                    "phoenix fee overflow".into(),
                )
            }
            TxPreconditionError::PhoenixFeeTampered => {
                TxAcceptanceError::VerificationFailed(
                    "phoenix fee tampered".into(),
                )
            }
            TxPreconditionError::PhoenixFeeRefundMismatch => {
                TxAcceptanceError::VerificationFailed(
                    "phoenix fee refund stealth address mismatch".into(),
                )
            }
        }
    }
}

fn check_supported_ingress_tx_format(
    tx: &CanonicalTransaction,
) -> Result<(), TxAcceptanceError> {
    // Live network admission accepts both Aegis and Boreas envelopes. Only the
    // historical PreAegis encoding remains replay-only.
    if tx.format() == TransactionFormat::PreAegis {
        return Err(TxAcceptanceError::UnsupportedIngressFormat {
            actual: tx.format(),
            minimum: TransactionFormat::Aegis,
        });
    }

    Ok(())
}

fn normalize_ingress_tx(
    tx: &LedgerTransaction,
    block_height: u64,
) -> Result<LedgerTransaction, TxAcceptanceError> {
    check_supported_ingress_tx_format(tx.canonical())?;
    Ok(tx.reformat_for_ingress(block_height))
}

pub struct MempoolSrv {
    inbound: AsyncQueue<Message>,
    conf: Params,
    /// Sender channel for sending out RUES events
    event_sender: Sender<Event>,
    future_nonce_retry_queue: FutureNonceRetryHandle,
}

impl MempoolSrv {
    pub fn new(conf: Params, event_sender: Sender<Event>) -> Self {
        let queue = FutureNonceRetryHandle::new(
            conf.max_queue_size,
            conf.max_moonlight_future_nonce_per_account,
        );
        Self::with_future_nonce_retry_queue(conf, event_sender, queue)
    }

    pub fn with_future_nonce_retry_queue(
        conf: Params,
        event_sender: Sender<Event>,
        future_nonce_retry_queue: FutureNonceRetryHandle,
    ) -> Self {
        info!("MempoolSrv::new with conf {}", conf);
        Self {
            inbound: AsyncQueue::bounded(
                conf.max_queue_size,
                "mempool_inbound",
            ),
            conf,
            event_sender,
            future_nonce_retry_queue,
        }
    }
}

#[async_trait]
impl<N: Network, DB: database::DB, VM: vm::VMExecution>
    LongLivedService<N, DB, VM> for MempoolSrv
{
    async fn execute(
        &mut self,
        network: Arc<RwLock<N>>,
        db: Arc<RwLock<DB>>,
        vm: Arc<RwLock<VM>>,
    ) -> anyhow::Result<usize> {
        LongLivedService::<N, DB, VM>::add_routes(
            self,
            TOPICS,
            self.inbound.clone(),
            &network,
        )
        .await?;

        // Request mempool update from N alive peers
        self.request_mempool(&network).await;

        let idle_interval =
            self.conf.idle_interval.unwrap_or(DEFAULT_IDLE_INTERVAL);

        let mempool_expiry = self
            .conf
            .mempool_expiry
            .unwrap_or(DEFAULT_EXPIRY_TIME)
            .as_secs();

        let retry_queue = self.future_nonce_retry_queue.clone();
        let retry_event_sender = self.event_sender.clone();
        let retry_max_mempool_txn_count = self.conf.max_mempool_txn_count;
        let retry_network = network.clone();
        let retry_db = db.clone();
        let retry_vm = vm.clone();
        tokio::spawn(async move {
            MempoolSrv::run_retry_worker(
                retry_queue,
                retry_event_sender,
                retry_max_mempool_txn_count,
                retry_network,
                retry_db,
                retry_vm,
            )
            .await;
        });

        // Mempool service loop
        let mut on_idle_event = tokio::time::interval(idle_interval);
        loop {
            tokio::select! {
                biased;
                _ = on_idle_event.tick() => {
                    info!(event = "mempool_idle", interval = ?idle_interval);

                    let expiration_time = get_current_timestamp()
                        .checked_sub(mempool_expiry)
                        .expect("valid duration");

                    // Remove expired transactions from the mempool
                    db.read().await.update(|db| {
                        let expired_txs = db.mempool_expired_txs(expiration_time).unwrap_or_else(|e| {
                            error!("cannot get expired txs: {e}");
                            vec![]
                        });
                        for tx_id in expired_txs {
                            info!(event = "expired_tx", hash = hex::encode(tx_id));
                            let deleted_txs = db.delete_mempool_tx(tx_id, true).unwrap_or_else(|e| {
                                error!("cannot delete expired tx: {e}");
                                vec![]
                            });
                            for deleted_tx_id in deleted_txs{
                                let event = TransactionEvent::Removed(deleted_tx_id);
                                info!(event = "mempool_deleted", hash = hex::encode(deleted_tx_id));
                                if let Err(e) = self.event_sender.try_send(event.into()) {
                                    warn!("cannot notify mempool removed transaction {e}")
                                };
                            }
                        }
                        Ok(())
                    })?;

                },
                msg = self.inbound.recv() => {
                    if let Ok(msg) = msg {
                        match &msg.payload {
                            Payload::Transaction(tx) => {
                                if let Err(e) = self
                                    .handle_tx_message(
                                        &network,
                                        &db,
                                        &vm,
                                        &msg,
                                    )
                                    .await
                                {
                                    error!("Tx {} not accepted: {e}", hex::encode(tx.id()));
                                };
                            }
                            _ => error!("invalid inbound message payload"),
                        }
                    }
                }
            }
        }
    }

    /// Returns service name.
    fn name(&self) -> &'static str {
        "mempool"
    }
}

impl MempoolSrv {
    async fn run_retry_worker<
        N: Network,
        DB: database::DB,
        VM: vm::VMExecution,
    >(
        future_nonce_retry_queue: FutureNonceRetryHandle,
        event_sender: Sender<Event>,
        max_mempool_txn_count: usize,
        network: Arc<RwLock<N>>,
        db: Arc<RwLock<DB>>,
        vm: Arc<RwLock<VM>>,
    ) {
        let mut on_retry_event = tokio::time::interval(RETRY_POLL_INTERVAL);

        loop {
            on_retry_event.tick().await;
            process_due_retries(
                &future_nonce_retry_queue,
                &event_sender,
                max_mempool_txn_count,
                &network,
                &db,
                &vm,
                Instant::now(),
            )
            .await;
        }
    }

    async fn broadcast_tx<N: Network>(network: &Arc<RwLock<N>>, msg: &Message) {
        let network = network.read().await;
        if let Err(e) = network.broadcast(msg).await {
            warn!("Unable to broadcast accepted tx: {e}");
        };
    }

    async fn broadcast_accepted_tx<N: Network>(
        network: &Arc<RwLock<N>>,
        msg: &Message,
        tx: &LedgerTransaction,
        source: Option<&str>,
        queue_age_ms: Option<u64>,
    ) {
        if let Some(source) = source {
            info!(
                event = "future_nonce_retry_accepted",
                hash = hex::encode(tx.id()),
                source,
                queue_age_ms
            );
        }
        Self::broadcast_tx(network, msg).await;
    }

    async fn handle_tx_message<
        N: Network,
        DB: database::DB,
        VM: vm::VMExecution,
    >(
        &mut self,
        network: &Arc<RwLock<N>>,
        db: &Arc<RwLock<DB>>,
        vm: &Arc<RwLock<VM>>,
        msg: &Message,
    ) -> Result<(), TxAcceptanceError> {
        let Payload::Transaction(tx) = &msg.payload else {
            return Err(TxAcceptanceError::Generic(anyhow!(
                "invalid inbound message payload"
            )));
        };

        let next_block_height = db
            .read()
            .await
            .view(|db| db.latest_block())
            .map_err(|e| {
                TxAcceptanceError::Generic(anyhow!(
                    "Cannot get tip block height from the database: {e}"
                ))
            })?
            .header
            .height
            .saturating_add(1);
        let tx = normalize_ingress_tx(tx, next_block_height)?;
        let msg = {
            let mut normalized = msg.clone();
            normalized.payload = tx.clone().into();
            normalized
        };

        match Self::accept_tx(
            &self.event_sender,
            self.conf.max_mempool_txn_count,
            db,
            vm,
            &tx,
        )
        .await
        {
            Ok(()) => {
                Self::broadcast_accepted_tx(network, &msg, &tx, None, None)
                    .await;
                drain_unblocked_chain(
                    &self.future_nonce_retry_queue,
                    &self.event_sender,
                    self.conf.max_mempool_txn_count,
                    network,
                    db,
                    vm,
                    &tx,
                )
                .await;
                Ok(())
            }
            Err(TxAcceptanceError::MissingIntermediateNonce(_)) => {
                handle_enqueue_outcome(
                    &self.event_sender,
                    &tx,
                    self.future_nonce_retry_queue
                        .enqueue_message_with_outcome(&msg)
                        .await,
                )
            }
            Err(err) => Err(err),
        }
    }

    async fn accept_tx<DB: database::DB, VM: vm::VMExecution>(
        event_sender: &Sender<Event>,
        max_mempool_txn_count: usize,
        db: &Arc<RwLock<DB>>,
        vm: &Arc<RwLock<VM>>,
        tx: &LedgerTransaction,
    ) -> Result<(), TxAcceptanceError> {
        let events =
            MempoolSrv::check_tx(db, vm, tx, false, max_mempool_txn_count)
                .await?;

        tracing::info!(
            event = "transaction accepted",
            hash = hex::encode(tx.id())
        );

        for tx_event in events {
            let node_event = tx_event.into();
            if let Err(e) = event_sender.try_send(node_event) {
                warn!("cannot notify mempool accepted transaction {e}")
            };
        }

        Ok(())
    }

    pub async fn check_tx<'t, DB: database::DB, VM: vm::VMExecution>(
        db: &Arc<RwLock<DB>>,
        vm: &Arc<RwLock<VM>>,
        tx: &'t LedgerTransaction,
        dry_run: bool,
        max_mempool_txn_count: usize,
    ) -> Result<Vec<TransactionEvent<'t>>, TxAcceptanceError> {
        let admission = TxAdmission::new(db, vm, max_mempool_txn_count)
            .check(tx.canonical())
            .await?;

        let mut events = vec![];
        db.read().await.update_dry_run(dry_run, |db| {
            events = apply_mempool_admission(
                db,
                tx,
                &admission.facts,
                admission.tx_to_delete,
                get_current_timestamp(),
            )?;
            Ok(())
        })?;

        Ok(events)
    }

    pub async fn check_canonical_tx_at_tip<
        DB: database::DB,
        VM: vm::VMExecution,
    >(
        db: &Arc<RwLock<DB>>,
        vm: &Arc<RwLock<VM>>,
        tx: &CanonicalTransaction,
        tip_height: u64,
        max_mempool_txn_count: usize,
    ) -> Result<LedgerTransaction, TxAcceptanceError> {
        let _ = TxAdmission::new(db, vm, max_mempool_txn_count)
            .check_with_tip(tx, tip_height)
            .await?;
        Ok(tx.clone().into())
    }

    /// Requests full mempool data from N alive peers
    ///
    /// Message flow:
    /// GetMempool -> Inv -> GetResource -> Tx
    async fn request_mempool<N: Network>(&self, network: &Arc<RwLock<N>>) {
        const WAIT_TIMEOUT: Duration = Duration::from_secs(5);
        let max_peers = self
            .conf
            .mempool_download_redundancy
            .unwrap_or(DEFAULT_DOWNLOAD_REDUNDANCY);

        let net = network.read().await;
        net.wait_for_alive_nodes(max_peers, WAIT_TIMEOUT).await;

        let msg = payload::GetMempool::default().into();
        if let Err(err) = net.send_to_alive_peers(msg, max_peers).await {
            error!("could not request mempool from network: {err}");
        }
    }
}

fn check_tx_serialization(
    tx: &dusk_core::transfer::Transaction,
) -> Result<(), TxAcceptanceError> {
    // The transaction is an argument to the transfer contract, so
    // its serialized size has to be within the same 64Kib limit.
    const SCRATCH_BUF_BYTES: usize = 1024;
    const ARGBUF_LEN: usize = 64 * 1024;
    let stripped_tx = tx.strip_off_bytecode().or(tx.blob_to_memo());
    let mut sbuf = [0u8; SCRATCH_BUF_BYTES];
    let mut buffer = [0u8; ARGBUF_LEN];
    let scratch = BufferScratch::new(&mut sbuf);
    let ser = BufferSerializer::new(&mut buffer);
    let mut ser = CompositeSerializer::new(ser, scratch, Infallible);
    if let Err(err) = ser.serialize_value(stripped_tx.as_ref().unwrap_or(tx)) {
        match err {
            CompositeSerializerError::SerializerError(err) => match err {
                BufferSerializerError::Overflow { .. } => {
                    return Err(TxAcceptanceError::TooLarge);
                }
            },
            err => return Err(TxAcceptanceError::Generic(anyhow!("{err}"))),
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use dusk_core::signatures::bls::{PublicKey, SecretKey};
    use rand::rngs::StdRng;
    use rand::{CryptoRng, Rng, RngCore, SeedableRng};
    use wallet_core::transaction::moonlight_deployment;

    use super::*;

    fn new_moonlight_deploy_tx<R: RngCore + CryptoRng>(
        rng: &mut R,
        bytecode: Vec<u8>,
        init_args: Vec<u8>,
    ) -> dusk_core::transfer::Transaction {
        const CHAIN_ID: u8 = 0xfa;
        let sk = SecretKey::random(rng);
        let pk = PublicKey::from(&SecretKey::random(rng));

        let gas_limit: u64 = rng.r#gen();
        let gas_price: u64 = rng.r#gen();
        let nonce: u64 = rng.r#gen();
        let deploy_nonce: u64 = rng.r#gen();

        moonlight_deployment(
            &sk,
            bytecode,
            &pk,
            init_args,
            gas_limit,
            gas_price,
            nonce,
            deploy_nonce,
            CHAIN_ID,
        )
        .expect("should create a transaction")
    }

    const MAX_MOONLIGHT_ARG_SIZE: usize = 64 * 1024 - 2320;

    #[test]
    fn test_tx_serialization_check_normal() {
        let mut rng = StdRng::seed_from_u64(42);
        let tx = new_moonlight_deploy_tx(
            &mut rng,
            vec![0; 64 * 1024],
            vec![0; MAX_MOONLIGHT_ARG_SIZE],
        );
        let result = check_tx_serialization(&tx);
        assert!(matches!(result, Ok(())));
    }

    #[test]
    fn test_tx_serialization_check_tx_too_large() {
        let mut rng = StdRng::seed_from_u64(42);
        let tx = new_moonlight_deploy_tx(
            &mut rng,
            vec![0; 64 * 1024],
            vec![0; MAX_MOONLIGHT_ARG_SIZE + 1],
        );
        let result = check_tx_serialization(&tx);
        assert!(matches!(result, Err(TxAcceptanceError::TooLarge)));
    }

    #[test]
    fn test_supported_ingress_format_check_rejects_pre_aegis() {
        let mut rng = StdRng::seed_from_u64(42);
        let tx = CanonicalTransaction::canonicalize(
            new_moonlight_deploy_tx(&mut rng, vec![0; 32], vec![0; 32]),
            TransactionFormat::PreAegis,
        );

        let result = check_supported_ingress_tx_format(&tx);

        assert!(matches!(
            result,
            Err(TxAcceptanceError::UnsupportedIngressFormat {
                actual: TransactionFormat::PreAegis,
                minimum: TransactionFormat::Aegis,
            })
        ));
    }

    #[test]
    fn test_supported_ingress_format_check_accepts_aegis() {
        let mut rng = StdRng::seed_from_u64(42);
        let tx = CanonicalTransaction::canonicalize(
            new_moonlight_deploy_tx(&mut rng, vec![0; 32], vec![0; 32]),
            node_data::hard_fork::ingress_tx_format_at(1),
        );

        let result = check_supported_ingress_tx_format(&tx);

        assert!(matches!(result, Ok(())));
    }

    #[test]
    fn test_normalize_ingress_tx_reformats_aegis_to_boreas() {
        let mut rng = StdRng::seed_from_u64(42);
        let tx = LedgerTransaction::from_protocol_with_format(
            new_moonlight_deploy_tx(&mut rng, vec![0; 32], vec![0; 32]),
            TransactionFormat::Aegis,
        );

        let normalized = normalize_ingress_tx(&tx, u64::MAX)
            .expect("aegis ingress should normalize to boreas");

        assert_eq!(normalized.format(), TransactionFormat::Boreas);
        assert_eq!(normalized.id(), tx.id());
    }

    #[test]
    fn test_normalize_ingress_tx_reformats_boreas_to_aegis() {
        let mut rng = StdRng::seed_from_u64(42);
        let tx = LedgerTransaction::from_protocol_with_format(
            new_moonlight_deploy_tx(&mut rng, vec![0; 32], vec![0; 32]),
            TransactionFormat::Boreas,
        );

        let normalized = normalize_ingress_tx(&tx, 1)
            .expect("boreas ingress should normalize to aegis");

        assert_eq!(normalized.format(), TransactionFormat::Aegis);
        assert_eq!(normalized.id(), tx.id());
    }
}