1use std::collections::{BTreeMap, BTreeSet};
7
8use custom_debug_derive::Debug;
9use futures::{channel::mpsc, StreamExt as _};
10#[cfg(with_metrics)]
11use linera_base::prometheus_util::MeasureLatency as _;
12use linera_base::{
13    data_types::{
14        Amount, ApplicationPermissions, ArithmeticError, BlobContent, BlockHeight, OracleResponse,
15        Timestamp,
16    },
17    ensure, hex_debug, hex_vec_debug, http,
18    identifiers::{Account, AccountOwner, BlobId, BlobType, ChainId, EventId, StreamId},
19    ownership::ChainOwnership,
20    time::Instant,
21};
22use linera_views::{batch::Batch, context::Context, views::View};
23use oneshot::Sender;
24use reqwest::{header::HeaderMap, Client, Url};
25
26use crate::{
27    execution::UserAction,
28    runtime::ContractSyncRuntime,
29    system::{CreateApplicationResult, OpenChainConfig},
30    util::{OracleResponseExt as _, RespondExt as _},
31    ApplicationDescription, ApplicationId, ExecutionError, ExecutionRuntimeConfig,
32    ExecutionRuntimeContext, ExecutionStateView, Message, MessageContext, MessageKind, ModuleId,
33    Operation, OperationContext, OutgoingMessage, ProcessStreamsContext, QueryContext,
34    QueryOutcome, ResourceController, SystemMessage, TransactionTracker, UserContractCode,
35    UserServiceCode,
36};
37
38pub struct ExecutionStateActor<'a, C> {
40    state: &'a mut ExecutionStateView<C>,
41    txn_tracker: &'a mut TransactionTracker,
42    resource_controller: &'a mut ResourceController<Option<AccountOwner>>,
43}
44
45#[cfg(with_metrics)]
46mod metrics {
47    use std::sync::LazyLock;
48
49    use linera_base::prometheus_util::{exponential_bucket_latencies, register_histogram_vec};
50    use prometheus::HistogramVec;
51
52    pub static LOAD_CONTRACT_LATENCY: LazyLock<HistogramVec> = LazyLock::new(|| {
54        register_histogram_vec(
55            "load_contract_latency",
56            "Load contract latency",
57            &[],
58            exponential_bucket_latencies(250.0),
59        )
60    });
61
62    pub static LOAD_SERVICE_LATENCY: LazyLock<HistogramVec> = LazyLock::new(|| {
64        register_histogram_vec(
65            "load_service_latency",
66            "Load service latency",
67            &[],
68            exponential_bucket_latencies(250.0),
69        )
70    });
71}
72
73pub(crate) type ExecutionStateSender = mpsc::UnboundedSender<ExecutionRequest>;
74
75impl<'a, C> ExecutionStateActor<'a, C>
76where
77    C: Context + Clone + Send + Sync + 'static,
78    C::Extra: ExecutionRuntimeContext,
79{
80    pub fn new(
82        state: &'a mut ExecutionStateView<C>,
83        txn_tracker: &'a mut TransactionTracker,
84        resource_controller: &'a mut ResourceController<Option<AccountOwner>>,
85    ) -> Self {
86        Self {
87            state,
88            txn_tracker,
89            resource_controller,
90        }
91    }
92
93    pub(crate) async fn load_contract(
94        &mut self,
95        id: ApplicationId,
96    ) -> Result<(UserContractCode, ApplicationDescription), ExecutionError> {
97        #[cfg(with_metrics)]
98        let _latency = metrics::LOAD_CONTRACT_LATENCY.measure_latency();
99        let blob_id = id.description_blob_id();
100        let description = match self.txn_tracker.get_blob_content(&blob_id) {
101            Some(blob) => bcs::from_bytes(blob.bytes())?,
102            None => {
103                self.state
104                    .system
105                    .describe_application(id, self.txn_tracker)
106                    .await?
107            }
108        };
109        let code = self
110            .state
111            .context()
112            .extra()
113            .get_user_contract(&description, self.txn_tracker)
114            .await?;
115        Ok((code, description))
116    }
117
118    pub(crate) async fn load_service(
119        &mut self,
120        id: ApplicationId,
121    ) -> Result<(UserServiceCode, ApplicationDescription), ExecutionError> {
122        #[cfg(with_metrics)]
123        let _latency = metrics::LOAD_SERVICE_LATENCY.measure_latency();
124        let blob_id = id.description_blob_id();
125        let description = match self.txn_tracker.get_blob_content(&blob_id) {
126            Some(blob) => bcs::from_bytes(blob.bytes())?,
127            None => {
128                self.state
129                    .system
130                    .describe_application(id, self.txn_tracker)
131                    .await?
132            }
133        };
134        let code = self
135            .state
136            .context()
137            .extra()
138            .get_user_service(&description, self.txn_tracker)
139            .await?;
140        Ok((code, description))
141    }
142
143    pub(crate) async fn handle_request(
145        &mut self,
146        request: ExecutionRequest,
147    ) -> Result<(), ExecutionError> {
148        use ExecutionRequest::*;
149        match request {
150            #[cfg(not(web))]
151            LoadContract { id, callback } => {
152                let (code, description) = self.load_contract(id).await?;
153                callback.respond((code, description))
154            }
155            #[cfg(not(web))]
156            LoadService { id, callback } => {
157                let (code, description) = self.load_service(id).await?;
158                callback.respond((code, description))
159            }
160
161            ChainBalance { callback } => {
162                let balance = *self.state.system.balance.get();
163                callback.respond(balance);
164            }
165
166            OwnerBalance { owner, callback } => {
167                let balance = self
168                    .state
169                    .system
170                    .balances
171                    .get(&owner)
172                    .await?
173                    .unwrap_or_default();
174                callback.respond(balance);
175            }
176
177            OwnerBalances { callback } => {
178                let balances = self.state.system.balances.index_values().await?;
179                callback.respond(balances.into_iter().collect());
180            }
181
182            BalanceOwners { callback } => {
183                let owners = self.state.system.balances.indices().await?;
184                callback.respond(owners);
185            }
186
187            Transfer {
188                source,
189                destination,
190                amount,
191                signer,
192                application_id,
193                callback,
194            } => {
195                let maybe_message = self
196                    .state
197                    .system
198                    .transfer(signer, Some(application_id), source, destination, amount)
199                    .await?;
200                self.txn_tracker.add_outgoing_messages(maybe_message);
201                callback.respond(());
202            }
203
204            Claim {
205                source,
206                destination,
207                amount,
208                signer,
209                application_id,
210                callback,
211            } => {
212                let maybe_message = self
213                    .state
214                    .system
215                    .claim(
216                        signer,
217                        Some(application_id),
218                        source.owner,
219                        source.chain_id,
220                        destination,
221                        amount,
222                    )
223                    .await?;
224                self.txn_tracker.add_outgoing_messages(maybe_message);
225                callback.respond(());
226            }
227
228            SystemTimestamp { callback } => {
229                let timestamp = *self.state.system.timestamp.get();
230                callback.respond(timestamp);
231            }
232
233            ChainOwnership { callback } => {
234                let ownership = self.state.system.ownership.get().clone();
235                callback.respond(ownership);
236            }
237
238            ContainsKey { id, key, callback } => {
239                let view = self.state.users.try_load_entry(&id).await?;
240                let result = match view {
241                    Some(view) => view.contains_key(&key).await?,
242                    None => false,
243                };
244                callback.respond(result);
245            }
246
247            ContainsKeys { id, keys, callback } => {
248                let view = self.state.users.try_load_entry(&id).await?;
249                let result = match view {
250                    Some(view) => view.contains_keys(keys).await?,
251                    None => vec![false; keys.len()],
252                };
253                callback.respond(result);
254            }
255
256            ReadMultiValuesBytes { id, keys, callback } => {
257                let view = self.state.users.try_load_entry(&id).await?;
258                let values = match view {
259                    Some(view) => view.multi_get(keys).await?,
260                    None => vec![None; keys.len()],
261                };
262                callback.respond(values);
263            }
264
265            ReadValueBytes { id, key, callback } => {
266                let view = self.state.users.try_load_entry(&id).await?;
267                let result = match view {
268                    Some(view) => view.get(&key).await?,
269                    None => None,
270                };
271                callback.respond(result);
272            }
273
274            FindKeysByPrefix {
275                id,
276                key_prefix,
277                callback,
278            } => {
279                let view = self.state.users.try_load_entry(&id).await?;
280                let result = match view {
281                    Some(view) => view.find_keys_by_prefix(&key_prefix).await?,
282                    None => Vec::new(),
283                };
284                callback.respond(result);
285            }
286
287            FindKeyValuesByPrefix {
288                id,
289                key_prefix,
290                callback,
291            } => {
292                let view = self.state.users.try_load_entry(&id).await?;
293                let result = match view {
294                    Some(view) => view.find_key_values_by_prefix(&key_prefix).await?,
295                    None => Vec::new(),
296                };
297                callback.respond(result);
298            }
299
300            WriteBatch {
301                id,
302                batch,
303                callback,
304            } => {
305                let mut view = self.state.users.try_load_entry_mut(&id).await?;
306                view.write_batch(batch).await?;
307                callback.respond(());
308            }
309
310            OpenChain {
311                ownership,
312                balance,
313                parent_id,
314                block_height,
315                application_permissions,
316                timestamp,
317                callback,
318            } => {
319                let config = OpenChainConfig {
320                    ownership,
321                    balance,
322                    application_permissions,
323                };
324                let chain_id = self
325                    .state
326                    .system
327                    .open_chain(config, parent_id, block_height, timestamp, self.txn_tracker)
328                    .await?;
329                callback.respond(chain_id);
330            }
331
332            CloseChain {
333                application_id,
334                callback,
335            } => {
336                let app_permissions = self.state.system.application_permissions.get();
337                if !app_permissions.can_close_chain(&application_id) {
338                    callback.respond(Err(ExecutionError::UnauthorizedApplication(application_id)));
339                } else {
340                    self.state.system.close_chain().await?;
341                    callback.respond(Ok(()));
342                }
343            }
344
345            ChangeApplicationPermissions {
346                application_id,
347                application_permissions,
348                callback,
349            } => {
350                let app_permissions = self.state.system.application_permissions.get();
351                if !app_permissions.can_change_application_permissions(&application_id) {
352                    callback.respond(Err(ExecutionError::UnauthorizedApplication(application_id)));
353                } else {
354                    self.state
355                        .system
356                        .application_permissions
357                        .set(application_permissions);
358                    callback.respond(Ok(()));
359                }
360            }
361
362            CreateApplication {
363                chain_id,
364                block_height,
365                module_id,
366                parameters,
367                required_application_ids,
368                callback,
369            } => {
370                let create_application_result = self
371                    .state
372                    .system
373                    .create_application(
374                        chain_id,
375                        block_height,
376                        module_id,
377                        parameters,
378                        required_application_ids,
379                        self.txn_tracker,
380                    )
381                    .await?;
382                callback.respond(Ok(create_application_result));
383            }
384
385            PerformHttpRequest {
386                request,
387                http_responses_are_oracle_responses,
388                callback,
389            } => {
390                let system = &mut self.state.system;
391                let response = self
392                    .txn_tracker
393                    .oracle(|| async {
394                        let headers = request
395                            .headers
396                            .into_iter()
397                            .map(|http::Header { name, value }| {
398                                Ok((name.parse()?, value.try_into()?))
399                            })
400                            .collect::<Result<HeaderMap, ExecutionError>>()?;
401
402                        let url = Url::parse(&request.url)?;
403                        let host = url
404                            .host_str()
405                            .ok_or_else(|| ExecutionError::UnauthorizedHttpRequest(url.clone()))?;
406
407                        let (_epoch, committee) = system
408                            .current_committee()
409                            .ok_or_else(|| ExecutionError::UnauthorizedHttpRequest(url.clone()))?;
410                        let allowed_hosts = &committee.policy().http_request_allow_list;
411
412                        ensure!(
413                            allowed_hosts.contains(host),
414                            ExecutionError::UnauthorizedHttpRequest(url)
415                        );
416
417                        let request = Client::new()
418                            .request(request.method.into(), url)
419                            .body(request.body)
420                            .headers(headers);
421                        #[cfg(not(web))]
422                        let request = request.timeout(linera_base::time::Duration::from_millis(
423                            committee.policy().http_request_timeout_ms,
424                        ));
425
426                        let response = request.send().await?;
427
428                        let mut response_size_limit =
429                            committee.policy().maximum_http_response_bytes;
430
431                        if http_responses_are_oracle_responses {
432                            response_size_limit = response_size_limit
433                                .min(committee.policy().maximum_oracle_response_bytes);
434                        }
435                        Ok(OracleResponse::Http(
436                            Self::receive_http_response(response, response_size_limit).await?,
437                        ))
438                    })
439                    .await?
440                    .to_http_response()?;
441                callback.respond(response);
442            }
443
444            ReadBlobContent { blob_id, callback } => {
445                let content = if let Some(content) = self.txn_tracker.get_blob_content(&blob_id) {
446                    content.clone()
447                } else {
448                    let content = self.state.system.read_blob_content(blob_id).await?;
449                    if blob_id.blob_type == BlobType::Data {
450                        self.resource_controller
451                            .with_state(&mut self.state.system)
452                            .await?
453                            .track_blob_read(content.bytes().len() as u64)?;
454                    }
455                    self.state
456                        .system
457                        .blob_used(self.txn_tracker, blob_id)
458                        .await?;
459                    content
460                };
461                callback.respond(content)
462            }
463
464            AssertBlobExists { blob_id, callback } => {
465                self.state.system.assert_blob_exists(blob_id).await?;
466                if blob_id.blob_type == BlobType::Data {
468                    self.resource_controller
469                        .with_state(&mut self.state.system)
470                        .await?
471                        .track_blob_read(0)?;
472                }
473                let is_new = self
474                    .state
475                    .system
476                    .blob_used(self.txn_tracker, blob_id)
477                    .await?;
478                if is_new {
479                    self.txn_tracker
480                        .replay_oracle_response(OracleResponse::Blob(blob_id))?;
481                }
482                callback.respond(());
483            }
484
485            Emit {
486                stream_id,
487                value,
488                callback,
489            } => {
490                let count = self
491                    .state
492                    .stream_event_counts
493                    .get_mut_or_default(&stream_id)
494                    .await?;
495                let index = *count;
496                *count = count.checked_add(1).ok_or(ArithmeticError::Overflow)?;
497                self.txn_tracker.add_event(stream_id, index, value);
498                callback.respond(index)
499            }
500
501            ReadEvent { event_id, callback } => {
502                let extra = self.state.context().extra();
503                let event = self
504                    .txn_tracker
505                    .oracle(|| async {
506                        let event = extra
507                            .get_event(event_id.clone())
508                            .await?
509                            .ok_or(ExecutionError::EventsNotFound(vec![event_id.clone()]))?;
510                        Ok(OracleResponse::Event(event_id.clone(), event))
511                    })
512                    .await?
513                    .to_event(&event_id)?;
514                callback.respond(event);
515            }
516
517            SubscribeToEvents {
518                chain_id,
519                stream_id,
520                subscriber_app_id,
521                callback,
522            } => {
523                let subscriptions = self
524                    .state
525                    .system
526                    .event_subscriptions
527                    .get_mut_or_default(&(chain_id, stream_id.clone()))
528                    .await?;
529                let next_index = if subscriptions.applications.insert(subscriber_app_id) {
530                    subscriptions.next_index
531                } else {
532                    0
533                };
534                self.txn_tracker.add_stream_to_process(
535                    subscriber_app_id,
536                    chain_id,
537                    stream_id,
538                    0,
539                    next_index,
540                );
541                callback.respond(());
542            }
543
544            UnsubscribeFromEvents {
545                chain_id,
546                stream_id,
547                subscriber_app_id,
548                callback,
549            } => {
550                let key = (chain_id, stream_id.clone());
551                let subscriptions = self
552                    .state
553                    .system
554                    .event_subscriptions
555                    .get_mut_or_default(&key)
556                    .await?;
557                subscriptions.applications.remove(&subscriber_app_id);
558                if subscriptions.applications.is_empty() {
559                    self.state.system.event_subscriptions.remove(&key)?;
560                }
561                if let crate::GenericApplicationId::User(app_id) = stream_id.application_id {
562                    self.txn_tracker
563                        .remove_stream_to_process(app_id, chain_id, stream_id);
564                }
565                callback.respond(());
566            }
567
568            GetApplicationPermissions { callback } => {
569                let app_permissions = self.state.system.application_permissions.get();
570                callback.respond(app_permissions.clone());
571            }
572
573            QueryServiceOracle {
574                deadline,
575                application_id,
576                next_block_height,
577                query,
578                callback,
579            } => {
580                let state = &mut self.state;
581                let local_time = self.txn_tracker.local_time();
582                let created_blobs = self.txn_tracker.created_blobs().clone();
583                let bytes = self
584                    .txn_tracker
585                    .oracle(|| async {
586                        let context = QueryContext {
587                            chain_id: state.context().extra().chain_id(),
588                            next_block_height,
589                            local_time,
590                        };
591                        let QueryOutcome {
592                            response,
593                            operations,
594                        } = Box::pin(state.query_user_application_with_deadline(
595                            application_id,
596                            context,
597                            query,
598                            deadline,
599                            created_blobs,
600                        ))
601                        .await?;
602                        ensure!(
603                            operations.is_empty(),
604                            ExecutionError::ServiceOracleQueryOperations(operations)
605                        );
606                        Ok(OracleResponse::Service(response))
607                    })
608                    .await?
609                    .to_service_response()?;
610                callback.respond(bytes);
611            }
612
613            AddOutgoingMessage { message, callback } => {
614                self.txn_tracker.add_outgoing_message(message);
615                callback.respond(());
616            }
617
618            SetLocalTime {
619                local_time,
620                callback,
621            } => {
622                self.txn_tracker.set_local_time(local_time);
623                callback.respond(());
624            }
625
626            AssertBefore {
627                timestamp,
628                callback,
629            } => {
630                let result = if !self
631                    .txn_tracker
632                    .replay_oracle_response(OracleResponse::Assert)?
633                {
634                    let local_time = self.txn_tracker.local_time();
636                    if local_time >= timestamp {
637                        Err(ExecutionError::AssertBefore {
638                            timestamp,
639                            local_time,
640                        })
641                    } else {
642                        Ok(())
643                    }
644                } else {
645                    Ok(())
646                };
647                callback.respond(result);
648            }
649
650            AddCreatedBlob { blob, callback } => {
651                self.txn_tracker.add_created_blob(blob);
652                callback.respond(());
653            }
654
655            ValidationRound { round, callback } => {
656                let validation_round = self
657                    .txn_tracker
658                    .oracle(|| async { Ok(OracleResponse::Round(round)) })
659                    .await?
660                    .to_round()?;
661                callback.respond(validation_round);
662            }
663        }
664
665        Ok(())
666    }
667
668    async fn process_subscriptions(
671        &mut self,
672        context: ProcessStreamsContext,
673    ) -> Result<(), ExecutionError> {
674        let mut processed = BTreeSet::new();
677        loop {
678            let to_process = self
679                .txn_tracker
680                .take_streams_to_process()
681                .into_iter()
682                .filter_map(|(app_id, updates)| {
683                    let updates = updates
684                        .into_iter()
685                        .filter_map(|update| {
686                            if !processed.insert((
687                                app_id,
688                                update.chain_id,
689                                update.stream_id.clone(),
690                            )) {
691                                return None;
692                            }
693                            Some(update)
694                        })
695                        .collect::<Vec<_>>();
696                    if updates.is_empty() {
697                        return None;
698                    }
699                    Some((app_id, updates))
700                })
701                .collect::<BTreeMap<_, _>>();
702            if to_process.is_empty() {
703                return Ok(());
704            }
705            for (app_id, updates) in to_process {
706                self.run_user_action(
707                    app_id,
708                    UserAction::ProcessStreams(context, updates),
709                    None,
710                    None,
711                )
712                .await?;
713            }
714        }
715    }
716
717    pub(crate) async fn run_user_action(
718        &mut self,
719        application_id: ApplicationId,
720        action: UserAction,
721        refund_grant_to: Option<Account>,
722        grant: Option<&mut Amount>,
723    ) -> Result<(), ExecutionError> {
724        let ExecutionRuntimeConfig {} = self.state.context().extra().execution_runtime_config();
725        self.run_user_action_with_runtime(application_id, action, refund_grant_to, grant)
726            .await
727    }
728
729    async fn run_user_action_with_runtime(
730        &mut self,
731        application_id: ApplicationId,
732        action: UserAction,
733        refund_grant_to: Option<Account>,
734        grant: Option<&mut Amount>,
735    ) -> Result<(), ExecutionError> {
736        let chain_id = self.state.context().extra().chain_id();
737        let mut cloned_grant = grant.as_ref().map(|x| **x);
738        let initial_balance = self
739            .resource_controller
740            .with_state_and_grant(&mut self.state.system, cloned_grant.as_mut())
741            .await?
742            .balance()?;
743        let controller = ResourceController::new(
744            self.resource_controller.policy().clone(),
745            self.resource_controller.tracker,
746            initial_balance,
747        );
748        let (execution_state_sender, mut execution_state_receiver) =
749            futures::channel::mpsc::unbounded();
750
751        let (code, description) = self.load_contract(application_id).await?;
752
753        let contract_runtime_task = linera_base::task::Blocking::spawn(move |mut codes| {
754            let runtime = ContractSyncRuntime::new(
755                execution_state_sender,
756                chain_id,
757                refund_grant_to,
758                controller,
759                &action,
760            );
761
762            async move {
763                let code = codes.next().await.expect("we send this immediately below");
764                runtime.preload_contract(application_id, code, description)?;
765                runtime.run_action(application_id, chain_id, action)
766            }
767        })
768        .await;
769
770        contract_runtime_task.send(code)?;
771
772        while let Some(request) = execution_state_receiver.next().await {
773            self.handle_request(request).await?;
774        }
775
776        let (result, controller) = contract_runtime_task.join().await?;
777
778        self.txn_tracker.add_operation_result(result);
779
780        self.resource_controller
781            .with_state_and_grant(&mut self.state.system, grant)
782            .await?
783            .merge_balance(initial_balance, controller.balance()?)?;
784        self.resource_controller.tracker = controller.tracker;
785
786        Ok(())
787    }
788
789    pub async fn execute_operation(
790        &mut self,
791        context: OperationContext,
792        operation: Operation,
793    ) -> Result<(), ExecutionError> {
794        assert_eq!(context.chain_id, self.state.context().extra().chain_id());
795        match operation {
796            Operation::System(op) => {
797                let new_application = self
798                    .state
799                    .system
800                    .execute_operation(context, *op, self.txn_tracker, self.resource_controller)
801                    .await?;
802                if let Some((application_id, argument)) = new_application {
803                    let user_action = UserAction::Instantiate(context, argument);
804                    self.run_user_action(
805                        application_id,
806                        user_action,
807                        context.refund_grant_to(),
808                        None,
809                    )
810                    .await?;
811                }
812            }
813            Operation::User {
814                application_id,
815                bytes,
816            } => {
817                self.run_user_action(
818                    application_id,
819                    UserAction::Operation(context, bytes),
820                    context.refund_grant_to(),
821                    None,
822                )
823                .await?;
824            }
825        }
826        self.process_subscriptions(context.into()).await?;
827        Ok(())
828    }
829
830    pub async fn execute_message(
831        &mut self,
832        context: MessageContext,
833        message: Message,
834        grant: Option<&mut Amount>,
835    ) -> Result<(), ExecutionError> {
836        assert_eq!(context.chain_id, self.state.context().extra().chain_id());
837        match message {
838            Message::System(message) => {
839                let outcome = self.state.system.execute_message(context, message).await?;
840                self.txn_tracker.add_outgoing_messages(outcome);
841            }
842            Message::User {
843                application_id,
844                bytes,
845            } => {
846                self.run_user_action(
847                    application_id,
848                    UserAction::Message(context, bytes),
849                    context.refund_grant_to,
850                    grant,
851                )
852                .await?;
853            }
854        }
855        self.process_subscriptions(context.into()).await?;
856        Ok(())
857    }
858
859    pub fn bounce_message(
860        &mut self,
861        context: MessageContext,
862        grant: Amount,
863        message: Message,
864    ) -> Result<(), ExecutionError> {
865        assert_eq!(context.chain_id, self.state.context().extra().chain_id());
866        self.txn_tracker.add_outgoing_message(OutgoingMessage {
867            destination: context.origin,
868            authenticated_signer: context.authenticated_signer,
869            refund_grant_to: context.refund_grant_to.filter(|_| !grant.is_zero()),
870            grant,
871            kind: MessageKind::Bouncing,
872            message,
873        });
874        Ok(())
875    }
876
877    pub fn send_refund(
878        &mut self,
879        context: MessageContext,
880        amount: Amount,
881    ) -> Result<(), ExecutionError> {
882        assert_eq!(context.chain_id, self.state.context().extra().chain_id());
883        if amount.is_zero() {
884            return Ok(());
885        }
886        let Some(account) = context.refund_grant_to else {
887            return Err(ExecutionError::InternalError(
888                "Messages with grants should have a non-empty `refund_grant_to`",
889            ));
890        };
891        let message = SystemMessage::Credit {
892            amount,
893            source: context.authenticated_signer.unwrap_or(AccountOwner::CHAIN),
894            target: account.owner,
895        };
896        self.txn_tracker.add_outgoing_message(
897            OutgoingMessage::new(account.chain_id, message).with_kind(MessageKind::Tracked),
898        );
899        Ok(())
900    }
901
902    async fn receive_http_response(
906        response: reqwest::Response,
907        size_limit: u64,
908    ) -> Result<http::Response, ExecutionError> {
909        let status = response.status().as_u16();
910        let maybe_content_length = response.content_length();
911
912        let headers = response
913            .headers()
914            .iter()
915            .map(|(name, value)| http::Header::new(name.to_string(), value.as_bytes()))
916            .collect::<Vec<_>>();
917
918        let total_header_size = headers
919            .iter()
920            .map(|header| (header.name.len() + header.value.len()) as u64)
921            .sum();
922
923        let mut remaining_bytes = size_limit.checked_sub(total_header_size).ok_or(
924            ExecutionError::HttpResponseSizeLimitExceeded {
925                limit: size_limit,
926                size: total_header_size,
927            },
928        )?;
929
930        if let Some(content_length) = maybe_content_length {
931            if content_length > remaining_bytes {
932                return Err(ExecutionError::HttpResponseSizeLimitExceeded {
933                    limit: size_limit,
934                    size: content_length + total_header_size,
935                });
936            }
937        }
938
939        let mut body = Vec::with_capacity(maybe_content_length.unwrap_or(0) as usize);
940        let mut body_stream = response.bytes_stream();
941
942        while let Some(bytes) = body_stream.next().await.transpose()? {
943            remaining_bytes = remaining_bytes.checked_sub(bytes.len() as u64).ok_or(
944                ExecutionError::HttpResponseSizeLimitExceeded {
945                    limit: size_limit,
946                    size: bytes.len() as u64 + (size_limit - remaining_bytes),
947                },
948            )?;
949
950            body.extend(&bytes);
951        }
952
953        Ok(http::Response {
954            status,
955            headers,
956            body,
957        })
958    }
959}
960
961#[derive(Debug)]
963pub enum ExecutionRequest {
964    #[cfg(not(web))]
965    LoadContract {
966        id: ApplicationId,
967        #[debug(skip)]
968        callback: Sender<(UserContractCode, ApplicationDescription)>,
969    },
970
971    #[cfg(not(web))]
972    LoadService {
973        id: ApplicationId,
974        #[debug(skip)]
975        callback: Sender<(UserServiceCode, ApplicationDescription)>,
976    },
977
978    ChainBalance {
979        #[debug(skip)]
980        callback: Sender<Amount>,
981    },
982
983    OwnerBalance {
984        owner: AccountOwner,
985        #[debug(skip)]
986        callback: Sender<Amount>,
987    },
988
989    OwnerBalances {
990        #[debug(skip)]
991        callback: Sender<Vec<(AccountOwner, Amount)>>,
992    },
993
994    BalanceOwners {
995        #[debug(skip)]
996        callback: Sender<Vec<AccountOwner>>,
997    },
998
999    Transfer {
1000        source: AccountOwner,
1001        destination: Account,
1002        amount: Amount,
1003        #[debug(skip_if = Option::is_none)]
1004        signer: Option<AccountOwner>,
1005        application_id: ApplicationId,
1006        #[debug(skip)]
1007        callback: Sender<()>,
1008    },
1009
1010    Claim {
1011        source: Account,
1012        destination: Account,
1013        amount: Amount,
1014        #[debug(skip_if = Option::is_none)]
1015        signer: Option<AccountOwner>,
1016        application_id: ApplicationId,
1017        #[debug(skip)]
1018        callback: Sender<()>,
1019    },
1020
1021    SystemTimestamp {
1022        #[debug(skip)]
1023        callback: Sender<Timestamp>,
1024    },
1025
1026    ChainOwnership {
1027        #[debug(skip)]
1028        callback: Sender<ChainOwnership>,
1029    },
1030
1031    ReadValueBytes {
1032        id: ApplicationId,
1033        #[debug(with = hex_debug)]
1034        key: Vec<u8>,
1035        #[debug(skip)]
1036        callback: Sender<Option<Vec<u8>>>,
1037    },
1038
1039    ContainsKey {
1040        id: ApplicationId,
1041        key: Vec<u8>,
1042        #[debug(skip)]
1043        callback: Sender<bool>,
1044    },
1045
1046    ContainsKeys {
1047        id: ApplicationId,
1048        #[debug(with = hex_vec_debug)]
1049        keys: Vec<Vec<u8>>,
1050        callback: Sender<Vec<bool>>,
1051    },
1052
1053    ReadMultiValuesBytes {
1054        id: ApplicationId,
1055        #[debug(with = hex_vec_debug)]
1056        keys: Vec<Vec<u8>>,
1057        #[debug(skip)]
1058        callback: Sender<Vec<Option<Vec<u8>>>>,
1059    },
1060
1061    FindKeysByPrefix {
1062        id: ApplicationId,
1063        #[debug(with = hex_debug)]
1064        key_prefix: Vec<u8>,
1065        #[debug(skip)]
1066        callback: Sender<Vec<Vec<u8>>>,
1067    },
1068
1069    FindKeyValuesByPrefix {
1070        id: ApplicationId,
1071        #[debug(with = hex_debug)]
1072        key_prefix: Vec<u8>,
1073        #[debug(skip)]
1074        callback: Sender<Vec<(Vec<u8>, Vec<u8>)>>,
1075    },
1076
1077    WriteBatch {
1078        id: ApplicationId,
1079        batch: Batch,
1080        #[debug(skip)]
1081        callback: Sender<()>,
1082    },
1083
1084    OpenChain {
1085        ownership: ChainOwnership,
1086        #[debug(skip_if = Amount::is_zero)]
1087        balance: Amount,
1088        parent_id: ChainId,
1089        block_height: BlockHeight,
1090        application_permissions: ApplicationPermissions,
1091        timestamp: Timestamp,
1092        #[debug(skip)]
1093        callback: Sender<ChainId>,
1094    },
1095
1096    CloseChain {
1097        application_id: ApplicationId,
1098        #[debug(skip)]
1099        callback: Sender<Result<(), ExecutionError>>,
1100    },
1101
1102    ChangeApplicationPermissions {
1103        application_id: ApplicationId,
1104        application_permissions: ApplicationPermissions,
1105        #[debug(skip)]
1106        callback: Sender<Result<(), ExecutionError>>,
1107    },
1108
1109    CreateApplication {
1110        chain_id: ChainId,
1111        block_height: BlockHeight,
1112        module_id: ModuleId,
1113        parameters: Vec<u8>,
1114        required_application_ids: Vec<ApplicationId>,
1115        #[debug(skip)]
1116        callback: Sender<Result<CreateApplicationResult, ExecutionError>>,
1117    },
1118
1119    PerformHttpRequest {
1120        request: http::Request,
1121        http_responses_are_oracle_responses: bool,
1122        #[debug(skip)]
1123        callback: Sender<http::Response>,
1124    },
1125
1126    ReadBlobContent {
1127        blob_id: BlobId,
1128        #[debug(skip)]
1129        callback: Sender<BlobContent>,
1130    },
1131
1132    AssertBlobExists {
1133        blob_id: BlobId,
1134        #[debug(skip)]
1135        callback: Sender<()>,
1136    },
1137
1138    Emit {
1139        stream_id: StreamId,
1140        #[debug(with = hex_debug)]
1141        value: Vec<u8>,
1142        #[debug(skip)]
1143        callback: Sender<u32>,
1144    },
1145
1146    ReadEvent {
1147        event_id: EventId,
1148        callback: oneshot::Sender<Vec<u8>>,
1149    },
1150
1151    SubscribeToEvents {
1152        chain_id: ChainId,
1153        stream_id: StreamId,
1154        subscriber_app_id: ApplicationId,
1155        #[debug(skip)]
1156        callback: Sender<()>,
1157    },
1158
1159    UnsubscribeFromEvents {
1160        chain_id: ChainId,
1161        stream_id: StreamId,
1162        subscriber_app_id: ApplicationId,
1163        #[debug(skip)]
1164        callback: Sender<()>,
1165    },
1166
1167    GetApplicationPermissions {
1168        #[debug(skip)]
1169        callback: Sender<ApplicationPermissions>,
1170    },
1171
1172    QueryServiceOracle {
1173        deadline: Option<Instant>,
1174        application_id: ApplicationId,
1175        next_block_height: BlockHeight,
1176        query: Vec<u8>,
1177        #[debug(skip)]
1178        callback: Sender<Vec<u8>>,
1179    },
1180
1181    AddOutgoingMessage {
1182        message: crate::OutgoingMessage,
1183        #[debug(skip)]
1184        callback: Sender<()>,
1185    },
1186
1187    SetLocalTime {
1188        local_time: Timestamp,
1189        #[debug(skip)]
1190        callback: Sender<()>,
1191    },
1192
1193    AssertBefore {
1194        timestamp: Timestamp,
1195        #[debug(skip)]
1196        callback: Sender<Result<(), ExecutionError>>,
1197    },
1198
1199    AddCreatedBlob {
1200        blob: crate::Blob,
1201        #[debug(skip)]
1202        callback: Sender<()>,
1203    },
1204
1205    ValidationRound {
1206        round: Option<u32>,
1207        #[debug(skip)]
1208        callback: Sender<Option<u32>>,
1209    },
1210}