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
use std::collections::HashMap;

use tracing::{debug, instrument};

use crate::{error::map_error, pubky_routing, PaykitAppId, PaykitError, PublicKey, Result};

/// Machine-readable identifier for a Payment Endpoint.
///
/// A `PaymentEndpointIdentifier` is a single, safe path segment stored in an
/// app-owned endpoint directory. It is validated at construction time to
/// prevent path injection attacks.
///
/// # Allowed characters
/// ASCII alphanumeric (`a-z`, `A-Z`, `0-9`), hyphens (`-`), underscores (`_`),
/// and dots (`.`) — but the value must not consist solely of dots (i.e. `"."` and
/// `".."` are rejected).
///
/// # Limits
/// - Must not be empty.
/// - Must not exceed 64 characters.
/// - Must not be a reserved Paykit storage value.
///
/// # Examples
/// ```
/// # use paykit_lib::PaymentEndpointIdentifier;
/// let id = PaymentEndpointIdentifier::new("btc-lightning-bolt11").unwrap();
/// assert_eq!(id.as_str(), "btc-lightning-bolt11");
///
/// // Path traversal is rejected:
/// assert!(PaymentEndpointIdentifier::new("../etc/passwd").is_err());
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PaymentEndpointIdentifier(String);

/// Maximum length (in bytes) of a [`PaymentEndpointIdentifier`] value.
const PAYMENT_ENDPOINT_IDENTIFIER_MAX_LEN: usize = 64;
/// Reserved [`PaymentEndpointIdentifier`] value used by private Paykit storage.
const PAYMENT_ENDPOINT_IDENTIFIER_RESERVED_PRIVATE: &str = "private";

impl PaymentEndpointIdentifier {
    /// Create a new `PaymentEndpointIdentifier` after validating the identifier.
    ///
    /// Returns `Err(PaykitError::Validation)` if the value is empty, too long,
    /// contains forbidden characters, resembles a path-traversal component,
    /// or collides with a reserved identifier.
    pub fn new(id: impl Into<String>) -> Result<Self> {
        let id = id.into();

        if id.is_empty() {
            return Err(PaykitError::Validation(
                "PaymentEndpointIdentifier must not be empty".into(),
            ));
        }

        if id.len() > PAYMENT_ENDPOINT_IDENTIFIER_MAX_LEN {
            return Err(PaykitError::Validation(format!(
                "PaymentEndpointIdentifier must not exceed {PAYMENT_ENDPOINT_IDENTIFIER_MAX_LEN} characters, got {}",
                id.chars().count()
            )));
        }

        if id == PAYMENT_ENDPOINT_IDENTIFIER_RESERVED_PRIVATE {
            return Err(PaykitError::Validation(format!(
                "PaymentEndpointIdentifier '{id}' is reserved for Paykit storage"
            )));
        }

        // Every character must be ASCII alphanumeric, hyphen, underscore, or dot.
        if let Some((pos, ch)) = id
            .char_indices()
            .find(|&(_, ch)| !(ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.'))
        {
            // SECURITY / REDACTION: the identifier can come from decrypted
            // private-message plaintext or remote public data. Report only the
            // code point and byte offset, as `PaymentReference::new` does.
            return Err(PaykitError::Validation(format!(
                "PaymentEndpointIdentifier contains forbidden character U+{:04X} at byte {pos}",
                ch as u32
            )));
        }

        // Reject pure-dot names that are path-traversal components.
        if id.bytes().all(|b| b == b'.') {
            return Err(PaykitError::Validation(format!(
                "PaymentEndpointIdentifier must not be a path-traversal component: \"{id}\""
            )));
        }

        Ok(Self(id))
    }

    /// Access the inner identifier string.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for PaymentEndpointIdentifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for PaymentEndpointIdentifier {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// Serialized Payment Endpoint Payload served by a Payment Endpoint.
///
/// The payload is UTF-8 text such as JSON, lnurl, or another payment-specific
/// descriptor. If you need to transmit binary payloads, encode them (for
/// example base64) before wrapping in `PaymentEndpointPayload`.
/// Public storage helpers reject payloads larger than
/// [`PAYMENT_ENDPOINT_PAYLOAD_MAX_BYTES`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PaymentEndpointPayload(String);

/// Maximum encoded size of one public Payment Endpoint payload.
pub const PAYMENT_ENDPOINT_PAYLOAD_MAX_BYTES: usize = 64 * 1024;
/// Maximum number of public Payment Endpoints fetched for one Paykit App.
pub const PAYMENT_LIST_MAX_ENDPOINTS: usize = 256;

impl PaymentEndpointPayload {
    /// Wrap a UTF-8 string as a Payment Endpoint Payload.
    pub fn new(data: impl Into<String>) -> Self {
        Self(data.into())
    }

    /// Access the inner payload string.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume the wrapper and return the inner string.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl std::fmt::Display for PaymentEndpointPayload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for PaymentEndpointPayload {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// Collection of Payment Endpoints keyed by Payment Endpoint Identifiers.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PaymentList {
    /// Map of Payment Endpoint Identifier to Payment Endpoint Payload.
    pub payment_endpoints: HashMap<PaymentEndpointIdentifier, PaymentEndpointPayload>,
}

/// Stores or updates a public payment endpoint in the authenticated Pubky session.
///
/// # Examples
/// ```
/// # use paykit_lib::{set_payment_endpoint, PaykitAppId, PaymentEndpointIdentifier, PaymentEndpointPayload};
/// # async fn demo(session: &pubky::PubkySession) -> paykit_lib::Result<()> {
/// let app_id = PaykitAppId::new("bitkit")?;
/// let identifier = PaymentEndpointIdentifier::new("btc-lightning-bolt11")?;
/// let payload = PaymentEndpointPayload::new("ln...");
/// set_payment_endpoint(session, &app_id, identifier, payload).await?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(session, payload), fields(identifier = %identifier))]
pub async fn set_payment_endpoint(
    session: &pubky::PubkySession,
    app_id: &PaykitAppId,
    identifier: PaymentEndpointIdentifier,
    payload: PaymentEndpointPayload,
) -> Result<()> {
    debug!("storing payment endpoint");
    pubky_routing::upsert_payment_endpoint(session, app_id, &identifier, &payload)
        .await
        .map_err(|err| map_error("set_payment_endpoint", err))
}

/// Creates a public Payment Endpoint only when it is currently absent.
///
/// Session creation, capability scope, and key rotation remain the caller's responsibility.
pub async fn create_payment_endpoint(
    session: &pubky::PubkySession,
    app_id: &PaykitAppId,
    identifier: PaymentEndpointIdentifier,
    payload: PaymentEndpointPayload,
) -> Result<()> {
    pubky_routing::create_payment_endpoint(session, app_id, &identifier, &payload)
        .await
        .map_err(|err| map_error("create_payment_endpoint", err))
}

/// Replaces a public Payment Endpoint only at the supplied strong revision.
///
/// Session creation, capability scope, and key rotation remain the caller's responsibility.
pub async fn update_payment_endpoint(
    session: &pubky::PubkySession,
    app_id: &PaykitAppId,
    identifier: PaymentEndpointIdentifier,
    payload: PaymentEndpointPayload,
    expected_revision: &str,
) -> Result<()> {
    pubky_routing::update_payment_endpoint(
        session,
        app_id,
        &identifier,
        &payload,
        expected_revision,
    )
    .await
    .map_err(|err| map_error("update_payment_endpoint", err))
}

/// Removes a public payment endpoint from the authenticated Pubky session.
#[instrument(skip(session), fields(identifier = %identifier))]
pub async fn remove_payment_endpoint(
    session: &pubky::PubkySession,
    app_id: &PaykitAppId,
    identifier: PaymentEndpointIdentifier,
) -> Result<()> {
    debug!("removing payment endpoint");
    pubky_routing::delete_payment_endpoint(session, app_id, &identifier)
        .await
        .map_err(|err| map_error("remove_payment_endpoint", err))
}

/// Removes a public Payment Endpoint only at the supplied strong revision.
///
/// Session creation, capability scope, and key rotation remain the caller's responsibility.
pub async fn remove_payment_endpoint_if_revision(
    session: &pubky::PubkySession,
    app_id: &PaykitAppId,
    identifier: PaymentEndpointIdentifier,
    expected_revision: &str,
) -> Result<()> {
    pubky_routing::delete_payment_endpoint_if_revision(
        session,
        app_id,
        &identifier,
        expected_revision,
    )
    .await
    .map_err(|err| map_error("remove_payment_endpoint_if_revision", err))
}

/// Retrieves the public Payment List for the given payee.
///
/// # Semantics
/// - Returns an empty map when the payee has not published any endpoints or their
///   storage directory is missing.
/// - Returns `Err(PaykitError::InvalidData)` when a resource path is unparseable or
///   an endpoint payload contains invalid UTF-8.
/// - Returns `Err(PaykitError::Transport)` for network or transport-layer failures.
///
/// # Examples
/// ```
/// # #![recursion_limit = "256"]
/// # use paykit_lib::{get_payment_list, PaykitAppId};
/// # async fn demo(storage: &pubky::PublicStorage, pk: &paykit_lib::PublicKey) -> paykit_lib::Result<()> {
/// let app_id = PaykitAppId::new("bitkit")?;
/// let payments = get_payment_list(storage, pk, &app_id).await?;
/// if payments.payment_endpoints.is_empty() {
///     println!("payee published no endpoints yet");
/// } else {
///     for (identifier, payload) in &payments.payment_endpoints {
///         println!(
///             "identifier={} payload={}",
///             identifier.as_str(),
///             payload.as_str()
///         );
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(storage))]
pub async fn get_payment_list(
    storage: &pubky::PublicStorage,
    payee: &PublicKey,
    app_id: &PaykitAppId,
) -> Result<PaymentList> {
    get_payment_list_with_limits(
        storage,
        payee,
        app_id,
        PAYMENT_LIST_MAX_ENDPOINTS,
        PAYMENT_LIST_MAX_ENDPOINTS * PAYMENT_ENDPOINT_PAYLOAD_MAX_BYTES,
    )
    .await
}

/// Fetch an app's public Payment Endpoints within caller-supplied aggregate limits.
///
/// The fetch fails if the app publishes more endpoints or total payload bytes
/// than the supplied limits. Per-endpoint protocol limits still apply.
#[instrument(skip(storage))]
pub async fn get_payment_list_with_limits(
    storage: &pubky::PublicStorage,
    payee: &PublicKey,
    app_id: &PaykitAppId,
    max_endpoints: usize,
    max_total_payload_bytes: usize,
) -> Result<PaymentList> {
    let mut remaining_requests = usize::MAX;
    let mut remaining_endpoints = max_endpoints;
    let mut remaining_payload_bytes = max_total_payload_bytes;
    get_payment_list_with_budget(
        storage,
        payee,
        app_id,
        &mut remaining_endpoints,
        &mut remaining_requests,
        &mut remaining_payload_bytes,
    )
    .await
}

/// Fetch an app's public Payment Endpoints using a budget shared across app loads.
///
/// Each directory-page or endpoint request consumes one request before it starts.
/// Each endpoint fetch also consumes one endpoint attempt, regardless of its result.
/// Endpoint body bytes consume the byte budget as they are read, even if the list
/// later fails validation. Missing and empty resources still consume requests.
/// Counters are retained on failure; exhausting the aggregate byte budget saturates
/// that counter at zero. Per-endpoint and per-list protocol limits still apply.
///
/// The caller owns client timeouts, session creation, capability scope, and key
/// rotation. This read only requires public Pubky storage.
#[instrument(skip(
    storage,
    remaining_endpoints,
    remaining_requests,
    remaining_payload_bytes
))]
pub async fn get_payment_list_with_budget(
    storage: &pubky::PublicStorage,
    payee: &PublicKey,
    app_id: &PaykitAppId,
    remaining_endpoints: &mut usize,
    remaining_requests: &mut usize,
    remaining_payload_bytes: &mut usize,
) -> Result<PaymentList> {
    debug!("fetching Payment List");
    let result = pubky_routing::fetch_payment_list_with_budget(
        storage,
        payee,
        app_id,
        remaining_endpoints,
        remaining_requests,
        remaining_payload_bytes,
    )
    .await
    .map_err(|err| map_error("get_payment_list", err))?;
    debug!(
        count = result.payment_endpoints.len(),
        "Payment List retrieved"
    );
    Ok(result)
}

/// Return whether a Payment List fetch failed because it exceeded caller-supplied limits.
pub fn is_payment_list_limit_exceeded(error: &PaykitError) -> bool {
    pubky_routing::is_payment_list_limit_exceeded(error)
}

/// Retrieves a specific Payment Endpoint for `payee` and `identifier`.
///
/// # Semantics
/// - Returns `Ok(None)` when the endpoint file is missing or empty.
/// - Returns `Err(PaykitError::InvalidData)` when the endpoint payload contains invalid UTF-8.
/// - Returns `Err(PaykitError::Transport)` for network or transport-layer failures.
///
/// # Examples
/// ```
/// # use paykit_lib::{get_payment_endpoint, PaykitAppId, PaymentEndpointIdentifier, PublicKey};
/// # async fn inspect(storage: &pubky::PublicStorage, pk: &PublicKey) -> paykit_lib::Result<()> {
/// let app_id = PaykitAppId::new("bitkit")?;
/// let lightning = PaymentEndpointIdentifier::new("btc-lightning-bolt11")?;
/// if let Some(endpoint) = get_payment_endpoint(storage, pk, &app_id, &lightning).await? {
///     println!("lightning endpoint: {}", endpoint.as_str());
/// } else {
///     println!("no lightning endpoint published");
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(storage), fields(identifier = %identifier))]
pub async fn get_payment_endpoint(
    storage: &pubky::PublicStorage,
    payee: &PublicKey,
    app_id: &PaykitAppId,
    identifier: &PaymentEndpointIdentifier,
) -> Result<Option<PaymentEndpointPayload>> {
    debug!("fetching payment endpoint");
    let result = pubky_routing::fetch_payment_endpoint(storage, payee, app_id, identifier)
        .await
        .map_err(|err| map_error("get_payment_endpoint", err))?;
    debug!(found = result.is_some(), "payment endpoint lookup complete");
    Ok(result)
}

/// Retrieves a specific public Payment Endpoint and its strong revision.
///
/// The outer `Option` is `None` when the resource is absent. The inner payload
/// is `None` when the resource exists but is empty.
pub async fn get_payment_endpoint_with_revision(
    storage: &pubky::PublicStorage,
    payee: &PublicKey,
    app_id: &PaykitAppId,
    identifier: &PaymentEndpointIdentifier,
) -> Result<Option<(Option<PaymentEndpointPayload>, String)>> {
    pubky_routing::fetch_payment_endpoint_with_revision(storage, payee, app_id, identifier)
        .await
        .map_err(|err| map_error("get_payment_endpoint_with_revision", err))
}

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

    // ── PaymentEndpointIdentifier: valid inputs ──────────────────────────────────────────

    #[test]
    fn test_payment_endpoint_identifier_valid_simple_names() {
        for name in [
            "btc-lightning-bolt11",
            "btc-lightning-bolt12",
            "btc-bitcoin-p2tr",
        ] {
            assert!(
                PaymentEndpointIdentifier::new(name).is_ok(),
                "expected '{name}' to be valid"
            );
        }
    }

    #[test]
    fn test_payment_endpoint_identifier_valid_with_dots() {
        let m = PaymentEndpointIdentifier::new("method.v2").unwrap();
        assert_eq!(m.as_str(), "method.v2");
    }

    #[test]
    fn test_payment_endpoint_identifier_valid_with_underscores() {
        let m = PaymentEndpointIdentifier::new("my_method").unwrap();
        assert_eq!(m.as_str(), "my_method");
    }

    #[test]
    fn test_payment_endpoint_identifier_valid_mixed_case() {
        let m = PaymentEndpointIdentifier::new("LnUrl-Pay").unwrap();
        assert_eq!(m.as_str(), "LnUrl-Pay");
    }

    #[test]
    fn test_payment_endpoint_identifier_valid_max_length() {
        let name = "a".repeat(PAYMENT_ENDPOINT_IDENTIFIER_MAX_LEN);
        assert!(PaymentEndpointIdentifier::new(&name).is_ok());
    }

    #[test]
    fn test_payment_endpoint_identifier_valid_single_char() {
        assert!(PaymentEndpointIdentifier::new("x").is_ok());
    }

    #[test]
    fn test_payment_endpoint_identifier_display() {
        let m = PaymentEndpointIdentifier::new("lightning").unwrap();
        assert_eq!(format!("{m}"), "lightning");
    }

    #[test]
    fn test_payment_endpoint_identifier_as_ref() {
        let m = PaymentEndpointIdentifier::new("onchain").unwrap();
        let s: &str = m.as_ref();
        assert_eq!(s, "onchain");
    }

    // ── PaymentEndpointIdentifier: invalid inputs ────────────────────────────────────────

    #[test]
    fn test_payment_endpoint_identifier_reject_empty() {
        let err = PaymentEndpointIdentifier::new("").unwrap_err();
        assert!(matches!(err, PaykitError::Validation(msg) if msg.contains("empty")));
    }

    #[test]
    fn test_payment_endpoint_identifier_reject_path_traversal_dotdot() {
        assert!(PaymentEndpointIdentifier::new("..").is_err());
    }

    #[test]
    fn test_payment_endpoint_identifier_reject_path_traversal_dot() {
        assert!(PaymentEndpointIdentifier::new(".").is_err());
    }

    #[test]
    fn test_payment_endpoint_identifier_reject_path_traversal_sequence() {
        // Slashes are rejected by the character allowlist, but verify the
        // specific traversal pattern is caught.
        assert!(PaymentEndpointIdentifier::new("../etc/passwd").is_err());
        assert!(PaymentEndpointIdentifier::new("../../foo").is_err());
    }

    #[test]
    fn test_payment_endpoint_identifier_reject_forward_slash() {
        assert!(PaymentEndpointIdentifier::new("foo/bar").is_err());
    }

    #[test]
    fn test_payment_endpoint_identifier_reject_backslash() {
        assert!(PaymentEndpointIdentifier::new("a\\b").is_err());
    }

    #[test]
    fn test_payment_endpoint_identifier_reject_null_byte() {
        assert!(PaymentEndpointIdentifier::new("foo\0bar").is_err());
    }

    #[test]
    fn test_payment_endpoint_identifier_reject_too_long() {
        let name = "a".repeat(PAYMENT_ENDPOINT_IDENTIFIER_MAX_LEN + 1);
        let err = PaymentEndpointIdentifier::new(&name).unwrap_err();
        assert!(matches!(err, PaykitError::Validation(msg) if msg.contains("exceed")));
    }

    #[test]
    fn test_payment_endpoint_identifier_reject_space() {
        assert!(PaymentEndpointIdentifier::new("foo bar").is_err());
    }

    #[test]
    fn test_payment_endpoint_identifier_reject_special_chars() {
        for bad in ["foo@bar", "foo:bar", "foo?bar", "foo#bar", "foo=bar"] {
            assert!(
                PaymentEndpointIdentifier::new(bad).is_err(),
                "expected '{bad}' to be rejected"
            );
        }
    }

    #[test]
    fn test_payment_endpoint_identifier_reject_unicode() {
        assert!(PaymentEndpointIdentifier::new("⚡lightning").is_err());
    }

    #[test]
    fn test_payment_endpoint_identifier_reject_triple_dots() {
        assert!(PaymentEndpointIdentifier::new("...").is_err());
    }

    #[test]
    fn test_payment_endpoint_identifier_reject_reserved_values() {
        let err = PaymentEndpointIdentifier::new("private").unwrap_err();
        assert!(matches!(err, PaykitError::Validation(msg) if msg.contains("reserved")));
    }

    #[test]
    fn test_payment_endpoint_identifier_forbidden_character_error_redacts_value() {
        let err = PaymentEndpointIdentifier::new("evil_SENTINEL\tid").unwrap_err();
        assert!(
            matches!(&err, PaykitError::Validation(msg)
                if msg.contains("U+0009 at byte 13")
                    && !msg.contains("SENTINEL")
                    && !msg.contains('\t')),
            "{err:?}"
        );
    }

    // ── PaymentEndpointPayload: basic accessors ───────────────────────────────────

    #[test]
    fn test_payment_endpoint_payload_new_and_accessors() {
        let d = PaymentEndpointPayload::new("ln...");
        assert_eq!(d.as_str(), "ln...");
        assert_eq!(format!("{d}"), "ln...");
    }

    #[test]
    fn test_payment_endpoint_payload_into_inner() {
        let d = PaymentEndpointPayload::new("payload");
        assert_eq!(d.into_inner(), "payload");
    }

    #[test]
    fn test_payment_endpoint_payload_as_ref() {
        let d = PaymentEndpointPayload::new("data");
        let s: &str = d.as_ref();
        assert_eq!(s, "data");
    }
}