1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the snarkVM library.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::*;

impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
    /// Returns the state root that contains the given `block height`.
    pub fn get_state_root(&self, block_height: u32) -> Result<Option<N::StateRoot>> {
        self.vm.block_store().get_state_root(block_height)
    }

    /// Returns a state path for the given commitment.
    pub fn get_state_path_for_commitment(&self, commitment: &Field<N>) -> Result<StatePath<N>> {
        self.vm.block_store().get_state_path_for_commitment(commitment)
    }

    /// Returns the epoch challenge for the given block height.
    pub fn get_epoch_challenge(&self, block_height: u32) -> Result<EpochChallenge<N>> {
        // Compute the epoch number from the current block height.
        let epoch_number = block_height / N::NUM_BLOCKS_PER_EPOCH;
        // Compute the epoch starting height (a multiple of `NUM_BLOCKS_PER_EPOCH`).
        let epoch_starting_height = epoch_number * N::NUM_BLOCKS_PER_EPOCH;
        // Retrieve the epoch block hash, defined as the 'previous block hash' from the epoch starting height.
        let epoch_block_hash = self.get_previous_hash(epoch_starting_height)?;
        // Construct the epoch challenge.
        EpochChallenge::new(epoch_number, epoch_block_hash, N::COINBASE_PUZZLE_DEGREE)
    }

    /// Returns the block for the given block height.
    pub fn get_block(&self, height: u32) -> Result<Block<N>> {
        // If the height is 0, return the genesis block.
        if height == 0 {
            return Ok(self.genesis.clone());
        }
        // Retrieve the block hash.
        let block_hash = match self.vm.block_store().get_block_hash(height)? {
            Some(block_hash) => block_hash,
            None => bail!("Block {height} does not exist in storage"),
        };
        // Retrieve the block.
        match self.vm.block_store().get_block(&block_hash)? {
            Some(block) => Ok(block),
            None => bail!("Block {height} ('{block_hash}') does not exist in storage"),
        }
    }

    /// Returns the blocks in the given block range.
    /// The range is inclusive of the start and exclusive of the end.
    pub fn get_blocks(&self, heights: Range<u32>) -> Result<Vec<Block<N>>> {
        cfg_into_iter!(heights).map(|height| self.get_block(height)).collect()
    }

    /// Returns the block for the given block hash.
    pub fn get_block_by_hash(&self, block_hash: &N::BlockHash) -> Result<Block<N>> {
        // Retrieve the block.
        match self.vm.block_store().get_block(block_hash)? {
            Some(block) => Ok(block),
            None => bail!("Block '{block_hash}' does not exist in storage"),
        }
    }

    /// Returns the block height for the given block hash.
    pub fn get_height(&self, block_hash: &N::BlockHash) -> Result<u32> {
        match self.vm.block_store().get_block_height(block_hash)? {
            Some(height) => Ok(height),
            None => bail!("Missing block height for block '{block_hash}'"),
        }
    }

    /// Returns the block hash for the given block height.
    pub fn get_hash(&self, height: u32) -> Result<N::BlockHash> {
        // If the height is 0, return the genesis block hash.
        if height == 0 {
            return Ok(self.genesis.hash());
        }
        match self.vm.block_store().get_block_hash(height)? {
            Some(block_hash) => Ok(block_hash),
            None => bail!("Missing block hash for block {height}"),
        }
    }

    /// Returns the previous block hash for the given block height.
    pub fn get_previous_hash(&self, height: u32) -> Result<N::BlockHash> {
        // If the height is 0, return the default block hash.
        if height == 0 {
            return Ok(N::BlockHash::default());
        }
        match self.vm.block_store().get_previous_block_hash(height)? {
            Some(previous_hash) => Ok(previous_hash),
            None => bail!("Missing previous block hash for block {height}"),
        }
    }

    /// Returns the block header for the given block height.
    pub fn get_header(&self, height: u32) -> Result<Header<N>> {
        // If the height is 0, return the genesis block header.
        if height == 0 {
            return Ok(*self.genesis.header());
        }
        // Retrieve the block hash.
        let block_hash = match self.vm.block_store().get_block_hash(height)? {
            Some(block_hash) => block_hash,
            None => bail!("Block {height} does not exist in storage"),
        };
        // Retrieve the block header.
        match self.vm.block_store().get_block_header(&block_hash)? {
            Some(header) => Ok(header),
            None => bail!("Missing block header for block {height}"),
        }
    }

    /// Returns the block transactions for the given block height.
    pub fn get_transactions(&self, height: u32) -> Result<Transactions<N>> {
        // If the height is 0, return the genesis block transactions.
        if height == 0 {
            return Ok(self.genesis.transactions().clone());
        }
        // Retrieve the block hash.
        let block_hash = match self.vm.block_store().get_block_hash(height)? {
            Some(block_hash) => block_hash,
            None => bail!("Block {height} does not exist in storage"),
        };
        // Retrieve the block transaction.
        match self.vm.block_store().get_block_transactions(&block_hash)? {
            Some(transactions) => Ok(transactions),
            None => bail!("Missing block transactions for block {height}"),
        }
    }

    /// Returns the transaction for the given transaction ID.
    pub fn get_transaction(&self, transaction_id: N::TransactionID) -> Result<Transaction<N>> {
        // Retrieve the transaction.
        match self.vm.transaction_store().get_transaction(&transaction_id)? {
            Some(transaction) => Ok(transaction),
            None => bail!("Missing transaction for ID {transaction_id}"),
        }
    }

    /// Returns the confirmed transaction for the given transaction ID.
    pub fn get_confirmed_transaction(&self, transaction_id: N::TransactionID) -> Result<ConfirmedTransaction<N>> {
        // Retrieve the confirmed transaction.
        match self.vm.block_store().get_confirmed_transaction(&transaction_id)? {
            Some(confirmed_transaction) => Ok(confirmed_transaction),
            None => bail!("Missing confirmed transaction for ID {transaction_id}"),
        }
    }

    /// Returns the program for the given program ID.
    pub fn get_program(&self, program_id: ProgramID<N>) -> Result<Program<N>> {
        match self.vm.transaction_store().get_program(&program_id)? {
            Some(program) => Ok(program),
            None => bail!("Missing program for ID {program_id}"),
        }
    }

    /// Returns the block coinbase solution for the given block height.
    pub fn get_coinbase(&self, height: u32) -> Result<Option<CoinbaseSolution<N>>> {
        // If the height is 0, return the genesis block coinbase.
        if height == 0 {
            return Ok(self.genesis.coinbase().cloned());
        }
        // Retrieve the block hash.
        let block_hash = match self.vm.block_store().get_block_hash(height)? {
            Some(block_hash) => block_hash,
            None => bail!("Block {height} does not exist in storage"),
        };
        // Retrieve the block coinbase solution.
        self.vm.block_store().get_block_coinbase(&block_hash)
    }

    /// Returns the block signature for the given block height.
    pub fn get_signature(&self, height: u32) -> Result<Signature<N>> {
        // If the height is 0, return the genesis block signature.
        if height == 0 {
            return Ok(*self.genesis.signature());
        }
        // Retrieve the block hash.
        let block_hash = match self.vm.block_store().get_block_hash(height)? {
            Some(block_hash) => block_hash,
            None => bail!("Block {height} does not exist in storage"),
        };
        // Retrieve the block signature.
        match self.vm.block_store().get_block_signature(&block_hash)? {
            Some(signature) => Ok(signature),
            None => bail!("Missing signature for block {height}"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::test_helpers::CurrentLedger;
    use console::network::Testnet3;

    type CurrentNetwork = Testnet3;

    #[test]
    fn test_get_block() {
        // Load the genesis block.
        let genesis = Block::from_bytes_le(CurrentNetwork::genesis_bytes()).unwrap();

        // Initialize a new ledger.
        let ledger = CurrentLedger::load(genesis.clone(), None).unwrap();
        // Retrieve the genesis block.
        let candidate = ledger.get_block(0).unwrap();
        // Ensure the genesis block matches.
        assert_eq!(genesis, candidate);
    }
}