Skip to main content

iota_types/
quorum_driver_types.rs

1// Copyright (c) 2021, Facebook, Inc. and its affiliates
2// Copyright (c) Mysten Labs, Inc.
3// Modifications Copyright (c) 2024 IOTA Stiftung
4// SPDX-License-Identifier: Apache-2.0
5
6use std::collections::BTreeMap;
7
8use iota_sdk_types::{ObjectReference, TransactionDigest, TransactionEffects, TransactionEvents};
9use itertools::Itertools;
10use serde::{Deserialize, Serialize};
11use strum::AsRefStr;
12use thiserror::Error;
13
14use crate::{
15    base_types::{AuthorityName, EpochId},
16    committee::{QUORUM_THRESHOLD, StakeUnit, TOTAL_VOTING_POWER},
17    crypto::{AuthorityStrongQuorumSignInfo, ConciseAuthorityPublicKeyBytes},
18    effects::{CertifiedTransactionEffects, VerifiedCertifiedTransactionEffects},
19    error::IotaError,
20    messages_checkpoint::CheckpointSequenceNumber,
21    object::Object,
22    transaction::TransactionEnvelope,
23};
24
25pub type QuorumDriverResult = Result<QuorumDriverResponse, QuorumDriverError>;
26
27pub type QuorumDriverEffectsQueueResult =
28    Result<(TransactionEnvelope, QuorumDriverResponse), (TransactionDigest, QuorumDriverError)>;
29
30pub const NON_RECOVERABLE_ERROR_MSG: &str =
31    "Transaction has non recoverable errors from at least 1/3 of validators";
32
33/// Client facing errors regarding transaction submission via Quorum Driver.
34/// Every invariant needs detailed documents to instruct client handling.
35#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Error, Hash, AsRefStr)]
36pub enum QuorumDriverError {
37    #[error("QuorumDriver internal error: {0}.")]
38    QuorumDriverInternal(IotaError),
39    #[error("Invalid user signature: {0}.")]
40    InvalidUserSignature(IotaError),
41    /// The fullnode's local validity check proved the transaction invalid.
42    /// The same bytes can never execute.
43    #[error("Invalid transaction: {0}.")]
44    InvalidTransaction(IotaError),
45    #[error(
46        "Failed to sign transaction by a quorum of validators because of locked objects: {conflicting_txes:?}"
47    )]
48    ObjectsDoubleUsed {
49        conflicting_txes:
50            BTreeMap<TransactionDigest, (Vec<(AuthorityName, ObjectReference)>, StakeUnit)>,
51    },
52    #[error("Transaction timed out before reaching finality")]
53    TimeoutBeforeFinality,
54    /// The fullnode resubmitted the transaction until its finality timeout.
55    /// The last attempt's error says what kept it from finalizing. Handled
56    /// by clients as `TimeoutBeforeFinality`.
57    #[error(
58        "Transaction timed out before reaching finality. Last recorded retriable error: {last_error}"
59    )]
60    TimeoutBeforeFinalityWithErrors { last_error: String },
61    #[error(
62        "Transaction failed to reach finality with transient error after {total_attempts} attempts."
63    )]
64    FailedWithTransientErrorAfterMaximumAttempts { total_attempts: u32 },
65    #[error("{NON_RECOVERABLE_ERROR_MSG}: {errors:?}.")]
66    NonRecoverableTransactionError { errors: GroupedErrors },
67    #[error(
68        "Transaction is not processed because {overloaded_stake} of validators by stake are overloaded with certificates pending execution."
69    )]
70    SystemOverload {
71        overloaded_stake: StakeUnit,
72        errors: GroupedErrors,
73    },
74    #[error("Transaction is already finalized but with different user signatures")]
75    TxAlreadyFinalizedWithDifferentUserSignatures,
76    #[error(
77        "Transaction is not processed because {overload_stake} of validators are overloaded and asked client to retry after {retry_after_secs}."
78    )]
79    SystemOverloadRetryAfter {
80        overload_stake: StakeUnit,
81        errors: GroupedErrors,
82        retry_after_secs: u64,
83    },
84    /// Over 1/3 of validator stake rejected the transaction during
85    /// submission. The verdicts may depend on validator-local state, and an
86    /// earlier submission attempt may already be in consensus, so the
87    /// transaction may still execute. `errors` holds the validators' reasons,
88    /// grouped by message and sorted by stake.
89    #[error(
90        "Transaction rejected by more than 1/3 of validator stake during submission: {errors:?}."
91    )]
92    RejectedByValidators { errors: Vec<String> },
93}
94
95impl QuorumDriverError {
96    /// Stable machine-readable discriminant for clients. The JSON-RPC layer
97    /// exposes it as the error object's `data.reason` field on errors whose
98    /// `data` was previously empty. `ObjectsDoubleUsed` is the exception: it
99    /// keeps its pre-existing conflicting-transactions `data` payload.
100    pub fn reason(&self) -> &'static str {
101        match self {
102            QuorumDriverError::QuorumDriverInternal(_) => "internal",
103            QuorumDriverError::InvalidUserSignature(_) => "invalid_user_signature",
104            QuorumDriverError::InvalidTransaction(_) => "invalid_transaction",
105            QuorumDriverError::RejectedByValidators { .. } => "rejected_by_validators",
106            QuorumDriverError::ObjectsDoubleUsed { .. } => "objects_double_used",
107            QuorumDriverError::TimeoutBeforeFinality
108            | QuorumDriverError::TimeoutBeforeFinalityWithErrors { .. } => {
109                "timeout_before_finality"
110            }
111            QuorumDriverError::FailedWithTransientErrorAfterMaximumAttempts { .. } => {
112                "failed_with_transient_error_after_maximum_attempts"
113            }
114            QuorumDriverError::NonRecoverableTransactionError { .. } => {
115                "non_recoverable_transaction_error"
116            }
117            QuorumDriverError::SystemOverload { .. } => "system_overload",
118            QuorumDriverError::TxAlreadyFinalizedWithDifferentUserSignatures => {
119                "tx_already_finalized_with_different_user_signatures"
120            }
121            QuorumDriverError::SystemOverloadRetryAfter { .. } => "system_overload_retry_after",
122        }
123    }
124
125    pub fn to_error_message(&self) -> String {
126        match self {
127            QuorumDriverError::InvalidUserSignature(err) => {
128                format!("Invalid user signature: {err}")
129            }
130            QuorumDriverError::InvalidTransaction(err) => {
131                format!("Invalid transaction: {err}")
132            }
133            QuorumDriverError::RejectedByValidators { errors } => input_errors_message(errors),
134            QuorumDriverError::TxAlreadyFinalizedWithDifferentUserSignatures => {
135                "The transaction is already finalized but with different user signatures"
136                    .to_string()
137            }
138            QuorumDriverError::TimeoutBeforeFinality
139            | QuorumDriverError::TimeoutBeforeFinalityWithErrors { .. }
140            | QuorumDriverError::FailedWithTransientErrorAfterMaximumAttempts { .. }
141            | QuorumDriverError::SystemOverload { .. }
142            | QuorumDriverError::SystemOverloadRetryAfter { .. } => self.to_string(),
143            QuorumDriverError::ObjectsDoubleUsed { conflicting_txes } => {
144                let weights: Vec<u64> =
145                    conflicting_txes.values().map(|(_, stake)| *stake).collect();
146                let remaining: u64 = TOTAL_VOTING_POWER - weights.iter().sum::<u64>();
147
148                // better version of above
149                let reason = if weights.iter().all(|w| remaining + w < QUORUM_THRESHOLD) {
150                    "equivocated until the next epoch"
151                } else {
152                    "reserved for another transaction"
153                };
154
155                format!(
156                    "Failed to sign transaction by a quorum of validators because one or more of its objects is {}. Other transactions locking these objects:\n{}",
157                    reason,
158                    conflicting_txes
159                        .iter()
160                        .sorted_by(|(_, (_, a)), (_, (_, b))| b.cmp(a))
161                        .map(|(digest, (_, stake))| format!(
162                            "- {} (stake {}.{})",
163                            digest,
164                            stake / 100,
165                            stake % 100,
166                        ))
167                        .join("\n"),
168                )
169            }
170            QuorumDriverError::NonRecoverableTransactionError { errors } => {
171                let new_errors: Vec<String> = errors
172                    .iter()
173                    // sort by total stake, descending, so users see the most prominent one
174                    // first
175                    .sorted_by(|(_, a, _), (_, b, _)| b.cmp(a))
176                    .filter_map(|(err, _, _)| {
177                        match &err {
178                            // Special handling of UserInputError:
179                            // ObjectNotFound and DependentPackageNotFound are considered
180                            // retryable errors but they have different treatment
181                            // in AuthorityAggregator.
182                            // The optimal fix would be to examine if the total stake
183                            // of ObjectNotFound/DependentPackageNotFound exceeds the
184                            // quorum threshold, but it takes a Committee here.
185                            // So, we take an easier route and consider them non-retryable
186                            // at all. Combining this with the sorting above, clients will
187                            // see the dominant error first.
188                            IotaError::UserInput { error } => Some(error.to_string()),
189                            _ => {
190                                if err.is_retryable().0 {
191                                    None
192                                } else {
193                                    Some(err.to_string())
194                                }
195                            }
196                        }
197                    })
198                    .collect();
199
200                // The aggregator builds this variant only from errors with
201                // non-retryable stake, but rendering an error must never
202                // panic: fall back to the unfiltered list.
203                if new_errors.is_empty() {
204                    let error_list = errors.iter().map(|(err, _, _)| err.to_string()).join(", ");
205                    return format!("{NON_RECOVERABLE_ERROR_MSG}: {error_list}.");
206                }
207
208                input_errors_message(&new_errors)
209            }
210            QuorumDriverError::QuorumDriverInternal { .. } => {
211                "Internal error occurred while executing transaction.".to_string()
212            }
213        }
214    }
215}
216
217/// Same text for a rejection by validators in both transaction flows.
218fn input_errors_message(errors: &[String]) -> String {
219    format!(
220        "Transaction execution failed due to issues with transaction inputs, please review the errors and try again:\n{}",
221        errors.iter().map(|err| format!("- {err}")).join("\n")
222    )
223}
224
225pub type GroupedErrors = Vec<(IotaError, StakeUnit, Vec<ConciseAuthorityPublicKeyBytes>)>;
226
227#[derive(Serialize, Deserialize, Clone, Debug)]
228pub enum ExecuteTransactionRequestType {
229    WaitForEffectsCert,
230    WaitForLocalExecution,
231}
232
233#[derive(Serialize, Deserialize, Clone, Debug)]
234pub enum EffectsFinalityInfo {
235    Certified(AuthorityStrongQuorumSignInfo),
236    Checkpointed(EpochId, CheckpointSequenceNumber),
237    /// A quorum of validators have acknowledged effects (used in
238    /// TransactionDriver flow).
239    QuorumExecuted(EpochId),
240
241    /// Effects from a single validator without quorum certification.
242    /// The caller MUST wait for local checkpoint execution before returning
243    /// these to the client, as they have not been certified by a quorum.
244    UncertifiedSingleValidator(EpochId),
245}
246
247/// When requested to execute a transaction with WaitForLocalExecution,
248/// TransactionOrchestrator attempts to execute this transaction locally
249/// after it is finalized. This value represents whether the transaction
250/// is confirmed to be executed on this node before the response returns.
251pub type IsTransactionExecutedLocally = bool;
252
253#[derive(Debug, Clone)]
254pub struct QuorumDriverResponse {
255    pub effects_cert: VerifiedCertifiedTransactionEffects,
256    // pub events: TransactionEvents,
257    pub events: Option<TransactionEvents>,
258    // Input objects will only be populated in the happy path
259    pub input_objects: Option<Vec<Object>>,
260    // Output objects will only be populated in the happy path
261    pub output_objects: Option<Vec<Object>>,
262    pub auxiliary_data: Option<Vec<u8>>,
263}
264
265#[derive(Serialize, Deserialize, Clone, Debug)]
266pub struct ExecuteTransactionRequestV1 {
267    pub transaction: TransactionEnvelope,
268
269    pub include_events: bool,
270    pub include_input_objects: bool,
271    pub include_output_objects: bool,
272    pub include_auxiliary_data: bool,
273}
274
275impl ExecuteTransactionRequestV1 {
276    pub fn new<T: Into<TransactionEnvelope>>(transaction: T) -> Self {
277        Self {
278            transaction: transaction.into(),
279            include_events: true,
280            include_input_objects: false,
281            include_output_objects: false,
282            include_auxiliary_data: false,
283        }
284    }
285}
286
287#[derive(Serialize, Deserialize, Clone, Debug)]
288pub struct ExecuteTransactionResponseV1 {
289    pub effects: FinalizedEffects,
290
291    pub events: Option<TransactionEvents>,
292    // Input objects will only be populated in the happy path
293    pub input_objects: Option<Vec<Object>>,
294    // Output objects will only be populated in the happy path
295    pub output_objects: Option<Vec<Object>>,
296    pub auxiliary_data: Option<Vec<u8>>,
297}
298
299#[derive(Serialize, Deserialize, Clone, Debug)]
300pub struct FinalizedEffects {
301    pub effects: TransactionEffects,
302    pub finality_info: EffectsFinalityInfo,
303}
304
305impl FinalizedEffects {
306    pub fn new_from_effects_cert(effects_cert: CertifiedTransactionEffects) -> Self {
307        let (data, sig) = effects_cert.into_data_and_sig();
308        Self {
309            effects: data,
310            finality_info: EffectsFinalityInfo::Certified(sig),
311        }
312    }
313
314    pub fn epoch(&self) -> EpochId {
315        match &self.finality_info {
316            EffectsFinalityInfo::Certified(cert) => cert.epoch,
317            EffectsFinalityInfo::Checkpointed(epoch, _)
318            | EffectsFinalityInfo::QuorumExecuted(epoch)
319            | EffectsFinalityInfo::UncertifiedSingleValidator(epoch) => *epoch,
320        }
321    }
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    /// Rendering must not panic when filtering leaves no non-retryable
329    /// error.
330    #[test]
331    fn non_recoverable_error_rendering_survives_empty_filter() {
332        let error = QuorumDriverError::NonRecoverableTransactionError {
333            errors: vec![(
334                IotaError::ValidatorOverloadedRetryAfter {
335                    retry_after_secs: 1,
336                },
337                0,
338                vec![],
339            )],
340        };
341        assert!(error.to_error_message().contains(NON_RECOVERABLE_ERROR_MSG));
342    }
343}