linera_execution/
lib.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! This module manages the execution of the system application and the user applications in a
5//! Linera chain.
6
7pub mod committee;
8pub mod evm;
9mod execution;
10pub mod execution_state_actor;
11#[cfg(with_graphql)]
12mod graphql;
13mod policy;
14mod resources;
15mod runtime;
16pub mod system;
17#[cfg(with_testing)]
18pub mod test_utils;
19mod transaction_tracker;
20mod util;
21mod wasm;
22
23use std::{any::Any, collections::BTreeMap, fmt, ops::RangeInclusive, str::FromStr, sync::Arc};
24
25use allocative::Allocative;
26use async_graphql::SimpleObject;
27use async_trait::async_trait;
28use custom_debug_derive::Debug;
29use derive_more::Display;
30#[cfg(web)]
31use js_sys::wasm_bindgen::JsValue;
32use linera_base::{
33    abi::Abi,
34    crypto::{BcsHashable, CryptoHash},
35    data_types::{
36        Amount, ApplicationDescription, ApplicationPermissions, ArithmeticError, Blob, BlockHeight,
37        Bytecode, DecompressionError, Epoch, NetworkDescription, SendMessageRequest, StreamUpdate,
38        Timestamp,
39    },
40    doc_scalar, ensure, hex_debug, http,
41    identifiers::{
42        Account, AccountOwner, ApplicationId, BlobId, BlobType, ChainId, DataBlobHash, EventId,
43        GenericApplicationId, ModuleId, StreamId, StreamName,
44    },
45    ownership::ChainOwnership,
46    vm::VmRuntime,
47};
48use linera_views::{batch::Batch, ViewError};
49use serde::{Deserialize, Serialize};
50use system::AdminOperation;
51use thiserror::Error;
52pub use web_thread_pool::Pool as ThreadPool;
53use web_thread_select as web_thread;
54
55#[cfg(with_revm)]
56use crate::evm::EvmExecutionError;
57use crate::system::{EpochEventData, EPOCH_STREAM_NAME};
58#[cfg(with_testing)]
59use crate::test_utils::dummy_chain_description;
60#[cfg(all(with_testing, with_wasm_runtime))]
61pub use crate::wasm::test as wasm_test;
62#[cfg(with_wasm_runtime)]
63pub use crate::wasm::{
64    BaseRuntimeApi, ContractEntrypoints, ContractRuntimeApi, RuntimeApiData, ServiceEntrypoints,
65    ServiceRuntimeApi, WasmContractModule, WasmExecutionError, WasmServiceModule,
66};
67pub use crate::{
68    committee::Committee,
69    execution::{ExecutionStateView, ServiceRuntimeEndpoint},
70    execution_state_actor::{ExecutionRequest, ExecutionStateActor},
71    policy::ResourceControlPolicy,
72    resources::{BalanceHolder, ResourceController, ResourceTracker},
73    runtime::{
74        ContractSyncRuntimeHandle, ServiceRuntimeRequest, ServiceSyncRuntime,
75        ServiceSyncRuntimeHandle,
76    },
77    system::{
78        SystemExecutionStateView, SystemMessage, SystemOperation, SystemQuery, SystemResponse,
79    },
80    transaction_tracker::{TransactionOutcome, TransactionTracker},
81};
82
83/// The `Linera.sol` library code to be included in solidity smart
84/// contracts using Linera features.
85pub const LINERA_SOL: &str = include_str!("../solidity/Linera.sol");
86pub const LINERA_TYPES_SOL: &str = include_str!("../solidity/LineraTypes.sol");
87
88/// The maximum length of a stream name.
89const MAX_STREAM_NAME_LEN: usize = 64;
90
91/// An implementation of [`UserContractModule`].
92#[derive(Clone)]
93pub struct UserContractCode(Box<dyn UserContractModule>);
94
95/// An implementation of [`UserServiceModule`].
96#[derive(Clone)]
97pub struct UserServiceCode(Box<dyn UserServiceModule>);
98
99/// An implementation of [`UserContract`].
100pub type UserContractInstance = Box<dyn UserContract>;
101
102/// An implementation of [`UserService`].
103pub type UserServiceInstance = Box<dyn UserService>;
104
105/// A factory trait to obtain a [`UserContract`] from a [`UserContractModule`]
106pub trait UserContractModule: dyn_clone::DynClone + Any + web_thread::Post + Send + Sync {
107    fn instantiate(
108        &self,
109        runtime: ContractSyncRuntimeHandle,
110    ) -> Result<UserContractInstance, ExecutionError>;
111}
112
113impl<T: UserContractModule + Send + Sync + 'static> From<T> for UserContractCode {
114    fn from(module: T) -> Self {
115        Self(Box::new(module))
116    }
117}
118
119dyn_clone::clone_trait_object!(UserContractModule);
120
121/// A factory trait to obtain a [`UserService`] from a [`UserServiceModule`]
122pub trait UserServiceModule: dyn_clone::DynClone + Any + web_thread::Post + Send + Sync {
123    fn instantiate(
124        &self,
125        runtime: ServiceSyncRuntimeHandle,
126    ) -> Result<UserServiceInstance, ExecutionError>;
127}
128
129impl<T: UserServiceModule + Send + Sync + 'static> From<T> for UserServiceCode {
130    fn from(module: T) -> Self {
131        Self(Box::new(module))
132    }
133}
134
135dyn_clone::clone_trait_object!(UserServiceModule);
136
137impl UserServiceCode {
138    fn instantiate(
139        &self,
140        runtime: ServiceSyncRuntimeHandle,
141    ) -> Result<UserServiceInstance, ExecutionError> {
142        self.0.instantiate(runtime)
143    }
144}
145
146impl UserContractCode {
147    fn instantiate(
148        &self,
149        runtime: ContractSyncRuntimeHandle,
150    ) -> Result<UserContractInstance, ExecutionError> {
151        self.0.instantiate(runtime)
152    }
153}
154
155pub struct JsVec<T>(pub Vec<T>);
156
157#[cfg(web)]
158const _: () = {
159    // TODO(#2775): add a vtable pointer into the JsValue rather than assuming the
160    // implementor
161
162    impl web_thread::AsJs for UserContractCode {
163        fn to_js(&self) -> Result<JsValue, JsValue> {
164            ((&*self.0) as &dyn Any)
165                .downcast_ref::<WasmContractModule>()
166                .expect("we only support Wasm modules on the Web for now")
167                .to_js()
168        }
169
170        fn from_js(value: JsValue) -> Result<Self, JsValue> {
171            WasmContractModule::from_js(value).map(Into::into)
172        }
173    }
174
175    impl web_thread::Post for UserContractCode {
176        fn transferables(&self) -> js_sys::Array {
177            self.0.transferables()
178        }
179    }
180
181    impl web_thread::AsJs for UserServiceCode {
182        fn to_js(&self) -> Result<JsValue, JsValue> {
183            ((&*self.0) as &dyn Any)
184                .downcast_ref::<WasmServiceModule>()
185                .expect("we only support Wasm modules on the Web for now")
186                .to_js()
187        }
188
189        fn from_js(value: JsValue) -> Result<Self, JsValue> {
190            WasmServiceModule::from_js(value).map(Into::into)
191        }
192    }
193
194    impl web_thread::Post for UserServiceCode {
195        fn transferables(&self) -> js_sys::Array {
196            self.0.transferables()
197        }
198    }
199
200    impl<T: web_thread::AsJs> web_thread::AsJs for JsVec<T> {
201        fn to_js(&self) -> Result<JsValue, JsValue> {
202            let array = self
203                .0
204                .iter()
205                .map(T::to_js)
206                .collect::<Result<js_sys::Array, _>>()?;
207            Ok(array.into())
208        }
209
210        fn from_js(value: JsValue) -> Result<Self, JsValue> {
211            let array = js_sys::Array::from(&value);
212            let v = array
213                .into_iter()
214                .map(T::from_js)
215                .collect::<Result<Vec<_>, _>>()?;
216            Ok(JsVec(v))
217        }
218    }
219
220    impl<T: web_thread::Post> web_thread::Post for JsVec<T> {
221        fn transferables(&self) -> js_sys::Array {
222            let mut array = js_sys::Array::new();
223            for x in &self.0 {
224                array = array.concat(&x.transferables());
225            }
226            array
227        }
228    }
229};
230
231/// A type for errors happening during execution.
232#[derive(Error, Debug)]
233pub enum ExecutionError {
234    #[error(transparent)]
235    ViewError(#[from] ViewError),
236    #[error(transparent)]
237    ArithmeticError(#[from] ArithmeticError),
238    #[error("User application reported an error: {0}")]
239    UserError(String),
240    #[cfg(with_wasm_runtime)]
241    #[error(transparent)]
242    WasmError(#[from] WasmExecutionError),
243    #[cfg(with_revm)]
244    #[error(transparent)]
245    EvmError(#[from] EvmExecutionError),
246    #[error(transparent)]
247    DecompressionError(#[from] DecompressionError),
248    #[error("The given promise is invalid or was polled once already")]
249    InvalidPromise,
250
251    #[error("Attempted to perform a reentrant call to application {0}")]
252    ReentrantCall(ApplicationId),
253    #[error(
254        "Application {caller_id} attempted to perform a cross-application to {callee_id} call \
255        from `finalize`"
256    )]
257    CrossApplicationCallInFinalize {
258        caller_id: Box<ApplicationId>,
259        callee_id: Box<ApplicationId>,
260    },
261    #[error("Failed to load bytecode from storage {0:?}")]
262    ApplicationBytecodeNotFound(Box<ApplicationDescription>),
263    // TODO(#2927): support dynamic loading of modules on the Web
264    #[error("Unsupported dynamic application load: {0:?}")]
265    UnsupportedDynamicApplicationLoad(Box<ApplicationId>),
266
267    #[error("Excessive number of bytes read from storage")]
268    ExcessiveRead,
269    #[error("Excessive number of bytes written to storage")]
270    ExcessiveWrite,
271    #[error("Block execution required too much fuel for VM {0}")]
272    MaximumFuelExceeded(VmRuntime),
273    #[error("Services running as oracles in block took longer than allowed")]
274    MaximumServiceOracleExecutionTimeExceeded,
275    #[error("Service running as an oracle produced a response that's too large")]
276    ServiceOracleResponseTooLarge,
277    #[error("Serialized size of the block exceeds limit")]
278    BlockTooLarge,
279    #[error("HTTP response exceeds the size limit of {limit} bytes, having at least {size} bytes")]
280    HttpResponseSizeLimitExceeded { limit: u64, size: u64 },
281    #[error("Runtime failed to respond to application")]
282    MissingRuntimeResponse,
283    #[error("Application is not authorized to perform system operations on this chain: {0:}")]
284    UnauthorizedApplication(ApplicationId),
285    #[error("Failed to make network reqwest: {0}")]
286    ReqwestError(#[from] reqwest::Error),
287    #[error("Encountered I/O error: {0}")]
288    IoError(#[from] std::io::Error),
289    #[error("More recorded oracle responses than expected")]
290    UnexpectedOracleResponse,
291    #[error("Invalid JSON: {0}")]
292    JsonError(#[from] serde_json::Error),
293    #[error(transparent)]
294    BcsError(#[from] bcs::Error),
295    #[error("Recorded response for oracle query has the wrong type")]
296    OracleResponseMismatch,
297    #[error("Service oracle query tried to create operations: {0:?}")]
298    ServiceOracleQueryOperations(Vec<Operation>),
299    #[error("Assertion failed: local time {local_time} is not earlier than {timestamp}")]
300    AssertBefore {
301        timestamp: Timestamp,
302        local_time: Timestamp,
303    },
304
305    #[error("Stream names can be at most {MAX_STREAM_NAME_LEN} bytes.")]
306    StreamNameTooLong,
307    #[error("Blob exceeds size limit")]
308    BlobTooLarge,
309    #[error("Bytecode exceeds size limit")]
310    BytecodeTooLarge,
311    #[error("Attempt to perform an HTTP request to an unauthorized host: {0:?}")]
312    UnauthorizedHttpRequest(reqwest::Url),
313    #[error("Attempt to perform an HTTP request to an invalid URL")]
314    InvalidUrlForHttpRequest(#[from] url::ParseError),
315    #[error("Worker thread failure: {0:?}")]
316    Thread(#[from] web_thread::Error),
317    #[error("The chain being queried is not active {0}")]
318    InactiveChain(ChainId),
319    #[error("Blobs not found: {0:?}")]
320    BlobsNotFound(Vec<BlobId>),
321    #[error("Events not found: {0:?}")]
322    EventsNotFound(Vec<EventId>),
323
324    #[error("Invalid HTTP header name used for HTTP request")]
325    InvalidHeaderName(#[from] reqwest::header::InvalidHeaderName),
326    #[error("Invalid HTTP header value used for HTTP request")]
327    InvalidHeaderValue(#[from] reqwest::header::InvalidHeaderValue),
328
329    #[error("No NetworkDescription found in storage")]
330    NoNetworkDescriptionFound,
331    #[error("{epoch:?} is not recognized by chain {chain_id:}")]
332    InvalidEpoch { chain_id: ChainId, epoch: Epoch },
333    #[error("Transfer must have positive amount")]
334    IncorrectTransferAmount,
335    #[error("Transfer from owned account must be authenticated by the right owner")]
336    UnauthenticatedTransferOwner,
337    #[error("The transferred amount must not exceed the balance of the current account {account}: {balance}")]
338    InsufficientBalance {
339        balance: Amount,
340        account: AccountOwner,
341    },
342    #[error("Required execution fees exceeded the total funding available. Fees {fees}, available balance: {balance}")]
343    FeesExceedFunding { fees: Amount, balance: Amount },
344    #[error("Claim must have positive amount")]
345    IncorrectClaimAmount,
346    #[error("Claim must be authenticated by the right owner")]
347    UnauthenticatedClaimOwner,
348    #[error("Admin operations are only allowed on the admin chain.")]
349    AdminOperationOnNonAdminChain,
350    #[error("Failed to create new committee: expected {expected}, but got {provided}")]
351    InvalidCommitteeEpoch { expected: Epoch, provided: Epoch },
352    #[error("Failed to remove committee")]
353    InvalidCommitteeRemoval,
354    #[error("No recorded response for oracle query")]
355    MissingOracleResponse,
356    #[error("process_streams was not called for all stream updates")]
357    UnprocessedStreams,
358    #[error("Internal error: {0}")]
359    InternalError(&'static str),
360    #[error("UpdateStreams is outdated")]
361    OutdatedUpdateStreams,
362}
363
364impl ExecutionError {
365    /// Returns whether this error is caused by an issue in the local node.
366    ///
367    /// Returns `false` whenever the error could be caused by a bad message from a peer.
368    pub fn is_local(&self) -> bool {
369        match self {
370            ExecutionError::ArithmeticError(_)
371            | ExecutionError::UserError(_)
372            | ExecutionError::DecompressionError(_)
373            | ExecutionError::InvalidPromise
374            | ExecutionError::CrossApplicationCallInFinalize { .. }
375            | ExecutionError::ReentrantCall(_)
376            | ExecutionError::ApplicationBytecodeNotFound(_)
377            | ExecutionError::UnsupportedDynamicApplicationLoad(_)
378            | ExecutionError::ExcessiveRead
379            | ExecutionError::ExcessiveWrite
380            | ExecutionError::MaximumFuelExceeded(_)
381            | ExecutionError::MaximumServiceOracleExecutionTimeExceeded
382            | ExecutionError::ServiceOracleResponseTooLarge
383            | ExecutionError::BlockTooLarge
384            | ExecutionError::HttpResponseSizeLimitExceeded { .. }
385            | ExecutionError::UnauthorizedApplication(_)
386            | ExecutionError::UnexpectedOracleResponse
387            | ExecutionError::JsonError(_)
388            | ExecutionError::BcsError(_)
389            | ExecutionError::OracleResponseMismatch
390            | ExecutionError::ServiceOracleQueryOperations(_)
391            | ExecutionError::AssertBefore { .. }
392            | ExecutionError::StreamNameTooLong
393            | ExecutionError::BlobTooLarge
394            | ExecutionError::BytecodeTooLarge
395            | ExecutionError::UnauthorizedHttpRequest(_)
396            | ExecutionError::InvalidUrlForHttpRequest(_)
397            | ExecutionError::InactiveChain(_)
398            | ExecutionError::BlobsNotFound(_)
399            | ExecutionError::EventsNotFound(_)
400            | ExecutionError::InvalidHeaderName(_)
401            | ExecutionError::InvalidHeaderValue(_)
402            | ExecutionError::InvalidEpoch { .. }
403            | ExecutionError::IncorrectTransferAmount
404            | ExecutionError::UnauthenticatedTransferOwner
405            | ExecutionError::InsufficientBalance { .. }
406            | ExecutionError::FeesExceedFunding { .. }
407            | ExecutionError::IncorrectClaimAmount
408            | ExecutionError::UnauthenticatedClaimOwner
409            | ExecutionError::AdminOperationOnNonAdminChain
410            | ExecutionError::InvalidCommitteeEpoch { .. }
411            | ExecutionError::InvalidCommitteeRemoval
412            | ExecutionError::MissingOracleResponse
413            | ExecutionError::UnprocessedStreams
414            | ExecutionError::OutdatedUpdateStreams
415            | ExecutionError::ViewError(ViewError::NotFound(_)) => false,
416            #[cfg(with_wasm_runtime)]
417            ExecutionError::WasmError(_) => false,
418            #[cfg(with_revm)]
419            ExecutionError::EvmError(..) => false,
420            ExecutionError::MissingRuntimeResponse
421            | ExecutionError::ViewError(_)
422            | ExecutionError::ReqwestError(_)
423            | ExecutionError::Thread(_)
424            | ExecutionError::NoNetworkDescriptionFound
425            | ExecutionError::InternalError(_)
426            | ExecutionError::IoError(_) => true,
427        }
428    }
429}
430
431/// The public entry points provided by the contract part of an application.
432pub trait UserContract {
433    /// Instantiate the application state on the chain that owns the application.
434    fn instantiate(&mut self, argument: Vec<u8>) -> Result<(), ExecutionError>;
435
436    /// Applies an operation from the current block.
437    fn execute_operation(&mut self, operation: Vec<u8>) -> Result<Vec<u8>, ExecutionError>;
438
439    /// Applies a message originating from a cross-chain message.
440    fn execute_message(&mut self, message: Vec<u8>) -> Result<(), ExecutionError>;
441
442    /// Reacts to new events on streams this application subscribes to.
443    fn process_streams(&mut self, updates: Vec<StreamUpdate>) -> Result<(), ExecutionError>;
444
445    /// Finishes execution of the current transaction.
446    fn finalize(&mut self) -> Result<(), ExecutionError>;
447}
448
449/// The public entry points provided by the service part of an application.
450pub trait UserService {
451    /// Executes unmetered read-only queries on the state of this application.
452    fn handle_query(&mut self, argument: Vec<u8>) -> Result<Vec<u8>, ExecutionError>;
453}
454
455/// Configuration options for the execution runtime available to applications.
456#[derive(Clone, Copy, Default)]
457pub struct ExecutionRuntimeConfig {
458    /// Whether contract log messages should be output.
459    /// This is typically enabled for clients but disabled for validators.
460    pub allow_application_logs: bool,
461}
462
463/// Requirements for the `extra` field in our state views (and notably the
464/// [`ExecutionStateView`]).
465#[cfg_attr(not(web), async_trait)]
466#[cfg_attr(web, async_trait(?Send))]
467pub trait ExecutionRuntimeContext {
468    fn chain_id(&self) -> ChainId;
469
470    fn thread_pool(&self) -> &Arc<ThreadPool>;
471
472    fn execution_runtime_config(&self) -> ExecutionRuntimeConfig;
473
474    fn user_contracts(&self) -> &Arc<papaya::HashMap<ApplicationId, UserContractCode>>;
475
476    fn user_services(&self) -> &Arc<papaya::HashMap<ApplicationId, UserServiceCode>>;
477
478    async fn get_user_contract(
479        &self,
480        description: &ApplicationDescription,
481        txn_tracker: &TransactionTracker,
482    ) -> Result<UserContractCode, ExecutionError>;
483
484    async fn get_user_service(
485        &self,
486        description: &ApplicationDescription,
487        txn_tracker: &TransactionTracker,
488    ) -> Result<UserServiceCode, ExecutionError>;
489
490    async fn get_blob(&self, blob_id: BlobId) -> Result<Option<Blob>, ViewError>;
491
492    async fn get_event(&self, event_id: EventId) -> Result<Option<Vec<u8>>, ViewError>;
493
494    async fn get_network_description(&self) -> Result<Option<NetworkDescription>, ViewError>;
495
496    /// Returns the committees for the epochs in the given range.
497    async fn get_committees(
498        &self,
499        epoch_range: RangeInclusive<Epoch>,
500    ) -> Result<BTreeMap<Epoch, Committee>, ExecutionError> {
501        let net_description = self
502            .get_network_description()
503            .await?
504            .ok_or(ExecutionError::NoNetworkDescriptionFound)?;
505        let committee_hashes = futures::future::join_all(
506            (epoch_range.start().0..=epoch_range.end().0).map(|epoch| async move {
507                if epoch == 0 {
508                    // Genesis epoch is stored in NetworkDescription.
509                    Ok((epoch, net_description.genesis_committee_blob_hash))
510                } else {
511                    let event_id = EventId {
512                        chain_id: net_description.admin_chain_id,
513                        stream_id: StreamId::system(EPOCH_STREAM_NAME),
514                        index: epoch,
515                    };
516                    let event = self
517                        .get_event(event_id.clone())
518                        .await?
519                        .ok_or_else(|| ExecutionError::EventsNotFound(vec![event_id]))?;
520                    let event_data: EpochEventData = bcs::from_bytes(&event)?;
521                    Ok((epoch, event_data.blob_hash))
522                }
523            }),
524        )
525        .await;
526        let missing_events = committee_hashes
527            .iter()
528            .filter_map(|result| {
529                if let Err(ExecutionError::EventsNotFound(event_ids)) = result {
530                    return Some(event_ids);
531                }
532                None
533            })
534            .flatten()
535            .cloned()
536            .collect::<Vec<_>>();
537        ensure!(
538            missing_events.is_empty(),
539            ExecutionError::EventsNotFound(missing_events)
540        );
541        let committee_hashes = committee_hashes
542            .into_iter()
543            .collect::<Result<Vec<_>, _>>()?;
544        let committees = futures::future::join_all(committee_hashes.into_iter().map(
545            |(epoch, committee_hash)| async move {
546                let blob_id = BlobId::new(committee_hash, BlobType::Committee);
547                let committee_blob = self
548                    .get_blob(blob_id)
549                    .await?
550                    .ok_or_else(|| ExecutionError::BlobsNotFound(vec![blob_id]))?;
551                Ok((Epoch(epoch), bcs::from_bytes(committee_blob.bytes())?))
552            },
553        ))
554        .await;
555        let missing_blobs = committees
556            .iter()
557            .filter_map(|result| {
558                if let Err(ExecutionError::BlobsNotFound(blob_ids)) = result {
559                    return Some(blob_ids);
560                }
561                None
562            })
563            .flatten()
564            .cloned()
565            .collect::<Vec<_>>();
566        ensure!(
567            missing_blobs.is_empty(),
568            ExecutionError::BlobsNotFound(missing_blobs)
569        );
570        committees.into_iter().collect()
571    }
572
573    async fn contains_blob(&self, blob_id: BlobId) -> Result<bool, ViewError>;
574
575    async fn contains_event(&self, event_id: EventId) -> Result<bool, ViewError>;
576
577    #[cfg(with_testing)]
578    async fn add_blobs(
579        &self,
580        blobs: impl IntoIterator<Item = Blob> + Send,
581    ) -> Result<(), ViewError>;
582
583    #[cfg(with_testing)]
584    async fn add_events(
585        &self,
586        events: impl IntoIterator<Item = (EventId, Vec<u8>)> + Send,
587    ) -> Result<(), ViewError>;
588}
589
590#[derive(Clone, Copy, Debug)]
591pub struct OperationContext {
592    /// The current chain ID.
593    pub chain_id: ChainId,
594    /// The authenticated owner of the operation, if any.
595    #[debug(skip_if = Option::is_none)]
596    pub authenticated_owner: Option<AccountOwner>,
597    /// The current block height.
598    pub height: BlockHeight,
599    /// The consensus round number, if this is a block that gets validated in a multi-leader round.
600    pub round: Option<u32>,
601    /// The timestamp of the block containing the operation.
602    pub timestamp: Timestamp,
603}
604
605#[derive(Clone, Copy, Debug)]
606pub struct MessageContext {
607    /// The current chain ID.
608    pub chain_id: ChainId,
609    /// The chain ID where the message originated from.
610    pub origin: ChainId,
611    /// Whether the message was rejected by the original receiver and is now bouncing back.
612    pub is_bouncing: bool,
613    /// The authenticated owner of the operation that created the message, if any.
614    #[debug(skip_if = Option::is_none)]
615    pub authenticated_owner: Option<AccountOwner>,
616    /// Where to send a refund for the unused part of each grant after execution, if any.
617    #[debug(skip_if = Option::is_none)]
618    pub refund_grant_to: Option<Account>,
619    /// The current block height.
620    pub height: BlockHeight,
621    /// The consensus round number, if this is a block that gets validated in a multi-leader round.
622    pub round: Option<u32>,
623    /// The timestamp of the block executing the message.
624    pub timestamp: Timestamp,
625}
626
627#[derive(Clone, Copy, Debug)]
628pub struct ProcessStreamsContext {
629    /// The current chain ID.
630    pub chain_id: ChainId,
631    /// The current block height.
632    pub height: BlockHeight,
633    /// The consensus round number, if this is a block that gets validated in a multi-leader round.
634    pub round: Option<u32>,
635    /// The timestamp of the current block.
636    pub timestamp: Timestamp,
637}
638
639impl From<MessageContext> for ProcessStreamsContext {
640    fn from(context: MessageContext) -> Self {
641        Self {
642            chain_id: context.chain_id,
643            height: context.height,
644            round: context.round,
645            timestamp: context.timestamp,
646        }
647    }
648}
649
650impl From<OperationContext> for ProcessStreamsContext {
651    fn from(context: OperationContext) -> Self {
652        Self {
653            chain_id: context.chain_id,
654            height: context.height,
655            round: context.round,
656            timestamp: context.timestamp,
657        }
658    }
659}
660
661#[derive(Clone, Copy, Debug)]
662pub struct FinalizeContext {
663    /// The current chain ID.
664    pub chain_id: ChainId,
665    /// The authenticated owner of the operation, if any.
666    #[debug(skip_if = Option::is_none)]
667    pub authenticated_owner: Option<AccountOwner>,
668    /// The current block height.
669    pub height: BlockHeight,
670    /// The consensus round number, if this is a block that gets validated in a multi-leader round.
671    pub round: Option<u32>,
672}
673
674#[derive(Clone, Copy, Debug, Eq, PartialEq)]
675pub struct QueryContext {
676    /// The current chain ID.
677    pub chain_id: ChainId,
678    /// The height of the next block on this chain.
679    pub next_block_height: BlockHeight,
680    /// The local time in the node executing the query.
681    pub local_time: Timestamp,
682}
683
684pub trait BaseRuntime {
685    type Read: fmt::Debug + Send + Sync;
686    type ContainsKey: fmt::Debug + Send + Sync;
687    type ContainsKeys: fmt::Debug + Send + Sync;
688    type ReadMultiValuesBytes: fmt::Debug + Send + Sync;
689    type ReadValueBytes: fmt::Debug + Send + Sync;
690    type FindKeysByPrefix: fmt::Debug + Send + Sync;
691    type FindKeyValuesByPrefix: fmt::Debug + Send + Sync;
692
693    /// The current chain ID.
694    fn chain_id(&mut self) -> Result<ChainId, ExecutionError>;
695
696    /// The current block height.
697    fn block_height(&mut self) -> Result<BlockHeight, ExecutionError>;
698
699    /// The current application ID.
700    fn application_id(&mut self) -> Result<ApplicationId, ExecutionError>;
701
702    /// The current application creator's chain ID.
703    fn application_creator_chain_id(&mut self) -> Result<ChainId, ExecutionError>;
704
705    /// The current application parameters.
706    fn application_parameters(&mut self) -> Result<Vec<u8>, ExecutionError>;
707
708    /// Reads the system timestamp.
709    fn read_system_timestamp(&mut self) -> Result<Timestamp, ExecutionError>;
710
711    /// Reads the balance of the chain.
712    fn read_chain_balance(&mut self) -> Result<Amount, ExecutionError>;
713
714    /// Reads the owner balance.
715    fn read_owner_balance(&mut self, owner: AccountOwner) -> Result<Amount, ExecutionError>;
716
717    /// Reads the balances from all owners.
718    fn read_owner_balances(&mut self) -> Result<Vec<(AccountOwner, Amount)>, ExecutionError>;
719
720    /// Reads balance owners.
721    fn read_balance_owners(&mut self) -> Result<Vec<AccountOwner>, ExecutionError>;
722
723    /// Reads the current ownership configuration for this chain.
724    fn chain_ownership(&mut self) -> Result<ChainOwnership, ExecutionError>;
725
726    /// Tests whether a key exists in the key-value store
727    #[cfg(feature = "test")]
728    fn contains_key(&mut self, key: Vec<u8>) -> Result<bool, ExecutionError> {
729        let promise = self.contains_key_new(key)?;
730        self.contains_key_wait(&promise)
731    }
732
733    /// Creates the promise to test whether a key exists in the key-value store
734    fn contains_key_new(&mut self, key: Vec<u8>) -> Result<Self::ContainsKey, ExecutionError>;
735
736    /// Resolves the promise to test whether a key exists in the key-value store
737    fn contains_key_wait(&mut self, promise: &Self::ContainsKey) -> Result<bool, ExecutionError>;
738
739    /// Tests whether multiple keys exist in the key-value store
740    #[cfg(feature = "test")]
741    fn contains_keys(&mut self, keys: Vec<Vec<u8>>) -> Result<Vec<bool>, ExecutionError> {
742        let promise = self.contains_keys_new(keys)?;
743        self.contains_keys_wait(&promise)
744    }
745
746    /// Creates the promise to test whether multiple keys exist in the key-value store
747    fn contains_keys_new(
748        &mut self,
749        keys: Vec<Vec<u8>>,
750    ) -> Result<Self::ContainsKeys, ExecutionError>;
751
752    /// Resolves the promise to test whether multiple keys exist in the key-value store
753    fn contains_keys_wait(
754        &mut self,
755        promise: &Self::ContainsKeys,
756    ) -> Result<Vec<bool>, ExecutionError>;
757
758    /// Reads several keys from the key-value store
759    #[cfg(feature = "test")]
760    fn read_multi_values_bytes(
761        &mut self,
762        keys: Vec<Vec<u8>>,
763    ) -> Result<Vec<Option<Vec<u8>>>, ExecutionError> {
764        let promise = self.read_multi_values_bytes_new(keys)?;
765        self.read_multi_values_bytes_wait(&promise)
766    }
767
768    /// Creates the promise to access several keys from the key-value store
769    fn read_multi_values_bytes_new(
770        &mut self,
771        keys: Vec<Vec<u8>>,
772    ) -> Result<Self::ReadMultiValuesBytes, ExecutionError>;
773
774    /// Resolves the promise to access several keys from the key-value store
775    fn read_multi_values_bytes_wait(
776        &mut self,
777        promise: &Self::ReadMultiValuesBytes,
778    ) -> Result<Vec<Option<Vec<u8>>>, ExecutionError>;
779
780    /// Reads the key from the key-value store
781    #[cfg(feature = "test")]
782    fn read_value_bytes(&mut self, key: Vec<u8>) -> Result<Option<Vec<u8>>, ExecutionError> {
783        let promise = self.read_value_bytes_new(key)?;
784        self.read_value_bytes_wait(&promise)
785    }
786
787    /// Creates the promise to access a key from the key-value store
788    fn read_value_bytes_new(
789        &mut self,
790        key: Vec<u8>,
791    ) -> Result<Self::ReadValueBytes, ExecutionError>;
792
793    /// Resolves the promise to access a key from the key-value store
794    fn read_value_bytes_wait(
795        &mut self,
796        promise: &Self::ReadValueBytes,
797    ) -> Result<Option<Vec<u8>>, ExecutionError>;
798
799    /// Creates the promise to access keys having a specific prefix
800    fn find_keys_by_prefix_new(
801        &mut self,
802        key_prefix: Vec<u8>,
803    ) -> Result<Self::FindKeysByPrefix, ExecutionError>;
804
805    /// Resolves the promise to access keys having a specific prefix
806    fn find_keys_by_prefix_wait(
807        &mut self,
808        promise: &Self::FindKeysByPrefix,
809    ) -> Result<Vec<Vec<u8>>, ExecutionError>;
810
811    /// Reads the data from the key/values having a specific prefix.
812    #[cfg(feature = "test")]
813    #[expect(clippy::type_complexity)]
814    fn find_key_values_by_prefix(
815        &mut self,
816        key_prefix: Vec<u8>,
817    ) -> Result<Vec<(Vec<u8>, Vec<u8>)>, ExecutionError> {
818        let promise = self.find_key_values_by_prefix_new(key_prefix)?;
819        self.find_key_values_by_prefix_wait(&promise)
820    }
821
822    /// Creates the promise to access key/values having a specific prefix
823    fn find_key_values_by_prefix_new(
824        &mut self,
825        key_prefix: Vec<u8>,
826    ) -> Result<Self::FindKeyValuesByPrefix, ExecutionError>;
827
828    /// Resolves the promise to access key/values having a specific prefix
829    #[expect(clippy::type_complexity)]
830    fn find_key_values_by_prefix_wait(
831        &mut self,
832        promise: &Self::FindKeyValuesByPrefix,
833    ) -> Result<Vec<(Vec<u8>, Vec<u8>)>, ExecutionError>;
834
835    /// Makes an HTTP request to the given URL and returns the answer, if any.
836    fn perform_http_request(
837        &mut self,
838        request: http::Request,
839    ) -> Result<http::Response, ExecutionError>;
840
841    /// Ensures that the current time at block validation is `< timestamp`. Note that block
842    /// validation happens at or after the block timestamp, but isn't necessarily the same.
843    ///
844    /// Cannot be used in fast blocks: A block using this call should be proposed by a regular
845    /// owner, not a super owner.
846    fn assert_before(&mut self, timestamp: Timestamp) -> Result<(), ExecutionError>;
847
848    /// Reads a data blob specified by a given hash.
849    fn read_data_blob(&mut self, hash: DataBlobHash) -> Result<Vec<u8>, ExecutionError>;
850
851    /// Asserts the existence of a data blob with the given hash.
852    fn assert_data_blob_exists(&mut self, hash: DataBlobHash) -> Result<(), ExecutionError>;
853
854    /// Returns true if the corresponding contract uses a zero amount of storage.
855    fn has_empty_storage(&mut self, application: ApplicationId) -> Result<bool, ExecutionError>;
856
857    /// Returns the maximum blob size from the `ResourceControlPolicy`.
858    fn maximum_blob_size(&mut self) -> Result<u64, ExecutionError>;
859
860    /// Returns whether contract log messages should be output.
861    /// This is typically enabled for clients but disabled for validators.
862    fn allow_application_logs(&mut self) -> Result<bool, ExecutionError>;
863}
864
865pub trait ServiceRuntime: BaseRuntime {
866    /// Queries another application.
867    fn try_query_application(
868        &mut self,
869        queried_id: ApplicationId,
870        argument: Vec<u8>,
871    ) -> Result<Vec<u8>, ExecutionError>;
872
873    /// Schedules an operation to be included in the block proposed after execution.
874    fn schedule_operation(&mut self, operation: Vec<u8>) -> Result<(), ExecutionError>;
875
876    /// Checks if the service has exceeded its execution time limit.
877    fn check_execution_time(&mut self) -> Result<(), ExecutionError>;
878}
879
880pub trait ContractRuntime: BaseRuntime {
881    /// The authenticated owner for this execution, if there is one.
882    fn authenticated_owner(&mut self) -> Result<Option<AccountOwner>, ExecutionError>;
883
884    /// If the current message (if there is one) was rejected by its destination and is now
885    /// bouncing back.
886    fn message_is_bouncing(&mut self) -> Result<Option<bool>, ExecutionError>;
887
888    /// The chain ID where the current message originated from, if there is one.
889    fn message_origin_chain_id(&mut self) -> Result<Option<ChainId>, ExecutionError>;
890
891    /// The optional authenticated caller application ID, if it was provided and if there is one
892    /// based on the execution context.
893    fn authenticated_caller_id(&mut self) -> Result<Option<ApplicationId>, ExecutionError>;
894
895    /// Returns the maximum gas fuel per block.
896    fn maximum_fuel_per_block(&mut self, vm_runtime: VmRuntime) -> Result<u64, ExecutionError>;
897
898    /// Returns the amount of execution fuel remaining before execution is aborted.
899    fn remaining_fuel(&mut self, vm_runtime: VmRuntime) -> Result<u64, ExecutionError>;
900
901    /// Consumes some of the execution fuel.
902    fn consume_fuel(&mut self, fuel: u64, vm_runtime: VmRuntime) -> Result<(), ExecutionError>;
903
904    /// Schedules a message to be sent.
905    fn send_message(&mut self, message: SendMessageRequest<Vec<u8>>) -> Result<(), ExecutionError>;
906
907    /// Transfers amount from source to destination.
908    fn transfer(
909        &mut self,
910        source: AccountOwner,
911        destination: Account,
912        amount: Amount,
913    ) -> Result<(), ExecutionError>;
914
915    /// Claims amount from source to destination.
916    fn claim(
917        &mut self,
918        source: Account,
919        destination: Account,
920        amount: Amount,
921    ) -> Result<(), ExecutionError>;
922
923    /// Calls another application. Forwarded sessions will now be visible to
924    /// `callee_id` (but not to the caller any more).
925    fn try_call_application(
926        &mut self,
927        authenticated: bool,
928        callee_id: ApplicationId,
929        argument: Vec<u8>,
930    ) -> Result<Vec<u8>, ExecutionError>;
931
932    /// Adds a new item to an event stream. Returns the new event's index in the stream.
933    fn emit(&mut self, name: StreamName, value: Vec<u8>) -> Result<u32, ExecutionError>;
934
935    /// Reads an event from a stream. Returns the event's value.
936    ///
937    /// Returns an error if the event doesn't exist.
938    fn read_event(
939        &mut self,
940        chain_id: ChainId,
941        stream_name: StreamName,
942        index: u32,
943    ) -> Result<Vec<u8>, ExecutionError>;
944
945    /// Subscribes this application to an event stream.
946    fn subscribe_to_events(
947        &mut self,
948        chain_id: ChainId,
949        application_id: ApplicationId,
950        stream_name: StreamName,
951    ) -> Result<(), ExecutionError>;
952
953    /// Unsubscribes this application from an event stream.
954    fn unsubscribe_from_events(
955        &mut self,
956        chain_id: ChainId,
957        application_id: ApplicationId,
958        stream_name: StreamName,
959    ) -> Result<(), ExecutionError>;
960
961    /// Queries a service.
962    fn query_service(
963        &mut self,
964        application_id: ApplicationId,
965        query: Vec<u8>,
966    ) -> Result<Vec<u8>, ExecutionError>;
967
968    /// Opens a new chain.
969    fn open_chain(
970        &mut self,
971        ownership: ChainOwnership,
972        application_permissions: ApplicationPermissions,
973        balance: Amount,
974    ) -> Result<ChainId, ExecutionError>;
975
976    /// Closes the current chain.
977    fn close_chain(&mut self) -> Result<(), ExecutionError>;
978
979    /// Changes the application permissions on the current chain.
980    fn change_application_permissions(
981        &mut self,
982        application_permissions: ApplicationPermissions,
983    ) -> Result<(), ExecutionError>;
984
985    /// Creates a new application on chain.
986    fn create_application(
987        &mut self,
988        module_id: ModuleId,
989        parameters: Vec<u8>,
990        argument: Vec<u8>,
991        required_application_ids: Vec<ApplicationId>,
992    ) -> Result<ApplicationId, ExecutionError>;
993
994    /// Returns the next application index, which is equal to the number of
995    /// new applications created so far in this block.
996    fn peek_application_index(&mut self) -> Result<u32, ExecutionError>;
997
998    /// Creates a new data blob and returns its hash.
999    fn create_data_blob(&mut self, bytes: Vec<u8>) -> Result<DataBlobHash, ExecutionError>;
1000
1001    /// Publishes a module with contract and service bytecode and returns the module ID.
1002    fn publish_module(
1003        &mut self,
1004        contract: Bytecode,
1005        service: Bytecode,
1006        vm_runtime: VmRuntime,
1007    ) -> Result<ModuleId, ExecutionError>;
1008
1009    /// Returns the multi-leader round in which this block was validated.
1010    fn validation_round(&mut self) -> Result<Option<u32>, ExecutionError>;
1011
1012    /// Writes a batch of changes.
1013    fn write_batch(&mut self, batch: Batch) -> Result<(), ExecutionError>;
1014}
1015
1016/// An operation to be executed in a block.
1017#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, Allocative)]
1018pub enum Operation {
1019    /// A system operation.
1020    System(Box<SystemOperation>),
1021    /// A user operation (in serialized form).
1022    User {
1023        application_id: ApplicationId,
1024        #[serde(with = "serde_bytes")]
1025        #[debug(with = "hex_debug")]
1026        bytes: Vec<u8>,
1027    },
1028}
1029
1030impl BcsHashable<'_> for Operation {}
1031
1032/// A message to be sent and possibly executed in the receiver's block.
1033#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, Allocative)]
1034pub enum Message {
1035    /// A system message.
1036    System(SystemMessage),
1037    /// A user message (in serialized form).
1038    User {
1039        application_id: ApplicationId,
1040        #[serde(with = "serde_bytes")]
1041        #[debug(with = "hex_debug")]
1042        bytes: Vec<u8>,
1043    },
1044}
1045
1046/// An query to be sent and possibly executed in the receiver's block.
1047#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1048pub enum Query {
1049    /// A system query.
1050    System(SystemQuery),
1051    /// A user query (in serialized form).
1052    User {
1053        application_id: ApplicationId,
1054        #[serde(with = "serde_bytes")]
1055        #[debug(with = "hex_debug")]
1056        bytes: Vec<u8>,
1057    },
1058}
1059
1060/// The outcome of the execution of a query.
1061#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1062pub struct QueryOutcome<Response = QueryResponse> {
1063    pub response: Response,
1064    pub operations: Vec<Operation>,
1065}
1066
1067impl From<QueryOutcome<SystemResponse>> for QueryOutcome {
1068    fn from(system_outcome: QueryOutcome<SystemResponse>) -> Self {
1069        let QueryOutcome {
1070            response,
1071            operations,
1072        } = system_outcome;
1073
1074        QueryOutcome {
1075            response: QueryResponse::System(response),
1076            operations,
1077        }
1078    }
1079}
1080
1081impl From<QueryOutcome<Vec<u8>>> for QueryOutcome {
1082    fn from(user_service_outcome: QueryOutcome<Vec<u8>>) -> Self {
1083        let QueryOutcome {
1084            response,
1085            operations,
1086        } = user_service_outcome;
1087
1088        QueryOutcome {
1089            response: QueryResponse::User(response),
1090            operations,
1091        }
1092    }
1093}
1094
1095/// The response to a query.
1096#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1097pub enum QueryResponse {
1098    /// A system response.
1099    System(SystemResponse),
1100    /// A user response (in serialized form).
1101    User(
1102        #[serde(with = "serde_bytes")]
1103        #[debug(with = "hex_debug")]
1104        Vec<u8>,
1105    ),
1106}
1107
1108/// The kind of outgoing message being sent.
1109#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, Copy, Allocative)]
1110pub enum MessageKind {
1111    /// The message can be skipped or rejected. No receipt is requested.
1112    Simple,
1113    /// The message cannot be skipped nor rejected. No receipt is requested.
1114    /// This only concerns certain system messages that cannot fail.
1115    Protected,
1116    /// The message cannot be skipped but can be rejected. A receipt must be sent
1117    /// when the message is rejected in a block of the receiver.
1118    Tracked,
1119    /// This message is a receipt automatically created when the original message was rejected.
1120    Bouncing,
1121}
1122
1123impl Display for MessageKind {
1124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1125        match self {
1126            MessageKind::Simple => write!(f, "Simple"),
1127            MessageKind::Protected => write!(f, "Protected"),
1128            MessageKind::Tracked => write!(f, "Tracked"),
1129            MessageKind::Bouncing => write!(f, "Bouncing"),
1130        }
1131    }
1132}
1133
1134/// A posted message together with routing information.
1135#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, SimpleObject, Allocative)]
1136pub struct OutgoingMessage {
1137    /// The destination of the message.
1138    pub destination: ChainId,
1139    /// The user authentication carried by the message, if any.
1140    #[debug(skip_if = Option::is_none)]
1141    pub authenticated_owner: Option<AccountOwner>,
1142    /// A grant to pay for the message execution.
1143    #[debug(skip_if = Amount::is_zero)]
1144    pub grant: Amount,
1145    /// Where to send a refund for the unused part of the grant after execution, if any.
1146    #[debug(skip_if = Option::is_none)]
1147    pub refund_grant_to: Option<Account>,
1148    /// The kind of message being sent.
1149    pub kind: MessageKind,
1150    /// The message itself.
1151    pub message: Message,
1152}
1153
1154impl BcsHashable<'_> for OutgoingMessage {}
1155
1156impl OutgoingMessage {
1157    /// Creates a new simple outgoing message with no grant and no authenticated owner.
1158    pub fn new(recipient: ChainId, message: impl Into<Message>) -> Self {
1159        OutgoingMessage {
1160            destination: recipient,
1161            authenticated_owner: None,
1162            grant: Amount::ZERO,
1163            refund_grant_to: None,
1164            kind: MessageKind::Simple,
1165            message: message.into(),
1166        }
1167    }
1168
1169    /// Returns the same message, with the specified kind.
1170    pub fn with_kind(mut self, kind: MessageKind) -> Self {
1171        self.kind = kind;
1172        self
1173    }
1174
1175    /// Returns the same message, with the specified authenticated owner.
1176    pub fn with_authenticated_owner(mut self, authenticated_owner: Option<AccountOwner>) -> Self {
1177        self.authenticated_owner = authenticated_owner;
1178        self
1179    }
1180}
1181
1182impl OperationContext {
1183    /// Returns an account for the refund.
1184    /// Returns `None` if there is no authenticated owner of the [`OperationContext`].
1185    fn refund_grant_to(&self) -> Option<Account> {
1186        self.authenticated_owner.map(|owner| Account {
1187            chain_id: self.chain_id,
1188            owner,
1189        })
1190    }
1191}
1192
1193#[cfg(with_testing)]
1194#[derive(Clone)]
1195pub struct TestExecutionRuntimeContext {
1196    chain_id: ChainId,
1197    thread_pool: Arc<ThreadPool>,
1198    execution_runtime_config: ExecutionRuntimeConfig,
1199    user_contracts: Arc<papaya::HashMap<ApplicationId, UserContractCode>>,
1200    user_services: Arc<papaya::HashMap<ApplicationId, UserServiceCode>>,
1201    blobs: Arc<papaya::HashMap<BlobId, Blob>>,
1202    events: Arc<papaya::HashMap<EventId, Vec<u8>>>,
1203}
1204
1205#[cfg(with_testing)]
1206impl TestExecutionRuntimeContext {
1207    pub fn new(chain_id: ChainId, execution_runtime_config: ExecutionRuntimeConfig) -> Self {
1208        Self {
1209            chain_id,
1210            thread_pool: Arc::new(ThreadPool::new(20)),
1211            execution_runtime_config,
1212            user_contracts: Arc::default(),
1213            user_services: Arc::default(),
1214            blobs: Arc::default(),
1215            events: Arc::default(),
1216        }
1217    }
1218}
1219
1220#[cfg(with_testing)]
1221#[cfg_attr(not(web), async_trait)]
1222#[cfg_attr(web, async_trait(?Send))]
1223impl ExecutionRuntimeContext for TestExecutionRuntimeContext {
1224    fn chain_id(&self) -> ChainId {
1225        self.chain_id
1226    }
1227
1228    fn thread_pool(&self) -> &Arc<ThreadPool> {
1229        &self.thread_pool
1230    }
1231
1232    fn execution_runtime_config(&self) -> ExecutionRuntimeConfig {
1233        self.execution_runtime_config
1234    }
1235
1236    fn user_contracts(&self) -> &Arc<papaya::HashMap<ApplicationId, UserContractCode>> {
1237        &self.user_contracts
1238    }
1239
1240    fn user_services(&self) -> &Arc<papaya::HashMap<ApplicationId, UserServiceCode>> {
1241        &self.user_services
1242    }
1243
1244    async fn get_user_contract(
1245        &self,
1246        description: &ApplicationDescription,
1247        _txn_tracker: &TransactionTracker,
1248    ) -> Result<UserContractCode, ExecutionError> {
1249        let application_id: ApplicationId = description.into();
1250        let pinned = self.user_contracts().pin();
1251        Ok(pinned
1252            .get(&application_id)
1253            .ok_or_else(|| {
1254                ExecutionError::ApplicationBytecodeNotFound(Box::new(description.clone()))
1255            })?
1256            .clone())
1257    }
1258
1259    async fn get_user_service(
1260        &self,
1261        description: &ApplicationDescription,
1262        _txn_tracker: &TransactionTracker,
1263    ) -> Result<UserServiceCode, ExecutionError> {
1264        let application_id: ApplicationId = description.into();
1265        let pinned = self.user_services().pin();
1266        Ok(pinned
1267            .get(&application_id)
1268            .ok_or_else(|| {
1269                ExecutionError::ApplicationBytecodeNotFound(Box::new(description.clone()))
1270            })?
1271            .clone())
1272    }
1273
1274    async fn get_blob(&self, blob_id: BlobId) -> Result<Option<Blob>, ViewError> {
1275        Ok(self.blobs.pin().get(&blob_id).cloned())
1276    }
1277
1278    async fn get_event(&self, event_id: EventId) -> Result<Option<Vec<u8>>, ViewError> {
1279        Ok(self.events.pin().get(&event_id).cloned())
1280    }
1281
1282    async fn get_network_description(&self) -> Result<Option<NetworkDescription>, ViewError> {
1283        let pinned = self.blobs.pin();
1284        let genesis_committee_blob_hash = pinned
1285            .iter()
1286            .find(|(_, blob)| blob.content().blob_type() == BlobType::Committee)
1287            .map_or_else(
1288                || CryptoHash::test_hash("genesis committee"),
1289                |(_, blob)| blob.id().hash,
1290            );
1291        Ok(Some(NetworkDescription {
1292            admin_chain_id: dummy_chain_description(0).id(),
1293            genesis_config_hash: CryptoHash::test_hash("genesis config"),
1294            genesis_timestamp: Timestamp::from(0),
1295            genesis_committee_blob_hash,
1296            name: "dummy network description".to_string(),
1297        }))
1298    }
1299
1300    async fn contains_blob(&self, blob_id: BlobId) -> Result<bool, ViewError> {
1301        Ok(self.blobs.pin().contains_key(&blob_id))
1302    }
1303
1304    async fn contains_event(&self, event_id: EventId) -> Result<bool, ViewError> {
1305        Ok(self.events.pin().contains_key(&event_id))
1306    }
1307
1308    #[cfg(with_testing)]
1309    async fn add_blobs(
1310        &self,
1311        blobs: impl IntoIterator<Item = Blob> + Send,
1312    ) -> Result<(), ViewError> {
1313        let pinned = self.blobs.pin();
1314        for blob in blobs {
1315            pinned.insert(blob.id(), blob);
1316        }
1317
1318        Ok(())
1319    }
1320
1321    #[cfg(with_testing)]
1322    async fn add_events(
1323        &self,
1324        events: impl IntoIterator<Item = (EventId, Vec<u8>)> + Send,
1325    ) -> Result<(), ViewError> {
1326        let pinned = self.events.pin();
1327        for (event_id, bytes) in events {
1328            pinned.insert(event_id, bytes);
1329        }
1330
1331        Ok(())
1332    }
1333}
1334
1335impl From<SystemOperation> for Operation {
1336    fn from(operation: SystemOperation) -> Self {
1337        Operation::System(Box::new(operation))
1338    }
1339}
1340
1341impl Operation {
1342    pub fn system(operation: SystemOperation) -> Self {
1343        Operation::System(Box::new(operation))
1344    }
1345
1346    /// Creates a new user application operation following the `application_id`'s [`Abi`].
1347    #[cfg(with_testing)]
1348    pub fn user<A: Abi>(
1349        application_id: ApplicationId<A>,
1350        operation: &A::Operation,
1351    ) -> Result<Self, bcs::Error> {
1352        Self::user_without_abi(application_id.forget_abi(), operation)
1353    }
1354
1355    /// Creates a new user application operation assuming that the `operation` is valid for the
1356    /// `application_id`.
1357    #[cfg(with_testing)]
1358    pub fn user_without_abi(
1359        application_id: ApplicationId,
1360        operation: &impl Serialize,
1361    ) -> Result<Self, bcs::Error> {
1362        Ok(Operation::User {
1363            application_id,
1364            bytes: bcs::to_bytes(&operation)?,
1365        })
1366    }
1367
1368    /// Returns a reference to the [`SystemOperation`] in this [`Operation`], if this [`Operation`]
1369    /// is for the system application.
1370    pub fn as_system_operation(&self) -> Option<&SystemOperation> {
1371        match self {
1372            Operation::System(system_operation) => Some(system_operation),
1373            Operation::User { .. } => None,
1374        }
1375    }
1376
1377    pub fn application_id(&self) -> GenericApplicationId {
1378        match self {
1379            Self::System(_) => GenericApplicationId::System,
1380            Self::User { application_id, .. } => GenericApplicationId::User(*application_id),
1381        }
1382    }
1383
1384    /// Returns the IDs of all blobs published in this operation.
1385    pub fn published_blob_ids(&self) -> Vec<BlobId> {
1386        match self.as_system_operation() {
1387            Some(SystemOperation::PublishDataBlob { blob_hash }) => {
1388                vec![BlobId::new(*blob_hash, BlobType::Data)]
1389            }
1390            Some(SystemOperation::Admin(AdminOperation::PublishCommitteeBlob { blob_hash })) => {
1391                vec![BlobId::new(*blob_hash, BlobType::Committee)]
1392            }
1393            Some(SystemOperation::PublishModule { module_id }) => module_id.bytecode_blob_ids(),
1394            _ => vec![],
1395        }
1396    }
1397
1398    /// Returns whether this operation is allowed regardless of application permissions.
1399    pub fn is_exempt_from_permissions(&self) -> bool {
1400        let Operation::System(system_op) = self else {
1401            return false;
1402        };
1403        matches!(
1404            **system_op,
1405            SystemOperation::ProcessNewEpoch(_)
1406                | SystemOperation::ProcessRemovedEpoch(_)
1407                | SystemOperation::UpdateStreams(_)
1408        )
1409    }
1410}
1411
1412impl From<SystemMessage> for Message {
1413    fn from(message: SystemMessage) -> Self {
1414        Message::System(message)
1415    }
1416}
1417
1418impl Message {
1419    pub fn system(message: SystemMessage) -> Self {
1420        Message::System(message)
1421    }
1422
1423    /// Creates a new user application message assuming that the `message` is valid for the
1424    /// `application_id`.
1425    pub fn user<A, M: Serialize>(
1426        application_id: ApplicationId<A>,
1427        message: &M,
1428    ) -> Result<Self, bcs::Error> {
1429        let application_id = application_id.forget_abi();
1430        let bytes = bcs::to_bytes(&message)?;
1431        Ok(Message::User {
1432            application_id,
1433            bytes,
1434        })
1435    }
1436
1437    pub fn application_id(&self) -> GenericApplicationId {
1438        match self {
1439            Self::System(_) => GenericApplicationId::System,
1440            Self::User { application_id, .. } => GenericApplicationId::User(*application_id),
1441        }
1442    }
1443}
1444
1445impl From<SystemQuery> for Query {
1446    fn from(query: SystemQuery) -> Self {
1447        Query::System(query)
1448    }
1449}
1450
1451impl Query {
1452    pub fn system(query: SystemQuery) -> Self {
1453        Query::System(query)
1454    }
1455
1456    /// Creates a new user application query following the `application_id`'s [`Abi`].
1457    pub fn user<A: Abi>(
1458        application_id: ApplicationId<A>,
1459        query: &A::Query,
1460    ) -> Result<Self, serde_json::Error> {
1461        Self::user_without_abi(application_id.forget_abi(), query)
1462    }
1463
1464    /// Creates a new user application query assuming that the `query` is valid for the
1465    /// `application_id`.
1466    pub fn user_without_abi(
1467        application_id: ApplicationId,
1468        query: &impl Serialize,
1469    ) -> Result<Self, serde_json::Error> {
1470        Ok(Query::User {
1471            application_id,
1472            bytes: serde_json::to_vec(&query)?,
1473        })
1474    }
1475
1476    pub fn application_id(&self) -> GenericApplicationId {
1477        match self {
1478            Self::System(_) => GenericApplicationId::System,
1479            Self::User { application_id, .. } => GenericApplicationId::User(*application_id),
1480        }
1481    }
1482}
1483
1484impl From<SystemResponse> for QueryResponse {
1485    fn from(response: SystemResponse) -> Self {
1486        QueryResponse::System(response)
1487    }
1488}
1489
1490impl From<Vec<u8>> for QueryResponse {
1491    fn from(response: Vec<u8>) -> Self {
1492        QueryResponse::User(response)
1493    }
1494}
1495
1496/// The state of a blob of binary data.
1497#[derive(Eq, PartialEq, Debug, Hash, Clone, Serialize, Deserialize)]
1498pub struct BlobState {
1499    /// Hash of the last `Certificate` that published or used this blob. If empty, the
1500    /// blob is known to be published by a confirmed certificate but we may not have fully
1501    /// processed this certificate just yet.
1502    pub last_used_by: Option<CryptoHash>,
1503    /// The `ChainId` of the chain that published the change
1504    pub chain_id: ChainId,
1505    /// The `BlockHeight` of the chain that published the change
1506    pub block_height: BlockHeight,
1507    /// Epoch of the `last_used_by` certificate (if any).
1508    pub epoch: Option<Epoch>,
1509}
1510
1511/// The runtime to use for running the application.
1512#[derive(Clone, Copy, Display)]
1513#[cfg_attr(with_wasm_runtime, derive(Debug, Default))]
1514pub enum WasmRuntime {
1515    #[cfg(with_wasmer)]
1516    #[default]
1517    #[display("wasmer")]
1518    Wasmer,
1519    #[cfg(with_wasmtime)]
1520    #[cfg_attr(not(with_wasmer), default)]
1521    #[display("wasmtime")]
1522    Wasmtime,
1523}
1524
1525#[derive(Clone, Copy, Display)]
1526#[cfg_attr(with_revm, derive(Debug, Default))]
1527pub enum EvmRuntime {
1528    #[cfg(with_revm)]
1529    #[default]
1530    #[display("revm")]
1531    Revm,
1532}
1533
1534/// Trait used to select a default `WasmRuntime`, if one is available.
1535pub trait WithWasmDefault {
1536    fn with_wasm_default(self) -> Self;
1537}
1538
1539impl WithWasmDefault for Option<WasmRuntime> {
1540    fn with_wasm_default(self) -> Self {
1541        #[cfg(with_wasm_runtime)]
1542        {
1543            Some(self.unwrap_or_default())
1544        }
1545        #[cfg(not(with_wasm_runtime))]
1546        {
1547            None
1548        }
1549    }
1550}
1551
1552impl FromStr for WasmRuntime {
1553    type Err = InvalidWasmRuntime;
1554
1555    fn from_str(string: &str) -> Result<Self, Self::Err> {
1556        match string {
1557            #[cfg(with_wasmer)]
1558            "wasmer" => Ok(WasmRuntime::Wasmer),
1559            #[cfg(with_wasmtime)]
1560            "wasmtime" => Ok(WasmRuntime::Wasmtime),
1561            unknown => Err(InvalidWasmRuntime(unknown.to_owned())),
1562        }
1563    }
1564}
1565
1566/// Attempts to create an invalid [`WasmRuntime`] instance from a string.
1567#[derive(Clone, Debug, Error)]
1568#[error("{0:?} is not a valid WebAssembly runtime")]
1569pub struct InvalidWasmRuntime(String);
1570
1571doc_scalar!(Operation, "An operation to be executed in a block");
1572doc_scalar!(
1573    Message,
1574    "A message to be sent and possibly executed in the receiver's block."
1575);
1576doc_scalar!(MessageKind, "The kind of outgoing message being sent");