Skip to main content

iota_types/
attestation.rs

1// Copyright (c) 2026 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use std::collections::BTreeMap;
5
6use iota_sdk_types::{GasCostSummary, ObjectReference, TransactionDigest};
7use serde::{Deserialize, Serialize};
8
9use crate::transaction::TransactionEnvelope;
10
11/// Index of a validator in the current epoch's consensus committee. Kept as a
12/// plain `u8` so `iota-types` does not depend on `starfish-config`, whose
13/// `AuthorityIndex(u8)` is BCS-identical; the value is untrusted until checked
14/// against the block author post-consensus.
15pub(super) type AuthorityIndex = u8;
16
17/// A pre-consensus claim produced by a trusted actor certifying that a specific
18/// transaction has been validated before entering consensus. The attestation is
19/// a separate artifact that travels alongside the transaction; the transaction
20/// and the user's signature are completely unchanged.
21///
22/// An enum so that other attestor kinds can be appended later; the variant
23/// order is protocol-significant.
24#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
25pub enum Attestation {
26    /// Produced by the block-proposing validator and authenticated by the
27    /// block signature, so it carries no signature of its own.
28    Authority {
29        payload: AttestationData,
30        /// Index of the attesting validator in the current epoch's committee
31        authority_index: AuthorityIndex,
32    },
33}
34
35/// The attested content carried by every [`Attestation`] variant.
36///
37/// Versioned to allow new fields to be introduced without breaking existing
38/// match arms.
39#[non_exhaustive]
40#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
41pub enum AttestationData {
42    V1 {
43        /// Expected computation units billed by the attestor's dry-run
44        /// (`computation_cost / gas_price`). Used by the sequencer to improve
45        /// shared-object scheduling before execution.
46        computation_units: u64,
47        /// Versions of the run-time-resolved objects the attestor read during
48        /// the dry-run whose version is NOT already pinned by the signed
49        /// `TransactionData`. This covers shared objects,
50        /// Move-authenticator account and function-ref field objects,
51        /// coin-deny-list references, and dynamic fields / child objects loaded
52        /// during execution.
53        object_versions: Vec<ObjectReference>,
54    },
55}
56
57/// A user transaction bundled with its attestation. This is the inner payload
58/// of `ConsensusTransactionKind::UserTransactionV1`.
59#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
60pub struct AttestedTransaction {
61    pub transaction: TransactionEnvelope,
62    /// `None` until validators attest transactions. Reserved now so attaching
63    /// an attestation later leaves the encoding of an unattested transaction
64    /// unchanged.
65    pub attestation: Option<Attestation>,
66}
67
68impl Attestation {
69    /// An attestation by the block-proposing validator at `authority_index`.
70    pub fn new_authority(payload: AttestationData, authority_index: AuthorityIndex) -> Self {
71        Self::Authority {
72            payload,
73            authority_index,
74        }
75    }
76
77    pub fn computation_units(&self) -> u64 {
78        let Attestation::Authority { payload, .. } = self;
79        let AttestationData::V1 {
80            computation_units, ..
81        } = payload;
82        *computation_units
83    }
84
85    pub fn object_versions(&self) -> &[ObjectReference] {
86        let Attestation::Authority { payload, .. } = self;
87        let AttestationData::V1 {
88            object_versions, ..
89        } = payload;
90        object_versions
91    }
92}
93
94/// The computation cost of `gas_cost_summary` in gas units, independent of
95/// the gas price the transaction paid. Rounds down, and is zero when
96/// `gas_price` is zero.
97pub fn computation_units(gas_cost_summary: &GasCostSummary, gas_price: u64) -> u64 {
98    gas_cost_summary
99        .computation_cost
100        .checked_div(gas_price)
101        .unwrap_or(0)
102}
103
104/// The verdict on an attested, executed transaction. The variant order is
105/// protocol-significant: append, never reorder.
106#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
107pub enum AttestationVerdict {
108    /// Not refuted and, whenever the transaction body ran, the claimed
109    /// computation units were within tolerance of the executed ones.
110    Valid,
111    /// Not refuted, but the claimed computation units were not within
112    /// tolerance. An honest claim can land here when a shared object or
113    /// dynamic field the dry run read moved before execution, so this is not
114    /// by itself evidence against the attestor.
115    Inaccurate,
116    /// Authentication failed, and the judge holds the attestor accountable for
117    /// it. `units` is the computation the failed runs consumed: execution's own
118    /// run, whether or not the effects charge it, plus the judge's re-run at the
119    /// recorded versions, when one was needed.
120    Refuted { units: u64 },
121    /// Authentication failed, and the judge could not decide whether the
122    /// attestor or the account is accountable: its re-run at the recorded
123    /// versions failed with an internal error. Nobody pays and the attestor is
124    /// not penalized; certified, so that a node executing from a checkpoint
125    /// charges nobody as well.
126    Undecided,
127}
128
129impl AttestationVerdict {
130    /// `refuted_units` carries the units of both failed runs when the failure
131    /// refutes the attestation. `executed_units` is `None` when the
132    /// transaction body never ran, so the claim cannot be assessed.
133    /// `tolerance_percentage` bounds `|attested - executed|` as a percentage
134    /// of the executed units; `None` disables the accuracy check.
135    pub fn new(
136        refuted_units: Option<u64>,
137        attested_units: u64,
138        executed_units: Option<u64>,
139        tolerance_percentage: Option<u64>,
140    ) -> Self {
141        if let Some(units) = refuted_units {
142            return Self::Refuted { units };
143        }
144        let accurate = match (executed_units, tolerance_percentage) {
145            (Some(executed), Some(tolerance)) => {
146                attested_units.abs_diff(executed).saturating_mul(100)
147                    <= tolerance.saturating_mul(executed)
148            }
149            _ => true,
150        };
151        if accurate {
152            Self::Valid
153        } else {
154            Self::Inaccurate
155        }
156    }
157
158    pub fn is_valid(&self) -> bool {
159        matches!(self, Self::Valid)
160    }
161}
162
163/// The validator's verdict on an attested, executed transaction, certified in
164/// the checkpoint summary unless `Valid`.
165#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
166pub struct AttestationRecord {
167    /// Index of the attestor in the committee of the checkpoint's epoch.
168    pub attestor: AuthorityIndex,
169    pub verdict: AttestationVerdict,
170}
171
172impl AttestationRecord {
173    pub fn new(attestation: &Attestation, verdict: AttestationVerdict) -> Self {
174        let Attestation::Authority {
175            authority_index, ..
176        } = attestation;
177        Self {
178            attestor: *authority_index,
179            verdict,
180        }
181    }
182}
183
184/// A record other than `Valid`, certified in the checkpoint summary at its
185/// transaction's position in the checkpoint contents.
186#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
187pub struct AttestationEntry {
188    pub position: u32,
189    pub record: AttestationRecord,
190}
191
192impl AttestationEntry {
193    /// The records other than `Valid`, each at its position in `records`.
194    ///
195    /// # Panics
196    ///
197    /// If a position does not fit `u32`.
198    pub fn from_records(records: &[Option<AttestationRecord>]) -> Vec<Self> {
199        records
200            .iter()
201            .enumerate()
202            .filter_map(|(position, record)| {
203                let record = (*record).filter(|record| !record.verdict.is_valid())?;
204                Some(Self {
205                    position: u32::try_from(position).expect("checkpoint positions fit u32"),
206                    record,
207                })
208            })
209            .collect()
210    }
211}
212
213/// Per-attestor totals of refuted attestations for the epoch so far,
214/// certified in every checkpoint summary. An attestor without refuted
215/// attestations has no entry.
216#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
217pub struct AttestationTotals {
218    /// Committee index to the sum of the squared units of its `Refuted`
219    /// verdicts since the epoch started; saturating.
220    pub refuted_units_squared: BTreeMap<AuthorityIndex, u64>,
221}
222
223impl AttestationTotals {
224    /// These totals plus the `Refuted` records of one more checkpoint.
225    pub fn with_records(mut self, records: &[Option<AttestationRecord>]) -> Self {
226        for record in records.iter().flatten() {
227            if let AttestationVerdict::Refuted { units } = record.verdict {
228                let sum = self
229                    .refuted_units_squared
230                    .entry(record.attestor)
231                    .or_default();
232                *sum = sum.saturating_add(units.saturating_pow(2));
233            }
234        }
235        self
236    }
237
238    /// These totals plus `other`'s; saturating.
239    pub fn with_totals(mut self, other: &Self) -> Self {
240        for (&attestor, &units_squared) in &other.refuted_units_squared {
241            let sum = self.refuted_units_squared.entry(attestor).or_default();
242            *sum = sum.saturating_add(units_squared);
243        }
244        self
245    }
246}
247
248impl AttestedTransaction {
249    pub fn new(transaction: TransactionEnvelope, attestation: Option<Attestation>) -> Self {
250        Self {
251            transaction,
252            attestation,
253        }
254    }
255
256    pub fn digest(&self) -> &TransactionDigest {
257        self.transaction.digest()
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use crate::{base_types::random_object_ref, utils::create_fake_transaction};
265
266    fn make_attestation_data() -> AttestationData {
267        AttestationData::V1 {
268            computation_units: 1_000_000,
269            object_versions: vec![random_object_ref()],
270        }
271    }
272
273    #[test]
274    fn attestation_data_bcs_round_trip() {
275        let data = make_attestation_data();
276        let encoded = bcs::to_bytes(&data).unwrap();
277        let decoded: AttestationData = bcs::from_bytes(&encoded).unwrap();
278        assert_eq!(decoded, data);
279    }
280
281    #[test]
282    fn attestation_authority_bcs_round_trip() {
283        let attestation = Attestation::Authority {
284            payload: make_attestation_data(),
285            authority_index: 3,
286        };
287        let encoded = bcs::to_bytes(&attestation).unwrap();
288        let decoded: Attestation = bcs::from_bytes(&encoded).unwrap();
289        assert_eq!(decoded, attestation);
290    }
291
292    /// Both sides of the check are `computation_cost / gas_price`, which the
293    /// gas meter rounds up to `gas_rounding_step`, so they are always multiples
294    /// of it and the smallest difference they can show is one step.
295    #[test]
296    fn verdict_accuracy_band() {
297        const STEP: u64 = 1_000;
298        let judge = |attested, executed, tolerance| {
299            AttestationVerdict::new(None, attested, Some(executed), tolerance)
300        };
301
302        // Under ten steps a tenth of the executed units is less than one step,
303        // so only the same value is accurate.
304        assert_eq!(
305            judge(3 * STEP, 3 * STEP, Some(10)),
306            AttestationVerdict::Valid
307        );
308        assert_eq!(
309            judge(4 * STEP, 3 * STEP, Some(10)),
310            AttestationVerdict::Inaccurate
311        );
312        assert_eq!(
313            judge(2 * STEP, 3 * STEP, Some(10)),
314            AttestationVerdict::Inaccurate
315        );
316
317        // At ten steps one step of drift is exactly the allowance.
318        assert_eq!(
319            judge(11 * STEP, 10 * STEP, Some(10)),
320            AttestationVerdict::Valid
321        );
322        assert_eq!(
323            judge(9 * STEP, 10 * STEP, Some(10)),
324            AttestationVerdict::Valid
325        );
326        assert_eq!(
327            judge(12 * STEP, 10 * STEP, Some(10)),
328            AttestationVerdict::Inaccurate
329        );
330
331        // Ten steps either way on a hundred-step transaction.
332        assert_eq!(
333            judge(110 * STEP, 100 * STEP, Some(10)),
334            AttestationVerdict::Valid
335        );
336        assert_eq!(
337            judge(111 * STEP, 100 * STEP, Some(10)),
338            AttestationVerdict::Inaccurate
339        );
340
341        // No tolerance configured disables the check.
342        assert_eq!(judge(50 * STEP, STEP, None), AttestationVerdict::Valid);
343        // A body that never ran cannot be assessed.
344        assert_eq!(
345            AttestationVerdict::new(None, 50 * STEP, None, Some(10)),
346            AttestationVerdict::Valid
347        );
348        // A refutation wins over accuracy and keeps the units of both runs.
349        assert_eq!(
350            AttestationVerdict::new(Some(7 * STEP), 3 * STEP, Some(3 * STEP), Some(10)),
351            AttestationVerdict::Refuted { units: 7 * STEP }
352        );
353    }
354
355    #[test]
356    fn entries_certify_every_record_other_than_valid() {
357        let record = |attestor, verdict| Some(AttestationRecord { attestor, verdict });
358        let entry = |position, attestor, verdict| AttestationEntry {
359            position,
360            record: AttestationRecord { attestor, verdict },
361        };
362
363        let entries = AttestationEntry::from_records(&[
364            record(1, AttestationVerdict::Valid),
365            record(2, AttestationVerdict::Inaccurate),
366            None,
367            record(0, AttestationVerdict::Refuted { units: 3 }),
368            record(1, AttestationVerdict::Undecided),
369        ]);
370
371        assert_eq!(
372            entries,
373            vec![
374                entry(1, 2, AttestationVerdict::Inaccurate),
375                entry(3, 0, AttestationVerdict::Refuted { units: 3 }),
376                entry(4, 1, AttestationVerdict::Undecided),
377            ]
378        );
379    }
380
381    #[test]
382    fn totals_sum_the_squared_units_of_refuted_records() {
383        let record = |attestor, verdict| Some(AttestationRecord { attestor, verdict });
384        let refuted = |units| AttestationVerdict::Refuted { units };
385        let totals = AttestationTotals::default().with_records(&[
386            record(2, refuted(3)),
387            record(1, AttestationVerdict::Valid),
388            record(1, AttestationVerdict::Inaccurate),
389            record(0, AttestationVerdict::Undecided),
390            None,
391            record(2, refuted(25)),
392        ]);
393        assert_eq!(totals.refuted_units_squared, BTreeMap::from([(2, 9 + 625)]));
394
395        // A later checkpoint adds to the running sums.
396        let totals = totals.with_records(&[record(0, refuted(1)), record(2, refuted(2))]);
397        assert_eq!(
398            totals.refuted_units_squared,
399            BTreeMap::from([(0, 1), (2, 9 + 625 + 4)])
400        );
401        assert_eq!(
402            bcs::to_bytes(&AttestationTotals::default()).unwrap(),
403            vec![0],
404            "empty totals cost one byte"
405        );
406    }
407
408    #[test]
409    fn attested_transaction_bcs_round_trip() {
410        let attested = AttestedTransaction::new(
411            create_fake_transaction(),
412            Some(Attestation::Authority {
413                payload: make_attestation_data(),
414                authority_index: 0,
415            }),
416        );
417        let encoded = bcs::to_bytes(&attested).unwrap();
418        let decoded: AttestedTransaction = bcs::from_bytes(&encoded).unwrap();
419        assert_eq!(decoded, attested);
420    }
421}