Skip to main content

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