dusk-vm 1.7.0

The VM to run smart contracts on the Dusk network
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
// 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 config;
pub mod feature;

pub use config::Config;
use dusk_core::abi::{ContractError, ContractId, Metadata};
use dusk_core::stake::STAKE_CONTRACT;
use dusk_core::transfer::data::{ContractBytecode, gen_contract_id};
use dusk_core::transfer::withdraw::{
    Withdraw, WithdrawReceiver, WithdrawReplayToken,
};
use dusk_core::transfer::{TRANSFER_CONTRACT, Transaction};
use piecrust::{CallReceipt, Session};
use rkyv::Deserialize;
use wasmparser::*;

use crate::ExecutionError;

const DEPLOY_FEATURE_VALIDATION_ERROR: &str =
    "failed deployment: bytecode validation rejected";
const PHOENIX_DISABLED_ERROR: &str = "phoenix is not enabled in the VM";
const TRANSFER_WITHDRAWAL_FUNCTIONS: &[&str] = &["mint", "withdraw", "convert"];

/// Executes a transaction in the provided session.
///
/// This function processes the transaction, invoking smart contracts or
/// updating state.
///
/// During the execution the following steps are performed:
///
/// 1. Check if the transaction contains contract deployment data, and if so,
///    verifies if gas limit is enough for deployment and if the gas price is
///    sufficient for deployment. If either gas price or gas limit is not
///    sufficient for deployment, transaction is discarded.
///
/// 2. Call the "spend_and_execute" function on the transfer contract with
///    unlimited gas. If this fails, an error is returned. If an error is
///    returned the transaction should be considered unspendable/invalid, but no
///    re-execution of previous transactions is required.
///
/// 3. If the transaction contains contract deployment data, additional checks
///    are performed and if they pass, deployment is executed. The following
///    checks are performed:
///    - gas limit should be is smaller than deploy charge plus gas used for
///      spending funds
///    - transaction's bytecode's bytes are consistent with bytecode's hash
///
///   Deployment execution may fail for deployment-specific reasons, such as:
///    - contract already deployed
///    - corrupted bytecode
///
///    If deployment execution fails, the entire gas limit is consumed and error
///    is returned.
///
/// 4. Call the "refund" function on the transfer contract with unlimited gas.
///    The amount charged depends on the gas spent by the transaction, and the
///    optional contract call in steps 2 or 3. If this fails, a specific error
///    `FailedRefund` is returned, then the tx should be considered
///    unspendable/invalid, and the caller SHALL DO a re-execution of previous
///    transactions.
///
/// Note that deployment transaction will never be re-executed for reasons
/// related to deployment, as it is either discarded or it charges the
/// full gas limit. It might be re-executed only if some other transaction
/// failed to fit the block.
///
/// # Arguments
/// * `session` - A mutable reference to the session executing the transaction.
/// * `tx` - The transaction to execute.
/// * `config` - The configuration for the execution of the transaction.
///
/// # Returns
/// A result indicating success or failure.
pub fn execute(
    session: &mut Session,
    tx: &Transaction,
    config: &Config,
) -> Result<CallReceipt<Result<Vec<u8>, ContractError>>, ExecutionError> {
    if config.disable_phoenix && matches!(tx, Transaction::Phoenix(_)) {
        return Err(ExecutionError::precondition(PHOENIX_DISABLED_ERROR));
    }

    tx.phoenix_fee_check()?;

    if config.phoenix_refund_check {
        tx.phoenix_refund_check()?;
    }

    // Transaction will be discarded if it is a deployment transaction
    // with gas limit smaller than deploy charge.
    tx.deploy_check(
        config.gas_per_deploy_byte,
        config.min_deploy_gas_price,
        config.min_deploy_points,
    )?;

    if let Some(contract_deploy) = tx.deploy() {
        let is_wasm64 = is_wasm64(&contract_deploy.bytecode.bytes);
        match (config.disable_wasm32, config.disable_wasm64) {
            (true, true) => Err(ExecutionError::precondition(
                "contract deployment is not enabled in the VM",
            )),
            (true, false) if !is_wasm64 => Err(ExecutionError::precondition(
                "32-bit wasm is not enabled in the VM",
            )),
            (false, true) if is_wasm64 => Err(ExecutionError::precondition(
                "64-bit wasm is not enabled in the VM",
            )),
            _ => Ok(()),
        }?
    }

    if config.disable_3rd_party
        && let Some(call) = tx.call()
        && call.contract != TRANSFER_CONTRACT
        && call.contract != STAKE_CONTRACT
    {
        return Err(ExecutionError::precondition(
            "3rd party contracts are not enabled in the VM",
        ));
    }

    let blob_min_charge = tx.blob_check(config.gas_per_blob)?;

    if blob_min_charge.is_some() && !config.with_blob {
        return Err(ExecutionError::precondition(
            "Blob processing is not enabled in the VM",
        ));
    }

    if config.with_public_sender {
        let _ = session
            .set_meta(Metadata::PUBLIC_SENDER, tx.moonlight_sender().copied());
    }

    let stripped_tx = tx.blob_to_memo().or(tx.strip_off_bytecode());

    // Register one combined call hook for VM execution invariants. Piecrust
    // supports one active hook, so all hook-based checks must be chained here.
    //
    // The withdrawal-nullifier check enforces that Phoenix withdrawal replay
    // tokens carry exactly the same number of nullifiers as the encapsulating
    // transaction. This is a defense-in-depth measure against audit finding
    // P1.6-3 (subset-vs-equality in mint_withdrawal).
    //
    // Gated behind the Boreas hard fork activation height.
    if (config.disable_phoenix || config.withdrawal_nullifier_check)
        && tx.call().is_some()
    {
        let disable_phoenix = config.disable_phoenix;
        let withdrawal_nullifier_check = config.withdrawal_nullifier_check;
        let tx_nullifier_count = tx.nullifiers().len();
        session.set_call_hook(Box::new(move |callee, fn_name, fn_args| {
            if disable_phoenix {
                check_phoenix_disabled_call(callee, fn_name, fn_args)?;
            }
            if withdrawal_nullifier_check {
                check_withdrawal_nullifiers(
                    callee,
                    fn_name,
                    fn_args,
                    tx_nullifier_count,
                )?;
            }
            Ok(())
        }));
    }

    // Spend the inputs and execute the call. If this errors the transaction is
    // unspendable.
    let mut receipt = session
        .call::<_, Result<Vec<u8>, ContractError>>(
            TRANSFER_CONTRACT,
            "spend_and_execute",
            stripped_tx.as_ref().unwrap_or(tx),
            tx.gas_limit(),
        )
        .inspect_err(|_| {
            clear_session(session, config);
        })
        .map_err(ExecutionError::from_spend_and_execute)?;

    // Deploy if this is a deployment transaction and spend part is successful.
    contract_deploy(session, tx, config, &mut receipt);

    // If this is a blob transaction, ensure the gas spent is at least the
    // minimum charge.
    if let Some(blob_min_charge) = blob_min_charge
        && receipt.gas_spent < blob_min_charge
    {
        receipt.gas_spent = blob_min_charge;
    }

    // Ensure all gas is consumed if there's an error in the contract call
    if receipt.data.is_err() {
        receipt.gas_spent = receipt.gas_limit;
    }

    // Refund the appropriate amount to the transaction. If this errors, the
    // transaction must be discarded by the caller who is also responsible to
    // revert the state applied during the spend_and_execute.
    let refund_receipt = session
        .call::<_, ()>(
            TRANSFER_CONTRACT,
            "refund",
            &receipt.gas_spent,
            u64::MAX,
        )
        .inspect_err(|_| {
            clear_session(session, config);
        })
        .map_err(ExecutionError::FailedRefund)?;

    receipt.events.extend(refund_receipt.events);

    clear_session(session, config);

    Ok(receipt)
}

fn check_phoenix_disabled_call(
    callee: &ContractId,
    fn_name: &str,
    fn_args: &[u8],
) -> Result<(), String> {
    if *callee != TRANSFER_CONTRACT
        || !TRANSFER_WITHDRAWAL_FUNCTIONS.contains(&fn_name)
    {
        return Ok(());
    }
    if fn_name == "convert" {
        // `convert` is the transfer contract's Phoenix/Moonlight bridge
        // entrypoint. Phoenix-paid transactions are discarded before execution,
        // so any `convert` that reaches this hook is Moonlight-paid and must
        // still be rejected when Phoenix is disabled.
        return Err(PHOENIX_DISABLED_ERROR.into());
    }
    let withdraw = deserialize_withdraw(fn_args)?;
    if withdraw_uses_phoenix(&withdraw) {
        return Err(PHOENIX_DISABLED_ERROR.into());
    }
    Ok(())
}

fn withdraw_uses_phoenix(withdraw: &Withdraw) -> bool {
    matches!(withdraw.receiver(), WithdrawReceiver::Phoenix(_))
        || matches!(withdraw.token(), WithdrawReplayToken::Phoenix(_))
}

fn deserialize_withdraw(fn_args: &[u8]) -> Result<Withdraw, String> {
    let Ok(root) = rkyv::check_archived_root::<Withdraw>(fn_args) else {
        return Err("failed to deserialize withdrawal arguments".into());
    };
    match root.deserialize(&mut rkyv::Infallible) {
        Ok(w) => Ok(w),
        Err(infallible) => match infallible {},
    }
}

fn is_wasm64(bytecode: &[u8]) -> bool {
    for payload in Parser::new(0).parse_all(bytecode).flatten() {
        if let Payload::MemorySection(section) = payload {
            return section
                .into_iter()
                .any(|memory| memory.is_ok_and(|m| m.memory64));
        }
    }
    false
}

fn clear_session(session: &mut Session, config: &Config) {
    if config.with_public_sender {
        let _ = session.remove_meta(Metadata::PUBLIC_SENDER);
    }
    session.clear_call_hook();
}

/// Checks that a withdrawal's Phoenix replay token nullifier count matches the
/// encapsulating transaction's nullifier count.
///
/// Returns `Err` when the nullifier count mismatches or the arguments
/// cannot be deserialized (fail-closed). Returns `Ok(())` for non-withdrawal
/// calls, Moonlight tokens, or matching counts.
fn check_withdrawal_nullifiers(
    callee: &ContractId,
    fn_name: &str,
    fn_args: &[u8],
    tx_nullifier_count: usize,
) -> Result<(), String> {
    if *callee != TRANSFER_CONTRACT || fn_name != "withdraw" {
        return Ok(());
    }
    let withdraw = deserialize_withdraw(fn_args)?;
    if let WithdrawReplayToken::Phoenix(nullifiers) = withdraw.token()
        && nullifiers.len() != tx_nullifier_count
    {
        return Err(format!(
            "nullifier count mismatch: withdrawal has {}, transaction has {}",
            nullifiers.len(),
            tx_nullifier_count,
        ));
    }
    Ok(())
}

// Contract deployment will fail and charge full gas limit in the
// following cases:
// 1) Pre-Boreas: transaction gas limit is smaller than deploy charge plus gas
//    used for spending funds.
// 2) Boreas+: remaining gas after spending funds is smaller than deploy charge.
// 3) Transaction's bytecode's bytes are not consistent with bytecode's hash.
// 4) Deployment fails for deploy-specific reasons like e.g.:
//      - contract already deployed
//      - corrupted bytecode
//      - sufficient gas to spend funds yet insufficient for deployment
fn contract_deploy(
    session: &mut Session,
    tx: &Transaction,
    config: &Config,
    receipt: &mut CallReceipt<Result<Vec<u8>, ContractError>>,
) {
    if let Some(deploy) = tx.deploy() {
        let gas_per_deploy_byte = config.gas_per_deploy_byte;
        let min_deploy_points = config.min_deploy_points;

        if receipt.data.is_ok() {
            let Ok(deploy_charge) =
                tx.deploy_charge(gas_per_deploy_byte, min_deploy_points)
            else {
                receipt.data =
                    Err(ContractError::Panic("deploy charge overflow".into()));
                return;
            };
            if !is_deploy_gas_sufficient(
                tx.gas_limit(),
                receipt.gas_spent,
                deploy_charge,
                config.deploy_remaining_gas_check,
            ) {
                receipt.data = Err(ContractError::OutOfGas);
            } else if !verify_bytecode_hash(&deploy.bytecode) {
                receipt.data = Err(ContractError::Panic(
                    "failed bytecode hash check".into(),
                ))
            } else if let Err(err) = validate_deploy_bytecode_features(
                &deploy.bytecode.bytes,
                config.with_reference_types,
            ) {
                receipt.data = Err(ContractError::Panic(err.into()))
            } else {
                let gas_left = tx.gas_limit().saturating_sub(receipt.gas_spent);
                let init_budget = if config.charge_init_gas {
                    gas_left.saturating_sub(deploy_charge)
                } else {
                    gas_left
                };
                let result = session.deploy_raw(
                    Some(gen_contract_id(
                        &deploy.bytecode.bytes,
                        deploy.nonce,
                        &deploy.owner,
                    )),
                    deploy.bytecode.bytes.as_slice(),
                    deploy.init_args.clone(),
                    deploy.owner.clone(),
                    init_budget,
                );
                match result {
                    Ok((_, init_receipt)) => {
                        receipt.gas_spent =
                            receipt.gas_spent.saturating_add(deploy_charge);
                        apply_deploy_init_receipt(
                            receipt,
                            init_receipt,
                            config.charge_init_gas,
                        );
                    }
                    Err(err) => {
                        let msg = format!("failed deployment: {err:?}");
                        receipt.data = Err(ContractError::Panic(msg))
                    }
                }
            }
        }
    }
}

fn validate_deploy_bytecode_features(
    bytecode: &[u8],
    with_reference_types: bool,
) -> Result<(), &'static str> {
    if with_reference_types {
        return Ok(());
    }

    Validator::new_with_features(pre_reference_types_deploy_features())
        .validate_all(bytecode)
        .map(|_| ())
        .map_err(|_| DEPLOY_FEATURE_VALIDATION_ERROR)
}

fn pre_reference_types_deploy_features() -> WasmFeatures {
    // Keep this independent from `WasmFeatures::default()`: that default is
    // tied to the local wasmparser version and can grow when the dependency is
    // bumped. This set mirrors dusk-wasmtime defaults before Piecrust enabled
    // the `gc` feature, plus the explicit `wasm_memory64(true)` setting used by
    // Piecrust.
    WasmFeatures::WASM2
        .difference(WasmFeatures::REFERENCE_TYPES)
        .union(WasmFeatures::RELAXED_SIMD)
        .union(WasmFeatures::MULTI_MEMORY)
        .union(WasmFeatures::MEMORY64)
}

fn apply_deploy_init_receipt(
    receipt: &mut CallReceipt<Result<Vec<u8>, ContractError>>,
    init_receipt: Option<CallReceipt<Vec<u8>>>,
    charge_init_gas: bool,
) {
    if let Some(init_receipt) = init_receipt {
        if charge_init_gas {
            receipt.gas_spent =
                receipt.gas_spent.saturating_add(init_receipt.gas_spent);
        }
        receipt.events.extend(init_receipt.events);
    }
}

fn is_deploy_gas_sufficient(
    gas_limit: u64,
    gas_spent: u64,
    deploy_charge: u64,
    deploy_remaining_gas_check: bool,
) -> bool {
    let gas_left = gas_limit.saturating_sub(gas_spent);

    if deploy_remaining_gas_check {
        gas_left >= deploy_charge
    } else {
        gas_spent
            .checked_add(deploy_charge)
            .is_some_and(|required| gas_left >= required)
    }
}

// Verifies that the stored contract bytecode hash is correct.
fn verify_bytecode_hash(bytecode: &ContractBytecode) -> bool {
    let computed: [u8; 32] = blake3::hash(bytecode.bytes.as_slice()).into();

    bytecode.hash == computed
}

#[cfg(test)]
mod tests {
    use alloc::vec;

    use dusk_core::BlsScalar;
    use dusk_core::abi::{ContractId, Event};
    use rand::rngs::StdRng;
    use rand::{RngCore, SeedableRng};
    // Dev-dependencies only used in integration tests trigger the
    // unused_crate_dependencies lint, so we re-import them here.
    use {ff as _, hex as _, once_cell as _};

    use super::*;
    use crate::CallTree;

    #[test]
    fn check_withdrawal_nullifiers_matching_count_passes() {
        let rng = &mut StdRng::seed_from_u64(0xbeef);

        let note_sk = dusk_core::signatures::schnorr::SecretKey::random(rng);
        let note_pk = dusk_core::signatures::schnorr::PublicKey::from(&note_sk);
        let address =
            dusk_core::transfer::phoenix::StealthAddress::from_raw_unchecked(
                *note_pk.as_ref(),
                note_pk,
            );

        let nullifiers = vec![BlsScalar::from(1), BlsScalar::from(2)];
        let withdraw = dusk_core::transfer::withdraw::Withdraw::new(
            rng,
            &note_sk,
            TRANSFER_CONTRACT,
            100,
            dusk_core::transfer::withdraw::WithdrawReceiver::Phoenix(address),
            dusk_core::transfer::withdraw::WithdrawReplayToken::Phoenix(
                nullifiers.clone(),
            ),
        );

        let args =
            rkyv::to_bytes::<_, 4096>(&withdraw).expect("should serialize");

        assert!(
            check_withdrawal_nullifiers(
                &TRANSFER_CONTRACT,
                "withdraw",
                &args,
                nullifiers.len(),
            )
            .is_ok()
        );
    }

    #[test]
    fn check_withdrawal_nullifiers_mismatched_count_rejects() {
        let rng = &mut StdRng::seed_from_u64(0xbeef);

        let note_sk = dusk_core::signatures::schnorr::SecretKey::random(rng);
        let note_pk = dusk_core::signatures::schnorr::PublicKey::from(&note_sk);
        let address =
            dusk_core::transfer::phoenix::StealthAddress::from_raw_unchecked(
                *note_pk.as_ref(),
                note_pk,
            );

        let nullifiers = vec![BlsScalar::from(1), BlsScalar::from(2)];
        let withdraw = dusk_core::transfer::withdraw::Withdraw::new(
            rng,
            &note_sk,
            TRANSFER_CONTRACT,
            100,
            dusk_core::transfer::withdraw::WithdrawReceiver::Phoenix(address),
            dusk_core::transfer::withdraw::WithdrawReplayToken::Phoenix(
                nullifiers,
            ),
        );

        let args =
            rkyv::to_bytes::<_, 4096>(&withdraw).expect("should serialize");

        // Mismatched count: 2 nullifiers in token, but tx has 3
        let err = check_withdrawal_nullifiers(
            &TRANSFER_CONTRACT,
            "withdraw",
            &args,
            3,
        )
        .unwrap_err();
        assert!(
            err.contains("nullifier count mismatch"),
            "expected mismatch message, got: {err}"
        );
        assert!(err.contains("2") && err.contains("3"));
    }

    #[test]
    fn check_withdrawal_nullifiers_ignores_non_withdraw_calls() {
        assert!(
            check_withdrawal_nullifiers(&TRANSFER_CONTRACT, "refund", &[], 5,)
                .is_ok()
        );

        assert!(
            check_withdrawal_nullifiers(
                &ContractId::from_bytes([0xAA; 32]),
                "withdraw",
                &[],
                5,
            )
            .is_ok()
        );
    }

    #[test]
    fn check_withdrawal_nullifiers_rejects_garbage_args() {
        // Garbage bytes that cannot be deserialized as a Withdraw must
        // be rejected (fail-closed).
        let err = check_withdrawal_nullifiers(
            &TRANSFER_CONTRACT,
            "withdraw",
            &[0xDE, 0xAD, 0xBE, 0xEF],
            2,
        )
        .unwrap_err();
        assert!(err.contains("deserialize"));

        // Empty args must also be rejected.
        check_withdrawal_nullifiers(&TRANSFER_CONTRACT, "withdraw", &[], 1)
            .unwrap_err();
    }

    #[test]
    fn check_withdrawal_nullifiers_ignores_moonlight_token() {
        let rng = &mut StdRng::seed_from_u64(0xdead);

        let moonlight_sk = dusk_core::signatures::bls::SecretKey::random(rng);
        let moonlight_pk =
            dusk_core::signatures::bls::PublicKey::from(&moonlight_sk);

        let withdraw = dusk_core::transfer::withdraw::Withdraw::new(
            rng,
            &moonlight_sk,
            TRANSFER_CONTRACT,
            100,
            dusk_core::transfer::withdraw::WithdrawReceiver::Moonlight(
                moonlight_pk,
            ),
            dusk_core::transfer::withdraw::WithdrawReplayToken::Moonlight(42),
        );

        let args =
            rkyv::to_bytes::<_, 4096>(&withdraw).expect("should serialize");

        // Moonlight token — should return Ok even with mismatched count
        assert!(
            check_withdrawal_nullifiers(
                &TRANSFER_CONTRACT,
                "withdraw",
                &args,
                999,
            )
            .is_ok()
        );
    }

    #[test]
    fn test_gen_contract_id() {
        let mut rng = StdRng::seed_from_u64(42);

        let mut bytes = vec![0; 1000];
        rng.fill_bytes(&mut bytes);

        let nonce = rng.next_u64();

        let mut owner = vec![0, 100];
        rng.fill_bytes(&mut owner);

        let contract_id =
            gen_contract_id(bytes.as_slice(), nonce, owner.as_slice());

        assert_eq!(
            contract_id.as_bytes(),
            [
                45, 168, 182, 39, 119, 137, 168, 140, 114, 21, 120, 158, 34,
                126, 244, 221, 151, 72, 109, 178, 82, 229, 84, 128, 92, 123,
                135, 74, 23, 224, 119, 133
            ]
        );
    }

    #[test]
    fn deploy_gas_check_matches_prefork_and_boreas_rules() {
        for (gas_limit, gas_spent, deploy_charge, boreas, expected) in [
            (10_000_000, 3_000_000, 5_000_000, false, false),
            (10_000_000, 3_000_000, 5_000_000, true, true),
            (7_000_000, 3_000_000, 5_000_000, false, false),
            (7_000_000, 3_000_000, 5_000_000, true, false),
            (u64::MAX, u64::MAX, 1, false, false),
        ] {
            assert_eq!(
                is_deploy_gas_sufficient(
                    gas_limit,
                    gas_spent,
                    deploy_charge,
                    boreas,
                ),
                expected,
            );
        }
    }

    #[test]
    fn deploy_bytecode_reference_types_are_height_gated() {
        const EMPTY_MODULE: &[u8] = b"\0asm\x01\0\0\0";
        const FUNC_WITH_EXTERNREF_MODULE: &[u8] = &[
            0x00, 0x61, 0x73, 0x6d, // magic
            0x01, 0x00, 0x00, 0x00, // version
            0x01, // type section
            0x05, // section length
            0x01, // type count
            0x60, // function type
            0x01, // one parameter
            0x6f, // externref
            0x00, // no results
        ];
        const TABLE_WITH_EXTERNREF_MODULE: &[u8] = &[
            0x00, 0x61, 0x73, 0x6d, // magic
            0x01, 0x00, 0x00, 0x00, // version
            0x04, // table section
            0x04, // section length
            0x01, // table count
            0x6f, // externref
            0x00, // min-only limits
            0x01, // minimum table size
        ];

        validate_deploy_bytecode_features(EMPTY_MODULE, false)
            .expect("MVP bytecode should validate without reference-types");

        let err = validate_deploy_bytecode_features(
            FUNC_WITH_EXTERNREF_MODULE,
            false,
        )
        .expect_err("reference-types bytecode should fail before activation");
        assert_eq!(err, DEPLOY_FEATURE_VALIDATION_ERROR);

        let err = validate_deploy_bytecode_features(
            TABLE_WITH_EXTERNREF_MODULE,
            false,
        )
        .expect_err("reference-types table should fail before activation");
        assert_eq!(err, DEPLOY_FEATURE_VALIDATION_ERROR);

        Validator::new_with_features(
            pre_reference_types_deploy_features()
                .union(WasmFeatures::REFERENCE_TYPES),
        )
        .validate_all(FUNC_WITH_EXTERNREF_MODULE)
        .expect("reference-types bytecode should validate when enabled");
    }

    #[test]
    fn pre_reference_types_deploy_features_are_pinned() {
        let features = pre_reference_types_deploy_features();

        assert!(!features.contains(WasmFeatures::REFERENCE_TYPES));
        assert!(!features.contains(WasmFeatures::FUNCTION_REFERENCES));
        assert!(!features.contains(WasmFeatures::GC));
        assert!(!features.contains(WasmFeatures::THREADS));
        assert!(!features.contains(WasmFeatures::TAIL_CALL));

        assert!(features.contains(WasmFeatures::BULK_MEMORY));
        assert!(features.contains(WasmFeatures::MULTI_VALUE));
        assert!(features.contains(WasmFeatures::SIMD));
        assert!(features.contains(WasmFeatures::RELAXED_SIMD));
        assert!(features.contains(WasmFeatures::MULTI_MEMORY));
        assert!(features.contains(WasmFeatures::MEMORY64));
        assert!(!features.contains(WasmFeatures::EXCEPTIONS));
        assert!(!features.contains(WasmFeatures::EXTENDED_CONST));
    }

    #[test]
    fn deploy_init_events_are_preserved_before_and_after_boreas() {
        let init_event = Event {
            source: ContractId::from_bytes([7; 32]),
            topic: "runtime_update".into(),
            data: vec![1, 2, 3, 4],
            reverted: false,
        };
        let build_init_receipt = || CallReceipt {
            gas_spent: 123,
            gas_limit: 999,
            events: vec![init_event.clone()],
            call_tree: CallTree::default(),
            data: Vec::new(),
        };

        let mut prefork_receipt = CallReceipt {
            gas_spent: 10,
            gas_limit: 1000,
            events: vec![],
            call_tree: CallTree::default(),
            data: Ok(Vec::new()),
        };
        apply_deploy_init_receipt(
            &mut prefork_receipt,
            Some(build_init_receipt()),
            false,
        );
        assert_eq!(prefork_receipt.gas_spent, 10);
        assert_eq!(prefork_receipt.events, vec![init_event.clone()]);

        let mut boreas_receipt = CallReceipt {
            gas_spent: 10,
            gas_limit: 1000,
            events: vec![],
            call_tree: CallTree::default(),
            data: Ok(Vec::new()),
        };
        apply_deploy_init_receipt(
            &mut boreas_receipt,
            Some(build_init_receipt()),
            true,
        );
        assert_eq!(boreas_receipt.gas_spent, 133);
        assert_eq!(boreas_receipt.events, vec![init_event]);
    }
}