snarkvm_synthesizer/vm/
execute.rs

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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
// Copyright 2024 Aleo Network Foundation
// This file is part of the snarkVM library.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(clippy::too_many_arguments)]

use super::*;

impl<N: Network, C: ConsensusStorage<N>> VM<N, C> {
    /// Returns a new execute transaction.
    ///
    /// If a `fee_record` is provided, then a private fee will be included in the transaction;
    /// otherwise, a public fee will be included in the transaction.
    ///
    /// The `priority_fee_in_microcredits` is an additional fee **on top** of the execution fee.
    pub fn execute<R: Rng + CryptoRng>(
        &self,
        private_key: &PrivateKey<N>,
        (program_id, function_name): (impl TryInto<ProgramID<N>>, impl TryInto<Identifier<N>>),
        inputs: impl ExactSizeIterator<Item = impl TryInto<Value<N>>>,
        fee_record: Option<Record<N, Plaintext<N>>>,
        priority_fee_in_microcredits: u64,
        query: Option<Query<N, C::BlockStorage>>,
        rng: &mut R,
    ) -> Result<Transaction<N>> {
        // Compute the authorization.
        let authorization = self.authorize(private_key, program_id, function_name, inputs, rng)?;
        // Determine if a fee is required.
        let is_fee_required = !authorization.is_split();
        // Determine if a priority fee is declared.
        let is_priority_fee_declared = priority_fee_in_microcredits > 0;
        // Compute the execution.
        let execution = self.execute_authorization_raw(authorization, query.clone(), rng)?;
        // Compute the fee.
        let fee = match is_fee_required || is_priority_fee_declared {
            true => {
                // Compute the minimum execution cost.
                let query = query.clone().unwrap_or(Query::VM(self.block_store().clone()));
                let block_height = query.current_block_height()?;
                let (minimum_execution_cost, (_, _)) = match block_height < N::CONSENSUS_V2_HEIGHT {
                    true => execution_cost_v1(&self.process().read(), &execution)?,
                    false => execution_cost_v2(&self.process().read(), &execution)?,
                };
                // Compute the execution ID.
                let execution_id = execution.to_execution_id()?;
                // Authorize the fee.
                let authorization = match fee_record {
                    Some(record) => self.authorize_fee_private(
                        private_key,
                        record,
                        minimum_execution_cost,
                        priority_fee_in_microcredits,
                        execution_id,
                        rng,
                    )?,
                    None => self.authorize_fee_public(
                        private_key,
                        minimum_execution_cost,
                        priority_fee_in_microcredits,
                        execution_id,
                        rng,
                    )?,
                };
                // Execute the fee.
                Some(self.execute_fee_authorization_raw(authorization, Some(query), rng)?)
            }
            false => None,
        };
        // Return the execute transaction.
        Transaction::from_execution(execution, fee)
    }

    /// Returns a new execute transaction for the given authorization.
    pub fn execute_authorization<R: Rng + CryptoRng>(
        &self,
        execute_authorization: Authorization<N>,
        fee_authorization: Option<Authorization<N>>,
        query: Option<Query<N, C::BlockStorage>>,
        rng: &mut R,
    ) -> Result<Transaction<N>> {
        // Compute the execution.
        let execution = self.execute_authorization_raw(execute_authorization, query.clone(), rng)?;
        // Compute the fee.
        let fee = match fee_authorization {
            Some(authorization) => Some(self.execute_fee_authorization_raw(authorization, query, rng)?),
            None => None,
        };
        // Return the execute transaction.
        Transaction::from_execution(execution, fee)
    }

    /// Returns a new fee for the given authorization.
    pub fn execute_fee_authorization<R: Rng + CryptoRng>(
        &self,
        authorization: Authorization<N>,
        query: Option<Query<N, C::BlockStorage>>,
        rng: &mut R,
    ) -> Result<Fee<N>> {
        debug_assert!(authorization.is_fee_private() || authorization.is_fee_public(), "Expected a fee authorization");
        self.execute_fee_authorization_raw(authorization, query, rng)
    }
}

impl<N: Network, C: ConsensusStorage<N>> VM<N, C> {
    /// Executes a call to the program function for the given authorization.
    /// Returns the execution.
    #[inline]
    fn execute_authorization_raw<R: Rng + CryptoRng>(
        &self,
        authorization: Authorization<N>,
        query: Option<Query<N, C::BlockStorage>>,
        rng: &mut R,
    ) -> Result<Execution<N>> {
        let timer = timer!("VM::execute_authorization_raw");

        // Construct the locator of the main function.
        let locator = {
            let request = authorization.peek_next()?;
            Locator::new(*request.program_id(), *request.function_name()).to_string()
        };
        // Prepare the query.
        let query = match query {
            Some(query) => query,
            None => Query::VM(self.block_store().clone()),
        };
        lap!(timer, "Prepare the query");

        macro_rules! logic {
            ($process:expr, $network:path, $aleo:path) => {{
                // Prepare the authorization.
                let authorization = cast_ref!(authorization as Authorization<$network>);
                // Execute the call.
                let (_, mut trace) = $process.execute::<$aleo, _>(authorization.clone(), rng)?;
                lap!(timer, "Execute the call");

                // Prepare the assignments.
                cast_mut_ref!(trace as Trace<N>).prepare(query)?;
                lap!(timer, "Prepare the assignments");

                // Compute the proof and construct the execution.
                let execution = trace.prove_execution::<$aleo, _>(&locator, rng)?;
                lap!(timer, "Compute the proof");

                // Return the execution.
                Ok(cast_ref!(execution as Execution<N>).clone())
            }};
        }

        // Execute the authorization.
        let result = process!(self, logic);
        finish!(timer, "Execute the authorization");
        result
    }

    /// Executes a call to the program function for the given fee authorization.
    /// Returns the fee.
    #[inline]
    fn execute_fee_authorization_raw<R: Rng + CryptoRng>(
        &self,
        authorization: Authorization<N>,
        query: Option<Query<N, C::BlockStorage>>,
        rng: &mut R,
    ) -> Result<Fee<N>> {
        let timer = timer!("VM::execute_fee_authorization_raw");

        // Prepare the query.
        let query = match query {
            Some(query) => query,
            None => Query::VM(self.block_store().clone()),
        };
        lap!(timer, "Prepare the query");

        macro_rules! logic {
            ($process:expr, $network:path, $aleo:path) => {{
                // Prepare the authorization.
                let authorization = cast_ref!(authorization as Authorization<$network>);
                // Execute the call.
                let (_, mut trace) = $process.execute::<$aleo, _>(authorization.clone(), rng)?;
                lap!(timer, "Execute the call");

                // Prepare the assignments.
                cast_mut_ref!(trace as Trace<N>).prepare(query)?;
                lap!(timer, "Prepare the assignments");

                // Compute the proof and construct the fee.
                let fee = trace.prove_fee::<$aleo, _>(rng)?;
                lap!(timer, "Compute the proof");

                // Return the fee.
                Ok(cast_ref!(fee as Fee<N>).clone())
            }};
        }

        // Execute the authorization.
        let result = process!(self, logic);
        finish!(timer, "Execute the authorization");
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use console::{
        account::{Address, ViewKey},
        network::MainnetV0,
        program::{Ciphertext, Value},
        types::Field,
    };
    use ledger_block::Transition;
    use ledger_store::helpers::memory::ConsensusMemory;
    use synthesizer_process::{ConsensusFeeVersion, cost_per_command, execution_cost_v2};
    use synthesizer_program::StackProgram;

    use indexmap::IndexMap;

    type CurrentNetwork = MainnetV0;

    fn prepare_vm(
        rng: &mut TestRng,
    ) -> Result<(
        VM<CurrentNetwork, ConsensusMemory<CurrentNetwork>>,
        IndexMap<Field<CurrentNetwork>, Record<CurrentNetwork, Ciphertext<CurrentNetwork>>>,
    )> {
        // Initialize the genesis block.
        let genesis = crate::vm::test_helpers::sample_genesis_block(rng);

        // Fetch the unspent records.
        let records = genesis.transitions().cloned().flat_map(Transition::into_records).collect::<IndexMap<_, _>>();

        // Initialize the genesis block.
        let genesis = crate::vm::test_helpers::sample_genesis_block(rng);

        // Initialize the VM.
        let vm = crate::vm::test_helpers::sample_vm();
        // Update the VM.
        vm.add_next_block(&genesis).unwrap();

        Ok((vm, records))
    }

    #[test]
    fn test_bond_validator_transaction_size() {
        let rng = &mut TestRng::default();

        // Initialize a new caller.
        let validator_private_key = crate::vm::test_helpers::sample_genesis_private_key(rng);
        let withdrawal_private_key = PrivateKey::<CurrentNetwork>::new(rng).unwrap();
        let withdrawal_address = Address::try_from(&withdrawal_private_key).unwrap();

        // Prepare the VM and records.
        let (vm, _) = prepare_vm(rng).unwrap();

        // Prepare the inputs.
        let inputs = [
            Value::<CurrentNetwork>::from_str(&withdrawal_address.to_string()).unwrap(),
            Value::<CurrentNetwork>::from_str("1_000_000u64").unwrap(),
            Value::<CurrentNetwork>::from_str("5u8").unwrap(),
        ]
        .into_iter();

        // Execute.
        let transaction =
            vm.execute(&validator_private_key, ("credits.aleo", "bond_validator"), inputs, None, 0, None, rng).unwrap();

        // Ensure the transaction is a bond public transition.
        assert_eq!(transaction.transitions().count(), 2);
        assert!(transaction.transitions().take(1).next().unwrap().is_bond_validator());

        // Assert the size of the transaction.
        let transaction_size_in_bytes = transaction.to_bytes_le().unwrap().len();
        assert_eq!(2914, transaction_size_in_bytes, "Update me if serialization has changed");

        // Assert the size of the execution.
        assert!(matches!(transaction, Transaction::Execute(_, _, _)));
        if let Transaction::Execute(_, execution, _) = &transaction {
            let execution_size_in_bytes = execution.to_bytes_le().unwrap().len();
            assert_eq!(1463, execution_size_in_bytes, "Update me if serialization has changed");
        }
    }

    #[test]
    fn test_bond_public_transaction_size() {
        let rng = &mut TestRng::default();

        // Initialize a new caller.
        let validator_private_key = crate::vm::test_helpers::sample_genesis_private_key(rng);
        let validator_address = Address::try_from(&validator_private_key).unwrap();
        let delegator_private_key = PrivateKey::<CurrentNetwork>::new(rng).unwrap();
        let delegator_address = Address::try_from(&delegator_private_key).unwrap();

        // Prepare the VM and records.
        let (vm, _) = prepare_vm(rng).unwrap();

        // Prepare the inputs.
        let inputs = [
            Value::<CurrentNetwork>::from_str(&validator_address.to_string()).unwrap(),
            Value::<CurrentNetwork>::from_str(&delegator_address.to_string()).unwrap(),
            Value::<CurrentNetwork>::from_str("1_000_000u64").unwrap(),
        ]
        .into_iter();

        // Execute.
        let transaction =
            vm.execute(&delegator_private_key, ("credits.aleo", "bond_public"), inputs, None, 0, None, rng).unwrap();

        // Ensure the transaction is a bond public transition.
        assert_eq!(transaction.transitions().count(), 2);
        assert!(transaction.transitions().take(1).next().unwrap().is_bond_public());

        // Assert the size of the transaction.
        let transaction_size_in_bytes = transaction.to_bytes_le().unwrap().len();
        assert_eq!(2970, transaction_size_in_bytes, "Update me if serialization has changed");

        // Assert the size of the execution.
        assert!(matches!(transaction, Transaction::Execute(_, _, _)));
        if let Transaction::Execute(_, execution, _) = &transaction {
            let execution_size_in_bytes = execution.to_bytes_le().unwrap().len();
            assert_eq!(1519, execution_size_in_bytes, "Update me if serialization has changed");
        }
    }

    #[cfg(feature = "test")]
    #[test]
    fn test_execute_cost_fee_migration() {
        let rng = &mut TestRng::default();
        let credits_program = "credits.aleo";
        let function_name = "transfer_public";

        // Initialize a new caller.
        let caller_private_key: PrivateKey<MainnetV0> = PrivateKey::new(rng).unwrap();
        let recipient_private_key: PrivateKey<MainnetV0> = PrivateKey::new(rng).unwrap();
        let recipient_address = Address::try_from(&recipient_private_key).unwrap();
        let transfer_public_amount = 1_000_000u64;
        let inputs = &[recipient_address.to_string(), format!("{transfer_public_amount}_u64")];

        // Prepare the VM and records.
        let (vm, _) = prepare_vm(rng).unwrap();

        // Prepare the inputs.

        let authorization = vm.authorize(&caller_private_key, credits_program, function_name, inputs, rng).unwrap();

        let execution = vm.execute_authorization_raw(authorization, None, rng).unwrap();
        let (cost, _) = execution_cost_v2(&vm.process().read(), &execution).unwrap();
        let (old_cost, _) = execution_cost_v1(&vm.process().read(), &execution).unwrap();

        assert_eq!(34_060, cost);
        assert_eq!(51_060, old_cost);

        // Since transfer_public has 2 get.or_use's, the difference is (MAPPING_COST_V1 - MAPPING_BASE_COST_V2) * 2
        assert_eq!(old_cost - cost, 8_500 * 2);
    }

    #[cfg(feature = "test")]
    #[test]
    fn test_fee_migration_occurs_at_correct_block_height() {
        // This test will fail if the consensus v2 height is 0
        assert_ne!(0, CurrentNetwork::CONSENSUS_V2_HEIGHT);

        let rng = &mut TestRng::default();

        // Initialize a new caller.
        let private_key = crate::vm::test_helpers::sample_genesis_private_key(rng);
        let address = Address::try_from(&private_key).unwrap();

        // Prepare the VM and records.
        let (vm, _) = prepare_vm(rng).unwrap();

        // Prepare the inputs.
        let inputs = [
            Value::<CurrentNetwork>::from_str(&address.to_string()).unwrap(),
            Value::<CurrentNetwork>::from_str("1_000_000u64").unwrap(),
        ]
        .into_iter();

        // Execute.
        let transaction =
            vm.execute(&private_key, ("credits.aleo", "transfer_public"), inputs.clone(), None, 0, None, rng).unwrap();

        assert_eq!(51_060, *transaction.base_fee_amount().unwrap());

        let transactions: [Transaction<CurrentNetwork>; 0] = [];
        for _ in 0..CurrentNetwork::CONSENSUS_V2_HEIGHT {
            // Call the function
            let next_block = crate::vm::test_helpers::sample_next_block(&vm, &private_key, &transactions, rng).unwrap();
            vm.add_next_block(&next_block).unwrap();
        }

        let transaction =
            vm.execute(&private_key, ("credits.aleo", "transfer_public"), inputs.clone(), None, 0, None, rng).unwrap();

        assert_eq!(34_060, *transaction.base_fee_amount().unwrap());
    }

    #[cfg(feature = "test")]
    #[test]
    fn test_fee_migration_correctly_calculates_nested() {
        // This test will fail if the consensus v2 height is 0
        assert_ne!(0, CurrentNetwork::CONSENSUS_V2_HEIGHT);

        let rng = &mut TestRng::default();

        // Initialize a new caller.
        let private_key = crate::vm::test_helpers::sample_genesis_private_key(rng);

        // Prepare the VM and records.
        let (vm, _) = prepare_vm(rng).unwrap();

        // Deploy a nested program to test the finalize cost cache
        let program = Program::from_str(
            r"
import credits.aleo;
program nested_call.aleo;
mapping data:
  key as field.public;
  value as field.public;
function test:
  input r0 as u64.public;
  call credits.aleo/transfer_public_as_signer nested_call.aleo r0 into r1;
  async test r1 into r2;
  output r2 as nested_call.aleo/test.future;
finalize test:
  input r0 as credits.aleo/transfer_public_as_signer.future;
  await r0;
  get data[0field] into r1;",
        )
        .unwrap();

        // Deploy the program.
        let transaction = vm.deploy(&private_key, &program, None, 0, None, rng).unwrap();

        // Construct the next block.
        let next_block = crate::test_helpers::sample_next_block(&vm, &private_key, &[transaction], rng).unwrap();

        // Add the next block to the VM.
        vm.add_next_block(&next_block).unwrap();

        // Prepare the inputs.
        let inputs = [Value::<CurrentNetwork>::from_str("1_000_000u64").unwrap()].into_iter();

        // Execute.
        let transaction =
            vm.execute(&private_key, ("nested_call.aleo", "test"), inputs.clone(), None, 0, None, rng).unwrap();

        // This fee should be at least the old credits.aleo/transfer_public fee, 51_060
        assert_eq!(62_776, *transaction.base_fee_amount().unwrap());

        let transactions: [Transaction<CurrentNetwork>; 0] = [];
        for _ in 1..CurrentNetwork::CONSENSUS_V2_HEIGHT {
            // Call the function
            let next_block = crate::vm::test_helpers::sample_next_block(&vm, &private_key, &transactions, rng).unwrap();
            vm.add_next_block(&next_block).unwrap();
        }

        let transaction =
            vm.execute(&private_key, ("nested_call.aleo", "test"), inputs.clone(), None, 0, None, rng).unwrap();

        // The difference in old vs new fees is 8_500 * 3 = 25_500 for the three get/get.or_use's
        // There are two get.or_use's in transfer_public and an additional one in the nested_call.aleo/test
        assert_eq!(37_276, *transaction.base_fee_amount().unwrap());
    }

    #[test]
    fn test_credits_bond_public_cost() {
        let rng = &mut TestRng::default();
        let credits_program = "credits.aleo";
        let function_name = "bond_public";

        // Initialize a new caller.
        let caller_private_key: PrivateKey<MainnetV0> = PrivateKey::new(rng).unwrap();
        let validator_private_key: PrivateKey<MainnetV0> = PrivateKey::new(rng).unwrap();
        let validator_address = Address::try_from(&validator_private_key).unwrap();
        let withdrawal_address = Address::try_from(&caller_private_key).unwrap();
        let bond_public_amount = 1_000_000u64;
        let inputs =
            &[validator_address.to_string(), withdrawal_address.to_string(), format!("{bond_public_amount}_u64")];

        // Prepare the VM and records.
        let (vm, _) = prepare_vm(rng).unwrap();

        // Prepare the inputs.

        let authorization = vm.authorize(&caller_private_key, credits_program, function_name, inputs, rng).unwrap();

        let execution = vm.execute_authorization_raw(authorization, None, rng).unwrap();
        let (cost, _) = execution_cost_v1(&vm.process().read(), &execution).unwrap();
        println!("Cost: {}", cost);
    }

    #[test]
    fn test_unbond_public_transaction_size() {
        let rng = &mut TestRng::default();

        // Initialize a new caller.
        let caller_private_key = crate::vm::test_helpers::sample_genesis_private_key(rng);
        let address = Address::try_from(&caller_private_key).unwrap();

        // Prepare the VM and records.
        let (vm, _) = prepare_vm(rng).unwrap();

        // Prepare the inputs.
        let inputs = [
            Value::<CurrentNetwork>::from_str(&address.to_string()).unwrap(),
            Value::<CurrentNetwork>::from_str("1u64").unwrap(),
        ]
        .into_iter();

        // Execute.
        let transaction =
            vm.execute(&caller_private_key, ("credits.aleo", "unbond_public"), inputs, None, 0, None, rng).unwrap();

        // Ensure the transaction is an unbond public transition.
        assert_eq!(transaction.transitions().count(), 2);
        assert!(transaction.transitions().take(1).next().unwrap().is_unbond_public());

        // Assert the size of the transaction.
        let transaction_size_in_bytes = transaction.to_bytes_le().unwrap().len();
        assert_eq!(2867, transaction_size_in_bytes, "Update me if serialization has changed");

        // Assert the size of the execution.
        assert!(matches!(transaction, Transaction::Execute(_, _, _)));
        if let Transaction::Execute(_, execution, _) = &transaction {
            let execution_size_in_bytes = execution.to_bytes_le().unwrap().len();
            assert_eq!(1416, execution_size_in_bytes, "Update me if serialization has changed");
        }
    }

    #[test]
    fn test_transfer_private_transaction_size() {
        let rng = &mut TestRng::default();

        // Initialize a new caller.
        let caller_private_key = crate::vm::test_helpers::sample_genesis_private_key(rng);
        let caller_view_key = ViewKey::try_from(&caller_private_key).unwrap();
        let address = Address::try_from(&caller_private_key).unwrap();

        // Prepare the VM and records.
        let (vm, records) = prepare_vm(rng).unwrap();

        // Fetch the unspent record.
        let record = records.values().next().unwrap().decrypt(&caller_view_key).unwrap();

        // Prepare the inputs.
        let inputs = [
            Value::<CurrentNetwork>::Record(record),
            Value::<CurrentNetwork>::from_str(&address.to_string()).unwrap(),
            Value::<CurrentNetwork>::from_str("1u64").unwrap(),
        ]
        .into_iter();

        // Execute.
        let transaction =
            vm.execute(&caller_private_key, ("credits.aleo", "transfer_private"), inputs, None, 0, None, rng).unwrap();

        // Assert the size of the transaction.
        let transaction_size_in_bytes = transaction.to_bytes_le().unwrap().len();
        assert_eq!(3693, transaction_size_in_bytes, "Update me if serialization has changed");

        // Assert the size of the execution.
        assert!(matches!(transaction, Transaction::Execute(_, _, _)));
        if let Transaction::Execute(_, execution, _) = &transaction {
            let execution_size_in_bytes = execution.to_bytes_le().unwrap().len();
            assert_eq!(2242, execution_size_in_bytes, "Update me if serialization has changed");
        }
    }

    #[test]
    fn test_transfer_public_transaction_size() {
        let rng = &mut TestRng::default();

        // Initialize a new caller.
        let caller_private_key = crate::vm::test_helpers::sample_genesis_private_key(rng);
        let address = Address::try_from(&caller_private_key).unwrap();

        // Prepare the VM and records.
        let (vm, _) = prepare_vm(rng).unwrap();

        // Prepare the inputs.
        let inputs = [
            Value::<CurrentNetwork>::from_str(&address.to_string()).unwrap(),
            Value::<CurrentNetwork>::from_str("1u64").unwrap(),
        ]
        .into_iter();

        // Execute.
        let transaction =
            vm.execute(&caller_private_key, ("credits.aleo", "transfer_public"), inputs, None, 0, None, rng).unwrap();

        // Assert the size of the transaction.
        let transaction_size_in_bytes = transaction.to_bytes_le().unwrap().len();
        assert_eq!(2871, transaction_size_in_bytes, "Update me if serialization has changed");

        // Assert the size of the execution.
        assert!(matches!(transaction, Transaction::Execute(_, _, _)));
        if let Transaction::Execute(_, execution, _) = &transaction {
            let execution_size_in_bytes = execution.to_bytes_le().unwrap().len();
            assert_eq!(1420, execution_size_in_bytes, "Update me if serialization has changed");
        }
    }

    #[test]
    fn test_transfer_public_as_signer_transaction_size() {
        let rng = &mut TestRng::default();

        // Initialize a new signer.
        let signer = crate::vm::test_helpers::sample_genesis_private_key(rng);
        let address = Address::try_from(&signer).unwrap();

        // Prepare the VM and records.
        let (vm, _) = prepare_vm(rng).unwrap();

        // Prepare the inputs.
        let inputs = [
            Value::<CurrentNetwork>::from_str(&address.to_string()).unwrap(),
            Value::<CurrentNetwork>::from_str("1u64").unwrap(),
        ]
        .into_iter();

        // Execute.
        let transaction =
            vm.execute(&signer, ("credits.aleo", "transfer_public_as_signer"), inputs, None, 0, None, rng).unwrap();

        // Assert the size of the transaction.
        let transaction_size_in_bytes = transaction.to_bytes_le().unwrap().len();
        assert_eq!(2891, transaction_size_in_bytes, "Update me if serialization has changed");

        // Assert the size of the execution.
        assert!(matches!(transaction, Transaction::Execute(_, _, _)));
        if let Transaction::Execute(_, execution, _) = &transaction {
            let execution_size_in_bytes = execution.to_bytes_le().unwrap().len();
            assert_eq!(1440, execution_size_in_bytes, "Update me if serialization has changed");
        }
    }

    #[test]
    fn test_join_transaction_size() {
        let rng = &mut TestRng::default();

        // Initialize a new caller.
        let caller_private_key = crate::vm::test_helpers::sample_genesis_private_key(rng);
        let caller_view_key = ViewKey::try_from(&caller_private_key).unwrap();

        // Prepare the VM and records.
        let (vm, records) = prepare_vm(rng).unwrap();

        // Fetch the unspent records.
        let mut records = records.values();
        let record_1 = records.next().unwrap().decrypt(&caller_view_key).unwrap();
        let record_2 = records.next().unwrap().decrypt(&caller_view_key).unwrap();

        // Prepare the inputs.
        let inputs = [Value::<CurrentNetwork>::Record(record_1), Value::<CurrentNetwork>::Record(record_2)].into_iter();

        // Execute.
        let transaction =
            vm.execute(&caller_private_key, ("credits.aleo", "join"), inputs, None, 0, None, rng).unwrap();

        // Assert the size of the transaction.
        let transaction_size_in_bytes = transaction.to_bytes_le().unwrap().len();
        assert_eq!(3538, transaction_size_in_bytes, "Update me if serialization has changed");

        // Assert the size of the execution.
        assert!(matches!(transaction, Transaction::Execute(_, _, _)));
        if let Transaction::Execute(_, execution, _) = &transaction {
            let execution_size_in_bytes = execution.to_bytes_le().unwrap().len();
            assert_eq!(2087, execution_size_in_bytes, "Update me if serialization has changed");
        }
    }

    #[test]
    fn test_split_transaction_size() {
        let rng = &mut TestRng::default();

        // Initialize a new caller.
        let caller_private_key = crate::vm::test_helpers::sample_genesis_private_key(rng);
        let caller_view_key = ViewKey::try_from(&caller_private_key).unwrap();

        // Prepare the VM and records.
        let (vm, records) = prepare_vm(rng).unwrap();

        // Fetch the unspent record.
        let record = records.values().next().unwrap().decrypt(&caller_view_key).unwrap();

        // Prepare the inputs.
        let inputs =
            [Value::<CurrentNetwork>::Record(record), Value::<CurrentNetwork>::from_str("1u64").unwrap()].into_iter();

        // Execute.
        let transaction =
            vm.execute(&caller_private_key, ("credits.aleo", "split"), inputs, None, 0, None, rng).unwrap();

        // Ensure the transaction is a split transition.
        assert_eq!(transaction.transitions().count(), 1);
        assert!(transaction.transitions().next().unwrap().is_split());

        // Assert the size of the transaction.
        let transaction_size_in_bytes = transaction.to_bytes_le().unwrap().len();
        assert_eq!(2166, transaction_size_in_bytes, "Update me if serialization has changed");

        // Assert the size of the execution.
        assert!(matches!(transaction, Transaction::Execute(_, _, _)));
        if let Transaction::Execute(_, execution, _) = &transaction {
            let execution_size_in_bytes = execution.to_bytes_le().unwrap().len();
            assert_eq!(2131, execution_size_in_bytes, "Update me if serialization has changed");
        }
    }

    #[test]
    fn test_fee_private_transition_size() {
        let rng = &mut TestRng::default();

        // Retrieve a fee transaction.
        let transaction = ledger_test_helpers::sample_fee_private_transaction(rng);
        // Retrieve the fee.
        let fee = match transaction {
            Transaction::Fee(_, fee) => fee,
            _ => panic!("Expected a fee transaction"),
        };

        // Ensure the transition is a fee transition.
        assert!(fee.is_fee_private());

        // Assert the size of the transition.
        let fee_size_in_bytes = fee.to_bytes_le().unwrap().len();
        assert_eq!(2043, fee_size_in_bytes, "Update me if serialization has changed");
    }

    #[test]
    fn test_fee_public_transition_size() {
        let rng = &mut TestRng::default();

        // Retrieve a fee transaction.
        let transaction = ledger_test_helpers::sample_fee_public_transaction(rng);
        // Retrieve the fee.
        let fee = match transaction {
            Transaction::Fee(_, fee) => fee,
            _ => panic!("Expected a fee transaction"),
        };

        // Ensure the transition is a fee transition.
        assert!(fee.is_fee_public());

        // Assert the size of the transition.
        let fee_size_in_bytes = fee.to_bytes_le().unwrap().len();
        assert_eq!(1416, fee_size_in_bytes, "Update me if serialization has changed");
    }

    #[test]
    fn test_wide_nested_execution_cost() {
        // Initialize an RNG.
        let rng = &mut TestRng::default();

        // Initialize a new caller.
        let caller_private_key = crate::vm::test_helpers::sample_genesis_private_key(rng);

        // Prepare the VM.
        let (vm, _) = prepare_vm(rng).unwrap();

        // Construct the child program.
        let child_program = Program::from_str(
            r"
program child.aleo;
mapping data:
    key as field.public;
    value as field.public;
function test:
    input r0 as field.public;
    input r1 as field.public;
    async test r0 r1 into r2;
    output r2 as child.aleo/test.future;
finalize test:
    input r0 as field.public;
    input r1 as field.public;
    hash.bhp256 r0 into r2 as field;
    hash.bhp256 r1 into r3 as field;
    set r2 into data[r3];",
        )
        .unwrap();

        // Deploy the program.
        let transaction = vm.deploy(&caller_private_key, &child_program, None, 0, None, rng).unwrap();

        // Construct the next block.
        let next_block = crate::test_helpers::sample_next_block(&vm, &caller_private_key, &[transaction], rng).unwrap();

        // Add the next block to the VM.
        vm.add_next_block(&next_block).unwrap();

        // Construct the parent program.
        let parent_program = Program::from_str(
            r"
import child.aleo;
program parent.aleo;
function test:
    call child.aleo/test 0field 1field into r0;
    call child.aleo/test 2field 3field into r1;
    call child.aleo/test 4field 5field into r2;
    call child.aleo/test 6field 7field into r3;
    call child.aleo/test 8field 9field into r4;
    call child.aleo/test 10field 11field into r5;
    call child.aleo/test 12field 13field into r6;
    call child.aleo/test 14field 15field into r7;
    call child.aleo/test 16field 17field into r8;
    call child.aleo/test 18field 19field into r9;
    call child.aleo/test 20field 21field into r10;
    call child.aleo/test 22field 23field into r11;
    call child.aleo/test 24field 25field into r12;
    call child.aleo/test 26field 27field into r13;
    call child.aleo/test 28field 29field into r14;
    call child.aleo/test 30field 31field into r15;
    async test r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 into r16;
    output r16 as parent.aleo/test.future;
finalize test:
    input r0 as child.aleo/test.future;
    input r1 as child.aleo/test.future;
    input r2 as child.aleo/test.future;
    input r3 as child.aleo/test.future;
    input r4 as child.aleo/test.future;
    input r5 as child.aleo/test.future;
    input r6 as child.aleo/test.future;
    input r7 as child.aleo/test.future;
    input r8 as child.aleo/test.future;
    input r9 as child.aleo/test.future;
    input r10 as child.aleo/test.future;
    input r11 as child.aleo/test.future;
    input r12 as child.aleo/test.future;
    input r13 as child.aleo/test.future;
    input r14 as child.aleo/test.future;
    input r15 as child.aleo/test.future;
    await r0;
    await r1;
    await r2;
    await r3;
    await r4;
    await r5;
    await r6;
    await r7;
    await r8;
    await r9;
    await r10;
    await r11;
    await r12;
    await r13;
    await r14;
    await r15;",
        )
        .unwrap();

        // Deploy the program.
        let transaction = vm.deploy(&caller_private_key, &parent_program, None, 0, None, rng).unwrap();

        // Construct the next block.
        let next_block = crate::test_helpers::sample_next_block(&vm, &caller_private_key, &[transaction], rng).unwrap();

        // Add the next block to the VM.
        vm.add_next_block(&next_block).unwrap();

        // Execute the parent program.
        let Transaction::Execute(_, execution, _) = vm
            .execute(&caller_private_key, ("parent.aleo", "test"), Vec::<Value<_>>::new().iter(), None, 0, None, rng)
            .unwrap()
        else {
            unreachable!("VM::execute always produces an `Execution`")
        };

        // Check that the number of transitions is correct.
        // Change me if the `MAX_INPUTS` changes.
        assert_eq!(execution.transitions().len(), <CurrentNetwork as Network>::MAX_INPUTS + 1);

        // Get the finalize cost of the execution.
        let (_, (_, finalize_cost)) = execution_cost_v2(&vm.process().read(), &execution).unwrap();

        // Compute the expected cost as the sum of the cost in microcredits of each command in each finalize block of each transition in the execution.
        let mut expected_cost = 0;
        for transition in execution.transitions() {
            // Get the program ID and name of the transition.
            let program_id = transition.program_id();
            let function_name = transition.function_name();
            // Get the stack.
            let stack = vm.process().read().get_stack(program_id).unwrap().clone();
            // Get the finalize block of the transition and sum the cost of each command.
            let cost = match stack.get_function(function_name).unwrap().finalize_logic() {
                None => 0,
                Some(finalize_logic) => {
                    // Aggregate the cost of all commands in the program.
                    finalize_logic
                        .commands()
                        .iter()
                        .map(|command| cost_per_command(&stack, finalize_logic, command, ConsensusFeeVersion::V2))
                        .try_fold(0u64, |acc, res| {
                            res.and_then(|x| acc.checked_add(x).ok_or(anyhow!("Finalize cost overflowed")))
                        })
                        .unwrap()
                }
            };
            // Add the cost to the total cost.
            expected_cost += cost;
        }

        // Check that the finalize cost is equal to the expected cost.
        assert_eq!(finalize_cost, expected_cost);
    }

    #[test]
    #[ignore = "memory-intensive"]
    fn test_deep_nested_execution_cost() {
        // Initialize an RNG.
        let rng = &mut TestRng::default();

        // Initialize a new caller.
        let caller_private_key = crate::vm::test_helpers::sample_genesis_private_key(rng);

        // Prepare the VM.
        let (vm, _) = prepare_vm(rng).unwrap();

        // Construct the base program.
        let base_program = Program::from_str(
            r"
program test_1.aleo;
mapping data:
    key as field.public;
    value as field.public;
function test:
    input r0 as field.public;
    input r1 as field.public;
    async test r0 r1 into r2;
    output r2 as test_1.aleo/test.future;
finalize test:
    input r0 as field.public;
    input r1 as field.public;
    hash.bhp256 r0 into r2 as field;
    hash.bhp256 r1 into r3 as field;
    set r2 into data[r3];",
        )
        .unwrap();

        // Deploy the program.
        let transaction = vm.deploy(&caller_private_key, &base_program, None, 0, None, rng).unwrap();

        // Construct the next block.
        let next_block = crate::test_helpers::sample_next_block(&vm, &caller_private_key, &[transaction], rng).unwrap();

        // Add the next block to the VM.
        vm.add_next_block(&next_block).unwrap();

        // Initialize programs up to the maximum depth.
        for i in 2..=Transaction::<CurrentNetwork>::MAX_TRANSITIONS - 1 {
            // Construct the program.
            let program = Program::from_str(&format!(
                r"
{imports}
program test_{curr}.aleo;
mapping data:
    key as field.public;
    value as field.public;
function test:
    input r0 as field.public;
    input r1 as field.public;
    call test_{prev}.aleo/test r0 r1 into r2;
    async test r0 r1 r2 into r3;
    output r3 as test_{curr}.aleo/test.future;
finalize test:
    input r0 as field.public;
    input r1 as field.public;
    input r2 as test_{prev}.aleo/test.future;
    await r2;
    hash.bhp256 r0 into r3 as field;
    hash.bhp256 r1 into r4 as field;
    set r3 into data[r4];",
                imports = (1..i).map(|j| format!("import test_{j}.aleo;")).join("\n"),
                prev = i - 1,
                curr = i,
            ))
            .unwrap();

            // Deploy the program.
            let transaction = vm.deploy(&caller_private_key, &program, None, 0, None, rng).unwrap();

            // Construct the next block.
            let next_block =
                crate::test_helpers::sample_next_block(&vm, &caller_private_key, &[transaction], rng).unwrap();

            // Add the next block to the VM.
            vm.add_next_block(&next_block).unwrap();
        }

        // Execute the program.
        let Transaction::Execute(_, execution, _) = vm
            .execute(
                &caller_private_key,
                (format!("test_{}.aleo", Transaction::<CurrentNetwork>::MAX_TRANSITIONS - 1), "test"),
                vec![Value::from_str("0field").unwrap(), Value::from_str("1field").unwrap()].iter(),
                None,
                0,
                None,
                rng,
            )
            .unwrap()
        else {
            unreachable!("VM::execute always produces an `Execution`")
        };

        // Check that the number of transitions is correct.
        assert_eq!(execution.transitions().len(), Transaction::<CurrentNetwork>::MAX_TRANSITIONS - 1);

        // Get the finalize cost of the execution.
        let (_, (_, finalize_cost)) = execution_cost_v2(&vm.process().read(), &execution).unwrap();

        // Compute the expected cost as the sum of the cost in microcredits of each command in each finalize block of each transition in the execution.
        let mut expected_cost = 0;
        for transition in execution.transitions() {
            // Get the program ID and name of the transition.
            let program_id = transition.program_id();
            let function_name = transition.function_name();
            // Get the stack.
            let stack = vm.process().read().get_stack(program_id).unwrap().clone();
            // Get the finalize block of the transition and sum the cost of each command.
            let cost = match stack.get_function(function_name).unwrap().finalize_logic() {
                None => 0,
                Some(finalize_logic) => {
                    // Aggregate the cost of all commands in the program.
                    finalize_logic
                        .commands()
                        .iter()
                        .map(|command| cost_per_command(&stack, finalize_logic, command, ConsensusFeeVersion::V2))
                        .try_fold(0u64, |acc, res| {
                            res.and_then(|x| acc.checked_add(x).ok_or(anyhow!("Finalize cost overflowed")))
                        })
                        .unwrap()
                }
            };
            // Add the cost to the total cost.
            expected_cost += cost;
        }

        // Check that the finalize cost is equal to the expected cost.
        assert_eq!(finalize_cost, expected_cost);
    }
}