aboutsummaryrefslogtreecommitdiff
path: root/src/message.rs
blob: 449a16ee4dc3872fa39b8ebc8d2612ab2b6cbc9c (plain)
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
//! Ethereum message for signing.

use ethdigest::Digest;
use std::io::Write as _;

/// A message to be signed with an Ethereum specific prefix.
pub struct EthereumMessage<T>(pub T);

impl<T> EthereumMessage<T>
where
    T: AsRef<[u8]>,
{
    /// Computes the 32-byte message used for ECDSA signing with a private key.
    pub fn signing_message(&self) -> Digest {
        digest(self.0.as_ref())
    }
}

/// Computes the Ethereum-specific digest for a message.
fn digest(data: &[u8]) -> Digest {
    let mut buffer = Vec::with_capacity(46 + data.len());
    buffer.extend_from_slice(b"\x19Ethereum Signed Message:\n");
    // Display implementation for `usize` should not error when writing to an
    // in memory buffer. Note that the standard library `ToString::to_string`
    // implementation has the same expectation:
    // <https://doc.rust-lang.org/std/string/trait.ToString.html#required-methods>
    write!(buffer, "{}", data.len()).expect("unexpected error writing number");
    buffer.extend_from_slice(data);

    Digest::of(buffer)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn computes_digest() {
        assert_eq!(
            digest(b"hello world!"),
            Digest::of(b"\x19Ethereum Signed Message:\n12hello world!"),
        );
    }
}