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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
use crate::types::H256;
#[derive(Debug, derive_more::Display, PartialEq, Clone)]
pub enum SigningError {
#[display(fmt = "Message has to be a non-zero 32-bytes slice.")]
InvalidMessage,
}
impl std::error::Error for SigningError {}
#[derive(Debug, derive_more::Display, PartialEq, Clone)]
pub enum RecoveryError {
#[display(fmt = "Message has to be a non-zero 32-bytes slice.")]
InvalidMessage,
#[display(fmt = "Signature is invalid (check recovery id).")]
InvalidSignature,
}
impl std::error::Error for RecoveryError {}
#[cfg(feature = "signing")]
pub use feature_gated::*;
#[cfg(feature = "signing")]
mod feature_gated {
use super::*;
use secp256k1::recovery::{RecoverableSignature, RecoveryId};
pub(crate) use secp256k1::SecretKey;
use secp256k1::{Message, PublicKey, Secp256k1};
use std::ops::Deref;
use crate::types::Address;
pub trait Key {
fn sign(&self, message: &[u8], chain_id: Option<u64>) -> Result<Signature, SigningError>;
fn address(&self) -> Address;
}
pub struct SecretKeyRef<'a> {
pub(super) key: &'a SecretKey,
}
impl<'a> SecretKeyRef<'a> {
pub fn new(key: &'a SecretKey) -> Self {
Self { key }
}
}
impl<'a> From<&'a SecretKey> for SecretKeyRef<'a> {
fn from(key: &'a SecretKey) -> Self {
Self::new(key)
}
}
impl<'a> Deref for SecretKeyRef<'a> {
type Target = SecretKey;
fn deref(&self) -> &Self::Target {
&self.key
}
}
impl<T: Deref<Target = SecretKey>> Key for T {
fn sign(&self, message: &[u8], chain_id: Option<u64>) -> Result<Signature, SigningError> {
let message = Message::from_slice(&message).map_err(|_| SigningError::InvalidMessage)?;
let (recovery_id, signature) = Secp256k1::signing_only()
.sign_recoverable(&message, self)
.serialize_compact();
let standard_v = recovery_id.to_i32() as u64;
let v = if let Some(chain_id) = chain_id {
standard_v + 35 + chain_id * 2
} else {
standard_v + 27
};
let r = H256::from_slice(&signature[..32]);
let s = H256::from_slice(&signature[32..]);
Ok(Signature { v, r, s })
}
fn address(&self) -> Address {
secret_key_address(self)
}
}
pub fn recover(message: &[u8], signature: &[u8], recovery_id: i32) -> Result<Address, RecoveryError> {
let message = Message::from_slice(message).map_err(|_| RecoveryError::InvalidMessage)?;
let recovery_id = RecoveryId::from_i32(recovery_id).map_err(|_| RecoveryError::InvalidSignature)?;
let signature =
RecoverableSignature::from_compact(&signature, recovery_id).map_err(|_| RecoveryError::InvalidSignature)?;
let public_key = Secp256k1::verification_only()
.recover(&message, &signature)
.map_err(|_| RecoveryError::InvalidSignature)?;
Ok(public_key_address(&public_key))
}
pub(crate) fn public_key_address(public_key: &PublicKey) -> Address {
let public_key = public_key.serialize_uncompressed();
debug_assert_eq!(public_key[0], 0x04);
let hash = keccak256(&public_key[1..]);
Address::from_slice(&hash[12..])
}
pub(crate) fn secret_key_address(key: &SecretKey) -> Address {
let secp = Secp256k1::signing_only();
let public_key = PublicKey::from_secret_key(&secp, key);
public_key_address(&public_key)
}
}
pub struct Signature {
pub v: u64,
pub r: H256,
pub s: H256,
}
pub fn keccak256(bytes: &[u8]) -> [u8; 32] {
use tiny_keccak::{Hasher, Keccak};
let mut output = [0u8; 32];
let mut hasher = Keccak::v256();
hasher.update(bytes);
hasher.finalize(&mut output);
output
}