Skip to main content

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    /// Blob IDs created or published by free apps (fees waived).
58    free_blob_ids: BTreeSet<BlobId>,
59}
60
61/// The [`TransactionTracker`] contents after a transaction has finished.
62#[derive(Debug, Default)]
63pub struct TransactionOutcome {
64    #[debug(skip_if = Vec::is_empty)]
65    pub oracle_responses: Vec<OracleResponse>,
66    #[debug(skip_if = Vec::is_empty)]
67    pub outgoing_messages: Vec<OutgoingMessage>,
68    pub next_application_index: u32,
69    pub next_chain_index: u32,
70    /// Events recorded by contracts' `emit` calls.
71    pub events: Vec<Event>,
72    /// Blobs created by contracts.
73    pub blobs: Vec<Blob>,
74    /// Operation result.
75    pub operation_result: Vec<u8>,
76    /// Blobs published by this transaction.
77    pub blobs_published: BTreeSet<BlobId>,
78    /// Blob IDs created or published by free apps (fees waived).
79    pub free_blob_ids: BTreeSet<BlobId>,
80}
81
82impl TransactionTracker {
83    pub fn new(
84        local_time: Timestamp,
85        transaction_index: u32,
86        next_application_index: u32,
87        next_chain_index: u32,
88        oracle_responses: Option<Vec<OracleResponse>>,
89        blobs: &[Vec<Blob>],
90    ) -> Self {
91        let mut previously_created_blobs = BTreeMap::new();
92        for tx_blobs in blobs {
93            for blob in tx_blobs {
94                previously_created_blobs.insert(blob.id(), blob.content().clone());
95            }
96        }
97        TransactionTracker {
98            local_time,
99            transaction_index,
100            next_application_index,
101            next_chain_index,
102            replaying_oracle_responses: oracle_responses.map(Vec::into_iter),
103            previously_created_blobs,
104            ..Self::default()
105        }
106    }
107
108    pub fn with_blobs(mut self, blobs: BTreeMap<BlobId, BlobContent>) -> Self {
109        self.blobs = blobs;
110        self
111    }
112
113    pub fn local_time(&self) -> Timestamp {
114        self.local_time
115    }
116
117    pub fn set_local_time(&mut self, local_time: Timestamp) {
118        self.local_time = local_time;
119    }
120
121    pub fn transaction_index(&self) -> u32 {
122        self.transaction_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    /// Marks a blob as created/published by a free app, so its fees will be waived.
171    pub fn mark_blob_free(&mut self, blob_id: BlobId) {
172        self.free_blob_ids.insert(blob_id);
173    }
174
175    pub fn created_blobs(&self) -> &BTreeMap<BlobId, BlobContent> {
176        &self.blobs
177    }
178
179    pub fn add_operation_result(&mut self, result: Option<Vec<u8>>) {
180        self.operation_result = result
181    }
182
183    /// In replay mode, returns the next recorded oracle response. Otherwise executes `f` and
184    /// records and returns the result. `f` is the implementation of the actual oracle and is
185    /// only called in validation mode, so it does not have to be fully deterministic.
186    pub async fn oracle<F, G>(&mut self, f: F) -> Result<&OracleResponse, ExecutionError>
187    where
188        F: FnOnce() -> G,
189        G: Future<Output = Result<OracleResponse, ExecutionError>>,
190    {
191        let response = match self.next_replayed_oracle_response()? {
192            Some(response) => response,
193            None => f().await?,
194        };
195        self.oracle_responses.push(response);
196        Ok(self.oracle_responses.last().unwrap())
197    }
198
199    pub fn add_stream_to_process(
200        &mut self,
201        application_id: ApplicationId,
202        chain_id: ChainId,
203        stream_id: StreamId,
204        previous_index: u32,
205        next_index: u32,
206    ) {
207        if next_index == previous_index {
208            return; // No new events in the stream.
209        }
210        self.streams_to_process
211            .entry(application_id)
212            .or_default()
213            .entry((chain_id, stream_id))
214            .and_modify(|(pi, ni)| {
215                *pi = (*pi).min(previous_index);
216                *ni = (*ni).max(next_index);
217            })
218            .or_insert_with(|| (previous_index, next_index));
219    }
220
221    pub fn remove_stream_to_process(
222        &mut self,
223        application_id: ApplicationId,
224        chain_id: ChainId,
225        stream_id: StreamId,
226    ) {
227        let Some(streams) = self.streams_to_process.get_mut(&application_id) else {
228            return;
229        };
230        if streams.remove(&(chain_id, stream_id)).is_some() && streams.is_empty() {
231            self.streams_to_process.remove(&application_id);
232        }
233    }
234
235    pub fn take_streams_to_process(&mut self) -> BTreeMap<ApplicationId, Vec<StreamUpdate>> {
236        mem::take(&mut self.streams_to_process)
237            .into_iter()
238            .map(|(app_id, streams)| {
239                let updates = streams
240                    .into_iter()
241                    .map(
242                        |((chain_id, stream_id), (previous_index, next_index))| StreamUpdate {
243                            chain_id,
244                            stream_id,
245                            previous_index,
246                            next_index,
247                        },
248                    )
249                    .collect();
250                (app_id, updates)
251            })
252            .collect()
253    }
254
255    /// Adds the oracle response to the record.
256    /// If replaying, it also checks that it matches the next replayed one and returns `true`.
257    pub fn replay_oracle_response(
258        &mut self,
259        oracle_response: OracleResponse,
260    ) -> Result<bool, ExecutionError> {
261        let replaying = if let Some(recorded_response) = self.next_replayed_oracle_response()? {
262            ensure!(
263                recorded_response == oracle_response,
264                ExecutionError::OracleResponseMismatch
265            );
266            true
267        } else {
268            false
269        };
270        self.oracle_responses.push(oracle_response);
271        Ok(replaying)
272    }
273
274    /// If in replay mode, returns the next oracle response, or an error if it is missing.
275    ///
276    /// If not in replay mode, `None` is returned, and the caller must execute the actual oracle
277    /// to obtain the value.
278    ///
279    /// In both cases, the value (returned or obtained from the oracle) must be recorded using
280    /// `add_oracle_response`.
281    fn next_replayed_oracle_response(&mut self) -> Result<Option<OracleResponse>, ExecutionError> {
282        let Some(responses) = &mut self.replaying_oracle_responses else {
283            return Ok(None); // Not in replay mode.
284        };
285        let response = responses
286            .next()
287            .ok_or_else(|| ExecutionError::MissingOracleResponse)?;
288        Ok(Some(response))
289    }
290
291    pub fn into_outcome(self) -> Result<TransactionOutcome, ExecutionError> {
292        let TransactionTracker {
293            replaying_oracle_responses,
294            oracle_responses,
295            outgoing_messages,
296            local_time: _,
297            transaction_index: _,
298            next_application_index,
299            next_chain_index,
300            events,
301            blobs,
302            previously_created_blobs: _,
303            operation_result,
304            streams_to_process,
305            blobs_published,
306            free_blob_ids,
307        } = self;
308        ensure!(
309            streams_to_process.is_empty(),
310            ExecutionError::UnprocessedStreams
311        );
312        if let Some(mut responses) = replaying_oracle_responses {
313            ensure!(
314                responses.next().is_none(),
315                ExecutionError::UnexpectedOracleResponse
316            );
317        }
318        let blobs = blobs
319            .into_iter()
320            .map(|(blob_id, content)| Blob::new_with_hash_unchecked(blob_id, content))
321            .collect::<Vec<_>>();
322        Ok(TransactionOutcome {
323            outgoing_messages,
324            oracle_responses,
325            next_application_index,
326            next_chain_index,
327            events,
328            blobs,
329            operation_result: operation_result.unwrap_or_default(),
330            blobs_published,
331            free_blob_ids,
332        })
333    }
334}
335
336#[cfg(with_testing)]
337impl TransactionTracker {
338    /// Creates a new [`TransactionTracker`] for testing, with default values and the given
339    /// oracle responses.
340    pub fn new_replaying(oracle_responses: Vec<OracleResponse>) -> Self {
341        TransactionTracker::new(Timestamp::from(0), 0, 0, 0, Some(oracle_responses), &[])
342    }
343
344    /// Creates a new [`TransactionTracker`] for testing, with default values and oracle responses
345    /// for the given blobs.
346    pub fn new_replaying_blobs<T>(blob_ids: T) -> Self
347    where
348        T: IntoIterator,
349        T::Item: std::borrow::Borrow<BlobId>,
350    {
351        use std::borrow::Borrow;
352
353        let oracle_responses = blob_ids
354            .into_iter()
355            .map(|blob_id| OracleResponse::Blob(*blob_id.borrow()))
356            .collect();
357        TransactionTracker::new_replaying(oracle_responses)
358    }
359}