1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use sha3::{Digest, Keccak256};
#[cfg(not(feature = "std"))]
use crate::no_std_prelude::*;
use crate::{
param_type::{ParamType, Writer},
Hash,
};
pub fn short_signature(name: &str, params: &[ParamType]) -> [u8; 4] {
let mut result = [0u8; 4];
fill_signature(name, params, &mut result);
result
}
pub fn long_signature(name: &str, params: &[ParamType]) -> Hash {
let mut result = [0u8; 32];
fill_signature(name, params, &mut result);
result.into()
}
fn fill_signature(name: &str, params: &[ParamType], result: &mut [u8]) {
let types = params.iter().map(Writer::write).collect::<Vec<String>>().join(",");
let data: Vec<u8> = From::from(format!("{name}({types})").as_str());
result.copy_from_slice(&Keccak256::digest(data)[..result.len()])
}
#[cfg(test)]
mod tests {
use super::short_signature;
use crate::ParamType;
use hex_literal::hex;
#[test]
fn test_signature() {
assert_eq!(hex!("cdcd77c0"), short_signature("baz", &[ParamType::Uint(32), ParamType::Bool]));
}
}