gear-backend-common 0.3.2

Common library for gear-core-backend
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
// This file is part of Gear.

// Copyright (C) 2023 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/>.

//! Syscall implementations generic over wasmi and sandbox backends.

use crate::{
    memory::{MemoryAccessError, WasmMemoryRead},
    runtime::{RunFallibleError, Runtime},
    syscall_trace, ActorTerminationReason, BackendAllocSyscallError, BackendExternalities,
    BackendSyscallError, MessageWaitedType, TrapExplanation, UndefinedTerminationReason,
    UnrecoverableExecutionError, UnrecoverableMemoryError, PTR_SPECIAL,
};
use alloc::string::{String, ToString};
use blake2_rfc::blake2b::blake2b;
use core::marker::PhantomData;
use gear_backend_codegen::host;
use gear_core::{
    buffer::{RuntimeBuffer, RuntimeBufferSizeError},
    costs::RuntimeCosts,
    env::{DropPayloadLockBound, Externalities},
    gas::CounterType,
    message::{HandlePacket, InitPacket, Payload, PayloadSizeError, ReplyPacket},
    pages::{PageNumber, PageU32Size, WasmPage},
};
use gear_core_errors::{MessageError, ReplyCode, SignalCode};
use gsys::{
    BlockNumberWithHash, ErrorBytes, ErrorWithBlockNumberAndValue, ErrorWithGas, ErrorWithHandle,
    ErrorWithHash, ErrorWithReplyCode, ErrorWithSignalCode, ErrorWithTwoHashes, Hash,
    HashWithValue, TwoHashesWithValue,
};

pub struct FuncsHandler<Ext: Externalities + 'static, Runtime> {
    _phantom: PhantomData<(Ext, Runtime)>,
}

impl<Ext, R> FuncsHandler<Ext, R>
where
    Ext: BackendExternalities + 'static,
    Ext::UnrecoverableError: BackendSyscallError,
    RunFallibleError: From<Ext::FallibleError>,
    Ext::AllocError: BackendAllocSyscallError<ExtError = Ext::UnrecoverableError>,
    R: Runtime<Ext>,
{
    /// !!! Usage warning: make sure to do it before any other read/write,
    /// because it may contain registered read.
    fn register_and_read_value(ctx: &mut R, value_ptr: u32) -> Result<u128, MemoryAccessError> {
        if value_ptr != PTR_SPECIAL {
            let read_value = ctx.register_read_decoded(value_ptr);
            return ctx.read_decoded(read_value);
        }

        Ok(0)
    }

    fn read_message_payload(
        ctx: &mut R,
        read_payload: WasmMemoryRead,
    ) -> Result<Payload, RunFallibleError> {
        ctx.read(read_payload)?
            .try_into()
            .map_err(|PayloadSizeError| MessageError::MaxMessageSizeExceed.into())
            .map_err(RunFallibleError::FallibleExt)
    }

    // TODO #3037
    #[allow(clippy::too_many_arguments)]
    #[host(fallible, wgas, cost = RuntimeCosts::Send(len))]
    pub fn send(
        ctx: &mut R,
        gas: u64,
        pid_value_ptr: u32,
        payload_ptr: u32,
        len: u32,
        delay: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_hash_val = ctx.register_read_as(pid_value_ptr);
        let read_payload = ctx.register_read(payload_ptr, len);
        let HashWithValue {
            hash: destination,
            value,
        } = ctx.read_as(read_hash_val)?;
        let payload = Self::read_message_payload(ctx, read_payload)?;

        ctx.ext_mut()
            .send(HandlePacket::new(destination.into(), payload, value), delay)
            .map_err(Into::into)
    }

    #[host(fallible, wgas, cost = RuntimeCosts::SendCommit)]
    pub fn send_commit(
        ctx: &mut R,
        gas: u64,
        handle: u32,
        pid_value_ptr: u32,
        delay: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_pid_value = ctx.register_read_as(pid_value_ptr);
        let HashWithValue {
            hash: destination,
            value,
        } = ctx.read_as(read_pid_value)?;

        ctx.ext_mut()
            .send_commit(
                handle,
                HandlePacket::new(destination.into(), Default::default(), value),
                delay,
            )
            .map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::SendInit, err = ErrorWithHandle)]
    pub fn send_init(ctx: &mut R, gas: u64) -> Result<(u64, ()), R::Error> {
        ctx.ext_mut().send_init().map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::SendPush(len), err = ErrorBytes)]
    pub fn send_push(
        ctx: &mut R,
        gas: u64,
        handle: u32,
        payload_ptr: u32,
        len: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_payload = ctx.register_read(payload_ptr, len);
        let payload = ctx.read(read_payload)?;

        ctx.ext_mut()
            .send_push(handle, &payload)
            .map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::ReservationSend(len))]
    pub fn reservation_send(
        ctx: &mut R,
        gas: u64,
        rid_pid_value_ptr: u32,
        payload_ptr: u32,
        len: u32,
        delay: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_rid_pid_value = ctx.register_read_as(rid_pid_value_ptr);
        let read_payload = ctx.register_read(payload_ptr, len);
        let TwoHashesWithValue {
            hash1: reservation_id,
            hash2: destination,
            value,
        } = ctx.read_as(read_rid_pid_value)?;
        let payload = Self::read_message_payload(ctx, read_payload)?;

        ctx.ext_mut()
            .reservation_send(
                reservation_id.into(),
                HandlePacket::new(destination.into(), payload, value),
                delay,
            )
            .map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::ReservationSendCommit)]
    pub fn reservation_send_commit(
        ctx: &mut R,
        gas: u64,
        handle: u32,
        rid_pid_value_ptr: u32,
        delay: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_rid_pid_value = ctx.register_read_as(rid_pid_value_ptr);
        let TwoHashesWithValue {
            hash1: reservation_id,
            hash2: destination,
            value,
        } = ctx.read_as(read_rid_pid_value)?;

        ctx.ext_mut()
            .reservation_send_commit(
                reservation_id.into(),
                handle,
                HandlePacket::new(destination.into(), Default::default(), value),
                delay,
            )
            .map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::Read, err = ErrorBytes)]
    pub fn read(
        ctx: &mut R,
        gas: u64,
        at: u32,
        len: u32,
        buffer_ptr: u32,
    ) -> Result<(u64, ()), R::Error> {
        let payload_lock = ctx.ext_mut().lock_payload(at, len)?;
        payload_lock
            .drop_with::<MemoryAccessError, _>(|payload_access| {
                let write_buffer = ctx.register_write(buffer_ptr, len);
                let write_res = ctx.write(write_buffer, payload_access.as_slice());
                let unlock_bound = ctx.ext_mut().unlock_payload(payload_access.into_lock());

                DropPayloadLockBound::from((unlock_bound, write_res))
            })
            .into_inner()
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::Size)]
    pub fn size(ctx: &mut R, gas: u64, size_ptr: u32) -> Result<(u64, ()), R::Error> {
        let size = ctx.ext_mut().size()? as u32;

        let write_size = ctx.register_write_as(size_ptr);
        ctx.write_as(write_size, size.to_le_bytes())
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::Exit)]
    pub fn exit(ctx: &mut R, gas: u64, inheritor_id_ptr: u32) -> Result<(u64, ()), R::Error> {
        let read_inheritor_id = ctx.register_read_decoded(inheritor_id_ptr);
        let inheritor_id = ctx.read_decoded(read_inheritor_id)?;
        Err(ActorTerminationReason::Exit(inheritor_id).into())
    }

    #[host(fallible, cost = RuntimeCosts::ReplyCode, err = ErrorWithReplyCode)]
    pub fn reply_code(ctx: &mut R, gas: u64) -> Result<(u64, ()), R::Error> {
        ctx.ext_mut()
            .reply_code()
            .map(ReplyCode::to_bytes)
            .map_err(Into::into)
    }

    // TODO: write proper benchmark #2825
    #[host(fallible, cost = RuntimeCosts::ReplyCode, err = ErrorWithSignalCode)]
    pub fn signal_code(ctx: &mut R, gas: u64) -> Result<(u64, ()), R::Error> {
        ctx.ext_mut()
            .signal_code()
            .map(SignalCode::to_u32)
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::Alloc(pages))]
    pub fn alloc(ctx: &mut R, gas: u64, pages: u32) -> Result<(u64, u32), R::Error> {
        let res = ctx.alloc(pages);
        let res = ctx.process_alloc_func_result(res)?;

        let page = match res {
            Ok(page) => {
                log::trace!("Alloc {pages:?} pages at {page:?}");
                page.raw()
            }
            Err(err) => {
                log::trace!("Alloc failed: {err}");
                u32::MAX
            }
        };
        Ok(page)
    }

    #[host(cost = RuntimeCosts::Free)]
    pub fn free(ctx: &mut R, gas: u64, page_no: u32) -> Result<(u64, i32), R::Error> {
        let page = WasmPage::new(page_no).map_err(|_| {
            UndefinedTerminationReason::Actor(ActorTerminationReason::Trap(
                TrapExplanation::Unknown,
            ))
        })?;

        let res = ctx.ext_mut().free(page);
        let res = ctx.process_alloc_func_result(res)?;

        match &res {
            Ok(()) => {
                log::trace!("Free {page:?}");
            }
            Err(err) => {
                log::trace!("Free failed: {err}");
            }
        };

        Ok(res.is_err() as i32)
    }

    #[host(cost = RuntimeCosts::BlockHeight)]
    pub fn block_height(ctx: &mut R, gas: u64, height_ptr: u32) -> Result<(u64, ()), R::Error> {
        let height = ctx.ext_mut().block_height()?;

        let write_height = ctx.register_write_as(height_ptr);
        ctx.write_as(write_height, height.to_le_bytes())
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::BlockTimestamp)]
    pub fn block_timestamp(
        ctx: &mut R,
        gas: u64,
        timestamp_ptr: u32,
    ) -> Result<(u64, ()), R::Error> {
        let timestamp = ctx.ext_mut().block_timestamp()?;

        let write_timestamp = ctx.register_write_as(timestamp_ptr);
        ctx.write_as(write_timestamp, timestamp.to_le_bytes())
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::Random)]
    pub fn random(
        ctx: &mut R,
        gas: u64,
        subject_ptr: u32,
        bn_random_ptr: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_subject = ctx.register_read_decoded(subject_ptr);
        let write_bn_random = ctx.register_write_as(bn_random_ptr);

        let raw_subject: Hash = ctx.read_decoded(read_subject)?;

        let (random, bn) = ctx.ext_mut().random()?;
        let subject = [&raw_subject, random].concat();

        let mut hash = [0; 32];
        hash.copy_from_slice(blake2b(32, &[], &subject).as_bytes());

        ctx.write_as(write_bn_random, BlockNumberWithHash { bn, hash })
            .map_err(Into::into)
    }

    #[host(fallible, wgas, cost = RuntimeCosts::Reply(len))]
    pub fn reply(
        ctx: &mut R,
        gas: u64,
        payload_ptr: u32,
        len: u32,
        value_ptr: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_payload = ctx.register_read(payload_ptr, len);
        let value = Self::register_and_read_value(ctx, value_ptr)?;
        let payload = Self::read_message_payload(ctx, read_payload)?;

        ctx.ext_mut()
            .reply(ReplyPacket::new(payload, value))
            .map_err(Into::into)
    }

    #[host(fallible, wgas, cost = RuntimeCosts::ReplyCommit)]
    pub fn reply_commit(ctx: &mut R, gas: u64, value_ptr: u32) -> Result<(u64, ()), R::Error> {
        let value = Self::register_and_read_value(ctx, value_ptr)?;

        ctx.ext_mut()
            .reply_commit(ReplyPacket::new(Default::default(), value))
            .map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::ReservationReply(len))]
    pub fn reservation_reply(
        ctx: &mut R,
        gas: u64,
        rid_value_ptr: u32,
        payload_ptr: u32,
        len: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_rid_value = ctx.register_read_as(rid_value_ptr);
        let read_payload = ctx.register_read(payload_ptr, len);
        let HashWithValue {
            hash: reservation_id,
            value,
        } = ctx.read_as(read_rid_value)?;
        let payload = Self::read_message_payload(ctx, read_payload)?;

        ctx.ext_mut()
            .reservation_reply(reservation_id.into(), ReplyPacket::new(payload, value))
            .map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::ReservationReplyCommit)]
    pub fn reservation_reply_commit(
        ctx: &mut R,
        gas: u64,
        rid_value_ptr: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_rid_value = ctx.register_read_as(rid_value_ptr);
        let HashWithValue {
            hash: reservation_id,
            value,
        } = ctx.read_as(read_rid_value)?;

        ctx.ext_mut()
            .reservation_reply_commit(
                reservation_id.into(),
                ReplyPacket::new(Default::default(), value),
            )
            .map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::ReplyTo)]
    pub fn reply_to(ctx: &mut R, gas: u64) -> Result<(u64, ()), R::Error> {
        ctx.ext_mut().reply_to().map_err(Into::into)
    }

    // TODO: write proper benchmark #2825
    #[host(fallible, cost = RuntimeCosts::SignalFrom)]
    pub fn signal_from(ctx: &mut R, gas: u64) -> Result<(u64, ()), R::Error> {
        ctx.ext_mut().signal_from().map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::ReplyPush(len), err = ErrorBytes)]
    pub fn reply_push(
        ctx: &mut R,
        gas: u64,
        payload_ptr: u32,
        len: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_payload = ctx.register_read(payload_ptr, len);
        let payload = ctx.read(read_payload)?;

        ctx.ext_mut().reply_push(&payload).map_err(Into::into)
    }

    #[host(fallible, wgas, cost = RuntimeCosts::ReplyInput)]
    pub fn reply_input(
        ctx: &mut R,
        gas: u64,
        offset: u32,
        len: u32,
        value_ptr: u32,
    ) -> Result<(u64, ()), R::Error> {
        // Charge for `len` is inside `reply_push_input`
        let value = Self::register_and_read_value(ctx, value_ptr)?;

        let mut f = || {
            ctx.ext_mut().reply_push_input(offset, len)?;
            ctx.ext_mut()
                .reply_commit(ReplyPacket::new(Default::default(), value))
        };

        f().map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::ReplyPushInput, err = ErrorBytes)]
    pub fn reply_push_input(
        ctx: &mut R,
        gas: u64,
        offset: u32,
        len: u32,
    ) -> Result<(u64, ()), R::Error> {
        ctx.ext_mut()
            .reply_push_input(offset, len)
            .map_err(Into::into)
    }

    #[allow(clippy::too_many_arguments)]
    #[host(fallible, wgas, cost = RuntimeCosts::SendInput)]
    pub fn send_input(
        ctx: &mut R,
        gas: u64,
        pid_value_ptr: u32,
        offset: u32,
        len: u32,
        delay: u32,
    ) -> Result<(u64, ()), R::Error> {
        // Charge for `len` inside `send_push_input`
        let read_pid_value = ctx.register_read_as(pid_value_ptr);
        let HashWithValue {
            hash: destination,
            value,
        } = ctx.read_as(read_pid_value)?;

        let mut f = || {
            let handle = ctx.ext_mut().send_init()?;
            ctx.ext_mut().send_push_input(handle, offset, len)?;
            ctx.ext_mut().send_commit(
                handle,
                HandlePacket::new(destination.into(), Default::default(), value),
                delay,
            )
        };

        f().map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::SendPushInput, err = ErrorBytes)]
    pub fn send_push_input(
        ctx: &mut R,
        gas: u64,
        handle: u32,
        offset: u32,
        len: u32,
    ) -> Result<(u64, ()), R::Error> {
        ctx.ext_mut()
            .send_push_input(handle, offset, len)
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::Debug(data_len))]
    pub fn debug(
        ctx: &mut R,
        gas: u64,
        data_ptr: u32,
        data_len: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_data = ctx.register_read(data_ptr, data_len);
        let data: RuntimeBuffer = ctx
            .read(read_data)?
            .try_into()
            .map_err(|RuntimeBufferSizeError| {
                UnrecoverableMemoryError::RuntimeAllocOutOfBounds.into()
            })
            .map_err(TrapExplanation::UnrecoverableExt)?;

        let s = String::from_utf8(data.into_vec())
            .map_err(|_err| UnrecoverableExecutionError::InvalidDebugString.into())
            .map_err(TrapExplanation::UnrecoverableExt)?;
        ctx.ext_mut().debug(&s)?;

        Ok(())
    }

    #[host(cost = RuntimeCosts::Null)]
    pub fn panic(
        ctx: &mut R,
        gas: u64,
        data_ptr: u32,
        data_len: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_data = ctx.register_read(data_ptr, data_len);
        let data = ctx.read(read_data).unwrap_or_default();

        let s = String::from_utf8_lossy(&data).to_string();

        Err(ActorTerminationReason::Trap(TrapExplanation::Panic(s.into())).into())
    }

    #[host(cost = RuntimeCosts::Null)]
    pub fn oom_panic(ctx: &mut R, gas: u64) -> Result<(u64, ()), R::Error> {
        Err(ActorTerminationReason::Trap(TrapExplanation::ProgramAllocOutOfBounds).into())
    }

    #[host(fallible, cost = RuntimeCosts::ReserveGas)]
    pub fn reserve_gas(
        ctx: &mut R,
        gas: u64,
        gas_value: u64,
        duration: u32,
    ) -> Result<(u64, ()), R::Error> {
        ctx.ext_mut()
            .reserve_gas(gas_value, duration)
            .map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::ReplyDeposit, err = ErrorBytes)]
    pub fn reply_deposit(
        ctx: &mut R,
        gas: u64,
        message_id_ptr: u32,
        gas_value: u64,
    ) -> Result<(u64, ()), R::Error> {
        let read_message_id = ctx.register_read_decoded(message_id_ptr);
        let message_id = ctx.read_decoded(read_message_id)?;

        ctx.ext_mut()
            .reply_deposit(message_id, gas_value)
            .map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::UnreserveGas, err = ErrorWithGas)]
    pub fn unreserve_gas(
        ctx: &mut R,
        gas: u64,
        reservation_id_ptr: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_reservation_id = ctx.register_read_decoded(reservation_id_ptr);
        let reservation_id = ctx.read_decoded(read_reservation_id)?;

        ctx.ext_mut()
            .unreserve_gas(reservation_id)
            .map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::SystemReserveGas, err = ErrorBytes)]
    pub fn system_reserve_gas(
        ctx: &mut R,
        gas: u64,
        gas_value: u64,
    ) -> Result<(u64, ()), R::Error> {
        ctx.ext_mut()
            .system_reserve_gas(gas_value)
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::GasAvailable)]
    pub fn gas_available(ctx: &mut R, gas: u64, gas_ptr: u32) -> Result<(u64, ()), R::Error> {
        let gas_available = ctx.ext_mut().gas_available()?;

        let write_gas = ctx.register_write_as(gas_ptr);
        ctx.write_as(write_gas, gas_available.to_le_bytes())
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::MsgId)]
    pub fn message_id(ctx: &mut R, gas: u64, message_id_ptr: u32) -> Result<(u64, ()), R::Error> {
        let message_id = ctx.ext_mut().message_id()?;

        let write_message_id = ctx.register_write_as(message_id_ptr);
        ctx.write_as(write_message_id, message_id.into_bytes())
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::ProgramId)]
    pub fn program_id(ctx: &mut R, gas: u64, program_id_ptr: u32) -> Result<(u64, ()), R::Error> {
        let program_id = ctx.ext_mut().program_id()?;

        let write_program_id = ctx.register_write_as(program_id_ptr);
        ctx.write_as(write_program_id, program_id.into_bytes())
            .map_err(Into::into)
    }

    #[host(fallible, cost = RuntimeCosts::PayProgramRent, err = ErrorWithBlockNumberAndValue)]
    pub fn pay_program_rent(
        ctx: &mut R,
        gas: u64,
        rent_pid_ptr: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_rent_pid = ctx.register_read_as(rent_pid_ptr);

        let HashWithValue {
            hash: program_id,
            value: rent,
        } = ctx.read_as(read_rent_pid)?;

        ctx.ext_mut()
            .pay_program_rent(program_id.into(), rent)
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::Source)]
    pub fn source(ctx: &mut R, gas: u64, source_ptr: u32) -> Result<(u64, ()), R::Error> {
        let source = ctx.ext_mut().source()?;

        let write_source = ctx.register_write_as(source_ptr);
        ctx.write_as(write_source, source.into_bytes())
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::Value)]
    pub fn value(ctx: &mut R, gas: u64, value_ptr: u32) -> Result<(u64, ()), R::Error> {
        let value = ctx.ext_mut().value()?;

        let write_value = ctx.register_write_as(value_ptr);
        ctx.write_as(write_value, value.to_le_bytes())
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::ValueAvailable)]
    pub fn value_available(ctx: &mut R, gas: u64, value_ptr: u32) -> Result<(u64, ()), R::Error> {
        let value_available = ctx.ext_mut().value_available()?;

        let write_value = ctx.register_write_as(value_ptr);
        ctx.write_as(write_value, value_available.to_le_bytes())
            .map_err(Into::into)
    }

    #[host(cost = RuntimeCosts::Leave)]
    pub fn leave(ctx: &mut R, gas: u64) -> Result<(u64, ()), R::Error> {
        Err(ActorTerminationReason::Leave.into())
    }

    #[host(cost = RuntimeCosts::Wait)]
    pub fn wait(ctx: &mut R, gas: u64) -> Result<(u64, ()), R::Error> {
        ctx.ext_mut().wait()?;
        Err(ActorTerminationReason::Wait(None, MessageWaitedType::Wait).into())
    }

    #[host(cost = RuntimeCosts::WaitFor)]
    pub fn wait_for(ctx: &mut R, gas: u64, duration: u32) -> Result<(u64, ()), R::Error> {
        ctx.ext_mut().wait_for(duration)?;
        Err(ActorTerminationReason::Wait(Some(duration), MessageWaitedType::WaitFor).into())
    }

    #[host(cost = RuntimeCosts::WaitUpTo)]
    pub fn wait_up_to(ctx: &mut R, gas: u64, duration: u32) -> Result<(u64, ()), R::Error> {
        let waited_type = if ctx.ext_mut().wait_up_to(duration)? {
            MessageWaitedType::WaitUpToFull
        } else {
            MessageWaitedType::WaitUpTo
        };
        Err(ActorTerminationReason::Wait(Some(duration), waited_type).into())
    }

    #[host(fallible, cost = RuntimeCosts::Wake, err = ErrorBytes)]
    pub fn wake(
        ctx: &mut R,
        gas: u64,
        message_id_ptr: u32,
        delay: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_message_id = ctx.register_read_decoded(message_id_ptr);
        let message_id = ctx.read_decoded(read_message_id)?;

        ctx.ext_mut().wake(message_id, delay).map_err(Into::into)
    }

    #[allow(clippy::too_many_arguments)]
    #[host(fallible, wgas, cost = RuntimeCosts::CreateProgram(payload_len, salt_len), err = ErrorWithTwoHashes)]
    pub fn create_program(
        ctx: &mut R,
        gas: u64,
        cid_value_ptr: u32,
        salt_ptr: u32,
        salt_len: u32,
        payload_ptr: u32,
        payload_len: u32,
        delay: u32,
    ) -> Result<(u64, ()), R::Error> {
        let read_cid_value = ctx.register_read_as(cid_value_ptr);
        let read_salt = ctx.register_read(salt_ptr, salt_len);
        let read_payload = ctx.register_read(payload_ptr, payload_len);
        let HashWithValue {
            hash: code_id,
            value,
        } = ctx.read_as(read_cid_value)?;
        let salt = Self::read_message_payload(ctx, read_salt)?;
        let payload = Self::read_message_payload(ctx, read_payload)?;

        ctx.ext_mut()
            .create_program(InitPacket::new(code_id.into(), salt, payload, value), delay)
            .map_err(Into::into)
    }

    pub fn forbidden(ctx: &mut R, gas: u64) -> Result<(u64, ()), R::Error> {
        syscall_trace!("forbidden");

        ctx.run_any(gas, RuntimeCosts::Null, |_| {
            Err(ActorTerminationReason::Trap(TrapExplanation::ForbiddenFunction).into())
        })
    }

    pub fn out_of_gas(ctx: &mut R, _gas: u64) -> Result<(u64, ()), R::Error> {
        syscall_trace!("out_of_gas");

        let ext = ctx.ext_mut();
        let current_counter = ext.current_counter_type();
        log::trace!(target: "syscalls", "[out_of_gas] Current counter in global represents {current_counter:?}");

        if current_counter == CounterType::GasAllowance {
            // We manually decrease it to 0 because global won't be affected
            // since it didn't pass comparison to argument of `gas_charge()`
            ext.decrease_current_counter_to(0);
        }

        let termination_reason: ActorTerminationReason = current_counter.into();

        ctx.set_termination_reason(termination_reason.into());
        Err(R::unreachable_error())
    }
}