ethexe-runtime-common 2.0.0-pre.1

Shared runtime types and storage traits for ethexe
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
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
// Copyright (C) Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

use crate::{
    TransitionController,
    state::{
        ActiveProgram, Dispatch, Expiring, MailboxMessage, ModifiableStorage, PayloadLookup,
        Program, ProgramState, Storage,
    },
    transitions::is_event_destination,
};
use alloc::{
    collections::{BTreeMap, BTreeSet},
    vec::Vec,
};
use core::{mem, num::NonZero, panic};
use ethexe_common::{
    ScheduledTask,
    gear::{INJECTED_MESSAGE_PANIC_GAS_CHARGE_THRESHOLD, Message, MessageType},
};
use gear_core::{
    env::MessageWaitedType,
    gas::GasAllowanceCounter,
    memory::PageBuf,
    message::{Dispatch as CoreDispatch, StoredDispatch},
    pages::{GearPage, WasmPage, num_traits::Zero as _, numerated::tree::IntervalsTree},
    reservation::GasReserver,
};
use gear_core_errors::{SignalCode, SuccessReplyReason};
use gear_core_processor::common::{DispatchOutcome, JournalHandler, JournalNote};
use gprimitives::{ActorId, CodeId, H256, MessageId, ReservationId};
use gsys::GasMultiplier;

/// Maximum duration for gr_wait_up_to in blocks,
/// when not enough gas was provided for the requested duration.
pub const WAIT_UP_TO_SAFE_DURATION: u32 = 64;

// Handles unprocessed journal notes during chunk processing.
pub struct NativeJournalHandler<'a, S: Storage + ?Sized> {
    pub program_id: ActorId,
    pub message_type: MessageType,
    pub call_reply: bool,
    pub controller: TransitionController<'a, S>,
    pub gas_allowance_counter: &'a GasAllowanceCounter,
    pub chunk_gas_limit: u64,
    pub out_of_gas: &'a mut bool,
    pub outgoing_messages_limiter: &'a mut u32,
    pub outgoing_messages_bytes_limiter: &'a mut u32,
    pub call_reply_limiter: &'a mut u32,
}

impl<S: Storage + ?Sized> NativeJournalHandler<'_, S> {
    fn send_dispatch_to_program(
        &mut self,
        _message_id: MessageId,
        destination: ActorId,
        dispatch: Dispatch,
        delay: u32,
    ) {
        if !dispatch.value.is_zero() {
            let source = dispatch.source;
            // Decrease sender's balance and value_to_receive
            self.controller
                .update_state(source, |state, _, transitions| {
                    state.balance = state.balance.checked_sub(dispatch.value).expect(
                        "Insufficient balance: underflow in state.balance -= dispatch.value()",
                    );

                    transitions.modify_transition(source, |transition| {
                        transition.value_to_receive = transition
                            .value_to_receive
                            .checked_sub(i128::try_from(dispatch.value).expect("value fits into i128"))
                            .expect("Insufficient balance: underflow in transition.value_to_receive -= dispatch.value()");
                    });

                });
        }

        self.controller
            .update_state(destination, |state, storage: &S, transitions| {
                if let Ok(non_zero_delay) = delay.try_into() {
                    let expiry = transitions.schedule_task(
                        non_zero_delay,
                        ScheduledTask::SendDispatch((destination, dispatch.id)),
                    );

                    storage.modify(&mut state.stash_hash, |stash| {
                        stash.add_to_program(dispatch, expiry);
                    });
                } else {
                    let queue = state.queue_from_msg_type(dispatch.message_type);
                    queue.modify_queue(storage, |queue| queue.queue(dispatch));
                }
            })
    }

    fn send_dispatch_to_user(
        &mut self,
        _message_id: MessageId,
        dispatch: StoredDispatch,
        delay: u32,
    ) {
        // TODO: #5227 delay must be taken into account
        *self.outgoing_messages_limiter = self.outgoing_messages_limiter.saturating_sub(1);
        *self.outgoing_messages_bytes_limiter =
            self.outgoing_messages_bytes_limiter.saturating_sub(
                u32::try_from(dispatch.payload_bytes().len())
                    .expect("payload size is too big for u32 in outgoing messages bytes limiter"),
            );
        if dispatch.is_reply() && self.call_reply {
            *self.call_reply_limiter = self.call_reply_limiter.saturating_sub(1);
        }

        if dispatch.is_reply() {
            self.controller
                .update_state(dispatch.source(), |state, _, transitions| {
                    if dispatch.value() != 0 {
                        state.balance = state.balance.checked_sub(dispatch.value()).expect(
                            "Insufficient balance: underflow in state.balance -= dispatch.value()",
                        );
                    }

                    transitions.modify_transition(dispatch.source(), |transition| {
                        let stored = dispatch.into_parts().1;

                        transition
                            .messages
                            .push(Message::from_stored(stored, self.call_reply))
                    });
                });

            return;
        }

        let message_type = self.message_type;
        let mailbox_validity = self.controller.transitions.cfg().mailbox_validity;
        let event_destinations = self
            .controller
            .transitions
            .cfg()
            .event_destinations_autoreply;
        let destination = dispatch.destination();

        self.controller
            .update_state(dispatch.source(), |state, storage, transitions| {
                let value = dispatch.value();

                // Charge value before branching: event destinations still settle via
                // transition claims and must not touch mailbox or scheduled tasks.
                if !value.is_zero() {
                    state.balance = state.balance.checked_sub(value).expect(
                        "Insufficient balance: underflow in state.balance -= dispatch.value()",
                    );

                    transitions.modify_transition(dispatch.source(), |transition| {
                        transition.value_to_receive = transition
                            .value_to_receive
                            .checked_sub(i128::try_from(value).expect("value fits into i128"))
                            .expect("Insufficient balance: underflow in transition.value_to_receive -= dispatch.value()");
                    });
                }

                if let Ok(non_zero_delay) = delay.try_into() {
                    let expiry = transitions.schedule_task(
                        non_zero_delay,
                        ScheduledTask::SendUserMessage {
                            message_id: dispatch.id(),
                            to_mailbox: dispatch.source(),
                        },
                    );

                    let user_id = dispatch.destination();
                    let dispatch =
                        Dispatch::from_core_stored(storage, dispatch, message_type, false);

                    storage.modify(&mut state.stash_hash, |stash| {
                        stash.add_to_user(dispatch, expiry, user_id);
                    });
                } else if event_destinations && is_event_destination(destination) {
                    let message_id = dispatch.id();

                    transitions.modify_transition(dispatch.source(), |transition| {
                        let stored = dispatch.into_parts().1;

                        transition
                            .messages
                            .push(Message::from_stored(stored, false));
                        transition.claims.push(ethexe_common::gear::ValueClaim {
                            message_id,
                            destination,
                            value,
                        });
                    });

                    let reply = Dispatch::reply(
                        message_id,
                        destination,
                        PayloadLookup::empty(),
                        0,
                        SuccessReplyReason::Auto,
                        message_type,
                        false,
                    );

                    let queue = state.queue_from_msg_type(message_type);
                    queue.modify_queue(storage, |queue| queue.queue(reply));
                } else {
                    let expiry = transitions.schedule_task(
                        mailbox_validity,
                        ScheduledTask::RemoveFromMailbox(
                            (dispatch.source(), dispatch.destination()),
                            dispatch.id(),
                        ),
                    );

                    // TODO (breathx): remove allocation
                    let payload = storage
                        .write_payload_raw(dispatch.payload_bytes().to_vec())
                        .expect("failed to write payload");

                    let message = MailboxMessage::new(payload, dispatch.value(), message_type);

                    storage.modify(&mut state.mailbox_hash, |mailbox| {
                        mailbox.add_and_store_user_mailbox(
                            storage,
                            dispatch.destination(),
                            dispatch.id(),
                            message,
                            expiry,
                        )
                    });

                    transitions.modify_transition(dispatch.source(), |transition| {
                        let stored = dispatch.into_parts().1;

                        transition
                            .messages
                            .push(Message::from_stored(stored, false))
                    });
                }
            });
    }
}

impl<S: Storage + ?Sized> JournalHandler for NativeJournalHandler<'_, S> {
    fn message_dispatched(
        &mut self,
        _message_id: MessageId,
        _source: ActorId,
        _outcome: DispatchOutcome,
    ) {
        unreachable!("Handled inside runtime by `RuntimeJournalHandler`")
    }

    fn gas_burned(&mut self, _message_id: MessageId, _amount: u64) {
        unreachable!("Handled inside runtime by `RuntimeJournalHandler`")
    }

    fn exit_dispatch(&mut self, id_exited: ActorId, inheritor: ActorId) {
        // TODO (breathx): handle rest of value cases; exec balance into value_to_receive.
        let balance = self
            .controller
            .update_state(id_exited, |state, _, transitions| {
                state.program = Program::Exited(inheritor);

                transitions.modify_transition(id_exited, |transition| {
                    transition.inheritor = Some(inheritor);
                });

                mem::replace(&mut state.balance, 0)
            });

        if self.controller.transitions.is_program(&inheritor) {
            self.controller.update_state(inheritor, |state, _, _| {
                state.balance = state.balance.checked_add(balance).expect(
                    "Overflow in state.balance += balance during exit dispatch value transfer",
                );
            })
        }
    }

    fn message_consumed(&mut self, message_id: MessageId) {
        let program_id = self.program_id;

        self.controller
            .update_state(program_id, |state, storage, _| {
                let queue = state.queue_from_msg_type(self.message_type);

                queue.modify_queue(storage, |queue| {
                    let head = queue
                        .dequeue()
                        .expect("an attempt to consume message from empty queue");

                    assert_eq!(
                        head.id, message_id,
                        "queue head doesn't match processed message"
                    );
                });
            })
    }

    fn send_dispatch(
        &mut self,
        message_id: MessageId,
        dispatch: CoreDispatch,
        delay: u32,
        reservation: Option<ReservationId>,
    ) {
        // Reservations are deprecated and gas_limited message dispatches are not supported anymore.
        if reservation.is_some() || dispatch.gas_limit().map(|v| v != 0).unwrap_or(false) {
            unreachable!("deprecated: {dispatch:?}");
        }

        let destination = dispatch.destination();
        let dispatch = dispatch.into_stored();

        if self.controller.transitions.is_program(&destination) {
            let dispatch = Dispatch::from_core_stored(
                self.controller.storage,
                dispatch,
                self.message_type,
                false,
            );

            self.send_dispatch_to_program(message_id, destination, dispatch, delay);
        } else {
            self.send_dispatch_to_user(message_id, dispatch, delay);
        }
    }

    fn wait_dispatch(
        &mut self,
        dispatch: StoredDispatch,
        duration: Option<u32>,
        waited_type: MessageWaitedType,
    ) {
        let Some(mut duration) = duration else {
            unreachable!("Wait dispatch without specified duration is forbidden in ethexe runtime");
        };

        match waited_type {
            MessageWaitedType::Wait => unreachable!("gr_wait is forbidden in ethexe runtime"),
            MessageWaitedType::WaitUpTo => {
                // If not gas was not enough for duration, we use safe duration as max
                duration = duration.min(WAIT_UP_TO_SAFE_DURATION);
            }
            MessageWaitedType::WaitFor | MessageWaitedType::WaitUpToFull => {}
        }

        let in_blocks =
            NonZero::<u32>::try_from(duration).expect("must be checked on backend side");

        let program_id = self.program_id;
        let message_type = self.message_type;
        let call_reply = self.call_reply;

        self.controller
            .update_state(program_id, |state, storage, transitions| {
                let expiry = transitions.schedule_task(
                    in_blocks,
                    ScheduledTask::WakeMessage(dispatch.destination(), dispatch.id()),
                );

                let dispatch =
                    Dispatch::from_core_stored(storage, dispatch, message_type, call_reply);

                let queue = state.queue_from_msg_type(message_type);

                queue.modify_queue(storage, |queue| {
                    let head = queue
                        .dequeue()
                        .expect("an attempt to wait message from empty queue");

                    assert_eq!(
                        head.id, dispatch.id,
                        "queue head doesn't match processed message"
                    );
                });

                storage.modify(&mut state.waitlist_hash, |waitlist| {
                    waitlist.wait(dispatch, expiry);
                });
            });
    }

    // TODO (breathx): deprecate delayed wakes?
    fn wake_message(
        &mut self,
        message_id: MessageId,
        program_id: ActorId,
        awakening_id: MessageId,
        delay: u32,
    ) {
        if delay != 0 {
            unreachable!("delayed wake is forbidden in ethexe runtime");
        }

        log::trace!("Dispatch {message_id} tries to wake {awakening_id}");

        self.controller
            .update_state(program_id, |state, storage, transitions| {
                let Some(Expiring {
                    value: dispatch,
                    expiry,
                }) = storage.modify(&mut state.waitlist_hash, |waitlist| {
                    waitlist.wake(&awakening_id)
                })
                else {
                    return;
                };

                let queue = state.queue_from_msg_type(dispatch.message_type);
                queue.modify_queue(storage, |queue| queue.queue(dispatch));

                transitions
                    .remove_task(
                        expiry,
                        &ScheduledTask::WakeMessage(program_id, awakening_id),
                    )
                    .expect("failed to remove scheduled task");
            });
    }

    fn update_pages_data(
        &mut self,
        _program_id: ActorId,
        _pages_data: BTreeMap<GearPage, PageBuf>,
    ) {
        unreachable!("Handled inside runtime by `RuntimeJournalHandler`")
    }

    fn update_allocations(
        &mut self,
        _program_id: ActorId,
        _new_allocations: IntervalsTree<WasmPage>,
    ) {
        unreachable!("Handled inside runtime by `RuntimeJournalHandler`")
    }

    fn send_value(&mut self, from: ActorId, to: ActorId, value: u128, _locked: bool) {
        if value.is_zero() {
            // Nothing to do
            return;
        }

        let src_is_prog = self.controller.transitions.is_program(&from);
        let dst_is_prog = self.controller.transitions.is_program(&to);

        match (src_is_prog, dst_is_prog) {
            // User to Program or Program to Program value transfer
            (_, true) => {
                self.controller.update_state(to, |state, _, transitions| {
                    state.balance = state
                        .balance
                        .checked_add(value)
                        .expect("Overflow in state.balance += value during value transfer");

                    transitions.modify_transition(to, |transition| {
                        transition.value_to_receive = transition
                            .value_to_receive
                            .checked_add(i128::try_from(value).expect("value fits into i128"))
                            .expect("Overflow in transition.value_to_receive += value");
                    });
                });
            }
            (true, false) => {
                // Program to User value transfer
                unreachable!("Program to User value transfer is not supported");
            }
            (false, false) => {
                // User to User value transfer is not supported
                unreachable!("User to User value transfer is not supported");
            }
        }
    }

    fn store_new_programs(
        &mut self,
        _program_id: ActorId,
        _code_id: CodeId,
        _candidates: Vec<(MessageId, ActorId)>,
    ) {
        todo!()
    }

    fn stop_processing(&mut self, _dispatch: StoredDispatch, _gas_burned: u64) {
        // This means we are out of gas for block, not for chunk.
        if self.gas_allowance_counter.left() < self.chunk_gas_limit {
            *self.out_of_gas = true;
        }
    }

    fn reserve_gas(&mut self, _: MessageId, _: ReservationId, _: ActorId, _: u64, _: u32) {
        unreachable!("deprecated");
    }

    fn unreserve_gas(&mut self, _: ReservationId, _: ActorId, _: u32) {
        unreachable!("deprecated");
    }

    fn update_gas_reservation(&mut self, _: ActorId, _: GasReserver) {
        unreachable!("deprecated");
    }

    fn system_reserve_gas(&mut self, _: MessageId, _: u64) {
        unreachable!("deprecated");
    }

    fn system_unreserve_gas(&mut self, _: MessageId) {
        unreachable!("deprecated");
    }

    fn send_signal(&mut self, _: MessageId, _: ActorId, _: SignalCode) {
        unreachable!("deprecated");
    }

    fn reply_deposit(&mut self, _: MessageId, _: MessageId, _: u64) {
        unreachable!("deprecated");
    }
}

// Handles unprocessed journal notes during message processing in the runtime.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RuntimeQueueReport {
    pub dispatched: Vec<RuntimeDispatchReport>,
    pub gas_burned: Vec<RuntimeGasBurnReport>,
}

impl RuntimeQueueReport {
    pub fn extend(&mut self, other: Self) {
        self.dispatched.extend(other.dispatched);
        self.gas_burned.extend(other.gas_burned);
    }
}

#[derive(Clone, Debug)]
pub struct RuntimeDispatchReport {
    pub message_id: MessageId,
    pub source: ActorId,
    pub outcome: DispatchOutcome,
}

impl PartialEq for RuntimeDispatchReport {
    fn eq(&self, other: &Self) -> bool {
        self.message_id == other.message_id
            && self.source == other.source
            && dispatch_outcome_eq(&self.outcome, &other.outcome)
    }
}

impl Eq for RuntimeDispatchReport {}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuntimeGasBurnReport {
    pub message_id: MessageId,
    pub amount: u64,
    pub charged_to_executable_balance: bool,
}

fn dispatch_outcome_eq(left: &DispatchOutcome, right: &DispatchOutcome) -> bool {
    match (left, right) {
        (
            DispatchOutcome::Exit {
                program_id: left_program_id,
            },
            DispatchOutcome::Exit {
                program_id: right_program_id,
            },
        )
        | (
            DispatchOutcome::InitSuccess {
                program_id: left_program_id,
            },
            DispatchOutcome::InitSuccess {
                program_id: right_program_id,
            },
        ) => left_program_id == right_program_id,
        (
            DispatchOutcome::InitFailure {
                program_id: left_program_id,
                origin: left_origin,
                reason: left_reason,
            },
            DispatchOutcome::InitFailure {
                program_id: right_program_id,
                origin: right_origin,
                reason: right_reason,
            },
        ) => {
            left_program_id == right_program_id
                && left_origin == right_origin
                && left_reason == right_reason
        }
        (
            DispatchOutcome::MessageTrap {
                program_id: left_program_id,
                trap: left_trap,
            },
            DispatchOutcome::MessageTrap {
                program_id: right_program_id,
                trap: right_trap,
            },
        ) => left_program_id == right_program_id && left_trap == right_trap,
        (DispatchOutcome::Success, DispatchOutcome::Success)
        | (DispatchOutcome::NoExecution, DispatchOutcome::NoExecution) => true,
        _ => false,
    }
}

pub struct RuntimeJournalHandler<'s, S>
where
    S: Storage,
{
    pub storage: &'s S,
    pub program_state: &'s mut ProgramState,
    pub gas_allowance_counter: &'s mut GasAllowanceCounter,
    pub gas_multiplier: &'s GasMultiplier,
    pub message_type: MessageType,
    pub is_first_execution: bool,
    pub stop_processing: bool,
    pub call_reply: bool,
    pub limiter: &'s mut Limiter,
}

impl<S> RuntimeJournalHandler<'_, S>
where
    S: Storage,
{
    // Returns unhandled journal notes, new program state hash, and runtime queue report
    pub fn handle_journal_with_report<I>(
        &mut self,
        journal: I,
    ) -> (Vec<JournalNote>, Option<H256>, RuntimeQueueReport)
    where
        I: IntoIterator<Item = JournalNote>,
        I::IntoIter: ExactSizeIterator,
    {
        let journal = journal.into_iter();
        let mut page_updates = BTreeMap::new();
        let mut allocations_update = BTreeMap::new();
        let notes_count = journal.len();
        let mut skipped_notes = 0;
        let mut report = RuntimeQueueReport::default();

        // The set of panic injected messages for which we do not charge executable balance.
        // Dispatches for these messages will not be include into filtered journal notes.
        let mut messages_to_skip = BTreeSet::new();

        let filtered: Vec<_> = journal
            .filter_map(|note| {
                match note {
                    JournalNote::MessageDispatched {
                        message_id,
                        source,
                        outcome,
                    } => {
                        report.dispatched.push(RuntimeDispatchReport {
                            message_id,
                            source,
                            outcome: outcome.clone(),
                        });
                        self.message_dispatched(message_id, source, outcome);
                    }
                    JournalNote::UpdatePage {
                        program_id,
                        page_number,
                        data,
                    } => {
                        let entry = page_updates.entry(program_id).or_insert_with(BTreeMap::new);
                        entry.insert(page_number, data);
                    }
                    JournalNote::UpdateAllocations {
                        program_id,
                        allocations,
                    } => {
                        allocations_update.insert(program_id, allocations);
                    }
                    JournalNote::GasBurned {
                        message_id,
                        amount,
                        is_panic,
                    } => {
                        self.gas_allowance_counter.charge(amount);

                        // Special case for panicked `Injected` messages with gas spent less than the threshold.
                        let charged_to_executable_balance =
                            !is_panic || self.should_charge_exec_balance_on_panic(amount);

                        report.gas_burned.push(RuntimeGasBurnReport {
                            message_id,
                            amount,
                            charged_to_executable_balance,
                        });

                        if charged_to_executable_balance {
                            self.charge_exec_balance(amount);
                        } else {
                            // Message panic and we do not charge exec balance - do not include to journal.
                            messages_to_skip.insert(message_id);
                        }
                    }
                    note @ JournalNote::StopProcessing {
                        dispatch: _,
                        gas_burned,
                    } => {
                        self.gas_allowance_counter.charge(gas_burned);
                        self.stop_processing = true;
                        return Some(note);
                    }
                    // TODO: #5228 handle the listed journal notes here:
                    // * WakeMessage
                    // * SendDispatch to self
                    // * SendValue to self
                    note => {
                        match &note {
                            JournalNote::SendDispatch { message_id, .. }
                                if messages_to_skip.contains(message_id) =>
                            {
                                return None;
                            }
                            JournalNote::SendDispatch { dispatch, .. } => {
                                // TODO: #5227 delay must be taken into account
                                self.limiter.outgoing_messages =
                                    self.limiter.outgoing_messages.saturating_sub(1);
                                self.limiter.outgoing_messages_bytes =
                                    self.limiter.outgoing_messages_bytes.saturating_sub(
                                        u32::try_from(dispatch.payload_bytes().len())
                                            .expect("payload size is too big for u32"),
                                    );

                                if dispatch.is_reply() && self.call_reply {
                                    self.limiter.call_replies =
                                        self.limiter.call_replies.saturating_sub(1);
                                }
                            }
                            _ => {}
                        }

                        skipped_notes += 1;
                        return Some(note);
                    }
                }

                None
            })
            .collect();

        for pages_data in page_updates.into_values() {
            self.update_pages_data(pages_data);
        }

        for allocations in allocations_update.into_values() {
            self.update_allocations(allocations);
        }

        // Some notes were processed, thus state changed
        let maybe_state_hash = (notes_count != skipped_notes)
            .then(|| self.storage.write_program_state(*self.program_state));

        (filtered, maybe_state_hash, report)
    }

    fn message_dispatched(
        &mut self,
        message_id: MessageId,
        _source: ActorId,
        outcome: DispatchOutcome,
    ) {
        match outcome {
            DispatchOutcome::Exit { program_id } => {
                log::trace!("Dispatch outcome exit: {message_id} for program {program_id}")
            }

            DispatchOutcome::InitSuccess { program_id } => {
                log::trace!("Dispatch {message_id} successfully initialized program {program_id}");

                match self.program_state.program {
                    Program::Active(ActiveProgram {
                        ref mut initialized,
                        ..
                    }) if *initialized => {
                        panic!("an attempt to initialize already initialized program")
                    }
                    Program::Active(ActiveProgram {
                        ref mut initialized,
                        ..
                    }) => *initialized = true,
                    _ => panic!("an attempt to dispatch init message for inactive program"),
                };
            }

            DispatchOutcome::InitFailure {
                program_id,
                origin,
                reason,
            } => {
                log::trace!("Dispatch {message_id} failed init of program {program_id}: {reason}");

                self.program_state.program = Program::Terminated(origin)
            }

            DispatchOutcome::MessageTrap { program_id, trap } => {
                log::trace!("Dispatch {message_id} trapped");
                log::debug!("🪤 Program {program_id} terminated with a trap: {trap}");
            }

            DispatchOutcome::Success => log::trace!("Dispatch {message_id} succeed"),

            DispatchOutcome::NoExecution => log::trace!("Dispatch {message_id} wasn't executed"),
        }
    }

    fn update_pages_data(&mut self, pages_data: BTreeMap<GearPage, PageBuf>) {
        if pages_data.is_empty() {
            return;
        }

        let Program::Active(ActiveProgram {
            ref mut pages_hash, ..
        }) = self.program_state.program
        else {
            panic!("an attempt to update pages data of inactive program");
        };

        self.storage.modify(pages_hash, |pages| {
            pages.update_and_store_regions(self.storage, self.storage.write_pages_data(pages_data));
        });
    }

    fn update_allocations(&mut self, new_allocations: IntervalsTree<WasmPage>) {
        let Program::Active(ActiveProgram {
            allocations_hash,
            pages_hash,
            ..
        }) = &mut self.program_state.program
        else {
            panic!("an attempt to update allocations of inactive program");
        };

        let removed_pages = self.storage.modify(allocations_hash, |allocations| {
            allocations.update(new_allocations)
        });

        if !removed_pages.is_empty() {
            self.storage.modify(pages_hash, |pages| {
                pages.remove_and_store_regions(self.storage, &removed_pages);
            })
        }
    }

    fn charge_exec_balance(&mut self, gas_burned: u64) {
        let spent_value = self.gas_multiplier.gas_to_value(gas_burned);
        self.program_state.executable_balance = self
            .program_state
            .executable_balance
            .checked_sub(spent_value)
            .expect(
                "Insufficient executable balance: underflow in executable_balance -= gas_burned",
            );
    }

    // Special case for panicked `Injected` messages with gas spent less than `INJECTED_MESSAGE_PANIC_GAS_CHARGE_THRESHOLD`.
    fn should_charge_exec_balance_on_panic(&self, gas_burned: u64) -> bool {
        gas_burned > INJECTED_MESSAGE_PANIC_GAS_CHARGE_THRESHOLD
            || self.message_type != MessageType::Injected
            || !self.is_first_execution
    }
}

pub(crate) struct Limiter {
    pub outgoing_messages: u32,
    pub outgoing_messages_bytes: u32,
    pub call_replies: u32,
}

#[derive(Debug)]
pub(crate) enum LimitsStatus {
    WithinLimits,
    OutgoingMessagesLimitExceeded,
    OutgoingMessagesBytesLimitExceeded,
    CallRepliesLimitExceeded,
}

impl Limiter {
    pub fn status(&self) -> LimitsStatus {
        if self.outgoing_messages == 0 {
            LimitsStatus::OutgoingMessagesLimitExceeded
        } else if self.outgoing_messages_bytes == 0 {
            LimitsStatus::OutgoingMessagesBytesLimitExceeded
        } else if self.call_replies == 0 {
            LimitsStatus::CallRepliesLimitExceeded
        } else {
            LimitsStatus::WithinLimits
        }
    }
}

#[cfg(test)]
mod tests {
    use ethexe_common::{ProgramStates, StateHashWithQueueSize};
    use gear_core::{
        ids::prelude::MessageIdExt,
        message::{DispatchKind, Message as CoreMessage, ReplyCode, StoredMessage},
    };

    use super::*;

    use crate::{
        InBlockTransitions, TransitionsConfig,
        state::MemStorage,
        transitions::{ETH_SAILS_EVENT, GEAR_SAILS_EVENT},
    };

    fn init_setup(
        exec_balance: u128,
        message_type: MessageType,
        is_first_execution: bool,
    ) -> RuntimeJournalHandler<'static, MemStorage> {
        const INITIAL_GAS_ALLOWANCE: u64 = 1_000_000_000_000;

        let storage = Box::leak(Box::new(MemStorage::default()));
        let program_state = {
            let mut ps = ProgramState::zero();
            ps.executable_balance = exec_balance;
            Box::leak(Box::new(ps))
        };
        let gas_allowance_counter =
            Box::leak(Box::new(GasAllowanceCounter::new(INITIAL_GAS_ALLOWANCE)));
        let gas_multiplier = Box::leak(Box::new(GasMultiplier::from_value_per_gas(100)));
        let limiter = Box::leak(Box::new(Limiter {
            outgoing_messages: 32,
            outgoing_messages_bytes: 4 * 1024,
            call_replies: 16,
        }));

        RuntimeJournalHandler {
            storage,
            program_state,
            gas_allowance_counter,
            gas_multiplier,
            message_type,
            is_first_execution,
            stop_processing: false,
            call_reply: false,
            limiter,
        }
    }

    fn dispatch_to(destination: ActorId, value: u128) -> CoreDispatch {
        CoreDispatch::new(
            DispatchKind::Handle,
            CoreMessage::new(
                MessageId::from(10),
                ActorId::from(7),
                destination,
                Default::default(),
                None,
                value,
                None,
            ),
        )
    }

    fn handle_user_dispatch(
        destination: ActorId,
        event_destinations_autoreply: bool,
    ) -> (MemStorage, ProgramState) {
        let storage = MemStorage::default();
        let source = ActorId::from(7);
        let mut state = ProgramState::zero();
        state.balance = 100;
        let state_hash = storage.write_program_state(state);
        let states = ProgramStates::from_iter([(
            source,
            StateHashWithQueueSize {
                hash: state_hash,
                canonical_queue_size: 0,
                injected_queue_size: 0,
            },
        )]);
        let cfg = TransitionsConfig {
            event_destinations_autoreply,
            ..Default::default()
        };
        let mut transitions = InBlockTransitions::new(cfg, states, Default::default());
        let gas_allowance_counter = GasAllowanceCounter::new(1_000_000);
        let mut out_of_gas = false;
        let mut outgoing_messages_limiter = 10;
        let mut outgoing_messages_bytes_limiter = 1024;
        let mut call_reply_limiter = 10;

        {
            let mut handler = NativeJournalHandler {
                program_id: source,
                message_type: MessageType::Canonical,
                call_reply: false,
                controller: TransitionController {
                    storage: &storage,
                    transitions: &mut transitions,
                },
                gas_allowance_counter: &gas_allowance_counter,
                chunk_gas_limit: 1_000_000,
                out_of_gas: &mut out_of_gas,
                outgoing_messages_limiter: &mut outgoing_messages_limiter,
                outgoing_messages_bytes_limiter: &mut outgoing_messages_bytes_limiter,
                call_reply_limiter: &mut call_reply_limiter,
            };

            handler.send_dispatch(MessageId::from(9), dispatch_to(destination, 11), 0, None);
        }

        let transition = transitions.modifications_mut().remove(&source).unwrap();
        let state_hash = transitions.state_of(&source).unwrap().hash;
        let state = storage.program_state(state_hash).unwrap();

        if event_destinations_autoreply {
            assert_eq!(transition.messages.len(), 1);
            assert_eq!(transition.messages[0].id, MessageId::from(10));
            assert_eq!(transition.messages[0].destination, destination);
            assert_eq!(transition.messages[0].value, 11);
            assert_eq!(transition.claims.len(), 1);
            assert_eq!(transition.claims[0].message_id, MessageId::from(10));
            assert_eq!(transition.claims[0].destination, destination);
            assert_eq!(transition.claims[0].value, 11);
        } else {
            assert_eq!(transition.messages.len(), 1);
            assert!(transition.claims.is_empty());
        }

        (storage, state)
    }

    #[test]
    fn event_destination_messages_skip_mailbox_and_expire_immediately() {
        for destination in [GEAR_SAILS_EVENT, ETH_SAILS_EVENT] {
            let (storage, state) = handle_user_dispatch(destination, true);

            assert!(state.mailbox_hash.is_empty());
            assert_eq!(state.balance, 89);

            let mut queue = state.canonical_queue.query(&storage).unwrap();
            let reply = queue.dequeue().expect("auto reply must be queued");
            assert_eq!(reply.id, MessageId::generate_reply(MessageId::from(10)));
            assert_eq!(reply.kind, DispatchKind::Reply);
            assert_eq!(reply.source, destination);
            assert_eq!(reply.value, 0);
            assert_eq!(reply.message_type, MessageType::Canonical);
            assert!(!reply.call);

            let details = reply.details.unwrap().to_reply_details().unwrap();
            assert_eq!(details.to_message_id(), MessageId::from(10));
            assert_eq!(
                details.to_reply_code(),
                ReplyCode::Success(SuccessReplyReason::Auto)
            );
            assert!(queue.is_empty());
        }
    }

    #[test]
    fn event_destination_messages_keep_legacy_mailbox_when_disabled() {
        let (_storage, state) = handle_user_dispatch(GEAR_SAILS_EVENT, false);

        assert!(!state.mailbox_hash.is_empty());
        assert!(state.canonical_queue.is_empty());
    }

    #[test]
    fn delayed_event_destination_stashes_then_matches_immediate_send() {
        use crate::schedule::Handler;
        use gear_core::tasks::TaskHandler;

        const DELAY: u32 = 5;
        let destination = ETH_SAILS_EVENT;
        let storage = MemStorage::default();
        let source = ActorId::from(7);
        let message_id = MessageId::from(10);
        let mut state = ProgramState::zero();
        state.balance = 100;
        let state_hash = storage.write_program_state(state);
        let states = ProgramStates::from_iter([(
            source,
            StateHashWithQueueSize {
                hash: state_hash,
                canonical_queue_size: 0,
                injected_queue_size: 0,
            },
        )]);
        let cfg = TransitionsConfig {
            event_destinations_autoreply: true,
            ..Default::default()
        };
        let mut transitions = InBlockTransitions::new(cfg, states, Default::default());
        let gas_allowance_counter = GasAllowanceCounter::new(1_000_000);
        let mut out_of_gas = false;
        let mut outgoing_messages_limiter = 10;
        let mut outgoing_messages_bytes_limiter = 1024;
        let mut call_reply_limiter = 10;

        {
            let mut handler = NativeJournalHandler {
                program_id: source,
                message_type: MessageType::Canonical,
                call_reply: false,
                controller: TransitionController {
                    storage: &storage,
                    transitions: &mut transitions,
                },
                gas_allowance_counter: &gas_allowance_counter,
                chunk_gas_limit: 1_000_000,
                out_of_gas: &mut out_of_gas,
                outgoing_messages_limiter: &mut outgoing_messages_limiter,
                outgoing_messages_bytes_limiter: &mut outgoing_messages_bytes_limiter,
                call_reply_limiter: &mut call_reply_limiter,
            };

            handler.send_dispatch(
                MessageId::from(9),
                dispatch_to(destination, 11),
                DELAY,
                None,
            );
        }

        let transition = transitions.modifications_mut().get(&source).unwrap();
        assert!(transition.messages.is_empty());
        assert!(transition.claims.is_empty());

        let state_hash = transitions.state_of(&source).unwrap().hash;
        let state = storage.program_state(state_hash).unwrap();
        assert!(state.mailbox_hash.is_empty());
        assert!(!state.stash_hash.is_empty());
        assert_eq!(state.balance, 89);
        assert!(state.canonical_queue.is_empty());

        {
            let mut handler = Handler {
                controller: TransitionController {
                    storage: &storage,
                    transitions: &mut transitions,
                },
            };
            handler.send_user_message(message_id, source);
        }

        let transition = transitions.modifications_mut().get(&source).unwrap();
        assert_eq!(transition.messages.len(), 1);
        assert_eq!(transition.messages[0].id, message_id);
        assert_eq!(transition.messages[0].destination, destination);
        assert_eq!(transition.messages[0].value, 11);
        assert_eq!(transition.claims.len(), 1);
        assert_eq!(transition.claims[0].message_id, message_id);
        assert_eq!(transition.claims[0].destination, destination);
        assert_eq!(transition.claims[0].value, 11);

        let state_hash = transitions.state_of(&source).unwrap().hash;
        let state = storage.program_state(state_hash).unwrap();
        assert!(state.mailbox_hash.is_empty());
        assert!(state.stash_hash.is_empty());

        let mut queue = state.canonical_queue.query(&storage).unwrap();
        let reply = queue.dequeue().expect("auto reply must be queued");
        assert_eq!(reply.id, MessageId::generate_reply(message_id));
        assert_eq!(reply.source, destination);
        assert_eq!(
            reply
                .details
                .unwrap()
                .to_reply_details()
                .unwrap()
                .to_reply_code(),
            ReplyCode::Success(SuccessReplyReason::Auto)
        );
        assert!(queue.is_empty());
    }

    #[test]
    fn charge_exec_balance() {
        const INITIAL_EXEC_BALANCE: u128 = 500_000_000_000;

        // Special case: Injected message first execution with panic and gas burned less than threshold
        let mut handler = init_setup(INITIAL_EXEC_BALANCE, MessageType::Injected, true);
        handler.handle_journal_with_report(vec![JournalNote::GasBurned {
            message_id: MessageId::new([0u8; 32]),
            amount: INJECTED_MESSAGE_PANIC_GAS_CHARGE_THRESHOLD,
            is_panic: true,
        }]);
        assert_eq!(
            handler.program_state.executable_balance,
            INITIAL_EXEC_BALANCE
        );

        // Normal cases:
        for message_type in [MessageType::Injected, MessageType::Canonical] {
            for is_panic in [false, true] {
                for amount in [
                    INJECTED_MESSAGE_PANIC_GAS_CHARGE_THRESHOLD,
                    INJECTED_MESSAGE_PANIC_GAS_CHARGE_THRESHOLD + 1,
                ] {
                    for is_first_execution in [true, false] {
                        // Skip special case already tested above
                        if message_type == MessageType::Injected
                            && is_panic
                            && is_first_execution
                            && amount == INJECTED_MESSAGE_PANIC_GAS_CHARGE_THRESHOLD
                        {
                            continue;
                        }

                        let mut handler =
                            init_setup(INITIAL_EXEC_BALANCE, message_type, is_first_execution);
                        handler.handle_journal_with_report(vec![JournalNote::GasBurned {
                            message_id: MessageId::new([0u8; 32]),
                            amount,
                            is_panic,
                        }]);
                        let expected_exec_balance =
                            INITIAL_EXEC_BALANCE - handler.gas_multiplier.gas_to_value(amount);
                        assert_eq!(
                            handler.program_state.executable_balance,
                            expected_exec_balance
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn runtime_journal_handler_reports_dispatches_and_gas() {
        const INITIAL_EXEC_BALANCE: u128 = 500_000_000_000;

        let mut handler = init_setup(INITIAL_EXEC_BALANCE, MessageType::Canonical, true);
        let message_id = MessageId::from(42);
        let source = ActorId::from(7);

        let (filtered, _hash, report) = handler.handle_journal_with_report(vec![
            JournalNote::MessageDispatched {
                message_id,
                source,
                outcome: DispatchOutcome::Success,
            },
            JournalNote::GasBurned {
                message_id,
                amount: 123,
                is_panic: false,
            },
        ]);

        assert!(filtered.is_empty());
        assert_eq!(report.dispatched.len(), 1);
        assert_eq!(report.dispatched[0].message_id, message_id);
        assert!(matches!(
            report.dispatched[0].outcome,
            DispatchOutcome::Success
        ));
        assert_eq!(report.gas_burned.len(), 1);
        assert_eq!(report.gas_burned[0].message_id, message_id);
        assert_eq!(report.gas_burned[0].amount, 123);
        assert!(report.gas_burned[0].charged_to_executable_balance);
    }

    #[test]
    fn runtime_journal_handler_reports_injected_panic_charge_exception() {
        const INITIAL_EXEC_BALANCE: u128 = 500_000_000_000;

        let message_id = MessageId::from(42);
        let mut handler = init_setup(INITIAL_EXEC_BALANCE, MessageType::Injected, true);

        let (_filtered, _hash, report) = handler.handle_journal_with_report(vec![
            JournalNote::GasBurned {
                message_id,
                amount: INJECTED_MESSAGE_PANIC_GAS_CHARGE_THRESHOLD,
                is_panic: true,
            },
            JournalNote::GasBurned {
                message_id,
                amount: INJECTED_MESSAGE_PANIC_GAS_CHARGE_THRESHOLD + 1,
                is_panic: true,
            },
        ]);

        assert_eq!(report.gas_burned.len(), 2);
        assert!(!report.gas_burned[0].charged_to_executable_balance);
        assert!(report.gas_burned[1].charged_to_executable_balance);
    }

    #[test]
    fn notes_update_state_hash() {
        let mut handler = init_setup(500_000_000_000, MessageType::Canonical, true);

        // Note unhandled (not processed in RuntimeJournalHandler)
        let (unhandled, state_hash, _) =
            handler.handle_journal_with_report(vec![JournalNote::SendDispatch {
                message_id: MessageId::new([1u8; 32]),
                dispatch: CoreDispatch::new(
                    DispatchKind::Handle,
                    CoreMessage::new(
                        MessageId::new([2u8; 32]),
                        ActorId::new([1u8; 32]),
                        ActorId::new([2u8; 32]),
                        Default::default(),
                        None,
                        0,
                        None,
                    ),
                ),
                delay: 0,
                reservation: None,
            }]);

        assert_eq!(unhandled.len(), 1);
        assert!(state_hash.is_none());

        // Note will be processed in here (in RuntimeJournalHandler) and also forwarded to `NativeJournalHandler`
        // and produce state hash update.
        let (unhandled, state_hash, _) =
            handler.handle_journal_with_report(vec![JournalNote::StopProcessing {
                dispatch: StoredDispatch::new(
                    DispatchKind::Handle,
                    StoredMessage::new(
                        MessageId::new([2u8; 32]),
                        ActorId::new([3u8; 32]),
                        ActorId::new([4u8; 32]),
                        Default::default(),
                        0,
                        None,
                    ),
                    None,
                ),
                gas_burned: 1000,
            }]);

        assert_eq!(unhandled.len(), 1);
        assert!(state_hash.is_some());

        // Note only processed in here (in RuntimeJournalHandler) and produce state hash update.
        let (unhandled, state_hash, _) =
            handler.handle_journal_with_report(vec![JournalNote::UpdatePage {
                program_id: ActorId::new([1u8; 32]),
                page_number: 16.into(),
                data: PageBuf::new_zeroed(),
            }]);
        assert!(unhandled.is_empty());
        assert!(state_hash.is_some());
    }
}