linera_execution/
transaction_tracker.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    collections::{BTreeMap, BTreeSet},
6    future::Future,
7    mem, vec,
8};
9
10use custom_debug_derive::Debug;
11use linera_base::{
12    data_types::{Blob, BlobContent, Event, OracleResponse, StreamUpdate, Timestamp},
13    ensure,
14    identifiers::{ApplicationId, BlobId, ChainId, StreamId},
15};
16
17use crate::{ExecutionError, OutgoingMessage};
18
19type AppStreamUpdates = BTreeMap<(ChainId, StreamId), (u32, u32)>;
20
21/// Tracks oracle responses and execution outcomes of an ongoing transaction execution, as well
22/// as replayed oracle responses.
23#[derive(Debug, Default)]
24pub struct TransactionTracker {
25    #[debug(skip_if = Option::is_none)]
26    replaying_oracle_responses: Option<vec::IntoIter<OracleResponse>>,
27    #[debug(skip_if = Vec::is_empty)]
28    oracle_responses: Vec<OracleResponse>,
29    #[debug(skip_if = Vec::is_empty)]
30    outgoing_messages: Vec<OutgoingMessage>,
31    /// The current local time.
32    local_time: Timestamp,
33    /// The index of the current transaction in the block.
34    transaction_index: u32,
35    next_application_index: u32,
36    next_chain_index: u32,
37    /// Events recorded by contracts' `emit` calls.
38    events: Vec<Event>,
39    /// Blobs created by contracts.
40    ///
41    /// As of right now, blobs created by the contracts are one of the following types:
42    /// - [`Data`]
43    /// - [`ContractBytecode`]
44    /// - [`ServiceBytecode`]
45    /// - [`EvmBytecode`]
46    /// - [`ApplicationDescription`]
47    /// - [`ChainDescription`]
48    blobs: BTreeMap<BlobId, BlobContent>,
49    /// The blobs created in the previous transactions.
50    previously_created_blobs: BTreeMap<BlobId, BlobContent>,
51    /// Operation result.
52    operation_result: Option<Vec<u8>>,
53    /// Streams that have been updated but not yet processed during this transaction.
54    streams_to_process: BTreeMap<ApplicationId, AppStreamUpdates>,
55    /// Published blobs this transaction refers to by [`BlobId`].
56    blobs_published: BTreeSet<BlobId>,
57}
58
59/// The [`TransactionTracker`] contents after a transaction has finished.
60#[derive(Debug, Default)]
61pub struct TransactionOutcome {
62    #[debug(skip_if = Vec::is_empty)]
63    pub oracle_responses: Vec<OracleResponse>,
64    #[debug(skip_if = Vec::is_empty)]
65    pub outgoing_messages: Vec<OutgoingMessage>,
66    pub next_application_index: u32,
67    pub next_chain_index: u32,
68    /// Events recorded by contracts' `emit` calls.
69    pub events: Vec<Event>,
70    /// Blobs created by contracts.
71    pub blobs: Vec<Blob>,
72    /// Operation result.
73    pub operation_result: Vec<u8>,
74    /// Blobs published by this transaction.
75    pub blobs_published: BTreeSet<BlobId>,
76}
77
78impl TransactionTracker {
79    pub fn new(
80        local_time: Timestamp,
81        transaction_index: u32,
82        next_application_index: u32,
83        next_chain_index: u32,
84        oracle_responses: Option<Vec<OracleResponse>>,
85        blobs: &[Vec<Blob>],
86    ) -> Self {
87        let mut previously_created_blobs = BTreeMap::new();
88        for tx_blobs in blobs {
89            for blob in tx_blobs {
90                previously_created_blobs.insert(blob.id(), blob.content().clone());
91            }
92        }
93        TransactionTracker {
94            local_time,
95            transaction_index,
96            next_application_index,
97            next_chain_index,
98            replaying_oracle_responses: oracle_responses.map(Vec::into_iter),
99            previously_created_blobs,
100            ..Self::default()
101        }
102    }
103
104    pub fn with_blobs(mut self, blobs: BTreeMap<BlobId, BlobContent>) -> Self {
105        self.blobs = blobs;
106        self
107    }
108
109    pub fn local_time(&self) -> Timestamp {
110        self.local_time
111    }
112
113    pub fn set_local_time(&mut self, local_time: Timestamp) {
114        self.local_time = local_time;
115    }
116
117    pub fn transaction_index(&self) -> u32 {
118        self.transaction_index
119    }
120
121    pub fn peek_application_index(&self) -> u32 {
122        self.next_application_index
123    }
124
125    pub fn next_application_index(&mut self) -> u32 {
126        let index = self.next_application_index;
127        self.next_application_index += 1;
128        index
129    }
130
131    pub fn next_chain_index(&mut self) -> u32 {
132        let index = self.next_chain_index;
133        self.next_chain_index += 1;
134        index
135    }
136
137    pub fn add_outgoing_message(&mut self, message: OutgoingMessage) {
138        self.outgoing_messages.push(message);
139    }
140
141    pub fn add_outgoing_messages(&mut self, messages: impl IntoIterator<Item = OutgoingMessage>) {
142        for message in messages {
143            self.add_outgoing_message(message);
144        }
145    }
146
147    pub fn add_event(&mut self, stream_id: StreamId, index: u32, value: Vec<u8>) {
148        self.events.push(Event {
149            stream_id,
150            index,
151            value,
152        });
153    }
154
155    pub fn get_blob_content(&self, blob_id: &BlobId) -> Option<&BlobContent> {
156        if let Some(content) = self.blobs.get(blob_id) {
157            return Some(content);
158        }
159        self.previously_created_blobs.get(blob_id)
160    }
161
162    pub fn add_created_blob(&mut self, blob: Blob) {
163        self.blobs.insert(blob.id(), blob.into_content());
164    }
165
166    pub fn add_published_blob(&mut self, blob_id: BlobId) {
167        self.blobs_published.insert(blob_id);
168    }
169
170    pub fn created_blobs(&self) -> &BTreeMap<BlobId, BlobContent> {
171        &self.blobs
172    }
173
174    pub fn add_operation_result(&mut self, result: Option<Vec<u8>>) {
175        self.operation_result = result
176    }
177
178    /// In replay mode, returns the next recorded oracle response. Otherwise executes `f` and
179    /// records and returns the result. `f` is the implementation of the actual oracle and is
180    /// only called in validation mode, so it does not have to be fully deterministic.
181    pub async fn oracle<F, G>(&mut self, f: F) -> Result<&OracleResponse, ExecutionError>
182    where
183        F: FnOnce() -> G,
184        G: Future<Output = Result<OracleResponse, ExecutionError>>,
185    {
186        let response = match self.next_replayed_oracle_response()? {
187            Some(response) => response,
188            None => f().await?,
189        };
190        self.oracle_responses.push(response);
191        Ok(self.oracle_responses.last().unwrap())
192    }
193
194    pub fn add_stream_to_process(
195        &mut self,
196        application_id: ApplicationId,
197        chain_id: ChainId,
198        stream_id: StreamId,
199        previous_index: u32,
200        next_index: u32,
201    ) {
202        if next_index == previous_index {
203            return; // No new events in the stream.
204        }
205        self.streams_to_process
206            .entry(application_id)
207            .or_default()
208            .entry((chain_id, stream_id))
209            .and_modify(|(pi, ni)| {
210                *pi = (*pi).min(previous_index);
211                *ni = (*ni).max(next_index);
212            })
213            .or_insert_with(|| (previous_index, next_index));
214    }
215
216    pub fn remove_stream_to_process(
217        &mut self,
218        application_id: ApplicationId,
219        chain_id: ChainId,
220        stream_id: StreamId,
221    ) {
222        let Some(streams) = self.streams_to_process.get_mut(&application_id) else {
223            return;
224        };
225        if streams.remove(&(chain_id, stream_id)).is_some() && streams.is_empty() {
226            self.streams_to_process.remove(&application_id);
227        }
228    }
229
230    pub fn take_streams_to_process(&mut self) -> BTreeMap<ApplicationId, Vec<StreamUpdate>> {
231        mem::take(&mut self.streams_to_process)
232            .into_iter()
233            .map(|(app_id, streams)| {
234                let updates = streams
235                    .into_iter()
236                    .map(
237                        |((chain_id, stream_id), (previous_index, next_index))| StreamUpdate {
238                            chain_id,
239                            stream_id,
240                            previous_index,
241                            next_index,
242                        },
243                    )
244                    .collect();
245                (app_id, updates)
246            })
247            .collect()
248    }
249
250    /// Adds the oracle response to the record.
251    /// If replaying, it also checks that it matches the next replayed one and returns `true`.
252    pub fn replay_oracle_response(
253        &mut self,
254        oracle_response: OracleResponse,
255    ) -> Result<bool, ExecutionError> {
256        let replaying = if let Some(recorded_response) = self.next_replayed_oracle_response()? {
257            ensure!(
258                recorded_response == oracle_response,
259                ExecutionError::OracleResponseMismatch
260            );
261            true
262        } else {
263            false
264        };
265        self.oracle_responses.push(oracle_response);
266        Ok(replaying)
267    }
268
269    /// If in replay mode, returns the next oracle response, or an error if it is missing.
270    ///
271    /// If not in replay mode, `None` is returned, and the caller must execute the actual oracle
272    /// to obtain the value.
273    ///
274    /// In both cases, the value (returned or obtained from the oracle) must be recorded using
275    /// `add_oracle_response`.
276    fn next_replayed_oracle_response(&mut self) -> Result<Option<OracleResponse>, ExecutionError> {
277        let Some(responses) = &mut self.replaying_oracle_responses else {
278            return Ok(None); // Not in replay mode.
279        };
280        let response = responses
281            .next()
282            .ok_or_else(|| ExecutionError::MissingOracleResponse)?;
283        Ok(Some(response))
284    }
285
286    pub fn into_outcome(self) -> Result<TransactionOutcome, ExecutionError> {
287        let TransactionTracker {
288            replaying_oracle_responses,
289            oracle_responses,
290            outgoing_messages,
291            local_time: _,
292            transaction_index: _,
293            next_application_index,
294            next_chain_index,
295            events,
296            blobs,
297            previously_created_blobs: _,
298            operation_result,
299            streams_to_process,
300            blobs_published,
301        } = self;
302        ensure!(
303            streams_to_process.is_empty(),
304            ExecutionError::UnprocessedStreams
305        );
306        if let Some(mut responses) = replaying_oracle_responses {
307            ensure!(
308                responses.next().is_none(),
309                ExecutionError::UnexpectedOracleResponse
310            );
311        }
312        let blobs = blobs
313            .into_iter()
314            .map(|(blob_id, content)| Blob::new_with_hash_unchecked(blob_id, content))
315            .collect::<Vec<_>>();
316        Ok(TransactionOutcome {
317            outgoing_messages,
318            oracle_responses,
319            next_application_index,
320            next_chain_index,
321            events,
322            blobs,
323            operation_result: operation_result.unwrap_or_default(),
324            blobs_published,
325        })
326    }
327}
328
329#[cfg(with_testing)]
330impl TransactionTracker {
331    /// Creates a new [`TransactionTracker`] for testing, with default values and the given
332    /// oracle responses.
333    pub fn new_replaying(oracle_responses: Vec<OracleResponse>) -> Self {
334        TransactionTracker::new(Timestamp::from(0), 0, 0, 0, Some(oracle_responses), &[])
335    }
336
337    /// Creates a new [`TransactionTracker`] for testing, with default values and oracle responses
338    /// for the given blobs.
339    pub fn new_replaying_blobs<T>(blob_ids: T) -> Self
340    where
341        T: IntoIterator,
342        T::Item: std::borrow::Borrow<BlobId>,
343    {
344        use std::borrow::Borrow;
345
346        let oracle_responses = blob_ids
347            .into_iter()
348            .map(|blob_id| OracleResponse::Blob(*blob_id.borrow()))
349            .collect();
350        TransactionTracker::new_replaying(oracle_responses)
351    }
352}