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::{Signature as CurveSignature, SigningKey};
11use serde::{Serialize, Serializer, ser::SerializeStruct};
12#[cfg(feature = "sign")]
13use zeroize::{ZeroizeOnDrop, Zeroizing};
14
15#[cfg(feature = "sign")]
16use crate::account::keys::curve::backend;
17use crate::utils::address::Address;
18#[cfg(feature = "sign")]
19use crate::utils::hex;
20use crate::utils::json::Json;
21use crate::utils::sign::eip712::{Domain, TypedStruct};
22
23pub(crate) const 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")]
171pub use super::recovery::{address_of_public_key, recover, verify};
172
173pub trait Signer {
177 fn address(&self) -> Address;
179
180 fn sign_typed(&self, domain: &Domain, data: &TypedStruct<'_>)
182 -> impl Future<Output = Result<Signature, SignError>>;
183
184 fn signature_is_known_good(&self) -> bool {
191 false
192 }
193}
194
195#[cfg(feature = "sign")]
197const _: fn() = || {
198 fn wiped_on_drop<T: ZeroizeOnDrop>() {}
199 wiped_on_drop::<SigningKey>();
200};
201
202#[cfg(feature = "sign")]
205pub struct LocalKey {
206 key: SigningKey,
207 address: Address,
208 signing: backend::Key,
209}
210
211#[cfg(feature = "sign")]
212impl LocalKey {
213 pub fn from_bytes(secret: &[u8; 32]) -> Result<Self, SignError> {
215 let key = SigningKey::from_bytes(secret.into()).map_err(|_| SignError::NotAKey)?;
216 let address = address_of_public_key(key.verifying_key());
217 let signing = backend::Key::new(&key)?;
218 Ok(LocalKey { key, address, signing })
219 }
220
221 pub fn from_hex(secret: &str) -> Result<Self, SignError> {
223 let mut bytes = Zeroizing::new([0u8; 32]);
224 hex::decode_into(secret, bytes.as_mut_slice()).map_err(|_| SignError::NotAKey)?;
225 LocalKey::from_bytes(&bytes)
226 }
227
228 #[must_use]
230 pub const fn address(&self) -> Address {
231 self.address
232 }
233
234 pub fn sign_digest(&self, digest: &[u8; 32]) -> Result<Signature, SignError> {
237 self.signing.sign(&self.key, digest)
238 }
239
240 #[cfg(all(any(test, fuzzing), feature = "secp256k1", not(target_arch = "wasm32")))]
242 pub(crate) const fn curve_key(&self) -> &SigningKey {
243 &self.key
244 }
245}
246
247#[cfg(feature = "sign")]
248impl Signer for LocalKey {
249 fn address(&self) -> Address {
250 self.address
251 }
252
253 fn sign_typed(
254 &self,
255 domain: &Domain,
256 data: &TypedStruct<'_>,
257 ) -> impl Future<Output = Result<Signature, SignError>> {
258 std::future::ready(self.sign_digest(&data.digest(domain)))
259 }
260
261 fn signature_is_known_good(&self) -> bool {
263 true
264 }
265}
266
267#[cfg(feature = "sign")]
268impl fmt::Debug for LocalKey {
269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270 f.debug_struct("LocalKey").field("address", &self.address.to_hex()).finish_non_exhaustive()
271 }
272}
273
274#[cfg(feature = "sign")]
276impl ZeroizeOnDrop for LocalKey {}
277
278#[cfg(test)]
279#[cfg(feature = "sign")]
280#[path = "tests/signer.rs"]
281mod tests;