Skip to content

Commit 4624caf

Browse files
committed
Move Payment{Hash,Preimage,Secret} into a new crate
`lightning-invoice` currently has a dependency on the entire `lightning` crate just because it wants to use some of the useful types from it. This is obviously backwards and leads to some awkwardness like the BOLT 11 invoice signing API in the `lightning` crate taking a `[u5]` rather than a `Bolt11Invoice`. This is the first step towards fixing that - moving the common types we need into a new `lightning-types` crate which both can depend on. Since we're using a new crate and can't depend on the existing `lightning` hex utility to implement `Display`, we also take this opportunity to switch to the new `Display` impl macro in `hex_conservative`.
1 parent bc1c026 commit 4624caf

File tree

11 files changed

+176
-73
lines changed

11 files changed

+176
-73
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ resolver = "2"
33

44
members = [
55
"lightning",
6+
"lightning-types",
67
"lightning-block-sync",
78
"lightning-invoice",
89
"lightning-net-tokio",

fuzz/src/chanmon_consistency.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ use lightning::ln::msgs::{
5656
self, ChannelMessageHandler, CommitmentUpdate, DecodeError, Init, UpdateAddHTLC,
5757
};
5858
use lightning::ln::script::ShutdownScript;
59-
use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
59+
use lightning::ln::types::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
6060
use lightning::offers::invoice::{BlindedPayInfo, UnsignedBolt12Invoice};
6161
use lightning::offers::invoice_request::UnsignedInvoiceRequest;
6262
use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath};

fuzz/src/full_stack.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ use lightning::ln::peer_handler::{
4949
IgnoringMessageHandler, MessageHandler, PeerManager, SocketDescriptor,
5050
};
5151
use lightning::ln::script::ShutdownScript;
52-
use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
52+
use lightning::ln::types::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
5353
use lightning::offers::invoice::{BlindedPayInfo, UnsignedBolt12Invoice};
5454
use lightning::offers::invoice_request::UnsignedInvoiceRequest;
5555
use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath};

fuzz/src/router.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use lightning::ln::channel_state::{ChannelCounterparty, ChannelDetails, ChannelS
1818
use lightning::ln::channelmanager;
1919
use lightning::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
2020
use lightning::ln::msgs;
21-
use lightning::ln::ChannelId;
21+
use lightning::ln::types::ChannelId;
2222
use lightning::offers::invoice::BlindedPayInfo;
2323
use lightning::routing::gossip::{NetworkGraph, RoutingFees};
2424
use lightning::routing::router::{

lightning-types/Cargo.toml

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
[package]
2+
name = "lightning-types"
3+
version = "0.1.0"
4+
authors = ["Matt Corallo"]
5+
license = "MIT OR Apache-2.0"
6+
repository = "https://github.com/lightningdevkit/rust-lightning/"
7+
description = """
8+
Basic types which are used in the lightning network
9+
"""
10+
edition = "2021"
11+
12+
[package.metadata.docs.rs]
13+
rustdoc-args = ["--cfg", "docsrs"]
14+
15+
[features]
16+
17+
[dependencies]
18+
bitcoin = { version = "0.31", default-features = false }
19+
# TODO: Once we switch to bitcoin 0.32 drop this explicit dep:
20+
hex-conservative = { version = "0.2", default-features = false }
21+
bech32 = { version = "0.9", default-features = false }
22+
23+
[lints]
24+
workspace = true

lightning-types/src/lib.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
#![crate_name = "lightning_types"]
11+
12+
//! Various types which are used in the lightning network.
13+
//!
14+
//! See the `lightning` crate for usage of these.
15+
16+
#![cfg_attr(not(test), no_std)]
17+
#![deny(missing_docs)]
18+
#![forbid(unsafe_code)]
19+
#![deny(rustdoc::broken_intra_doc_links)]
20+
#![deny(rustdoc::private_intra_doc_links)]
21+
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
22+
23+
extern crate alloc;
24+
extern crate core;
25+
26+
pub mod payment;

lightning-types/src/payment.rs

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
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+
12+
use alloc::vec::Vec;
13+
14+
use core::borrow::Borrow;
15+
16+
use bitcoin::hashes::{
17+
Hash as _,
18+
sha256::Hash as Sha256,
19+
};
20+
21+
// TODO: Once we switch to rust-bitcoin 0.32, import this as bitcoin::hex
22+
use hex_conservative::display::impl_fmt_traits;
23+
24+
/// The payment hash is the hash of the [`PaymentPreimage`] which is the value used to lock funds
25+
/// in HTLCs while they transit the lightning network.
26+
///
27+
/// This is not exported to bindings users as we just use [u8; 32] directly
28+
#[derive(Hash, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)]
29+
pub struct PaymentHash(pub [u8; 32]);
30+
31+
impl Borrow<[u8]> for PaymentHash {
32+
fn borrow(&self) -> &[u8] {
33+
&self.0[..]
34+
}
35+
}
36+
37+
impl_fmt_traits! {
38+
impl fmt_traits for PaymentHash {
39+
const LENGTH: usize = 32;
40+
}
41+
}
42+
43+
/// The payment preimage is the "secret key" which is used to claim the funds of an HTLC on-chain
44+
/// or in a lightning channel.
45+
///
46+
/// This is not exported to bindings users as we just use [u8; 32] directly
47+
#[derive(Hash, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)]
48+
pub struct PaymentPreimage(pub [u8; 32]);
49+
50+
impl Borrow<[u8]> for PaymentPreimage {
51+
fn borrow(&self) -> &[u8] {
52+
&self.0[..]
53+
}
54+
}
55+
56+
impl_fmt_traits! {
57+
impl fmt_traits for PaymentPreimage {
58+
const LENGTH: usize = 32;
59+
}
60+
}
61+
62+
/// Converts a `PaymentPreimage` into a `PaymentHash` by hashing the preimage with SHA256.
63+
impl From<PaymentPreimage> for PaymentHash {
64+
fn from(value: PaymentPreimage) -> Self {
65+
PaymentHash(Sha256::hash(&value.0).to_byte_array())
66+
}
67+
}
68+
69+
/// The payment secret is used to authenticate the sender of an HTLC to the recipient and tie
70+
/// multi-part HTLCs together into a single payment.
71+
///
72+
/// This is not exported to bindings users as we just use [u8; 32] directly
73+
#[derive(Hash, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)]
74+
pub struct PaymentSecret(pub [u8; 32]);
75+
76+
impl Borrow<[u8]> for PaymentSecret {
77+
fn borrow(&self) -> &[u8] {
78+
&self.0[..]
79+
}
80+
}
81+
82+
impl_fmt_traits! {
83+
impl fmt_traits for PaymentSecret {
84+
const LENGTH: usize = 32;
85+
}
86+
}
87+
88+
use bech32::{Base32Len, FromBase32, ToBase32, WriteBase32, u5};
89+
90+
impl FromBase32 for PaymentSecret {
91+
type Err = bech32::Error;
92+
93+
fn from_base32(field_data: &[u5]) -> Result<PaymentSecret, bech32::Error> {
94+
if field_data.len() != 52 {
95+
return Err(bech32::Error::InvalidLength)
96+
} else {
97+
let data_bytes = Vec::<u8>::from_base32(field_data)?;
98+
let mut payment_secret = [0; 32];
99+
payment_secret.copy_from_slice(&data_bytes);
100+
Ok(PaymentSecret(payment_secret))
101+
}
102+
}
103+
}
104+
105+
impl ToBase32 for PaymentSecret {
106+
fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
107+
(&self.0[..]).write_base32(writer)
108+
}
109+
}
110+
111+
impl Base32Len for PaymentSecret {
112+
fn base32_len(&self) -> usize {
113+
52
114+
}
115+
}

lightning/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ grind_signatures = []
4040
default = ["std", "grind_signatures"]
4141

4242
[dependencies]
43+
lightning-types = { version = "0.1", path = "../lightning-types", default-features = false }
44+
4345
bech32 = { version = "0.9.1", default-features = false }
4446
bitcoin = { version = "0.31.2", default-features = false, features = ["secp-recovery"] }
4547

lightning/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ compile_error!("Tests will always fail with cfg=fuzzing");
6161

6262
#[macro_use]
6363
extern crate alloc;
64+
65+
extern crate lightning_types;
66+
6467
pub extern crate bitcoin;
6568
#[cfg(any(test, feature = "std"))]
6669
extern crate core;

lightning/src/ln/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ pub mod features;
2525
pub mod script;
2626
pub mod types;
2727

28-
pub use types::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
28+
pub use lightning_types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
2929

3030
#[cfg(fuzzing)]
3131
pub mod peer_channel_encryptor;

0 commit comments

Comments
 (0)