1use std::collections::BTreeMap;
5
6use iota_sdk_types::{GasCostSummary, ObjectReference, TransactionDigest};
7use serde::{Deserialize, Serialize};
8
9use crate::transaction::TransactionEnvelope;
10
11pub(super) type AuthorityIndex = u8;
16
17#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
25pub enum Attestation {
26 Authority {
29 payload: AttestationData,
30 authority_index: AuthorityIndex,
32 },
33}
34
35#[non_exhaustive]
40#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
41pub enum AttestationData {
42 V1 {
43 computation_units: u64,
47 object_versions: Vec<ObjectReference>,
54 },
55}
56
57#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
60pub struct AttestedTransaction {
61 pub transaction: TransactionEnvelope,
62 pub attestation: Option<Attestation>,
66}
67
68impl Attestation {
69 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
94pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
107pub enum AttestationVerdict {
108 Valid,
111 Inaccurate,
116 Refuted { units: u64 },
121 Undecided,
127}
128
129impl AttestationVerdict {
130 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
166pub struct AttestationRecord {
167 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#[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 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#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
217pub struct AttestationTotals {
218 pub refuted_units_squared: BTreeMap<AuthorityIndex, u64>,
221}
222
223impl AttestationTotals {
224 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 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 #[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 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 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 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 assert_eq!(judge(50 * STEP, STEP, None), AttestationVerdict::Valid);
343 assert_eq!(
345 AttestationVerdict::new(None, 50 * STEP, None, Some(10)),
346 AttestationVerdict::Valid
347 );
348 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 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}