raiden_primitives/
hashing.rs1#![warn(clippy::missing_docs_in_private_items)]
2
3use sha2::{
4 Digest,
5 Sha256,
6};
7use web3::signing::keccak256;
8
9use crate::{
10 constants::LOCKSROOT_OF_NO_LOCKS,
11 types::{
12 BalanceHash,
13 LockedAmount,
14 Locksroot,
15 TokenAmount,
16 },
17};
18
19pub fn hash_secret(secret: &[u8]) -> [u8; 32] {
21 let mut hasher = Sha256::new();
22 hasher.update(secret);
23 hasher.finalize().into()
24}
25
26pub fn hash_balance_data(
28 transferred_amount: TokenAmount,
29 locked_amount: LockedAmount,
30 locksroot: Locksroot,
31) -> Result<BalanceHash, String> {
32 if locksroot.is_zero() {
33 return Err("Can't hash empty locksroot".to_string())
34 }
35
36 if locksroot.0.len() != 32 {
37 return Err("Locksroot has wrong length".to_string())
38 }
39
40 if transferred_amount == TokenAmount::zero() &&
41 locked_amount == TokenAmount::zero() &&
42 locksroot == *LOCKSROOT_OF_NO_LOCKS
43 {
44 return Ok(BalanceHash::zero())
45 }
46
47 let mut transferred_amount_in_bytes: [u8; 32] = [0; 32];
48 transferred_amount.to_big_endian(&mut transferred_amount_in_bytes);
49
50 let mut locked_amount_in_bytes: [u8; 32] = [0; 32];
51 locked_amount.to_big_endian(&mut locked_amount_in_bytes);
52
53 let hash = keccak256(
54 &[&transferred_amount_in_bytes[..], &locked_amount_in_bytes[..], &locksroot.0[..]].concat(),
55 );
56 Ok(BalanceHash::from_slice(&hash))
57}