@@ -94,19 +94,24 @@ impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
9494
9595 /// Returns the block for the given block height.
9696 pub fn get_block ( & self , height : u32 ) -> Result < Block < N > > {
97- // If the height is 0, return the genesis block.
97+ match self . try_get_block ( height) ? {
98+ Some ( block) => Ok ( block) ,
99+ None => bail ! ( "Block {height} does not exist in storage" ) ,
100+ }
101+ }
102+
103+ /// Returns the block for the given block height.
104+ ///
105+ /// This behaves the same as [`Self::get_block`], except that a missing block will cause the function to
106+ /// return `Ok(None)` instead of an error.
107+ pub fn try_get_block ( & self , height : u32 ) -> Result < Option < Block < N > > > {
98108 if height == 0 {
99- return Ok ( self . genesis_block . clone ( ) ) ;
109+ return Ok ( Some ( self . genesis_block . clone ( ) ) ) ;
100110 }
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" ) ,
111+
112+ match self . vm . block_store ( ) . get_block_hash ( height) ? {
113+ Some ( hash) => self . vm . block_store ( ) . get_block ( & hash) ,
114+ None => Ok ( None ) ,
110115 }
111116 }
112117
@@ -118,13 +123,20 @@ impl<N: Network, C: ConsensusStorage<N>> Ledger<N, C> {
118123
119124 /// Returns the block for the given block hash.
120125 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) ? {
126+ match self . try_get_block_by_hash ( block_hash) ? {
123127 Some ( block) => Ok ( block) ,
124128 None => bail ! ( "Block '{block_hash}' does not exist in storage" ) ,
125129 }
126130 }
127131
132+ /// Returns the block for the given block hash.
133+ ///
134+ /// This behaves the same as [`Self::get_block_by_hash`], except that a missing block will cause the function to
135+ /// return `Ok(None)` instead of an error.
136+ pub fn try_get_block_by_hash ( & self , block_hash : & N :: BlockHash ) -> Result < Option < Block < N > > > {
137+ self . vm . block_store ( ) . get_block ( block_hash)
138+ }
139+
128140 /// Returns the block height for the given block hash.
129141 pub fn get_height ( & self , block_hash : & N :: BlockHash ) -> Result < u32 > {
130142 match self . vm . block_store ( ) . get_block_height ( block_hash) ? {
0 commit comments