Skip to main content

cast/cmd/safe/
service.rs

1use super::contracts::{ISafe, SafeTx};
2use alloy_network::Ethereum;
3use alloy_primitives::{Address, B256, Bytes, U256};
4use alloy_sol_types::{SolStruct, eip712_domain};
5use clap::Args;
6use eyre::{Context, Result, ensure};
7use foundry_common::{sh_status, sh_warn};
8use reqwest::{Client, Method, Url, header};
9use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
10use serde_json::{Value, json};
11use std::str::FromStr;
12
13const SAFE_SIGNATURE_LENGTH: usize = 65;
14const CONTRACT_SIGNATURE_HEADER_LENGTH: usize = SAFE_SIGNATURE_LENGTH + U256::BYTES;
15const P256_SIGNATURE_DATA_LENGTH: usize = 128;
16const P256_SIGNATURE_LENGTH: usize = SAFE_SIGNATURE_LENGTH + P256_SIGNATURE_DATA_LENGTH;
17
18#[derive(Args, Clone, Debug)]
19pub struct SafeServiceOpts {
20    /// Safe Transaction Service URL. Inferred from the RPC chain ID when omitted.
21    /// The `/api` suffix is optional.
22    #[arg(long, env = "SAFE_TRANSACTION_SERVICE_URL")]
23    pub(super) service_url: Option<Url>,
24
25    /// Safe Transaction Service API key.
26    #[arg(long, env = "SAFE_API_KEY")]
27    api_key: Option<String>,
28}
29
30#[derive(Debug, Deserialize)]
31#[serde(rename_all = "camelCase")]
32pub(super) struct SafeTransaction {
33    pub(super) safe: Address,
34    pub(super) to: Address,
35    #[serde(deserialize_with = "deserialize_number_string")]
36    pub(super) value: String,
37    #[serde(default, deserialize_with = "deserialize_null_default")]
38    pub(super) data: Bytes,
39    pub(super) operation: u8,
40    #[serde(deserialize_with = "deserialize_number_string")]
41    pub(super) safe_tx_gas: String,
42    #[serde(deserialize_with = "deserialize_number_string")]
43    pub(super) base_gas: String,
44    #[serde(deserialize_with = "deserialize_number_string")]
45    pub(super) gas_price: String,
46    #[serde(default, deserialize_with = "deserialize_null_default")]
47    pub(super) gas_token: Address,
48    #[serde(default, deserialize_with = "deserialize_null_default")]
49    pub(super) refund_receiver: Address,
50    #[serde(deserialize_with = "deserialize_number_string")]
51    pub(super) nonce: String,
52    #[serde(alias = "contractTransactionHash")]
53    pub(super) safe_tx_hash: B256,
54    #[serde(default, deserialize_with = "deserialize_null_default")]
55    pub(super) confirmations: Vec<SafeConfirmation>,
56    #[serde(default)]
57    pub(super) is_executed: bool,
58    #[serde(default)]
59    pub(super) transaction_hash: Option<B256>,
60}
61
62#[derive(Debug, Deserialize)]
63#[serde(rename_all = "camelCase")]
64pub(super) struct SafeConfirmation {
65    owner: Address,
66    #[serde(default)]
67    signature: Option<Bytes>,
68}
69
70#[derive(Debug, Deserialize, Serialize)]
71#[serde(rename_all = "camelCase")]
72pub(super) struct SafeDelegate {
73    safe: Option<Address>,
74    delegate: Address,
75    delegator: Address,
76    label: String,
77}
78
79#[derive(Debug, Deserialize)]
80pub(super) struct SafeDelegatesResponse {
81    #[serde(default)]
82    pub(super) next: Option<String>,
83    pub(super) results: Vec<SafeDelegate>,
84}
85
86impl SafeTransaction {
87    pub(super) fn number(value: &str, field: &str) -> Result<U256> {
88        U256::from_str(value).wrap_err_with(|| format!("invalid {field} in transaction"))
89    }
90
91    /// Computes a standard Safe transaction hash locally and checks that the contract agrees.
92    pub(super) async fn calculate_hash<P>(&self, provider: &P, chain_id: u64) -> Result<B256>
93    where
94        P: alloy_provider::Provider<Ethereum>,
95    {
96        let transaction = SafeTx {
97            to: self.to,
98            value: Self::number(&self.value, "value")?,
99            data: self.data.clone(),
100            operation: self.operation,
101            safeTxGas: Self::number(&self.safe_tx_gas, "safeTxGas")?,
102            baseGas: Self::number(&self.base_gas, "baseGas")?,
103            gasPrice: Self::number(&self.gas_price, "gasPrice")?,
104            gasToken: self.gas_token,
105            refundReceiver: self.refund_receiver,
106            nonce: Self::number(&self.nonce, "nonce")?,
107        };
108        let calculated = transaction.eip712_signing_hash(&eip712_domain! {
109            chain_id: chain_id,
110            verifying_contract: self.safe,
111        });
112        // Safe v1.0.0 through v1.2.0 omit the chain ID from the domain.
113        let legacy = transaction.eip712_signing_hash(&eip712_domain! {
114            verifying_contract: self.safe,
115        });
116        let remote = ISafe::new(self.safe, provider)
117            .getTransactionHash(
118                transaction.to,
119                transaction.value,
120                transaction.data,
121                transaction.operation,
122                transaction.safeTxGas,
123                transaction.baseGas,
124                transaction.gasPrice,
125                transaction.gasToken,
126                transaction.refundReceiver,
127                transaction.nonce,
128            )
129            .call()
130            .await
131            .wrap_err("failed to calculate Safe transaction hash")?;
132        ensure!(
133            remote == calculated || remote == legacy,
134            "Safe transaction hash mismatch: contract returned {remote}, locally calculated {calculated} (chain ID {chain_id}) or {legacy} (pre-v1.3.0 Safe)"
135        );
136        if remote == legacy {
137            sh_warn!(
138                "This Safe uses a pre-v1.3.0 transaction hash without a chain ID. Its signatures can be replayed on other chains."
139            )?;
140        }
141        Ok(remote)
142    }
143
144    pub(super) async fn verify_hash<P>(
145        &self,
146        expected_safe: Address,
147        provider: &P,
148        chain_id: u64,
149    ) -> Result<()>
150    where
151        P: alloy_provider::Provider<Ethereum>,
152    {
153        ensure!(
154            self.safe == expected_safe,
155            "Transaction Service returned Safe {}, expected {expected_safe}",
156            self.safe
157        );
158        ensure!(self.operation <= 1, "invalid Safe operation: {}", self.operation);
159        let calculated = self.calculate_hash(provider, chain_id).await?;
160        ensure!(
161            calculated == self.safe_tx_hash,
162            "Safe transaction hash mismatch: service/file returned {}, calculated {calculated}",
163            self.safe_tx_hash
164        );
165        Ok(())
166    }
167
168    pub(super) fn proposal_body(
169        &self,
170        sender: Address,
171        signature: String,
172        origin: Option<String>,
173    ) -> Value {
174        let mut body = json!({
175            "to": self.to.to_checksum(None),
176            "value": self.value,
177            "data": self.data,
178            "operation": self.operation,
179            "safeTxGas": self.safe_tx_gas,
180            "baseGas": self.base_gas,
181            "gasPrice": self.gas_price,
182            "gasToken": self.gas_token.to_checksum(None),
183            "refundReceiver": self.refund_receiver.to_checksum(None),
184            "nonce": self.nonce,
185            "contractTransactionHash": self.safe_tx_hash,
186            "sender": sender.to_checksum(None),
187            "signature": signature,
188        });
189        if let Some(origin) = origin {
190            body["origin"] = Value::String(origin);
191        }
192        body
193    }
194
195    pub(super) fn packed_signatures(&self) -> Result<Bytes> {
196        let mut confirmations = self.confirmations.iter().collect::<Vec<_>>();
197        confirmations.sort_unstable_by_key(|confirmation| confirmation.owner);
198        let static_len = confirmations.len() * SAFE_SIGNATURE_LENGTH;
199        let mut signatures = Vec::with_capacity(static_len);
200        let mut dynamic = Vec::new();
201        for confirmation in confirmations {
202            let signature = confirmation.signature.as_ref().ok_or_else(|| {
203                eyre::eyre!("confirmation from {} does not contain a signature", confirmation.owner)
204            })?;
205            ensure!(
206                signature.len() >= SAFE_SIGNATURE_LENGTH,
207                "invalid signature from {}: expected at least {SAFE_SIGNATURE_LENGTH} bytes, got {}",
208                confirmation.owner,
209                signature.len()
210            );
211            let v = signature[SAFE_SIGNATURE_LENGTH - 1];
212            match v {
213                // Contract (v = 0) and P-256 (v = 2) signatures carry dynamic data after the
214                // static part, which points at the dynamic offset.
215                0 | 2 => {
216                    let kind = if v == 0 { "contract" } else { "P-256" };
217                    if v == 0 {
218                        ensure!(
219                            signature.len() >= CONTRACT_SIGNATURE_HEADER_LENGTH,
220                            "contract signature from {} does not contain a length",
221                            confirmation.owner
222                        );
223                        let data_len = U256::from_be_slice(
224                            &signature[SAFE_SIGNATURE_LENGTH..CONTRACT_SIGNATURE_HEADER_LENGTH],
225                        );
226                        ensure!(
227                            data_len
228                                == U256::from(signature.len() - CONTRACT_SIGNATURE_HEADER_LENGTH),
229                            "invalid contract signature length from {}: expected {}, got {data_len}",
230                            confirmation.owner,
231                            signature.len() - CONTRACT_SIGNATURE_HEADER_LENGTH
232                        );
233                    } else {
234                        ensure!(
235                            signature.len() == P256_SIGNATURE_LENGTH,
236                            "invalid P-256 signature from {}: expected {P256_SIGNATURE_LENGTH} bytes, got {}",
237                            confirmation.owner,
238                            signature.len()
239                        );
240                    }
241                    let offset =
242                        U256::from_be_slice(&signature[U256::BYTES..SAFE_SIGNATURE_LENGTH - 1]);
243                    ensure!(
244                        offset == U256::from(SAFE_SIGNATURE_LENGTH),
245                        "invalid {kind} signature offset from {}: expected {SAFE_SIGNATURE_LENGTH}, got {offset}",
246                        confirmation.owner
247                    );
248
249                    signatures.extend_from_slice(&signature[..U256::BYTES]);
250                    signatures.extend_from_slice(
251                        &U256::from(static_len + dynamic.len()).to_be_bytes::<{ U256::BYTES }>(),
252                    );
253                    signatures.push(v);
254                    dynamic.extend_from_slice(&signature[SAFE_SIGNATURE_LENGTH..]);
255                }
256                1 => {
257                    eyre::bail!(
258                        "approved-hash signatures (v = 1) are not supported by `cast safe execute`"
259                    );
260                }
261                _ => {
262                    ensure!(
263                        signature.len() == SAFE_SIGNATURE_LENGTH,
264                        "invalid signature from {}: expected {SAFE_SIGNATURE_LENGTH} bytes, got {}",
265                        confirmation.owner,
266                        signature.len()
267                    );
268                    signatures.extend_from_slice(signature);
269                }
270            }
271        }
272        ensure!(!signatures.is_empty(), "Safe transaction has no confirmations");
273        signatures.extend_from_slice(&dynamic);
274        Ok(signatures.into())
275    }
276
277    pub(super) fn show_transaction_summary(&self, chain_id: u64) -> Result<()> {
278        let operation = if self.operation == 0 { "CALL" } else { "DELEGATECALL" };
279        sh_status!("Safe transaction: {}", self.safe_tx_hash)?;
280        sh_status!("  Chain ID:        {chain_id}")?;
281        sh_status!("  Safe:            {}", self.safe)?;
282        sh_status!("  To:              {}", self.to)?;
283        sh_status!("  Value:           {}", self.value)?;
284        sh_status!("  Operation:       {} ({operation})", self.operation)?;
285        sh_status!("  Safe tx gas:     {}", self.safe_tx_gas)?;
286        sh_status!("  Base gas:        {}", self.base_gas)?;
287        sh_status!("  Gas price:       {}", self.gas_price)?;
288        sh_status!("  Gas token:       {}", self.gas_token)?;
289        sh_status!("  Refund receiver: {}", self.refund_receiver)?;
290        sh_status!("  Nonce:           {}", self.nonce)?;
291        sh_status!("  Data:            {}", self.data)?;
292        Ok(())
293    }
294}
295
296impl SafeServiceOpts {
297    pub(super) fn endpoint(&self, chain_id: u64, path: &str) -> Result<Url> {
298        let mut url = match &self.service_url {
299            Some(url) => url.clone(),
300            None => default_service_url(chain_id)?,
301        };
302        let mut endpoint = url.path().trim_end_matches('/').to_string();
303        if !endpoint.ends_with("/api") {
304            endpoint.push_str("/api");
305        }
306        endpoint.push('/');
307        endpoint.push_str(path.trim_start_matches('/'));
308        url.set_path(&endpoint);
309        url.set_query(None);
310        url.set_fragment(None);
311        Ok(url)
312    }
313
314    pub(super) fn request(&self, method: Method, url: Url) -> reqwest::RequestBuilder {
315        let request = Client::new()
316            .request(method, url)
317            .header(header::ACCEPT, "application/json")
318            .header(header::CONTENT_TYPE, "application/json");
319        if let Some(api_key) = &self.api_key { request.bearer_auth(api_key) } else { request }
320    }
321
322    /// Sends `request` and returns the successful response body.
323    async fn send(&self, request: reqwest::RequestBuilder) -> Result<String> {
324        let response = request.send().await.wrap_err("Safe Transaction Service request failed")?;
325        let status = response.status();
326        let text = response.text().await.wrap_err("failed to read Transaction Service response")?;
327        ensure!(status.is_success(), "Safe Transaction Service returned {status}: {}", text.trim());
328        Ok(text)
329    }
330
331    pub(super) async fn response<T: DeserializeOwned>(
332        &self,
333        request: reqwest::RequestBuilder,
334    ) -> Result<T> {
335        serde_json::from_str(&self.send(request).await?)
336            .wrap_err("invalid Transaction Service response")
337    }
338
339    pub(super) async fn empty_response(&self, request: reqwest::RequestBuilder) -> Result<()> {
340        self.send(request).await.map(drop)
341    }
342
343    pub(super) async fn get_transaction(
344        &self,
345        chain_id: u64,
346        api_version: &str,
347        safe_tx_hash: B256,
348    ) -> Result<SafeTransaction> {
349        let url = self
350            .endpoint(chain_id, &format!("{api_version}/multisig-transactions/{safe_tx_hash}/"))?;
351        let transaction: SafeTransaction = self.response(self.request(Method::GET, url)).await?;
352        ensure!(
353            transaction.safe_tx_hash == safe_tx_hash,
354            "Transaction Service returned a different Safe transaction hash"
355        );
356        Ok(transaction)
357    }
358
359    pub(super) async fn next_nonce(
360        &self,
361        chain_id: u64,
362        safe: Address,
363        onchain_nonce: U256,
364    ) -> Result<U256> {
365        let response: Value = self
366            .response(self.request(Method::GET, self.next_nonce_endpoint(chain_id, safe)?))
367            .await?;
368        let Some(nonce) = response
369            .get("results")
370            .and_then(Value::as_array)
371            .and_then(|results| results.first())
372            .and_then(|tx| tx.get("nonce"))
373        else {
374            return Ok(onchain_nonce);
375        };
376        let nonce = match nonce {
377            Value::String(nonce) => U256::from_str(nonce),
378            Value::Number(nonce) => U256::from_str(&nonce.to_string()),
379            _ => eyre::bail!("invalid nonce returned by Safe Transaction Service"),
380        }
381        .wrap_err("invalid nonce returned by Safe Transaction Service")?;
382        Ok(std::cmp::max(onchain_nonce, nonce.saturating_add(U256::ONE)))
383    }
384
385    fn next_nonce_endpoint(&self, chain_id: u64, safe: Address) -> Result<Url> {
386        let mut url = self.endpoint(
387            chain_id,
388            &format!("v1/safes/{}/multisig-transactions/", safe.to_checksum(None)),
389        )?;
390        url.query_pairs_mut()
391            .append_pair("executed", "false")
392            .append_pair("ordering", "-nonce")
393            .append_pair("limit", "1");
394        Ok(url)
395    }
396}
397
398fn deserialize_number_string<'de, D>(deserializer: D) -> Result<String, D::Error>
399where
400    D: Deserializer<'de>,
401{
402    match Value::deserialize(deserializer)? {
403        Value::String(value) => Ok(value),
404        Value::Number(value) => Ok(value.to_string()),
405        value => Err(serde::de::Error::custom(format!("expected number or string, got {value}"))),
406    }
407}
408
409fn deserialize_null_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
410where
411    D: Deserializer<'de>,
412    T: Deserialize<'de> + Default,
413{
414    Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
415}
416
417fn default_service_url(chain_id: u64) -> Result<Url> {
418    let short_name = match chain_id {
419        1 => "eth",
420        10 => "oeth",
421        56 => "bnb",
422        100 => "gno",
423        130 => "unichain",
424        137 => "pol",
425        146 => "sonic",
426        196 => "okb",
427        232 => "lens",
428        324 => "zksync",
429        480 => "wc",
430        4217 => "tempo",
431        5000 => "mantle",
432        8453 => "base",
433        9745 => "plasma",
434        10200 => "chi",
435        42161 => "arb1",
436        42220 => "celo",
437        42431 => "tempo-moderato",
438        43114 => "avax",
439        43111 => "hemi",
440        57073 => "ink",
441        59144 => "linea",
442        747474 => "katana",
443        80094 => "berachain",
444        84532 => "basesep",
445        534352 => "scr",
446        11155111 => "sep",
447        1313161554 => "aurora",
448        _ => eyre::bail!(
449            "no known Safe Transaction Service for chain ID {chain_id}; pass --service-url"
450        ),
451    };
452    format!("https://api.safe.global/tx-service/{short_name}")
453        .parse()
454        .wrap_err("invalid built-in Safe Transaction Service URL")
455}
456
457#[cfg(test)]
458mod tests {
459    use super::*;
460
461    fn transaction() -> SafeTransaction {
462        SafeTransaction {
463            safe: Address::ZERO,
464            to: Address::ZERO,
465            value: "1".to_string(),
466            data: Bytes::new(),
467            operation: 0,
468            safe_tx_gas: "0".to_string(),
469            base_gas: "0".to_string(),
470            gas_price: "0".to_string(),
471            gas_token: Address::ZERO,
472            refund_receiver: Address::ZERO,
473            nonce: "7".to_string(),
474            safe_tx_hash: B256::ZERO,
475            confirmations: Vec::new(),
476            is_executed: false,
477            transaction_hash: None,
478        }
479    }
480
481    fn eoa_signature(byte: u8) -> Bytes {
482        let mut signature = vec![byte; SAFE_SIGNATURE_LENGTH];
483        signature[SAFE_SIGNATURE_LENGTH - 1] = 27;
484        signature.into()
485    }
486
487    fn contract_signature(owner: Address, payload: &[u8]) -> Bytes {
488        let mut signature = Vec::with_capacity(CONTRACT_SIGNATURE_HEADER_LENGTH + payload.len());
489        signature.extend_from_slice(owner.into_word().as_slice());
490        signature.extend_from_slice(&U256::from(SAFE_SIGNATURE_LENGTH).to_be_bytes::<32>());
491        signature.push(0);
492        signature.extend_from_slice(&U256::from(payload.len()).to_be_bytes::<32>());
493        signature.extend_from_slice(payload);
494        signature.into()
495    }
496
497    fn p256_signature(owner: Address, payload: &[u8; 128]) -> Bytes {
498        let mut signature = Vec::with_capacity(SAFE_SIGNATURE_LENGTH + payload.len());
499        signature.extend_from_slice(owner.into_word().as_slice());
500        signature.extend_from_slice(&U256::from(SAFE_SIGNATURE_LENGTH).to_be_bytes::<32>());
501        signature.push(2);
502        signature.extend_from_slice(payload);
503        signature.into()
504    }
505
506    #[test]
507    fn normalizes_transaction_service_urls() {
508        for base in [
509            "https://api.safe.global/tx-service/tempo-moderato/",
510            "https://api.safe.global/tx-service/tempo-moderato/api",
511        ] {
512            let service =
513                SafeServiceOpts { service_url: Some(base.parse().unwrap()), api_key: None };
514            assert_eq!(
515                service.endpoint(42431, "v2/delegates/").unwrap().as_str(),
516                "https://api.safe.global/tx-service/tempo-moderato/api/v2/delegates/"
517            );
518        }
519    }
520
521    #[test]
522    fn infers_tempo_transaction_service_urls() {
523        assert_eq!(
524            default_service_url(4217).unwrap().as_str(),
525            "https://api.safe.global/tx-service/tempo"
526        );
527        assert_eq!(
528            default_service_url(42431).unwrap().as_str(),
529            "https://api.safe.global/tx-service/tempo-moderato"
530        );
531        for chain_id in [1101, 81457, 31337] {
532            assert!(default_service_url(chain_id).is_err());
533        }
534    }
535
536    #[test]
537    fn builds_pending_nonce_query_as_url_parameters() {
538        let service = SafeServiceOpts { service_url: None, api_key: None };
539        assert_eq!(
540            service.next_nonce_endpoint(42431, Address::ZERO).unwrap().as_str(),
541            "https://api.safe.global/tx-service/tempo-moderato/api/v1/safes/0x0000000000000000000000000000000000000000/multisig-transactions/?executed=false&ordering=-nonce&limit=1"
542        );
543    }
544
545    #[test]
546    fn parses_transaction_service_response() {
547        let transaction: SafeTransaction = serde_json::from_value(json!({
548            "safe": Address::ZERO,
549            "to": Address::ZERO,
550            "value": "1",
551            "data": null,
552            "operation": 0,
553            "safeTxGas": 0,
554            "baseGas": "0",
555            "gasPrice": 0,
556            "gasToken": null,
557            "refundReceiver": null,
558            "nonce": 7,
559            "safeTxHash": B256::ZERO,
560        }))
561        .unwrap();
562
563        assert_eq!(transaction.data, Bytes::new());
564        assert_eq!(transaction.nonce, "7");
565        assert_eq!(transaction.gas_token, Address::ZERO);
566        assert_eq!(transaction.refund_receiver, Address::ZERO);
567    }
568
569    #[test]
570    fn packs_confirmations_in_owner_order() {
571        let mut transaction = transaction();
572        transaction.confirmations = vec![
573            SafeConfirmation { owner: Address::repeat_byte(2), signature: Some(eoa_signature(2)) },
574            SafeConfirmation { owner: Address::repeat_byte(1), signature: Some(eoa_signature(1)) },
575        ];
576
577        let signatures = transaction.packed_signatures().unwrap();
578        assert_eq!(&signatures[..64], &[1; 64]);
579        assert_eq!(signatures[64], 27);
580        assert_eq!(&signatures[65..129], &[2; 64]);
581        assert_eq!(signatures[129], 27);
582    }
583
584    #[test]
585    fn packs_contract_signatures_after_static_signatures() {
586        let first_owner = Address::repeat_byte(1);
587        let third_owner = Address::repeat_byte(3);
588        let first_payload = [4, 5, 6];
589        let third_payload = [7, 8, 9, 10];
590
591        let mut transaction = transaction();
592        transaction.confirmations = vec![
593            SafeConfirmation {
594                owner: third_owner,
595                signature: Some(contract_signature(third_owner, &third_payload)),
596            },
597            SafeConfirmation { owner: Address::repeat_byte(2), signature: Some(eoa_signature(2)) },
598            SafeConfirmation {
599                owner: first_owner,
600                signature: Some(contract_signature(first_owner, &first_payload)),
601            },
602        ];
603
604        let signatures = transaction.packed_signatures().unwrap();
605        assert_eq!(&signatures[..32], first_owner.into_word().as_slice());
606        assert_eq!(U256::from_be_slice(&signatures[32..64]), U256::from(195));
607        assert_eq!(signatures[64], 0);
608        assert_eq!(&signatures[65..130], &eoa_signature(2));
609        assert_eq!(&signatures[130..162], third_owner.into_word().as_slice());
610        assert_eq!(U256::from_be_slice(&signatures[162..194]), U256::from(230));
611        assert_eq!(signatures[194], 0);
612        assert_eq!(U256::from_be_slice(&signatures[195..227]), U256::from(3));
613        assert_eq!(&signatures[227..230], &first_payload);
614        assert_eq!(U256::from_be_slice(&signatures[230..262]), U256::from(4));
615        assert_eq!(&signatures[262..], &third_payload);
616    }
617
618    #[test]
619    fn packs_p256_and_contract_signatures_after_static_signatures() {
620        let p256_owner = Address::repeat_byte(1);
621        let contract_owner = Address::repeat_byte(3);
622        let p256_payload = [4; 128];
623        let contract_payload = [5, 6, 7];
624        let mut transaction = transaction();
625        transaction.confirmations = vec![
626            SafeConfirmation {
627                owner: contract_owner,
628                signature: Some(contract_signature(contract_owner, &contract_payload)),
629            },
630            SafeConfirmation { owner: Address::repeat_byte(2), signature: Some(eoa_signature(2)) },
631            SafeConfirmation {
632                owner: p256_owner,
633                signature: Some(p256_signature(p256_owner, &p256_payload)),
634            },
635        ];
636
637        let signatures = transaction.packed_signatures().unwrap();
638        assert_eq!(&signatures[..32], p256_owner.into_word().as_slice());
639        assert_eq!(U256::from_be_slice(&signatures[32..64]), U256::from(195));
640        assert_eq!(signatures[64], 2);
641        assert_eq!(&signatures[65..130], &eoa_signature(2));
642        assert_eq!(&signatures[130..162], contract_owner.into_word().as_slice());
643        assert_eq!(U256::from_be_slice(&signatures[162..194]), U256::from(323));
644        assert_eq!(signatures[194], 0);
645        assert_eq!(&signatures[195..323], &p256_payload);
646        assert_eq!(U256::from_be_slice(&signatures[323..355]), U256::from(3));
647        assert_eq!(&signatures[355..], &contract_payload);
648    }
649
650    #[test]
651    fn rejects_malformed_confirmation_signatures() {
652        let owner = Address::repeat_byte(1);
653        let mut wrong_offset = vec![0; 97];
654        wrong_offset[32..64].copy_from_slice(B256::with_last_byte(66).as_slice());
655        let mut wrong_length = vec![0; 97];
656        wrong_length[32..64].copy_from_slice(B256::with_last_byte(65).as_slice());
657        wrong_length[65..97].copy_from_slice(B256::with_last_byte(1).as_slice());
658
659        for signature in [vec![1; 66], vec![0; 65], wrong_offset, wrong_length] {
660            let mut transaction = transaction();
661            transaction.confirmations =
662                vec![SafeConfirmation { owner, signature: Some(signature.into()) }];
663            assert!(transaction.packed_signatures().is_err());
664        }
665    }
666
667    #[test]
668    fn rejects_malformed_p256_signatures() {
669        let owner = Address::repeat_byte(1);
670        let signature = |len: usize, offset: usize| {
671            let mut signature = vec![0; len];
672            signature[..U256::BYTES].copy_from_slice(owner.into_word().as_slice());
673            signature[U256::BYTES..SAFE_SIGNATURE_LENGTH - 1]
674                .copy_from_slice(&U256::from(offset).to_be_bytes::<32>());
675            signature[SAFE_SIGNATURE_LENGTH - 1] = 2;
676            signature
677        };
678
679        for signature in [
680            signature(SAFE_SIGNATURE_LENGTH, SAFE_SIGNATURE_LENGTH),
681            signature(P256_SIGNATURE_LENGTH - 1, SAFE_SIGNATURE_LENGTH),
682            signature(P256_SIGNATURE_LENGTH + 1, SAFE_SIGNATURE_LENGTH),
683            signature(P256_SIGNATURE_LENGTH, SAFE_SIGNATURE_LENGTH + 1),
684        ] {
685            let mut transaction = transaction();
686            transaction.confirmations =
687                vec![SafeConfirmation { owner, signature: Some(signature.into()) }];
688            assert!(transaction.packed_signatures().is_err());
689        }
690    }
691}