Skip to content

Instantly share code, notes, and snippets.

@cygaar
Created September 1, 2023 19:37
Show Gist options
  • Save cygaar/ee3cf1d1f98a57369717c9d91e076fd1 to your computer and use it in GitHub Desktop.
Save cygaar/ee3cf1d1f98a57369717c9d91e076fd1 to your computer and use it in GitHub Desktop.
Rust (Stylus) contract that loops n times and hashes an input string repeatedly
// Only run this as a WASM if the export-abi feature is not set.
#![cfg_attr(not(feature = "export-abi"), no_main)]
extern crate alloc;
/// Initializes a custom, global allocator for Rust programs compiled to WASM.
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
/// Import the Stylus SDK along with alloy primitive types for use in our program.
use stylus_sdk::{alloy_primitives::U256, alloy_primitives::FixedBytes, abi::FixedBytes as ABIFixedBytes, crypto::keccak, prelude::*};
// use sha3::{Digest, Keccak256};
// Define the entrypoint as a Solidity storage object
sol_storage! {
#[entrypoint]
pub struct Hasher {
bytes32 hash;
}
}
/// Define an implementation of the generated Hasher struct
#[external]
impl Hasher {
pub fn hash(&self) -> Result<ABIFixedBytes<32>, Vec<u8>> {
Ok(self.hash.get().0.into())
}
pub fn keccak_loop(&mut self, input_string: String, amount: U256) -> Result<(), Vec<u8>> {
let mut hash = input_string.as_bytes();
let mut hashed_value: FixedBytes<32>;
for _ in 0..amount.try_into().unwrap() {
hashed_value = keccak(hash);
hash = hashed_value.as_slice();
}
let hash_hex: Vec<String> = hash.iter().map(|b| format!("{:02x}", b)).collect();
let hash_hex = hash_hex.join("");
self.hash.set(hash_hex.parse::<FixedBytes<32>>().unwrap());
Ok(())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment