thruput-tx-validation 0.43.0

Pre-submission transaction checks that mirror the bounds hogd enforces at execution
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
//! Off-chain mirror of the bounds hogd checks before executing a
//! transaction.
//!
//! hogd's `SystemCallHandler::perform_initial_validation` rejects a
//! transaction deterministically, before running any of it, when its root
//! invocation budgets more gas than the chain's `max_tx_gas`, when it
//! attaches more contracts than the chain's network config permits, when
//! any attached contract's code exceeds the size the config admits, when
//! the same contract is attached twice, or when an attached RV32 artifact
//! declares more guest memory or code than the config admits (the
//! attachment fails verification in `NewContractSet::make`). Applying the
//! same checks before submission turns a silent later failure into an
//! immediate, structured [`TxInvalidDetail`].
//!
//! The chain-configured bounds are read from the network config a db tip
//! carries, flattened once into [`NetworkConfigParams`] so every later
//! access is a field read. A bound is enforced only with a value the
//! protocol defines: the one the config states, or, for the parameters
//! whose unstated value the protocol itself fixes
//! (`kDefaultMaxContractSizeBytes`, `kDefaultMaxRv32CodeBytes`,
//! `kDefaultMaxRv32MemoryBytes`, and `max_tx_gas`'s 1,000,000,000), that
//! constant. Nothing is copied from
//! hogd's own fallbacks. None of this is a trust boundary: the executor
//! re-checks everything, and a reading that lags a block is harmless
//! because these parameters change only through explicit config upgrades.

use thruput_json_rpc_types::error::TxInvalidDetail;
use thruput_rv32_artifact::{
    DEFAULT_MAX_CODE_BYTES, DEFAULT_MEMORY_BYTES, DeclaredSizes, declared_sizes,
};
use thruput_xdr::{
    contract::{Contract, kDefaultMaxContractSizeBytes},
    transaction::Transaction,
};

/// `kDefaultMaxRv32CodeBytes` from the protocol's `hog_exec_constants.x`: the
/// code bound in force for a configuration that does not state one.
///
/// The Rust protocol bindings do not bind that file yet, so the value is
/// pinned here and held to the artifact crate's restatement of it.
const DEFAULT_MAX_RV32_CODE_BYTES: u32 = 262_144;
/// `kDefaultMaxRv32MemoryBytes` from `hog_exec_constants.x`: the guest memory
/// bound in force for a configuration that does not state one.
const DEFAULT_MAX_RV32_MEMORY_BYTES: u32 = 65_536;
/// The `max_tx_gas` in force for a configuration that does not state one, as
/// the protocol documents it on `kConfigParamMaxTxGas`. The bindings carry no
/// constant for it, so it is pinned here.
const DEFAULT_MAX_TX_GAS: u64 = 1_000_000_000;
const _: () = assert!(DEFAULT_MAX_RV32_CODE_BYTES as usize == DEFAULT_MAX_CODE_BYTES);
const _: () = assert!(DEFAULT_MAX_RV32_MEMORY_BYTES as usize == DEFAULT_MEMORY_BYTES);

pub use thruput_json_rpc_types::network_config::{NetworkConfigParams, UnsupportedNetworkConfig};

/// Bytes one attached contract's code blob may hold under `params`.
///
/// The protocol fixes `kDefaultMaxContractSizeBytes` as the value in
/// force for a configuration that does not state the parameter, since
/// every chain predating it ran under that cap. Unlike the other bounds,
/// this one is therefore always known.
fn max_contract_size_bytes_in_force(params: &NetworkConfigParams) -> u32 {
    params
        .max_contract_size_bytes
        .unwrap_or(kDefaultMaxContractSizeBytes)
}

/// Code bytes an attached RV32 artifact may carry under `params`.
///
/// The protocol fixes `kDefaultMaxRv32CodeBytes` as the value in force
/// for a configuration that does not state the parameter, so, like the
/// contract size, this bound is always known.
fn max_rv32_code_bytes_in_force(params: &NetworkConfigParams) -> u32 {
    params
        .max_rv32_code_bytes
        .unwrap_or(DEFAULT_MAX_RV32_CODE_BYTES)
}

/// Gas a transaction's root invocation may budget under `params`; the
/// protocol's 1,000,000,000 when unstated, so this bound is always known.
fn max_tx_gas_in_force(params: &NetworkConfigParams) -> u64 {
    params.max_tx_gas.unwrap_or(DEFAULT_MAX_TX_GAS)
}

/// Guest data memory bytes an attached RV32 artifact may declare under
/// `params`; `kDefaultMaxRv32MemoryBytes` when unstated.
fn max_rv32_memory_bytes_in_force(params: &NetworkConfigParams) -> u32 {
    params
        .max_rv32_memory_bytes
        .unwrap_or(DEFAULT_MAX_RV32_MEMORY_BYTES)
}

/// The name a chain execution parameter carries outside its XDR encoding.
///
/// The protocol encodes each parameter as a `ConfigParam` union arm; every
/// surface that has to *say* which parameter it means spells the arm's field
/// name instead. hog-devnode's `--network-config NAME=VALUE` flag keys its
/// genesis overrides by these names and records them under the same names in
/// a data directory's bootstrap metadata. This enum is the one place the
/// Rust side spells them, so a parameter cannot reach hog-devnode under a
/// name no parameter has.
///
/// Naming a parameter says nothing about which values it admits; that stays
/// hog-devnode's call, against the ceilings its build was compiled with.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum ConfigParamName {
    /// [`NetworkConfigParams::max_sha256_buffers`].
    MaxSha256Buffers,
    /// [`NetworkConfigParams::max_cross_invoke_depth`].
    MaxCrossInvokeDepth,
    /// [`NetworkConfigParams::max_new_contracts_per_tx`].
    MaxNewContractsPerTx,
    /// [`NetworkConfigParams::max_bytestring_len`].
    MaxBytestringLen,
    /// [`NetworkConfigParams::max_contract_size_bytes`].
    MaxContractSizeBytes,
    /// [`NetworkConfigParams::max_savepoint_depth`].
    MaxSavepointDepth,
    /// [`NetworkConfigParams::max_auth_token_depth`].
    MaxAuthTokenDepth,
    /// [`NetworkConfigParams::max_rv32_code_bytes`].
    MaxRv32CodeBytes,
    /// [`NetworkConfigParams::max_rv32_memory_bytes`].
    MaxRv32MemoryBytes,
    /// [`NetworkConfigParams::max_tx_gas`].
    MaxTxGas,
}

impl ConfigParamName {
    /// Every parameter this build names, in protocol id order.
    pub const ALL: &[Self] = &[
        Self::MaxSha256Buffers,
        Self::MaxCrossInvokeDepth,
        Self::MaxNewContractsPerTx,
        Self::MaxBytestringLen,
        Self::MaxContractSizeBytes,
        Self::MaxSavepointDepth,
        Self::MaxAuthTokenDepth,
        Self::MaxRv32CodeBytes,
        Self::MaxRv32MemoryBytes,
        Self::MaxTxGas,
    ];

    /// The protocol's field name for this parameter.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MaxSha256Buffers => "max_sha256_buffers",
            Self::MaxCrossInvokeDepth => "max_cross_invoke_depth",
            Self::MaxNewContractsPerTx => "max_new_contracts_per_tx",
            Self::MaxBytestringLen => "max_bytestring_len",
            Self::MaxContractSizeBytes => "max_contract_size_bytes",
            Self::MaxSavepointDepth => "max_savepoint_depth",
            Self::MaxAuthTokenDepth => "max_auth_token_depth",
            Self::MaxRv32CodeBytes => "max_rv32_code_bytes",
            Self::MaxRv32MemoryBytes => "max_rv32_memory_bytes",
            Self::MaxTxGas => "max_tx_gas",
        }
    }

    /// The value `params` states for this parameter, `None` when unstated.
    ///
    /// This is the binding between a name and the field it reads, so a
    /// parameter added to one has to be added to the other.
    pub fn stated_in(self, params: &NetworkConfigParams) -> Option<u64> {
        match self {
            Self::MaxSha256Buffers => params.max_sha256_buffers.map(u64::from),
            Self::MaxCrossInvokeDepth => params.max_cross_invoke_depth.map(u64::from),
            Self::MaxNewContractsPerTx => params.max_new_contracts_per_tx.map(u64::from),
            Self::MaxBytestringLen => params.max_bytestring_len.map(u64::from),
            Self::MaxContractSizeBytes => params.max_contract_size_bytes.map(u64::from),
            Self::MaxSavepointDepth => params.max_savepoint_depth.map(u64::from),
            Self::MaxAuthTokenDepth => params.max_auth_token_depth.map(u64::from),
            Self::MaxRv32CodeBytes => params.max_rv32_code_bytes.map(u64::from),
            Self::MaxRv32MemoryBytes => params.max_rv32_memory_bytes.map(u64::from),
            Self::MaxTxGas => params.max_tx_gas,
        }
    }

    /// The names this build knows, comma-separated, for diagnostics.
    pub fn known_names() -> String {
        Self::ALL
            .iter()
            .copied()
            .map(Self::as_str)
            .collect::<Vec<_>>()
            .join(", ")
    }
}

impl std::fmt::Display for ConfigParamName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for ConfigParamName {
    type Err = UnknownConfigParamName;

    fn from_str(name: &str) -> Result<Self, Self::Err> {
        Self::ALL
            .iter()
            .copied()
            .find(|param| param.as_str() == name)
            .ok_or_else(|| UnknownConfigParamName {
                name: name.to_string(),
            })
    }
}

/// A name that does not belong to any parameter this build knows.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
    "unknown network parameter {name:?}; this build knows {}",
    ConfigParamName::known_names()
)]
pub struct UnknownConfigParamName {
    /// The name as it was written.
    pub name: String,
}

/// Check a decoded transaction against the executor's pre-execution bounds.
///
/// The root invocation's `gas_limit` is checked first, against the
/// `max_tx_gas` in force (1,000,000,000 when unstated), as hogd checks it
/// before any attachment. The duplicate-attachment rule always applies. The attached-contract
/// count is checked only when `params` states a bound for it. Each
/// attached contract's code is checked against the size in force
/// (`kDefaultMaxContractSizeBytes` when unstated), and each attached RV32
/// artifact's declared guest memory and code size against
/// `kDefaultMaxRv32MemoryBytes` and `kDefaultMaxRv32CodeBytes` when
/// unstated, so pass `NetworkConfigParams::default()` when no chain
/// reading is available and the protocol's own values apply.
pub fn check_transaction(
    tx: &Transaction,
    params: &NetworkConfigParams,
) -> Result<(), TxInvalidDetail> {
    let max_gas = max_tx_gas_in_force(params);
    if tx.invocation.gas_limit > max_gas {
        return Err(TxInvalidDetail::GasLimitTooHigh {
            gas_limit: tx.invocation.gas_limit,
            max_gas,
        });
    }

    let contracts = &tx.contracts_to_deploy.0;
    let attached = u32::try_from(contracts.len()).unwrap_or(u32::MAX);

    if let Some(max) = params.max_new_contracts_per_tx
        && attached > max
    {
        return Err(TxInvalidDetail::TooManyContracts { attached, max });
    }

    let max_bytes = max_contract_size_bytes_in_force(params);
    for (index, contract) in contracts.iter().enumerate() {
        let index = u32::try_from(index).unwrap_or(u32::MAX);
        let size_bytes = u32::try_from(contract_code_size(contract)).unwrap_or(u32::MAX);
        if size_bytes > max_bytes {
            return Err(TxInvalidDetail::ContractTooLarge {
                index,
                size_bytes,
                max_bytes,
            });
        }
    }

    // The executor keys attachments by the SHA-256 of their XDR encoding, and
    // TXS encoding is canonical, so value equality is hash equality. The
    // attachment count is small (bounded by `max_new_contracts_per_tx`), so a
    // pairwise scan beats hashing every blob on the submit path.
    for (index, contract) in contracts.iter().enumerate() {
        if let Some(first_index) = contracts[..index].iter().position(|seen| seen == contract) {
            return Err(TxInvalidDetail::DuplicateContract {
                index: u32::try_from(index).unwrap_or(u32::MAX),
                first_index: u32::try_from(first_index).unwrap_or(u32::MAX),
            });
        }
    }

    // hogd verifies each attachment after the gates above, and its artifact
    // parser checks the declared memory before the code size; the same order
    // here, so both name the same first violation.
    let max_memory_bytes = max_rv32_memory_bytes_in_force(params);
    let max_code_bytes = max_rv32_code_bytes_in_force(params);
    for (index, contract) in contracts.iter().enumerate() {
        let Some(sizes) = rv32_declared_sizes(contract) else {
            continue;
        };
        let index = u32::try_from(index).unwrap_or(u32::MAX);
        if sizes.memory_bytes > max_memory_bytes {
            return Err(TxInvalidDetail::Rv32MemoryTooLarge {
                index,
                memory_bytes: sizes.memory_bytes,
                max_bytes: max_memory_bytes,
            });
        }
        if sizes.code_bytes > max_code_bytes {
            return Err(TxInvalidDetail::Rv32CodeTooLarge {
                index,
                code_bytes: sizes.code_bytes,
                max_bytes: max_code_bytes,
            });
        }
    }

    Ok(())
}

/// The sizes an attached RV32 artifact's header declares, when it carries one.
///
/// A blob without a readable v5 header is left to the executor, which rejects
/// it as unverifiable: this pre-check speaks only for headers it can read, and
/// a contract shape this build does not know carries none.
fn rv32_declared_sizes(contract: &Contract) -> Option<DeclaredSizes> {
    match contract {
        Contract::kRv32 { rv32_contract } => declared_sizes(&rv32_contract.data.0),
        _ => None,
    }
}

/// Code bytes the executor charges an attached contract for.
///
/// Mirrors hogd's `contract_blob_size`: only RV32 blobs carry code, and any
/// contract shape this build does not know is treated as code-free so the
/// executor, not this pre-check, decides its fate.
fn contract_code_size(contract: &Contract) -> usize {
    match contract {
        Contract::kRv32 { rv32_contract } => rv32_contract.data.len(),
        _ => 0,
    }
}

#[cfg(test)]
mod tests {
    use thruput_xdr::{
        contract::ContractBlob,
        network_config::{ConfigParam, NetworkConfig, NetworkConfigV0},
        precompiles::HogexecPrecompiledNativeContracts,
        transaction::SignedTransaction,
    };
    use xdr_common::{BytesM, VecM};

    use super::*;

    /// Canonical signed-transaction vector shared with `json-rpc-server`'s
    /// tests; only its inner transaction shape matters here.
    const CANONICAL_SIGNED_TX_XDR: &str = "\
bc10f38522c4e14265a1483af9e5375f5dea0e2c6bf25727ee8b429bf3c1a9b7\
000000000000000000000000000f42400000000000000000000f424000000000000000010000000000000001\
13df30e7ceeb7c4c78ba6287e9d8830cabf5a744f3d6be3139f2428d7bb4f9e7000000000000000000000001\
000000000000000041d0144af2776cae9804ed899018a6bc17a5705d74c84e02556b9695031c9d3fe2554e5c\
e62ceadc95ba43c4aa0884cd2f9ebea4e3845ef877761a6222e91f0d000000010000000050ec72dbafd4898c\
5df0e15ea6ba3e46240945b7210fe2d63dde1e896f42107a";

    fn transaction_with(contracts: Vec<Contract>) -> Transaction {
        let canonical = hex::decode(CANONICAL_SIGNED_TX_XDR).unwrap();
        let mut signed: SignedTransaction = xdrs::txs::decode(&canonical).unwrap();
        signed.tx.contracts_to_deploy = VecM(contracts);
        signed.tx
    }

    fn rv32(size: usize, fill: u8) -> Contract {
        Contract::kRv32 {
            rv32_contract: ContractBlob {
                data: BytesM(vec![fill; size]),
            },
        }
    }

    fn network_config(params: Vec<ConfigParam>) -> NetworkConfig {
        NetworkConfig::_0 {
            v0: NetworkConfigV0 {
                params: VecM(params),
            },
        }
    }

    /// The `ConfigParam` that states `value` for `name`.
    ///
    /// Exhaustive on purpose: a parameter added to [`ConfigParamName`] does
    /// not compile here until it is given its union arm, and the test below
    /// then fails until `from_network_config` lands it on its field.
    fn stated(name: ConfigParamName, value: u32) -> ConfigParam {
        match name {
            ConfigParamName::MaxSha256Buffers => ConfigParam::kConfigParamMaxSHA256Buffers {
                max_sha256_buffers: value,
            },
            ConfigParamName::MaxCrossInvokeDepth => ConfigParam::kConfigParamMaxCrossInvokeDepth {
                max_cross_invoke_depth: value,
            },
            ConfigParamName::MaxNewContractsPerTx => {
                ConfigParam::kConfigParamMaxNewContractsPerTx {
                    max_new_contracts_per_tx: value,
                }
            }
            ConfigParamName::MaxBytestringLen => ConfigParam::kConfigParamMaxBytestringLen {
                max_bytestring_len: value,
            },
            ConfigParamName::MaxContractSizeBytes => {
                ConfigParam::kConfigParamMaxContractSizeBytes {
                    max_contract_size_bytes: value,
                }
            }
            ConfigParamName::MaxSavepointDepth => ConfigParam::kConfigParamMaxSavepointDepth {
                max_savepoint_depth: value,
            },
            ConfigParamName::MaxAuthTokenDepth => ConfigParam::kConfigParamMaxAuthTokenDepth {
                max_auth_token_depth: value,
            },
            ConfigParamName::MaxRv32CodeBytes => ConfigParam::kConfigParamMaxRv32CodeBytes {
                max_rv32_code_bytes: value,
            },
            ConfigParamName::MaxRv32MemoryBytes => ConfigParam::kConfigParamMaxRv32MemoryBytes {
                max_rv32_memory_bytes: value,
            },
            ConfigParamName::MaxTxGas => ConfigParam::kConfigParamMaxTxGas {
                max_tx_gas: u64::from(value),
            },
        }
    }

    #[test]
    fn every_named_parameter_flattens_onto_the_field_it_names() {
        for (name, value) in ConfigParamName::ALL.iter().copied().zip(1_000u32..) {
            let params = NetworkConfigParams::from_network_config(&network_config(vec![stated(
                name, value,
            )]))
            .unwrap();

            assert_eq!(name.stated_in(&params), Some(u64::from(value)), "{name}");
            for other in ConfigParamName::ALL.iter().copied() {
                if other != name {
                    assert_eq!(other.stated_in(&params), None, "{name} also stated {other}");
                }
            }
        }
    }

    #[test]
    fn names_round_trip_and_an_unknown_one_lists_the_known_names() {
        for name in ConfigParamName::ALL.iter().copied() {
            assert_eq!(name.as_str().parse::<ConfigParamName>(), Ok(name));
            assert_eq!(name.to_string(), name.as_str());
        }

        let error = "max_rv32_memmory_bytes"
            .parse::<ConfigParamName>()
            .unwrap_err();

        assert_eq!(error.name, "max_rv32_memmory_bytes");
        assert!(
            error.to_string().contains("max_rv32_memory_bytes"),
            "{error}"
        );
    }

    fn tx_gas_cap(max_tx_gas: u64) -> NetworkConfigParams {
        NetworkConfigParams {
            max_tx_gas: Some(max_tx_gas),
            ..NetworkConfigParams::default()
        }
    }

    fn transaction_budgeting(gas_limit: u64) -> Transaction {
        let mut tx = transaction_with(vec![]);
        tx.invocation.gas_limit = gas_limit;
        tx
    }

    #[test]
    fn root_gas_limit_is_bounded_by_the_default_cap_when_unstated() {
        let params = NetworkConfigParams::default();
        assert_eq!(
            check_transaction(&transaction_budgeting(1_000_000_000), &params),
            Ok(())
        );
        assert_eq!(
            check_transaction(&transaction_budgeting(1_000_000_001), &params),
            Err(TxInvalidDetail::GasLimitTooHigh {
                gas_limit: 1_000_000_001,
                max_gas: 1_000_000_000,
            })
        );
        // The SDK's "all remaining gas" sentinel is no root budget.
        assert_eq!(
            check_transaction(&transaction_budgeting(u64::MAX), &params),
            Err(TxInvalidDetail::GasLimitTooHigh {
                gas_limit: u64::MAX,
                max_gas: 1_000_000_000,
            })
        );
    }

    #[test]
    fn root_gas_limit_is_bounded_by_the_stated_cap() {
        // Lower than the default: the stated cap is the one in force.
        assert_eq!(
            check_transaction(&transaction_budgeting(500_001), &tx_gas_cap(500_000)),
            Err(TxInvalidDetail::GasLimitTooHigh {
                gas_limit: 500_001,
                max_gas: 500_000,
            })
        );
        // Higher than the default: a budget past 1B is admitted.
        assert_eq!(
            check_transaction(
                &transaction_budgeting(5_000_000_000),
                &tx_gas_cap(5_000_000_000)
            ),
            Ok(())
        );
    }

    #[test]
    fn gas_limit_is_checked_before_attachments() {
        // hogd refuses the budget before it looks at any attachment, so an
        // over-budget transaction that also attaches too many contracts is
        // reported for its gas.
        let mut tx = transaction_with(vec![rv32(8, 1), rv32(8, 2)]);
        tx.invocation.gas_limit = 1_000_000_001;
        assert_eq!(
            check_transaction(&tx, &max_contracts(1)),
            Err(TxInvalidDetail::GasLimitTooHigh {
                gas_limit: 1_000_000_001,
                max_gas: 1_000_000_000,
            })
        );
    }

    fn max_contracts(max_new_contracts_per_tx: u32) -> NetworkConfigParams {
        NetworkConfigParams {
            max_new_contracts_per_tx: Some(max_new_contracts_per_tx),
            ..NetworkConfigParams::default()
        }
    }

    fn contract_size_cap(max_contract_size_bytes: u32) -> NetworkConfigParams {
        NetworkConfigParams {
            max_contract_size_bytes: Some(max_contract_size_bytes),
            ..NetworkConfigParams::default()
        }
    }

    fn rv32_caps(
        max_rv32_code_bytes: Option<u32>,
        max_rv32_memory_bytes: Option<u32>,
    ) -> NetworkConfigParams {
        NetworkConfigParams {
            max_rv32_code_bytes,
            max_rv32_memory_bytes,
            ..NetworkConfigParams::default()
        }
    }

    /// A well-formed v5 artifact carrying `code_bytes` of code and declaring
    /// `memory_bytes` of guest memory, as an attached contract.
    fn artifact(code_bytes: usize, memory_bytes: usize) -> Contract {
        let artifact =
            thruput_rv32_artifact::build_artifact(&vec![0u8; code_bytes], &[], 0, memory_bytes)
                .unwrap();
        Contract::kRv32 {
            rv32_contract: ContractBlob {
                data: BytesM(artifact),
            },
        }
    }

    #[test]
    fn every_stated_parameter_lands_on_its_field() {
        let config = network_config(vec![
            ConfigParam::kConfigParamMaxSHA256Buffers {
                max_sha256_buffers: 3,
            },
            ConfigParam::kConfigParamMaxCrossInvokeDepth {
                max_cross_invoke_depth: 17,
            },
            ConfigParam::kConfigParamMaxNewContractsPerTx {
                max_new_contracts_per_tx: 7,
            },
            ConfigParam::kConfigParamMaxBytestringLen {
                max_bytestring_len: 4096,
            },
            ConfigParam::kConfigParamMaxContractSizeBytes {
                max_contract_size_bytes: 131_072,
            },
            ConfigParam::kConfigParamMaxSavepointDepth {
                max_savepoint_depth: 9,
            },
            ConfigParam::kConfigParamMaxAuthTokenDepth {
                max_auth_token_depth: 5,
            },
            ConfigParam::kConfigParamMaxRv32CodeBytes {
                max_rv32_code_bytes: 65536,
            },
            ConfigParam::kConfigParamMaxRv32MemoryBytes {
                max_rv32_memory_bytes: 1_048_576,
            },
            ConfigParam::kConfigParamMaxAuthTokens {
                max_auth_tokens: 64,
            },
            ConfigParam::kConfigParamMaxCalldataLen {
                max_calldata_len: 65_536,
            },
            ConfigParam::kConfigParamMaxReturnBufferLen {
                max_return_buffer_len: 1024,
            },
            ConfigParam::kConfigParamMaxTxGas {
                max_tx_gas: 5_000_000_000,
            },
        ]);

        let params = NetworkConfigParams::from_network_config(&config).unwrap();

        assert_eq!(
            params,
            NetworkConfigParams {
                max_sha256_buffers: Some(3),
                max_cross_invoke_depth: Some(17),
                max_new_contracts_per_tx: Some(7),
                max_bytestring_len: Some(4096),
                max_contract_size_bytes: Some(131_072),
                max_savepoint_depth: Some(9),
                max_auth_token_depth: Some(5),
                max_rv32_code_bytes: Some(65536),
                max_rv32_memory_bytes: Some(1_048_576),
                max_tx_gas: Some(5_000_000_000),
            }
        );
    }

    #[test]
    fn unstated_parameters_stay_unset() {
        // A list that stops after the second id is what a chain predating the
        // later parameters states; nothing is invented for the rest.
        let config = network_config(vec![
            ConfigParam::kConfigParamMaxSHA256Buffers {
                max_sha256_buffers: 8,
            },
            ConfigParam::kConfigParamMaxCrossInvokeDepth {
                max_cross_invoke_depth: 64,
            },
        ]);

        let params = NetworkConfigParams::from_network_config(&config).unwrap();

        assert_eq!(
            params,
            NetworkConfigParams {
                max_sha256_buffers: Some(8),
                max_cross_invoke_depth: Some(64),
                ..NetworkConfigParams::default()
            }
        );
        assert_eq!(
            NetworkConfigParams::from_network_config(&network_config(vec![])).unwrap(),
            NetworkConfigParams::default()
        );
    }

    #[test]
    fn contract_size_in_force_is_the_stated_value_or_the_protocol_default() {
        assert_eq!(
            max_contract_size_bytes_in_force(&NetworkConfigParams::default()),
            kDefaultMaxContractSizeBytes
        );
        assert_eq!(
            max_contract_size_bytes_in_force(&contract_size_cap(1024)),
            1024
        );
    }

    #[test]
    fn transaction_within_bounds_passes() {
        let tx = transaction_with(vec![
            rv32(16, 1),
            rv32(kDefaultMaxContractSizeBytes as usize, 2),
        ]);

        assert_eq!(check_transaction(&tx, &max_contracts(2)), Ok(()));
        assert_eq!(
            check_transaction(&tx, &NetworkConfigParams::default()),
            Ok(())
        );
    }

    #[test]
    fn too_many_contracts_is_rejected_only_when_the_bound_is_stated() {
        let tx = transaction_with(vec![rv32(1, 1), rv32(1, 2), rv32(1, 3)]);

        assert_eq!(
            check_transaction(&tx, &max_contracts(2)),
            Err(TxInvalidDetail::TooManyContracts {
                attached: 3,
                max: 2
            })
        );
        assert_eq!(
            check_transaction(&tx, &NetworkConfigParams::default()),
            Ok(())
        );
    }

    #[test]
    fn oversized_contract_is_rejected_under_the_protocol_default() {
        let tx = transaction_with(vec![
            rv32(1, 1),
            rv32(kDefaultMaxContractSizeBytes as usize + 1, 2),
        ]);

        assert_eq!(
            check_transaction(&tx, &NetworkConfigParams::default()),
            Err(TxInvalidDetail::ContractTooLarge {
                index: 1,
                size_bytes: kDefaultMaxContractSizeBytes + 1,
                max_bytes: kDefaultMaxContractSizeBytes,
            })
        );
    }

    #[test]
    fn stated_contract_size_cap_replaces_the_protocol_default() {
        // A stated cap governs in both directions: below the default it
        // rejects what the default would admit, above it admits what the
        // default would reject.
        let small = transaction_with(vec![rv32(1025, 1)]);
        let large = transaction_with(vec![rv32(kDefaultMaxContractSizeBytes as usize + 1, 1)]);

        assert_eq!(
            check_transaction(&small, &contract_size_cap(1024)),
            Err(TxInvalidDetail::ContractTooLarge {
                index: 0,
                size_bytes: 1025,
                max_bytes: 1024,
            })
        );
        assert_eq!(
            check_transaction(&large, &contract_size_cap(kDefaultMaxContractSizeBytes + 1)),
            Ok(())
        );
    }

    #[test]
    fn count_check_runs_before_size_check() {
        // Cheapest check first: the count is knowable without touching any
        // blob, and the executor orders them the same way.
        let tx = transaction_with(vec![rv32(kDefaultMaxContractSizeBytes as usize + 1, 1); 2]);

        assert!(matches!(
            check_transaction(&tx, &max_contracts(1)),
            Err(TxInvalidDetail::TooManyContracts { .. })
        ));
    }

    #[test]
    fn duplicate_contract_reports_both_positions() {
        let tx = transaction_with(vec![rv32(4, 1), rv32(4, 2), rv32(4, 1)]);

        assert_eq!(
            check_transaction(&tx, &NetworkConfigParams::default()),
            Err(TxInvalidDetail::DuplicateContract {
                index: 2,
                first_index: 0,
            })
        );
    }

    #[test]
    fn rv32_bounds_in_force_are_the_stated_values_or_the_protocol_defaults() {
        let unstated = NetworkConfigParams::default();
        assert_eq!(max_rv32_code_bytes_in_force(&unstated), 262_144);
        assert_eq!(max_rv32_memory_bytes_in_force(&unstated), 65_536);

        let stated = rv32_caps(Some(4096), Some(1 << 20));
        assert_eq!(max_rv32_code_bytes_in_force(&stated), 4096);
        assert_eq!(max_rv32_memory_bytes_in_force(&stated), 1 << 20);
    }

    #[test]
    fn rv32_sizes_at_the_protocol_defaults_pass() {
        let tx = transaction_with(vec![artifact(DEFAULT_MAX_CODE_BYTES, DEFAULT_MEMORY_BYTES)]);

        assert_eq!(
            check_transaction(&tx, &NetworkConfigParams::default()),
            Ok(())
        );
    }

    #[test]
    fn rv32_memory_over_the_bound_is_rejected_and_checked_before_code() {
        // Both fields over: memory is reported, as hogd's artifact parser
        // orders the two checks.
        let tx = transaction_with(vec![
            artifact(16, 1),
            artifact(DEFAULT_MAX_CODE_BYTES + 4, DEFAULT_MEMORY_BYTES + 1),
        ]);

        assert_eq!(
            check_transaction(&tx, &NetworkConfigParams::default()),
            Err(TxInvalidDetail::Rv32MemoryTooLarge {
                index: 1,
                memory_bytes: 65_537,
                max_bytes: 65_536,
            })
        );
    }

    #[test]
    fn rv32_code_over_the_bound_is_rejected() {
        let tx = transaction_with(vec![artifact(
            DEFAULT_MAX_CODE_BYTES + 4,
            DEFAULT_MEMORY_BYTES,
        )]);

        assert_eq!(
            check_transaction(&tx, &NetworkConfigParams::default()),
            Err(TxInvalidDetail::Rv32CodeTooLarge {
                index: 0,
                code_bytes: 262_148,
                max_bytes: 262_144,
            })
        );
    }

    #[test]
    fn stated_rv32_bounds_replace_the_protocol_defaults() {
        // Above the defaults, a chain configured for it admits the artifact.
        let large = transaction_with(vec![artifact(
            DEFAULT_MAX_CODE_BYTES + 4,
            DEFAULT_MEMORY_BYTES + 1,
        )]);
        assert_eq!(
            check_transaction(&large, &rv32_caps(Some(262_148), Some(65_537))),
            Ok(())
        );

        // Below the defaults, a stated cap rejects what the default admits.
        let small = transaction_with(vec![artifact(1024, 4096)]);
        assert_eq!(
            check_transaction(&small, &rv32_caps(Some(1020), None)),
            Err(TxInvalidDetail::Rv32CodeTooLarge {
                index: 0,
                code_bytes: 1024,
                max_bytes: 1020,
            })
        );
        assert_eq!(
            check_transaction(&small, &rv32_caps(None, Some(4095))),
            Err(TxInvalidDetail::Rv32MemoryTooLarge {
                index: 0,
                memory_bytes: 4096,
                max_bytes: 4095,
            })
        );
    }

    #[test]
    fn a_blob_without_an_artifact_header_is_left_to_the_executor() {
        // Not a v5 artifact: the executor rejects it as unverifiable, and this
        // pre-check has no header to read a declared size from.
        let blob = rv32(DEFAULT_MAX_CODE_BYTES + 1024, 0x5a);
        assert_eq!(rv32_declared_sizes(&blob), None);

        let tx = transaction_with(vec![blob]);
        assert_eq!(
            check_transaction(&tx, &rv32_caps(Some(16), Some(16))),
            Ok(())
        );
    }

    #[test]
    fn native_contracts_count_but_carry_no_code() {
        let native = Contract::kNative {
            native_contract_id: HogexecPrecompiledNativeContracts::from(0),
        };
        let tx = transaction_with(vec![native.clone(), rv32(4, 1)]);

        assert_eq!(contract_code_size(&native), 0);
        assert_eq!(
            check_transaction(&tx, &max_contracts(1)),
            Err(TxInvalidDetail::TooManyContracts {
                attached: 2,
                max: 1
            })
        );
    }
}