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
// This file is part of Gear.

// Copyright (C) 2022-2024 Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use crate::{
    ids::{MessageId, ProgramId, ReservationId},
    message::{
        Dispatch, HandleMessage, HandlePacket, IncomingMessage, InitMessage, InitPacket, Payload,
        ReplyMessage, ReplyPacket,
    },
    reservation::{GasReserver, ReservationNonce},
};
use alloc::{
    collections::{BTreeMap, BTreeSet},
    vec::Vec,
};
use gear_core_errors::{ExecutionError, ExtError, MessageError as Error, MessageError};
use scale_info::{
    scale::{Decode, Encode},
    TypeInfo,
};

use super::{DispatchKind, IncomingDispatch};

/// Context settings.
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Decode, Encode, TypeInfo)]
pub struct ContextSettings {
    /// Fee for sending message.
    sending_fee: u64,
    /// Fee for sending scheduled message.
    scheduled_sending_fee: u64,
    /// Fee for calling wait.
    waiting_fee: u64,
    /// Fee for waking messages.
    waking_fee: u64,
    /// Fee for creating reservation.
    reservation_fee: u64,
    /// Limit of outgoing messages that program can send during execution of current message.
    outgoing_limit: u32,
}

impl ContextSettings {
    /// Create new ContextSettings.
    pub fn new(
        sending_fee: u64,
        scheduled_sending_fee: u64,
        waiting_fee: u64,
        waking_fee: u64,
        reservation_fee: u64,
        outgoing_limit: u32,
    ) -> Self {
        Self {
            sending_fee,
            scheduled_sending_fee,
            waiting_fee,
            waking_fee,
            reservation_fee,
            outgoing_limit,
        }
    }

    /// Getter for inner sending fee field.
    pub fn sending_fee(&self) -> u64 {
        self.sending_fee
    }

    /// Getter for inner scheduled sending fee field.
    pub fn scheduled_sending_fee(&self) -> u64 {
        self.scheduled_sending_fee
    }

    /// Getter for inner waiting fee field.
    pub fn waiting_fee(&self) -> u64 {
        self.waiting_fee
    }

    /// Getter for inner waking fee field.
    pub fn waking_fee(&self) -> u64 {
        self.waking_fee
    }

    /// Getter for inner reservation fee field.
    pub fn reservation_fee(&self) -> u64 {
        self.reservation_fee
    }

    /// Getter for inner outgoing limit field.
    pub fn outgoing_limit(&self) -> u32 {
        self.outgoing_limit
    }
}

/// Dispatch or message with additional information.
pub type OutgoingMessageInfo<T> = (T, u32, Option<ReservationId>);
pub type OutgoingMessageInfoNoDelay<T> = (T, Option<ReservationId>);

/// Context outcome dispatches and awakening ids.
pub struct ContextOutcomeDrain {
    /// Outgoing dispatches to be sent.
    pub outgoing_dispatches: Vec<OutgoingMessageInfo<Dispatch>>,
    /// Messages to be waken.
    pub awakening: Vec<(MessageId, u32)>,
    /// Reply deposits to be provided.
    pub reply_deposits: Vec<(MessageId, u64)>,
}

/// Context outcome.
///
/// Contains all outgoing messages and wakes that should be done after execution.
#[derive(Default, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Decode, Encode, TypeInfo)]
pub struct ContextOutcome {
    init: Vec<OutgoingMessageInfo<InitMessage>>,
    handle: Vec<OutgoingMessageInfo<HandleMessage>>,
    reply: Option<OutgoingMessageInfoNoDelay<ReplyMessage>>,
    // u32 is delay
    awakening: Vec<(MessageId, u32)>,
    // u64 is gas limit
    // TODO: add Option<ReservationId> after #1828
    reply_deposits: Vec<(MessageId, u64)>,
    // Additional information section.
    program_id: ProgramId,
    source: ProgramId,
    origin_msg_id: MessageId,
}

impl ContextOutcome {
    /// Create new ContextOutcome.
    fn new(program_id: ProgramId, source: ProgramId, origin_msg_id: MessageId) -> Self {
        Self {
            program_id,
            source,
            origin_msg_id,
            ..Default::default()
        }
    }

    /// Destructs outcome after execution and returns provided dispatches and awaken message ids.
    pub fn drain(self) -> ContextOutcomeDrain {
        let mut dispatches = Vec::new();

        for (msg, delay, reservation) in self.init.into_iter() {
            dispatches.push((msg.into_dispatch(self.program_id), delay, reservation));
        }

        for (msg, delay, reservation) in self.handle.into_iter() {
            dispatches.push((msg.into_dispatch(self.program_id), delay, reservation));
        }

        if let Some((msg, reservation)) = self.reply {
            dispatches.push((
                msg.into_dispatch(self.program_id, self.source, self.origin_msg_id),
                0,
                reservation,
            ));
        };

        ContextOutcomeDrain {
            outgoing_dispatches: dispatches,
            awakening: self.awakening,
            reply_deposits: self.reply_deposits,
        }
    }
}

/// Store of previous message execution context.
#[derive(Clone, Default, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Decode, Encode, TypeInfo)]
pub struct ContextStore {
    outgoing: BTreeMap<u32, Option<Payload>>,
    reply: Option<Payload>,
    initialized: BTreeSet<ProgramId>,
    awaken: BTreeSet<MessageId>,
    reply_sent: bool,
    reservation_nonce: ReservationNonce,
    system_reservation: Option<u64>,
}

impl ContextStore {
    /// Returns stored within message context reservation nonce.
    ///
    /// Will be non zero, if any reservations were created during
    /// previous execution of the message.
    pub(crate) fn reservation_nonce(&self) -> ReservationNonce {
        self.reservation_nonce
    }

    /// Set reservation nonce from gas reserver.
    ///
    /// Gas reserver has actual nonce state during/after execution.
    pub fn set_reservation_nonce(&mut self, gas_reserver: &GasReserver) {
        self.reservation_nonce = gas_reserver.nonce();
    }

    /// Set system reservation.
    pub fn add_system_reservation(&mut self, amount: u64) {
        let reservation = &mut self.system_reservation;
        *reservation = reservation
            .map(|reservation| reservation.saturating_add(amount))
            .or(Some(amount));
    }

    /// Get system reservation.
    pub fn system_reservation(&self) -> Option<u64> {
        self.system_reservation
    }

    /// Get info about was reply sent.
    pub fn reply_sent(&self) -> bool {
        self.reply_sent
    }
}

/// Context of currently processing incoming message.
#[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Decode, Encode, TypeInfo)]
pub struct MessageContext {
    kind: DispatchKind,
    current: IncomingMessage,
    outcome: ContextOutcome,
    store: ContextStore,
    settings: ContextSettings,
}

impl MessageContext {
    /// Create new MessageContext with given ContextSettings.
    pub fn new(
        dispatch: IncomingDispatch,
        program_id: ProgramId,
        settings: ContextSettings,
    ) -> Self {
        let (kind, message, store) = dispatch.into_parts();

        Self {
            kind,
            outcome: ContextOutcome::new(program_id, message.source(), message.id()),
            current: message,
            store: store.unwrap_or_default(),
            settings,
        }
    }

    /// Getter for inner settings.
    pub fn settings(&self) -> &ContextSettings {
        &self.settings
    }

    fn check_reply_availability(&self) -> Result<(), ExecutionError> {
        if !matches!(self.kind, DispatchKind::Init | DispatchKind::Handle) {
            return Err(ExecutionError::IncorrectEntryForReply);
        }

        Ok(())
    }

    /// Return bool defining was reply sent within the execution.
    pub fn reply_sent(&self) -> bool {
        self.store.reply_sent
    }

    /// Send a new program initialization message.
    ///
    /// Generates a new message from provided data packet.
    /// Returns message id and generated program id.
    pub fn init_program(
        &mut self,
        packet: InitPacket,
        delay: u32,
    ) -> Result<(MessageId, ProgramId), Error> {
        let program_id = packet.destination();

        if self.store.initialized.contains(&program_id) {
            return Err(Error::DuplicateInit);
        }

        let last = self.store.outgoing.len() as u32;

        if last >= self.settings.outgoing_limit {
            return Err(Error::OutgoingMessagesAmountLimitExceeded);
        }

        let message_id = MessageId::generate_outgoing(self.current.id(), last);
        let message = InitMessage::from_packet(message_id, packet);

        self.store.outgoing.insert(last, None);
        self.store.initialized.insert(program_id);
        self.outcome.init.push((message, delay, None));

        Ok((message_id, program_id))
    }

    /// Send a new program initialization message.
    ///
    /// Generates message from provided data packet and stored by handle payload.
    /// Returns message id.
    pub fn send_commit(
        &mut self,
        handle: u32,
        packet: HandlePacket,
        delay: u32,
        reservation: Option<ReservationId>,
    ) -> Result<MessageId, Error> {
        if let Some(payload) = self.store.outgoing.get_mut(&handle) {
            if let Some(data) = payload.take() {
                let packet = {
                    let mut packet = packet;
                    packet
                        .try_prepend(data)
                        .map_err(|_| Error::MaxMessageSizeExceed)?;
                    packet
                };

                let message_id = MessageId::generate_outgoing(self.current.id(), handle);
                let message = HandleMessage::from_packet(message_id, packet);

                self.outcome.handle.push((message, delay, reservation));

                Ok(message_id)
            } else {
                Err(Error::LateAccess)
            }
        } else {
            Err(Error::OutOfBounds)
        }
    }

    /// Provide space for storing payload for future message creation.
    ///
    /// Returns it's handle.
    pub fn send_init(&mut self) -> Result<u32, Error> {
        let last = self.store.outgoing.len() as u32;

        if last < self.settings.outgoing_limit {
            self.store.outgoing.insert(last, Some(Default::default()));

            Ok(last)
        } else {
            Err(Error::OutgoingMessagesAmountLimitExceeded)
        }
    }

    /// Pushes payload into stored payload by handle.
    pub fn send_push(&mut self, handle: u32, buffer: &[u8]) -> Result<(), Error> {
        match self.store.outgoing.get_mut(&handle) {
            Some(Some(data)) => {
                data.try_extend_from_slice(buffer)
                    .map_err(|_| Error::MaxMessageSizeExceed)?;
                Ok(())
            }
            Some(None) => Err(Error::LateAccess),
            None => Err(Error::OutOfBounds),
        }
    }

    /// Pushes the incoming buffer/payload into stored payload by handle.
    pub fn send_push_input(&mut self, handle: u32, range: CheckedRange) -> Result<(), Error> {
        let data = self
            .store
            .outgoing
            .get_mut(&handle)
            .ok_or(Error::OutOfBounds)?
            .as_mut()
            .ok_or(Error::LateAccess)?;

        let CheckedRange {
            offset,
            excluded_end,
        } = range;

        data.try_extend_from_slice(&self.current.payload_bytes()[offset..excluded_end])
            .map_err(|_| Error::MaxMessageSizeExceed)?;

        Ok(())
    }

    /// Check if provided `offset`/`len` are correct for the current payload
    /// limits. Result `CheckedRange` instance is accepted by
    /// `send_push_input`/`reply_push_input` and has the method `len`
    /// allowing to charge gas before the calls.
    pub fn check_input_range(&self, offset: u32, len: u32) -> CheckedRange {
        let input = self.current.payload_bytes();
        let offset = offset as usize;
        if offset >= input.len() {
            return CheckedRange {
                offset: 0,
                excluded_end: 0,
            };
        }

        CheckedRange {
            offset,
            excluded_end: if len == 0 {
                offset
            } else {
                offset.saturating_add(len as usize).min(input.len())
            },
        }
    }

    /// Send reply message.
    ///
    /// Generates reply from provided data packet and stored reply payload.
    /// Returns message id.
    pub fn reply_commit(
        &mut self,
        packet: ReplyPacket,
        reservation: Option<ReservationId>,
    ) -> Result<MessageId, ExtError> {
        self.check_reply_availability()?;

        if !self.reply_sent() {
            let data = self.store.reply.take().unwrap_or_default();

            let packet = {
                let mut packet = packet;
                packet
                    .try_prepend(data)
                    .map_err(|_| Error::MaxMessageSizeExceed)?;
                packet
            };

            let message_id = MessageId::generate_reply(self.current.id());
            let message = ReplyMessage::from_packet(message_id, packet);

            self.outcome.reply = Some((message, reservation));
            self.store.reply_sent = true;

            Ok(message_id)
        } else {
            Err(Error::DuplicateReply.into())
        }
    }

    /// Pushes payload into stored reply payload.
    pub fn reply_push(&mut self, buffer: &[u8]) -> Result<(), ExtError> {
        self.check_reply_availability()?;

        if !self.reply_sent() {
            let data = self.store.reply.get_or_insert_with(Default::default);
            data.try_extend_from_slice(buffer)
                .map_err(|_| Error::MaxMessageSizeExceed)?;

            Ok(())
        } else {
            Err(Error::LateAccess.into())
        }
    }

    /// Return reply destination.
    pub fn reply_destination(&self) -> ProgramId {
        self.outcome.source
    }

    /// Pushes the incoming message buffer into stored reply payload.
    pub fn reply_push_input(&mut self, range: CheckedRange) -> Result<(), ExtError> {
        self.check_reply_availability()?;

        if !self.reply_sent() {
            let CheckedRange {
                offset,
                excluded_end,
            } = range;

            let data = self.store.reply.get_or_insert_with(Default::default);
            data.try_extend_from_slice(&self.current.payload_bytes()[offset..excluded_end])
                .map_err(|_| Error::MaxMessageSizeExceed)?;

            Ok(())
        } else {
            Err(Error::LateAccess.into())
        }
    }

    /// Wake message by it's message id.
    pub fn wake(&mut self, waker_id: MessageId, delay: u32) -> Result<(), Error> {
        if self.store.awaken.insert(waker_id) {
            self.outcome.awakening.push((waker_id, delay));

            Ok(())
        } else {
            Err(Error::DuplicateWaking)
        }
    }

    /// Create deposit to handle future reply on message id was sent.
    pub fn reply_deposit(
        &mut self,
        message_id: MessageId,
        amount: u64,
    ) -> Result<(), MessageError> {
        if self
            .outcome
            .reply_deposits
            .iter()
            .any(|(mid, _)| mid == &message_id)
        {
            return Err(MessageError::DuplicateReplyDeposit);
        }

        if !self
            .outcome
            .handle
            .iter()
            .any(|(message, ..)| message.id() == message_id)
            && !self
                .outcome
                .init
                .iter()
                .any(|(message, ..)| message.id() == message_id)
        {
            return Err(MessageError::IncorrectMessageForReplyDeposit);
        }

        self.outcome.reply_deposits.push((message_id, amount));

        Ok(())
    }

    /// Current processing incoming message.
    pub fn current(&self) -> &IncomingMessage {
        &self.current
    }

    /// Mutable reference to currently processed incoming message.
    pub fn payload_mut(&mut self) -> &mut Payload {
        self.current.payload_mut()
    }

    /// Current program's id.
    pub fn program_id(&self) -> ProgramId {
        self.outcome.program_id
    }

    /// Destructs context after execution and returns provided outcome and store.
    pub fn drain(self) -> (ContextOutcome, ContextStore) {
        let Self { outcome, store, .. } = self;

        (outcome, store)
    }
}

pub struct CheckedRange {
    offset: usize,
    excluded_end: usize,
}

impl CheckedRange {
    pub fn len(&self) -> u32 {
        (self.excluded_end - self.offset) as u32
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;
    use core::convert::TryInto;

    macro_rules! assert_ok {
        ( $x:expr $(,)? ) => {
            let is = $x;
            match is {
                Ok(_) => (),
                _ => assert!(false, "Expected Ok(_). Got {:#?}", is),
            }
        };
        ( $x:expr, $y:expr $(,)? ) => {
            assert_eq!($x, Ok($y));
        };
    }

    macro_rules! assert_err {
        ( $x:expr , $y:expr $(,)? ) => {
            assert_eq!($x, Err($y.into()));
        };
    }

    #[test]
    fn duplicated_init() {
        let mut message_context = MessageContext::new(
            Default::default(),
            Default::default(),
            ContextSettings::new(0, 0, 0, 0, 0, 1024),
        );

        // first init to default ProgramId.
        assert_ok!(message_context.init_program(Default::default(), 0));

        // second init to same default ProgramId should get error.
        assert_err!(
            message_context.init_program(Default::default(), 0),
            Error::DuplicateInit,
        );
    }

    #[test]
    fn outgoing_limit_exceeded() {
        // Check that we can always send exactly outgoing_limit messages.
        let max_n = 5;

        for n in 0..=max_n {
            // for outgoing_limit n checking that LimitExceeded will be after n's message.
            let settings = ContextSettings::new(0, 0, 0, 0, 0, n);

            let mut message_context =
                MessageContext::new(Default::default(), Default::default(), settings);
            // send n messages
            for _ in 0..n {
                let handle = message_context.send_init().expect("unreachable");
                message_context
                    .send_push(handle, b"payload")
                    .expect("unreachable");
                message_context
                    .send_commit(handle, HandlePacket::default(), 0, None)
                    .expect("unreachable");
            }
            // n + 1 should get first error.
            let limit_exceeded = message_context.send_init();
            assert_eq!(
                limit_exceeded,
                Err(Error::OutgoingMessagesAmountLimitExceeded)
            );

            // we can't send messages in this MessageContext.
            let limit_exceeded = message_context.init_program(Default::default(), 0);
            assert_eq!(
                limit_exceeded,
                Err(Error::OutgoingMessagesAmountLimitExceeded)
            );
        }
    }

    #[test]
    fn invalid_out_of_bounds() {
        let mut message_context = MessageContext::new(
            Default::default(),
            Default::default(),
            ContextSettings::new(0, 0, 0, 0, 0, 1024),
        );

        // Use invalid handle 0.
        let out_of_bounds = message_context.send_commit(0, Default::default(), 0, None);
        assert_eq!(out_of_bounds, Err(Error::OutOfBounds));

        // make 0 valid.
        let valid_handle = message_context.send_init().expect("unreachable");
        assert_eq!(valid_handle, 0);

        // Use valid handle 0.
        assert_ok!(message_context.send_commit(0, Default::default(), 0, None));

        // Use invalid handle 42.
        assert_err!(
            message_context.send_commit(42, Default::default(), 0, None),
            Error::OutOfBounds,
        );
    }

    #[test]
    fn double_reply() {
        let mut message_context = MessageContext::new(
            Default::default(),
            Default::default(),
            ContextSettings::new(0, 0, 0, 0, 0, 1024),
        );

        // First reply.
        assert_ok!(message_context.reply_commit(Default::default(), None));

        // Reply twice in one message is forbidden.
        assert_err!(
            message_context.reply_commit(Default::default(), None),
            Error::DuplicateReply,
        );
    }

    // Set of constants for clarity of a part of the test
    const INCOMING_MESSAGE_ID: u64 = 3;
    const INCOMING_MESSAGE_SOURCE: u64 = 4;

    #[test]
    /// Test that covers full api of `MessageContext`
    fn message_context_api() {
        // Creating an incoming message around which the runner builds the `MessageContext`
        let incoming_message = IncomingMessage::new(
            MessageId::from(INCOMING_MESSAGE_ID),
            ProgramId::from(INCOMING_MESSAGE_SOURCE),
            vec![1, 2].try_into().unwrap(),
            0,
            0,
            None,
        );

        let incoming_dispatch = IncomingDispatch::new(DispatchKind::Handle, incoming_message, None);

        // Creating a message context
        let mut context = MessageContext::new(
            incoming_dispatch,
            Default::default(),
            ContextSettings::new(0, 0, 0, 0, 0, 1024),
        );

        // Checking that the initial parameters of the context match the passed constants
        assert_eq!(context.current().id(), MessageId::from(INCOMING_MESSAGE_ID));
        assert!(context.store.reply.is_none());
        assert!(context.outcome.reply.is_none());

        // Creating a reply packet
        let reply_packet = ReplyPacket::new(vec![0, 0].try_into().unwrap(), 0);

        // Checking that we are able to initialize reply
        assert_ok!(context.reply_push(&[1, 2, 3]));

        // Setting reply message and making sure the operation was successful
        assert_ok!(context.reply_commit(reply_packet.clone(), None));

        // Checking that the `ReplyMessage` matches the passed one
        assert_eq!(
            context
                .outcome
                .reply
                .as_ref()
                .unwrap()
                .0
                .payload_bytes()
                .to_vec(),
            vec![1, 2, 3, 0, 0],
        );

        // Checking that repeated call `reply_push(...)` returns error and does not do anything
        assert_err!(context.reply_push(&[1]), Error::LateAccess);
        assert_eq!(
            context
                .outcome
                .reply
                .as_ref()
                .unwrap()
                .0
                .payload_bytes()
                .to_vec(),
            vec![1, 2, 3, 0, 0],
        );

        // Checking that repeated call `reply_commit(...)` returns error and does not
        assert_err!(
            context.reply_commit(reply_packet, None),
            Error::DuplicateReply
        );

        // Checking that at this point vector of outgoing messages is empty
        assert!(context.outcome.handle.is_empty());

        // Creating an expected handle for a future initialized message
        let expected_handle = 0;

        // Initializing message and compare its handle with expected one
        assert_eq!(
            context.send_init().expect("Error initializing new message"),
            expected_handle
        );

        // And checking that it is not formed
        assert!(context
            .store
            .outgoing
            .get(&expected_handle)
            .expect("This key should be")
            .is_some());

        // Checking that we are able to push payload for the
        // message that we have not committed yet
        assert_ok!(context.send_push(expected_handle, &[5, 7]));
        assert_ok!(context.send_push(expected_handle, &[9]));

        // Creating an outgoing packet to commit sending by parts
        let commit_packet = HandlePacket::default();

        // Checking if commit is successful
        assert_ok!(context.send_commit(expected_handle, commit_packet, 0, None));

        // Checking that we are **NOT** able to push payload for the message or
        // commit it if we already committed it or directly pushed before
        assert_err!(
            context.send_push(expected_handle, &[5, 7]),
            Error::LateAccess,
        );
        assert_err!(
            context.send_commit(expected_handle, HandlePacket::default(), 0, None),
            Error::LateAccess,
        );

        // Creating a handle to push and do commit non-existent message
        let expected_handle = 15;

        // Checking that we also get an error when trying
        // to commit or send a non-existent message
        assert_err!(context.send_push(expected_handle, &[0]), Error::OutOfBounds);
        assert_err!(
            context.send_commit(expected_handle, HandlePacket::default(), 0, None),
            Error::OutOfBounds,
        );

        // Creating a handle to init and do not commit later
        // to show that the message will not be sent
        let expected_handle = 1;

        assert_eq!(
            context.send_init().expect("Error initializing new message"),
            expected_handle
        );
        assert_ok!(context.send_push(expected_handle, &[2, 2]));

        // Checking that reply message not lost and matches our initial
        assert!(context.outcome.reply.is_some());
        assert_eq!(
            context.outcome.reply.as_ref().unwrap().0.payload_bytes(),
            vec![1, 2, 3, 0, 0]
        );

        // Checking that on drain we get only messages that were fully formed (directly sent or committed)
        let (expected_result, _) = context.drain();
        assert_eq!(expected_result.handle.len(), 1);
        assert_eq!(expected_result.handle[0].0.payload_bytes(), vec![5, 7, 9]);
    }

    #[test]
    fn duplicate_waking() {
        let incoming_message = IncomingMessage::new(
            MessageId::from(INCOMING_MESSAGE_ID),
            ProgramId::from(INCOMING_MESSAGE_SOURCE),
            vec![1, 2].try_into().unwrap(),
            0,
            0,
            None,
        );

        let incoming_dispatch = IncomingDispatch::new(DispatchKind::Handle, incoming_message, None);

        let mut context = MessageContext::new(
            incoming_dispatch,
            Default::default(),
            ContextSettings::new(0, 0, 0, 0, 0, 1024),
        );

        context.wake(MessageId::default(), 10).unwrap();

        assert_eq!(
            context.wake(MessageId::default(), 1),
            Err(Error::DuplicateWaking)
        );
    }

    #[test]
    fn duplicate_reply_deposit() {
        let incoming_message = IncomingMessage::new(
            MessageId::from(INCOMING_MESSAGE_ID),
            ProgramId::from(INCOMING_MESSAGE_SOURCE),
            vec![1, 2].try_into().unwrap(),
            0,
            0,
            None,
        );

        let incoming_dispatch = IncomingDispatch::new(DispatchKind::Handle, incoming_message, None);

        let mut message_context = MessageContext::new(
            incoming_dispatch,
            Default::default(),
            ContextSettings::new(0, 0, 0, 0, 0, 1024),
        );

        let handle = message_context.send_init().expect("unreachable");
        message_context
            .send_push(handle, b"payload")
            .expect("unreachable");
        let message_id = message_context
            .send_commit(handle, HandlePacket::default(), 0, None)
            .expect("unreachable");

        assert!(message_context.reply_deposit(message_id, 1234).is_ok());
        assert_err!(
            message_context.reply_deposit(message_id, 1234),
            MessageError::DuplicateReplyDeposit
        );
    }

    #[test]
    fn inexistent_reply_deposit() {
        let incoming_message = IncomingMessage::new(
            MessageId::from(INCOMING_MESSAGE_ID),
            ProgramId::from(INCOMING_MESSAGE_SOURCE),
            vec![1, 2].try_into().unwrap(),
            0,
            0,
            None,
        );

        let incoming_dispatch = IncomingDispatch::new(DispatchKind::Handle, incoming_message, None);

        let mut message_context = MessageContext::new(
            incoming_dispatch,
            Default::default(),
            ContextSettings::new(0, 0, 0, 0, 0, 1024),
        );

        let message_id = message_context
            .reply_commit(ReplyPacket::default(), None)
            .expect("unreachable");

        assert_err!(
            message_context.reply_deposit(message_id, 1234),
            MessageError::IncorrectMessageForReplyDeposit
        );
        assert_err!(
            message_context.reply_deposit(Default::default(), 1234),
            MessageError::IncorrectMessageForReplyDeposit
        );
    }
}