snarkvm_ledger/
get.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
19    /// Returns the committee for the given `block height`.
20    pub fn get_committee(&self, block_height: u32) -> Result<Option<Committee<N>>> {
21        self.vm.finalize_store().committee_store().get_committee(block_height)
22    }
23
24    /// Returns the committee for the given `round`.
25    pub fn get_committee_for_round(&self, round: u64) -> Result<Option<Committee<N>>> {
26        // Check if the committee is already in the cache.
27        if let Some(committee) = self.committee_cache.lock().get(&round) {
28            return Ok(Some(committee.clone()));
29        }
30
31        match self.vm.finalize_store().committee_store().get_committee_for_round(round)? {
32            // Return the committee if it exists.
33            Some(committee) => {
34                // Insert the committee into the cache.
35                self.committee_cache.lock().push(round, committee.clone());
36                // Return the committee.
37                Ok(Some(committee))
38            }
39            // Return the current committee if the round is equivalent.
40            None => {
41                // Retrieve the current committee.
42                let current_committee = self.latest_committee()?;
43                // Return the current committee if the round is equivalent.
44                match current_committee.starting_round() == round {
45                    true => Ok(Some(current_committee)),
46                    false => Ok(None),
47                }
48            }
49        }
50    }
51
52    /// Returns the committee lookback for the given round.
53    pub fn get_committee_lookback_for_round(&self, round: u64) -> Result<Option<Committee<N>>> {
54        // Get the round number for the previous committee. Note, we subtract 2 from odd rounds,
55        // because committees are updated in even rounds.
56        let previous_round = match round % 2 == 0 {
57            true => round.saturating_sub(1),
58            false => round.saturating_sub(2),
59        };
60
61        // Get the committee lookback round.
62        let committee_lookback_round = previous_round.saturating_sub(Committee::<N>::COMMITTEE_LOOKBACK_RANGE);
63
64        // Retrieve the committee for the committee lookback round.
65        self.get_committee_for_round(committee_lookback_round)
66    }
67
68    /// Returns the state root that contains the given `block height`.
69    pub fn get_state_root(&self, block_height: u32) -> Result<Option<N::StateRoot>> {
70        self.vm.block_store().get_state_root(block_height)
71    }
72
73    /// Returns a state path for the given commitment.
74    pub fn get_state_path_for_commitment(&self, commitment: &Field<N>) -> Result<StatePath<N>> {
75        self.vm.block_store().get_state_path_for_commitment(commitment)
76    }
77
78    /// Returns the epoch hash for the given block height.
79    pub fn get_epoch_hash(&self, block_height: u32) -> Result<N::BlockHash> {
80        // Compute the epoch number from the current block height.
81        let epoch_number = block_height.saturating_div(N::NUM_BLOCKS_PER_EPOCH);
82        // Compute the epoch starting height (a multiple of `NUM_BLOCKS_PER_EPOCH`).
83        let epoch_starting_height = epoch_number.saturating_mul(N::NUM_BLOCKS_PER_EPOCH);
84        // Retrieve the epoch hash, defined as the 'previous block hash' from the epoch starting height.
85        let epoch_hash = self.get_previous_hash(epoch_starting_height)?;
86        // Construct the epoch hash.
87        Ok(epoch_hash)
88    }
89
90    /// Returns the block for the given block height.
91    pub fn get_block(&self, height: u32) -> Result<Block<N>> {
92        // If the height is 0, return the genesis block.
93        if height == 0 {
94            return Ok(self.genesis_block.clone());
95        }
96        // Retrieve the block hash.
97        let block_hash = match self.vm.block_store().get_block_hash(height)? {
98            Some(block_hash) => block_hash,
99            None => bail!("Block {height} does not exist in storage"),
100        };
101        // Retrieve the block.
102        match self.vm.block_store().get_block(&block_hash)? {
103            Some(block) => Ok(block),
104            None => bail!("Block {height} ('{block_hash}') does not exist in storage"),
105        }
106    }
107
108    /// Returns the blocks in the given block range.
109    /// The range is inclusive of the start and exclusive of the end.
110    pub fn get_blocks(&self, heights: Range<u32>) -> Result<Vec<Block<N>>> {
111        cfg_into_iter!(heights).map(|height| self.get_block(height)).collect()
112    }
113
114    /// Returns the block for the given block hash.
115    pub fn get_block_by_hash(&self, block_hash: &N::BlockHash) -> Result<Block<N>> {
116        // Retrieve the block.
117        match self.vm.block_store().get_block(block_hash)? {
118            Some(block) => Ok(block),
119            None => bail!("Block '{block_hash}' does not exist in storage"),
120        }
121    }
122
123    /// Returns the block height for the given block hash.
124    pub fn get_height(&self, block_hash: &N::BlockHash) -> Result<u32> {
125        match self.vm.block_store().get_block_height(block_hash)? {
126            Some(height) => Ok(height),
127            None => bail!("Missing block height for block '{block_hash}'"),
128        }
129    }
130
131    /// Returns the block hash for the given block height.
132    pub fn get_hash(&self, height: u32) -> Result<N::BlockHash> {
133        // If the height is 0, return the genesis block hash.
134        if height == 0 {
135            return Ok(self.genesis_block.hash());
136        }
137        match self.vm.block_store().get_block_hash(height)? {
138            Some(block_hash) => Ok(block_hash),
139            None => bail!("Missing block hash for block {height}"),
140        }
141    }
142
143    /// Returns the previous block hash for the given block height.
144    pub fn get_previous_hash(&self, height: u32) -> Result<N::BlockHash> {
145        // If the height is 0, return the default block hash.
146        if height == 0 {
147            return Ok(N::BlockHash::default());
148        }
149        match self.vm.block_store().get_previous_block_hash(height)? {
150            Some(previous_hash) => Ok(previous_hash),
151            None => bail!("Missing previous block hash for block {height}"),
152        }
153    }
154
155    /// Returns the block header for the given block height.
156    pub fn get_header(&self, height: u32) -> Result<Header<N>> {
157        // If the height is 0, return the genesis block header.
158        if height == 0 {
159            return Ok(*self.genesis_block.header());
160        }
161        // Retrieve the block hash.
162        let block_hash = match self.vm.block_store().get_block_hash(height)? {
163            Some(block_hash) => block_hash,
164            None => bail!("Block {height} does not exist in storage"),
165        };
166        // Retrieve the block header.
167        match self.vm.block_store().get_block_header(&block_hash)? {
168            Some(header) => Ok(header),
169            None => bail!("Missing block header for block {height}"),
170        }
171    }
172
173    /// Returns the block transactions for the given block height.
174    pub fn get_transactions(&self, height: u32) -> Result<Transactions<N>> {
175        // If the height is 0, return the genesis block transactions.
176        if height == 0 {
177            return Ok(self.genesis_block.transactions().clone());
178        }
179        // Retrieve the block hash.
180        let Some(block_hash) = self.vm.block_store().get_block_hash(height)? else {
181            bail!("Block {height} does not exist in storage");
182        };
183        // Retrieve the block transaction.
184        match self.vm.block_store().get_block_transactions(&block_hash)? {
185            Some(transactions) => Ok(transactions),
186            None => bail!("Missing block transactions for block {height}"),
187        }
188    }
189
190    /// Returns the aborted transaction IDs for the given block height.
191    pub fn get_aborted_transaction_ids(&self, height: u32) -> Result<Vec<N::TransactionID>> {
192        // If the height is 0, return the genesis block aborted transaction IDs.
193        if height == 0 {
194            return Ok(self.genesis_block.aborted_transaction_ids().clone());
195        }
196        // Retrieve the block hash.
197        let Some(block_hash) = self.vm.block_store().get_block_hash(height)? else {
198            bail!("Block {height} does not exist in storage");
199        };
200        // Retrieve the aborted transaction IDs.
201        match self.vm.block_store().get_block_aborted_transaction_ids(&block_hash)? {
202            Some(aborted_transaction_ids) => Ok(aborted_transaction_ids),
203            None => bail!("Missing aborted transaction IDs for block {height}"),
204        }
205    }
206
207    /// Returns the transaction for the given transaction ID.
208    pub fn get_transaction(&self, transaction_id: N::TransactionID) -> Result<Transaction<N>> {
209        // Retrieve the transaction.
210        match self.vm.block_store().get_transaction(&transaction_id)? {
211            Some(transaction) => Ok(transaction),
212            None => bail!("Missing transaction for ID {transaction_id}"),
213        }
214    }
215
216    /// Returns the confirmed transaction for the given transaction ID.
217    pub fn get_confirmed_transaction(&self, transaction_id: N::TransactionID) -> Result<ConfirmedTransaction<N>> {
218        // Retrieve the confirmed transaction.
219        match self.vm.block_store().get_confirmed_transaction(&transaction_id)? {
220            Some(confirmed_transaction) => Ok(confirmed_transaction),
221            None => bail!("Missing confirmed transaction for ID {transaction_id}"),
222        }
223    }
224
225    /// Returns the unconfirmed transaction for the given `transaction ID`.
226    pub fn get_unconfirmed_transaction(&self, transaction_id: &N::TransactionID) -> Result<Transaction<N>> {
227        // Retrieve the unconfirmed transaction.
228        match self.vm.block_store().get_unconfirmed_transaction(transaction_id)? {
229            Some(unconfirmed_transaction) => Ok(unconfirmed_transaction),
230            None => bail!("Missing unconfirmed transaction for ID {transaction_id}"),
231        }
232    }
233
234    /// Returns the latest edition for the given `program ID`.
235    pub fn get_latest_edition_for_program(&self, program_id: &ProgramID<N>) -> Result<u16> {
236        match self.vm.block_store().get_latest_edition_for_program(program_id)? {
237            Some(edition) => Ok(edition),
238            None => bail!("Missing latest edition for program ID {program_id}"),
239        }
240    }
241
242    /// Returns the latest program for the given `program ID`.
243    pub fn get_program(&self, program_id: ProgramID<N>) -> Result<Program<N>> {
244        match self.vm.block_store().get_latest_program(&program_id)? {
245            Some(program) => Ok(program),
246            None => bail!("Missing program for ID {program_id}"),
247        }
248    }
249
250    /// Returns the program for the given `program ID` and `edition`.
251    pub fn get_program_for_edition(&self, program_id: ProgramID<N>, edition: u16) -> Result<Program<N>> {
252        match self.vm.block_store().get_program_for_edition(&program_id, edition)? {
253            Some(program) => Ok(program),
254            None => bail!("Missing program for ID {program_id} and edition {edition}"),
255        }
256    }
257
258    /// Returns the block solutions for the given block height.
259    pub fn get_solutions(&self, height: u32) -> Result<Solutions<N>> {
260        // If the height is 0, return the genesis block solutions.
261        if height == 0 {
262            return Ok(self.genesis_block.solutions().clone());
263        }
264        // Retrieve the block hash.
265        let block_hash = match self.vm.block_store().get_block_hash(height)? {
266            Some(block_hash) => block_hash,
267            None => bail!("Block {height} does not exist in storage"),
268        };
269        // Retrieve the block solutions.
270        self.vm.block_store().get_block_solutions(&block_hash)
271    }
272
273    /// Returns the solution for the given solution ID.
274    pub fn get_solution(&self, solution_id: &SolutionID<N>) -> Result<Solution<N>> {
275        self.vm.block_store().get_solution(solution_id)
276    }
277
278    /// Returns the block authority for the given block height.
279    pub fn get_authority(&self, height: u32) -> Result<Authority<N>> {
280        // If the height is 0, return the genesis block authority.
281        if height == 0 {
282            return Ok(self.genesis_block.authority().clone());
283        }
284        // Retrieve the block hash.
285        let block_hash = match self.vm.block_store().get_block_hash(height)? {
286            Some(block_hash) => block_hash,
287            None => bail!("Block {height} does not exist in storage"),
288        };
289        // Retrieve the block authority.
290        match self.vm.block_store().get_block_authority(&block_hash)? {
291            Some(authority) => Ok(authority),
292            None => bail!("Missing authority for block {height}"),
293        }
294    }
295
296    /// Returns the batch certificate for the given `certificate ID`.
297    pub fn get_batch_certificate(&self, certificate_id: &Field<N>) -> Result<Option<BatchCertificate<N>>> {
298        self.vm.block_store().get_batch_certificate(certificate_id)
299    }
300
301    /// Returns the delegators for the given validator.
302    pub fn get_delegators_for_validator(&self, validator: &Address<N>) -> Result<Vec<Address<N>>> {
303        // Construct the credits.aleo program ID.
304        let credits_program_id = ProgramID::from_str("credits.aleo")?;
305        // Construct the bonded mapping name.
306        let bonded_mapping = Identifier::from_str("bonded")?;
307        // Construct the bonded mapping key name.
308        let bonded_mapping_key = Identifier::from_str("validator")?;
309        // Get the credits.aleo bonded mapping.
310        let bonded = self.vm.finalize_store().get_mapping_confirmed(credits_program_id, bonded_mapping)?;
311        // Select the delegators for the given validator.
312        cfg_into_iter!(bonded)
313            .filter_map(|(bonded_address, bond_state)| {
314                let Plaintext::Literal(Literal::Address(bonded_address), _) = bonded_address else {
315                    return Some(Err(anyhow!("Invalid delegator in finalize storage.")));
316                };
317                let Value::Plaintext(Plaintext::Struct(bond_state, _)) = bond_state else {
318                    return Some(Err(anyhow!("Invalid bond_state in finalize storage.")));
319                };
320                let Some(mapping_validator) = bond_state.get(&bonded_mapping_key) else {
321                    return Some(Err(anyhow!("Invalid bond_state validator in finalize storage.")));
322                };
323                let Plaintext::Literal(Literal::Address(mapping_validator), _) = mapping_validator else {
324                    return Some(Err(anyhow!("Invalid validator in finalize storage.")));
325                };
326                // Select bonded addresses which:
327                // 1. are bonded to the right validator.
328                // 2. are not themselves the validator.
329                (mapping_validator == validator && bonded_address != *validator).then_some(Ok(bonded_address))
330            })
331            .collect::<Result<_>>()
332    }
333
334    /// Returns the amount of microcredits that the given address has bonded.
335    pub fn get_bonded_amount(&self, address: &Address<N>) -> Result<u64> {
336        // Construct the credits.aleo program ID.
337        let credits_program_id = ProgramID::from_str("credits.aleo")?;
338        // Construct the bonded mapping name.
339        let bonded_mapping = Identifier::from_str("bonded")?;
340        // Construct the bonded mapping key name.
341        let bonded_mapping_key = Plaintext::from(Literal::Address(*address));
342        // Construct the bond_state microcredits key.
343        let microcredits_key = Identifier::from_str("microcredits")?;
344        // Get the bond state for the given staker.
345        let bond_state =
346            self.vm.finalize_store().get_value_confirmed(credits_program_id, bonded_mapping, &bonded_mapping_key)?;
347        // Find the microcredits in the bond state.
348        match bond_state {
349            Some(Value::Plaintext(Plaintext::Struct(bond_state, _))) => match bond_state.get(&microcredits_key) {
350                Some(Plaintext::Literal(Literal::U64(amount), _)) => Ok(**amount),
351                _ => bail!("Expected 'microcredits' as a u64 in bond_state struct."),
352            },
353            // If the address is not bonded, then return 0.
354            None => Ok(0),
355            _ => bail!("Invalid bond_state in finalize storage."),
356        }
357    }
358}