lightning_types/payment.rs
1// This file is Copyright its original authors, visible in version control
2// history.
3//
4// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7// You may not use this file except in accordance with one or both of these
8// licenses.
9
10//! Types which describe payments in lightning.
11
12use core::borrow::Borrow;
13
14use bitcoin::hashes::{sha256::Hash as Sha256, Hash as _};
15use bitcoin::hex::display::impl_fmt_traits;
16
17/// The payment hash is the hash of the [`PaymentPreimage`] which is the value used to lock funds
18/// in HTLCs while they transit the lightning network.
19///
20/// This is not exported to bindings users as we just use [u8; 32] directly
21#[derive(Hash, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)]
22pub struct PaymentHash(pub [u8; 32]);
23
24impl Borrow<[u8]> for PaymentHash {
25 fn borrow(&self) -> &[u8] {
26 &self.0[..]
27 }
28}
29
30impl_fmt_traits! {
31 impl fmt_traits for PaymentHash {
32 const LENGTH: usize = 32;
33 }
34}
35
36/// The payment preimage is the "secret key" which is used to claim the funds of an HTLC on-chain
37/// or in a lightning channel.
38///
39/// This is not exported to bindings users as we just use [u8; 32] directly
40#[derive(Hash, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)]
41pub struct PaymentPreimage(pub [u8; 32]);
42
43impl Borrow<[u8]> for PaymentPreimage {
44 fn borrow(&self) -> &[u8] {
45 &self.0[..]
46 }
47}
48
49impl_fmt_traits! {
50 impl fmt_traits for PaymentPreimage {
51 const LENGTH: usize = 32;
52 }
53}
54
55/// Converts a `PaymentPreimage` into a `PaymentHash` by hashing the preimage with SHA256.
56impl From<PaymentPreimage> for PaymentHash {
57 fn from(value: PaymentPreimage) -> Self {
58 PaymentHash(Sha256::hash(&value.0).to_byte_array())
59 }
60}
61
62/// The payment secret is used to authenticate the sender of an HTLC to the recipient and tie
63/// multi-part HTLCs together into a single payment.
64///
65/// This is not exported to bindings users as we just use [u8; 32] directly
66#[derive(Hash, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)]
67pub struct PaymentSecret(pub [u8; 32]);
68
69impl Borrow<[u8]> for PaymentSecret {
70 fn borrow(&self) -> &[u8] {
71 &self.0[..]
72 }
73}
74
75impl_fmt_traits! {
76 impl fmt_traits for PaymentSecret {
77 const LENGTH: usize = 32;
78 }
79}