bsv-messagebox-client 0.2.0

BSV MessageBox client — peer-to-peer messaging and payments with BRC-78 encryption, WebSocket live delivery, and overlay host resolution. Full parity with @bsv/message-box-client.
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
822
823
824
825
826
827
828
829
830
831
832
//! Overlay host resolution, advertisement, and revocation.
//!
//! Implements the four overlay methods that mirror the TypeScript MessageBoxClient:
//! - `query_advertisements` — lookup PushDrop-encoded host advertisements on the overlay
//! - `resolve_host_for_recipient` — derive the recipient's MessageBox host URL
//! - `anoint_host` — broadcast a host advertisement via SHIP/PushDrop
//! - `revoke_host_advertisement` — spend an existing advertisement UTXO
//!
//! Advertisement locking scripts are built with the SDK's `PushDrop` template
//! (bsv-sdk >= 0.3), which is wallet-driven: it derives the locking key via
//! `getPublicKey` and appends the `createSignature` field itself. Earlier versions
//! of the template took a raw `PrivateKey` — which `WalletInterface` cannot expose —
//! so this module used to hand-build the script from chunks around a dummy key.
//! That workaround is gone.

use std::collections::HashMap;

use bsv::primitives::hash::sha256;
use bsv::script::locking_script::LockingScript;
use bsv::script::op::Op;
use bsv::script::script::Script;
use bsv::script::script_chunk::ScriptChunk;
use bsv::script::templates::push_drop::{decode as decode_push_drop, LockPosition, PushDrop};
use bsv::services::overlay_tools::{
    LookupResolver, LookupResolverConfig, TopicBroadcaster, TopicBroadcasterConfig,
};
use bsv::services::overlay_tools::{LookupAnswer, LookupQuestion};
use bsv::transaction::Transaction;
use bsv::wallet::interfaces::{
    CreateActionArgs, CreateActionInput, CreateActionOptions, CreateActionOutput,
    SignActionArgs, SignActionSpend, WalletInterface,
};
use bsv::wallet::types::{
    BooleanDefaultTrue, Counterparty, CounterpartyType, Protocol,
};

use crate::client::MessageBoxClient;
use crate::error::MessageBoxError;
use crate::types::{AdvertisementToken, ListDevicesResponse, RegisterDeviceRequest, RegisterDeviceResponse, RegisteredDevice};

// ---------------------------------------------------------------------------
// Standalone helpers
// ---------------------------------------------------------------------------

/// Build a correct data-push chunk for an arbitrary-length byte slice.
///
/// Uses the shortest possible push opcode per Bitcoin script encoding rules:
/// - len < 0x4c: opcode IS the length (direct push)
/// - len < 256: OP_PUSHDATA1 prefix
/// - len < 65536: OP_PUSHDATA2 prefix
/// - else: OP_PUSHDATA4 prefix
fn make_data_push(data: &[u8]) -> ScriptChunk {
    let len = data.len();
    if len < 0x4c {
        ScriptChunk::new_raw(len as u8, Some(data.to_vec()))
    } else if len < 256 {
        ScriptChunk::new_raw(Op::OpPushData1.to_byte(), Some(data.to_vec()))
    } else if len < 65536 {
        ScriptChunk::new_raw(Op::OpPushData2.to_byte(), Some(data.to_vec()))
    } else {
        ScriptChunk::new_raw(Op::OpPushData4.to_byte(), Some(data.to_vec()))
    }
}

/// Build the unlocking script that spends a `messagebox advertisement` PushDrop
/// output: a single data push of `<DER signature || sighash byte>`.
///
/// The digest convention is the load-bearing part. `create_signature` hashes its
/// `data` with SHA-256 exactly ONCE and signs that (`ProtoWallet::create_signature_sync`),
/// while a BSV sighash is `sha256d(preimage)` — so the caller supplies the FIRST
/// hash and the wallet applies the second. Handing over the raw preimage signs
/// `sha256(preimage)`, which no script engine will accept. Same convention as the
/// SDK's own `PushDrop::unlock` and ts-sdk's `PushDrop.unlock`.
async fn build_advertisement_unlock_script<W: WalletInterface + ?Sized>(
    wallet: &W,
    originator: Option<&str>,
    partial_tx: &Transaction,
    input_index: usize,
    sighash_type: u32,
    source_satoshis: u64,
    lock_script: &LockingScript,
) -> Result<Script, MessageBoxError> {
    let preimage = partial_tx
        .sighash_preimage(input_index, sighash_type, source_satoshis, lock_script)
        .map_err(|e| MessageBoxError::Overlay(format!("sighash_preimage: {e}")))?;

    let sig_result = wallet
        .create_signature(
            bsv::wallet::interfaces::CreateSignatureArgs {
                protocol_id: Protocol {
                    security_level: 1,
                    protocol: "messagebox advertisement".to_string(),
                },
                key_id: "1".to_string(),
                counterparty: Counterparty {
                    counterparty_type: CounterpartyType::Anyone,
                    public_key: None,
                },
                data: Some(sha256(&preimage).to_vec()),
                hash_to_directly_sign: None,
                privileged: false,
                privileged_reason: None,
                seek_permission: None,
            },
            originator,
        )
        .await
        .map_err(|e| MessageBoxError::Wallet(e.to_string()))?;

    // One data push of <sig_DER + sighash_byte>.
    let mut sig_bytes = sig_result.signature;
    sig_bytes.push(sighash_type as u8);
    Ok(Script::from_chunks(vec![make_data_push(&sig_bytes)]))
}


// ---------------------------------------------------------------------------
// MessageBoxClient impl — host resolution methods
// ---------------------------------------------------------------------------

impl<W: WalletInterface + Clone + 'static + Send + Sync> MessageBoxClient<W> {
    /// Query the `ls_messagebox` overlay service for host advertisement tokens.
    ///
    /// Returns all matching `AdvertisementToken`s. Malformed outputs are silently
    /// skipped. The ENTIRE method is wrapped in error recovery that returns an empty
    /// Vec — matching the TypeScript `queryAdvertisements` which wraps everything in
    /// try/catch and returns `[]` on any error, including overlay unreachability.
    ///
    /// TS parity:
    /// ```typescript
    /// } catch (err) { Logger.error('failed:', err); }
    /// return hosts  // always returns, never throws
    /// ```
    pub async fn query_advertisements(
        &self,
        identity_key: Option<&str>,
        host: Option<&str>,
    ) -> Result<Vec<AdvertisementToken>, MessageBoxError> {
        // CRITICAL TS PARITY: wrap everything; return empty vec on any failure
        match self.query_advertisements_inner(identity_key, host).await {
            Ok(tokens) => Ok(tokens),
            Err(_) => Ok(vec![]),
        }
    }

    /// Inner implementation — errors propagate; wrapped by `query_advertisements`.
    async fn query_advertisements_inner(
        &self,
        identity_key: Option<&str>,
        host: Option<&str>,
    ) -> Result<Vec<AdvertisementToken>, MessageBoxError> {
        let ik = match identity_key {
            Some(k) => k.to_string(),
            None => self.get_identity_key().await?,
        };

        let mut query_obj = serde_json::json!({ "identityKey": ik });
        if let Some(h) = host {
            let trimmed = h.trim();
            if !trimmed.is_empty() {
                query_obj["host"] = serde_json::Value::String(trimmed.to_string());
            }
        }

        let question = LookupQuestion {
            service: "ls_messagebox".to_string(),
            query: query_obj,
        };

        // The SLAP trackers serve as universal overlay lookup hosts. Services
        // like ls_messagebox may not have dedicated SLAP registrations, so we
        // add the default SLAP tracker URLs as host_overrides for ls_messagebox.
        // This lets the resolver query them directly without SLAP→host discovery.
        let mut host_overrides = std::collections::HashMap::new();
        let tracker_urls = self.network.default_slap_trackers();
        host_overrides.insert("ls_messagebox".to_string(), tracker_urls);

        let resolver = LookupResolver::new(LookupResolverConfig {
            network: self.network.clone(),
            host_overrides,
            ..Default::default()
        });

        let answer = resolver
            .query(&question, None)
            .await
            .map_err(|e| MessageBoxError::Overlay(e.to_string()))?;

        let mut tokens = Vec::new();

        if let LookupAnswer::OutputList { outputs } = answer {
            for output in outputs {
                // Convert BEEF bytes to hex string — Transaction::from_beef takes &str hex
                let beef_hex = hex::encode(&output.beef);
                let tx = match Transaction::from_beef(&beef_hex) {
                    Ok(t) => t,
                    Err(_) => continue,
                };

                let idx = output.output_index as usize;
                if idx >= tx.outputs.len() {
                    continue;
                }

                let script = &tx.outputs[idx].locking_script;
                let pd = match decode_push_drop(script) {
                    Ok(t) => t,
                    Err(_) => continue,
                };

                if pd.fields.len() < 2 {
                    continue;
                }

                let host_url = match String::from_utf8(pd.fields[1].clone()) {
                    Ok(h) => h,
                    Err(_) => continue,
                };

                // TS does NOT filter by protocol or hostname — all valid PushDrop
                // hosts are returned. This allows local dev with http://localhost.

                // tx.id() returns Result<String> with no argument (unlike TS)
                let txid = match tx.id() {
                    Ok(id) => id,
                    Err(_) => continue,
                };

                tokens.push(AdvertisementToken {
                    host: host_url,
                    txid,
                    output_index: output.output_index,
                    locking_script: script.to_hex(),
                    beef: output.beef,
                });
            }
        }

        Ok(tokens)
    }

    /// Resolve the MessageBox host for a given recipient identity key.
    ///
    /// Queries the overlay for the recipient's advertisements and returns the
    /// first matching host. Falls back to `self.host` when:
    /// - No advertisements exist for the recipient, or
    /// - The overlay is unreachable (query_advertisements always returns Ok)
    pub async fn resolve_host_for_recipient(
        &self,
        recipient: &str,
    ) -> Result<String, MessageBoxError> {
        let ads = self.query_advertisements(Some(recipient), None).await?;
        if let Some(ad) = ads.into_iter().next() {
            Ok(ad.host)
        } else {
            Ok(self.host().to_string())
        }
    }

    /// Broadcast a host advertisement to the `tm_messagebox` overlay topic.
    ///
    /// Builds a PushDrop transaction with:
    /// - fields[0] = identity key bytes (hex-decoded from identity key string)
    /// - fields[1] = host URL bytes (UTF-8)
    ///
    /// Returns the txid of the broadcast transaction, matching TS `anointHost`
    /// which returns `{ txid }`.
    pub async fn anoint_host(&self, host: &str) -> Result<String, MessageBoxError> {
        let identity_key = self.get_identity_key().await?;


        // fields[0] = raw identity key bytes (hex-decoded per Pitfall 3)
        let id_key_bytes = hex::decode(&identity_key)
            .map_err(|e| MessageBoxError::Overlay(format!("hex decode identity key: {e}")))?;
        let host_bytes = host.as_bytes().to_vec();

        // bsv-sdk 0.3: PushDrop is wallet-driven, so it derives the locking key and
        // appends the signature field itself — with the SAME (protocol, keyID,
        // counterparty, forSelf) triple used for the pubkey derivation above.
        //
        // This replaces a workaround that the old PrivateKey-based API forced:
        // sign the fields by hand, construct PushDrop with a DUMMY PrivateKey(1)
        // just to get the script shape, then splice chunk[0] to swap the dummy
        // pubkey for the wallet-derived one. That was script surgery standing in
        // for an API that couldn't express "lock to a key the wallet derives".
        // Same bytes, none of the surgery.
        let locking_script = PushDrop::new(self.wallet(), self.originator().map(String::from))
            .lock(
                vec![id_key_bytes, host_bytes],
                Protocol {
                    security_level: 1,
                    protocol: "messagebox advertisement".to_string(),
                },
                "1",
                Counterparty {
                    counterparty_type: CounterpartyType::Anyone,
                    public_key: None,
                },
                true, // for_self — matches the get_public_key derivation above
                true, // include_signature — TS/Go default; appends sig as field[2]
                LockPosition::Before,
            )
            .await
            .map_err(|e| MessageBoxError::Overlay(format!("PushDrop lock: {e}")))?;

        // Create the overlay advertisement transaction
        let create_result = self
            .wallet()
            .create_action(
                CreateActionArgs {
                    description: "Anoint host for overlay routing".to_string(),
                    input_beef: None,
                    inputs: vec![],
                    outputs: vec![CreateActionOutput {
                        locking_script: Some(locking_script.to_binary()),
                        satoshis: 1,
                        output_description: "Overlay advertisement output".to_string(),
                        basket: Some("overlay advertisements".to_string()),
                        custom_instructions: None,
                        tags: vec![],
                    }],
                    lock_time: None,
                    version: None,
                    labels: vec![],
                    options: Some(CreateActionOptions {
                        // randomize_outputs: false — output_index 0 is stable
                        randomize_outputs: BooleanDefaultTrue(Some(false)),
                        accept_delayed_broadcast: BooleanDefaultTrue(Some(false)),
                        ..Default::default()
                    }),
                    reference: None,
                },
                self.originator(),
            )
            .await
            .map_err(|e| MessageBoxError::Wallet(e.to_string()))?;

        // create_action returns BEEF bytes. Parse to Transaction only for
        // the txid — broadcast the original BEEF bytes directly to avoid
        // losing the source transaction chain.
        let beef_bytes = create_result
            .tx
            .ok_or_else(|| MessageBoxError::Overlay("create_action returned no tx".into()))?;
        let beef_hex = hex::encode(&beef_bytes);
        let tx = Transaction::from_beef(&beef_hex)
            .map_err(|e| MessageBoxError::Overlay(format!("parse BEEF: {e}")))?;
        let txid = tx
            .id()
            .map_err(|e| MessageBoxError::Overlay(format!("tx.id(): {e}")))?;

        // Broadcast the original BEEF bytes via TopicBroadcaster.
        // We use broadcast_beef() to pass pre-built BEEF directly,
        // avoiding the Transaction → to_beef() round-trip which loses
        // source transactions.
        let broadcaster = TopicBroadcaster::new(
            vec!["tm_messagebox".to_string()],
            TopicBroadcasterConfig {
                network: self.network.clone(),
                ..Default::default()
            },
            LookupResolver::new(LookupResolverConfig {
                network: self.network.clone(),
                ..Default::default()
            }),
        )
        .map_err(|e| MessageBoxError::Overlay(format!("build broadcaster: {e}")))?;

        broadcaster
            .broadcast_beef(beef_bytes)
            .await
            .map_err(|e| MessageBoxError::Overlay(format!("broadcast failed: {}", e.description)))?;

        Ok(txid)
    }

    /// Register a device for FCM push notifications.
    ///
    /// POSTs `{"fcmToken": ..., "deviceId": ..., "platform": ...}` (camelCase) to
    /// `{host}/registerDevice`. Returns `RegisterDeviceResponse { status, message, deviceId }`.
    ///
    /// TS parity: `registerDevice` returns the full response object including `deviceId`.
    pub async fn register_device(
        &self,
        fcm_token: &str,
        device_id: Option<&str>,
        platform: Option<&str>,
        override_host: Option<&str>,
    ) -> Result<RegisterDeviceResponse, MessageBoxError> {
        self.assert_initialized().await?;

        let base = override_host.unwrap_or_else(|| self.host());
        let request = RegisterDeviceRequest {
            fcm_token: fcm_token.to_string(),
            device_id: device_id.map(String::from),
            platform: platform.map(String::from),
        };

        let body_bytes = serde_json::to_vec(&request)
            .map_err(|e| MessageBoxError::Overlay(format!("serialize RegisterDeviceRequest: {e}")))?;

        let url = format!("{base}/registerDevice");
        let response = self.post_json(&url, body_bytes).await?;

        let resp: RegisterDeviceResponse = serde_json::from_slice(&response.body)
            .map_err(|e| MessageBoxError::Overlay(format!("deserialize RegisterDeviceResponse: {e}")))?;

        Ok(resp)
    }

    /// List all registered devices for this identity.
    ///
    /// GETs `{host}/devices` and returns `Vec<RegisteredDevice>`.
    /// All 8 server fields (id, deviceId, fcmToken, platform, active,
    /// createdAt, updatedAt, lastUsed) are captured.
    pub async fn list_registered_devices(
        &self,
        override_host: Option<&str>,
    ) -> Result<Vec<RegisteredDevice>, MessageBoxError> {
        self.assert_initialized().await?;

        let base = override_host.unwrap_or_else(|| self.host());
        let url = format!("{base}/devices");
        let response = self.get_json(&url).await?;

        let resp: ListDevicesResponse = serde_json::from_slice(&response.body)
            .map_err(|e| MessageBoxError::Overlay(format!("deserialize ListDevicesResponse: {e}")))?;

        Ok(resp.devices)
    }

    /// Revoke an existing host advertisement by spending its UTXO.
    ///
    /// Two-step create+sign pattern:
    /// 1. `create_action` with `input_beef` + input pointing to the advertisement UTXO.
    ///    Returns a signable transaction with a `reference` for the sign step.
    /// 2. Derive sighash preimage from the partial transaction.
    /// 3. `create_signature` over `sha256(preimage)` with the advertisement protocol
    ///    (the wallet applies the second hash) to produce a DER signature.
    /// 4. `sign_action` with the DER+sighash-type unlock script.
    /// 5. Broadcast the signed transaction via TopicBroadcaster.
    ///
    /// Returns the txid of the spending transaction.
    pub async fn revoke_host_advertisement(
        &self,
        token: &AdvertisementToken,
    ) -> Result<String, MessageBoxError> {
        // Step 1: create a signable (unsigned) transaction spending the advertisement UTXO.
        // unlocking_script_length: 73 matches TS (1 push byte + 72 DER sig bytes)
        let create_result = self
            .wallet()
            .create_action(
                CreateActionArgs {
                    description: "Revoke MessageBox host advertisement".to_string(),
                    input_beef: Some(token.beef.clone()),
                    inputs: vec![CreateActionInput {
                        outpoint: format!("{}.{}", token.txid, token.output_index),
                        input_description: "Revoking host advertisement token".to_string(),
                        unlocking_script: None,
                        unlocking_script_length: Some(73),
                        sequence_number: None,
                    }],
                    outputs: vec![],
                    lock_time: None,
                    version: None,
                    labels: vec![],
                    options: Some(CreateActionOptions {
                        accept_delayed_broadcast: BooleanDefaultTrue(Some(false)),
                        ..Default::default()
                    }),
                    reference: None,
                },
                self.originator(),
            )
            .await
            .map_err(|e| MessageBoxError::Wallet(e.to_string()))?;

        // Step 2: Extract the signable transaction and its reference
        let signable = create_result.signable_transaction.ok_or_else(|| {
            MessageBoxError::Overlay("create_action returned no signable_transaction".into())
        })?;

        // Step 3: Build the partial transaction so we can compute the sighash preimage
        let partial_tx = Transaction::from_beef(&hex::encode(&signable.tx))
            .map_err(|e| MessageBoxError::Overlay(format!("parse signable tx: {e}")))?;

        // Recover the locking script from the token for the preimage
        let lock_script = LockingScript::from_hex(&token.locking_script)
            .map_err(|e| MessageBoxError::Overlay(format!("parse locking script hex: {e}")))?;

        // SIGHASH_ALL | SIGHASH_FORKID = 0x41
        let sighash_type: u32 = 0x41;

        // Steps 4+5: sign the sighash through the wallet and wrap the DER signature
        // in the unlocking script. `build_advertisement_unlock_script` owns the
        // digest convention (it pre-hashes the preimage — see its docs).
        let unlock_script = build_advertisement_unlock_script(
            self.wallet(),
            self.originator(),
            &partial_tx,
            0,
            sighash_type,
            1,
            &lock_script,
        )
        .await?;

        // Step 6: sign_action finalizes the transaction with our unlock script
        let sign_result = self
            .wallet()
            .sign_action(
                SignActionArgs {
                    reference: signable.reference,
                    spends: HashMap::from([(
                        0u32,
                        SignActionSpend {
                            unlocking_script: unlock_script.to_binary(),
                            sequence_number: None,
                        },
                    )]),
                    options: None,
                },
                self.originator(),
            )
            .await
            .map_err(|e| MessageBoxError::Wallet(e.to_string()))?;

        // Step 7: Broadcast signed BEEF directly (avoids from_beef → to_beef round-trip)
        let signed_bytes = sign_result
            .tx
            .ok_or_else(|| MessageBoxError::Overlay("sign_action returned no tx".into()))?;

        // Parse only for the txid — broadcast the original BEEF bytes.
        let signed_tx = Transaction::from_beef(&hex::encode(&signed_bytes))
            .map_err(|e| MessageBoxError::Overlay(format!("parse signed tx: {e}")))?;
        let txid = signed_tx
            .id()
            .map_err(|e| MessageBoxError::Overlay(format!("signed_tx.id(): {e}")))?;

        let broadcaster = TopicBroadcaster::new(
            vec!["tm_messagebox".to_string()],
            TopicBroadcasterConfig {
                network: self.network.clone(),
                ..Default::default()
            },
            LookupResolver::new(LookupResolverConfig {
                network: self.network.clone(),
                ..Default::default()
            }),
        )
        .map_err(|e| MessageBoxError::Overlay(format!("build broadcaster: {e}")))?;

        broadcaster
            .broadcast_beef(signed_bytes)
            .await
            .map_err(|e| MessageBoxError::Overlay(format!("broadcast failed: {}", e.description)))?;

        Ok(txid)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use bsv::primitives::private_key::PrivateKey;
    use bsv::services::overlay_tools::Network;
    use bsv::wallet::error::WalletError;
    use bsv::wallet::interfaces::*;
    use bsv::wallet::proto_wallet::ProtoWallet;
    use std::sync::Arc;

    /// Test helper: thin Arc wrapper so ProtoWallet satisfies the Clone bound.
    #[derive(Clone)]
    struct ArcWallet(Arc<ProtoWallet>);

    impl ArcWallet {
        fn new() -> Self {
            let key = PrivateKey::from_random().expect("random key");
            ArcWallet(Arc::new(ProtoWallet::new(key)))
        }

        /// Fixed key, so a script-validation failure reproduces byte-for-byte.
        fn deterministic() -> Self {
            let key = PrivateKey::from_bytes(&[0x42u8; 32]).expect("fixed key");
            ArcWallet(Arc::new(ProtoWallet::new(key)))
        }
    }

    #[async_trait::async_trait]
    impl WalletInterface for ArcWallet {
        async fn create_action(&self, args: CreateActionArgs, orig: Option<&str>) -> Result<CreateActionResult, WalletError> { self.0.create_action(args, orig).await }
        async fn sign_action(&self, args: SignActionArgs, orig: Option<&str>) -> Result<SignActionResult, WalletError> { self.0.sign_action(args, orig).await }
        async fn abort_action(&self, args: AbortActionArgs, orig: Option<&str>) -> Result<AbortActionResult, WalletError> { self.0.abort_action(args, orig).await }
        async fn list_actions(&self, args: ListActionsArgs, orig: Option<&str>) -> Result<ListActionsResult, WalletError> { self.0.list_actions(args, orig).await }
        async fn internalize_action(&self, args: InternalizeActionArgs, orig: Option<&str>) -> Result<InternalizeActionResult, WalletError> { self.0.internalize_action(args, orig).await }
        async fn list_outputs(&self, args: ListOutputsArgs, orig: Option<&str>) -> Result<ListOutputsResult, WalletError> { self.0.list_outputs(args, orig).await }
        async fn relinquish_output(&self, args: RelinquishOutputArgs, orig: Option<&str>) -> Result<RelinquishOutputResult, WalletError> { self.0.relinquish_output(args, orig).await }
        async fn get_public_key(&self, args: GetPublicKeyArgs, orig: Option<&str>) -> Result<GetPublicKeyResult, WalletError> { self.0.get_public_key(args, orig).await }
        async fn reveal_counterparty_key_linkage(&self, args: RevealCounterpartyKeyLinkageArgs, orig: Option<&str>) -> Result<RevealCounterpartyKeyLinkageResult, WalletError> { self.0.reveal_counterparty_key_linkage(args, orig).await }
        async fn reveal_specific_key_linkage(&self, args: RevealSpecificKeyLinkageArgs, orig: Option<&str>) -> Result<RevealSpecificKeyLinkageResult, WalletError> { self.0.reveal_specific_key_linkage(args, orig).await }
        async fn encrypt(&self, args: EncryptArgs, orig: Option<&str>) -> Result<EncryptResult, WalletError> { self.0.encrypt(args, orig).await }
        async fn decrypt(&self, args: DecryptArgs, orig: Option<&str>) -> Result<DecryptResult, WalletError> { self.0.decrypt(args, orig).await }
        async fn create_hmac(&self, args: CreateHmacArgs, orig: Option<&str>) -> Result<CreateHmacResult, WalletError> { self.0.create_hmac(args, orig).await }
        async fn verify_hmac(&self, args: VerifyHmacArgs, orig: Option<&str>) -> Result<VerifyHmacResult, WalletError> { self.0.verify_hmac(args, orig).await }
        async fn create_signature(&self, args: CreateSignatureArgs, orig: Option<&str>) -> Result<CreateSignatureResult, WalletError> { self.0.create_signature(args, orig).await }
        async fn verify_signature(&self, args: VerifySignatureArgs, orig: Option<&str>) -> Result<VerifySignatureResult, WalletError> { self.0.verify_signature(args, orig).await }
        async fn acquire_certificate(&self, args: AcquireCertificateArgs, orig: Option<&str>) -> Result<Certificate, WalletError> { self.0.acquire_certificate(args, orig).await }
        async fn list_certificates(&self, args: ListCertificatesArgs, orig: Option<&str>) -> Result<ListCertificatesResult, WalletError> { self.0.list_certificates(args, orig).await }
        async fn prove_certificate(&self, args: ProveCertificateArgs, orig: Option<&str>) -> Result<ProveCertificateResult, WalletError> { self.0.prove_certificate(args, orig).await }
        async fn relinquish_certificate(&self, args: RelinquishCertificateArgs, orig: Option<&str>) -> Result<RelinquishCertificateResult, WalletError> { self.0.relinquish_certificate(args, orig).await }
        async fn discover_by_identity_key(&self, args: DiscoverByIdentityKeyArgs, orig: Option<&str>) -> Result<DiscoverCertificatesResult, WalletError> { self.0.discover_by_identity_key(args, orig).await }
        async fn discover_by_attributes(&self, args: DiscoverByAttributesArgs, orig: Option<&str>) -> Result<DiscoverCertificatesResult, WalletError> { self.0.discover_by_attributes(args, orig).await }
        async fn is_authenticated(&self, orig: Option<&str>) -> Result<AuthenticatedResult, WalletError> { self.0.is_authenticated(orig).await }
        async fn wait_for_authentication(&self, orig: Option<&str>) -> Result<AuthenticatedResult, WalletError> { self.0.wait_for_authentication(orig).await }
        async fn get_height(&self, orig: Option<&str>) -> Result<GetHeightResult, WalletError> { self.0.get_height(orig).await }
        async fn get_header_for_height(&self, args: GetHeaderArgs, orig: Option<&str>) -> Result<GetHeaderResult, WalletError> { self.0.get_header_for_height(args, orig).await }
        async fn get_network(&self, orig: Option<&str>) -> Result<GetNetworkResult, WalletError> { self.0.get_network(orig).await }
        async fn get_version(&self, orig: Option<&str>) -> Result<GetVersionResult, WalletError> { self.0.get_version(orig).await }
    }

    fn make_client() -> MessageBoxClient<ArcWallet> {
        MessageBoxClient::new(
            "https://example.com".to_string(),
            ArcWallet::new(),
            None,
            Network::Mainnet,
        )
    }

    /// `resolve_host_for_recipient` falls back to `self.host` when overlay returns empty.
    ///
    /// With Network::Mainnet, `query_advertisements` will fail to reach SLAP trackers
    /// and return an empty vec (TS parity: no error propagation). The fallback kicks in.
    #[tokio::test]
    async fn test_resolve_host_falls_back_to_default() {
        let client = make_client();
        // Overlay unreachable from unit test → empty vec → fall back to self.host
        let host = client
            .resolve_host_for_recipient("03deadbeef")
            .await
            .expect("should not error");
        assert_eq!(host, "https://example.com", "must fall back to self.host");
    }

    /// revoke_host_advertisement builds an outpoint as "{txid}.{output_index}".
    #[test]
    fn test_revoke_host_args_correct() {
        let txid = "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab";
        let output_index: u32 = 0;
        let outpoint = format!("{txid}.{output_index}");
        assert_eq!(
            outpoint,
            "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab.0"
        );
    }

    /// The revocation unlocking script must actually SPEND the advertisement output.
    ///
    /// Runs the SDK script interpreter over (unlocking script, locking script) in the
    /// real transaction context, so OP_CHECKSIG recomputes the BIP-143 sighash itself
    /// and ECDSA-verifies our DER signature against `sha256d(preimage)` under the
    /// PushDrop locking key. Nothing else in this crate ever executed the script, which
    /// is exactly why signing the wrong digest (`sha256(preimage)`) survived — the
    /// unlocking script was well-FORMED but not VALID. Handing `create_signature` the
    /// raw preimage again turns this assertion red.
    #[tokio::test]
    async fn revocation_unlock_script_validates_against_the_advertisement_lock() {
        use bsv::script::spend::{Spend, SpendParams};
        use bsv::script::unlocking_script::UnlockingScript;
        use bsv::transaction::{TransactionInput, TransactionOutput};

        let wallet = ArcWallet::deterministic();
        let sighash_type: u32 = 0x41; // SIGHASH_ALL | SIGHASH_FORKID

        // The advertisement output, locked exactly as `anoint_host` locks it:
        // same protocol/keyID/counterparty/for_self triple, so the key that
        // `create_signature` derives is the counterpart of the locking key.
        let locking_script = PushDrop::new(&wallet, None)
            .lock(
                vec![vec![0x02u8; 33], b"https://example.com".to_vec()],
                Protocol {
                    security_level: 1,
                    protocol: "messagebox advertisement".to_string(),
                },
                "1",
                Counterparty {
                    counterparty_type: CounterpartyType::Anyone,
                    public_key: None,
                },
                true, // for_self
                true, // include_signature
                LockPosition::Before,
            )
            .await
            .expect("PushDrop lock");

        let mut source = Transaction::new();
        source.outputs.push(TransactionOutput {
            satoshis: Some(1),
            locking_script: locking_script.clone(),
            change: false,
        });
        let source_txid = source.id().expect("source txid");

        // The revocation shape `create_action` hands back: one input, no outputs.
        let mut partial_tx = Transaction::new();
        partial_tx.inputs.push(TransactionInput {
            source_transaction: Some(Box::new(source)),
            source_txid: Some(source_txid.clone()),
            source_output_index: 0,
            unlocking_script: None,
            sequence: 0xFFFF_FFFF,
        });

        // The production path under test.
        let unlock_script = build_advertisement_unlock_script(
            &wallet,
            None,
            &partial_tx,
            0,
            sighash_type,
            1,
            &locking_script,
        )
        .await
        .expect("build unlock script");

        let mut spend = Spend::new(SpendParams {
            locking_script: locking_script.clone(),
            unlocking_script: UnlockingScript::from_binary(&unlock_script.to_binary()),
            source_txid,
            source_output_index: 0,
            source_satoshis: 1,
            transaction_version: partial_tx.version,
            transaction_lock_time: partial_tx.lock_time,
            transaction_sequence: partial_tx.inputs[0].sequence,
            other_inputs: vec![],
            other_outputs: partial_tx.outputs.clone(),
            input_index: 0,
        });

        let valid = spend
            .validate()
            .unwrap_or_else(|e| panic!("script engine errored on the revocation spend: {e:?}"));
        assert!(
            valid,
            "the revocation unlocking script must satisfy the advertisement locking \
             script; a signature over sha256(preimage) instead of sha256d(preimage) \
             fails here"
        );
    }

    // -----------------------------------------------------------------------
    // Task 3 — device registration tests
    // -----------------------------------------------------------------------

    /// `RegisterDeviceRequest` serializes to camelCase JSON with correct field names.
    #[test]
    fn test_register_device_request_serializes_camelcase() {
        use crate::types::RegisterDeviceRequest;
        let req = RegisterDeviceRequest {
            fcm_token: "abc".to_string(),
            device_id: Some("d1".to_string()),
            platform: None,
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("\"fcmToken\":\"abc\""), "fcmToken must be camelCase: {json}");
        assert!(json.contains("\"deviceId\":\"d1\""), "deviceId must be camelCase: {json}");
        assert!(!json.contains("platform"), "platform absent when None: {json}");
        assert!(!json.contains("fcm_token"), "no snake_case leakage: {json}");
        assert!(!json.contains("device_id"), "no snake_case leakage: {json}");
    }

    /// `ListDevicesResponse` deserializes a full server response including all 8 fields.
    #[test]
    fn test_list_devices_response_deserializes() {
        use crate::types::ListDevicesResponse;
        let raw = r#"{
            "status": "success",
            "devices": [{
                "id": 1,
                "deviceId": "d1",
                "fcmToken": "tok",
                "platform": "ios",
                "active": true,
                "createdAt": "2026-01-01",
                "updatedAt": "2026-01-01",
                "lastUsed": "2026-01-01"
            }]
        }"#;
        let resp: ListDevicesResponse = serde_json::from_str(raw).unwrap();
        assert_eq!(resp.status, "success");
        assert_eq!(resp.devices.len(), 1);
        let dev = &resp.devices[0];
        assert_eq!(dev.id, Some(1));
        assert_eq!(dev.device_id.as_deref(), Some("d1"));
        assert_eq!(dev.fcm_token, "tok");
        assert_eq!(dev.platform.as_deref(), Some("ios"));
        assert_eq!(dev.active, Some(true));
        assert!(dev.created_at.is_some());
        assert!(dev.updated_at.is_some());
        assert!(dev.last_used.is_some());
    }

    /// `RegisterDeviceResponse` deserializes `{status, message, deviceId}` correctly.
    #[test]
    fn test_register_device_response_deserializes() {
        use crate::types::RegisterDeviceResponse;
        let raw = r#"{"status":"success","message":"registered","deviceId":42}"#;
        let resp: RegisterDeviceResponse = serde_json::from_str(raw).unwrap();
        assert_eq!(resp.status, "success");
        assert_eq!(resp.message.as_deref(), Some("registered"));
        assert_eq!(resp.device_id, Some(42));
    }

    /// `register_device` method exists on `MessageBoxClient` — compile check.
    ///
    /// Verifies the method signature accepts fcm_token, device_id, platform.
    #[allow(dead_code)]
    fn register_device_compiles(client: &MessageBoxClient<ArcWallet>) {
        let _fut = client.register_device("tok123", Some("dev1"), Some("ios"), None);
    }

    /// `list_registered_devices` method exists on `MessageBoxClient` — compile check.
    #[allow(dead_code)]
    fn list_registered_devices_compiles(client: &MessageBoxClient<ArcWallet>) {
        let _fut = client.list_registered_devices(None);
    }
}