alloy_signer/
signer.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
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
use crate::Result;
use alloy_primitives::{eip191_hash_message, Address, ChainId, Signature, B256};
use async_trait::async_trait;
use auto_impl::auto_impl;

#[cfg(feature = "eip712")]
use alloy_dyn_abi::eip712::TypedData;
#[cfg(feature = "eip712")]
use alloy_sol_types::{Eip712Domain, SolStruct};

/// Asynchronous Ethereum signer.
///
/// All provided implementations rely on [`sign_hash`](Signer::sign_hash). A signer may not always
/// be able to implement this method, in which case it should return
/// [`UnsupportedOperation`](crate::Error::UnsupportedOperation), and implement all the signing
/// methods directly.
///
/// Synchronous signers should implement both this trait and [`SignerSync`].
///
/// [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[auto_impl(&mut, Box)]
pub trait Signer<Sig = Signature> {
    /// Signs the given hash.
    async fn sign_hash(&self, hash: &B256) -> Result<Sig>;

    /// Signs the hash of the provided message after prefixing it, as specified in [EIP-191].
    ///
    /// [EIP-191]: https://eips.ethereum.org/EIPS/eip-191
    #[inline]
    async fn sign_message(&self, message: &[u8]) -> Result<Sig> {
        self.sign_hash(&eip191_hash_message(message)).await
    }

    /// Encodes and signs the typed data according to [EIP-712].
    ///
    /// [EIP-712]: https://eips.ethereum.org/EIPS/eip-712
    #[cfg(feature = "eip712")]
    #[inline]
    #[auto_impl(keep_default_for(&mut, Box))]
    async fn sign_typed_data<T: SolStruct + Send + Sync>(
        &self,
        payload: &T,
        domain: &Eip712Domain,
    ) -> Result<Sig>
    where
        Self: Sized,
    {
        self.sign_hash(&payload.eip712_signing_hash(domain)).await
    }

    /// Encodes and signs the typed data according to [EIP-712] for Signers that are not dynamically
    /// sized.
    #[cfg(feature = "eip712")]
    #[inline]
    async fn sign_dynamic_typed_data(&self, payload: &TypedData) -> Result<Sig> {
        self.sign_hash(&payload.eip712_signing_hash()?).await
    }

    /// Returns the signer's Ethereum Address.
    fn address(&self) -> Address;

    /// Returns the signer's chain ID.
    fn chain_id(&self) -> Option<ChainId>;

    /// Sets the signer's chain ID.
    fn set_chain_id(&mut self, chain_id: Option<ChainId>);

    /// Sets the signer's chain ID and returns `self`.
    #[inline]
    #[must_use]
    #[auto_impl(keep_default_for(&mut, Box))]
    fn with_chain_id(mut self, chain_id: Option<ChainId>) -> Self
    where
        Self: Sized,
    {
        self.set_chain_id(chain_id);
        self
    }
}

/// Synchronous Ethereum signer.
///
/// All provided implementations rely on [`sign_hash_sync`](SignerSync::sign_hash_sync). A signer
/// may not always be able to implement this method, in which case it should return
/// [`UnsupportedOperation`](crate::Error::UnsupportedOperation), and implement all the signing
/// methods directly.
///
/// Synchronous signers should also implement [`Signer`], as they are always able to by delegating
/// the asynchronous methods to the synchronous ones.
///
/// [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
#[auto_impl(&, &mut, Box, Rc, Arc)]
pub trait SignerSync<Sig = Signature> {
    /// Signs the given hash.
    fn sign_hash_sync(&self, hash: &B256) -> Result<Sig>;

    /// Signs the hash of the provided message after prefixing it, as specified in [EIP-191].
    ///
    /// [EIP-191]: https://eips.ethereum.org/EIPS/eip-191
    #[inline]
    fn sign_message_sync(&self, message: &[u8]) -> Result<Sig> {
        self.sign_hash_sync(&eip191_hash_message(message))
    }

    /// Encodes and signs the typed data according to [EIP-712].
    ///
    /// [EIP-712]: https://eips.ethereum.org/EIPS/eip-712
    #[cfg(feature = "eip712")]
    #[inline]
    #[auto_impl(keep_default_for(&, &mut, Box, Rc, Arc))]
    fn sign_typed_data_sync<T: SolStruct>(&self, payload: &T, domain: &Eip712Domain) -> Result<Sig>
    where
        Self: Sized,
    {
        self.sign_hash_sync(&payload.eip712_signing_hash(domain))
    }

    /// Encodes and signs the typed data according to [EIP-712] for Signers that are not dynamically
    /// sized.
    ///
    /// [EIP-712]: https://eips.ethereum.org/EIPS/eip-712
    #[cfg(feature = "eip712")]
    #[inline]
    fn sign_dynamic_typed_data_sync(&self, payload: &TypedData) -> Result<Sig> {
        let hash = payload.eip712_signing_hash()?;
        self.sign_hash_sync(&hash)
    }

    /// Returns the signer's chain ID.
    fn chain_id_sync(&self) -> Option<ChainId>;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Error, UnsupportedSignerOperation};
    use assert_matches::assert_matches;
    use std::sync::Arc;

    struct _ObjectSafe(Box<dyn Signer>, Box<dyn SignerSync>);

    #[tokio::test]
    async fn unimplemented() {
        #[cfg(feature = "eip712")]
        alloy_sol_types::sol! {
            #[derive(Default, serde::Serialize)]
            struct Eip712Data {
                uint64 a;
            }
        }

        async fn test_unimplemented_signer<S: Signer + SignerSync + Send + Sync>(s: &S) {
            test_unsized_unimplemented_signer(s).await;
            test_unsized_unimplemented_signer_sync(s);

            #[cfg(feature = "eip712")]
            assert!(s
                .sign_typed_data_sync(&Eip712Data::default(), &Eip712Domain::default())
                .is_err());
            #[cfg(feature = "eip712")]
            assert!(s
                .sign_typed_data(&Eip712Data::default(), &Eip712Domain::default())
                .await
                .is_err());
        }

        async fn test_unsized_unimplemented_signer<S: Signer + ?Sized + Send + Sync>(s: &S) {
            assert_matches!(
                s.sign_hash(&B256::ZERO).await,
                Err(Error::UnsupportedOperation(UnsupportedSignerOperation::SignHash))
            );

            assert_matches!(
                s.sign_message(&[]).await,
                Err(Error::UnsupportedOperation(UnsupportedSignerOperation::SignHash))
            );

            #[cfg(feature = "eip712")]
            assert_matches!(
                s.sign_dynamic_typed_data(&TypedData::from_struct(&Eip712Data::default(), None))
                    .await,
                Err(Error::UnsupportedOperation(UnsupportedSignerOperation::SignHash))
            );

            assert_eq!(s.chain_id(), None);
        }

        fn test_unsized_unimplemented_signer_sync<S: SignerSync + ?Sized>(s: &S) {
            assert_matches!(
                s.sign_hash_sync(&B256::ZERO),
                Err(Error::UnsupportedOperation(UnsupportedSignerOperation::SignHash))
            );

            assert_matches!(
                s.sign_message_sync(&[]),
                Err(Error::UnsupportedOperation(UnsupportedSignerOperation::SignHash))
            );

            #[cfg(feature = "eip712")]
            assert_matches!(
                s.sign_dynamic_typed_data_sync(&TypedData::from_struct(
                    &Eip712Data::default(),
                    None
                )),
                Err(Error::UnsupportedOperation(UnsupportedSignerOperation::SignHash))
            );

            assert_eq!(s.chain_id_sync(), None);
        }

        struct UnimplementedSigner;

        #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
        #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
        impl Signer for UnimplementedSigner {
            async fn sign_hash(&self, _hash: &B256) -> Result<Signature> {
                Err(Error::UnsupportedOperation(UnsupportedSignerOperation::SignHash))
            }

            fn address(&self) -> Address {
                Address::ZERO
            }

            fn chain_id(&self) -> Option<ChainId> {
                None
            }

            fn set_chain_id(&mut self, _chain_id: Option<ChainId>) {}
        }

        impl SignerSync for UnimplementedSigner {
            fn sign_hash_sync(&self, _hash: &B256) -> Result<Signature> {
                Err(Error::UnsupportedOperation(UnsupportedSignerOperation::SignHash))
            }

            fn chain_id_sync(&self) -> Option<ChainId> {
                None
            }
        }

        test_unimplemented_signer(&UnimplementedSigner).await;
        test_unsized_unimplemented_signer(&UnimplementedSigner as &(dyn Signer + Send + Sync))
            .await;
        test_unsized_unimplemented_signer_sync(
            &UnimplementedSigner as &(dyn SignerSync + Send + Sync),
        );

        test_unsized_unimplemented_signer(
            &(Box::new(UnimplementedSigner) as Box<dyn Signer + Send + Sync>),
        )
        .await;
        test_unsized_unimplemented_signer_sync(
            &(Box::new(UnimplementedSigner) as Box<dyn SignerSync + Send + Sync>),
        );

        test_unsized_unimplemented_signer_sync(
            &(Arc::new(UnimplementedSigner) as Arc<dyn SignerSync + Send + Sync>),
        );
    }
}