Skip to content

Commit 4146fd6

Browse files
author
Antoine Riard
committed
Typify payment_hash and payment_preimage
Fix variable name as payment_hash instead of txid for index of remote_hash_commitment_number in ChannelMonitor reader
1 parent b2f1181 commit 4146fd6

File tree

9 files changed

+163
-121
lines changed

9 files changed

+163
-121
lines changed

fuzz/fuzz_targets/full_stack_target.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,C
1717
use lightning::chain::transaction::OutPoint;
1818
use lightning::chain::keysinterface::{ChannelKeys, KeysInterface};
1919
use lightning::ln::channelmonitor;
20-
use lightning::ln::channelmanager::{ChannelManager, PaymentFailReason};
20+
use lightning::ln::channelmanager::{ChannelManager, PaymentFailReason, PaymentHash, PaymentPreimage};
2121
use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor};
2222
use lightning::ln::router::Router;
2323
use lightning::util::events::{EventsProvider,Event};
@@ -328,7 +328,7 @@ pub fn do_test(data: &[u8], logger: &Arc<Logger>) {
328328
}, our_network_key, Arc::clone(&logger)));
329329

330330
let mut should_forward = false;
331-
let mut payments_received: Vec<[u8; 32]> = Vec::new();
331+
let mut payments_received: Vec<PaymentHash> = Vec::new();
332332
let mut payments_sent = 0;
333333
let mut pending_funding_generation: Vec<([u8; 32], u64, Script)> = Vec::new();
334334
let mut pending_funding_signatures = HashMap::new();
@@ -380,11 +380,11 @@ pub fn do_test(data: &[u8], logger: &Arc<Logger>) {
380380
Ok(route) => route,
381381
Err(_) => return,
382382
};
383-
let mut payment_hash = [0; 32];
384-
payment_hash[0..8].copy_from_slice(&be64_to_array(payments_sent));
383+
let mut payment_hash = PaymentHash([0; 32]);
384+
payment_hash.0[0..8].copy_from_slice(&be64_to_array(payments_sent));
385385
let mut sha = Sha256::new();
386-
sha.input(&payment_hash);
387-
sha.result(&mut payment_hash);
386+
sha.input(&payment_hash.0[..]);
387+
sha.result(&mut payment_hash.0[..]);
388388
payments_sent += 1;
389389
match channelmanager.send_payment(route, payment_hash) {
390390
Ok(_) => {},
@@ -418,11 +418,11 @@ pub fn do_test(data: &[u8], logger: &Arc<Logger>) {
418418
// for the remaining bytes. Thus, if not all remaining bytes are 0s we cannot
419419
// fulfill this HTLC, but if they are, we can just take the first byte and
420420
// place that anywhere in our preimage.
421-
if &payment[1..] != &[0; 31] {
421+
if &payment.0[1..] != &[0; 31] {
422422
channelmanager.fail_htlc_backwards(&payment, PaymentFailReason::PreimageUnknown);
423423
} else {
424-
let mut payment_preimage = [0; 32];
425-
payment_preimage[0] = payment[0];
424+
let mut payment_preimage = PaymentPreimage([0; 32]);
425+
payment_preimage.0[0] = payment.0[0];
426426
channelmanager.claim_funds(payment_preimage);
427427
}
428428
}

src/ln/chan_utils.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ use bitcoin::blockdata::opcodes;
33
use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction};
44
use bitcoin::util::hash::{Hash160,Sha256dHash};
55

6+
use ln::channelmanager::PaymentHash;
7+
68
use secp256k1::key::{PublicKey,SecretKey};
79
use secp256k1::Secp256k1;
810
use secp256k1;
@@ -156,15 +158,15 @@ pub struct HTLCOutputInCommitment {
156158
pub offered: bool,
157159
pub amount_msat: u64,
158160
pub cltv_expiry: u32,
159-
pub payment_hash: [u8; 32],
161+
pub payment_hash: PaymentHash,
160162
pub transaction_output_index: u32,
161163
}
162164

163165
#[inline]
164166
pub fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
165167
let payment_hash160 = {
166168
let mut ripemd = Ripemd160::new();
167-
ripemd.input(&htlc.payment_hash);
169+
ripemd.input(&htlc.payment_hash.0[..]);
168170
let mut res = [0; 20];
169171
ripemd.result(&mut res);
170172
res

src/ln/channel.rs

Lines changed: 45 additions & 45 deletions
Large diffs are not rendered by default.

src/ln/channelmanager.rs

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -63,14 +63,15 @@ use std::time::{Instant,Duration};
6363
mod channel_held_info {
6464
use ln::msgs;
6565
use ln::router::Route;
66+
use ln::channelmanager::PaymentHash;
6667
use secp256k1::key::SecretKey;
6768

6869
/// Stores the info we will need to send when we want to forward an HTLC onwards
6970
#[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
7071
pub struct PendingForwardHTLCInfo {
7172
pub(super) onion_packet: Option<msgs::OnionPacket>,
7273
pub(super) incoming_shared_secret: [u8; 32],
73-
pub(super) payment_hash: [u8; 32],
74+
pub(super) payment_hash: PaymentHash,
7475
pub(super) short_channel_id: u64,
7576
pub(super) amt_to_forward: u64,
7677
pub(super) outgoing_cltv_value: u32,
@@ -133,13 +134,21 @@ mod channel_held_info {
133134
}
134135
pub(crate) use self::channel_held_info::*;
135136

136-
type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, [u8; 32])>);
137+
/// payment_hash type, use to cross-lock hop
138+
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
139+
pub struct PaymentHash(pub [u8;32]);
140+
/// payment_preimage type, use to route payment between hop
141+
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
142+
pub struct PaymentPreimage(pub [u8;32]);
143+
144+
type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
137145

138146
/// Error type returned across the channel_state mutex boundary. When an Err is generated for a
139147
/// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
140148
/// immediately (ie with no further calls on it made). Thus, this step happens inside a
141149
/// channel_state lock. We then return the set of things that need to be done outside the lock in
142150
/// this struct and call handle_error!() on it.
151+
143152
struct MsgHandleErrInternal {
144153
err: msgs::HandleError,
145154
shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
@@ -248,7 +257,7 @@ struct ChannelHolder {
248257
/// Note that while this is held in the same mutex as the channels themselves, no consistency
249258
/// guarantees are made about the channels given here actually existing anymore by the time you
250259
/// go to read them!
251-
claimable_htlcs: HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
260+
claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
252261
/// Messages to send to peers - pushed to in the same lock that they are generated in (except
253262
/// for broadcast messages, where ordering isn't as strict).
254263
pending_msg_events: Vec<events::MessageSendEvent>,
@@ -258,7 +267,7 @@ struct MutChannelHolder<'a> {
258267
short_to_id: &'a mut HashMap<u64, [u8; 32]>,
259268
next_forward: &'a mut Instant,
260269
forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
261-
claimable_htlcs: &'a mut HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
270+
claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
262271
pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
263272
}
264273
impl ChannelHolder {
@@ -831,7 +840,7 @@ impl ChannelManager {
831840
}
832841

833842
const ZERO:[u8; 21*65] = [0; 21*65];
834-
fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &[u8; 32]) -> msgs::OnionPacket {
843+
fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &PaymentHash) -> msgs::OnionPacket {
835844
let mut buf = Vec::with_capacity(21*65);
836845
buf.resize(21*65, 0);
837846

@@ -868,7 +877,7 @@ impl ChannelManager {
868877

869878
let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
870879
hmac.input(&packet_data);
871-
hmac.input(&associated_data[..]);
880+
hmac.input(&associated_data.0[..]);
872881
hmac.raw_result(&mut hmac_res);
873882
}
874883

@@ -990,7 +999,7 @@ impl ChannelManager {
990999

9911000
let mut hmac = Hmac::new(Sha256::new(), &mu);
9921001
hmac.input(&msg.onion_routing_packet.hop_data);
993-
hmac.input(&msg.payment_hash);
1002+
hmac.input(&msg.payment_hash.0[..]);
9941003
if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
9951004
return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
9961005
}
@@ -1188,7 +1197,7 @@ impl ChannelManager {
11881197
///
11891198
/// Raises APIError::RoutError when invalid route or forward parameter
11901199
/// (cltv_delta, fee, node public key) is specified
1191-
pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<(), APIError> {
1200+
pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
11921201
if route.hops.len() < 1 || route.hops.len() > 20 {
11931202
return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
11941203
}
@@ -1482,7 +1491,7 @@ impl ChannelManager {
14821491
}
14831492

14841493
/// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect after a PaymentReceived event.
1485-
pub fn fail_htlc_backwards(&self, payment_hash: &[u8; 32], reason: PaymentFailReason) -> bool {
1494+
pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, reason: PaymentFailReason) -> bool {
14861495
let _ = self.total_consistency_lock.read().unwrap();
14871496

14881497
let mut channel_state = Some(self.channel_state.lock().unwrap());
@@ -1502,7 +1511,7 @@ impl ChannelManager {
15021511
/// to fail and take the channel_state lock for each iteration (as we take ownership and may
15031512
/// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
15041513
/// still-available channels.
1505-
fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &[u8; 32], onion_error: HTLCFailReason) {
1514+
fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
15061515
match source {
15071516
HTLCSource::OutboundRoute { .. } => {
15081517
mem::drop(channel_state_lock);
@@ -1575,11 +1584,11 @@ impl ChannelManager {
15751584
/// should probably kick the net layer to go send messages if this returns true!
15761585
///
15771586
/// May panic if called except in response to a PaymentReceived event.
1578-
pub fn claim_funds(&self, payment_preimage: [u8; 32]) -> bool {
1587+
pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
15791588
let mut sha = Sha256::new();
1580-
sha.input(&payment_preimage);
1581-
let mut payment_hash = [0; 32];
1582-
sha.result(&mut payment_hash);
1589+
sha.input(&payment_preimage.0[..]);
1590+
let mut payment_hash = PaymentHash([0; 32]);
1591+
sha.result(&mut payment_hash.0[..]);
15831592

15841593
let _ = self.total_consistency_lock.read().unwrap();
15851594

@@ -1593,7 +1602,7 @@ impl ChannelManager {
15931602
true
15941603
} else { false }
15951604
}
1596-
fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: [u8; 32]) {
1605+
fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
15971606
match source {
15981607
HTLCSource::OutboundRoute { .. } => {
15991608
mem::drop(channel_state_lock);
@@ -3280,7 +3289,7 @@ mod tests {
32803289
use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
32813290
use chain::keysinterface;
32823291
use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
3283-
use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder};
3292+
use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,OnionKeys,PaymentFailReason,RAACommitmentOrder, PaymentPreimage, PaymentHash};
32843293
use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
32853294
use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
32863295
use ln::router::{Route, RouteHop, Router};
@@ -3443,7 +3452,7 @@ mod tests {
34433452
},
34443453
);
34453454

3446-
let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &[0x42; 32]);
3455+
let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &PaymentHash([0x42; 32]));
34473456
// Just check the final packet encoding, as it includes all the per-hop vectors in it
34483457
// anyway...
34493458
assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
@@ -3924,18 +3933,18 @@ mod tests {
39243933
macro_rules! get_payment_preimage_hash {
39253934
($node: expr) => {
39263935
{
3927-
let payment_preimage = [*$node.network_payment_count.borrow(); 32];
3936+
let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
39283937
*$node.network_payment_count.borrow_mut() += 1;
3929-
let mut payment_hash = [0; 32];
3938+
let mut payment_hash = PaymentHash([0; 32]);
39303939
let mut sha = Sha256::new();
3931-
sha.input(&payment_preimage[..]);
3932-
sha.result(&mut payment_hash);
3940+
sha.input(&payment_preimage.0[..]);
3941+
sha.result(&mut payment_hash.0[..]);
39333942
(payment_preimage, payment_hash)
39343943
}
39353944
}
39363945
}
39373946

3938-
fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
3947+
fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
39393948
let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
39403949

39413950
let mut payment_event = {
@@ -3989,7 +3998,7 @@ mod tests {
39893998
(our_payment_preimage, our_payment_hash)
39903999
}
39914000

3992-
fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: [u8; 32]) {
4001+
fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
39934002
assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
39944003
check_added_monitors!(expected_route.last().unwrap(), 1);
39954004

@@ -4074,13 +4083,13 @@ mod tests {
40744083
}
40754084
}
40764085

4077-
fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: [u8; 32]) {
4086+
fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
40784087
claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
40794088
}
40804089

40814090
const TEST_FINAL_CLTV: u32 = 32;
40824091

4083-
fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
4092+
fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
40844093
let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), None, &Vec::new(), recv_value, TEST_FINAL_CLTV).unwrap();
40854094
assert_eq!(route.hops.len(), expected_route.len());
40864095
for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
@@ -4111,7 +4120,7 @@ mod tests {
41114120
claim_payment(&origin, expected_route, our_payment_preimage);
41124121
}
41134122

4114-
fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: [u8; 32]) {
4123+
fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
41154124
assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, PaymentFailReason::PreimageUnknown));
41164125
check_added_monitors!(expected_route.last().unwrap(), 1);
41174126

@@ -4176,7 +4185,7 @@ mod tests {
41764185
}
41774186
}
41784187

4179-
fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: [u8; 32]) {
4188+
fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
41804189
fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
41814190
}
41824191

0 commit comments

Comments
 (0)