-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
eip191.rs
42 lines (34 loc) · 1.15 KB
/
eip191.rs
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
// SPDX-License-Identifier: Apache-2.0
//
// Copyright © 2017 Trust Wallet.
use crate::message::{EthMessage, MessageSigningResult};
use tw_hash::sha3::keccak256;
use tw_hash::H256;
/// cbindgen:ignore
pub const ETHEREUM_PREFIX: u8 = 0x19;
/// cbindgen:ignore
pub const ETHEREUM_MESSAGE_PREFIX: &str = "Ethereum Signed Message:\n";
pub struct Eip191Message {
user_message: String,
}
impl Eip191Message {
pub fn new<S: Into<String>>(user_message: S) -> Eip191Message {
Eip191Message {
user_message: user_message.into(),
}
}
fn data_to_sign(&self) -> Vec<u8> {
let mut data = Vec::with_capacity(self.user_message.len() * 2);
data.push(ETHEREUM_PREFIX);
data.extend_from_slice(ETHEREUM_MESSAGE_PREFIX.as_bytes());
data.extend_from_slice(self.user_message.len().to_string().as_bytes());
data.extend_from_slice(self.user_message.as_bytes());
data
}
}
impl EthMessage for Eip191Message {
fn hash(&self) -> MessageSigningResult<H256> {
let hash = keccak256(&self.data_to_sign());
Ok(H256::try_from(hash.as_slice()).expect("Expected 32 byte hash"))
}
}