Skip to content

Commit

Permalink
byte using starknet's sha256
Browse files Browse the repository at this point in the history
  • Loading branch information
gaetbout committed Aug 7, 2024
1 parent e8546cf commit 846621a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
13 changes: 7 additions & 6 deletions packages/bytes/src/bytes.cairo
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use alexandria_bytes::utils::{
u128_join, read_sub_u128, u128_split, u128_array_slice, keccak_u128s_be, u8_array_to_u256
u128_join, read_sub_u128, u128_split, u128_array_slice, keccak_u128s_be, u8_array_to_u256,
u32s_to_u256
};
use alexandria_math::sha256::sha256;
use alexandria_math::{U128BitShift, U256BitShift};
use core::byte_array::ByteArrayTrait;
use core::ops::index::IndexView;
use core::sha256;
use starknet::ContractAddress;
/// Bytes is a dynamic array of u128, where each element contains 16 bytes.
pub const BYTES_PER_ELEMENT: usize = 16;
Expand Down Expand Up @@ -552,18 +553,18 @@ impl BytesImpl of BytesTrait {

/// sha256 hash
fn sha256(self: @Bytes) -> u256 {
let mut hash_data: Array<u8> = array![];
let mut i: usize = 0;
let mut offset: usize = 0;
let mut hash_data_byte_array = "";
while i != self.size() {
let (new_offset, hash_data_item) = self.read_u8(offset);
hash_data.append(hash_data_item);
hash_data_byte_array.append_byte(hash_data_item);
offset = new_offset;
i += 1;
};

let output: Array<u8> = sha256(hash_data);
u8_array_to_u256(output.span())
let output = sha256::compute_sha256_byte_array(@hash_data_byte_array);
u32s_to_u256(output.span())
}
}

Expand Down
15 changes: 15 additions & 0 deletions packages/bytes/src/utils.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,21 @@ pub fn u8_array_to_u256(arr: Span<u8>) -> u256 {
u256 { low, high }
}

pub fn u32s_to_u256(arr: Span<u32>) -> u256 {
assert!(arr.len() == 8, "u32s_to_u2562: input must be 8 elements long");
let low: u128 = (*arr[7]).into()
+ (*arr[6]).into() * 0x1_0000_0000
+ (*arr[5]).into() * 0x1_0000_0000_0000_0000
+ (*arr[4]).into() * 0x1_0000_0000_0000_0000_0000_0000;
let low = low.try_into().expect('u32s_to_u2562:overflow-low');
let high = (*arr[3]).into()
+ (*arr[2]).into() * 0x1_0000_0000
+ (*arr[1]).into() * 0x1_0000_0000_0000_0000
+ (*arr[0]).into() * 0x1_0000_0000_0000_0000_0000_0000;
let high = high.try_into().expect('u32s_to_u2562:overflow-high');
u256 { high, low }
}

fn u64_array_slice(src: @Array<u64>, mut begin: usize, len: usize) -> Array<u64> {
let mut slice = array![];
let end = begin + len;
Expand Down

0 comments on commit 846621a

Please sign in to comment.