signet_types/seq/
resp.rs

1use crate::SignRequest;
2use alloy::primitives::{Address, Signature, SignatureError};
3use serde::{Deserialize, Serialize};
4
5/// A signature response from a [`RequestSigner`].
6///
7/// [`RequestSigner`]: crate::RequestSigner
8#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
9#[serde(rename_all = "camelCase")]
10pub struct SignResponse {
11    /// The request that was signed.
12    pub req: SignRequest,
13    /// The signature over that request.
14    pub sig: Signature,
15}
16
17impl SignResponse {
18    /// Get the signer of the request.
19    ///
20    /// # Panics
21    ///
22    /// - If recovery fails due to a k256 error.
23    pub fn signer(&self) -> Result<Address, SignatureError> {
24        self.sig.recover_address_from_prehash(&self.req.signing_hash())
25    }
26}
27
28#[cfg(test)]
29mod test {
30    use super::*;
31    use crate::{RequestSigner, SignRequest};
32    use alloy::primitives::U256;
33
34    #[tokio::test]
35    async fn test_sign_response() {
36        let req = SignRequest {
37            host_block_number: U256::from(0),
38            host_chain_id: U256::from(1u64),
39            ru_chain_id: U256::from(2u64),
40            gas_limit: U256::from(5u64),
41            ru_reward_address: Address::repeat_byte(6),
42            contents: [7u8; 32].into(),
43        };
44        let signer = alloy::signers::local::PrivateKeySigner::from_slice(&[8u8; 32]).unwrap();
45        let sig = signer.sign_request(&req).await.unwrap();
46        let resp = SignResponse { req, sig };
47        let addr = resp.signer().unwrap();
48
49        assert_eq!(addr, signer.address());
50    }
51
52    #[tokio::test]
53    async fn deser_roundtrip() {
54        let req = SignRequest {
55            host_block_number: U256::from(0),
56            host_chain_id: U256::from(1u64),
57            ru_chain_id: U256::from(2u64),
58            gas_limit: U256::from(5u64),
59            ru_reward_address: Address::repeat_byte(6),
60            contents: [7u8; 32].into(),
61        };
62        let signer = alloy::signers::local::PrivateKeySigner::from_slice(&[8u8; 32]).unwrap();
63
64        let sig = signer.sign_request(&req).await.unwrap();
65
66        let resp = SignResponse { req, sig };
67
68        let json = serde_json::to_string(&resp).unwrap();
69        let resp2: SignResponse = serde_json::from_str(&json).unwrap();
70
71        assert_eq!(resp, resp2);
72    }
73}