Skip to main content

iota_graphql_rpc/types/
epoch.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::collections::{BTreeMap, BTreeSet, HashMap};
6
7use async_graphql::{connection::Connection, dataloader::Loader, *};
8use diesel::{ExpressionMethods, OptionalExtension, QueryDsl, SelectableHelper};
9use fastcrypto::encoding::{Base58, Encoding};
10use iota_indexer::{models::epoch::QueryableEpochInfo, schema::epochs};
11use iota_sdk_types::CheckpointCommitment as EpochCommitment;
12
13use crate::{
14    config::DEFAULT_PAGE_SIZE,
15    context_data::db_data_provider::PgManager,
16    data::{DataLoader, Db, DbConnection, QueryExecutor},
17    error::Error,
18    server::watermark_task::Watermark,
19    types::{
20        big_int::BigInt,
21        chain_identifier::ChainIdentifierCache,
22        checkpoint::{self, Checkpoint, CheckpointConnection},
23        cursor::Page,
24        date_time::DateTime,
25        protocol_config::ProtocolConfigs,
26        system_state_summary::{NativeStateValidatorInfo, SystemStateSummary},
27        transaction_block::{
28            self, TransactionBlock, TransactionBlockConnection, TransactionBlockFilter,
29        },
30        uint53::UInt53,
31        validator_set::ValidatorSet,
32    },
33};
34
35#[derive(Clone)]
36pub(crate) struct Epoch {
37    pub stored: QueryableEpochInfo,
38    pub checkpoint_viewed_at: u64,
39}
40
41/// `DataLoader` key for fetching an `Epoch` by its ID, optionally constrained
42/// by a consistency cursor.
43#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
44struct EpochKey {
45    pub epoch_id: u64,
46    pub checkpoint_viewed_at: u64,
47}
48
49/// Operation of the IOTA network is temporally partitioned into non-overlapping
50/// epochs, and the network aims to keep epochs roughly the same duration as
51/// each other. During a particular epoch the following data is fixed:
52///
53/// - the protocol version
54/// - the reference gas price
55/// - the set of participating validators
56#[Object]
57impl Epoch {
58    /// The epoch's id as a sequence number that starts at 0 and is incremented
59    /// by one at every epoch change.
60    async fn epoch_id(&self) -> Result<UInt53> {
61        UInt53::try_from(self.stored.epoch as u64).extend()
62    }
63
64    /// The minimum gas price that a quorum of validators are guaranteed to sign
65    /// a transaction for.
66    async fn reference_gas_price(&self) -> Option<BigInt> {
67        Some(BigInt::from(self.stored.reference_gas_price as u64))
68    }
69
70    /// Validator related properties, including the active validators.
71    ///
72    /// For epochs other than the current the data provided refer to the start
73    /// of the epoch.
74    async fn validator_set(&self, ctx: &Context<'_>) -> Result<Option<ValidatorSet>> {
75        let system_state = ctx
76            .data_unchecked::<PgManager>()
77            .fetch_iota_system_state(Some(self.stored.epoch as u64))
78            .await?;
79
80        let validator_set = NativeStateValidatorInfo::from(system_state).into_validator_set(
81            self.stored.total_stake as u64,
82            self.checkpoint_viewed_at,
83            self.stored.epoch as u64,
84        )?;
85        Ok(Some(validator_set))
86    }
87
88    /// The epoch's starting timestamp.
89    async fn start_timestamp(&self) -> Result<DateTime, Error> {
90        DateTime::from_ms(self.stored.epoch_start_timestamp)
91    }
92
93    /// The epoch's ending timestamp.
94    async fn end_timestamp(&self) -> Result<Option<DateTime>, Error> {
95        self.stored
96            .epoch_end_timestamp
97            .map(DateTime::from_ms)
98            .transpose()
99    }
100
101    /// The total number of checkpoints in this epoch.
102    async fn total_checkpoints(&self, ctx: &Context<'_>) -> Result<Option<UInt53>> {
103        let last = match self.stored.last_checkpoint_id {
104            Some(last) => last as u64,
105            None => {
106                let Watermark { checkpoint, .. } = *ctx.data_unchecked();
107                checkpoint
108            }
109        };
110
111        Ok(Some(
112            UInt53::try_from(last - self.stored.first_checkpoint_id as u64 + 1).extend()?,
113        ))
114    }
115
116    /// The total number of transaction blocks in this epoch.
117    async fn total_transactions(&self) -> Result<Option<UInt53>> {
118        // TODO: this currently returns None for the current epoch. Fix this.
119        self.stored
120            .epoch_total_transactions()
121            .map(|v| UInt53::try_from(v as u64))
122            .transpose()
123            .extend()
124    }
125
126    /// The total amount of gas fees (in NANOS) that were paid in this epoch.
127    async fn total_gas_fees(&self) -> Option<BigInt> {
128        self.stored.total_gas_fees.map(BigInt::from)
129    }
130
131    /// The total NANOS rewarded as stake.
132    async fn total_stake_rewards(&self) -> Option<BigInt> {
133        self.stored
134            .total_stake_rewards_distributed
135            .map(BigInt::from)
136    }
137
138    /// The storage fund available in this epoch.
139    /// This fund is used to redistribute storage fees from past transactions
140    /// to future validators.
141    async fn fund_size(&self) -> Option<BigInt> {
142        Some(BigInt::from(self.stored.storage_fund_balance))
143    }
144
145    /// The difference between the fund inflow and outflow, representing
146    /// the net amount of storage fees accumulated in this epoch.
147    async fn net_inflow(&self) -> Option<BigInt> {
148        if let (Some(fund_inflow), Some(fund_outflow)) =
149            (self.stored.storage_charge, self.stored.storage_rebate)
150        {
151            Some(BigInt::from(fund_inflow - fund_outflow))
152        } else {
153            None
154        }
155    }
156
157    /// The storage fees paid for transactions executed during the epoch.
158    async fn fund_inflow(&self) -> Option<BigInt> {
159        self.stored.storage_charge.map(BigInt::from)
160    }
161
162    /// The storage fee rebates paid to users who deleted the data associated
163    /// with past transactions.
164    async fn fund_outflow(&self) -> Option<BigInt> {
165        self.stored.storage_rebate.map(BigInt::from)
166    }
167
168    /// The epoch's corresponding protocol configuration, including the feature
169    /// flags and the configuration options.
170    async fn protocol_configs(&self, ctx: &Context<'_>) -> Result<ProtocolConfigs> {
171        ProtocolConfigs::query(ctx.data_unchecked(), Some(self.protocol_version()))
172            .await
173            .extend()
174    }
175
176    #[graphql(flatten)]
177    async fn system_state_summary(&self, ctx: &Context<'_>) -> Result<SystemStateSummary> {
178        let mut state = ctx
179            .data_unchecked::<PgManager>()
180            .fetch_iota_system_state(Some(self.stored.epoch as u64))
181            .await?;
182        let chain = ctx
183            .data_unchecked::<ChainIdentifierCache>()
184            .read(ctx.data_unchecked(), ctx.data_unchecked())
185            .await
186            .extend()?
187            .into_inner()
188            .chain();
189        state.apply_protocol_config_validator_parameters(chain);
190        Ok(SystemStateSummary { native: state })
191    }
192
193    /// A commitment by the committee at the end of epoch on the contents of the
194    /// live object set at that time. This can be used to verify state
195    /// snapshots.
196    async fn live_object_set_digest(&self) -> Result<Option<String>> {
197        let Some(commitments) = self.stored.epoch_commitments.as_ref() else {
198            return Ok(None);
199        };
200        let commitments: Vec<EpochCommitment> = bcs::from_bytes(commitments).map_err(|e| {
201            Error::Internal(format!("Error deserializing commitments: {e}")).extend()
202        })?;
203
204        let digest = commitments.into_iter().next().map(|commitment| {
205            let EpochCommitment::EcmhLiveObjectSet { digest } = commitment else {
206                panic!("a new CheckpointCommitment variant was added and must be handled")
207            };
208            Base58::encode(digest.into_bytes())
209        });
210
211        Ok(digest)
212    }
213
214    /// The epoch's corresponding checkpoints.
215    async fn checkpoints(
216        &self,
217        ctx: &Context<'_>,
218        first: Option<u64>,
219        after: Option<checkpoint::Cursor>,
220        last: Option<u64>,
221        before: Option<checkpoint::Cursor>,
222    ) -> Result<CheckpointConnection> {
223        let page = Page::from_params(ctx.data_unchecked(), first, after, last, before)?;
224        let epoch = self.stored.epoch as u64;
225        Checkpoint::paginate(
226            ctx.data_unchecked(),
227            page,
228            Some(epoch),
229            self.checkpoint_viewed_at,
230        )
231        .await
232        .extend()
233    }
234
235    /// The epoch's corresponding transaction blocks.
236    #[graphql(
237        complexity = "first.or(last).unwrap_or(DEFAULT_PAGE_SIZE as u64) as usize * child_complexity"
238    )]
239    async fn transaction_blocks(
240        &self,
241        ctx: &Context<'_>,
242        first: Option<u64>,
243        after: Option<transaction_block::Cursor>,
244        last: Option<u64>,
245        before: Option<transaction_block::Cursor>,
246        filter: Option<TransactionBlockFilter>,
247    ) -> Result<TransactionBlockConnection> {
248        let page = Page::from_params(ctx.data_unchecked(), first, after, last, before)?;
249
250        let Some(filter) = filter
251            .unwrap_or_default()
252            .intersect(TransactionBlockFilter {
253                // If `first_checkpoint_id` is 0, we include the 0th checkpoint by leaving it None
254                after_checkpoint: (self.stored.first_checkpoint_id > 0)
255                    .then(|| UInt53::try_from(self.stored.first_checkpoint_id as u64 - 1))
256                    .transpose()
257                    .extend()?,
258                before_checkpoint: self
259                    .stored
260                    .last_checkpoint_id
261                    .map(|id| UInt53::try_from(id as u64 + 1))
262                    .transpose()
263                    .extend()?,
264                ..Default::default()
265            })
266        else {
267            return Ok(Connection::with_additional_fields(
268                false,
269                false,
270                Default::default(),
271            ));
272        };
273
274        TransactionBlock::paginate(ctx, page, filter, self.checkpoint_viewed_at)
275            .await
276            .extend()
277    }
278}
279
280impl Epoch {
281    /// The epoch's protocol version.
282    pub(crate) fn protocol_version(&self) -> u64 {
283        self.stored.protocol_version as u64
284    }
285
286    /// Look up an `Epoch` in the database, optionally filtered by its Epoch ID.
287    /// If no ID is supplied, defaults to fetching the latest epoch.
288    pub(crate) async fn query(
289        ctx: &Context<'_>,
290        filter: Option<u64>,
291        checkpoint_viewed_at: u64,
292    ) -> Result<Option<Self>, Error> {
293        if let Some(epoch_id) = filter {
294            let DataLoader(dl) = ctx.data_unchecked();
295            dl.load_one(EpochKey {
296                epoch_id,
297                checkpoint_viewed_at,
298            })
299            .await
300        } else {
301            Self::query_latest_at(ctx.data_unchecked(), checkpoint_viewed_at).await
302        }
303    }
304
305    /// Look up the latest `Epoch` from the database, optionally filtered by a
306    /// consistency cursor (querying for a consistency cursor in the past
307    /// looks for the latest epoch as of that cursor).
308    pub(crate) async fn query_latest_at(
309        db: &Db,
310        checkpoint_viewed_at: u64,
311    ) -> Result<Option<Self>, Error> {
312        use epochs::dsl;
313
314        let stored: Option<QueryableEpochInfo> = db
315            .execute(move |conn| {
316                conn.first(move || {
317                    // Bound the query on `checkpoint_viewed_at` by filtering for the epoch
318                    // whose `first_checkpoint_id <= checkpoint_viewed_at`, selecting the epoch
319                    // with the largest `first_checkpoint_id` among the filtered set.
320                    dsl::epochs
321                        .select(QueryableEpochInfo::as_select())
322                        .filter(dsl::first_checkpoint_id.le(checkpoint_viewed_at as i64))
323                        .order_by(dsl::first_checkpoint_id.desc())
324                })
325                .optional()
326            })
327            .await
328            .map_err(|e| Error::Internal(format!("Failed to fetch epoch: {e}")))?;
329
330        Ok(stored.map(|stored| Epoch {
331            stored,
332            checkpoint_viewed_at,
333        }))
334    }
335}
336
337impl Loader<EpochKey> for Db {
338    type Value = Epoch;
339    type Error = Error;
340
341    async fn load(&self, keys: &[EpochKey]) -> Result<HashMap<EpochKey, Epoch>, Error> {
342        use epochs::dsl;
343
344        let epoch_ids: BTreeSet<_> = keys.iter().map(|key| key.epoch_id as i64).collect();
345        let epochs: Vec<QueryableEpochInfo> = self
346            .execute_repeatable(move |conn| {
347                conn.results(move || {
348                    dsl::epochs
349                        .select(QueryableEpochInfo::as_select())
350                        .filter(dsl::epoch.eq_any(epoch_ids.iter().cloned()))
351                })
352            })
353            .await
354            .map_err(|e| Error::Internal(format!("Failed to fetch epochs: {e}")))?;
355
356        let epoch_id_to_stored: BTreeMap<_, _> = epochs
357            .into_iter()
358            .map(|stored| (stored.epoch as u64, stored))
359            .collect();
360
361        Ok(keys
362            .iter()
363            .filter_map(|key| {
364                let stored = epoch_id_to_stored.get(&key.epoch_id).cloned()?;
365                let epoch = Epoch {
366                    stored,
367                    checkpoint_viewed_at: key.checkpoint_viewed_at,
368                };
369
370                // We filter by checkpoint viewed at in memory because it should be quite rare
371                // that this query actually filters something (only in edge
372                // cases), and not trying to encode it in the SQL query makes
373                // the query much simpler and therefore easier for
374                // the DB to plan.
375                let start = epoch.stored.first_checkpoint_id as u64;
376                (key.checkpoint_viewed_at >= start).then_some((*key, epoch))
377            })
378            .collect())
379    }
380}