Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add block_header_hash() function #4493

Merged
merged 8 commits into from
Apr 25, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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() {
Braqzen marked this conversation as resolved.
Show resolved Hide resolved
// 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
Loading