df_hyperliquid_core/account/keys/
signer.rs1#[cfg(feature = "sign")]
6use std::fmt;
7use std::future::Future;
8
9#[cfg(feature = "sign")]
10use k256::ecdsa::{RecoveryId, Signature as CurveSignature, SigningKey, VerifyingKey};
11use serde::{Serialize, Serializer, ser::SerializeStruct};
12#[cfg(feature = "sign")]
13use zeroize::{ZeroizeOnDrop, Zeroizing};
14
15use crate::utils::address::Address;
16#[cfg(feature = "sign")]
17use crate::utils::hex;
18use crate::utils::json::Json;
19use crate::utils::sign::eip712::{Domain, TypedStruct};
20#[cfg(feature = "sign")]
21use crate::utils::sign::keccak::keccak256;
22
23const V_OFFSET: u8 = 27;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct Signature {
28 r: [u8; 32],
29 s: [u8; 32],
30 v: u8,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
35#[non_exhaustive]
36pub enum SignError {
37 #[error("the key could not sign this digest")]
39 Sign,
40 #[error("a signature is 65 bytes of hex")]
42 NotASignature,
43 #[error("the signature components are not a valid curve point")]
45 Malformed,
46 #[error("no public key recovers from this signature")]
48 Unrecoverable,
49 #[error("`{0}` is not an Ethereum recovery parameter; expected 27 or 28")]
51 BadV(u8),
52 #[error("the signature is from {recovered}, not {expected}")]
54 WrongSigner {
55 expected: Address,
57 recovered: Address,
59 },
60 #[error("the key is not a valid secp256k1 private key")]
62 NotAKey,
63}
64
65impl Signature {
66 #[must_use]
68 pub const fn from_parts(r: [u8; 32], s: [u8; 32], v: u8) -> Self {
69 Signature { r, s, v }
70 }
71
72 #[cfg(feature = "sign")]
77 pub fn from_hex(text: &str) -> Result<Signature, SignError> {
78 let bytes: [u8; 65] = hex::decode_array(text).map_err(|_| SignError::NotASignature)?;
79 let mut r = [0u8; 32];
80 let mut s = [0u8; 32];
81 r.copy_from_slice(&bytes[..32]);
82 s.copy_from_slice(&bytes[32..64]);
83 let parity = match bytes[64] {
84 0 | 27 => 0,
85 1 | 28 => 1,
86 other => return Err(SignError::BadV(other)),
87 };
88 let compact = Signature { r, s, v: V_OFFSET + parity }.to_compact();
89 let curve = CurveSignature::from_slice(&compact).map_err(|_| SignError::Malformed)?;
90 Ok(match curve.normalize_s() {
91 None => Signature { r, s, v: V_OFFSET + parity },
92 Some(low) => {
93 s.copy_from_slice(&low.to_bytes()[32..]);
94 Signature { r, s, v: V_OFFSET + (parity ^ 1) }
95 }
96 })
97 }
98
99 #[must_use]
101 pub const fn r(&self) -> &[u8; 32] {
102 &self.r
103 }
104
105 #[must_use]
107 pub const fn s(&self) -> &[u8; 32] {
108 &self.s
109 }
110
111 #[must_use]
113 pub const fn v(&self) -> u8 {
114 self.v
115 }
116
117 #[must_use]
119 pub const fn recovery_id(&self) -> Option<u8> {
120 self.v.checked_sub(V_OFFSET)
121 }
122
123 #[must_use]
125 pub fn r_hex(&self) -> String {
126 crate::utils::hex::encode_prefixed(&self.r)
127 }
128
129 #[must_use]
131 pub fn s_hex(&self) -> String {
132 crate::utils::hex::encode_prefixed(&self.s)
133 }
134
135 #[must_use]
137 pub fn to_compact(&self) -> [u8; 64] {
138 let mut bytes = [0u8; 64];
139 bytes[..32].copy_from_slice(&self.r);
140 bytes[32..].copy_from_slice(&self.s);
141 bytes
142 }
143
144 #[must_use]
147 pub fn to_json(&self) -> String {
148 self.json().compact()
149 }
150
151 pub(crate) fn json(&self) -> Json {
152 Json::Object(vec![
153 ("r".to_owned(), Json::String(self.r_hex())),
154 ("s".to_owned(), Json::String(self.s_hex())),
155 ("v".to_owned(), Json::Number(self.v.to_string())),
156 ])
157 }
158}
159
160impl Serialize for Signature {
161 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
162 let mut signature = serializer.serialize_struct("Signature", 3)?;
163 signature.serialize_field("r", &self.r_hex())?;
164 signature.serialize_field("s", &self.s_hex())?;
165 signature.serialize_field("v", &self.v)?;
166 signature.end()
167 }
168}
169
170#[cfg(feature = "sign")]
172pub fn recover(digest: &[u8; 32], signature: &Signature) -> Result<Address, SignError> {
173 let recovery_id = signature.recovery_id().and_then(RecoveryId::from_byte).ok_or(SignError::BadV(signature.v))?;
174 let curve_signature = CurveSignature::from_slice(&signature.to_compact()).map_err(|_| SignError::Malformed)?;
175 let key = VerifyingKey::recover_from_prehash(digest, &curve_signature, recovery_id)
176 .map_err(|_| SignError::Unrecoverable)?;
177 Ok(address_of_public_key(&key))
178}
179
180#[cfg(feature = "sign")]
183pub fn verify(digest: &[u8; 32], signature: &Signature, expected: Address) -> Result<(), SignError> {
184 let recovered = recover(digest, signature)?;
185 match recovered == expected {
186 true => Ok(()),
187 false => Err(SignError::WrongSigner { expected, recovered }),
188 }
189}
190
191#[cfg(feature = "sign")]
193#[must_use]
194pub fn address_of_public_key(key: &VerifyingKey) -> Address {
195 let point = key.to_encoded_point(false);
196 let coordinates = &point.as_bytes()[1..];
197 let hash = keccak256(coordinates);
198 let mut bytes = [0u8; 20];
199 bytes.copy_from_slice(&hash[12..]);
200 Address::from_bytes(bytes)
201}
202
203pub trait Signer {
207 fn address(&self) -> Address;
209
210 fn sign_typed(&self, domain: &Domain, data: &TypedStruct<'_>)
212 -> impl Future<Output = Result<Signature, SignError>>;
213}
214
215#[cfg(feature = "sign")]
217const _: fn() = || {
218 fn wiped_on_drop<T: ZeroizeOnDrop>() {}
219 wiped_on_drop::<SigningKey>();
220};
221
222#[cfg(feature = "sign")]
225pub struct LocalKey {
226 key: SigningKey,
227 address: Address,
228}
229
230#[cfg(feature = "sign")]
231impl LocalKey {
232 pub fn from_bytes(secret: &[u8; 32]) -> Result<Self, SignError> {
234 let key = SigningKey::from_bytes(secret.into()).map_err(|_| SignError::NotAKey)?;
235 let address = address_of_public_key(key.verifying_key());
236 Ok(LocalKey { key, address })
237 }
238
239 pub fn from_hex(secret: &str) -> Result<Self, SignError> {
241 let mut bytes = Zeroizing::new([0u8; 32]);
242 hex::decode_into(secret, bytes.as_mut_slice()).map_err(|_| SignError::NotAKey)?;
243 LocalKey::from_bytes(&bytes)
244 }
245
246 #[must_use]
248 pub const fn address(&self) -> Address {
249 self.address
250 }
251
252 pub fn sign_digest(&self, digest: &[u8; 32]) -> Result<Signature, SignError> {
254 let (signature, recovery_id): (CurveSignature, RecoveryId) =
255 self.key.sign_prehash_recoverable(digest).map_err(|_| SignError::Sign)?;
256 let bytes = signature.to_bytes();
257 let mut r = [0u8; 32];
258 let mut s = [0u8; 32];
259 r.copy_from_slice(&bytes[..32]);
260 s.copy_from_slice(&bytes[32..]);
261 Ok(Signature { r, s, v: recovery_id.to_byte() + V_OFFSET })
262 }
263}
264
265#[cfg(feature = "sign")]
266impl Signer for LocalKey {
267 fn address(&self) -> Address {
268 self.address
269 }
270
271 fn sign_typed(
272 &self,
273 domain: &Domain,
274 data: &TypedStruct<'_>,
275 ) -> impl Future<Output = Result<Signature, SignError>> {
276 std::future::ready(self.sign_digest(&data.digest(domain)))
277 }
278}
279
280#[cfg(feature = "sign")]
281impl fmt::Debug for LocalKey {
282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283 f.debug_struct("LocalKey").field("address", &self.address.to_hex()).finish_non_exhaustive()
284 }
285}
286
287#[cfg(feature = "sign")]
289impl ZeroizeOnDrop for LocalKey {}
290
291#[cfg(test)]
292#[cfg(feature = "sign")]
293#[path = "tests/signer.rs"]
294mod tests;