Skip to content

Commit

Permalink
Add sha256 and keccak256 hash functions to Bytes type (FuelLabs#3822)
Browse files Browse the repository at this point in the history
Due to the need to hash the elements in the `Bytes` type, the sha256()
and keccak256() functions have been added to the `Bytes` library.

Closes FuelLabs#3809

Co-authored-by: bitzoic <[email protected]>
  • Loading branch information
bitzoic and bitzoic authored Jan 20, 2023
1 parent a9daf98 commit 5968792
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions sway-lib-std/src/bytes.sw
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,48 @@ impl Bytes {
pub fn is_empty(self) -> bool {
self.len == 0
}

/// Returns the SHA-2-256 hash of the elements.
///
/// ### Examples
///
/// ```sway
/// use std:bytes::Bytes;
///
/// let bytes = Bytes::new();
/// bytes.push(1);
/// bytes.push(2);
/// bytes.push(3);
/// let sha256_hash = bytes.sha256();
/// ```
pub fn sha256(self) -> b256 {
let mut result_buffer = b256::min();
asm(hash: result_buffer, ptr: self.buf.ptr, bytes: self.len) {
s256 hash ptr bytes;
hash: b256
}
}

/// Returns the KECCAK-256 hash of the elements.
///
/// ### Examples
///
/// ```sway
/// use std:bytes::Bytes;
///
/// let bytes = Bytes::new();
/// bytes.push(1);
/// bytes.push(2);
/// bytes.push(3);
/// let keccak256_hash = bytes.keccak256();
/// ```
pub fn keccak256(self) -> b256 {
let mut result_buffer = b256::min();
asm(hash: result_buffer, ptr: self.buf.ptr, bytes: self.len) {
k256 hash ptr bytes;
hash: b256
}
}
}

// Need to use seperate impl blocks for now: https://github.com/FuelLabs/sway/issues/1548
Expand Down Expand Up @@ -913,3 +955,31 @@ fn test_eq() {
other.swap(0, 1);
assert(bytes != other);
}

#[test()]
fn test_sha256() {
use ::hash::sha256;
let (mut bytes, a, b, c) = setup();
bytes.push(0u8);
bytes.push(0u8);
bytes.push(0u8);
bytes.push(0u8);
bytes.push(0u8);

// The u8 bytes [5, 7, 9, 0, 0, 0, 0, 0] are equivalent to the u64 integer "362268190631264256"
assert(sha256(362268190631264256) == bytes.sha256());
}

#[test()]
fn test_keccak256() {
use ::hash::keccak256;
let (mut bytes, a, b, c) = setup();
bytes.push(0u8);
bytes.push(0u8);
bytes.push(0u8);
bytes.push(0u8);
bytes.push(0u8);

// The u8 bytes [5, 7, 9, 0, 0, 0, 0, 0] are equivalent to the u64 integer "362268190631264256"
assert(keccak256(362268190631264256) == bytes.keccak256());
}

0 comments on commit 5968792

Please sign in to comment.