Skip to content

Commit

Permalink
Add block_header_hash() function (#4493)
Browse files Browse the repository at this point in the history
## Description


## Checklist

- [ ] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [x] I have requested a review from the relevant team or maintainers.
  • Loading branch information
nfurfaro committed Apr 25, 2023
1 parent fe02ce3 commit f62148f
Show file tree
Hide file tree
Showing 5 changed files with 400 additions and 214 deletions.
57 changes: 57 additions & 0 deletions sway-lib-std/src/block.sw
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
//! Functionality for accessing block-related data.
library;

use ::assert::assert;
use ::constants::ZERO_B256;
use ::result::Result;
use ::logging::log;

enum BlockHashError {
BlockHeightTooHigh: (),
}

/// Get the current block height.
pub fn height() -> u64 {
asm(height) {
Expand All @@ -21,3 +30,51 @@ pub fn timestamp_of_block(block_height: u64) -> u64 {
timestamp: u64
}
}

/// Get the header hash of the block at height `block_height`
pub fn block_header_hash(block_height: u64) -> Result<b256, BlockHashError> {

let mut header_hash = ZERO_B256;

asm(r1: __addr_of(header_hash), r2: block_height) {
bhsh r1 r2;
};

// `bhsh` returns b256(0) if the block is not found, so catch this and return an error
if header_hash == ZERO_B256 {
Result::Err(BlockHashError::BlockHeightTooHigh)
} else {
Result::Ok(header_hash)
}
}

////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////

#[test(should_revert)]
fn test_block_header_hash_err_current_height() {
// Get the header hash of the current block. Each time this test runs, the block height will be 1. calling BHSH with a height >= current height will fail.
let mut hash = block_header_hash(height());
let correct_error = match hash {
Result::Ok(_) => false,
Result::Err(BlockHashError::BlockHeightTooHigh) => true,
};

assert(correct_error);
}

#[test(should_revert)]
fn test_block_header_hash_err_future_height() {

// Try to get header hash of a block in the future
// The function should return a BlockHashError
let hash = block_header_hash(height() + 1);
let correct_error = match hash {
Result::Ok(_) => false,
Result::Err(BlockHashError::BlockHeightTooHigh) => true,
};

assert(correct_error);

}
Loading

0 comments on commit f62148f

Please sign in to comment.