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 a list of state paths for the given list of `commitment`s.
79    pub fn get_state_paths_for_commitments(&self, commitments: &[Field<N>]) -> Result<Vec<StatePath<N>>> {
80        self.vm.block_store().get_state_paths_for_commitments(commitments)
81    }
82
83    /// Returns the epoch hash for the given block height.
84    pub fn get_epoch_hash(&self, block_height: u32) -> Result<N::BlockHash> {
85        // Compute the epoch number from the current block height.
86        let epoch_number = block_height.saturating_div(N::NUM_BLOCKS_PER_EPOCH);
87        // Compute the epoch starting height (a multiple of `NUM_BLOCKS_PER_EPOCH`).
88        let epoch_starting_height = epoch_number.saturating_mul(N::NUM_BLOCKS_PER_EPOCH);
89        // Retrieve the epoch hash, defined as the 'previous block hash' from the epoch starting height.
90        let epoch_hash = self.get_previous_hash(epoch_starting_height)?;
91        // Construct the epoch hash.
92        Ok(epoch_hash)
93    }
94
95    /// Returns the block for the given block height.
96    pub fn get_block(&self, height: u32) -> Result<Block<N>> {
97        // If the height is 0, return the genesis block.
98        if height == 0 {
99            return Ok(self.genesis_block.clone());
100        }
101        // Retrieve the block hash.
102        let block_hash = match self.vm.block_store().get_block_hash(height)? {
103            Some(block_hash) => block_hash,
104            None => bail!("Block {height} does not exist in storage"),
105        };
106        // Retrieve the block.
107        match self.vm.block_store().get_block(&block_hash)? {
108            Some(block) => Ok(block),
109            None => bail!("Block {height} ('{block_hash}') does not exist in storage"),
110        }
111    }
112
113    /// Returns the blocks in the given block range.
114    /// The range is inclusive of the start and exclusive of the end.
115    pub fn get_blocks(&self, heights: Range<u32>) -> Result<Vec<Block<N>>> {
116        cfg_into_iter!(heights).map(|height| self.get_block(height)).collect()
117    }
118
119    /// Returns the block for the given block hash.
120    pub fn get_block_by_hash(&self, block_hash: &N::BlockHash) -> Result<Block<N>> {
121        // Retrieve the block.
122        match self.vm.block_store().get_block(block_hash)? {
123            Some(block) => Ok(block),
124            None => bail!("Block '{block_hash}' does not exist in storage"),
125        }
126    }
127
128    /// Returns the block height for the given block hash.
129    pub fn get_height(&self, block_hash: &N::BlockHash) -> Result<u32> {
130        match self.vm.block_store().get_block_height(block_hash)? {
131            Some(height) => Ok(height),
132            None => bail!("Missing block height for block '{block_hash}'"),
133        }
134    }
135
136    /// Returns the block hash for the given block height.
137    pub fn get_hash(&self, height: u32) -> Result<N::BlockHash> {
138        // If the height is 0, return the genesis block hash.
139        if height == 0 {
140            return Ok(self.genesis_block.hash());
141        }
142        match self.vm.block_store().get_block_hash(height)? {
143            Some(block_hash) => Ok(block_hash),
144            None => bail!("Missing block hash for block {height}"),
145        }
146    }
147
148    /// Returns the previous block hash for the given block height.
149    pub fn get_previous_hash(&self, height: u32) -> Result<N::BlockHash> {
150        // If the height is 0, return the default block hash.
151        if height == 0 {
152            return Ok(N::BlockHash::default());
153        }
154        match self.vm.block_store().get_previous_block_hash(height)? {
155            Some(previous_hash) => Ok(previous_hash),
156            None => bail!("Missing previous block hash for block {height}"),
157        }
158    }
159
160    /// Returns the block header for the given block height.
161    pub fn get_header(&self, height: u32) -> Result<Header<N>> {
162        // If the height is 0, return the genesis block header.
163        if height == 0 {
164            return Ok(*self.genesis_block.header());
165        }
166        // Retrieve the block hash.
167        let block_hash = match self.vm.block_store().get_block_hash(height)? {
168            Some(block_hash) => block_hash,
169            None => bail!("Block {height} does not exist in storage"),
170        };
171        // Retrieve the block header.
172        match self.vm.block_store().get_block_header(&block_hash)? {
173            Some(header) => Ok(header),
174            None => bail!("Missing block header for block {height}"),
175        }
176    }
177
178    /// Returns the block transactions for the given block height.
179    pub fn get_transactions(&self, height: u32) -> Result<Transactions<N>> {
180        // If the height is 0, return the genesis block transactions.
181        if height == 0 {
182            return Ok(self.genesis_block.transactions().clone());
183        }
184        // Retrieve the block hash.
185        let Some(block_hash) = self.vm.block_store().get_block_hash(height)? else {
186            bail!("Block {height} does not exist in storage");
187        };
188        // Retrieve the block transaction.
189        match self.vm.block_store().get_block_transactions(&block_hash)? {
190            Some(transactions) => Ok(transactions),
191            None => bail!("Missing block transactions for block {height}"),
192        }
193    }
194
195    /// Returns the aborted transaction IDs for the given block height.
196    pub fn get_aborted_transaction_ids(&self, height: u32) -> Result<Vec<N::TransactionID>> {
197        // If the height is 0, return the genesis block aborted transaction IDs.
198        if height == 0 {
199            return Ok(self.genesis_block.aborted_transaction_ids().clone());
200        }
201        // Retrieve the block hash.
202        let Some(block_hash) = self.vm.block_store().get_block_hash(height)? else {
203            bail!("Block {height} does not exist in storage");
204        };
205        // Retrieve the aborted transaction IDs.
206        match self.vm.block_store().get_block_aborted_transaction_ids(&block_hash)? {
207            Some(aborted_transaction_ids) => Ok(aborted_transaction_ids),
208            None => bail!("Missing aborted transaction IDs for block {height}"),
209        }
210    }
211
212    /// Returns the transaction for the given transaction ID.
213    pub fn get_transaction(&self, transaction_id: N::TransactionID) -> Result<Transaction<N>> {
214        // Retrieve the transaction.
215        match self.vm.block_store().get_transaction(&transaction_id)? {
216            Some(transaction) => Ok(transaction),
217            None => bail!("Missing transaction for ID {transaction_id}"),
218        }
219    }
220
221    /// Returns the confirmed transaction for the given transaction ID.
222    pub fn get_confirmed_transaction(&self, transaction_id: N::TransactionID) -> Result<ConfirmedTransaction<N>> {
223        // Retrieve the confirmed transaction.
224        match self.vm.block_store().get_confirmed_transaction(&transaction_id)? {
225            Some(confirmed_transaction) => Ok(confirmed_transaction),
226            None => bail!("Missing confirmed transaction for ID {transaction_id}"),
227        }
228    }
229
230    /// Returns the unconfirmed transaction for the given `transaction ID`.
231    pub fn get_unconfirmed_transaction(&self, transaction_id: &N::TransactionID) -> Result<Transaction<N>> {
232        // Retrieve the unconfirmed transaction.
233        match self.vm.block_store().get_unconfirmed_transaction(transaction_id)? {
234            Some(unconfirmed_transaction) => Ok(unconfirmed_transaction),
235            None => bail!("Missing unconfirmed transaction for ID {transaction_id}"),
236        }
237    }
238
239    /// Returns the latest edition for the given `program ID`.
240    pub fn get_latest_edition_for_program(&self, program_id: &ProgramID<N>) -> Result<u16> {
241        match self.vm.block_store().get_latest_edition_for_program(program_id)? {
242            Some(edition) => Ok(edition),
243            None => bail!("Missing latest edition for program ID {program_id}"),
244        }
245    }
246
247    /// Returns the latest program for the given `program ID`.
248    pub fn get_program(&self, program_id: ProgramID<N>) -> Result<Program<N>> {
249        match self.vm.block_store().get_latest_program(&program_id)? {
250            Some(program) => Ok(program),
251            None => bail!("Missing program for ID {program_id}"),
252        }
253    }
254
255    /// Returns the program for the given `program ID` and `edition`.
256    pub fn get_program_for_edition(&self, program_id: ProgramID<N>, edition: u16) -> Result<Program<N>> {
257        match self.vm.block_store().get_program_for_edition(&program_id, edition)? {
258            Some(program) => Ok(program),
259            None => bail!("Missing program for ID {program_id} and edition {edition}"),
260        }
261    }
262
263    /// Returns the block solutions for the given block height.
264    pub fn get_solutions(&self, height: u32) -> Result<Solutions<N>> {
265        // If the height is 0, return the genesis block solutions.
266        if height == 0 {
267            return Ok(self.genesis_block.solutions().clone());
268        }
269        // Retrieve the block hash.
270        let block_hash = match self.vm.block_store().get_block_hash(height)? {
271            Some(block_hash) => block_hash,
272            None => bail!("Block {height} does not exist in storage"),
273        };
274        // Retrieve the block solutions.
275        self.vm.block_store().get_block_solutions(&block_hash)
276    }
277
278    /// Returns the solution for the given solution ID.
279    pub fn get_solution(&self, solution_id: &SolutionID<N>) -> Result<Solution<N>> {
280        self.vm.block_store().get_solution(solution_id)
281    }
282
283    /// Returns the block authority for the given block height.
284    pub fn get_authority(&self, height: u32) -> Result<Authority<N>> {
285        // If the height is 0, return the genesis block authority.
286        if height == 0 {
287            return Ok(self.genesis_block.authority().clone());
288        }
289        // Retrieve the block hash.
290        let block_hash = match self.vm.block_store().get_block_hash(height)? {
291            Some(block_hash) => block_hash,
292            None => bail!("Block {height} does not exist in storage"),
293        };
294        // Retrieve the block authority.
295        match self.vm.block_store().get_block_authority(&block_hash)? {
296            Some(authority) => Ok(authority),
297            None => bail!("Missing authority for block {height}"),
298        }
299    }
300
301    /// Returns the batch certificate for the given `certificate ID`.
302    pub fn get_batch_certificate(&self, certificate_id: &Field<N>) -> Result<Option<BatchCertificate<N>>> {
303        self.vm.block_store().get_batch_certificate(certificate_id)
304    }
305
306    /// Returns the delegators for the given validator.
307    pub fn get_delegators_for_validator(&self, validator: &Address<N>) -> Result<Vec<Address<N>>> {
308        // Construct the credits.aleo program ID.
309        let credits_program_id = ProgramID::from_str("credits.aleo")?;
310        // Construct the bonded mapping name.
311        let bonded_mapping = Identifier::from_str("bonded")?;
312        // Construct the bonded mapping key name.
313        let bonded_mapping_key = Identifier::from_str("validator")?;
314        // Get the credits.aleo bonded mapping.
315        let bonded = self.vm.finalize_store().get_mapping_confirmed(credits_program_id, bonded_mapping)?;
316        // Select the delegators for the given validator.
317        cfg_into_iter!(bonded)
318            .filter_map(|(bonded_address, bond_state)| {
319                let Plaintext::Literal(Literal::Address(bonded_address), _) = bonded_address else {
320                    return Some(Err(anyhow!("Invalid delegator in finalize storage.")));
321                };
322                let Value::Plaintext(Plaintext::Struct(bond_state, _)) = bond_state else {
323                    return Some(Err(anyhow!("Invalid bond_state in finalize storage.")));
324                };
325                let Some(mapping_validator) = bond_state.get(&bonded_mapping_key) else {
326                    return Some(Err(anyhow!("Invalid bond_state validator in finalize storage.")));
327                };
328                let Plaintext::Literal(Literal::Address(mapping_validator), _) = mapping_validator else {
329                    return Some(Err(anyhow!("Invalid validator in finalize storage.")));
330                };
331                // Select bonded addresses which:
332                // 1. are bonded to the right validator.
333                // 2. are not themselves the validator.
334                (mapping_validator == validator && bonded_address != *validator).then_some(Ok(bonded_address))
335            })
336            .collect::<Result<_>>()
337    }
338
339    /// Returns the amount of microcredits that the given address has bonded.
340    pub fn get_bonded_amount(&self, address: &Address<N>) -> Result<u64> {
341        // Construct the credits.aleo program ID.
342        let credits_program_id = ProgramID::from_str("credits.aleo")?;
343        // Construct the bonded mapping name.
344        let bonded_mapping = Identifier::from_str("bonded")?;
345        // Construct the bonded mapping key name.
346        let bonded_mapping_key = Plaintext::from(Literal::Address(*address));
347        // Construct the bond_state microcredits key.
348        let microcredits_key = Identifier::from_str("microcredits")?;
349        // Get the bond state for the given staker.
350        let bond_state =
351            self.vm.finalize_store().get_value_confirmed(credits_program_id, bonded_mapping, &bonded_mapping_key)?;
352        // Find the microcredits in the bond state.
353        match bond_state {
354            Some(Value::Plaintext(Plaintext::Struct(bond_state, _))) => match bond_state.get(&microcredits_key) {
355                Some(Plaintext::Literal(Literal::U64(amount), _)) => Ok(**amount),
356                _ => bail!("Expected 'microcredits' as a u64 in bond_state struct."),
357            },
358            // If the address is not bonded, then return 0.
359            None => Ok(0),
360            _ => bail!("Invalid bond_state in finalize storage."),
361        }
362    }
363}