ab_contracts_executor/
lib.rs

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

mod aligned_buffer;
mod slots;

use crate::aligned_buffer::{OwnedAlignedBuffer, SharedAlignedBuffer};
use crate::slots::{Slots, UsedSlots};
use ab_contracts_common::env::{Env, EnvState, ExecutorContext, MethodContext, PreparedMethod};
use ab_contracts_common::metadata::decode::{
    ArgumentKind, ArgumentMetadataItem, MetadataDecoder, MetadataDecodingError, MetadataItem,
    MethodKind, MethodMetadataDecoder, MethodMetadataItem, MethodsContainerKind,
};
use ab_contracts_common::method::MethodFingerprint;
use ab_contracts_common::{
    Address, Contract, ContractError, ContractsMethodsFnPointer, ExitCode, ShardIndex,
};
#[cfg(feature = "system-contracts")]
use ab_system_contract_address_allocator::{AddressAllocator, AddressAllocatorExt};
#[cfg(feature = "system-contracts")]
use ab_system_contract_code::Code;
#[cfg(feature = "system-contracts")]
use ab_system_contract_state::State;
use std::collections::HashMap;
use std::ffi::c_void;
use std::ptr::NonNull;
use std::slice;
use std::sync::{Arc, Weak};
use tracing::{debug, error, info_span};

/// Read a pointer of type `$ty` from `$external` and advance `$external` past it
macro_rules! read_ptr {
    ($external:ident as $ty:ty) => {{
        let ptr = NonNull::<NonNull<c_void>>::cast::<$ty>($external).read();

        $external = $external.offset(1);

        ptr
    }};
}

/// Write a `$src` pointer of type `$ty` into `$internal`, advance `$internal` past written pointer
/// and return pointer to the written location
macro_rules! write_ptr {
    ($src:expr => $internal:ident as $ty:ty) => {{
        let ptr = NonNull::<*mut c_void>::cast::<$ty>($internal);
        ptr.write($src);

        $internal = $internal.offset(1);

        ptr
    }};
}

/// Read a pointer from `$external`, write into `$internal`, advance both `$external` and
/// `$internal` by pointer size and return read pointer
macro_rules! copy_ptr {
    ($external:ident => $internal:ident as $ty:ty) => {{
        let ptr;
        {
            let src = NonNull::<NonNull<c_void>>::cast::<$ty>($external);
            let dst = NonNull::<*mut c_void>::cast::<$ty>($internal);
            ptr = src.read();
            dst.write(ptr);
        }

        $external = $external.offset(1);
        $internal = $internal.offset(1);

        ptr
    }};
}

/// Stores details about arguments that need to be processed after FFI call
enum DelayedProcessing {
    SlotReadOnly {
        size: u32,
    },
    SlotReadWrite {
        /// Pointer to `InternalArgs` where guest will store a pointer to potentially updated slot
        /// contents
        data_ptr: NonNull<*mut u8>,
        /// Pointer to slot's bytes buffer here bytes from `data_ptr` will need to be written
        /// after FFI function call
        slot_ptr: NonNull<OwnedAlignedBuffer>,
        /// Pointer to `InternalArgs` where guest will store potentially updated slot size,
        /// corresponds to `data_ptr`, filled during the second pass through the arguments
        /// (while reading `ExternalArgs`)
        size: u32,
        capacity: u32,
    },
}

#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
compile_error!("Unsupported pointer width");

#[derive(Debug, Copy, Clone)]
struct MethodDetails {
    recommended_state_capacity: u32,
    recommended_slot_capacity: u32,
    recommended_tmp_capacity: u32,
    method_metadata: &'static [u8],
    ffi_fn: unsafe extern "C" fn(NonNull<NonNull<c_void>>) -> ExitCode,
}

#[derive(Debug)]
struct NativeExecutorContext {
    shard_index: ShardIndex,
    /// Indexed by contract's code (crate name is treated as "code")
    methods_by_code: HashMap<&'static [u8], HashMap<MethodFingerprint, MethodDetails>>,
    // TODO: Think about optimizing locking
    slots: Slots,
    weak: Weak<Self>,
}

impl ExecutorContext for NativeExecutorContext {
    fn call_many(
        &self,
        previous_env_state: &EnvState,
        prepared_methods: &[PreparedMethod<'_>],
    ) -> Result<(), ContractError> {
        // TODO: Check slot misuse across recursive calls
        // TODO: Check read/write environment access permissions
        // `used_slots` must be before processing of the method because in the process of method
        // handling, some data structures will store pointers to `UsedSlot`'s internals.
        let mut used_slots = UsedSlots::new(&self.slots);

        // TODO: Parallelism
        for prepared_method in prepared_methods {
            let PreparedMethod {
                contract,
                fingerprint,
                external_args,
                method_context,
                ..
            } = prepared_method;
            // SAFETY: For native execution environment pointers correspond to the native pointers
            // and obey lifetime rules, essentially they are "trusted"
            let contract = unsafe { contract.as_ref() };
            // SAFETY: For native execution environment pointers correspond to the native pointers
            // and obey lifetime rules, essentially they are "trusted"
            let fingerprint = unsafe { fingerprint.as_ref() };
            // SAFETY: For native execution environment pointers correspond to the native pointers
            // and obey lifetime rules, essentially they are "trusted"
            let method_context = unsafe { method_context.as_ref() };
            let mut env = Env::with_executor_context(
                EnvState {
                    shard_index: self.shard_index,
                    own_address: *contract,
                    context: match method_context {
                        MethodContext::Keep => previous_env_state.context,
                        MethodContext::Reset => Address::NULL,
                        MethodContext::Replace => previous_env_state.own_address,
                    },
                    caller: previous_env_state.own_address,
                },
                self.weak
                    .upgrade()
                    .expect("Reference to itself, hence upgrade always succeeds; qed"),
            );

            let span = info_span!("NativeExecutorContext", %contract);
            let _span_guard = span.enter();

            let method_details = {
                let code = self
                    .slots
                    .get(contract, &Address::SYSTEM_CODE)
                    .ok_or_else(|| {
                        error!("Contract or its code not found");
                        ContractError::NotFound
                    })?;
                *self
                    .methods_by_code
                    .get(code.as_slice())
                    .ok_or_else(|| {
                        let code = String::from_utf8_lossy(&code);
                        error!(%code, "Contract's code not found in methods map");
                        ContractError::InvalidState
                    })?
                    .get(fingerprint)
                    .ok_or_else(|| {
                        let code = String::from_utf8_lossy(&code);
                        error!(%code, %fingerprint, "Method's fingerprint not found");
                        ContractError::InvalidState
                    })?
            };

            let MethodDetails {
                recommended_state_capacity,
                recommended_slot_capacity,
                recommended_tmp_capacity,
                mut method_metadata,
                ffi_fn,
            } = method_details;

            let method_metadata_decoder =
                MethodMetadataDecoder::new(&mut method_metadata, MethodsContainerKind::Unknown);
            let (mut arguments_metadata_decoder, method_metadata_item) =
                match method_metadata_decoder.decode_next() {
                    Ok(result) => result,
                    Err(error) => {
                        error!(%error, "Method metadata decoding error");
                        return Err(ContractError::InvalidState);
                    }
                };
            let MethodMetadataItem {
                method_kind,
                num_arguments,
                ..
            } = method_metadata_item;

            let total_arguments = usize::from(num_arguments)
                + method_kind.has_self().then_some(1).unwrap_or_default();
            // Allocate a buffer that will contain incrementally built `InternalArgs` that method
            // expects, according to its metadata.
            // `* 4` is due to slots having 2 pointers (detecting this accurately is more code,
            // so we just assume the worst case), otherwise it would be 3 pointers: data + size
            // + capacity.
            let mut internal_args = Box::<[*mut c_void]>::new_uninit_slice(total_arguments * 4);
            let internal_args = NonNull::from_mut(internal_args.as_mut()).cast::<*mut c_void>();

            // This pointer will be moving as the data structure is being constructed, while
            // `internal_args` will keep pointing to the beginning
            let mut internal_args_cursor = internal_args;
            // This pointer will be moving as the data structure is being read, while
            // `external_args` will keep pointing to the beginning
            let mut external_args_cursor = *external_args;
            // Delayed processing of sizes as capacities since knowing them requires processing all
            // arguments first
            let mut delayed_processing = Vec::with_capacity(total_arguments);

            // Handle `&self` and `&mut self`
            match method_kind {
                MethodKind::Init => {
                    // Handled after the rest of the arguments if needed
                }
                MethodKind::UpdateStateless | MethodKind::ViewStateless => {
                    // No state handling is needed
                }
                MethodKind::UpdateStatefulRo | MethodKind::ViewStatefulRo => {
                    let state_bytes = used_slots.use_ro(contract, &Address::SYSTEM_STATE)?;

                    delayed_processing.push(DelayedProcessing::SlotReadOnly {
                        size: state_bytes.len(),
                    });
                    let Some(DelayedProcessing::SlotReadOnly { size }) = delayed_processing.last()
                    else {
                        unreachable!("Just inserted `SlotReadOnly` entry; qed");
                    };

                    // SAFETY: `internal_args_cursor`'s memory is allocated with sufficient size
                    // above and aligned correctly
                    unsafe {
                        write_ptr!(state_bytes.as_ptr() => internal_args_cursor as *const u8);
                        write_ptr!(size => internal_args_cursor as *const u32);
                    }
                }
                MethodKind::UpdateStatefulRw => {
                    let state_bytes = used_slots.use_rw(
                        contract,
                        &Address::SYSTEM_STATE,
                        recommended_state_capacity,
                    )?;

                    delayed_processing.push(DelayedProcessing::SlotReadWrite {
                        // Is updated below
                        data_ptr: NonNull::dangling(),
                        slot_ptr: NonNull::from_mut(&mut *state_bytes),
                        size: state_bytes.len(),
                        capacity: state_bytes.capacity(),
                    });
                    let Some(DelayedProcessing::SlotReadWrite {
                        data_ptr,
                        size,
                        capacity,
                        ..
                    }) = delayed_processing.last_mut()
                    else {
                        unreachable!("Just inserted `SlotReadWrite` entry; qed");
                    };

                    // SAFETY: `internal_args_cursor`'s memory is allocated with sufficient size
                    // above and aligned correctly
                    unsafe {
                        *data_ptr =
                            write_ptr!(state_bytes.as_mut_ptr() => internal_args_cursor as *mut u8);
                        write_ptr!(size => internal_args_cursor as *mut u32);
                        write_ptr!(capacity => internal_args_cursor as *const u32);
                    }
                }
            }

            // Handle all other arguments one by one
            while let Some(result) = arguments_metadata_decoder.decode_next() {
                let item = match result {
                    Ok(result) => result,
                    Err(error) => {
                        error!(%error, "Argument metadata decoding error");
                        return Err(ContractError::InvalidState);
                    }
                };

                let ArgumentMetadataItem { argument_kind, .. } = item;

                match argument_kind {
                    ArgumentKind::EnvRo => {
                        // SAFETY: `internal_args_cursor`'s memory is allocated with sufficient size
                        // above and aligned correctly
                        unsafe {
                            write_ptr!(&env => internal_args_cursor as *const Env);
                        }

                        // Size for `#[env]` is implicit and doesn't need to be added to
                        // `InternalArgs`
                    }
                    ArgumentKind::EnvRw => {
                        // SAFETY: `internal_args_cursor`'s memory is allocated with sufficient size
                        // above and aligned correctly
                        unsafe {
                            write_ptr!(&mut env => internal_args_cursor as *mut Env);
                        }

                        // Size for `#[env]` is implicit and doesn't need to be added to
                        // `InternalArgs`
                    }
                    ArgumentKind::TmpRo => {
                        // Null contact is used implicitly for `#[tmp]` since it is not possible for
                        // this contract to write something there directly
                        let tmp_bytes = used_slots.use_ro(contract, &Address::NULL)?;

                        delayed_processing.push(DelayedProcessing::SlotReadOnly {
                            size: tmp_bytes.len(),
                        });
                        let Some(DelayedProcessing::SlotReadOnly { size }) =
                            delayed_processing.last()
                        else {
                            unreachable!("Just inserted `SlotReadOnly` entry; qed");
                        };

                        // SAFETY: `internal_args_cursor`'s memory is allocated with sufficient size
                        // above and aligned correctly
                        unsafe {
                            write_ptr!(tmp_bytes.as_ptr() => internal_args_cursor as *const u8);
                            write_ptr!(size => internal_args_cursor as *const u32);
                        }
                    }
                    ArgumentKind::TmpRw => {
                        // Null contact is used implicitly for `#[tmp]` since it is not possible for
                        // this contract to write something there directly
                        let tmp_bytes = used_slots.use_rw(
                            contract,
                            &Address::NULL,
                            recommended_tmp_capacity,
                        )?;

                        delayed_processing.push(DelayedProcessing::SlotReadWrite {
                            // Is updated below
                            data_ptr: NonNull::dangling(),
                            slot_ptr: NonNull::from_mut(&mut *tmp_bytes),
                            size: tmp_bytes.len(),
                            capacity: tmp_bytes.capacity(),
                        });
                        let Some(DelayedProcessing::SlotReadWrite {
                            data_ptr,
                            size,
                            capacity,
                            ..
                        }) = delayed_processing.last_mut()
                        else {
                            unreachable!("Just inserted `SlotReadWrite` entry; qed");
                        };

                        // SAFETY: `internal_args_cursor`'s memory is allocated with sufficient size
                        // above and aligned correctly
                        unsafe {
                            *data_ptr = write_ptr!(tmp_bytes.as_mut_ptr() => internal_args_cursor as *mut u8);
                            write_ptr!(size => internal_args_cursor as *mut u32);
                            write_ptr!(capacity => internal_args_cursor as *const u32);
                        }
                    }
                    ArgumentKind::SlotRo => {
                        // SAFETY: `external_args_cursor`'s must contain a valid pointer to address,
                        // moving right past that is safe
                        let address =
                            unsafe { &*read_ptr!(external_args_cursor as *const Address) };

                        let slot_bytes = used_slots.use_ro(address, contract)?;

                        delayed_processing.push(DelayedProcessing::SlotReadOnly {
                            size: slot_bytes.len(),
                        });
                        let Some(DelayedProcessing::SlotReadOnly { size }) =
                            delayed_processing.last()
                        else {
                            unreachable!("Just inserted `SlotReadOnly` entry; qed");
                        };

                        // SAFETY: `internal_args_cursor`'s memory is allocated with sufficient size
                        // above and aligned correctly
                        unsafe {
                            write_ptr!(address => internal_args_cursor as *const Address);
                            write_ptr!(slot_bytes.as_ptr() => internal_args_cursor as *const u8);
                            write_ptr!(size => internal_args_cursor as *const u32);
                        }
                    }
                    ArgumentKind::SlotRw => {
                        // SAFETY: `external_args_cursor`'s must contain a valid pointer to address,
                        // moving right past that is safe
                        let address =
                            unsafe { &*read_ptr!(external_args_cursor as *const Address) };

                        let slot_bytes =
                            used_slots.use_rw(address, contract, recommended_slot_capacity)?;

                        delayed_processing.push(DelayedProcessing::SlotReadWrite {
                            // Is updated below
                            data_ptr: NonNull::dangling(),
                            slot_ptr: NonNull::from_mut(&mut *slot_bytes),
                            size: slot_bytes.len(),
                            capacity: slot_bytes.capacity(),
                        });
                        let Some(DelayedProcessing::SlotReadWrite {
                            data_ptr,
                            size,
                            capacity,
                            ..
                        }) = delayed_processing.last_mut()
                        else {
                            unreachable!("Just inserted `SlotReadWrite` entry; qed");
                        };

                        // SAFETY: `internal_args_cursor`'s memory is allocated with sufficient size
                        // above and aligned correctly
                        unsafe {
                            write_ptr!(address => internal_args_cursor as *const Address);
                            *data_ptr = write_ptr!(slot_bytes.as_mut_ptr() => internal_args_cursor as *mut u8);
                            write_ptr!(size => internal_args_cursor as *mut u32);
                            write_ptr!(capacity => internal_args_cursor as *const u32);
                        }
                    }
                    ArgumentKind::Input => {
                        // SAFETY: `external_args_cursor`'s must contain a pointers to input + size.
                        // `internal_args_cursor`'s memory is allocated with sufficient size above
                        // and aligned correctly.
                        unsafe {
                            // Input
                            copy_ptr!(external_args_cursor => internal_args_cursor as *const u8);
                            // Size
                            copy_ptr!(external_args_cursor => internal_args_cursor as *const u32);
                        }
                    }
                    ArgumentKind::Output => {
                        // SAFETY: `external_args_cursor`'s must contain a pointers to input + size
                        // + capacity.
                        // `internal_args_cursor`'s memory is allocated with sufficient size above
                        // and aligned correctly.
                        unsafe {
                            // Output
                            copy_ptr!(external_args_cursor => internal_args_cursor as *mut u8);
                            // Size
                            let size_ptr =
                                copy_ptr!(external_args_cursor => internal_args_cursor as *mut u32);
                            if !size_ptr.is_null() {
                                // Override output size to be zero even if caller guest tried to put
                                // something there
                                size_ptr.write(0);
                            }
                            // Capacity
                            copy_ptr!(external_args_cursor => internal_args_cursor as *const u32);
                        }
                    }
                    ArgumentKind::Result => {
                        // `#[init]` method returns state of the contract and needs to be stored
                        // accordingly
                        if matches!(method_kind, MethodKind::Init) {
                            let state_bytes = used_slots.use_rw(
                                contract,
                                &Address::SYSTEM_STATE,
                                recommended_state_capacity,
                            )?;

                            if !state_bytes.is_empty() {
                                debug!("Can't initialize already initialized contract");
                                return Err(ContractError::AccessDenied);
                            }

                            delayed_processing.push(DelayedProcessing::SlotReadWrite {
                                // Is updated below
                                data_ptr: NonNull::dangling(),
                                slot_ptr: NonNull::from_mut(&mut *state_bytes),
                                size: 0,
                                capacity: state_bytes.capacity(),
                            });
                            let Some(DelayedProcessing::SlotReadWrite {
                                data_ptr,
                                size,
                                capacity,
                                ..
                            }) = delayed_processing.last_mut()
                            else {
                                unreachable!("Just inserted `SlotReadWrite` entry; qed");
                            };

                            // SAFETY: `internal_args_cursor`'s memory is allocated with sufficient
                            // size above and aligned correctly
                            unsafe {
                                *data_ptr = write_ptr!(state_bytes.as_mut_ptr() => internal_args_cursor as *mut u8);
                                write_ptr!(size => internal_args_cursor as *mut u32);
                                write_ptr!(capacity => internal_args_cursor as *const u32);
                            }
                        } else {
                            // SAFETY: `external_args_cursor`'s must contain a pointers to input
                            // + size + capacity.
                            // `internal_args_cursor`'s memory is allocated with sufficient size
                            // above and aligned correctly.
                            unsafe {
                                // Output
                                copy_ptr!(external_args_cursor => internal_args_cursor as *mut u8);
                                // Size
                                let size_ptr = copy_ptr!(external_args_cursor => internal_args_cursor as *mut u32);
                                if !size_ptr.is_null() {
                                    // Override output size to be zero even if caller guest tried to
                                    // put something there
                                    size_ptr.write(0);
                                }
                                // Capacity
                                copy_ptr!(external_args_cursor => internal_args_cursor as *const u32);
                            }
                        }
                    }
                }
            }

            // SAFETY: FFI function was generated at the same time as corresponding `Args` and must
            // match ABI of the fingerprint or else it wouldn't compile
            Result::<(), ContractError>::from(unsafe {
                ffi_fn(internal_args.cast::<NonNull<c_void>>())
            })?;

            for entry in delayed_processing {
                match entry {
                    DelayedProcessing::SlotReadOnly { .. } => {
                        // No processing is necessary
                    }
                    DelayedProcessing::SlotReadWrite {
                        data_ptr,
                        mut slot_ptr,
                        size,
                        ..
                    } => {
                        // SAFETY: Correct pointer created earlier that is not used for anything
                        // else at the moment
                        let data_ptr = unsafe { data_ptr.as_ptr().read().cast_const() };
                        // SAFETY: Correct pointer created earlier that is not used for anything
                        // else at the moment (no other contract in the stack can access the same
                        // slot exclusively at the same time, which is guaranteed by `UsedSlots`
                        // API)
                        let slot_bytes = unsafe { slot_ptr.as_mut() };

                        // Guest created a different allocation for slot, copy bytes
                        if data_ptr != slot_bytes.as_mut_ptr() {
                            if data_ptr.is_null() {
                                error!("Contract returned `null` pointer for slot data");
                                return Err(ContractError::InvalidOutput);
                            }
                            // SAFETY: For native execution guest behavior is assumed to be trusted
                            // and provide a correct pointer and size
                            let data = unsafe { slice::from_raw_parts(data_ptr, size as usize) };
                            slot_bytes.copy_from_slice(data);
                            continue;
                        }

                        if size > slot_bytes.capacity() {
                            error!(
                                %size,
                                capacity = %slot_bytes.capacity(),
                                "Contract returned invalid size for slot data in source allocation"
                            );
                            return Err(ContractError::InvalidOutput);
                        }
                        // Otherwise, set the size to what guest claims
                        //
                        // SAFETY: For native execution guest behavior is assumed to be trusted and
                        // provide a correct size
                        unsafe {
                            slot_bytes.set_len(size);
                        }
                    }
                }
            }
        }

        used_slots.persist();

        Ok(())
    }
}

/// Native executor errors
#[derive(Debug, thiserror::Error)]
pub enum NativeExecutorError {
    /// Contract metadata not found
    #[error("Contract metadata not found")]
    ContractMetadataNotFound,
    /// Contract metadata decoding error
    #[error("Contract metadata decoding error: {error}")]
    ContractMetadataDecodingError {
        error: MetadataDecodingError<'static>,
    },
    /// Expected contract metadata, found trait
    #[error("Expected contract metadata, found trait")]
    ExpectedContractMetadataFoundTrait,
    /// Duplicate method in contract
    #[error("Duplicate method in contract {crate_name}: {method_fingerprint}")]
    DuplicateMethodInContract {
        /// Name of the crate in which method was duplicated
        crate_name: &'static str,
        /// Method fingerprint
        method_fingerprint: &'static MethodFingerprint,
    },
}

pub struct NativeExecutor {
    context: Arc<NativeExecutorContext>,
}

impl NativeExecutor {
    /// Instantiate in-memory native executor.
    ///
    /// Returns error in case of method duplicates.
    pub fn in_memory(shard_index: ShardIndex) -> Result<Self, NativeExecutorError> {
        let mut methods_by_code = HashMap::<_, HashMap<_, _>>::new();
        for &contract_methods_fn_pointer in inventory::iter::<ContractsMethodsFnPointer> {
            let ContractsMethodsFnPointer {
                crate_name,
                main_contract_metadata,
                method_fingerprint,
                method_metadata,
                ffi_fn,
            } = contract_methods_fn_pointer;
            let recommended_capacities = match MetadataDecoder::new(main_contract_metadata)
                .decode_next()
                .ok_or(NativeExecutorError::ContractMetadataNotFound)?
                .map_err(|error| NativeExecutorError::ContractMetadataDecodingError { error })?
            {
                MetadataItem::Contract {
                    recommended_state_capacity,
                    recommended_slot_capacity,
                    recommended_tmp_capacity,
                    ..
                } => (
                    recommended_state_capacity,
                    recommended_slot_capacity,
                    recommended_tmp_capacity,
                ),
                MetadataItem::Trait { .. } => {
                    return Err(NativeExecutorError::ExpectedContractMetadataFoundTrait);
                }
            };
            let (recommended_state_capacity, recommended_slot_capacity, recommended_tmp_capacity) =
                recommended_capacities;

            if methods_by_code
                .entry(crate_name.as_bytes())
                .or_default()
                .insert(
                    *method_fingerprint,
                    MethodDetails {
                        recommended_state_capacity,
                        recommended_slot_capacity,
                        recommended_tmp_capacity,
                        method_metadata,
                        ffi_fn,
                    },
                )
                .is_some()
            {
                return Err(NativeExecutorError::DuplicateMethodInContract {
                    crate_name,
                    method_fingerprint,
                });
            }
        }

        let context = Arc::new_cyclic(|weak| NativeExecutorContext {
            shard_index,
            methods_by_code,
            slots: Slots::default(),
            weak: weak.clone(),
        });

        Ok(Self { context })
    }

    /// Run a function under fresh execution environment
    pub fn with_env<F, T>(
        &mut self,
        context: Address,
        caller: Address,
        mut f: F,
    ) -> Result<T, ContractError>
    where
        F: FnMut(&mut Env) -> Result<T, ContractError>,
    {
        let env_state = EnvState {
            shard_index: self.context.shard_index,
            own_address: Address::NULL,
            context,
            caller,
        };

        let mut env = Env::with_executor_context(env_state, Arc::clone(&self.context) as _);
        f(&mut env)
    }

    /// Shortcut for [`Self::with_env`] with context and caller set to [`Address::NULL`]
    #[inline]
    pub fn with_env_null<F, T>(&mut self, f: F) -> Result<T, ContractError>
    where
        F: FnMut(&mut Env) -> Result<T, ContractError>,
    {
        self.with_env(Address::NULL, Address::NULL, f)
    }

    /// Deploy typical system contracts at default addresses.
    ///
    /// It uses low-level method [`Self::deploy_system_contract_at()`].
    #[cfg(feature = "system-contracts")]
    pub fn deploy_typical_system_contracts(&mut self) -> Result<(), ContractError> {
        let address_allocator_address = Address::system_address_allocator(self.context.shard_index);
        self.deploy_system_contract_at::<AddressAllocator>(address_allocator_address);
        self.deploy_system_contract_at::<Code>(Address::SYSTEM_CODE);
        self.deploy_system_contract_at::<State>(Address::SYSTEM_STATE);

        // Initialize shard state
        self.with_env_null(|env| {
            env.address_allocator_new(&MethodContext::Keep, &address_allocator_address)
        })?;

        Ok(())
    }

    /// Deploy a system contract at a known address.
    ///
    /// It is used by convenient high-level helper method `Self::deploy_typical_system_contracts()`
    /// and often doesn't need to be called directly.
    pub fn deploy_system_contract_at<C>(&mut self, address: Address)
    where
        C: Contract,
    {
        // TODO: Replace with a call into a contract once that is implemented instead of direct
        //  manipulation of data structures
        self.context.slots.put(
            address,
            Address::SYSTEM_CODE,
            SharedAlignedBuffer::from_bytes(C::CRATE_NAME.as_bytes()),
        );
    }
}