Skip to main content

ab_executor_native/
lib.rs

1#![feature(const_convert, const_trait_impl, slice_ptr_get)]
2
3mod context;
4
5use crate::context::{MethodDetails, NativeExecutorContext};
6use ab_aligned_buffer::SharedAlignedBuffer;
7use ab_contracts_common::env::{Env, EnvState, MethodContext};
8use ab_contracts_common::metadata::decode::{MetadataDecoder, MetadataDecodingError, MetadataItem};
9use ab_contracts_common::method::MethodFingerprint;
10use ab_contracts_common::{
11    Contract, ContractError, ContractTrait, ContractTraitDefinition, MAX_CODE_SIZE,
12    NativeExecutorContactMethod,
13};
14use ab_contracts_standards::fungible::Fungible;
15use ab_contracts_standards::tx_handler::TxHandlerExt;
16use ab_core_primitives::address::Address;
17use ab_core_primitives::balance::Balance;
18use ab_core_primitives::shard::ShardIndex;
19use ab_core_primitives::transaction::{Transaction, TransactionHeader, TransactionSlot};
20use ab_executor_slots::{Slot, SlotKey, Slots};
21use ab_io_type::variable_bytes::VariableBytes;
22use ab_io_type::variable_elements::VariableElements;
23use ab_system_contract_address_allocator::{AddressAllocator, AddressAllocatorExt};
24use ab_system_contract_block::{Block, BlockExt};
25use ab_system_contract_code::{Code, CodeExt};
26use ab_system_contract_native_token::{NativeToken, NativeTokenExt};
27use ab_system_contract_simple_wallet_base::SimpleWalletBase;
28use ab_system_contract_state::State;
29use halfbrown::HashMap;
30
31/// Native executor errors
32#[derive(Debug, thiserror::Error)]
33pub enum NativeExecutorError {
34    /// Contract metadata not found
35    #[error("Contract metadata not found")]
36    ContractMetadataNotFound,
37    /// Contract metadata decoding error
38    #[error("Contract metadata decoding error: {error}")]
39    ContractMetadataDecodingError {
40        error: MetadataDecodingError<'static>,
41    },
42    /// Expected contract metadata, found trait
43    #[error("Expected contract metadata, found trait")]
44    ExpectedContractMetadataFoundTrait,
45    /// Duplicate method in contract
46    #[error("Duplicate method fingerprint {method_fingerprint} for contract code {contact_code}")]
47    DuplicateMethodInContract {
48        /// Name of the crate in which the method was duplicated
49        contact_code: &'static str,
50        /// Method fingerprint
51        method_fingerprint: &'static MethodFingerprint,
52    },
53}
54
55#[derive(Debug, Clone)]
56struct MethodsEntry {
57    contact_code: &'static str,
58    main_contract_metadata: &'static [u8],
59    native_executor_methods: &'static [NativeExecutorContactMethod],
60}
61
62/// Builder for [`NativeExecutor`]
63#[derive(Debug, Clone)]
64pub struct NativeExecutorBuilder {
65    shard_index: ShardIndex,
66    methods: Vec<MethodsEntry>,
67}
68
69impl NativeExecutorBuilder {
70    fn new(shard_index: ShardIndex) -> Self {
71        let instance = Self {
72            shard_index,
73            methods: Vec::new(),
74        };
75
76        // Start with system contracts
77        instance
78            .with_contract::<AddressAllocator>()
79            .with_contract::<Block>()
80            .with_contract::<Code>()
81            .with_contract::<NativeToken>()
82            .with_contract_trait::<NativeToken, dyn Fungible>()
83            .with_contract::<SimpleWalletBase>()
84            .with_contract::<State>()
85    }
86
87    /// Make the native execution environment aware of the contract specified in the generic
88    /// argument.
89    ///
90    /// Here `C` is the contract type:
91    /// ```ignore
92    /// # fn foo(mut builder: NativeExecutorBuilder) -> NativeExecutorBuilder {
93    ///     builder.with_contract::<Flipper>()
94    /// # }
95    /// ```
96    ///
97    /// NOTE: System contracts are already included by default.
98    #[must_use]
99    pub fn with_contract<C>(mut self) -> Self
100    where
101        C: Contract,
102    {
103        self.methods.push(MethodsEntry {
104            contact_code: C::CODE,
105            main_contract_metadata: C::MAIN_CONTRACT_METADATA,
106            native_executor_methods: C::NATIVE_EXECUTOR_METHODS,
107        });
108        self
109    }
110
111    /// Make the native execution environment aware of the trait implemented by the contract
112    /// specified in the generic argument.
113    ///
114    /// Here `C` is the contract type and `DynCT` is a trait it implements in the form of
115    /// `dyn ContractTrait`:
116    /// ```ignore
117    /// # fn foo(mut builder: NativeExecutorBuilder) -> NativeExecutorBuilder {
118    ///     builder
119    ///         .with_contract::<Token>()
120    ///         .with_contract_trait::<Token, dyn Fungible>()
121    /// # }
122    /// ```
123    #[must_use]
124    pub fn with_contract_trait<C, DynCT>(mut self) -> Self
125    where
126        C: Contract + ContractTrait<DynCT>,
127        DynCT: ContractTraitDefinition + ?Sized,
128    {
129        self.methods.push(MethodsEntry {
130            contact_code: C::CODE,
131            main_contract_metadata: C::MAIN_CONTRACT_METADATA,
132            native_executor_methods: <C as ContractTrait<DynCT>>::NATIVE_EXECUTOR_METHODS,
133        });
134        self
135    }
136
137    /// Build native execution configuration
138    pub fn build(self) -> Result<NativeExecutor, NativeExecutorError> {
139        // 10 is a decent capacity for many typical cases without reallocation
140        let mut methods_by_code = HashMap::with_capacity(10);
141        for methods_entry in self.methods {
142            let MethodsEntry {
143                contact_code,
144                main_contract_metadata,
145                native_executor_methods,
146            } = methods_entry;
147            for &native_executor_method in native_executor_methods {
148                let NativeExecutorContactMethod {
149                    method_fingerprint,
150                    method_metadata,
151                    ffi_fn,
152                } = native_executor_method;
153                #[expect(
154                    clippy::rest_pattern_accessible_field,
155                    reason = "Do not need other fields"
156                )]
157                let recommended_capacities = match MetadataDecoder::new(main_contract_metadata)
158                    .decode_next()
159                    .ok_or(NativeExecutorError::ContractMetadataNotFound)?
160                    .map_err(|error| NativeExecutorError::ContractMetadataDecodingError { error })?
161                {
162                    MetadataItem::Contract {
163                        state_type_details,
164                        slot_type_details,
165                        tmp_type_details,
166                        ..
167                    } => (
168                        state_type_details.recommended_capacity,
169                        slot_type_details.recommended_capacity,
170                        tmp_type_details.recommended_capacity,
171                    ),
172                    MetadataItem::Trait { .. } => {
173                        return Err(NativeExecutorError::ExpectedContractMetadataFoundTrait);
174                    }
175                };
176                let (
177                    recommended_state_capacity,
178                    recommended_slot_capacity,
179                    recommended_tmp_capacity,
180                ) = recommended_capacities;
181
182                if methods_by_code
183                    .insert(
184                        (contact_code.as_bytes(), method_fingerprint),
185                        MethodDetails {
186                            recommended_state_capacity,
187                            recommended_slot_capacity,
188                            recommended_tmp_capacity,
189                            method_metadata,
190                            ffi_fn,
191                        },
192                    )
193                    .is_some()
194                {
195                    return Err(NativeExecutorError::DuplicateMethodInContract {
196                        contact_code,
197                        method_fingerprint,
198                    });
199                }
200            }
201        }
202
203        Ok(NativeExecutor {
204            shard_index: self.shard_index,
205            methods_by_code,
206        })
207    }
208}
209
210#[derive(Debug)]
211pub struct NativeExecutor {
212    shard_index: ShardIndex,
213    /// Indexed by contract's code and method fingerprint
214    methods_by_code: HashMap<(&'static [u8], &'static MethodFingerprint), MethodDetails>,
215}
216
217impl NativeExecutor {
218    /// Create a new [`Slots`] instance with system contracts already deployed
219    pub fn new_storage_slots(&self) -> Result<Slots, ContractError> {
220        // Manually deploy code of system code contract
221        let slots = [Slot::ReadWrite {
222            key: SlotKey {
223                owner: Address::SYSTEM_CODE,
224                contract: Address::SYSTEM_CODE,
225            },
226            buffer: SharedAlignedBuffer::from_bytes(Code::code().get_initialized()),
227        }];
228
229        let address_allocator_address = Address::system_address_allocator(self.shard_index);
230        let mut slots = Slots::new(slots);
231
232        let system_contracts: [(Address, &VariableBytes<{ MAX_CODE_SIZE }>); _] = [
233            (Address::SYSTEM_STATE, &State::code()),
234            (address_allocator_address, &AddressAllocator::code()),
235            (Address::SYSTEM_BLOCK, &Block::code()),
236            (Address::SYSTEM_NATIVE_TOKEN, &NativeToken::code()),
237            (
238                Address::SYSTEM_SIMPLE_WALLET_BASE,
239                &SimpleWalletBase::code(),
240            ),
241        ];
242
243        {
244            let mut nested_slots = slots.new_nested_rw();
245            // Allow deployment of system contracts
246            for (address, _code) in system_contracts {
247                let result = nested_slots.add_new_contract(address);
248                debug_assert!(result);
249            }
250        }
251
252        // Deploy and initialize other system contacts
253        self.transaction_emulate(Address::NULL, &mut slots, |env| {
254            for (address, code) in system_contracts {
255                env.code_store(MethodContext::Reset, Address::SYSTEM_CODE, &address, code)?;
256            }
257
258            env.address_allocator_new(MethodContext::Reset, address_allocator_address)?;
259            env.block_genesis(MethodContext::Reset, Address::SYSTEM_BLOCK)?;
260            env.native_token_initialize(
261                MethodContext::Reset,
262                Address::SYSTEM_NATIVE_TOKEN,
263                &Address::SYSTEM_NATIVE_TOKEN,
264                // TODO: The balance should not be `max` by default, define rules and use them
265                &Balance::MAX,
266            )
267        })?;
268
269        Ok(slots)
270    }
271
272    /// Builder of native executor for specified shard index
273    #[must_use]
274    pub fn builder(shard_index: ShardIndex) -> NativeExecutorBuilder {
275        NativeExecutorBuilder::new(shard_index)
276    }
277
278    /// Verify the provided transaction.
279    ///
280    /// [`Self::transaction_execute()`] can be used for transaction execution if needed.
281    /// [`Self::transaction_verify_execute()`] can be used to verify and execute a transaction with
282    /// a single call, primarily for testing purposes.
283    pub fn transaction_verify(
284        &self,
285        transaction: Transaction<'_>,
286        slots: &Slots,
287    ) -> Result<(), ContractError> {
288        if transaction.header.version != TransactionHeader::TRANSACTION_VERSION {
289            return Err(ContractError::BadInput);
290        }
291
292        let env_state = EnvState {
293            shard_index: self.shard_index,
294            padding_0: [0; _],
295            own_address: Address::NULL,
296            context: Address::NULL,
297            caller: Address::NULL,
298        };
299
300        let read_slots_size =
301            u32::try_from(size_of_val::<[TransactionSlot]>(transaction.read_slots))
302                .map_err(|_error| ContractError::BadInput)?;
303        let read_slots = VariableElements::from_buffer(transaction.read_slots, &read_slots_size);
304
305        let write_slots_size =
306            u32::try_from(size_of_val::<[TransactionSlot]>(transaction.write_slots))
307                .map_err(|_error| ContractError::BadInput)?;
308        let write_slots = VariableElements::from_buffer(transaction.write_slots, &write_slots_size);
309
310        let payload_size = u32::try_from(size_of_val::<[u128]>(transaction.payload))
311            .map_err(|_error| ContractError::BadInput)?;
312        let payload = VariableElements::from_buffer(transaction.payload, &payload_size);
313
314        let seal_size = u32::try_from(size_of_val::<[u8]>(transaction.seal))
315            .map_err(|_error| ContractError::BadInput)?;
316        let seal = VariableBytes::from_buffer(transaction.seal, &seal_size);
317
318        let mut executor_context = NativeExecutorContext::new(
319            self.shard_index,
320            &self.methods_by_code,
321            slots.new_nested_ro(),
322            false,
323        );
324        let env = Env::with_executor_context(env_state, &mut executor_context);
325        env.tx_handler_authorize(
326            transaction.header.contract,
327            transaction.header,
328            &read_slots,
329            &write_slots,
330            &payload,
331            &seal,
332        )
333    }
334
335    /// Execute the previously verified transaction.
336    ///
337    /// [`Self::transaction_verify()`] must be used for verification.
338    /// [`Self::transaction_verify_execute()`] can be used to verify and execute a transaction with
339    /// a single call, primarily for testing purposes.
340    pub fn transaction_execute(
341        &self,
342        transaction: Transaction<'_>,
343        slots: &mut Slots,
344    ) -> Result<(), ContractError> {
345        if transaction.header.version != TransactionHeader::TRANSACTION_VERSION {
346            return Err(ContractError::BadInput);
347        }
348
349        // TODO: This is a pretty large data structure to copy around, try to make it a reference
350        let env_state = EnvState {
351            shard_index: self.shard_index,
352            padding_0: [0; _],
353            own_address: Address::NULL,
354            context: Address::NULL,
355            caller: Address::NULL,
356        };
357
358        let read_slots_size =
359            u32::try_from(size_of_val::<[TransactionSlot]>(transaction.read_slots))
360                .map_err(|_error| ContractError::BadInput)?;
361        let read_slots = VariableElements::from_buffer(transaction.read_slots, &read_slots_size);
362
363        let write_slots_size =
364            u32::try_from(size_of_val::<[TransactionSlot]>(transaction.write_slots))
365                .map_err(|_error| ContractError::BadInput)?;
366        let write_slots = VariableElements::from_buffer(transaction.write_slots, &write_slots_size);
367
368        let payload_size = u32::try_from(size_of_val::<[u128]>(transaction.payload))
369            .map_err(|_error| ContractError::BadInput)?;
370        let payload = VariableElements::from_buffer(transaction.payload, &payload_size);
371
372        let seal_size = u32::try_from(size_of_val::<[u8]>(transaction.seal))
373            .map_err(|_error| ContractError::BadInput)?;
374        let seal = VariableBytes::from_buffer(transaction.seal, &seal_size);
375
376        let mut executor_context = NativeExecutorContext::new(
377            self.shard_index,
378            &self.methods_by_code,
379            slots.new_nested_rw(),
380            true,
381        );
382
383        let mut env = Env::with_executor_context(env_state, &mut executor_context);
384        env.tx_handler_execute(
385            MethodContext::Reset,
386            transaction.header.contract,
387            transaction.header,
388            &read_slots,
389            &write_slots,
390            &payload,
391            &seal,
392        )
393    }
394
395    /// Verify and execute the provided transaction, primarily for testing purposes.
396    ///
397    /// A slightly more efficient shortcut for [`Self::transaction_verify()`] +
398    /// [`Self::transaction_execute()`] compared to calling them separately.
399    pub fn transaction_verify_execute(
400        &self,
401        transaction: Transaction<'_>,
402        slots: &mut Slots,
403    ) -> Result<(), ContractError> {
404        if transaction.header.version != TransactionHeader::TRANSACTION_VERSION {
405            return Err(ContractError::BadInput);
406        }
407
408        // TODO: This is a pretty large data structure to copy around, try to make it a reference
409        let env_state = EnvState {
410            shard_index: self.shard_index,
411            padding_0: [0; _],
412            own_address: Address::NULL,
413            context: Address::NULL,
414            caller: Address::NULL,
415        };
416
417        let read_slots_size =
418            u32::try_from(size_of_val::<[TransactionSlot]>(transaction.read_slots))
419                .map_err(|_error| ContractError::BadInput)?;
420        let read_slots = VariableElements::from_buffer(transaction.read_slots, &read_slots_size);
421
422        let write_slots_size =
423            u32::try_from(size_of_val::<[TransactionSlot]>(transaction.write_slots))
424                .map_err(|_error| ContractError::BadInput)?;
425        let write_slots = VariableElements::from_buffer(transaction.write_slots, &write_slots_size);
426
427        let payload_size = u32::try_from(size_of_val::<[u128]>(transaction.payload))
428            .map_err(|_error| ContractError::BadInput)?;
429        let payload = VariableElements::from_buffer(transaction.payload, &payload_size);
430
431        let seal_size = u32::try_from(size_of_val::<[u8]>(transaction.seal))
432            .map_err(|_error| ContractError::BadInput)?;
433        let seal = VariableBytes::from_buffer(transaction.seal, &seal_size);
434
435        // TODO: Make it more efficient by not recreating NativeExecutorContext twice here
436        {
437            let mut executor_context = NativeExecutorContext::new(
438                self.shard_index,
439                &self.methods_by_code,
440                slots.new_nested_ro(),
441                false,
442            );
443            let env = Env::with_executor_context(env_state, &mut executor_context);
444            env.tx_handler_authorize(
445                transaction.header.contract,
446                transaction.header,
447                &read_slots,
448                &write_slots,
449                &payload,
450                &seal,
451            )?;
452        }
453
454        {
455            let mut executor_context = NativeExecutorContext::new(
456                self.shard_index,
457                &self.methods_by_code,
458                slots.new_nested_rw(),
459                true,
460            );
461            let mut env = Env::with_executor_context(env_state, &mut executor_context);
462            env.tx_handler_execute(
463                MethodContext::Reset,
464                transaction.header.contract,
465                transaction.header,
466                &read_slots,
467                &write_slots,
468                &payload,
469                &seal,
470            )?;
471        }
472
473        Ok(())
474    }
475
476    /// Emulate a transaction submitted by `contract` with method calls happening inside `calls`
477    /// without going through `TxHandler`.
478    ///
479    /// NOTE: This is primarily useful for testing environment, usually changes are done in the
480    /// transaction execution using [`Self::transaction_execute()`].
481    ///
482    /// Returns `None` if the read-only [`Slots`] instance was given.
483    pub fn transaction_emulate<Calls, T>(
484        &self,
485        contract: Address,
486        slots: &mut Slots,
487        calls: Calls,
488    ) -> T
489    where
490        Calls: FnOnce(&mut Env<'_>) -> T,
491    {
492        let env_state = EnvState {
493            shard_index: self.shard_index,
494            padding_0: [0; _],
495            own_address: contract,
496            context: contract,
497            caller: Address::NULL,
498        };
499
500        let mut executor_context = NativeExecutorContext::new(
501            self.shard_index,
502            &self.methods_by_code,
503            slots.new_nested_rw(),
504            true,
505        );
506        let mut env = Env::with_executor_context(env_state, &mut executor_context);
507        calls(&mut env)
508    }
509
510    /// Get a read-only `Env` instance for calling `#[view]` methods on it directly.
511    ///
512    /// For stateful methods, execute a transaction using [`Self::transaction_execute()`] or
513    /// emulate one with [`Self::transaction_emulate()`].
514    #[must_use]
515    pub fn with_env_ro<Callback, T>(&self, slots: &Slots, callback: Callback) -> T
516    where
517        Callback: FnOnce(&Env<'_>) -> T,
518    {
519        let env_state = EnvState {
520            shard_index: self.shard_index,
521            padding_0: [0; _],
522            own_address: Address::NULL,
523            context: Address::NULL,
524            caller: Address::NULL,
525        };
526
527        let mut executor_context = NativeExecutorContext::new(
528            self.shard_index,
529            &self.methods_by_code,
530            slots.new_nested_ro(),
531            false,
532        );
533        let env = Env::with_executor_context(env_state, &mut executor_context);
534        callback(&env)
535    }
536}