Skip to content

Commit 884e85f

Browse files
Implement route blinding spec test vectors.
1 parent ce20284 commit 884e85f

File tree

3 files changed

+270
-9
lines changed

3 files changed

+270
-9
lines changed

lightning/src/blinded_path/payment.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ enum BlindedPaymentTlvsRef<'a> {
9797
/// Parameters for relaying over a given [`BlindedHop`].
9898
///
9999
/// [`BlindedHop`]: crate::blinded_path::BlindedHop
100-
#[derive(Clone, Debug)]
100+
#[derive(Clone, Debug, PartialEq)]
101101
pub struct PaymentRelay {
102102
/// Number of blocks subtracted from an incoming HTLC's `cltv_expiry` for this [`BlindedHop`].
103103
pub cltv_expiry_delta: u16,
@@ -111,7 +111,7 @@ pub struct PaymentRelay {
111111
/// Constraints for relaying over a given [`BlindedHop`].
112112
///
113113
/// [`BlindedHop`]: crate::blinded_path::BlindedHop
114-
#[derive(Clone, Debug)]
114+
#[derive(Clone, Debug, PartialEq)]
115115
pub struct PaymentConstraints {
116116
/// The maximum total CLTV that is acceptable when relaying a payment over this [`BlindedHop`].
117117
pub max_cltv_expiry: u32,

lightning/src/blinded_path/utils.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ where
108108
}
109109

110110
// Panics if `unblinded_tlvs` length is less than `unblinded_pks` length
111-
pub(super) fn construct_blinded_hops<'a, T, I1, I2>(
111+
pub(crate) fn construct_blinded_hops<'a, T, I1, I2>(
112112
secp_ctx: &Secp256k1<T>, unblinded_pks: I1, mut unblinded_tlvs: I2, session_priv: &SecretKey
113113
) -> Result<Vec<BlindedHop>, secp256k1::Error>
114114
where

lightning/src/ln/blinded_payment_tests.rs

Lines changed: 267 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,24 +7,34 @@
77
// You may not use this file except in accordance with one or both of these
88
// licenses.
99

10-
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
10+
use bech32::u5;
11+
use bitcoin::hashes::hex::FromHex;
12+
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey, schnorr};
13+
use bitcoin::secp256k1::ecdh::SharedSecret;
14+
use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
15+
use crate::blinded_path;
1116
use crate::blinded_path::BlindedPath;
1217
use crate::blinded_path::payment::{ForwardNode, ForwardTlvs, PaymentConstraints, PaymentContext, PaymentRelay, ReceiveTlvs};
1318
use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PaymentFailureReason};
14-
use crate::ln::types::PaymentSecret;
19+
use crate::ln::types::{ChannelId, PaymentHash, PaymentSecret};
1520
use crate::ln::channelmanager;
21+
use crate::ln::channelmanager::HTLCFailureMsg;
1622
use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
17-
use crate::ln::features::BlindedHopFeatures;
23+
use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, NodeFeatures};
1824
use crate::ln::functional_test_utils::*;
1925
use crate::ln::msgs;
20-
use crate::ln::msgs::ChannelMessageHandler;
26+
use crate::ln::msgs::{ChannelMessageHandler, UnsignedGossipMessage};
27+
use crate::ln::onion_payment;
2128
use crate::ln::onion_utils;
2229
use crate::ln::onion_utils::INVALID_ONION_BLINDING;
2330
use crate::ln::outbound_payment::{Retry, IDEMPOTENCY_TIMEOUT_TICKS};
24-
use crate::offers::invoice::BlindedPayInfo;
31+
use crate::offers::invoice::{BlindedPayInfo, UnsignedBolt12Invoice};
32+
use crate::offers::invoice_request::UnsignedInvoiceRequest;
2533
use crate::prelude::*;
26-
use crate::routing::router::{Payee, PaymentParameters, RouteParameters};
34+
use crate::routing::router::{BlindedTail, Path, Payee, PaymentParameters, RouteHop, RouteParameters};
35+
use crate::sign::{KeyMaterial, NodeSigner, Recipient};
2736
use crate::util::config::UserConfig;
37+
use crate::util::ser::WithoutLength;
2838
use crate::util::test_utils;
2939

3040
fn blinded_payment_path(
@@ -1333,3 +1343,254 @@ fn custom_tlvs_to_blinded_path() {
13331343
.with_custom_tlvs(recipient_onion_fields.custom_tlvs.clone())
13341344
);
13351345
}
1346+
1347+
fn secret_from_hex(hex: &str) -> SecretKey {
1348+
SecretKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()).unwrap()
1349+
}
1350+
1351+
fn bytes_from_hex(hex: &str) -> Vec<u8> {
1352+
<Vec<u8>>::from_hex(hex).unwrap()
1353+
}
1354+
1355+
fn pubkey_from_hex(hex: &str) -> PublicKey {
1356+
PublicKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()).unwrap()
1357+
}
1358+
1359+
fn update_add_msg(
1360+
amount_msat: u64, cltv_expiry: u32, blinding_point: Option<PublicKey>,
1361+
onion_routing_packet: msgs::OnionPacket
1362+
) -> msgs::UpdateAddHTLC {
1363+
msgs::UpdateAddHTLC {
1364+
channel_id: ChannelId::from_bytes([0; 32]),
1365+
htlc_id: 0,
1366+
amount_msat,
1367+
cltv_expiry,
1368+
payment_hash: PaymentHash([0; 32]),
1369+
onion_routing_packet,
1370+
skimmed_fee_msat: None,
1371+
blinding_point,
1372+
}
1373+
}
1374+
1375+
#[test]
1376+
fn route_blinding_spec_test_vector() {
1377+
let mut secp_ctx = Secp256k1::new();
1378+
let bob_secret = secret_from_hex("4242424242424242424242424242424242424242424242424242424242424242");
1379+
let bob_node_id = PublicKey::from_secret_key(&secp_ctx, &bob_secret);
1380+
let bob_unblinded_tlvs = bytes_from_hex("011a0000000000000000000000000000000000000000000000000000020800000000000006c10a0800240000009627100c06000b69e505dc0e00fd023103123456");
1381+
let carol_secret = secret_from_hex("4343434343434343434343434343434343434343434343434343434343434343");
1382+
let carol_node_id = PublicKey::from_secret_key(&secp_ctx, &carol_secret);
1383+
let carol_unblinded_tlvs = bytes_from_hex("020800000000000004510821031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f0a0800300000006401f40c06000b69c105dc0e00");
1384+
let dave_secret = secret_from_hex("4444444444444444444444444444444444444444444444444444444444444444");
1385+
let dave_node_id = PublicKey::from_secret_key(&secp_ctx, &dave_secret);
1386+
let dave_unblinded_tlvs = bytes_from_hex("01230000000000000000000000000000000000000000000000000000000000000000000000020800000000000002310a060090000000fa0c06000b699105dc0e00");
1387+
let eve_secret = secret_from_hex("4545454545454545454545454545454545454545454545454545454545454545");
1388+
let eve_node_id = PublicKey::from_secret_key(&secp_ctx, &eve_secret);
1389+
let eve_unblinded_tlvs = bytes_from_hex("011a00000000000000000000000000000000000000000000000000000604deadbeef0c06000b690105dc0e0f020000000000000000000000000000fdffff0206c1");
1390+
1391+
// Eve creates a blinded path to herself through Dave:
1392+
let dave_eve_session_priv = secret_from_hex("0101010101010101010101010101010101010101010101010101010101010101");
1393+
let blinding_override = PublicKey::from_secret_key(&secp_ctx, &dave_eve_session_priv);
1394+
assert_eq!(blinding_override, pubkey_from_hex("031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f"));
1395+
// Can't use the public API here as the encrypted payloads contain unknown TLVs.
1396+
let mut dave_eve_blinded_hops = blinded_path::utils::construct_blinded_hops(
1397+
&secp_ctx, [dave_node_id, eve_node_id].iter(),
1398+
&mut [WithoutLength(&dave_unblinded_tlvs), WithoutLength(&eve_unblinded_tlvs)].iter(),
1399+
&dave_eve_session_priv
1400+
).unwrap();
1401+
1402+
// Concatenate an additional Bob -> Carol blinded path to the Eve -> Dave blinded path.
1403+
let bob_carol_session_priv = secret_from_hex("0202020202020202020202020202020202020202020202020202020202020202");
1404+
let bob_blinding_point = PublicKey::from_secret_key(&secp_ctx, &bob_carol_session_priv);
1405+
let bob_carol_blinded_hops = blinded_path::utils::construct_blinded_hops(
1406+
&secp_ctx, [bob_node_id, carol_node_id].iter(),
1407+
&mut [WithoutLength(&bob_unblinded_tlvs), WithoutLength(&carol_unblinded_tlvs)].iter(),
1408+
&bob_carol_session_priv
1409+
).unwrap();
1410+
1411+
let mut blinded_hops = bob_carol_blinded_hops;
1412+
blinded_hops.append(&mut dave_eve_blinded_hops);
1413+
assert_eq!(
1414+
vec![
1415+
pubkey_from_hex("03da173ad2aee2f701f17e59fbd16cb708906d69838a5f088e8123fb36e89a2c25"),
1416+
pubkey_from_hex("02e466727716f044290abf91a14a6d90e87487da160c2a3cbd0d465d7a78eb83a7"),
1417+
pubkey_from_hex("036861b366f284f0a11738ffbf7eda46241a8977592878fe3175ae1d1e4754eccf"),
1418+
pubkey_from_hex("021982a48086cb8984427d3727fe35a03d396b234f0701f5249daa12e8105c8dae")
1419+
],
1420+
blinded_hops.iter().map(|bh| bh.blinded_node_id).collect::<Vec<PublicKey>>()
1421+
);
1422+
assert_eq!(
1423+
vec![
1424+
bytes_from_hex("cd4100ff9c09ed28102b210ac73aa12d63e90852cebc496c49f57c49982088b49f2e70b99287fdee0aa58aa39913ab405813b999f66783aa2fe637b3cda91ffc0913c30324e2c6ce327e045183e4bffecb"),
1425+
bytes_from_hex("cc0f16524fd7f8bb0b1d8d40ad71709ef140174c76faa574cac401bb8992fef76c4d004aa485dd599ed1cf2715f57ff62da5aaec5d7b10d59b04d8a9d77e472b9b3ecc2179334e411be22fa4c02b467c7e"),
1426+
bytes_from_hex("0fa0a72cff3b64a3d6e1e4903cf8c8b0a17144aeb249dcb86561adee1f679ee8db3e561d9c43815fd4bcebf6f58c546da0cd8a9bf5cebd0d554802f6c0255e28e4a27343f761fe518cd897463187991105"),
1427+
bytes_from_hex("da1a7e5f7881219884beae6ae68971de73bab4c3055d9865b1afb60724a2e4d3f0489ad884f7f3f77149209f0df51efd6b276294a02e3949c7254fbc8b5cab58212d9a78983e1cf86fe218b30c4ca8f6d8")
1428+
],
1429+
blinded_hops.iter().map(|bh| bh.encrypted_payload.clone()).collect::<Vec<Vec<u8>>>()
1430+
);
1431+
1432+
let mut amt_msat = 100_000;
1433+
let session_priv = secret_from_hex("0303030303030303030303030303030303030303030303030303030303030303");
1434+
let path = Path {
1435+
hops: vec![RouteHop {
1436+
pubkey: bob_node_id,
1437+
node_features: NodeFeatures::empty(),
1438+
short_channel_id: 42,
1439+
channel_features: ChannelFeatures::empty(),
1440+
fee_msat: 100,
1441+
cltv_expiry_delta: 42,
1442+
maybe_announced_channel: false,
1443+
}],
1444+
blinded_tail: Some(BlindedTail {
1445+
hops: blinded_hops,
1446+
blinding_point: bob_blinding_point,
1447+
excess_final_cltv_expiry_delta: 0,
1448+
final_value_msat: amt_msat
1449+
}),
1450+
};
1451+
let cur_height = 747_000;
1452+
let (bob_onion, _, _) = onion_utils::create_payment_onion(&secp_ctx, &path, &session_priv, amt_msat, &RecipientOnionFields::spontaneous_empty(), cur_height, &PaymentHash([0; 32]), &None, [0; 32]).unwrap();
1453+
1454+
struct TestEcdhSigner {
1455+
node_secret: SecretKey,
1456+
}
1457+
impl NodeSigner for TestEcdhSigner {
1458+
fn ecdh(
1459+
&self, _recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
1460+
) -> Result<SharedSecret, ()> {
1461+
let mut node_secret = self.node_secret.clone();
1462+
if let Some(tweak) = tweak {
1463+
node_secret = self.node_secret.mul_tweak(tweak).map_err(|_| ())?;
1464+
}
1465+
Ok(SharedSecret::new(other_key, &node_secret))
1466+
}
1467+
fn get_inbound_payment_key_material(&self) -> KeyMaterial { unreachable!() }
1468+
fn get_node_id(&self, _recipient: Recipient) -> Result<PublicKey, ()> { unreachable!() }
1469+
fn sign_invoice(
1470+
&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient,
1471+
) -> Result<RecoverableSignature, ()> { unreachable!() }
1472+
fn sign_bolt12_invoice_request(
1473+
&self, _invoice_request: &UnsignedInvoiceRequest,
1474+
) -> Result<schnorr::Signature, ()> { unreachable!() }
1475+
fn sign_bolt12_invoice(
1476+
&self, _invoice: &UnsignedBolt12Invoice,
1477+
) -> Result<schnorr::Signature, ()> { unreachable!() }
1478+
fn sign_gossip_message(&self, _msg: UnsignedGossipMessage) -> Result<Signature, ()> { unreachable!() }
1479+
}
1480+
let logger = test_utils::TestLogger::with_id("".to_owned());
1481+
1482+
let bob_update_add = update_add_msg(110_000, 747_500, None, bob_onion);
1483+
let bob_node_signer = TestEcdhSigner { node_secret: bob_secret };
1484+
// Can't use the public API here as we need to avoid the CLTV delta checks (test vector uses
1485+
// < MIN_CLTV_EXPIRY_DELTA).
1486+
let (bob_peeled_onion, _, next_packet_details_opt) =
1487+
match onion_payment::decode_incoming_update_add_htlc_onion(
1488+
&bob_update_add, &&bob_node_signer, &&logger, &secp_ctx
1489+
) {
1490+
Ok(res) => res,
1491+
_ => panic!("Unexpected error")
1492+
};
1493+
let (carol_packet_bytes, carol_hmac) = if let onion_utils::Hop::Forward {
1494+
next_hop_data: msgs::InboundOnionPayload::BlindedForward {
1495+
short_channel_id, payment_relay, payment_constraints, features, intro_node_blinding_point, next_blinding_override
1496+
}, next_hop_hmac, new_packet_bytes
1497+
} = bob_peeled_onion {
1498+
assert_eq!(short_channel_id, 1729);
1499+
assert!(next_blinding_override.is_none());
1500+
assert_eq!(intro_node_blinding_point, Some(bob_blinding_point));
1501+
assert_eq!(payment_relay, PaymentRelay { cltv_expiry_delta: 36, fee_proportional_millionths: 150, fee_base_msat: 10_000 });
1502+
assert_eq!(features, BlindedHopFeatures::empty());
1503+
assert_eq!(payment_constraints, PaymentConstraints { max_cltv_expiry: 748_005, htlc_minimum_msat: 1500 });
1504+
(new_packet_bytes, next_hop_hmac)
1505+
} else { panic!() };
1506+
1507+
let carol_packet_details = next_packet_details_opt.unwrap();
1508+
let carol_onion = msgs::OnionPacket {
1509+
version: 0,
1510+
public_key: carol_packet_details.next_packet_pubkey,
1511+
hop_data: carol_packet_bytes,
1512+
hmac: carol_hmac,
1513+
};
1514+
let carol_update_add = update_add_msg(
1515+
carol_packet_details.outgoing_amt_msat, carol_packet_details.outgoing_cltv_value,
1516+
Some(pubkey_from_hex("034e09f450a80c3d252b258aba0a61215bf60dda3b0dc78ffb0736ea1259dfd8a0")),
1517+
carol_onion
1518+
);
1519+
let carol_node_signer = TestEcdhSigner { node_secret: carol_secret };
1520+
let (carol_peeled_onion, _, next_packet_details_opt) =
1521+
match onion_payment::decode_incoming_update_add_htlc_onion(
1522+
&carol_update_add, &&carol_node_signer, &&logger, &secp_ctx
1523+
) {
1524+
Ok(res) => res,
1525+
_ => panic!("Unexpected error")
1526+
};
1527+
let (dave_packet_bytes, dave_hmac) = if let onion_utils::Hop::Forward {
1528+
next_hop_data: msgs::InboundOnionPayload::BlindedForward {
1529+
short_channel_id, payment_relay, payment_constraints, features, intro_node_blinding_point, next_blinding_override
1530+
}, next_hop_hmac, new_packet_bytes
1531+
} = carol_peeled_onion {
1532+
assert_eq!(short_channel_id, 1105);
1533+
assert_eq!(next_blinding_override, Some(pubkey_from_hex("031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f")));
1534+
assert!(intro_node_blinding_point.is_none());
1535+
assert_eq!(payment_relay, PaymentRelay { cltv_expiry_delta: 48, fee_proportional_millionths: 100, fee_base_msat: 500 });
1536+
assert_eq!(features, BlindedHopFeatures::empty());
1537+
assert_eq!(payment_constraints, PaymentConstraints { max_cltv_expiry: 747_969, htlc_minimum_msat: 1500 });
1538+
(new_packet_bytes, next_hop_hmac)
1539+
} else { panic!() };
1540+
1541+
let dave_packet_details = next_packet_details_opt.unwrap();
1542+
let dave_onion = msgs::OnionPacket {
1543+
version: 0,
1544+
public_key: dave_packet_details.next_packet_pubkey,
1545+
hop_data: dave_packet_bytes,
1546+
hmac: dave_hmac,
1547+
};
1548+
let dave_update_add = update_add_msg(
1549+
dave_packet_details.outgoing_amt_msat, dave_packet_details.outgoing_cltv_value,
1550+
Some(pubkey_from_hex("031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f")),
1551+
dave_onion
1552+
);
1553+
let dave_node_signer = TestEcdhSigner { node_secret: dave_secret };
1554+
let (dave_peeled_onion, _, next_packet_details_opt) =
1555+
match onion_payment::decode_incoming_update_add_htlc_onion(
1556+
&dave_update_add, &&dave_node_signer, &&logger, &secp_ctx
1557+
) {
1558+
Ok(res) => res,
1559+
_ => panic!("Unexpected error")
1560+
};
1561+
let (eve_packet_bytes, eve_hmac) = if let onion_utils::Hop::Forward {
1562+
next_hop_data: msgs::InboundOnionPayload::BlindedForward {
1563+
short_channel_id, payment_relay, payment_constraints, features, intro_node_blinding_point, next_blinding_override
1564+
}, next_hop_hmac, new_packet_bytes
1565+
} = dave_peeled_onion {
1566+
assert_eq!(short_channel_id, 561);
1567+
assert!(next_blinding_override.is_none());
1568+
assert!(intro_node_blinding_point.is_none());
1569+
assert_eq!(payment_relay, PaymentRelay { cltv_expiry_delta: 144, fee_proportional_millionths: 250, fee_base_msat: 0 });
1570+
assert_eq!(features, BlindedHopFeatures::empty());
1571+
assert_eq!(payment_constraints, PaymentConstraints { max_cltv_expiry: 747_921, htlc_minimum_msat: 1500 });
1572+
(new_packet_bytes, next_hop_hmac)
1573+
} else { panic!() };
1574+
1575+
let eve_packet_details = next_packet_details_opt.unwrap();
1576+
let eve_onion = msgs::OnionPacket {
1577+
version: 0,
1578+
public_key: eve_packet_details.next_packet_pubkey,
1579+
hop_data: eve_packet_bytes,
1580+
hmac: eve_hmac,
1581+
};
1582+
let eve_update_add = update_add_msg(
1583+
eve_packet_details.outgoing_amt_msat, eve_packet_details.outgoing_cltv_value,
1584+
Some(pubkey_from_hex("03e09038ee76e50f444b19abf0a555e8697e035f62937168b80adf0931b31ce52a")),
1585+
eve_onion
1586+
);
1587+
let eve_node_signer = TestEcdhSigner { node_secret: eve_secret };
1588+
// We can't decode the final payload because it contains a path_id and is missing some LDK
1589+
// specific fields.
1590+
match onion_payment::decode_incoming_update_add_htlc_onion(
1591+
&eve_update_add, &&eve_node_signer, &&logger, &secp_ctx
1592+
) {
1593+
Err(HTLCFailureMsg::Malformed(msg)) => assert_eq!(msg.failure_code, INVALID_ONION_BLINDING),
1594+
_ => panic!("Unexpected error")
1595+
}
1596+
}

0 commit comments

Comments
 (0)