rtvm_precompile/
hash.rs

1use super::calc_linear_cost_u32;
2use crate::{Error, Precompile, PrecompileResult, PrecompileWithAddress};
3use rtvm_primitives::Bytes;
4use sha2::Digest;
5
6pub const SHA256: PrecompileWithAddress =
7    PrecompileWithAddress(crate::u64_to_address(2), Precompile::Standard(sha256_run));
8
9pub const RIPEMD160: PrecompileWithAddress = PrecompileWithAddress(
10    crate::u64_to_address(3),
11    Precompile::Standard(ripemd160_run),
12);
13
14/// See: <https://ethereum.github.io/yellowpaper/paper.pdf>
15/// See: <https://docs.soliditylang.org/en/develop/units-and-global-variables.html#mathematical-and-cryptographic-functions>
16/// See: <https://etherscan.io/address/0000000000000000000000000000000000000002>
17pub fn sha256_run(input: &Bytes, gas_limit: u64) -> PrecompileResult {
18    let cost = calc_linear_cost_u32(input.len(), 60, 12);
19    if cost > gas_limit {
20        Err(Error::OutOfGas)
21    } else {
22        let output = sha2::Sha256::digest(input);
23        Ok((cost, output.to_vec().into()))
24    }
25}
26
27/// See: <https://ethereum.github.io/yellowpaper/paper.pdf>
28/// See: <https://docs.soliditylang.org/en/develop/units-and-global-variables.html#mathematical-and-cryptographic-functions>
29/// See: <https://etherscan.io/address/0000000000000000000000000000000000000003>
30pub fn ripemd160_run(input: &Bytes, gas_limit: u64) -> PrecompileResult {
31    let gas_used = calc_linear_cost_u32(input.len(), 600, 120);
32    if gas_used > gas_limit {
33        Err(Error::OutOfGas)
34    } else {
35        let mut hasher = ripemd::Ripemd160::new();
36        hasher.update(input);
37
38        let mut output = [0u8; 32];
39        hasher.finalize_into((&mut output[12..]).into());
40        Ok((gas_used, output.to_vec().into()))
41    }
42}