Merge pull request #1068 from TheBlueMatt/2021-09-ser-cleanup
[rust-lightning] / lightning / src / ln / onion_utils.rs
index 4128d09905f0a2ee5379c95f1b5f730b83656fc5..ee3ed96b5ef0efdcaaeda40a32f2e71653948ac0 100644 (file)
@@ -1,11 +1,21 @@
-use ln::channelmanager::{PaymentHash, PaymentSecret, HTLCSource};
+// This file is Copyright its original authors, visible in version control
+// history.
+//
+// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
+// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
+// You may not use this file except in accordance with one or both of these
+// licenses.
+
+use ln::{PaymentHash, PaymentPreimage, PaymentSecret};
+use ln::channelmanager::HTLCSource;
 use ln::msgs;
-use ln::router::RouteHop;
-use util::byte_utils;
+use routing::network_graph::NetworkUpdate;
+use routing::router::RouteHop;
 use util::chacha20::ChaCha20;
 use util::errors::{self, APIError};
 use util::ser::{Readable, Writeable, LengthCalculatingWriter};
-use util::logger::{Logger, LogHolder};
+use util::logger::Logger;
 
 use bitcoin::hashes::{Hash, HashEngine};
 use bitcoin::hashes::cmp::fixed_time_eq;
@@ -17,8 +27,10 @@ use bitcoin::secp256k1::Secp256k1;
 use bitcoin::secp256k1::ecdh::SharedSecret;
 use bitcoin::secp256k1;
 
-use std::io::Cursor;
-use std::sync::Arc;
+use prelude::*;
+use io::Cursor;
+use core::convert::TryInto;
+use core::ops::Deref;
 
 pub(super) struct OnionKeys {
        #[cfg(test)]
@@ -108,7 +120,7 @@ pub(super) fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T
 }
 
 /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
-pub(super) fn build_onion_payloads(path: &Vec<RouteHop>, total_msat: u64, payment_secret_option: &Option<PaymentSecret>, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
+pub(super) fn build_onion_payloads(path: &Vec<RouteHop>, total_msat: u64, payment_secret_option: &Option<PaymentSecret>, starting_htlc_offset: u32, keysend_preimage: &Option<PaymentPreimage>) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
        let mut cur_value_msat = 0u64;
        let mut cur_cltv = starting_htlc_offset;
        let mut last_short_channel_id = 0;
@@ -130,6 +142,7 @@ pub(super) fn build_onion_payloads(path: &Vec<RouteHop>, total_msat: u64, paymen
                                                                total_msat,
                                                        })
                                                } else { None },
+                                               keysend_preimage: *keysend_preimage,
                                        }
                                } else {
                                        msgs::OnionHopDataFormat::NonFinalNode {
@@ -146,11 +159,11 @@ pub(super) fn build_onion_payloads(path: &Vec<RouteHop>, total_msat: u64, paymen
                });
                cur_value_msat += hop.fee_msat;
                if cur_value_msat >= 21000000 * 100000000 * 1000 {
-                       return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
+                       return Err(APIError::RouteError{err: "Channel fees overflowed?"});
                }
                cur_cltv += hop.cltv_expiry_delta as u32;
                if cur_cltv >= 500000000 {
-                       return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
+                       return Err(APIError::RouteError{err: "Channel CLTV overflowed?"});
                }
                last_short_channel_id = hop.short_channel_id;
        }
@@ -297,8 +310,8 @@ pub(super) fn build_failure_packet(shared_secret: &[u8], failure_type: u16, fail
        };
        let mut packet = msgs::DecodedOnionErrorPacket {
                hmac: [0; 32],
-               failuremsg: failuremsg,
-               pad: pad,
+               failuremsg,
+               pad,
        };
 
        let mut hmac = HmacEngine::<Sha256>::new(&um);
@@ -318,8 +331,8 @@ pub(super) fn build_first_hop_failure_packet(shared_secret: &[u8], failure_type:
 /// OutboundRoute).
 /// Returns update, a boolean indicating that the payment itself failed, and the error code.
 #[inline]
-pub(super) fn process_onion_failure<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, logger: &Arc<Logger>, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<msgs::HTLCFailChannelUpdate>, bool, Option<u16>, Option<Vec<u8>>) {
-       if let &HTLCSource::OutboundRoute { ref path, ref session_priv, ref first_hop_htlc_msat } = htlc_source {
+pub(super) fn process_onion_failure<T: secp256k1::Signing, L: Deref>(secp_ctx: &Secp256k1<T>, logger: &L, htlc_source: &HTLCSource, mut packet_decrypted: Vec<u8>) -> (Option<NetworkUpdate>, bool, Option<u16>, Option<Vec<u8>>) where L::Target: Logger {
+       if let &HTLCSource::OutboundRoute { ref path, ref session_priv, ref first_hop_htlc_msat, .. } = htlc_source {
                let mut res = None;
                let mut htlc_msat = *first_hop_htlc_msat;
                let mut error_code_ret = None;
@@ -356,7 +369,7 @@ pub(super) fn process_onion_failure<T: secp256k1::Signing>(secp_ctx: &Secp256k1<
                                                const NODE: u16 = 0x2000;
                                                const UPDATE: u16 = 0x1000;
 
-                                               let error_code = byte_utils::slice_to_be16(&error_code_slice);
+                                               let error_code = u16::from_be_bytes(error_code_slice.try_into().expect("len is 2"));
                                                error_code_ret = Some(error_code);
                                                error_packet_ret = Some(err_packet.failuremsg[2..].to_vec());
 
@@ -370,20 +383,20 @@ pub(super) fn process_onion_failure<T: secp256k1::Signing>(secp_ctx: &Secp256k1<
                                                } && is_from_final_node) // PERM bit observed below even this error is from the intermediate nodes
                                                || error_code == 21; // Special case error 21 as the Route object is bogus, TODO: Maybe fail the node if the CLTV was reasonable?
 
-                                               let mut fail_channel_update = None;
+                                               let mut network_update = None;
 
                                                if error_code & NODE == NODE {
-                                                       fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure { node_id: route_hop.pubkey, is_permanent: error_code & PERM == PERM });
+                                                       network_update = Some(NetworkUpdate::NodeFailure { node_id: route_hop.pubkey, is_permanent: error_code & PERM == PERM });
                                                }
                                                else if error_code & PERM == PERM {
-                                                       fail_channel_update = if payment_failed {None} else {Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
+                                                       network_update = if payment_failed { None } else { Some(NetworkUpdate::ChannelClosed {
                                                                short_channel_id: path[next_route_hop_ix - if next_route_hop_ix == path.len() { 1 } else { 0 }].short_channel_id,
                                                                is_permanent: true,
                                                        })};
                                                }
                                                else if error_code & UPDATE == UPDATE {
                                                        if let Some(update_len_slice) = err_packet.failuremsg.get(debug_field_size+2..debug_field_size+4) {
-                                                               let update_len = byte_utils::slice_to_be16(&update_len_slice) as usize;
+                                                               let update_len = u16::from_be_bytes(update_len_slice.try_into().expect("len is 2")) as usize;
                                                                if let Some(update_slice) = err_packet.failuremsg.get(debug_field_size + 4..debug_field_size + 4 + update_len) {
                                                                        if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) {
                                                                                // if channel_update should NOT have caused the failure:
@@ -400,25 +413,25 @@ pub(super) fn process_onion_failure<T: secp256k1::Signing>(secp_ctx: &Secp256k1<
                                                                                        20 => chan_update.contents.flags & 2 == 0,
                                                                                        _ => false, // unknown error code; take channel_update as valid
                                                                                };
-                                                                               fail_channel_update = if is_chan_update_invalid {
+                                                                               network_update = if is_chan_update_invalid {
                                                                                        // This probably indicates the node which forwarded
                                                                                        // to the node in question corrupted something.
-                                                                                       Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
+                                                                                       Some(NetworkUpdate::ChannelClosed {
                                                                                                short_channel_id: route_hop.short_channel_id,
                                                                                                is_permanent: true,
                                                                                        })
                                                                                } else {
-                                                                                       Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
+                                                                                       Some(NetworkUpdate::ChannelUpdateMessage {
                                                                                                msg: chan_update,
                                                                                        })
                                                                                };
                                                                        }
                                                                }
                                                        }
-                                                       if fail_channel_update.is_none() {
+                                                       if network_update.is_none() {
                                                                // They provided an UPDATE which was obviously bogus, not worth
                                                                // trying to relay through them anymore.
-                                                               fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
+                                                               network_update = Some(NetworkUpdate::NodeFailure {
                                                                        node_id: route_hop.pubkey,
                                                                        is_permanent: true,
                                                                });
@@ -427,7 +440,7 @@ pub(super) fn process_onion_failure<T: secp256k1::Signing>(secp_ctx: &Secp256k1<
                                                        // We can't understand their error messages and they failed to
                                                        // forward...they probably can't understand our forwards so its
                                                        // really not worth trying any further.
-                                                       fail_channel_update = Some(msgs::HTLCFailChannelUpdate::NodeFailure {
+                                                       network_update = Some(NetworkUpdate::NodeFailure {
                                                                node_id: route_hop.pubkey,
                                                                is_permanent: true,
                                                        });
@@ -436,21 +449,19 @@ pub(super) fn process_onion_failure<T: secp256k1::Signing>(secp_ctx: &Secp256k1<
                                                // TODO: Here (and a few other places) we assume that BADONION errors
                                                // are always "sourced" from the node previous to the one which failed
                                                // to decode the onion.
-                                               res = Some((fail_channel_update, !(error_code & PERM == PERM && is_from_final_node)));
+                                               res = Some((network_update, !(error_code & PERM == PERM && is_from_final_node)));
 
                                                let (description, title) = errors::get_onion_error_description(error_code);
                                                if debug_field_size > 0 && err_packet.failuremsg.len() >= 4 + debug_field_size {
-                                                       let log_holder = LogHolder { logger };
-                                                       log_warn!(log_holder, "Onion Error[{}({:#x}) {}({})] {}", title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
+                                                       log_warn!(logger, "Onion Error[from {}: {}({:#x}) {}({})] {}", route_hop.pubkey, title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
                                                }
                                                else {
-                                                       let log_holder = LogHolder { logger };
-                                                       log_warn!(log_holder, "Onion Error[{}({:#x})] {}", title, error_code, description);
+                                                       log_warn!(logger, "Onion Error[from {}: {}({:#x})] {}", route_hop.pubkey, title, error_code, description);
                                                }
                                        } else {
                                                // Useless packet that we can't use but it passed HMAC, so it
                                                // definitely came from the peer in question
-                                               res = Some((Some(msgs::HTLCFailChannelUpdate::NodeFailure {
+                                               res = Some((Some(NetworkUpdate::NodeFailure {
                                                        node_id: route_hop.pubkey,
                                                        is_permanent: true,
                                                }), !is_from_final_node));
@@ -470,9 +481,11 @@ pub(super) fn process_onion_failure<T: secp256k1::Signing>(secp_ctx: &Secp256k1<
 
 #[cfg(test)]
 mod tests {
-       use ln::channelmanager::PaymentHash;
+       use io;
+       use prelude::*;
+       use ln::PaymentHash;
        use ln::features::{ChannelFeatures, NodeFeatures};
-       use ln::router::{Route, RouteHop};
+       use routing::router::{Route, RouteHop};
        use ln::msgs;
        use util::ser::{Writeable, Writer};
 
@@ -637,7 +650,7 @@ mod tests {
                }
        }
        impl Writeable for RawOnionHopData {
-               fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
+               fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
                        writer.write_all(&self.data[..])
                }
        }