paykit-lib 0.1.0

Paykit library implementation
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
use tracing::{debug, instrument};

use crate::{PaykitAppId, PaykitError, PublicKey, Result};

use super::{
    paths::{compute_private_payment_paths, validate_private_payment_paths},
    private_application_message::{self, PrivateApplicationMessage},
    EncryptedLinkRecoveryContext, EncryptedLinkSnapshot,
};

/// Outbound private message prepared for atomic persistence before publication.
///
/// Persist [`destination_path`](Self::destination_path),
/// [`ciphertext`](Self::ciphertext), and
/// [`resulting_snapshot`](Self::resulting_snapshot) together before
/// acknowledging this value.
pub struct PreparedPrivateApplicationMessageSend {
    prepared: pubky_noise::PreparedSend,
    resulting_snapshot: EncryptedLinkSnapshot,
}

impl PreparedPrivateApplicationMessageSend {
    /// Pubky storage path for the exact ciphertext.
    pub fn destination_path(&self) -> &str {
        self.prepared.destination_path()
    }

    /// Exact ciphertext to publish or retry after a crash.
    pub fn ciphertext(&self) -> &[u8] {
        self.prepared.ciphertext()
    }

    /// Encrypted Link snapshot after this send.
    pub fn resulting_snapshot(&self) -> &EncryptedLinkSnapshot {
        &self.resulting_snapshot
    }
}

impl std::fmt::Debug for PreparedPrivateApplicationMessageSend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PreparedPrivateApplicationMessageSend")
            .field("destination_path", &"<redacted>")
            .field(
                "ciphertext",
                &format_args!("<redacted:{} bytes>", self.ciphertext().len()),
            )
            .field("resulting_snapshot", &"<redacted>")
            .finish()
    }
}

/// Inbound private message prepared for atomic application-state persistence.
pub struct PreparedPrivateApplicationMessageReceive {
    prepared: pubky_noise::PreparedReceive,
    message: PrivateApplicationMessage,
    resulting_snapshot: EncryptedLinkSnapshot,
}

impl PreparedPrivateApplicationMessageReceive {
    /// Decrypted Paykit application message.
    pub fn message(&self) -> &PrivateApplicationMessage {
        &self.message
    }

    /// Encrypted Link snapshot after this receive.
    pub fn resulting_snapshot(&self) -> &EncryptedLinkSnapshot {
        &self.resulting_snapshot
    }
}

impl std::fmt::Debug for PreparedPrivateApplicationMessageReceive {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PreparedPrivateApplicationMessageReceive")
            .field("message", &"<redacted>")
            .field("resulting_snapshot", &"<redacted>")
            .finish()
    }
}

/// Handle to an established Encrypted Link with a counterparty.
///
/// Created by [`advance_handshake`](crate::advance_handshake) (via
/// [`HandshakeProgress::Complete`](crate::HandshakeProgress::Complete)) after
/// a successful Noise handshake. It wraps a transport-mode
/// [`pubky_noise::PubkyNoiseEncryptor`] and should be closed with
/// [`close_encrypted_link`] when no longer needed.
///
/// # Session resumption
///
/// An established Encrypted Link can be snapshotted via [`snapshot`](Self::snapshot)
/// or serialized via [`serialize`](Self::serialize), then restored with
/// [`restore_encrypted_link`] or [`restore_encrypted_link_from_config`].
///
/// # Private Application Message stream
///
/// All private Paykit protocol messages on this link share one ordered stream.
/// Use [`receive_private_application_messages`](Self::receive_private_application_messages)
/// for ordered intake. Callers or SDK layers that derive durable Event Message
/// state should persist and route the returned messages before replacing a
/// stored link snapshot whose read counter has advanced.
///
/// # Automatic send retry
///
/// Send helpers retry transient homeserver write failures according to
/// [`set_max_send_retries`](Self::set_max_send_retries). Deterministic Noise
/// state, counter, nonce, or encryption errors fail immediately.
pub struct EncryptedLink {
    /// The Noise session manager in transport mode.
    encryptor: pubky_noise::PubkyNoiseEncryptor,
    /// The counterparty's Pubky identity key.
    recipient: PublicKey,
    /// The counterparty's identity-wide Noise public key.
    remote_noise_public_key: PublicKey,
    recovery_context: EncryptedLinkRecoveryContext,
    /// Shared Noise configuration retained for snapshot-based session resumption.
    config: std::sync::Arc<pubky_noise::PubkyNoiseConfig>,
    /// Maximum number of automatic Private Application Message `send_message`
    /// retries.
    max_send_retries: u32,
}

impl EncryptedLink {
    /// X25519 static key authenticated by the Noise transcript.
    /// The caller must bind this key to the expected identity, including after restore.
    pub fn remote_static_public_key(&self) -> Option<&[u8]> {
        self.encryptor.remote_static_public_key()
    }

    pub(super) fn from_parts(
        encryptor: pubky_noise::PubkyNoiseEncryptor,
        recipient: PublicKey,
        remote_noise_public_key: PublicKey,
        recovery_context: EncryptedLinkRecoveryContext,
        config: std::sync::Arc<pubky_noise::PubkyNoiseConfig>,
    ) -> Self {
        Self {
            encryptor,
            recipient,
            remote_noise_public_key,
            recovery_context,
            config,
            max_send_retries: DEFAULT_MAX_SEND_RETRIES,
        }
    }

    /// Set the maximum number of automatic Private Application Message
    /// `send_message` retries before Paykit gives up and returns
    /// [`PaykitError::Transport`].
    ///
    /// Retryable homeserver write failures are retried. Deterministic Noise
    /// state, counter, nonce, or encryption errors fail immediately.
    ///
    /// Default: [`DEFAULT_MAX_SEND_RETRIES`] (3).
    pub fn set_max_send_retries(&mut self, max: u32) -> &mut Self {
        self.max_send_retries = max;
        self
    }

    /// Capture the current link state as a serializable snapshot.
    ///
    /// The snapshot captures transport keys, counters, and counterparty identity.
    /// Take a new snapshot after receiving or sending messages when the caller
    /// wants the persisted read/write counters to catch up with local state.
    ///
    /// Snapshot bytes include sensitive key material and must be stored as
    /// secrets. Do not log them or include them in telemetry.
    pub fn snapshot(&self) -> Result<EncryptedLinkSnapshot> {
        Ok(EncryptedLinkSnapshot::from_state(
            self.encryptor
                .snapshot()
                .map_err(|err| PaykitError::InvalidData {
                    context: format!("capture Encrypted Link snapshot: {err:?}"),
                    source: None,
                })?,
            self.recipient.clone(),
            self.remote_noise_public_key.clone(),
            self.recovery_context.clone(),
        ))
    }

    /// Serialize the current link state to bytes for persistence.
    ///
    /// Convenience method equivalent to `self.snapshot()?.serialize()`.
    pub fn serialize(&self) -> Result<Vec<u8>> {
        Ok(self.snapshot()?.serialize())
    }

    /// Access the shared Noise configuration for this link.
    ///
    /// Useful for passing to [`restore_encrypted_link_from_config`] when
    /// performing in-process session recovery without an app restart.
    pub fn config(&self) -> &std::sync::Arc<pubky_noise::PubkyNoiseConfig> {
        &self.config
    }

    /// Access the counterparty public key for this Encrypted Link.
    pub fn recipient(&self) -> &PublicKey {
        &self.recipient
    }

    async fn send_private_application_message_with_context(
        &mut self,
        plaintext: &[u8],
        context: &'static str,
    ) -> Result<()> {
        private_application_message::send_private_application_message(
            &mut self.encryptor,
            self.max_send_retries,
            plaintext,
            context,
        )
        .await
    }

    pub(crate) async fn send_private_payment_list_message(
        &mut self,
        plaintext: &[u8],
    ) -> Result<()> {
        self.send_private_application_message_with_context(plaintext, "Private Payment List")
            .await
    }

    pub(crate) async fn send_receipt_access_message(&mut self, plaintext: &[u8]) -> Result<()> {
        self.send_private_application_message_with_context(plaintext, "Receipt Access")
            .await
    }

    pub(crate) async fn send_payment_request_message(&mut self, plaintext: &[u8]) -> Result<()> {
        self.send_private_application_message_with_context(plaintext, "Payment Request")
            .await
    }

    pub(crate) async fn send_payment_request_acceptance_message(
        &mut self,
        plaintext: &[u8],
    ) -> Result<()> {
        self.send_private_application_message_with_context(plaintext, "Payment Request Acceptance")
            .await
    }

    pub(crate) async fn send_payment_request_rejection_message(
        &mut self,
        plaintext: &[u8],
    ) -> Result<()> {
        self.send_private_application_message_with_context(plaintext, "Payment Request Rejection")
            .await
    }

    pub(crate) async fn send_payment_request_cancellation_message(
        &mut self,
        plaintext: &[u8],
    ) -> Result<()> {
        self.send_private_application_message_with_context(
            plaintext,
            "Payment Request Cancellation",
        )
        .await
    }

    pub(crate) async fn send_payment_proof_message(&mut self, plaintext: &[u8]) -> Result<()> {
        self.send_private_application_message_with_context(plaintext, "Payment Proof")
            .await
    }

    pub(crate) async fn send_payment_conversion_quote_message(
        &mut self,
        plaintext: &[u8],
    ) -> Result<()> {
        self.send_private_application_message_with_context(plaintext, "Payment Conversion Quote")
            .await
    }

    pub(crate) async fn send_allowance_message(&mut self, plaintext: &[u8]) -> Result<()> {
        self.send_private_application_message_with_context(plaintext, "Allowance Event Message")
            .await
    }

    /// Send one raw JSON Private Application Message.
    ///
    /// This is the low-level send counterpart to
    /// [`receive_private_application_messages`](Self::receive_private_application_messages).
    /// It validates the generic `version`, `kind`, and `app_id` envelope
    /// fields; it does not require a known Paykit kind or validate known Paykit
    /// message bodies. Use the typed serializers or SDK queue for
    /// protocol-managed Paykit messages.
    ///
    /// Higher-level callers should persist the exact JSON before sending when
    /// retrying the same message matters.
    ///
    /// Transient outbox write failures are retried up to the configured budget.
    /// If every attempt fails, the prepared packet is retained and blocks
    /// further sends, receives, and snapshots on this link until it is
    /// republished with [`retry_pending_send`](Self::retry_pending_send).
    ///
    /// Do not restore an older snapshot to recover from a failed send: the
    /// failed write may still have reached the homeserver, and rolling back
    /// the sending nonce and slot would reuse the transport key and nonce for
    /// the next plaintext. Only the identical prepared packet may be
    /// republished; otherwise establish a fresh link.
    pub async fn send_private_application_message_json(&mut self, raw_json: &str) -> Result<()> {
        validate_private_application_message_json(raw_json)?;
        self.send_private_application_message_with_context(
            raw_json.as_bytes(),
            "Private Application Message",
        )
        .await
    }

    /// Republish the prepared packet retained after a failed convenience send.
    ///
    /// Until the identical packet is republished, sends, receives, and snapshots
    /// remain blocked. Never restore an older snapshot to retry with different
    /// plaintext: an ambiguous write may already have used that key and nonce.
    /// SDK callers using staged sends should instead publish their durably
    /// persisted ciphertext with [`publish_prepared_private_application_message`](Self::publish_prepared_private_application_message).
    #[allow(deprecated)]
    pub async fn retry_pending_send(&mut self) -> Result<()> {
        self.encryptor
            .retry_pending_send()
            .await
            .map_err(|err| PaykitError::Transport {
                context: format!("retry pending private send: {err:?}"),
                source: anyhow::anyhow!("pubky-noise retry_pending_send failed: {err:?}"),
            })
    }

    /// Prepare one raw JSON Private Application Message for durable handoff.
    ///
    /// Persist the returned ciphertext and resulting snapshot atomically before
    /// calling [`acknowledge_persisted_private_send`](Self::acknowledge_persisted_private_send).
    pub fn prepare_private_application_message_json(
        &mut self,
        raw_json: &str,
    ) -> Result<PreparedPrivateApplicationMessageSend> {
        private_application_message::validate_private_application_message_size(
            raw_json.as_bytes(),
            "Private Application Message",
        )?;
        validate_private_application_message_json(raw_json)?;
        let prepared = self
            .encryptor
            .prepare_send(raw_json.as_bytes())
            .map_err(|err| PaykitError::Transport {
                context: format!("prepare Private Application Message send: {err:?}"),
                source: anyhow::Error::new(crate::error::NonRetryablePrivateSendError(err)),
            })?;
        let resulting_snapshot = EncryptedLinkSnapshot::from_state(
            prepared.resulting_session_state().clone(),
            self.recipient.clone(),
            self.remote_noise_public_key.clone(),
            self.recovery_context.clone(),
        );
        Ok(PreparedPrivateApplicationMessageSend {
            prepared,
            resulting_snapshot,
        })
    }

    /// Acknowledge that a prepared send and its resulting snapshot are durable.
    pub fn acknowledge_persisted_private_send(
        &mut self,
        prepared: PreparedPrivateApplicationMessageSend,
    ) -> Result<()> {
        self.encryptor
            .acknowledge_persisted_send(prepared.prepared)
            .map_err(|err| PaykitError::InvalidData {
                context: format!("acknowledge persisted private send: {err:?}"),
                source: None,
            })
    }

    /// Publish an exact prepared ciphertext, retrying without re-encryption.
    ///
    /// This accepts values restored from durable SDK state after a crash. The
    /// destination must belong to this link's local write stream.
    pub async fn publish_prepared_private_application_message(
        &self,
        destination_path: &str,
        ciphertext: &[u8],
    ) -> Result<()> {
        let expected_prefix = format!("{}/", self.config.write_path);
        if !destination_path.starts_with(&expected_prefix)
            || destination_path[expected_prefix.len()..]
                .parse::<u32>()
                .is_err()
        {
            return Err(PaykitError::Validation(
                "prepared private send destination does not belong to this Encrypted Link".into(),
            ));
        }
        if ciphertext.len() != pubky_noise::snow_crypto::PUBKY_NOISE_TRANSPORT_PACKET_LEN {
            return Err(PaykitError::InvalidData {
                context: "prepared private send ciphertext has an invalid length".into(),
                source: None,
            });
        }

        let max_attempts = self.max_send_retries.saturating_add(1);
        let mut last_error = None;
        for attempt in 1..=max_attempts {
            match self
                .config
                .local_session
                .storage()
                .put(destination_path, ciphertext.to_vec())
                .await
            {
                Ok(_) => return Ok(()),
                Err(err) => {
                    last_error = Some(err);
                    if attempt < max_attempts {
                        tracing::warn!(
                            attempt,
                            max_retries = self.max_send_retries,
                            "prepared private message publication failed, retrying"
                        );
                    }
                }
            }
        }

        Err(PaykitError::Transport {
            context: format!(
                "failed to publish prepared Private Application Message after {max_attempts} attempts"
            ),
            source: last_error
                .expect("at least one prepared private send attempt must run")
                .into(),
        })
    }

    /// Fetch and prepare the next available inbound Private Application Message.
    ///
    /// Persist the application result and returned snapshot atomically before
    /// calling [`acknowledge_persisted_private_receive`](Self::acknowledge_persisted_private_receive).
    pub async fn prepare_next_private_application_message(
        &mut self,
    ) -> Result<Option<PreparedPrivateApplicationMessageReceive>> {
        let path = self
            .encryptor
            .next_receive_path()
            .map_err(|err| PaykitError::Transport {
                context: format!("prepare Private Application Message receive path: {err:?}"),
                source: anyhow::Error::new(crate::error::NonRetryablePrivateReceiveError(err)),
            })?;
        let response = match self.config.outbox_client.public_storage().get(path).await {
            Ok(response) => response,
            Err(pubky::Error::Request(pubky::errors::RequestError::Server { status, .. }))
                if status == pubky::StatusCode::NOT_FOUND || status == pubky::StatusCode::GONE =>
            {
                return Ok(None)
            }
            Err(err) => {
                return Err(PaykitError::Transport {
                    context: "fetch next Private Application Message ciphertext".into(),
                    source: err.into(),
                })
            }
        };
        // Bound hostile outbox bodies before buffering or authenticating them.
        let ciphertext = crate::pubky_routing::read_bounded_body(
            response,
            pubky_noise::snow_crypto::PUBKY_NOISE_TRANSPORT_PACKET_LEN,
            "read next Private Application Message ciphertext",
        )
        .await?;
        let prepared =
            self.encryptor
                .prepare_receive(&ciphertext)
                .map_err(|err| PaykitError::Transport {
                    context: format!("prepare Private Application Message receive: {err:?}"),
                    source: anyhow::Error::new(crate::error::NonRetryablePrivateReceiveError(err)),
                })?;
        let message =
            private_application_message::decode_private_application_message(prepared.plaintext())?;
        let resulting_snapshot = EncryptedLinkSnapshot::from_state(
            prepared.resulting_session_state().clone(),
            self.recipient.clone(),
            self.remote_noise_public_key.clone(),
            self.recovery_context.clone(),
        );
        Ok(Some(PreparedPrivateApplicationMessageReceive {
            prepared,
            message,
            resulting_snapshot,
        }))
    }

    /// Acknowledge that a prepared receive and its application result are durable.
    pub fn acknowledge_persisted_private_receive(
        &mut self,
        prepared: PreparedPrivateApplicationMessageReceive,
    ) -> Result<()> {
        self.encryptor
            .acknowledge_persisted_receive(prepared.prepared)
            .map_err(|err| PaykitError::InvalidData {
                context: format!("acknowledge persisted private receive: {err:?}"),
                source: None,
            })
    }

    #[cfg(test)]
    pub(crate) async fn send_private_application_message_for_test(
        &mut self,
        plaintext: &[u8],
    ) -> Result<()> {
        self.send_private_application_message_with_context(
            plaintext,
            "raw test Private Application Message",
        )
        .await
    }

    #[cfg(test)]
    pub(crate) fn next_receive_path_for_test(&self) -> Result<String> {
        self.encryptor
            .next_receive_path()
            .map_err(|err| PaykitError::Transport {
                context: format!("next_receive_path: {err:?}"),
                source: anyhow::anyhow!("pubky-noise next_receive_path failed: {err:?}"),
            })
    }

    #[cfg(test)]
    pub(crate) fn enable_write_failure_for_test(&mut self) {
        self.encryptor.test_enable_write_failure();
    }

    #[cfg(test)]
    pub(crate) fn disable_write_failure_for_test(&mut self) {
        self.encryptor.test_disable_write_failure();
    }

    /// Receive a bounded batch of available Private Application Messages in
    /// stream order.
    ///
    /// The Noise read checkpoint advances past the returned messages. Callers
    /// that need crash-safe Event Message handling should persist returned
    /// messages before replacing a stored link snapshot. Call again to drain
    /// more than [`PRIVATE_APPLICATION_MESSAGE_RECEIVE_LIMIT`](crate::PRIVATE_APPLICATION_MESSAGE_RECEIVE_LIMIT)
    /// available stream slots.
    #[instrument(skip(self))]
    pub async fn receive_private_application_messages(
        &mut self,
    ) -> Result<Vec<PrivateApplicationMessage>> {
        private_application_message::receive_private_application_messages(&mut self.encryptor).await
    }
}

fn validate_private_application_message_json(raw_json: &str) -> Result<()> {
    let value: serde_json::Value =
        serde_json::from_str(raw_json).map_err(|err| PaykitError::Validation(err.to_string()))?;
    if value
        .get("version")
        .and_then(serde_json::Value::as_u64)
        .is_none_or(|version| u8::try_from(version).is_err())
    {
        return Err(PaykitError::Validation(
            "Private Application Message version must be a u8 integer".into(),
        ));
    }
    if !value.get("kind").is_some_and(serde_json::Value::is_string) {
        return Err(PaykitError::Validation(
            "Private Application Message kind must be a string".into(),
        ));
    }
    let app_id = value
        .get("app_id")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| {
            PaykitError::Validation("Private Application Message app_id must be a string".into())
        })?;
    PaykitAppId::new(app_id)?;
    Ok(())
}

/// Default maximum number of automatic Private Application Message
/// `send_message` retries before Paykit gives up and returns an error.
///
/// Override per-link via [`EncryptedLink::set_max_send_retries`].
pub const DEFAULT_MAX_SEND_RETRIES: u32 = 3;

/// Closes an Encrypted Link and cleans up the Noise session state.
///
/// After calling this function, the [`EncryptedLink`] is consumed and can no
/// longer be used for encryption or decryption.
#[instrument(skip(link))]
pub async fn close_encrypted_link(mut link: EncryptedLink) -> Result<()> {
    debug!("closing Encrypted Link");
    link.encryptor.close();
    debug!("Encrypted Link closed successfully");
    Ok(())
}

/// Restores an [`EncryptedLink`] from a previously saved snapshot.
///
/// Use this after an app restart when the original Noise configuration is no
/// longer available. The caller supplies a fresh authenticated Pubky session,
/// the same local secret key used for the original link, the counterparty
/// public key, and the saved snapshot.
///
/// Restored links reset `max_send_retries` to [`DEFAULT_MAX_SEND_RETRIES`].
/// `remote_identity_public_key` must match `snapshot.recipient()`.
/// Download failures return [`PaykitError::Transport`]; retain the snapshot to retry.
/// Missing or invalid handshake transcripts return [`PaykitError::InvalidData`].
#[instrument(skip(session, secret_key, outbox_client, snapshot))]
pub async fn restore_encrypted_link(
    session: pubky::PubkySession,
    secret_key: [u8; 32],
    remote_identity_public_key: &PublicKey,
    outbox_client: pubky::Pubky,
    snapshot: EncryptedLinkSnapshot,
) -> Result<EncryptedLink> {
    debug!("restoring Encrypted Link from snapshot (raw params)");

    let (write_path, read_path) = compute_private_payment_paths(
        &secret_key,
        session.info().public_key(),
        remote_identity_public_key,
        snapshot.remote_noise_public_key(),
        snapshot.recovery_context(),
    );

    let config = pubky_noise::PubkyNoiseConfig::new_with_paths(
        secret_key,
        0,
        "XX",
        session,
        write_path,
        read_path,
        outbox_client,
    )
    .map_err(|err| PaykitError::InvalidData {
        context: format!("failed to create encryptor config for restore: {err:?}"),
        source: Some(anyhow::anyhow!(
            "pubky-noise PubkyNoiseConfig::new failed: {err:?}"
        )),
    })?;

    restore_encrypted_link_inner(config, remote_identity_public_key, snapshot).await
}

/// Restores an [`EncryptedLink`] from a previously saved snapshot using an
/// existing Noise configuration.
///
/// Use this in-process when the original `Arc<PubkyNoiseConfig>` is still
/// available. For cross-restart recovery, use [`restore_encrypted_link`].
///
/// Restored links reset `max_send_retries` to [`DEFAULT_MAX_SEND_RETRIES`].
/// `remote_identity_public_key` must match `snapshot.recipient()`.
/// The config's Noise key must match the snapshot's static key.
/// The config paths must match the session's local Pubky identity, the remote
/// identity, and the Noise keys; mismatches return [`PaykitError::Validation`].
/// Download failures return [`PaykitError::Transport`]; missing or invalid
/// handshake transcripts return [`PaykitError::InvalidData`].
#[instrument(skip(config, snapshot))]
pub async fn restore_encrypted_link_from_config(
    config: std::sync::Arc<pubky_noise::PubkyNoiseConfig>,
    remote_identity_public_key: &PublicKey,
    snapshot: EncryptedLinkSnapshot,
) -> Result<EncryptedLink> {
    debug!("restoring Encrypted Link from snapshot (existing config)");
    restore_encrypted_link_inner(config, remote_identity_public_key, snapshot).await
}

/// Shared implementation for both restore variants.
async fn restore_encrypted_link_inner(
    config: std::sync::Arc<pubky_noise::PubkyNoiseConfig>,
    remote_identity_public_key: &PublicKey,
    snapshot: EncryptedLinkSnapshot,
) -> Result<EncryptedLink> {
    if snapshot.recipient() != remote_identity_public_key {
        return Err(PaykitError::Validation(format!(
            "remote_identity_public_key does not match snapshot recipient (remote={}, snapshot={})",
            remote_identity_public_key,
            snapshot.recipient(),
        )));
    }

    let phase = snapshot.phase();
    if !matches!(phase, pubky_noise::snow_crypto::NoisePhase::Transport) {
        return Err(PaykitError::Validation(format!(
            "Encrypted Link restore requires transport-phase snapshot, got {:?}",
            phase,
        )));
    }

    let remote_noise_public_key = snapshot.remote_noise_public_key().clone();
    let recovery_context = snapshot.recovery_context().clone();
    validate_private_payment_paths(
        &config,
        remote_identity_public_key,
        &remote_noise_public_key,
        &recovery_context,
    )?;
    let state = snapshot.into_state();
    if state.static_secret != Some(config.pubky_root_keypair.secret_key()) {
        return Err(PaykitError::Validation(
            "Noise config key does not match snapshot static key".into(),
        ));
    }
    let encryptor = pubky_noise::PubkyNoiseEncryptor::restore(
        config.clone(),
        state,
        remote_identity_public_key.clone(),
    )
    .await
    .map_err(|err| PaykitError::InvalidData {
        context: format!("failed to restore Encrypted Link: {err:?}"),
        source: Some(anyhow::anyhow!("pubky-noise restore failed: {err:?}")),
    })?;

    debug!("Encrypted Link restored successfully");
    Ok(EncryptedLink::from_parts(
        encryptor,
        remote_identity_public_key.clone(),
        remote_noise_public_key,
        recovery_context,
        config,
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validate_private_application_message_json_requires_header() {
        assert!(validate_private_application_message_json(
            r#"{"version":1,"kind":"paykit.private_payment_list","app_id":"bitkit"}"#
        )
        .is_ok());
        assert!(validate_private_application_message_json(r#"{"version":1}"#).is_err());
        assert!(validate_private_application_message_json(r#"{"kind":"paykit.test"}"#).is_err());
        assert!(
            validate_private_application_message_json(r#"{"version":1,"kind":"paykit.test"}"#)
                .is_err()
        );
        assert!(validate_private_application_message_json(
            r#"{"version":1,"kind":"paykit.test","app_id":"bad/path"}"#
        )
        .is_err());
    }
}