cosigner-client 0.3.0

Local and proxy-backed Arch Network signers for the arch-cosigner custody proxy
Documentation
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
//! Signers for Arch Network transactions, local or through the
//! `arch-cosigner` custody proxy.
//!
//! [`ArchSignerT`] is the signing interface: implementors provide
//! [`pubkey`](ArchSignerT::pubkey) and
//! [`sign_message`](ArchSignerT::sign_message), and inherit transaction
//! assembly ([`sign_transaction`](ArchSignerT::sign_transaction),
//! [`sign_transaction_mixed`](ArchSignerT::sign_transaction_mixed)).
//! [`LocalSigner`] signs with an in-memory keypair; [`RemoteSigner`] delegates
//! to the proxy's `POST /v1/sign` and verifies every response, or coalesces
//! several messages into one `POST /v1/sign_batch`
//! ([`sign_messages`](ArchSignerT::sign_messages)). [`ArchSigner`]
//! wraps both behind one type so the deployment environment can choose the
//! backend ([`ArchSigner::from_env`]).
//!
//! # Examples
//!
//! ```
//! use cosigner_client::{ArchSigner, ArchSignerT, SignError};
//!
//! async fn submit(
//!     message: arch_program::sanitized::ArchMessage,
//! ) -> Result<arch_sdk::RuntimeTransaction, SignError> {
//!     let signer = ArchSigner::from_env()?;
//!     signer.sign_transaction(message).await
//! }
//! ```

#![warn(missing_docs)]

mod batch;
mod env;

pub use batch::BatchSigner;

use std::str::FromStr;
use std::time::Duration;

use arch_program::pubkey::Pubkey;
use arch_program::sanitized::ArchMessage;
use arch_sdk::{RuntimeTransaction, Signature};
use async_trait::async_trait;
use base64::Engine;
use bitcoin::key::UntweakedKeypair;
use bitcoin::secp256k1::{Secp256k1, SecretKey, XOnlyPublicKey};

/// Error surface for signer construction and signing.
///
/// `Clone` so one whole-request failure can be reported to every caller whose
/// message shared the batch that failed.
#[derive(Clone, Debug, thiserror::Error)]
pub enum SignError {
    /// Signer configuration is missing, ambiguous, or invalid.
    #[error("signer configuration: {0}")]
    Config(String),
    /// Producing a signature failed, or a required signer key has no matching
    /// signer.
    #[error("signing failed: {0}")]
    Signing(String),
    /// The cosigner proxy answered with a non-success status, or the request
    /// did not complete.
    #[error("cosigner proxy error{}: {detail}", fmt_status(.status))]
    Proxy {
        /// HTTP status answered by the proxy; `None` for transport failures
        /// (connect errors and timeouts).
        status: Option<u16>,
        /// Detail from the proxy's error body, or the transport error text.
        detail: String,
    },
    /// A proxy response failed the checks described on [`RemoteSigner`].
    #[error("response verification failed: {0}")]
    Verification(String),
}

fn fmt_status(status: &Option<u16>) -> String {
    match status {
        Some(code) => format!(" (http {code})"),
        None => String::new(),
    }
}

/// A signature over a message's BIP322 digest, with backend metadata.
#[derive(Debug, Clone)]
pub struct SignResponse {
    /// 64-byte BIP340 signature over the message's BIP322 digest.
    pub signature: [u8; 64],
    /// The Arch account key the signature verifies under.
    pub arch_account_pubkey: [u8; 32],
    /// Digest the proxy reports having signed, hex; `None` for local signing.
    pub digest_hex: Option<String>,
    /// Turnkey activity id for audit reconciliation; `None` for local signing.
    pub turnkey_activity_id: Option<String>,
}

impl SignResponse {
    /// Returns the 64-byte BIP340 signature.
    pub fn signature(&self) -> &[u8; 64] {
        &self.signature
    }
}

/// Signing interface shared by local and remote backends.
///
/// Implementors supply [`pubkey`](Self::pubkey) and
/// [`sign_message`](Self::sign_message); the transaction-assembly methods are
/// provided. Object-safe: `&dyn ArchSignerT` works.
#[async_trait]
pub trait ArchSignerT: Send + Sync {
    /// Returns the Arch account key this signer signs for.
    fn pubkey(&self) -> Pubkey;

    /// Signs the message's BIP322 digest.
    ///
    /// # Errors
    /// [`SignError::Signing`] when producing the signature fails.
    /// [`RemoteSigner`] also returns [`SignError::Proxy`] and
    /// [`SignError::Verification`] as described on its type documentation.
    async fn sign_message(&self, message: &ArchMessage) -> Result<SignResponse, SignError>;

    /// Signs every message in `messages`, returning one result per input in
    /// input order.
    ///
    /// A per-item failure does not fail its neighbours. The default
    /// implementation signs sequentially; [`RemoteSigner`] overrides it with a
    /// single `POST /v1/sign_batch` round trip, which costs one request against
    /// the role's Turnkey rate limit instead of one per message.
    ///
    /// Each signature is verified against the message it was requested for, in
    /// both implementations.
    ///
    /// # Errors
    /// [`SignError`] as the whole-request outcome: authentication, transport, a
    /// batch larger than the proxy accepts, or a response that cannot be mapped
    /// back to the requested messages. Per-item failures are in the returned
    /// vector.
    async fn sign_messages(
        &self,
        messages: &[ArchMessage],
    ) -> Result<Vec<Result<SignResponse, SignError>>, SignError> {
        let mut results = Vec::with_capacity(messages.len());
        for message in messages {
            results.push(self.sign_message(message).await);
        }
        Ok(results)
    }

    /// Signs a transaction whose only required signer is this signer.
    ///
    /// # Errors
    /// As for [`sign_transaction_mixed`](Self::sign_transaction_mixed) with no
    /// cosigners.
    async fn sign_transaction(
        &self,
        message: ArchMessage,
    ) -> Result<RuntimeTransaction, SignError> {
        self.sign_transaction_mixed(message, &[]).await
    }

    /// Signs a transaction with this signer plus local cosigner keypairs.
    ///
    /// Each of the first `num_required_signatures` entries of
    /// `message.account_keys` receives a signature at its own position: this
    /// signer's key is signed via [`sign_message`](Self::sign_message), a
    /// cosigner key is signed with its keypair, and the assembled
    /// [`RuntimeTransaction`] carries the signatures in `account_keys` order.
    ///
    /// # Errors
    /// Propagates [`sign_message`](Self::sign_message) errors;
    /// [`SignError::Signing`] when a required key matches neither this signer
    /// nor a cosigner, or when a cosigner signature fails.
    async fn sign_transaction_mixed(
        &self,
        message: ArchMessage,
        local_cosigners: &[UntweakedKeypair],
    ) -> Result<RuntimeTransaction, SignError> {
        let digest = message.hash();
        let required = message.header.num_required_signatures as usize;
        let mut signatures = Vec::with_capacity(required);

        for key in message.account_keys.iter().take(required) {
            if *key == self.pubkey() {
                signatures.push(Signature(self.sign_message(&message).await?.signature));
            } else if let Some(kp) = local_cosigners
                .iter()
                .find(|kp| XOnlyPublicKey::from_keypair(kp).0.serialize() == key.serialize())
            {
                // BIP-0322 P2TR signatures are network-independent (the
                // script_pubkey carries no network), so Bitcoin is safe for
                // ephemeral cosigners regardless of deployment network.
                let sig = arch_sdk::sign_message_bip322(kp, &digest, bitcoin::Network::Bitcoin)
                    .map_err(|e| SignError::Signing(e.to_string()))?;
                signatures.push(Signature(sig));
            } else {
                return Err(SignError::Signing(format!(
                    "no signer for required key {}",
                    hex::encode(key.serialize())
                )));
            }
        }

        Ok(RuntimeTransaction {
            version: 0,
            signatures,
            message,
        })
    }
}

/// Signs with an in-memory keypair via [`arch_sdk::sign_message_bip322`].
#[derive(Clone)]
pub struct LocalSigner {
    keypair: UntweakedKeypair,
    pubkey: Pubkey,
    network: bitcoin::Network,
}

impl LocalSigner {
    /// Wraps an in-memory keypair, with the network defaulting to Bitcoin.
    pub fn new(keypair: UntweakedKeypair) -> Self {
        let pubkey = Pubkey::from_slice(&XOnlyPublicKey::from_keypair(&keypair).0.serialize());
        Self {
            keypair,
            pubkey,
            network: bitcoin::Network::Bitcoin,
        }
    }

    /// Loads a keypair from a file in [`arch_sdk::with_secret_key_file`]
    /// format: a hex-encoded secret key or a JSON byte array.
    ///
    /// Never generates or writes a key.
    ///
    /// # Errors
    /// [`SignError::Config`] when the file is unreadable or does not parse
    /// as a secret key.
    pub fn from_key_file(path: &str) -> Result<Self, SignError> {
        let content = std::fs::read_to_string(path)
            .map_err(|e| SignError::Config(format!("reading key file {path}: {e}")))?;
        let secret = parse_secret_key(&content)
            .map_err(|e| SignError::Config(format!("key file {path}: {e}")))?;
        Ok(Self::new(UntweakedKeypair::from_secret_key(
            &Secp256k1::new(),
            &secret,
        )))
    }

    /// Returns this signer with `network` used for BIP322 digests.
    pub fn with_network(mut self, network: bitcoin::Network) -> Self {
        self.network = network;
        self
    }

    /// Returns the Arch account key derived from the wrapped keypair.
    pub fn pubkey(&self) -> Pubkey {
        self.pubkey
    }

    /// Returns the network used for BIP322 digests.
    pub fn network(&self) -> bitcoin::Network {
        self.network
    }
}

/// Parses the two encodings accepted by [`arch_sdk::with_secret_key_file`]:
/// a hex secret key, or a JSON byte array whose first 32 bytes are the key.
fn parse_secret_key(content: &str) -> Result<SecretKey, String> {
    if let Ok(secret) = SecretKey::from_str(content) {
        return Ok(secret);
    }
    let bytes: Vec<u8> = serde_json::from_str(content)
        .map_err(|_| "neither a hex secret key nor a JSON byte array".to_string())?;
    let head = bytes
        .get(..32)
        .ok_or_else(|| format!("byte array holds {} bytes, need 32", bytes.len()))?;
    SecretKey::from_slice(head).map_err(|e| e.to_string())
}

#[async_trait]
impl ArchSignerT for LocalSigner {
    fn pubkey(&self) -> Pubkey {
        self.pubkey
    }

    async fn sign_message(&self, message: &ArchMessage) -> Result<SignResponse, SignError> {
        let signature = arch_sdk::sign_message_bip322(&self.keypair, &message.hash(), self.network)
            .map_err(|e| SignError::Signing(e.to_string()))?;
        Ok(SignResponse {
            signature,
            arch_account_pubkey: self.pubkey.serialize(),
            digest_hex: None,
            turnkey_activity_id: None,
        })
    }
}

/// Signs by delegating to an `arch-cosigner` proxy over `POST /v1/sign`.
///
/// Every response is verified before it is returned: the response's
/// `arch_account_pubkey` must equal the configured [`pubkey`](Self::pubkey),
/// and the signature must BIP322-verify for the exact submitted message under
/// that key (DEFAULT-then-ALL sighash, the validator's order). A failed check
/// is [`SignError::Verification`].
///
/// [`sign_message`](ArchSignerT::sign_message) retries `Proxy` errors with
/// status 502 and transport failures (`Proxy` with status `None`) up to the
/// configured retry count, with exponential backoff. Every other error,
/// including a 503 from an unavailable proxy or infrastructure in front of
/// it, returns on first occurrence.
#[derive(Clone)]
pub struct RemoteSigner {
    http: reqwest::Client,
    url: String,
    token: String,
    role: String,
    intent: String,
    pubkey: Pubkey,
    network: bitcoin::Network,
    retries: u32,
    backoff: Duration,
}

impl RemoteSigner {
    /// Creates a signer for `role` at the proxy base `url`, verifying every
    /// response against `pubkey`.
    ///
    /// Defaults: network Bitcoin, 35 s request timeout, 2 retries, intent
    /// "unlabeled", 250 ms retry backoff.
    pub fn new(url: &str, token: &str, role: &str, pubkey: Pubkey) -> Self {
        Self {
            // The default timeout covers the proxy's worst case of
            // (1 + retries) × turnkey_timeout + backoff ≈ 31 s.
            http: http_client(Duration::from_secs(35)),
            url: url.trim_end_matches('/').to_string(),
            token: token.to_string(),
            role: role.to_string(),
            intent: "unlabeled".to_string(),
            pubkey,
            network: bitcoin::Network::Bitcoin,
            retries: 2,
            backoff: Duration::from_millis(250),
        }
    }

    /// Returns this signer with `network` used for response verification.
    pub fn with_network(mut self, network: bitcoin::Network) -> Self {
        self.network = network;
        self
    }

    /// Returns this signer with the intent label recorded in the proxy's
    /// audit log.
    pub fn with_intent(mut self, intent: &str) -> Self {
        self.intent = intent.to_string();
        self
    }

    /// Returns this signer with the retry budget for retryable errors.
    pub fn with_retries(mut self, retries: u32) -> Self {
        self.retries = retries;
        self
    }

    /// Returns this signer with the per-request HTTP timeout.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.http = http_client(timeout);
        self
    }

    /// Returns the Arch account key responses are verified against.
    pub fn pubkey(&self) -> Pubkey {
        self.pubkey
    }

    /// Returns the network used for response verification.
    pub fn network(&self) -> bitcoin::Network {
        self.network
    }

    /// Returns the proxy base URL with any trailing `/` trimmed.
    pub fn base_url(&self) -> &str {
        &self.url
    }

    /// One `POST /v1/sign` round trip, verified; no retries at this level.
    async fn sign_once(
        &self,
        message_b64: &str,
        message: &ArchMessage,
    ) -> Result<SignResponse, SignError> {
        let resp = self
            .http
            .post(format!("{}/v1/sign", self.url))
            .bearer_auth(&self.token)
            .json(&serde_json::json!({
                "role": self.role,
                "intent_type": self.intent,
                "unsigned_message_b64": message_b64,
            }))
            .send()
            .await
            .map_err(|e| SignError::Proxy {
                status: None,
                detail: e.to_string(),
            })?;

        let status = resp.status().as_u16();
        let body: serde_json::Value = match resp.json().await {
            Ok(body) => body,
            // A 200 whose body fails to arrive is a transport failure;
            // error-status bodies only feed the detail string below.
            Err(e) if status == 200 => {
                return Err(SignError::Proxy {
                    status: None,
                    detail: format!("response body: {e}"),
                })
            }
            Err(_) => serde_json::Value::Null,
        };
        if status != 200 {
            // "halted" is the 0.1 proxy's 503 body shape — read for wire
            // compatibility with deployed proxies.
            let detail = body["error"]
                .as_str()
                .or_else(|| body["halted"].as_str())
                .unwrap_or("<no detail>")
                .to_string();
            return Err(SignError::Proxy {
                status: Some(status),
                detail,
            });
        }

        self.verified_response(&body, message)
    }

    /// Verifies one signed body against the message it was requested for.
    ///
    /// Applied per item in the batch path as well as to the single-sign
    /// response. Collapsing it into one check per batch would let a misaligned
    /// response hand the caller a valid signature over a different message, so
    /// it stays per item.
    ///
    /// # Errors
    /// [`SignError::Verification`] when `signature_hex` is absent or not 64
    /// bytes, when `arch_account_pubkey` is not this signer's key, or when the
    /// signature does not BIP322-verify for `message` under that key.
    fn verified_response(
        &self,
        body: &serde_json::Value,
        message: &ArchMessage,
    ) -> Result<SignResponse, SignError> {
        let signature: [u8; 64] = hex::decode(body["signature_hex"].as_str().unwrap_or_default())
            .ok()
            .and_then(|v| v.try_into().ok())
            .ok_or_else(|| {
                SignError::Verification("signature_hex missing or not 64 bytes".into())
            })?;

        let expected_pubkey = hex::encode(self.pubkey.serialize());
        if body["arch_account_pubkey"].as_str() != Some(expected_pubkey.as_str()) {
            return Err(SignError::Verification(format!(
                "proxy signed with {} but this signer is configured for {expected_pubkey}",
                body["arch_account_pubkey"]
            )));
        }

        let digest = message.hash();
        arch_sdk::verify_message_bip322(
            &digest,
            self.pubkey.serialize(),
            signature,
            false,
            self.network,
        )
        .or_else(|_| {
            arch_sdk::verify_message_bip322(
                &digest,
                self.pubkey.serialize(),
                signature,
                true,
                self.network,
            )
        })
        .map_err(|e| SignError::Verification(e.to_string()))?;

        Ok(SignResponse {
            signature,
            arch_account_pubkey: self.pubkey.serialize(),
            digest_hex: body["digest_hex"].as_str().map(str::to_string),
            turnkey_activity_id: body["turnkey_activity_id"].as_str().map(str::to_string),
        })
    }

    /// One `POST /v1/sign_batch` round trip, every item verified; no retries at
    /// this level.
    async fn sign_batch_once(
        &self,
        messages: &[ArchMessage],
    ) -> Result<Vec<Result<SignResponse, SignError>>, SignError> {
        let items: Vec<serde_json::Value> = messages
            .iter()
            .map(|message| {
                serde_json::json!({
                    "intent_type": self.intent,
                    "unsigned_message_b64": base64::engine::general_purpose::STANDARD
                        .encode(message.serialize()),
                })
            })
            .collect();

        let resp = self
            .http
            .post(format!("{}/v1/sign_batch", self.url))
            .bearer_auth(&self.token)
            .json(&serde_json::json!({ "role": self.role, "items": items }))
            .send()
            .await
            .map_err(|e| SignError::Proxy {
                status: None,
                detail: e.to_string(),
            })?;

        let status = resp.status().as_u16();
        let body: serde_json::Value = match resp.json().await {
            Ok(body) => body,
            Err(e) if status == 200 => {
                return Err(SignError::Proxy {
                    status: None,
                    detail: format!("response body: {e}"),
                })
            }
            Err(_) => serde_json::Value::Null,
        };
        if status != 200 {
            return Err(SignError::Proxy {
                status: Some(status),
                detail: body["error"].as_str().unwrap_or("<no detail>").to_string(),
            });
        }

        let results = body["results"]
            .as_array()
            .ok_or_else(|| SignError::Verification("batch response has no results array".into()))?;
        // Results are positional, so a count mismatch makes every mapping a
        // guess: fail the whole request rather than pair signatures with
        // messages they may not belong to.
        if results.len() != messages.len() {
            return Err(SignError::Verification(format!(
                "batch response has {} results for {} messages",
                results.len(),
                messages.len()
            )));
        }

        Ok(results
            .iter()
            .zip(messages)
            .map(|(item, message)| {
                if item["status"].as_str() == Some("signed") {
                    self.verified_response(item, message)
                } else {
                    Err(SignError::Signing(format!(
                        "proxy rejected this message: {}",
                        item["error"].as_str().unwrap_or("<no detail>")
                    )))
                }
            })
            .collect())
    }

    /// Runs `attempt` until it succeeds or fails unretryably, spending the
    /// configured retry budget with exponential backoff.
    ///
    /// # Errors
    /// The last [`SignError`] seen; see [`RemoteSigner`] for which errors are
    /// retried.
    async fn send_with_retries<T, F, Fut>(&self, attempt: F) -> Result<T, SignError>
    where
        F: Fn() -> Fut,
        Fut: std::future::Future<Output = Result<T, SignError>>,
    {
        let mut n = 0;
        loop {
            match attempt().await {
                Err(err) if n < self.retries && is_retryable(&err) => {
                    tokio::time::sleep(self.backoff.saturating_mul(2u32.saturating_pow(n))).await;
                    n += 1;
                }
                result => return result,
            }
        }
    }
}

impl std::fmt::Debug for RemoteSigner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RemoteSigner")
            .field("url", &self.url)
            .field("token", &"<redacted>")
            .field("role", &self.role)
            .field("intent", &self.intent)
            .field("pubkey", &self.pubkey)
            .field("network", &self.network)
            .field("retries", &self.retries)
            .finish_non_exhaustive()
    }
}

fn http_client(timeout: Duration) -> reqwest::Client {
    reqwest::Client::builder()
        .timeout(timeout)
        .build()
        .expect("client construction with static config cannot fail")
}

pub(crate) fn is_retryable(err: &SignError) -> bool {
    matches!(
        err,
        SignError::Proxy {
            status: Some(502) | None,
            ..
        }
    )
}

#[async_trait]
impl ArchSignerT for RemoteSigner {
    fn pubkey(&self) -> Pubkey {
        self.pubkey
    }

    async fn sign_message(&self, message: &ArchMessage) -> Result<SignResponse, SignError> {
        let message_b64 = base64::engine::general_purpose::STANDARD.encode(message.serialize());
        self.send_with_retries(|| self.sign_once(&message_b64, message))
            .await
    }

    async fn sign_messages(
        &self,
        messages: &[ArchMessage],
    ) -> Result<Vec<Result<SignResponse, SignError>>, SignError> {
        // The proxy rejects an empty batch, and there is nothing to ask for.
        if messages.is_empty() {
            return Ok(Vec::new());
        }
        self.send_with_retries(|| self.sign_batch_once(messages))
            .await
    }
}

/// A signer whose backend, local or remote, is chosen at runtime.
#[derive(Clone)]
pub enum ArchSigner {
    /// In-process signing with a [`LocalSigner`].
    Local(LocalSigner),
    /// Proxy-delegated signing with a [`RemoteSigner`].
    Remote(RemoteSigner),
}

impl ArchSigner {
    /// Wraps `keypair` as a [`LocalSigner`].
    pub fn local(keypair: UntweakedKeypair) -> Self {
        Self::Local(LocalSigner::new(keypair))
    }

    /// Loads a [`LocalSigner`] from a key file.
    ///
    /// # Errors
    /// [`SignError::Config`] as described on [`LocalSigner::from_key_file`].
    pub fn local_from_key_file(path: &str) -> Result<Self, SignError> {
        Ok(Self::Local(LocalSigner::from_key_file(path)?))
    }

    /// Creates a [`RemoteSigner`] for `role` at the proxy base `url`.
    pub fn remote(url: &str, token: &str, role: &str, pubkey: Pubkey) -> Self {
        Self::Remote(RemoteSigner::new(url, token, role, pubkey))
    }

    /// Resolves a signer from bare environment variables.
    ///
    /// Remote configuration reads `COSIGNER_URL`, `COSIGNER_TOKEN`,
    /// `COSIGNER_ROLE`, and `COSIGNER_PUBKEY` (64 hex characters); local
    /// configuration reads `ARCH_KEY_PATH`. Exactly one of `COSIGNER_URL` and
    /// `ARCH_KEY_PATH` must be set, and empty values count as unset. The
    /// network is not read from the environment: it defaults to Bitcoin and
    /// is set with [`with_network`](Self::with_network).
    ///
    /// # Errors
    /// [`SignError::Config`] when neither or both backends are configured,
    /// when a required remote variable is missing (the message names every
    /// missing variable), or when `COSIGNER_PUBKEY` is not 64 hex characters.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use cosigner_client::ArchSigner;
    ///
    /// # fn main() -> Result<(), cosigner_client::SignError> {
    /// let signer = ArchSigner::from_env()?.with_intent("sweep");
    /// # let _ = signer;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_env() -> Result<Self, SignError> {
        env::resolve("")
    }

    /// Resolves a signer from `{prefix}_`-prefixed environment variables,
    /// falling back to the bare names.
    ///
    /// Each variable from [`from_env`](Self::from_env) is first looked up as
    /// `{prefix}_{NAME}`. The backend is chosen at the most specific level
    /// that sets a backend-selecting variable (`{prefix}_COSIGNER_URL` or
    /// `{prefix}_ARCH_KEY_PATH`); when the prefixed level sets neither, the
    /// bare level decides. After the backend is chosen, every variable fills
    /// per-variable with the prefixed value first, so one bare `COSIGNER_URL`
    /// can serve several prefixed tokens. Trailing underscores in `prefix`
    /// are ignored, and an empty `prefix` behaves exactly like
    /// [`from_env`](Self::from_env).
    ///
    /// # Errors
    /// [`SignError::Config`] under the conditions listed on
    /// [`from_env`](Self::from_env), with the ambiguity check applied at the
    /// deciding level.
    pub fn from_prefixed_env(prefix: &str) -> Result<Self, SignError> {
        env::resolve(prefix)
    }

    /// Returns this signer with `network` applied to either variant.
    pub fn with_network(self, network: bitcoin::Network) -> Self {
        match self {
            Self::Local(s) => Self::Local(s.with_network(network)),
            Self::Remote(s) => Self::Remote(s.with_network(network)),
        }
    }

    /// Returns this signer with the intent label set on the remote variant;
    /// no-op for a local signer.
    pub fn with_intent(self, intent: &str) -> Self {
        match self {
            Self::Remote(s) => Self::Remote(s.with_intent(intent)),
            local => local,
        }
    }

    /// Returns this signer with the retry budget set on the remote variant;
    /// no-op for a local signer.
    pub fn with_retries(self, retries: u32) -> Self {
        match self {
            Self::Remote(s) => Self::Remote(s.with_retries(retries)),
            local => local,
        }
    }

    /// Returns this signer with the HTTP timeout set on the remote variant;
    /// no-op for a local signer.
    pub fn with_timeout(self, timeout: Duration) -> Self {
        match self {
            Self::Remote(s) => Self::Remote(s.with_timeout(timeout)),
            local => local,
        }
    }

    /// Returns the configured network.
    pub fn network(&self) -> bitcoin::Network {
        match self {
            Self::Local(s) => s.network(),
            Self::Remote(s) => s.network(),
        }
    }

    /// Returns whether this signer delegates to a proxy.
    pub fn is_remote(&self) -> bool {
        matches!(self, Self::Remote(_))
    }

    /// Returns the local variant, if any.
    pub fn as_local(&self) -> Option<&LocalSigner> {
        match self {
            Self::Local(s) => Some(s),
            Self::Remote(_) => None,
        }
    }

    /// Returns the remote variant, if any.
    pub fn as_remote(&self) -> Option<&RemoteSigner> {
        match self {
            Self::Local(_) => None,
            Self::Remote(s) => Some(s),
        }
    }
}

#[async_trait]
impl ArchSignerT for ArchSigner {
    fn pubkey(&self) -> Pubkey {
        match self {
            Self::Local(s) => s.pubkey(),
            Self::Remote(s) => s.pubkey(),
        }
    }

    async fn sign_message(&self, message: &ArchMessage) -> Result<SignResponse, SignError> {
        match self {
            Self::Local(s) => s.sign_message(message).await,
            Self::Remote(s) => s.sign_message(message).await,
        }
    }

    // Delegated rather than inherited: the provided default signs one message
    // per request, which would silently drop batching for the remote variant.
    async fn sign_messages(
        &self,
        messages: &[ArchMessage],
    ) -> Result<Vec<Result<SignResponse, SignError>>, SignError> {
        match self {
            Self::Local(s) => s.sign_messages(messages).await,
            Self::Remote(s) => s.sign_messages(messages).await,
        }
    }
}