1pub 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::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
83pub const LINERA_SOL: &str = include_str!("../solidity/Linera.sol");
86pub const LINERA_TYPES_SOL: &str = include_str!("../solidity/LineraTypes.sol");
87
88const MAX_STREAM_NAME_LEN: usize = 64;
90
91pub const FLAG_ZERO_HASH: &str = "FLAG_ZERO_HASH.linera.network";
96pub const FLAG_FREE_REJECT: &str = "FLAG_FREE_REJECT.linera.network";
100pub const FLAG_MANDATORY_APPS_NEED_ACCEPTED_MESSAGE: &str =
104 "FLAG_MANDATORY_APPS_NEED_ACCEPTED_MESSAGE.linera.network";
105pub const FLAG_FREE_APPLICATION_ID_PREFIX: &str = "FLAG_FREE_APPLICATION_ID_";
108pub const FLAG_FREE_APPLICATION_ID_SUFFIX: &str = ".linera.network";
110
111#[derive(Clone)]
113pub struct UserContractCode(Box<dyn UserContractModule>);
114
115#[derive(Clone)]
117pub struct UserServiceCode(Box<dyn UserServiceModule>);
118
119pub type UserContractInstance = Box<dyn UserContract>;
121
122pub type UserServiceInstance = Box<dyn UserService>;
124
125pub 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
141pub 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 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#[derive(Error, Debug)]
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 #[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 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 pub fn is_limit_error(&self) -> bool {
455 matches!(
456 self,
457 ExecutionError::ExcessiveRead
458 | ExecutionError::ExcessiveWrite
459 | ExecutionError::MaximumFuelExceeded(_)
460 | ExecutionError::MaximumServiceOracleExecutionTimeExceeded
461 | ExecutionError::BlockTooLarge
462 )
463 }
464
465 pub fn is_transient_error(&self) -> bool {
471 matches!(
472 self,
473 ExecutionError::BlobsNotFound(_) | ExecutionError::EventsNotFound(_)
474 )
475 }
476}
477
478pub trait UserContract {
480 fn instantiate(&mut self, argument: Vec<u8>) -> Result<(), ExecutionError>;
482
483 fn execute_operation(&mut self, operation: Vec<u8>) -> Result<Vec<u8>, ExecutionError>;
485
486 fn execute_message(&mut self, message: Vec<u8>) -> Result<(), ExecutionError>;
488
489 fn process_streams(&mut self, updates: Vec<StreamUpdate>) -> Result<(), ExecutionError>;
491
492 fn finalize(&mut self) -> Result<(), ExecutionError>;
494}
495
496pub trait UserService {
498 fn handle_query(&mut self, argument: Vec<u8>) -> Result<Vec<u8>, ExecutionError>;
500}
501
502#[derive(Clone, Copy)]
504pub struct ExecutionRuntimeConfig {
505 pub allow_application_logs: bool,
508}
509
510impl Default for ExecutionRuntimeConfig {
511 fn default() -> Self {
512 Self {
513 allow_application_logs: true,
514 }
515 }
516}
517
518#[cfg_attr(not(web), async_trait)]
521#[cfg_attr(web, async_trait(?Send))]
522pub trait ExecutionRuntimeContext {
523 fn chain_id(&self) -> ChainId;
524
525 fn thread_pool(&self) -> &Arc<ThreadPool>;
526
527 fn execution_runtime_config(&self) -> ExecutionRuntimeConfig;
528
529 fn user_contracts(&self) -> &Arc<papaya::HashMap<ApplicationId, UserContractCode>>;
530
531 fn user_services(&self) -> &Arc<papaya::HashMap<ApplicationId, UserServiceCode>>;
532
533 async fn get_user_contract(
534 &self,
535 description: &ApplicationDescription,
536 txn_tracker: &TransactionTracker,
537 ) -> Result<UserContractCode, ExecutionError>;
538
539 async fn get_user_service(
540 &self,
541 description: &ApplicationDescription,
542 txn_tracker: &TransactionTracker,
543 ) -> Result<UserServiceCode, ExecutionError>;
544
545 async fn get_blob(&self, blob_id: BlobId) -> Result<Option<Blob>, ViewError>;
546
547 async fn get_event(&self, event_id: EventId) -> Result<Option<Vec<u8>>, ViewError>;
548
549 async fn get_network_description(&self) -> Result<Option<NetworkDescription>, ViewError>;
550
551 async fn get_committees(
553 &self,
554 epoch_range: RangeInclusive<Epoch>,
555 ) -> Result<BTreeMap<Epoch, Committee>, ExecutionError> {
556 let net_description = self
557 .get_network_description()
558 .await?
559 .ok_or(ExecutionError::NoNetworkDescriptionFound)?;
560 let committee_hashes = futures::future::join_all(
561 (epoch_range.start().0..=epoch_range.end().0).map(|epoch| async move {
562 if epoch == 0 {
563 Ok((epoch, net_description.genesis_committee_blob_hash))
565 } else {
566 let event_id = EventId {
567 chain_id: net_description.admin_chain_id,
568 stream_id: StreamId::system(EPOCH_STREAM_NAME),
569 index: epoch,
570 };
571 let event = self
572 .get_event(event_id.clone())
573 .await?
574 .ok_or_else(|| ExecutionError::EventsNotFound(vec![event_id]))?;
575 Ok((epoch, bcs::from_bytes(&event)?))
576 }
577 }),
578 )
579 .await;
580 let missing_events = committee_hashes
581 .iter()
582 .filter_map(|result| {
583 if let Err(ExecutionError::EventsNotFound(event_ids)) = result {
584 return Some(event_ids);
585 }
586 None
587 })
588 .flatten()
589 .cloned()
590 .collect::<Vec<_>>();
591 ensure!(
592 missing_events.is_empty(),
593 ExecutionError::EventsNotFound(missing_events)
594 );
595 let committee_hashes = committee_hashes
596 .into_iter()
597 .collect::<Result<Vec<_>, _>>()?;
598 let committees = futures::future::join_all(committee_hashes.into_iter().map(
599 |(epoch, committee_hash)| async move {
600 let blob_id = BlobId::new(committee_hash, BlobType::Committee);
601 let committee_blob = self
602 .get_blob(blob_id)
603 .await?
604 .ok_or_else(|| ExecutionError::BlobsNotFound(vec![blob_id]))?;
605 Ok((Epoch(epoch), bcs::from_bytes(committee_blob.bytes())?))
606 },
607 ))
608 .await;
609 let missing_blobs = committees
610 .iter()
611 .filter_map(|result| {
612 if let Err(ExecutionError::BlobsNotFound(blob_ids)) = result {
613 return Some(blob_ids);
614 }
615 None
616 })
617 .flatten()
618 .cloned()
619 .collect::<Vec<_>>();
620 ensure!(
621 missing_blobs.is_empty(),
622 ExecutionError::BlobsNotFound(missing_blobs)
623 );
624 committees.into_iter().collect()
625 }
626
627 async fn contains_blob(&self, blob_id: BlobId) -> Result<bool, ViewError>;
628
629 async fn contains_event(&self, event_id: EventId) -> Result<bool, ViewError>;
630
631 #[cfg(with_testing)]
632 async fn add_blobs(
633 &self,
634 blobs: impl IntoIterator<Item = Blob> + Send,
635 ) -> Result<(), ViewError>;
636
637 #[cfg(with_testing)]
638 async fn add_events(
639 &self,
640 events: impl IntoIterator<Item = (EventId, Vec<u8>)> + Send,
641 ) -> Result<(), ViewError>;
642}
643
644#[derive(Clone, Copy, Debug)]
645pub struct OperationContext {
646 pub chain_id: ChainId,
648 #[debug(skip_if = Option::is_none)]
650 pub authenticated_signer: Option<AccountOwner>,
651 pub height: BlockHeight,
653 pub round: Option<u32>,
655 pub timestamp: Timestamp,
657}
658
659#[derive(Clone, Copy, Debug)]
660pub struct MessageContext {
661 pub chain_id: ChainId,
663 pub origin: ChainId,
665 pub is_bouncing: bool,
667 #[debug(skip_if = Option::is_none)]
669 pub authenticated_signer: Option<AccountOwner>,
670 #[debug(skip_if = Option::is_none)]
672 pub refund_grant_to: Option<Account>,
673 pub height: BlockHeight,
675 pub round: Option<u32>,
677 pub timestamp: Timestamp,
679}
680
681#[derive(Clone, Copy, Debug)]
682pub struct ProcessStreamsContext {
683 pub chain_id: ChainId,
685 pub height: BlockHeight,
687 pub round: Option<u32>,
689 pub timestamp: Timestamp,
691}
692
693impl From<MessageContext> for ProcessStreamsContext {
694 fn from(context: MessageContext) -> Self {
695 Self {
696 chain_id: context.chain_id,
697 height: context.height,
698 round: context.round,
699 timestamp: context.timestamp,
700 }
701 }
702}
703
704impl From<OperationContext> for ProcessStreamsContext {
705 fn from(context: OperationContext) -> Self {
706 Self {
707 chain_id: context.chain_id,
708 height: context.height,
709 round: context.round,
710 timestamp: context.timestamp,
711 }
712 }
713}
714
715#[derive(Clone, Copy, Debug)]
716pub struct FinalizeContext {
717 pub chain_id: ChainId,
719 #[debug(skip_if = Option::is_none)]
721 pub authenticated_signer: Option<AccountOwner>,
722 pub height: BlockHeight,
724 pub round: Option<u32>,
726}
727
728#[derive(Clone, Copy, Debug, Eq, PartialEq)]
729pub struct QueryContext {
730 pub chain_id: ChainId,
732 pub next_block_height: BlockHeight,
734 pub local_time: Timestamp,
736}
737
738pub trait BaseRuntime {
739 type Read: fmt::Debug + Send + Sync;
740 type ContainsKey: fmt::Debug + Send + Sync;
741 type ContainsKeys: fmt::Debug + Send + Sync;
742 type ReadMultiValuesBytes: fmt::Debug + Send + Sync;
743 type ReadValueBytes: fmt::Debug + Send + Sync;
744 type FindKeysByPrefix: fmt::Debug + Send + Sync;
745 type FindKeyValuesByPrefix: fmt::Debug + Send + Sync;
746
747 fn chain_id(&mut self) -> Result<ChainId, ExecutionError>;
749
750 fn block_height(&mut self) -> Result<BlockHeight, ExecutionError>;
752
753 fn application_id(&mut self) -> Result<ApplicationId, ExecutionError>;
755
756 fn application_creator_chain_id(&mut self) -> Result<ChainId, ExecutionError>;
758
759 fn read_application_description(
761 &mut self,
762 application_id: ApplicationId,
763 ) -> Result<ApplicationDescription, ExecutionError>;
764
765 fn application_parameters(&mut self) -> Result<Vec<u8>, ExecutionError>;
767
768 fn read_system_timestamp(&mut self) -> Result<Timestamp, ExecutionError>;
770
771 fn read_chain_balance(&mut self) -> Result<Amount, ExecutionError>;
773
774 fn read_owner_balance(&mut self, owner: AccountOwner) -> Result<Amount, ExecutionError>;
776
777 fn read_owner_balances(&mut self) -> Result<Vec<(AccountOwner, Amount)>, ExecutionError>;
779
780 fn read_balance_owners(&mut self) -> Result<Vec<AccountOwner>, ExecutionError>;
782
783 fn chain_ownership(&mut self) -> Result<ChainOwnership, ExecutionError>;
785
786 fn application_permissions(&mut self) -> Result<ApplicationPermissions, ExecutionError>;
788
789 #[cfg(feature = "test")]
791 fn contains_key(&mut self, key: Vec<u8>) -> Result<bool, ExecutionError> {
792 let promise = self.contains_key_new(key)?;
793 self.contains_key_wait(&promise)
794 }
795
796 fn contains_key_new(&mut self, key: Vec<u8>) -> Result<Self::ContainsKey, ExecutionError>;
798
799 fn contains_key_wait(&mut self, promise: &Self::ContainsKey) -> Result<bool, ExecutionError>;
801
802 #[cfg(feature = "test")]
804 fn contains_keys(&mut self, keys: Vec<Vec<u8>>) -> Result<Vec<bool>, ExecutionError> {
805 let promise = self.contains_keys_new(keys)?;
806 self.contains_keys_wait(&promise)
807 }
808
809 fn contains_keys_new(
811 &mut self,
812 keys: Vec<Vec<u8>>,
813 ) -> Result<Self::ContainsKeys, ExecutionError>;
814
815 fn contains_keys_wait(
817 &mut self,
818 promise: &Self::ContainsKeys,
819 ) -> Result<Vec<bool>, ExecutionError>;
820
821 #[cfg(feature = "test")]
823 fn read_multi_values_bytes(
824 &mut self,
825 keys: Vec<Vec<u8>>,
826 ) -> Result<Vec<Option<Vec<u8>>>, ExecutionError> {
827 let promise = self.read_multi_values_bytes_new(keys)?;
828 self.read_multi_values_bytes_wait(&promise)
829 }
830
831 fn read_multi_values_bytes_new(
833 &mut self,
834 keys: Vec<Vec<u8>>,
835 ) -> Result<Self::ReadMultiValuesBytes, ExecutionError>;
836
837 fn read_multi_values_bytes_wait(
839 &mut self,
840 promise: &Self::ReadMultiValuesBytes,
841 ) -> Result<Vec<Option<Vec<u8>>>, ExecutionError>;
842
843 #[cfg(feature = "test")]
845 fn read_value_bytes(&mut self, key: Vec<u8>) -> Result<Option<Vec<u8>>, ExecutionError> {
846 let promise = self.read_value_bytes_new(key)?;
847 self.read_value_bytes_wait(&promise)
848 }
849
850 fn read_value_bytes_new(
852 &mut self,
853 key: Vec<u8>,
854 ) -> Result<Self::ReadValueBytes, ExecutionError>;
855
856 fn read_value_bytes_wait(
858 &mut self,
859 promise: &Self::ReadValueBytes,
860 ) -> Result<Option<Vec<u8>>, ExecutionError>;
861
862 fn find_keys_by_prefix_new(
864 &mut self,
865 key_prefix: Vec<u8>,
866 ) -> Result<Self::FindKeysByPrefix, ExecutionError>;
867
868 fn find_keys_by_prefix_wait(
870 &mut self,
871 promise: &Self::FindKeysByPrefix,
872 ) -> Result<Vec<Vec<u8>>, ExecutionError>;
873
874 #[cfg(feature = "test")]
876 #[expect(clippy::type_complexity)]
877 fn find_key_values_by_prefix(
878 &mut self,
879 key_prefix: Vec<u8>,
880 ) -> Result<Vec<(Vec<u8>, Vec<u8>)>, ExecutionError> {
881 let promise = self.find_key_values_by_prefix_new(key_prefix)?;
882 self.find_key_values_by_prefix_wait(&promise)
883 }
884
885 fn find_key_values_by_prefix_new(
887 &mut self,
888 key_prefix: Vec<u8>,
889 ) -> Result<Self::FindKeyValuesByPrefix, ExecutionError>;
890
891 #[expect(clippy::type_complexity)]
893 fn find_key_values_by_prefix_wait(
894 &mut self,
895 promise: &Self::FindKeyValuesByPrefix,
896 ) -> Result<Vec<(Vec<u8>, Vec<u8>)>, ExecutionError>;
897
898 fn perform_http_request(
900 &mut self,
901 request: http::Request,
902 ) -> Result<http::Response, ExecutionError>;
903
904 fn assert_before(&mut self, timestamp: Timestamp) -> Result<(), ExecutionError>;
910
911 fn read_data_blob(&mut self, hash: DataBlobHash) -> Result<Vec<u8>, ExecutionError>;
913
914 fn assert_data_blob_exists(&mut self, hash: DataBlobHash) -> Result<(), ExecutionError>;
916
917 fn allow_application_logs(&mut self) -> Result<bool, ExecutionError>;
920
921 #[cfg(web)]
924 fn send_log(&mut self, message: String, level: tracing::log::Level);
925}
926
927pub trait ServiceRuntime: BaseRuntime {
928 fn try_query_application(
930 &mut self,
931 queried_id: ApplicationId,
932 argument: Vec<u8>,
933 ) -> Result<Vec<u8>, ExecutionError>;
934
935 fn schedule_operation(&mut self, operation: Vec<u8>) -> Result<(), ExecutionError>;
937
938 fn check_execution_time(&mut self) -> Result<(), ExecutionError>;
940}
941
942pub trait ContractRuntime: BaseRuntime {
943 fn authenticated_signer(&mut self) -> Result<Option<AccountOwner>, ExecutionError>;
945
946 fn message_is_bouncing(&mut self) -> Result<Option<bool>, ExecutionError>;
949
950 fn message_origin_chain_id(&mut self) -> Result<Option<ChainId>, ExecutionError>;
952
953 fn authenticated_caller_id(&mut self) -> Result<Option<ApplicationId>, ExecutionError>;
956
957 fn maximum_fuel_per_block(&mut self, vm_runtime: VmRuntime) -> Result<u64, ExecutionError>;
959
960 fn remaining_fuel(&mut self, vm_runtime: VmRuntime) -> Result<u64, ExecutionError>;
962
963 fn consume_fuel(&mut self, fuel: u64, vm_runtime: VmRuntime) -> Result<(), ExecutionError>;
965
966 fn send_message(&mut self, message: SendMessageRequest<Vec<u8>>) -> Result<(), ExecutionError>;
968
969 fn transfer(
971 &mut self,
972 source: AccountOwner,
973 destination: Account,
974 amount: Amount,
975 ) -> Result<(), ExecutionError>;
976
977 fn claim(
979 &mut self,
980 source: Account,
981 destination: Account,
982 amount: Amount,
983 ) -> Result<(), ExecutionError>;
984
985 fn try_call_application(
988 &mut self,
989 authenticated: bool,
990 callee_id: ApplicationId,
991 argument: Vec<u8>,
992 ) -> Result<Vec<u8>, ExecutionError>;
993
994 fn emit(&mut self, name: StreamName, value: Vec<u8>) -> Result<u32, ExecutionError>;
996
997 fn read_event(
1001 &mut self,
1002 chain_id: ChainId,
1003 stream_name: StreamName,
1004 index: u32,
1005 ) -> Result<Vec<u8>, ExecutionError>;
1006
1007 fn subscribe_to_events(
1009 &mut self,
1010 chain_id: ChainId,
1011 application_id: ApplicationId,
1012 stream_name: StreamName,
1013 ) -> Result<(), ExecutionError>;
1014
1015 fn unsubscribe_from_events(
1017 &mut self,
1018 chain_id: ChainId,
1019 application_id: ApplicationId,
1020 stream_name: StreamName,
1021 ) -> Result<(), ExecutionError>;
1022
1023 fn query_service(
1025 &mut self,
1026 application_id: ApplicationId,
1027 query: Vec<u8>,
1028 ) -> Result<Vec<u8>, ExecutionError>;
1029
1030 fn open_chain(
1032 &mut self,
1033 ownership: ChainOwnership,
1034 application_permissions: ApplicationPermissions,
1035 balance: Amount,
1036 ) -> Result<ChainId, ExecutionError>;
1037
1038 fn close_chain(&mut self) -> Result<(), ExecutionError>;
1040
1041 fn change_ownership(&mut self, ownership: ChainOwnership) -> Result<(), ExecutionError>;
1043
1044 fn change_application_permissions(
1046 &mut self,
1047 application_permissions: ApplicationPermissions,
1048 ) -> Result<(), ExecutionError>;
1049
1050 fn create_application(
1052 &mut self,
1053 module_id: ModuleId,
1054 parameters: Vec<u8>,
1055 argument: Vec<u8>,
1056 required_application_ids: Vec<ApplicationId>,
1057 ) -> Result<ApplicationId, ExecutionError>;
1058
1059 fn create_data_blob(&mut self, bytes: Vec<u8>) -> Result<DataBlobHash, ExecutionError>;
1061
1062 fn publish_module(
1064 &mut self,
1065 contract: Bytecode,
1066 service: Bytecode,
1067 vm_runtime: VmRuntime,
1068 ) -> Result<ModuleId, ExecutionError>;
1069
1070 fn validation_round(&mut self) -> Result<Option<u32>, ExecutionError>;
1072
1073 fn write_batch(&mut self, batch: Batch) -> Result<(), ExecutionError>;
1075}
1076
1077#[derive(
1079 Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, Allocative, strum::AsRefStr,
1080)]
1081pub enum Operation {
1082 System(Box<SystemOperation>),
1084 User {
1086 application_id: ApplicationId,
1087 #[serde(with = "serde_bytes")]
1088 #[debug(with = "hex_debug")]
1089 bytes: Vec<u8>,
1090 },
1091}
1092
1093impl BcsHashable<'_> for Operation {}
1094
1095#[derive(
1097 Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, Allocative, strum::AsRefStr,
1098)]
1099pub enum Message {
1100 System(SystemMessage),
1102 User {
1104 application_id: ApplicationId,
1105 #[serde(with = "serde_bytes")]
1106 #[debug(with = "hex_debug")]
1107 bytes: Vec<u8>,
1108 },
1109}
1110
1111#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1113pub enum Query {
1114 System(SystemQuery),
1116 User {
1118 application_id: ApplicationId,
1119 #[serde(with = "serde_bytes")]
1120 #[debug(with = "hex_debug")]
1121 bytes: Vec<u8>,
1122 },
1123}
1124
1125#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1127pub struct QueryOutcome<Response = QueryResponse> {
1128 pub response: Response,
1129 pub operations: Vec<Operation>,
1130}
1131
1132impl From<QueryOutcome<SystemResponse>> for QueryOutcome {
1133 fn from(system_outcome: QueryOutcome<SystemResponse>) -> Self {
1134 let QueryOutcome {
1135 response,
1136 operations,
1137 } = system_outcome;
1138
1139 QueryOutcome {
1140 response: QueryResponse::System(response),
1141 operations,
1142 }
1143 }
1144}
1145
1146impl From<QueryOutcome<Vec<u8>>> for QueryOutcome {
1147 fn from(user_service_outcome: QueryOutcome<Vec<u8>>) -> Self {
1148 let QueryOutcome {
1149 response,
1150 operations,
1151 } = user_service_outcome;
1152
1153 QueryOutcome {
1154 response: QueryResponse::User(response),
1155 operations,
1156 }
1157 }
1158}
1159
1160#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1162pub enum QueryResponse {
1163 System(SystemResponse),
1165 User(
1167 #[serde(with = "serde_bytes")]
1168 #[debug(with = "hex_debug")]
1169 Vec<u8>,
1170 ),
1171}
1172
1173#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, Copy, Allocative)]
1175pub enum MessageKind {
1176 Simple,
1178 Protected,
1181 Tracked,
1184 Bouncing,
1186}
1187
1188impl Display for MessageKind {
1189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1190 match self {
1191 MessageKind::Simple => write!(f, "Simple"),
1192 MessageKind::Protected => write!(f, "Protected"),
1193 MessageKind::Tracked => write!(f, "Tracked"),
1194 MessageKind::Bouncing => write!(f, "Bouncing"),
1195 }
1196 }
1197}
1198
1199#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, SimpleObject, Allocative)]
1201pub struct OutgoingMessage {
1202 pub destination: ChainId,
1204 #[debug(skip_if = Option::is_none)]
1206 pub authenticated_signer: Option<AccountOwner>,
1207 #[debug(skip_if = Amount::is_zero)]
1209 pub grant: Amount,
1210 #[debug(skip_if = Option::is_none)]
1212 pub refund_grant_to: Option<Account>,
1213 pub kind: MessageKind,
1215 pub message: Message,
1217}
1218
1219impl BcsHashable<'_> for OutgoingMessage {}
1220
1221impl OutgoingMessage {
1222 pub fn new(recipient: ChainId, message: impl Into<Message>) -> Self {
1224 OutgoingMessage {
1225 destination: recipient,
1226 authenticated_signer: None,
1227 grant: Amount::ZERO,
1228 refund_grant_to: None,
1229 kind: MessageKind::Simple,
1230 message: message.into(),
1231 }
1232 }
1233
1234 pub fn with_kind(mut self, kind: MessageKind) -> Self {
1236 self.kind = kind;
1237 self
1238 }
1239
1240 pub fn with_authenticated_signer(mut self, authenticated_signer: Option<AccountOwner>) -> Self {
1242 self.authenticated_signer = authenticated_signer;
1243 self
1244 }
1245}
1246
1247impl OperationContext {
1248 fn refund_grant_to(&self) -> Option<Account> {
1251 self.authenticated_signer.map(|owner| Account {
1252 chain_id: self.chain_id,
1253 owner,
1254 })
1255 }
1256}
1257
1258#[cfg(with_testing)]
1259#[derive(Clone)]
1260pub struct TestExecutionRuntimeContext {
1261 chain_id: ChainId,
1262 thread_pool: Arc<ThreadPool>,
1263 execution_runtime_config: ExecutionRuntimeConfig,
1264 user_contracts: Arc<papaya::HashMap<ApplicationId, UserContractCode>>,
1265 user_services: Arc<papaya::HashMap<ApplicationId, UserServiceCode>>,
1266 blobs: Arc<papaya::HashMap<BlobId, Blob>>,
1267 events: Arc<papaya::HashMap<EventId, Vec<u8>>>,
1268}
1269
1270#[cfg(with_testing)]
1271impl TestExecutionRuntimeContext {
1272 pub fn new(chain_id: ChainId, execution_runtime_config: ExecutionRuntimeConfig) -> Self {
1273 Self {
1274 chain_id,
1275 thread_pool: Arc::new(ThreadPool::new(20)),
1276 execution_runtime_config,
1277 user_contracts: Arc::default(),
1278 user_services: Arc::default(),
1279 blobs: Arc::default(),
1280 events: Arc::default(),
1281 }
1282 }
1283}
1284
1285#[cfg(with_testing)]
1286#[cfg_attr(not(web), async_trait)]
1287#[cfg_attr(web, async_trait(?Send))]
1288impl ExecutionRuntimeContext for TestExecutionRuntimeContext {
1289 fn chain_id(&self) -> ChainId {
1290 self.chain_id
1291 }
1292
1293 fn thread_pool(&self) -> &Arc<ThreadPool> {
1294 &self.thread_pool
1295 }
1296
1297 fn execution_runtime_config(&self) -> ExecutionRuntimeConfig {
1298 self.execution_runtime_config
1299 }
1300
1301 fn user_contracts(&self) -> &Arc<papaya::HashMap<ApplicationId, UserContractCode>> {
1302 &self.user_contracts
1303 }
1304
1305 fn user_services(&self) -> &Arc<papaya::HashMap<ApplicationId, UserServiceCode>> {
1306 &self.user_services
1307 }
1308
1309 async fn get_user_contract(
1310 &self,
1311 description: &ApplicationDescription,
1312 _txn_tracker: &TransactionTracker,
1313 ) -> Result<UserContractCode, ExecutionError> {
1314 let application_id: ApplicationId = description.into();
1315 let pinned = self.user_contracts().pin();
1316 Ok(pinned
1317 .get(&application_id)
1318 .ok_or_else(|| {
1319 ExecutionError::ApplicationBytecodeNotFound(Box::new(description.clone()))
1320 })?
1321 .clone())
1322 }
1323
1324 async fn get_user_service(
1325 &self,
1326 description: &ApplicationDescription,
1327 _txn_tracker: &TransactionTracker,
1328 ) -> Result<UserServiceCode, ExecutionError> {
1329 let application_id: ApplicationId = description.into();
1330 let pinned = self.user_services().pin();
1331 Ok(pinned
1332 .get(&application_id)
1333 .ok_or_else(|| {
1334 ExecutionError::ApplicationBytecodeNotFound(Box::new(description.clone()))
1335 })?
1336 .clone())
1337 }
1338
1339 async fn get_blob(&self, blob_id: BlobId) -> Result<Option<Blob>, ViewError> {
1340 Ok(self.blobs.pin().get(&blob_id).cloned())
1341 }
1342
1343 async fn get_event(&self, event_id: EventId) -> Result<Option<Vec<u8>>, ViewError> {
1344 Ok(self.events.pin().get(&event_id).cloned())
1345 }
1346
1347 async fn get_network_description(&self) -> Result<Option<NetworkDescription>, ViewError> {
1348 let pinned = self.blobs.pin();
1349 let genesis_committee_blob_hash = pinned
1350 .iter()
1351 .find(|(_, blob)| blob.content().blob_type() == BlobType::Committee)
1352 .map_or_else(
1353 || CryptoHash::test_hash("genesis committee"),
1354 |(_, blob)| blob.id().hash,
1355 );
1356 Ok(Some(NetworkDescription {
1357 admin_chain_id: dummy_chain_description(0).id(),
1358 genesis_config_hash: CryptoHash::test_hash("genesis config"),
1359 genesis_timestamp: Timestamp::from(0),
1360 genesis_committee_blob_hash,
1361 name: "dummy network description".to_string(),
1362 }))
1363 }
1364
1365 async fn contains_blob(&self, blob_id: BlobId) -> Result<bool, ViewError> {
1366 Ok(self.blobs.pin().contains_key(&blob_id))
1367 }
1368
1369 async fn contains_event(&self, event_id: EventId) -> Result<bool, ViewError> {
1370 Ok(self.events.pin().contains_key(&event_id))
1371 }
1372
1373 #[cfg(with_testing)]
1374 async fn add_blobs(
1375 &self,
1376 blobs: impl IntoIterator<Item = Blob> + Send,
1377 ) -> Result<(), ViewError> {
1378 let pinned = self.blobs.pin();
1379 for blob in blobs {
1380 pinned.insert(blob.id(), blob);
1381 }
1382
1383 Ok(())
1384 }
1385
1386 #[cfg(with_testing)]
1387 async fn add_events(
1388 &self,
1389 events: impl IntoIterator<Item = (EventId, Vec<u8>)> + Send,
1390 ) -> Result<(), ViewError> {
1391 let pinned = self.events.pin();
1392 for (event_id, bytes) in events {
1393 pinned.insert(event_id, bytes);
1394 }
1395
1396 Ok(())
1397 }
1398}
1399
1400impl From<SystemOperation> for Operation {
1401 fn from(operation: SystemOperation) -> Self {
1402 Operation::System(Box::new(operation))
1403 }
1404}
1405
1406impl Operation {
1407 pub fn system(operation: SystemOperation) -> Self {
1408 Operation::System(Box::new(operation))
1409 }
1410
1411 #[cfg(with_testing)]
1413 pub fn user<A: Abi>(
1414 application_id: ApplicationId<A>,
1415 operation: &A::Operation,
1416 ) -> Result<Self, bcs::Error> {
1417 Self::user_without_abi(application_id.forget_abi(), operation)
1418 }
1419
1420 #[cfg(with_testing)]
1423 pub fn user_without_abi(
1424 application_id: ApplicationId,
1425 operation: &impl Serialize,
1426 ) -> Result<Self, bcs::Error> {
1427 Ok(Operation::User {
1428 application_id,
1429 bytes: bcs::to_bytes(&operation)?,
1430 })
1431 }
1432
1433 pub fn as_system_operation(&self) -> Option<&SystemOperation> {
1436 match self {
1437 Operation::System(system_operation) => Some(system_operation),
1438 Operation::User { .. } => None,
1439 }
1440 }
1441
1442 pub fn application_id(&self) -> GenericApplicationId {
1443 match self {
1444 Self::System(_) => GenericApplicationId::System,
1445 Self::User { application_id, .. } => GenericApplicationId::User(*application_id),
1446 }
1447 }
1448
1449 pub fn published_blob_ids(&self) -> Vec<BlobId> {
1451 match self.as_system_operation() {
1452 Some(SystemOperation::PublishDataBlob { blob_hash }) => {
1453 vec![BlobId::new(*blob_hash, BlobType::Data)]
1454 }
1455 Some(SystemOperation::Admin(AdminOperation::PublishCommitteeBlob { blob_hash })) => {
1456 vec![BlobId::new(*blob_hash, BlobType::Committee)]
1457 }
1458 Some(SystemOperation::PublishModule { module_id }) => module_id.bytecode_blob_ids(),
1459 _ => vec![],
1460 }
1461 }
1462
1463 pub fn is_exempt_from_permissions(&self) -> bool {
1465 let Operation::System(system_op) = self else {
1466 return false;
1467 };
1468 matches!(
1469 **system_op,
1470 SystemOperation::ProcessNewEpoch(_)
1471 | SystemOperation::ProcessRemovedEpoch(_)
1472 | SystemOperation::UpdateStreams(_)
1473 )
1474 }
1475}
1476
1477impl From<SystemMessage> for Message {
1478 fn from(message: SystemMessage) -> Self {
1479 Message::System(message)
1480 }
1481}
1482
1483impl Message {
1484 pub fn system(message: SystemMessage) -> Self {
1485 Message::System(message)
1486 }
1487
1488 pub fn user<A, M: Serialize>(
1491 application_id: ApplicationId<A>,
1492 message: &M,
1493 ) -> Result<Self, bcs::Error> {
1494 let application_id = application_id.forget_abi();
1495 let bytes = bcs::to_bytes(&message)?;
1496 Ok(Message::User {
1497 application_id,
1498 bytes,
1499 })
1500 }
1501
1502 pub fn application_id(&self) -> GenericApplicationId {
1503 match self {
1504 Self::System(_) => GenericApplicationId::System,
1505 Self::User { application_id, .. } => GenericApplicationId::User(*application_id),
1506 }
1507 }
1508}
1509
1510impl From<SystemQuery> for Query {
1511 fn from(query: SystemQuery) -> Self {
1512 Query::System(query)
1513 }
1514}
1515
1516impl Query {
1517 pub fn system(query: SystemQuery) -> Self {
1518 Query::System(query)
1519 }
1520
1521 pub fn user<A: Abi>(
1523 application_id: ApplicationId<A>,
1524 query: &A::Query,
1525 ) -> Result<Self, serde_json::Error> {
1526 Self::user_without_abi(application_id.forget_abi(), query)
1527 }
1528
1529 pub fn user_without_abi(
1532 application_id: ApplicationId,
1533 query: &impl Serialize,
1534 ) -> Result<Self, serde_json::Error> {
1535 Ok(Query::User {
1536 application_id,
1537 bytes: serde_json::to_vec(&query)?,
1538 })
1539 }
1540
1541 pub fn application_id(&self) -> GenericApplicationId {
1542 match self {
1543 Self::System(_) => GenericApplicationId::System,
1544 Self::User { application_id, .. } => GenericApplicationId::User(*application_id),
1545 }
1546 }
1547}
1548
1549impl From<SystemResponse> for QueryResponse {
1550 fn from(response: SystemResponse) -> Self {
1551 QueryResponse::System(response)
1552 }
1553}
1554
1555impl From<Vec<u8>> for QueryResponse {
1556 fn from(response: Vec<u8>) -> Self {
1557 QueryResponse::User(response)
1558 }
1559}
1560
1561#[derive(Eq, PartialEq, Debug, Hash, Clone, Serialize, Deserialize)]
1563pub struct BlobState {
1564 pub last_used_by: Option<CryptoHash>,
1568 pub chain_id: ChainId,
1570 pub block_height: BlockHeight,
1572 pub epoch: Option<Epoch>,
1574}
1575
1576#[derive(Clone, Copy, Display)]
1578#[cfg_attr(with_wasm_runtime, derive(Debug, Default))]
1579pub enum WasmRuntime {
1580 #[cfg(with_wasmer)]
1581 #[default]
1582 #[display("wasmer")]
1583 Wasmer,
1584 #[cfg(with_wasmtime)]
1585 #[cfg_attr(not(with_wasmer), default)]
1586 #[display("wasmtime")]
1587 Wasmtime,
1588}
1589
1590#[derive(Clone, Copy, Display)]
1591#[cfg_attr(with_revm, derive(Debug, Default))]
1592pub enum EvmRuntime {
1593 #[cfg(with_revm)]
1594 #[default]
1595 #[display("revm")]
1596 Revm,
1597}
1598
1599pub trait WithWasmDefault {
1601 fn with_wasm_default(self) -> Self;
1602}
1603
1604impl WithWasmDefault for Option<WasmRuntime> {
1605 fn with_wasm_default(self) -> Self {
1606 #[cfg(with_wasm_runtime)]
1607 {
1608 Some(self.unwrap_or_default())
1609 }
1610 #[cfg(not(with_wasm_runtime))]
1611 {
1612 None
1613 }
1614 }
1615}
1616
1617impl FromStr for WasmRuntime {
1618 type Err = InvalidWasmRuntime;
1619
1620 fn from_str(string: &str) -> Result<Self, Self::Err> {
1621 match string {
1622 #[cfg(with_wasmer)]
1623 "wasmer" => Ok(WasmRuntime::Wasmer),
1624 #[cfg(with_wasmtime)]
1625 "wasmtime" => Ok(WasmRuntime::Wasmtime),
1626 unknown => Err(InvalidWasmRuntime(unknown.to_owned())),
1627 }
1628 }
1629}
1630
1631#[derive(Clone, Debug, Error)]
1633#[error("{0:?} is not a valid WebAssembly runtime")]
1634pub struct InvalidWasmRuntime(String);
1635
1636doc_scalar!(Operation, "An operation to be executed in a block");
1637doc_scalar!(
1638 Message,
1639 "A message to be sent and possibly executed in the receiver's block."
1640);
1641doc_scalar!(MessageKind, "The kind of outgoing message being sent");