1 use bitcoin::blockdata::block::BlockHeader;
2 use bitcoin::blockdata::transaction::Transaction;
3 use bitcoin::blockdata::constants::genesis_block;
4 use bitcoin::network::constants::Network;
5 use bitcoin::network::serialize::BitcoinHash;
6 use bitcoin::util::hash::Sha256dHash;
8 use secp256k1::key::{SecretKey,PublicKey};
9 use secp256k1::{Secp256k1,Message};
10 use secp256k1::ecdh::SharedSecret;
13 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
14 use chain::transaction::OutPoint;
15 use ln::channel::{Channel, ChannelKeys};
16 use ln::channelmonitor::ManyChannelMonitor;
17 use ln::router::{Route,RouteHop};
19 use ln::msgs::{HandleError,ChannelMessageHandler,MsgEncodable,MsgDecodable};
20 use util::{byte_utils, events, internal_traits, rng};
21 use util::sha2::Sha256;
22 use util::chacha20poly1305rfc::ChaCha20;
23 use util::logger::Logger;
24 use util::errors::APIError;
27 use crypto::mac::{Mac,MacResult};
28 use crypto::hmac::Hmac;
29 use crypto::digest::Digest;
30 use crypto::symmetriccipher::SynchronousStreamCipher;
33 use std::collections::HashMap;
34 use std::collections::hash_map;
35 use std::sync::{Mutex,MutexGuard,Arc};
36 use std::sync::atomic::{AtomicUsize, Ordering};
37 use std::time::{Instant,Duration};
39 /// We hold various information about HTLC relay in the HTLC objects in Channel itself:
41 /// Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
42 /// forward the HTLC with information it will give back to us when it does so, or if it should Fail
43 /// the HTLC with the relevant message for the Channel to handle giving to the remote peer.
45 /// When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
46 /// which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
47 /// filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
48 /// the HTLC backwards along the relevant path).
49 /// Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
50 /// our payment, which we can use to decode errors or inform the user that the payment was sent.
51 mod channel_held_info {
53 use ln::router::Route;
54 use secp256k1::key::SecretKey;
55 use secp256k1::ecdh::SharedSecret;
57 /// Stores the info we will need to send when we want to forward an HTLC onwards
58 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
59 pub struct PendingForwardHTLCInfo {
60 pub(super) onion_packet: Option<msgs::OnionPacket>,
61 pub(super) incoming_shared_secret: SharedSecret,
62 pub(super) payment_hash: [u8; 32],
63 pub(super) short_channel_id: u64,
64 pub(super) amt_to_forward: u64,
65 pub(super) outgoing_cltv_value: u32,
68 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
69 pub enum HTLCFailureMsg {
70 Relay(msgs::UpdateFailHTLC),
71 Malformed(msgs::UpdateFailMalformedHTLC),
74 /// Stores whether we can't forward an HTLC or relevant forwarding info
75 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
76 pub enum PendingHTLCStatus {
77 Forward(PendingForwardHTLCInfo),
81 #[cfg(feature = "fuzztarget")]
82 impl PendingHTLCStatus {
83 pub fn dummy() -> Self {
84 let secp_ctx = ::secp256k1::Secp256k1::signing_only();
85 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
87 incoming_shared_secret: SharedSecret::new(&secp_ctx,
88 &::secp256k1::key::PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &[1; 32]).unwrap()),
89 &SecretKey::from_slice(&secp_ctx, &[1; 32]).unwrap()),
90 payment_hash: [0; 32],
93 outgoing_cltv_value: 0,
98 /// Tracks the inbound corresponding to an outbound HTLC
100 pub struct HTLCPreviousHopData {
101 pub(super) short_channel_id: u64,
102 pub(super) htlc_id: u64,
103 pub(super) incoming_packet_shared_secret: SharedSecret,
106 /// Tracks the inbound corresponding to an outbound HTLC
108 pub enum HTLCSource {
109 PreviousHopData(HTLCPreviousHopData),
112 session_priv: SecretKey,
115 #[cfg(any(test, feature = "fuzztarget"))]
117 pub fn dummy() -> Self {
118 HTLCSource::OutboundRoute {
119 route: Route { hops: Vec::new() },
120 session_priv: SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[1; 32]).unwrap(),
125 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
126 pub enum HTLCFailReason {
128 err: msgs::OnionErrorPacket,
136 #[cfg(feature = "fuzztarget")]
137 impl HTLCFailReason {
138 pub fn dummy() -> Self {
139 HTLCFailReason::Reason {
140 failure_code: 0, data: Vec::new(),
145 #[cfg(feature = "fuzztarget")]
146 pub use self::channel_held_info::*;
147 #[cfg(not(feature = "fuzztarget"))]
148 pub(crate) use self::channel_held_info::*;
150 struct MsgHandleErrInternal {
151 err: msgs::HandleError,
152 needs_channel_force_close: bool,
154 impl MsgHandleErrInternal {
156 fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
160 action: Some(msgs::ErrorAction::SendErrorMessage {
161 msg: msgs::ErrorMessage {
163 data: err.to_string()
167 needs_channel_force_close: false,
171 fn send_err_msg_close_chan(err: &'static str, channel_id: [u8; 32]) -> Self {
175 action: Some(msgs::ErrorAction::SendErrorMessage {
176 msg: msgs::ErrorMessage {
178 data: err.to_string()
182 needs_channel_force_close: true,
186 fn from_maybe_close(err: msgs::HandleError) -> Self {
187 Self { err, needs_channel_force_close: true }
190 fn from_no_close(err: msgs::HandleError) -> Self {
191 Self { err, needs_channel_force_close: false }
195 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
196 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
197 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
198 /// probably increase this significantly.
199 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
201 struct HTLCForwardInfo {
202 prev_short_channel_id: u64,
204 forward_info: PendingForwardHTLCInfo,
207 struct ChannelHolder {
208 by_id: HashMap<[u8; 32], Channel>,
209 short_to_id: HashMap<u64, [u8; 32]>,
210 next_forward: Instant,
211 /// short channel id -> forward infos. Key of 0 means payments received
212 /// Note that while this is held in the same mutex as the channels themselves, no consistency
213 /// guarantees are made about there existing a channel with the short id here, nor the short
214 /// ids in the PendingForwardHTLCInfo!
215 forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
216 /// Note that while this is held in the same mutex as the channels themselves, no consistency
217 /// guarantees are made about the channels given here actually existing anymore by the time you
219 claimable_htlcs: HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
221 struct MutChannelHolder<'a> {
222 by_id: &'a mut HashMap<[u8; 32], Channel>,
223 short_to_id: &'a mut HashMap<u64, [u8; 32]>,
224 next_forward: &'a mut Instant,
225 forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
226 claimable_htlcs: &'a mut HashMap<[u8; 32], Vec<HTLCPreviousHopData>>,
229 fn borrow_parts(&mut self) -> MutChannelHolder {
231 by_id: &mut self.by_id,
232 short_to_id: &mut self.short_to_id,
233 next_forward: &mut self.next_forward,
234 forward_htlcs: &mut self.forward_htlcs,
235 claimable_htlcs: &mut self.claimable_htlcs,
240 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
241 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
243 /// Manager which keeps track of a number of channels and sends messages to the appropriate
244 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
245 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
246 /// to individual Channels.
247 pub struct ChannelManager {
248 genesis_hash: Sha256dHash,
249 fee_estimator: Arc<FeeEstimator>,
250 monitor: Arc<ManyChannelMonitor>,
251 chain_monitor: Arc<ChainWatchInterface>,
252 tx_broadcaster: Arc<BroadcasterInterface>,
254 announce_channels_publicly: bool,
255 fee_proportional_millionths: u32,
256 latest_block_height: AtomicUsize,
257 secp_ctx: Secp256k1<secp256k1::All>,
259 channel_state: Mutex<ChannelHolder>,
260 our_network_key: SecretKey,
262 pending_events: Mutex<Vec<events::Event>>,
267 const CLTV_EXPIRY_DELTA: u16 = 6 * 24 * 2; //TODO?
269 macro_rules! secp_call {
270 ( $res: expr, $err: expr ) => {
273 Err(_) => return Err($err),
280 shared_secret: SharedSecret,
282 blinding_factor: [u8; 32],
283 ephemeral_pubkey: PublicKey,
288 pub struct ChannelDetails {
289 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
290 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
291 /// Note that this means this value is *not* persistent - it can change once during the
292 /// lifetime of the channel.
293 pub channel_id: [u8; 32],
294 /// The position of the funding transaction in the chain. None if the funding transaction has
295 /// not yet been confirmed and the channel fully opened.
296 pub short_channel_id: Option<u64>,
297 pub remote_network_id: PublicKey,
298 pub channel_value_satoshis: u64,
299 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
303 impl ChannelManager {
304 /// Constructs a new ChannelManager to hold several channels and route between them. This is
305 /// the main "logic hub" for all channel-related actions, and implements ChannelMessageHandler.
306 /// fee_proportional_millionths is an optional fee to charge any payments routed through us.
307 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
308 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
309 pub fn new(our_network_key: SecretKey, fee_proportional_millionths: u32, announce_channels_publicly: bool, network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>) -> Result<Arc<ChannelManager>, secp256k1::Error> {
310 let secp_ctx = Secp256k1::new();
312 let res = Arc::new(ChannelManager {
313 genesis_hash: genesis_block(network).header.bitcoin_hash(),
314 fee_estimator: feeest.clone(),
315 monitor: monitor.clone(),
319 announce_channels_publicly,
320 fee_proportional_millionths,
321 latest_block_height: AtomicUsize::new(0), //TODO: Get an init value (generally need to replay recent chain on chain_monitor registration)
324 channel_state: Mutex::new(ChannelHolder{
325 by_id: HashMap::new(),
326 short_to_id: HashMap::new(),
327 next_forward: Instant::now(),
328 forward_htlcs: HashMap::new(),
329 claimable_htlcs: HashMap::new(),
333 pending_events: Mutex::new(Vec::new()),
337 let weak_res = Arc::downgrade(&res);
338 res.chain_monitor.register_listener(weak_res);
342 /// Creates a new outbound channel to the given remote node and with the given value.
343 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
344 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
345 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
346 /// may wish to avoid using 0 for user_id here.
347 /// If successful, will generate a SendOpenChannel event, so you should probably poll
348 /// PeerManager::process_events afterwards.
349 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat being greater than channel_value_satoshis * 1k
350 pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
351 let chan_keys = if cfg!(feature = "fuzztarget") {
353 funding_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
354 revocation_base_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
355 payment_base_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
356 delayed_payment_base_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
357 htlc_base_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
358 channel_close_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
359 channel_monitor_claim_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap(),
360 commitment_seed: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
363 let mut key_seed = [0u8; 32];
364 rng::fill_bytes(&mut key_seed);
365 match ChannelKeys::new_from_seed(&key_seed) {
367 Err(_) => panic!("RNG is busted!")
371 let channel = Channel::new_outbound(&*self.fee_estimator, chan_keys, their_network_key, channel_value_satoshis, push_msat, self.announce_channels_publicly, user_id, Arc::clone(&self.logger))?;
372 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator)?;
373 let mut channel_state = self.channel_state.lock().unwrap();
374 match channel_state.by_id.insert(channel.channel_id(), channel) {
375 Some(_) => panic!("RNG is bad???"),
379 let mut events = self.pending_events.lock().unwrap();
380 events.push(events::Event::SendOpenChannel {
381 node_id: their_network_key,
387 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
388 /// more information.
389 pub fn list_channels(&self) -> Vec<ChannelDetails> {
390 let channel_state = self.channel_state.lock().unwrap();
391 let mut res = Vec::with_capacity(channel_state.by_id.len());
392 for (channel_id, channel) in channel_state.by_id.iter() {
393 res.push(ChannelDetails {
394 channel_id: (*channel_id).clone(),
395 short_channel_id: channel.get_short_channel_id(),
396 remote_network_id: channel.get_their_node_id(),
397 channel_value_satoshis: channel.get_value_satoshis(),
398 user_id: channel.get_user_id(),
404 /// Gets the list of usable channels, in random order. Useful as an argument to
405 /// Router::get_route to ensure non-announced channels are used.
406 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
407 let channel_state = self.channel_state.lock().unwrap();
408 let mut res = Vec::with_capacity(channel_state.by_id.len());
409 for (channel_id, channel) in channel_state.by_id.iter() {
410 if channel.is_usable() {
411 res.push(ChannelDetails {
412 channel_id: (*channel_id).clone(),
413 short_channel_id: channel.get_short_channel_id(),
414 remote_network_id: channel.get_their_node_id(),
415 channel_value_satoshis: channel.get_value_satoshis(),
416 user_id: channel.get_user_id(),
423 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
424 /// will be accepted on the given channel, and after additional timeout/the closing of all
425 /// pending HTLCs, the channel will be closed on chain.
426 /// May generate a SendShutdown event on success, which should be relayed.
427 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), HandleError> {
428 let (mut res, node_id, chan_option) = {
429 let mut channel_state_lock = self.channel_state.lock().unwrap();
430 let channel_state = channel_state_lock.borrow_parts();
431 match channel_state.by_id.entry(channel_id.clone()) {
432 hash_map::Entry::Occupied(mut chan_entry) => {
433 let res = chan_entry.get_mut().get_shutdown()?;
434 if chan_entry.get().is_shutdown() {
435 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
436 channel_state.short_to_id.remove(&short_id);
438 (res, chan_entry.get().get_their_node_id(), Some(chan_entry.remove_entry().1))
439 } else { (res, chan_entry.get().get_their_node_id(), None) }
441 hash_map::Entry::Vacant(_) => return Err(HandleError{err: "No such channel", action: None})
444 for htlc_source in res.1.drain(..) {
445 // unknown_next_peer...I dunno who that is anymore....
446 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
448 let chan_update = if let Some(chan) = chan_option {
449 if let Ok(update) = self.get_channel_update(&chan) {
454 let mut events = self.pending_events.lock().unwrap();
455 if let Some(update) = chan_update {
456 events.push(events::Event::BroadcastChannelUpdate {
460 events.push(events::Event::SendShutdown {
469 fn finish_force_close_channel(&self, shutdown_res: (Vec<Transaction>, Vec<(HTLCSource, [u8; 32])>)) {
470 let (local_txn, mut failed_htlcs) = shutdown_res;
471 for htlc_source in failed_htlcs.drain(..) {
472 // unknown_next_peer...I dunno who that is anymore....
473 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
475 for tx in local_txn {
476 self.tx_broadcaster.broadcast_transaction(&tx);
478 //TODO: We need to have a way where outbound HTLC claims can result in us claiming the
479 //now-on-chain HTLC output for ourselves (and, thereafter, passing the HTLC backwards).
480 //TODO: We need to handle monitoring of pending offered HTLCs which just hit the chain and
481 //may be claimed, resulting in us claiming the inbound HTLCs (and back-failing after
482 //timeouts are hit and our claims confirm).
483 //TODO: In any case, we need to make sure we remove any pending htlc tracking (via
484 //fail_backwards or claim_funds) eventually for all HTLCs that were in the channel
487 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
488 /// the chain and rejecting new HTLCs on the given channel.
489 pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
491 let mut channel_state_lock = self.channel_state.lock().unwrap();
492 let channel_state = channel_state_lock.borrow_parts();
493 if let Some(chan) = channel_state.by_id.remove(channel_id) {
494 if let Some(short_id) = chan.get_short_channel_id() {
495 channel_state.short_to_id.remove(&short_id);
502 self.finish_force_close_channel(chan.force_shutdown());
503 let mut events = self.pending_events.lock().unwrap();
504 if let Ok(update) = self.get_channel_update(&chan) {
505 events.push(events::Event::BroadcastChannelUpdate {
511 /// Force close all channels, immediately broadcasting the latest local commitment transaction
512 /// for each to the chain and rejecting new HTLCs on each.
513 pub fn force_close_all_channels(&self) {
514 for chan in self.list_channels() {
515 self.force_close_channel(&chan.channel_id);
520 fn gen_rho_mu_from_shared_secret(shared_secret: &SharedSecret) -> ([u8; 32], [u8; 32]) {
522 let mut hmac = Hmac::new(Sha256::new(), &[0x72, 0x68, 0x6f]); // rho
523 hmac.input(&shared_secret[..]);
524 let mut res = [0; 32];
525 hmac.raw_result(&mut res);
529 let mut hmac = Hmac::new(Sha256::new(), &[0x6d, 0x75]); // mu
530 hmac.input(&shared_secret[..]);
531 let mut res = [0; 32];
532 hmac.raw_result(&mut res);
538 fn gen_um_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
539 let mut hmac = Hmac::new(Sha256::new(), &[0x75, 0x6d]); // um
540 hmac.input(&shared_secret[..]);
541 let mut res = [0; 32];
542 hmac.raw_result(&mut res);
547 fn gen_ammag_from_shared_secret(shared_secret: &SharedSecret) -> [u8; 32] {
548 let mut hmac = Hmac::new(Sha256::new(), &[0x61, 0x6d, 0x6d, 0x61, 0x67]); // ammag
549 hmac.input(&shared_secret[..]);
550 let mut res = [0; 32];
551 hmac.raw_result(&mut res);
555 // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
557 fn construct_onion_keys_callback<T: secp256k1::Signing, FType: FnMut(SharedSecret, [u8; 32], PublicKey, &RouteHop)> (secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey, mut callback: FType) -> Result<(), secp256k1::Error> {
558 let mut blinded_priv = session_priv.clone();
559 let mut blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
561 for hop in route.hops.iter() {
562 let shared_secret = SharedSecret::new(secp_ctx, &hop.pubkey, &blinded_priv);
564 let mut sha = Sha256::new();
565 sha.input(&blinded_pub.serialize()[..]);
566 sha.input(&shared_secret[..]);
567 let mut blinding_factor = [0u8; 32];
568 sha.result(&mut blinding_factor);
570 let ephemeral_pubkey = blinded_pub;
572 blinded_priv.mul_assign(secp_ctx, &SecretKey::from_slice(secp_ctx, &blinding_factor)?)?;
573 blinded_pub = PublicKey::from_secret_key(secp_ctx, &blinded_priv);
575 callback(shared_secret, blinding_factor, ephemeral_pubkey, hop);
581 // can only fail if an intermediary hop has an invalid public key or session_priv is invalid
582 fn construct_onion_keys<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, route: &Route, session_priv: &SecretKey) -> Result<Vec<OnionKeys>, secp256k1::Error> {
583 let mut res = Vec::with_capacity(route.hops.len());
585 Self::construct_onion_keys_callback(secp_ctx, route, session_priv, |shared_secret, _blinding_factor, ephemeral_pubkey, _| {
586 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
592 blinding_factor: _blinding_factor,
602 /// returns the hop data, as well as the first-hop value_msat and CLTV value we should send.
603 fn build_onion_payloads(route: &Route, starting_htlc_offset: u32) -> Result<(Vec<msgs::OnionHopData>, u64, u32), APIError> {
604 let mut cur_value_msat = 0u64;
605 let mut cur_cltv = starting_htlc_offset;
606 let mut last_short_channel_id = 0;
607 let mut res: Vec<msgs::OnionHopData> = Vec::with_capacity(route.hops.len());
608 internal_traits::test_no_dealloc::<msgs::OnionHopData>(None);
609 unsafe { res.set_len(route.hops.len()); }
611 for (idx, hop) in route.hops.iter().enumerate().rev() {
612 // First hop gets special values so that it can check, on receipt, that everything is
613 // exactly as it should be (and the next hop isn't trying to probe to find out if we're
614 // the intended recipient).
615 let value_msat = if cur_value_msat == 0 { hop.fee_msat } else { cur_value_msat };
616 let cltv = if cur_cltv == starting_htlc_offset { hop.cltv_expiry_delta + starting_htlc_offset } else { cur_cltv };
617 res[idx] = msgs::OnionHopData {
619 data: msgs::OnionRealm0HopData {
620 short_channel_id: last_short_channel_id,
621 amt_to_forward: value_msat,
622 outgoing_cltv_value: cltv,
626 cur_value_msat += hop.fee_msat;
627 if cur_value_msat >= 21000000 * 100000000 * 1000 {
628 return Err(APIError::RouteError{err: "Channel fees overflowed?!"});
630 cur_cltv += hop.cltv_expiry_delta as u32;
631 if cur_cltv >= 500000000 {
632 return Err(APIError::RouteError{err: "Channel CLTV overflowed?!"});
634 last_short_channel_id = hop.short_channel_id;
636 Ok((res, cur_value_msat, cur_cltv))
640 fn shift_arr_right(arr: &mut [u8; 20*65]) {
642 ptr::copy(arr[0..].as_ptr(), arr[65..].as_mut_ptr(), 19*65);
650 fn xor_bufs(dst: &mut[u8], src: &[u8]) {
651 assert_eq!(dst.len(), src.len());
653 for i in 0..dst.len() {
658 const ZERO:[u8; 21*65] = [0; 21*65];
659 fn construct_onion_packet(mut payloads: Vec<msgs::OnionHopData>, onion_keys: Vec<OnionKeys>, associated_data: &[u8; 32]) -> msgs::OnionPacket {
660 let mut buf = Vec::with_capacity(21*65);
661 buf.resize(21*65, 0);
664 let iters = payloads.len() - 1;
665 let end_len = iters * 65;
666 let mut res = Vec::with_capacity(end_len);
667 res.resize(end_len, 0);
669 for (i, keys) in onion_keys.iter().enumerate() {
670 if i == payloads.len() - 1 { continue; }
671 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
672 chacha.process(&ChannelManager::ZERO, &mut buf); // We don't have a seek function :(
673 ChannelManager::xor_bufs(&mut res[0..(i + 1)*65], &buf[(20 - i)*65..21*65]);
678 let mut packet_data = [0; 20*65];
679 let mut hmac_res = [0; 32];
681 for (i, (payload, keys)) in payloads.iter_mut().zip(onion_keys.iter()).rev().enumerate() {
682 ChannelManager::shift_arr_right(&mut packet_data);
683 payload.hmac = hmac_res;
684 packet_data[0..65].copy_from_slice(&payload.encode()[..]);
686 let mut chacha = ChaCha20::new(&keys.rho, &[0u8; 8]);
687 chacha.process(&packet_data, &mut buf[0..20*65]);
688 packet_data[..].copy_from_slice(&buf[0..20*65]);
691 packet_data[20*65 - filler.len()..20*65].copy_from_slice(&filler[..]);
694 let mut hmac = Hmac::new(Sha256::new(), &keys.mu);
695 hmac.input(&packet_data);
696 hmac.input(&associated_data[..]);
697 hmac.raw_result(&mut hmac_res);
702 public_key: Ok(onion_keys.first().unwrap().ephemeral_pubkey),
703 hop_data: packet_data,
708 /// Encrypts a failure packet. raw_packet can either be a
709 /// msgs::DecodedOnionErrorPacket.encode() result or a msgs::OnionErrorPacket.data element.
710 fn encrypt_failure_packet(shared_secret: &SharedSecret, raw_packet: &[u8]) -> msgs::OnionErrorPacket {
711 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
713 let mut packet_crypted = Vec::with_capacity(raw_packet.len());
714 packet_crypted.resize(raw_packet.len(), 0);
715 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
716 chacha.process(&raw_packet, &mut packet_crypted[..]);
717 msgs::OnionErrorPacket {
718 data: packet_crypted,
722 fn build_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::DecodedOnionErrorPacket {
723 assert!(failure_data.len() <= 256 - 2);
725 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
728 let mut res = Vec::with_capacity(2 + failure_data.len());
729 res.push(((failure_type >> 8) & 0xff) as u8);
730 res.push(((failure_type >> 0) & 0xff) as u8);
731 res.extend_from_slice(&failure_data[..]);
735 let mut res = Vec::with_capacity(256 - 2 - failure_data.len());
736 res.resize(256 - 2 - failure_data.len(), 0);
739 let mut packet = msgs::DecodedOnionErrorPacket {
741 failuremsg: failuremsg,
745 let mut hmac = Hmac::new(Sha256::new(), &um);
746 hmac.input(&packet.encode()[32..]);
747 hmac.raw_result(&mut packet.hmac);
753 fn build_first_hop_failure_packet(shared_secret: &SharedSecret, failure_type: u16, failure_data: &[u8]) -> msgs::OnionErrorPacket {
754 let failure_packet = ChannelManager::build_failure_packet(shared_secret, failure_type, failure_data);
755 ChannelManager::encrypt_failure_packet(shared_secret, &failure_packet.encode()[..])
758 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
759 macro_rules! get_onion_hash {
762 let mut sha = Sha256::new();
763 sha.input(&msg.onion_routing_packet.hop_data);
764 let mut onion_hash = [0; 32];
765 sha.result(&mut onion_hash);
771 if let Err(_) = msg.onion_routing_packet.public_key {
772 log_info!(self, "Failed to accept/forward incoming HTLC with invalid ephemeral pubkey");
773 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
774 channel_id: msg.channel_id,
775 htlc_id: msg.htlc_id,
776 sha256_of_onion: get_onion_hash!(),
777 failure_code: 0x8000 | 0x4000 | 6,
778 })), self.channel_state.lock().unwrap());
781 let shared_secret = SharedSecret::new(&self.secp_ctx, &msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key);
782 let (rho, mu) = ChannelManager::gen_rho_mu_from_shared_secret(&shared_secret);
784 let mut channel_state = None;
785 macro_rules! return_err {
786 ($msg: expr, $err_code: expr, $data: expr) => {
788 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
789 if channel_state.is_none() {
790 channel_state = Some(self.channel_state.lock().unwrap());
792 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
793 channel_id: msg.channel_id,
794 htlc_id: msg.htlc_id,
795 reason: ChannelManager::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
796 })), channel_state.unwrap());
801 if msg.onion_routing_packet.version != 0 {
802 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
803 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
804 //the hash doesn't really serve any purpuse - in the case of hashing all data, the
805 //receiving node would have to brute force to figure out which version was put in the
806 //packet by the node that send us the message, in the case of hashing the hop_data, the
807 //node knows the HMAC matched, so they already know what is there...
808 return_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4, &get_onion_hash!());
811 let mut hmac = Hmac::new(Sha256::new(), &mu);
812 hmac.input(&msg.onion_routing_packet.hop_data);
813 hmac.input(&msg.payment_hash);
814 if hmac.result() != MacResult::new(&msg.onion_routing_packet.hmac) {
815 return_err!("HMAC Check failed", 0x8000 | 0x4000 | 5, &get_onion_hash!());
818 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
819 let next_hop_data = {
820 let mut decoded = [0; 65];
821 chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
822 match msgs::OnionHopData::decode(&decoded[..]) {
824 let error_code = match err {
825 msgs::DecodeError::UnknownRealmByte => 0x4000 | 1,
826 _ => 0x2000 | 2, // Should never happen
828 return_err!("Unable to decode our hop data", error_code, &[0;0]);
834 //TODO: Check that msg.cltv_expiry is within acceptable bounds!
836 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
838 if next_hop_data.data.amt_to_forward != msg.amount_msat {
839 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
841 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
842 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
845 // Note that we could obviously respond immediately with an update_fulfill_htlc
846 // message, however that would leak that we are the recipient of this payment, so
847 // instead we stay symmetric with the forwarding case, only responding (after a
848 // delay) once they've send us a commitment_signed!
850 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
852 payment_hash: msg.payment_hash.clone(),
854 incoming_shared_secret: shared_secret.clone(),
855 amt_to_forward: next_hop_data.data.amt_to_forward,
856 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
859 let mut new_packet_data = [0; 20*65];
860 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
861 chacha.process(&ChannelManager::ZERO[0..65], &mut new_packet_data[19*65..]);
863 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
865 let blinding_factor = {
866 let mut sha = Sha256::new();
867 sha.input(&new_pubkey.serialize()[..]);
868 sha.input(&shared_secret[..]);
869 let mut res = [0u8; 32];
870 sha.result(&mut res);
871 match SecretKey::from_slice(&self.secp_ctx, &res) {
873 return_err!("Blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
879 if let Err(_) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor) {
880 return_err!("New blinding factor is an invalid private key", 0x8000 | 0x4000 | 6, &get_onion_hash!());
883 let outgoing_packet = msgs::OnionPacket {
885 public_key: Ok(new_pubkey),
886 hop_data: new_packet_data,
887 hmac: next_hop_data.hmac.clone(),
890 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
891 onion_packet: Some(outgoing_packet),
892 payment_hash: msg.payment_hash.clone(),
893 short_channel_id: next_hop_data.data.short_channel_id,
894 incoming_shared_secret: shared_secret.clone(),
895 amt_to_forward: next_hop_data.data.amt_to_forward,
896 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
900 channel_state = Some(self.channel_state.lock().unwrap());
901 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
902 if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
903 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
904 let forwarding_id = match id_option {
906 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
908 Some(id) => id.clone(),
910 if let Some((err, code, chan_update)) = {
911 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
913 Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, self.get_channel_update(chan).unwrap()))
915 let fee = amt_to_forward.checked_mul(self.fee_proportional_millionths as u64).and_then(|prop_fee| { (prop_fee / 1000000).checked_add(chan.get_our_fee_base_msat(&*self.fee_estimator) as u64) });
916 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward {
917 Some(("Prior hop has deviated from specified fees parameters or origin node has obsolete ones", 0x1000 | 12, self.get_channel_update(chan).unwrap()))
919 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 {
920 Some(("Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta", 0x1000 | 13, self.get_channel_update(chan).unwrap()))
927 return_err!(err, code, &chan_update.encode_with_len()[..]);
932 (pending_forward_info, channel_state.unwrap())
935 /// only fails if the channel does not yet have an assigned short_id
936 fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
937 let short_channel_id = match chan.get_short_channel_id() {
938 None => return Err(HandleError{err: "Channel not yet established", action: None}),
942 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
944 let unsigned = msgs::UnsignedChannelUpdate {
945 chain_hash: self.genesis_hash,
946 short_channel_id: short_channel_id,
947 timestamp: chan.get_channel_update_count(),
948 flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
949 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
950 htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
951 fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
952 fee_proportional_millionths: self.fee_proportional_millionths,
953 excess_data: Vec::new(),
956 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
957 let sig = self.secp_ctx.sign(&Message::from_slice(&msg_hash[..]).unwrap(), &self.our_network_key); //TODO Can we unwrap here?
959 Ok(msgs::ChannelUpdate {
965 /// Sends a payment along a given route.
966 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
967 /// fields for more info.
968 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
969 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
970 /// next hop knows the preimage to payment_hash they can claim an additional amount as
971 /// specified in the last hop in the route! Thus, you should probably do your own
972 /// payment_preimage tracking (which you should already be doing as they represent "proof of
973 /// payment") and prevent double-sends yourself.
974 /// See-also docs on Channel::send_htlc_and_commit.
975 /// May generate a SendHTLCs event on success, which should be relayed.
976 /// Raises APIError::RoutError when invalid route or forward parameter
977 /// (cltv_delta, fee, node public key) is specified
978 pub fn send_payment(&self, route: Route, payment_hash: [u8; 32]) -> Result<(), APIError> {
979 if route.hops.len() < 1 || route.hops.len() > 20 {
980 return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
982 let our_node_id = self.get_our_node_id();
983 for (idx, hop) in route.hops.iter().enumerate() {
984 if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
985 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
989 let session_priv = SecretKey::from_slice(&self.secp_ctx, &{
990 let mut session_key = [0; 32];
991 rng::fill_bytes(&mut session_key);
993 }).expect("RNG is bad!");
995 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
997 let onion_keys = secp_call!(ChannelManager::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
998 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
999 let (onion_payloads, htlc_msat, htlc_cltv) = ChannelManager::build_onion_payloads(&route, cur_height)?;
1000 let onion_packet = ChannelManager::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
1002 let (first_hop_node_id, (update_add, commitment_signed, chan_monitor)) = {
1003 let mut channel_state_lock = self.channel_state.lock().unwrap();
1004 let channel_state = channel_state_lock.borrow_parts();
1006 let id = match channel_state.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1007 None => return Err(APIError::RouteError{err: "No channel available with first hop!"}),
1008 Some(id) => id.clone(),
1012 let chan = channel_state.by_id.get_mut(&id).unwrap();
1013 if chan.get_their_node_id() != route.hops.first().unwrap().pubkey {
1014 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1016 if !chan.is_live() {
1017 return Err(APIError::RouteError{err: "Peer for first hop currently disconnected!"});
1019 chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1020 route: route.clone(),
1021 session_priv: session_priv.clone(),
1022 }, onion_packet).map_err(|he| APIError::RouteError{err: he.err})?
1025 let first_hop_node_id = route.hops.first().unwrap().pubkey;
1028 Some(msgs) => (first_hop_node_id, msgs),
1029 None => return Ok(()),
1033 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1037 let mut events = self.pending_events.lock().unwrap();
1038 events.push(events::Event::UpdateHTLCs {
1039 node_id: first_hop_node_id,
1040 updates: msgs::CommitmentUpdate {
1041 update_add_htlcs: vec![update_add],
1042 update_fulfill_htlcs: Vec::new(),
1043 update_fail_htlcs: Vec::new(),
1044 update_fail_malformed_htlcs: Vec::new(),
1051 /// Call this upon creation of a funding transaction for the given channel.
1052 /// Panics if a funding transaction has already been provided for this channel.
1053 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1054 /// be trivially prevented by using unique funding transaction keys per-channel).
1055 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1057 macro_rules! add_pending_event {
1060 let mut pending_events = self.pending_events.lock().unwrap();
1061 pending_events.push($event);
1066 let (chan, msg, chan_monitor) = {
1067 let mut channel_state = self.channel_state.lock().unwrap();
1068 match channel_state.by_id.remove(temporary_channel_id) {
1070 match chan.get_outbound_funding_created(funding_txo) {
1071 Ok(funding_msg) => {
1072 (chan, funding_msg.0, funding_msg.1)
1075 log_error!(self, "Got bad signatures: {}!", e.err);
1076 mem::drop(channel_state);
1077 add_pending_event!(events::Event::HandleError {
1078 node_id: chan.get_their_node_id(),
1087 }; // Release channel lock for install_watch_outpoint call,
1088 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1091 add_pending_event!(events::Event::SendFundingCreated {
1092 node_id: chan.get_their_node_id(),
1096 let mut channel_state = self.channel_state.lock().unwrap();
1097 match channel_state.by_id.entry(chan.channel_id()) {
1098 hash_map::Entry::Occupied(_) => {
1099 panic!("Generated duplicate funding txid?");
1101 hash_map::Entry::Vacant(e) => {
1107 fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1108 if !chan.should_announce() { return None }
1110 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1112 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1114 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1115 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1117 Some(msgs::AnnouncementSignatures {
1118 channel_id: chan.channel_id(),
1119 short_channel_id: chan.get_short_channel_id().unwrap(),
1120 node_signature: our_node_sig,
1121 bitcoin_signature: our_bitcoin_sig,
1125 /// Processes HTLCs which are pending waiting on random forward delay.
1126 /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1127 /// Will likely generate further events.
1128 pub fn process_pending_htlc_forwards(&self) {
1129 let mut new_events = Vec::new();
1130 let mut failed_forwards = Vec::new();
1132 let mut channel_state_lock = self.channel_state.lock().unwrap();
1133 let channel_state = channel_state_lock.borrow_parts();
1135 if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1139 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1140 if short_chan_id != 0 {
1141 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1142 Some(chan_id) => chan_id.clone(),
1144 failed_forwards.reserve(pending_forwards.len());
1145 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1146 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1147 short_channel_id: prev_short_channel_id,
1148 htlc_id: prev_htlc_id,
1149 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1151 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1156 let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1158 let mut add_htlc_msgs = Vec::new();
1159 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1160 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1161 short_channel_id: prev_short_channel_id,
1162 htlc_id: prev_htlc_id,
1163 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1165 match forward_chan.send_htlc(forward_info.amt_to_forward, forward_info.payment_hash, forward_info.outgoing_cltv_value, htlc_source.clone(), forward_info.onion_packet.unwrap()) {
1167 let chan_update = self.get_channel_update(forward_chan).unwrap();
1168 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1173 Some(msg) => { add_htlc_msgs.push(msg); },
1175 // Nothing to do here...we're waiting on a remote
1176 // revoke_and_ack before we can add anymore HTLCs. The Channel
1177 // will automatically handle building the update_add_htlc and
1178 // commitment_signed messages when we can.
1179 // TODO: Do some kind of timer to set the channel as !is_live()
1180 // as we don't really want others relying on us relaying through
1181 // this channel currently :/.
1188 if !add_htlc_msgs.is_empty() {
1189 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1192 if let &Some(msgs::ErrorAction::DisconnectPeer{msg: Some(ref _err_msg)}) = &e.action {
1193 } else if let &Some(msgs::ErrorAction::SendErrorMessage{msg: ref _err_msg}) = &e.action {
1195 panic!("Stated return value requirements in send_commitment() were not met");
1197 //TODO: Handle...this is bad!
1201 new_events.push((Some(monitor), events::Event::UpdateHTLCs {
1202 node_id: forward_chan.get_their_node_id(),
1203 updates: msgs::CommitmentUpdate {
1204 update_add_htlcs: add_htlc_msgs,
1205 update_fulfill_htlcs: Vec::new(),
1206 update_fail_htlcs: Vec::new(),
1207 update_fail_malformed_htlcs: Vec::new(),
1208 commitment_signed: commitment_msg,
1213 for HTLCForwardInfo { prev_short_channel_id, prev_htlc_id, forward_info } in pending_forwards.drain(..) {
1214 let prev_hop_data = HTLCPreviousHopData {
1215 short_channel_id: prev_short_channel_id,
1216 htlc_id: prev_htlc_id,
1217 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1219 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1220 hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1221 hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1223 new_events.push((None, events::Event::PaymentReceived {
1224 payment_hash: forward_info.payment_hash,
1225 amt: forward_info.amt_to_forward,
1232 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1234 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1235 Some(chan_update) => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: chan_update.encode_with_len() }),
1239 if new_events.is_empty() { return }
1241 new_events.retain(|event| {
1242 if let &Some(ref monitor) = &event.0 {
1243 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor.clone()) {
1244 unimplemented!();// but def dont push the event...
1250 let mut events = self.pending_events.lock().unwrap();
1251 events.reserve(new_events.len());
1252 for event in new_events.drain(..) {
1253 events.push(event.1);
1257 /// Indicates that the preimage for payment_hash is unknown after a PaymentReceived event.
1258 pub fn fail_htlc_backwards(&self, payment_hash: &[u8; 32]) -> bool {
1259 let mut channel_state = Some(self.channel_state.lock().unwrap());
1260 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1261 if let Some(mut sources) = removed_source {
1262 for htlc_with_hash in sources.drain(..) {
1263 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1264 self.fail_htlc_backwards_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: Vec::new() });
1270 /// Fails an HTLC backwards to the sender of it to us.
1271 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1272 /// There are several callsites that do stupid things like loop over a list of payment_hashes
1273 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1274 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1275 /// still-available channels.
1276 fn fail_htlc_backwards_internal(&self, mut channel_state: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &[u8; 32], onion_error: HTLCFailReason) {
1278 HTLCSource::OutboundRoute { .. } => {
1279 mem::drop(channel_state);
1281 let mut pending_events = self.pending_events.lock().unwrap();
1282 pending_events.push(events::Event::PaymentFailed {
1283 payment_hash: payment_hash.clone()
1286 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1287 let err_packet = match onion_error {
1288 HTLCFailReason::Reason { failure_code, data } => {
1289 let packet = ChannelManager::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1290 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1292 HTLCFailReason::ErrorPacket { err } => {
1293 ChannelManager::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1297 let (node_id, fail_msgs) = {
1298 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1299 Some(chan_id) => chan_id.clone(),
1303 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1304 match chan.get_update_fail_htlc_and_commit(htlc_id, err_packet) {
1305 Ok(msg) => (chan.get_their_node_id(), msg),
1307 //TODO: Do something with e?
1314 Some((msg, commitment_msg, chan_monitor)) => {
1315 mem::drop(channel_state);
1317 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1318 unimplemented!();// but def dont push the event...
1321 let mut pending_events = self.pending_events.lock().unwrap();
1322 pending_events.push(events::Event::UpdateHTLCs {
1324 updates: msgs::CommitmentUpdate {
1325 update_add_htlcs: Vec::new(),
1326 update_fulfill_htlcs: Vec::new(),
1327 update_fail_htlcs: vec![msg],
1328 update_fail_malformed_htlcs: Vec::new(),
1329 commitment_signed: commitment_msg,
1339 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1340 /// generating message events for the net layer to claim the payment, if possible. Thus, you
1341 /// should probably kick the net layer to go send messages if this returns true!
1342 /// May panic if called except in response to a PaymentReceived event.
1343 pub fn claim_funds(&self, payment_preimage: [u8; 32]) -> bool {
1344 let mut sha = Sha256::new();
1345 sha.input(&payment_preimage);
1346 let mut payment_hash = [0; 32];
1347 sha.result(&mut payment_hash);
1349 let mut channel_state = Some(self.channel_state.lock().unwrap());
1350 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1351 if let Some(mut sources) = removed_source {
1352 for htlc_with_hash in sources.drain(..) {
1353 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1354 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1359 fn claim_funds_internal(&self, mut channel_state: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: [u8; 32]) {
1361 HTLCSource::OutboundRoute { .. } => {
1362 mem::drop(channel_state);
1363 let mut pending_events = self.pending_events.lock().unwrap();
1364 pending_events.push(events::Event::PaymentSent {
1368 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1369 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1370 let (node_id, fulfill_msgs) = {
1371 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1372 Some(chan_id) => chan_id.clone(),
1374 // TODO: There is probably a channel manager somewhere that needs to
1375 // learn the preimage as the channel already hit the chain and that's
1381 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1382 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1383 Ok(msg) => (chan.get_their_node_id(), msg),
1385 // TODO: There is probably a channel manager somewhere that needs to
1386 // learn the preimage as the channel may be about to hit the chain.
1387 //TODO: Do something with e?
1393 mem::drop(channel_state);
1394 if let Some(chan_monitor) = fulfill_msgs.1 {
1395 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1396 unimplemented!();// but def dont push the event...
1400 if let Some((msg, commitment_msg)) = fulfill_msgs.0 {
1401 let mut pending_events = self.pending_events.lock().unwrap();
1402 pending_events.push(events::Event::UpdateHTLCs {
1404 updates: msgs::CommitmentUpdate {
1405 update_add_htlcs: Vec::new(),
1406 update_fulfill_htlcs: vec![msg],
1407 update_fail_htlcs: Vec::new(),
1408 update_fail_malformed_htlcs: Vec::new(),
1409 commitment_signed: commitment_msg,
1417 /// Gets the node_id held by this ChannelManager
1418 pub fn get_our_node_id(&self) -> PublicKey {
1419 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1422 /// Used to restore channels to normal operation after a
1423 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1425 pub fn test_restore_channel_monitor(&self) {
1429 fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, MsgHandleErrInternal> {
1430 if msg.chain_hash != self.genesis_hash {
1431 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1433 let mut channel_state = self.channel_state.lock().unwrap();
1434 if channel_state.by_id.contains_key(&msg.temporary_channel_id) {
1435 return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone()));
1438 let chan_keys = if cfg!(feature = "fuzztarget") {
1440 funding_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]).unwrap(),
1441 revocation_base_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0]).unwrap(),
1442 payment_base_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0]).unwrap(),
1443 delayed_payment_base_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0]).unwrap(),
1444 htlc_base_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0]).unwrap(),
1445 channel_close_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0]).unwrap(),
1446 channel_monitor_claim_key: SecretKey::from_slice(&self.secp_ctx, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0]).unwrap(),
1447 commitment_seed: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1450 let mut key_seed = [0u8; 32];
1451 rng::fill_bytes(&mut key_seed);
1452 match ChannelKeys::new_from_seed(&key_seed) {
1454 Err(_) => panic!("RNG is busted!")
1458 let channel = Channel::new_from_req(&*self.fee_estimator, chan_keys, their_node_id.clone(), msg, 0, false, self.announce_channels_publicly, Arc::clone(&self.logger)).map_err(|e| MsgHandleErrInternal::from_no_close(e))?;
1459 let accept_msg = channel.get_accept_channel();
1460 channel_state.by_id.insert(channel.channel_id(), channel);
1464 fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1465 let (value, output_script, user_id) = {
1466 let mut channel_state = self.channel_state.lock().unwrap();
1467 match channel_state.by_id.get_mut(&msg.temporary_channel_id) {
1469 if chan.get_their_node_id() != *their_node_id {
1470 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1471 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1473 chan.accept_channel(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1474 (chan.get_value_satoshis(), chan.get_funding_redeemscript().to_v0_p2wsh(), chan.get_user_id())
1476 //TODO: same as above
1477 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1480 let mut pending_events = self.pending_events.lock().unwrap();
1481 pending_events.push(events::Event::FundingGenerationReady {
1482 temporary_channel_id: msg.temporary_channel_id,
1483 channel_value_satoshis: value,
1484 output_script: output_script,
1485 user_channel_id: user_id,
1490 fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, MsgHandleErrInternal> {
1491 let (chan, funding_msg, monitor_update) = {
1492 let mut channel_state = self.channel_state.lock().unwrap();
1493 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1494 hash_map::Entry::Occupied(mut chan) => {
1495 if chan.get().get_their_node_id() != *their_node_id {
1496 //TODO: here and below MsgHandleErrInternal, #153 case
1497 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1499 match chan.get_mut().funding_created(msg) {
1500 Ok((funding_msg, monitor_update)) => {
1501 (chan.remove(), funding_msg, monitor_update)
1504 return Err(e).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1508 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1510 }; // Release channel lock for install_watch_outpoint call,
1511 // note that this means if the remote end is misbehaving and sends a message for the same
1512 // channel back-to-back with funding_created, we'll end up thinking they sent a message
1513 // for a bogus channel.
1514 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1517 let mut channel_state = self.channel_state.lock().unwrap();
1518 match channel_state.by_id.entry(funding_msg.channel_id) {
1519 hash_map::Entry::Occupied(_) => {
1520 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1522 hash_map::Entry::Vacant(e) => {
1529 fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1530 let (funding_txo, user_id, monitor) = {
1531 let mut channel_state = self.channel_state.lock().unwrap();
1532 match channel_state.by_id.get_mut(&msg.channel_id) {
1534 if chan.get_their_node_id() != *their_node_id {
1535 //TODO: here and below MsgHandleErrInternal, #153 case
1536 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1538 let chan_monitor = chan.funding_signed(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1539 (chan.get_funding_txo().unwrap(), chan.get_user_id(), chan_monitor)
1541 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1544 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1547 let mut pending_events = self.pending_events.lock().unwrap();
1548 pending_events.push(events::Event::FundingBroadcastSafe {
1549 funding_txo: funding_txo,
1550 user_channel_id: user_id,
1555 fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, MsgHandleErrInternal> {
1556 let mut channel_state = self.channel_state.lock().unwrap();
1557 match channel_state.by_id.get_mut(&msg.channel_id) {
1559 if chan.get_their_node_id() != *their_node_id {
1560 //TODO: here and below MsgHandleErrInternal, #153 case
1561 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1563 chan.funding_locked(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1564 return Ok(self.get_announcement_sigs(chan));
1566 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1570 fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), MsgHandleErrInternal> {
1571 let (mut res, chan_option) = {
1572 let mut channel_state_lock = self.channel_state.lock().unwrap();
1573 let channel_state = channel_state_lock.borrow_parts();
1575 match channel_state.by_id.entry(msg.channel_id.clone()) {
1576 hash_map::Entry::Occupied(mut chan_entry) => {
1577 if chan_entry.get().get_their_node_id() != *their_node_id {
1578 //TODO: here and below MsgHandleErrInternal, #153 case
1579 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1581 let res = chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1582 if chan_entry.get().is_shutdown() {
1583 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1584 channel_state.short_to_id.remove(&short_id);
1586 (res, Some(chan_entry.remove_entry().1))
1587 } else { (res, None) }
1589 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1592 for htlc_source in res.2.drain(..) {
1593 // unknown_next_peer...I dunno who that is anymore....
1594 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
1596 if let Some(chan) = chan_option {
1597 if let Ok(update) = self.get_channel_update(&chan) {
1598 let mut events = self.pending_events.lock().unwrap();
1599 events.push(events::Event::BroadcastChannelUpdate {
1607 fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, MsgHandleErrInternal> {
1608 let (res, chan_option) = {
1609 let mut channel_state_lock = self.channel_state.lock().unwrap();
1610 let channel_state = channel_state_lock.borrow_parts();
1611 match channel_state.by_id.entry(msg.channel_id.clone()) {
1612 hash_map::Entry::Occupied(mut chan_entry) => {
1613 if chan_entry.get().get_their_node_id() != *their_node_id {
1614 //TODO: here and below MsgHandleErrInternal, #153 case
1615 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1617 let res = chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1618 if res.1.is_some() {
1619 // We're done with this channel, we've got a signed closing transaction and
1620 // will send the closing_signed back to the remote peer upon return. This
1621 // also implies there are no pending HTLCs left on the channel, so we can
1622 // fully delete it from tracking (the channel monitor is still around to
1623 // watch for old state broadcasts)!
1624 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1625 channel_state.short_to_id.remove(&short_id);
1627 (res, Some(chan_entry.remove_entry().1))
1628 } else { (res, None) }
1630 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1633 if let Some(broadcast_tx) = res.1 {
1634 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
1636 if let Some(chan) = chan_option {
1637 if let Ok(update) = self.get_channel_update(&chan) {
1638 let mut events = self.pending_events.lock().unwrap();
1639 events.push(events::Event::BroadcastChannelUpdate {
1647 fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
1648 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
1649 //determine the state of the payment based on our response/if we forward anything/the time
1650 //we take to respond. We should take care to avoid allowing such an attack.
1652 //TODO: There exists a further attack where a node may garble the onion data, forward it to
1653 //us repeatedly garbled in different ways, and compare our error messages, which are
1654 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
1655 //but we should prevent it anyway.
1657 let (pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
1658 let channel_state = channel_state_lock.borrow_parts();
1660 match channel_state.by_id.get_mut(&msg.channel_id) {
1662 if chan.get_their_node_id() != *their_node_id {
1663 //TODO: here MsgHandleErrInternal, #153 case
1664 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1666 if !chan.is_usable() {
1667 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Channel not yet available for receiving HTLCs", action: Some(msgs::ErrorAction::IgnoreError)}));
1669 chan.update_add_htlc(&msg, pending_forward_info).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1671 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1675 fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
1676 let mut channel_state = self.channel_state.lock().unwrap();
1677 let htlc_source = match channel_state.by_id.get_mut(&msg.channel_id) {
1679 if chan.get_their_node_id() != *their_node_id {
1680 //TODO: here and below MsgHandleErrInternal, #153 case
1681 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1683 chan.update_fulfill_htlc(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?.clone()
1685 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1687 self.claim_funds_internal(channel_state, htlc_source, msg.payment_preimage.clone());
1691 fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<Option<msgs::HTLCFailChannelUpdate>, MsgHandleErrInternal> {
1692 let mut channel_state = self.channel_state.lock().unwrap();
1693 let htlc_source = match channel_state.by_id.get_mut(&msg.channel_id) {
1695 if chan.get_their_node_id() != *their_node_id {
1696 //TODO: here and below MsgHandleErrInternal, #153 case
1697 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1699 chan.update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1701 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1705 &HTLCSource::OutboundRoute { ref route, ref session_priv, .. } => {
1706 // Handle packed channel/node updates for passing back for the route handler
1707 let mut packet_decrypted = msg.reason.data.clone();
1709 Self::construct_onion_keys_callback(&self.secp_ctx, &route, &session_priv, |shared_secret, _, _, route_hop| {
1710 if res.is_some() { return; }
1712 let ammag = ChannelManager::gen_ammag_from_shared_secret(&shared_secret);
1714 let mut decryption_tmp = Vec::with_capacity(packet_decrypted.len());
1715 decryption_tmp.resize(packet_decrypted.len(), 0);
1716 let mut chacha = ChaCha20::new(&ammag, &[0u8; 8]);
1717 chacha.process(&packet_decrypted, &mut decryption_tmp[..]);
1718 packet_decrypted = decryption_tmp;
1720 if let Ok(err_packet) = msgs::DecodedOnionErrorPacket::decode(&packet_decrypted) {
1721 if err_packet.failuremsg.len() >= 2 {
1722 let um = ChannelManager::gen_um_from_shared_secret(&shared_secret);
1724 let mut hmac = Hmac::new(Sha256::new(), &um);
1725 hmac.input(&err_packet.encode()[32..]);
1726 let mut calc_tag = [0u8; 32];
1727 hmac.raw_result(&mut calc_tag);
1728 if crypto::util::fixed_time_eq(&calc_tag, &err_packet.hmac) {
1729 const UNKNOWN_CHAN: u16 = 0x4000|10;
1730 const TEMP_CHAN_FAILURE: u16 = 0x4000|7;
1731 match byte_utils::slice_to_be16(&err_packet.failuremsg[0..2]) {
1732 TEMP_CHAN_FAILURE => {
1733 if err_packet.failuremsg.len() >= 4 {
1734 let update_len = byte_utils::slice_to_be16(&err_packet.failuremsg[2..4]) as usize;
1735 if err_packet.failuremsg.len() >= 4 + update_len {
1736 if let Ok(chan_update) = msgs::ChannelUpdate::decode(&err_packet.failuremsg[4..4 + update_len]) {
1737 res = Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {
1745 // No such next-hop. We know this came from the
1746 // current node as the HMAC validated.
1747 res = Some(msgs::HTLCFailChannelUpdate::ChannelClosed {
1748 short_channel_id: route_hop.short_channel_id
1751 _ => {}, //TODO: Enumerate all of these!
1763 fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
1764 let mut channel_state = self.channel_state.lock().unwrap();
1765 match channel_state.by_id.get_mut(&msg.channel_id) {
1767 if chan.get_their_node_id() != *their_node_id {
1768 //TODO: here and below MsgHandleErrInternal, #153 case
1769 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1771 chan.update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() }).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1774 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1778 fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>), MsgHandleErrInternal> {
1779 let (revoke_and_ack, commitment_signed, chan_monitor) = {
1780 let mut channel_state = self.channel_state.lock().unwrap();
1781 match channel_state.by_id.get_mut(&msg.channel_id) {
1783 if chan.get_their_node_id() != *their_node_id {
1784 //TODO: here and below MsgHandleErrInternal, #153 case
1785 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1787 chan.commitment_signed(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?
1789 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1792 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1796 Ok((revoke_and_ack, commitment_signed))
1799 fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<Option<msgs::CommitmentUpdate>, MsgHandleErrInternal> {
1800 let ((res, mut pending_forwards, mut pending_failures, chan_monitor), short_channel_id) = {
1801 let mut channel_state = self.channel_state.lock().unwrap();
1802 match channel_state.by_id.get_mut(&msg.channel_id) {
1804 if chan.get_their_node_id() != *their_node_id {
1805 //TODO: here and below MsgHandleErrInternal, #153 case
1806 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1808 (chan.revoke_and_ack(&msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?, chan.get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
1810 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1813 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1816 for failure in pending_failures.drain(..) {
1817 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1820 let mut forward_event = None;
1821 if !pending_forwards.is_empty() {
1822 let mut channel_state = self.channel_state.lock().unwrap();
1823 if channel_state.forward_htlcs.is_empty() {
1824 forward_event = Some(Instant::now() + Duration::from_millis(((rng::rand_f32() * 4.0 + 1.0) * MIN_HTLC_RELAY_HOLDING_CELL_MILLIS as f32) as u64));
1825 channel_state.next_forward = forward_event.unwrap();
1827 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
1828 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
1829 hash_map::Entry::Occupied(mut entry) => {
1830 entry.get_mut().push(HTLCForwardInfo { prev_short_channel_id: short_channel_id, prev_htlc_id, forward_info });
1832 hash_map::Entry::Vacant(entry) => {
1833 entry.insert(vec!(HTLCForwardInfo { prev_short_channel_id: short_channel_id, prev_htlc_id, forward_info }));
1838 match forward_event {
1840 let mut pending_events = self.pending_events.lock().unwrap();
1841 pending_events.push(events::Event::PendingHTLCsForwardable {
1842 time_forwardable: time
1851 fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
1852 let mut channel_state = self.channel_state.lock().unwrap();
1853 match channel_state.by_id.get_mut(&msg.channel_id) {
1855 if chan.get_their_node_id() != *their_node_id {
1856 //TODO: here and below MsgHandleErrInternal, #153 case
1857 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1859 chan.update_fee(&*self.fee_estimator, &msg).map_err(|e| MsgHandleErrInternal::from_maybe_close(e))
1861 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1865 fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
1866 let (chan_announcement, chan_update) = {
1867 let mut channel_state = self.channel_state.lock().unwrap();
1868 match channel_state.by_id.get_mut(&msg.channel_id) {
1870 if chan.get_their_node_id() != *their_node_id {
1871 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1873 if !chan.is_usable() {
1874 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
1877 let our_node_id = self.get_our_node_id();
1878 let (announcement, our_bitcoin_sig) = chan.get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone())
1879 .map_err(|e| MsgHandleErrInternal::from_maybe_close(e))?;
1881 let were_node_one = announcement.node_id_1 == our_node_id;
1882 let msghash = Message::from_slice(&Sha256dHash::from_data(&announcement.encode()[..])[..]).unwrap();
1883 let bad_sig_action = MsgHandleErrInternal::send_err_msg_close_chan("Bad announcement_signatures node_signature", msg.channel_id);
1884 secp_call!(self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }), bad_sig_action);
1885 secp_call!(self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }), bad_sig_action);
1887 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1889 (msgs::ChannelAnnouncement {
1890 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
1891 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
1892 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
1893 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
1894 contents: announcement,
1895 }, self.get_channel_update(chan).unwrap()) // can only fail if we're not in a ready state
1897 None => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1900 let mut pending_events = self.pending_events.lock().unwrap();
1901 pending_events.push(events::Event::BroadcastChannelAnnouncement { msg: chan_announcement, update_msg: chan_update });
1908 impl events::EventsProvider for ChannelManager {
1909 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
1910 let mut pending_events = self.pending_events.lock().unwrap();
1911 let mut ret = Vec::new();
1912 mem::swap(&mut ret, &mut *pending_events);
1917 impl ChainListener for ChannelManager {
1918 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
1919 let mut new_events = Vec::new();
1920 let mut failed_channels = Vec::new();
1922 let mut channel_lock = self.channel_state.lock().unwrap();
1923 let channel_state = channel_lock.borrow_parts();
1924 let short_to_id = channel_state.short_to_id;
1925 channel_state.by_id.retain(|_, channel| {
1926 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
1927 if let Ok(Some(funding_locked)) = chan_res {
1928 let announcement_sigs = self.get_announcement_sigs(channel);
1929 new_events.push(events::Event::SendFundingLocked {
1930 node_id: channel.get_their_node_id(),
1931 msg: funding_locked,
1932 announcement_sigs: announcement_sigs
1934 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
1935 } else if let Err(e) = chan_res {
1936 new_events.push(events::Event::HandleError {
1937 node_id: channel.get_their_node_id(),
1940 if channel.is_shutdown() {
1944 if let Some(funding_txo) = channel.get_funding_txo() {
1945 for tx in txn_matched {
1946 for inp in tx.input.iter() {
1947 if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
1948 if let Some(short_id) = channel.get_short_channel_id() {
1949 short_to_id.remove(&short_id);
1951 // It looks like our counterparty went on-chain. We go ahead and
1952 // broadcast our latest local state as well here, just in case its
1953 // some kind of SPV attack, though we expect these to be dropped.
1954 failed_channels.push(channel.force_shutdown());
1955 if let Ok(update) = self.get_channel_update(&channel) {
1956 new_events.push(events::Event::BroadcastChannelUpdate {
1965 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
1966 if let Some(short_id) = channel.get_short_channel_id() {
1967 short_to_id.remove(&short_id);
1969 failed_channels.push(channel.force_shutdown());
1970 // If would_broadcast_at_height() is true, the channel_monitor will broadcast
1971 // the latest local tx for us, so we should skip that here (it doesn't really
1972 // hurt anything, but does make tests a bit simpler).
1973 failed_channels.last_mut().unwrap().0 = Vec::new();
1974 if let Ok(update) = self.get_channel_update(&channel) {
1975 new_events.push(events::Event::BroadcastChannelUpdate {
1984 for failure in failed_channels.drain(..) {
1985 self.finish_force_close_channel(failure);
1987 let mut pending_events = self.pending_events.lock().unwrap();
1988 for funding_locked in new_events.drain(..) {
1989 pending_events.push(funding_locked);
1991 self.latest_block_height.store(height as usize, Ordering::Release);
1994 /// We force-close the channel without letting our counterparty participate in the shutdown
1995 fn block_disconnected(&self, header: &BlockHeader) {
1996 let mut new_events = Vec::new();
1997 let mut failed_channels = Vec::new();
1999 let mut channel_lock = self.channel_state.lock().unwrap();
2000 let channel_state = channel_lock.borrow_parts();
2001 let short_to_id = channel_state.short_to_id;
2002 channel_state.by_id.retain(|_, v| {
2003 if v.block_disconnected(header) {
2004 if let Some(short_id) = v.get_short_channel_id() {
2005 short_to_id.remove(&short_id);
2007 failed_channels.push(v.force_shutdown());
2008 if let Ok(update) = self.get_channel_update(&v) {
2009 new_events.push(events::Event::BroadcastChannelUpdate {
2019 for failure in failed_channels.drain(..) {
2020 self.finish_force_close_channel(failure);
2022 if !new_events.is_empty() {
2023 let mut pending_events = self.pending_events.lock().unwrap();
2024 for funding_locked in new_events.drain(..) {
2025 pending_events.push(funding_locked);
2028 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2032 macro_rules! handle_error {
2033 ($self: ident, $internal: expr, $their_node_id: expr) => {
2036 Err(MsgHandleErrInternal { err, needs_channel_force_close }) => {
2037 if needs_channel_force_close {
2039 &Some(msgs::ErrorAction::DisconnectPeer { msg: Some(ref msg) }) => {
2040 if msg.channel_id == [0; 32] {
2041 $self.peer_disconnected(&$their_node_id, true);
2043 $self.force_close_channel(&msg.channel_id);
2046 &Some(msgs::ErrorAction::DisconnectPeer { msg: None }) => {},
2047 &Some(msgs::ErrorAction::IgnoreError) => {},
2048 &Some(msgs::ErrorAction::SendErrorMessage { ref msg }) => {
2049 if msg.channel_id == [0; 32] {
2050 $self.peer_disconnected(&$their_node_id, true);
2052 $self.force_close_channel(&msg.channel_id);
2064 impl ChannelMessageHandler for ChannelManager {
2065 //TODO: Handle errors and close channel (or so)
2066 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<msgs::AcceptChannel, HandleError> {
2067 handle_error!(self, self.internal_open_channel(their_node_id, msg), their_node_id)
2070 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2071 handle_error!(self, self.internal_accept_channel(their_node_id, msg), their_node_id)
2074 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<msgs::FundingSigned, HandleError> {
2075 handle_error!(self, self.internal_funding_created(their_node_id, msg), their_node_id)
2078 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2079 handle_error!(self, self.internal_funding_signed(their_node_id, msg), their_node_id)
2082 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<Option<msgs::AnnouncementSignatures>, HandleError> {
2083 handle_error!(self, self.internal_funding_locked(their_node_id, msg), their_node_id)
2086 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(Option<msgs::Shutdown>, Option<msgs::ClosingSigned>), HandleError> {
2087 handle_error!(self, self.internal_shutdown(their_node_id, msg), their_node_id)
2090 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<Option<msgs::ClosingSigned>, HandleError> {
2091 handle_error!(self, self.internal_closing_signed(their_node_id, msg), their_node_id)
2094 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2095 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg), their_node_id)
2098 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2099 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg), their_node_id)
2102 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<Option<msgs::HTLCFailChannelUpdate>, HandleError> {
2103 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg), their_node_id)
2106 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2107 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg), their_node_id)
2110 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(msgs::RevokeAndACK, Option<msgs::CommitmentSigned>), HandleError> {
2111 handle_error!(self, self.internal_commitment_signed(their_node_id, msg), their_node_id)
2114 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<Option<msgs::CommitmentUpdate>, HandleError> {
2115 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg), their_node_id)
2118 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2119 handle_error!(self, self.internal_update_fee(their_node_id, msg), their_node_id)
2122 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2123 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg), their_node_id)
2126 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2127 let mut new_events = Vec::new();
2128 let mut failed_channels = Vec::new();
2130 let mut channel_state_lock = self.channel_state.lock().unwrap();
2131 let channel_state = channel_state_lock.borrow_parts();
2132 let short_to_id = channel_state.short_to_id;
2133 if no_connection_possible {
2134 channel_state.by_id.retain(|_, chan| {
2135 if chan.get_their_node_id() == *their_node_id {
2136 if let Some(short_id) = chan.get_short_channel_id() {
2137 short_to_id.remove(&short_id);
2139 failed_channels.push(chan.force_shutdown());
2140 if let Ok(update) = self.get_channel_update(&chan) {
2141 new_events.push(events::Event::BroadcastChannelUpdate {
2151 for chan in channel_state.by_id {
2152 if chan.1.get_their_node_id() == *their_node_id {
2153 //TODO: mark channel disabled (and maybe announce such after a timeout). Also
2154 //fail and wipe any uncommitted outbound HTLCs as those are considered after
2160 for failure in failed_channels.drain(..) {
2161 self.finish_force_close_channel(failure);
2163 if !new_events.is_empty() {
2164 let mut pending_events = self.pending_events.lock().unwrap();
2165 for event in new_events.drain(..) {
2166 pending_events.push(event);
2171 fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2172 if msg.channel_id == [0; 32] {
2173 for chan in self.list_channels() {
2174 if chan.remote_network_id == *their_node_id {
2175 self.force_close_channel(&chan.channel_id);
2179 self.force_close_channel(&msg.channel_id);
2186 use chain::chaininterface;
2187 use chain::transaction::OutPoint;
2188 use chain::chaininterface::ChainListener;
2189 use ln::channelmanager::{ChannelManager,OnionKeys};
2190 use ln::router::{Route, RouteHop, Router};
2192 use ln::msgs::{MsgEncodable,ChannelMessageHandler,RoutingMessageHandler};
2193 use util::test_utils;
2194 use util::events::{Event, EventsProvider};
2195 use util::logger::Logger;
2196 use util::errors::APIError;
2198 use bitcoin::util::hash::Sha256dHash;
2199 use bitcoin::blockdata::block::{Block, BlockHeader};
2200 use bitcoin::blockdata::transaction::{Transaction, TxOut};
2201 use bitcoin::blockdata::constants::genesis_block;
2202 use bitcoin::network::constants::Network;
2203 use bitcoin::network::serialize::serialize;
2204 use bitcoin::network::serialize::BitcoinHash;
2208 use secp256k1::{Secp256k1, Message};
2209 use secp256k1::key::{PublicKey,SecretKey};
2211 use crypto::sha2::Sha256;
2212 use crypto::digest::Digest;
2214 use rand::{thread_rng,Rng};
2216 use std::cell::RefCell;
2217 use std::collections::HashMap;
2218 use std::default::Default;
2220 use std::sync::{Arc, Mutex};
2221 use std::time::Instant;
2224 fn build_test_onion_keys() -> Vec<OnionKeys> {
2225 // Keys from BOLT 4, used in both test vector tests
2226 let secp_ctx = Secp256k1::new();
2231 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
2232 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
2235 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
2236 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
2239 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
2240 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
2243 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991").unwrap()[..]).unwrap(),
2244 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
2247 pubkey: PublicKey::from_slice(&secp_ctx, &hex::decode("02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145").unwrap()[..]).unwrap(),
2248 short_channel_id: 0, fee_msat: 0, cltv_expiry_delta: 0 // Test vectors are garbage and not generateble from a RouteHop, we fill in payloads manually
2253 let session_priv = SecretKey::from_slice(&secp_ctx, &hex::decode("4141414141414141414141414141414141414141414141414141414141414141").unwrap()[..]).unwrap();
2255 let onion_keys = ChannelManager::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
2256 assert_eq!(onion_keys.len(), route.hops.len());
2261 fn onion_vectors() {
2262 // Packet creation test vectors from BOLT 4
2263 let onion_keys = build_test_onion_keys();
2265 assert_eq!(onion_keys[0].shared_secret[..], hex::decode("53eb63ea8a3fec3b3cd433b85cd62a4b145e1dda09391b348c4e1cd36a03ea66").unwrap()[..]);
2266 assert_eq!(onion_keys[0].blinding_factor[..], hex::decode("2ec2e5da605776054187180343287683aa6a51b4b1c04d6dd49c45d8cffb3c36").unwrap()[..]);
2267 assert_eq!(onion_keys[0].ephemeral_pubkey.serialize()[..], hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]);
2268 assert_eq!(onion_keys[0].rho, hex::decode("ce496ec94def95aadd4bec15cdb41a740c9f2b62347c4917325fcc6fb0453986").unwrap()[..]);
2269 assert_eq!(onion_keys[0].mu, hex::decode("b57061dc6d0a2b9f261ac410c8b26d64ac5506cbba30267a649c28c179400eba").unwrap()[..]);
2271 assert_eq!(onion_keys[1].shared_secret[..], hex::decode("a6519e98832a0b179f62123b3567c106db99ee37bef036e783263602f3488fae").unwrap()[..]);
2272 assert_eq!(onion_keys[1].blinding_factor[..], hex::decode("bf66c28bc22e598cfd574a1931a2bafbca09163df2261e6d0056b2610dab938f").unwrap()[..]);
2273 assert_eq!(onion_keys[1].ephemeral_pubkey.serialize()[..], hex::decode("028f9438bfbf7feac2e108d677e3a82da596be706cc1cf342b75c7b7e22bf4e6e2").unwrap()[..]);
2274 assert_eq!(onion_keys[1].rho, hex::decode("450ffcabc6449094918ebe13d4f03e433d20a3d28a768203337bc40b6e4b2c59").unwrap()[..]);
2275 assert_eq!(onion_keys[1].mu, hex::decode("05ed2b4a3fb023c2ff5dd6ed4b9b6ea7383f5cfe9d59c11d121ec2c81ca2eea9").unwrap()[..]);
2277 assert_eq!(onion_keys[2].shared_secret[..], hex::decode("3a6b412548762f0dbccce5c7ae7bb8147d1caf9b5471c34120b30bc9c04891cc").unwrap()[..]);
2278 assert_eq!(onion_keys[2].blinding_factor[..], hex::decode("a1f2dadd184eb1627049673f18c6325814384facdee5bfd935d9cb031a1698a5").unwrap()[..]);
2279 assert_eq!(onion_keys[2].ephemeral_pubkey.serialize()[..], hex::decode("03bfd8225241ea71cd0843db7709f4c222f62ff2d4516fd38b39914ab6b83e0da0").unwrap()[..]);
2280 assert_eq!(onion_keys[2].rho, hex::decode("11bf5c4f960239cb37833936aa3d02cea82c0f39fd35f566109c41f9eac8deea").unwrap()[..]);
2281 assert_eq!(onion_keys[2].mu, hex::decode("caafe2820fa00eb2eeb78695ae452eba38f5a53ed6d53518c5c6edf76f3f5b78").unwrap()[..]);
2283 assert_eq!(onion_keys[3].shared_secret[..], hex::decode("21e13c2d7cfe7e18836df50872466117a295783ab8aab0e7ecc8c725503ad02d").unwrap()[..]);
2284 assert_eq!(onion_keys[3].blinding_factor[..], hex::decode("7cfe0b699f35525029ae0fa437c69d0f20f7ed4e3916133f9cacbb13c82ff262").unwrap()[..]);
2285 assert_eq!(onion_keys[3].ephemeral_pubkey.serialize()[..], hex::decode("031dde6926381289671300239ea8e57ffaf9bebd05b9a5b95beaf07af05cd43595").unwrap()[..]);
2286 assert_eq!(onion_keys[3].rho, hex::decode("cbe784ab745c13ff5cffc2fbe3e84424aa0fd669b8ead4ee562901a4a4e89e9e").unwrap()[..]);
2287 assert_eq!(onion_keys[3].mu, hex::decode("5052aa1b3d9f0655a0932e50d42f0c9ba0705142c25d225515c45f47c0036ee9").unwrap()[..]);
2289 assert_eq!(onion_keys[4].shared_secret[..], hex::decode("b5756b9b542727dbafc6765a49488b023a725d631af688fc031217e90770c328").unwrap()[..]);
2290 assert_eq!(onion_keys[4].blinding_factor[..], hex::decode("c96e00dddaf57e7edcd4fb5954be5b65b09f17cb6d20651b4e90315be5779205").unwrap()[..]);
2291 assert_eq!(onion_keys[4].ephemeral_pubkey.serialize()[..], hex::decode("03a214ebd875aab6ddfd77f22c5e7311d7f77f17a169e599f157bbcdae8bf071f4").unwrap()[..]);
2292 assert_eq!(onion_keys[4].rho, hex::decode("034e18b8cc718e8af6339106e706c52d8df89e2b1f7e9142d996acf88df8799b").unwrap()[..]);
2293 assert_eq!(onion_keys[4].mu, hex::decode("8e45e5c61c2b24cb6382444db6698727afb063adecd72aada233d4bf273d975a").unwrap()[..]);
2295 // Test vectors below are flat-out wrong: they claim to set outgoing_cltv_value to non-0 :/
2296 let payloads = vec!(
2297 msgs::OnionHopData {
2299 data: msgs::OnionRealm0HopData {
2300 short_channel_id: 0,
2302 outgoing_cltv_value: 0,
2306 msgs::OnionHopData {
2308 data: msgs::OnionRealm0HopData {
2309 short_channel_id: 0x0101010101010101,
2310 amt_to_forward: 0x0100000001,
2311 outgoing_cltv_value: 0,
2315 msgs::OnionHopData {
2317 data: msgs::OnionRealm0HopData {
2318 short_channel_id: 0x0202020202020202,
2319 amt_to_forward: 0x0200000002,
2320 outgoing_cltv_value: 0,
2324 msgs::OnionHopData {
2326 data: msgs::OnionRealm0HopData {
2327 short_channel_id: 0x0303030303030303,
2328 amt_to_forward: 0x0300000003,
2329 outgoing_cltv_value: 0,
2333 msgs::OnionHopData {
2335 data: msgs::OnionRealm0HopData {
2336 short_channel_id: 0x0404040404040404,
2337 amt_to_forward: 0x0400000004,
2338 outgoing_cltv_value: 0,
2344 let packet = ChannelManager::construct_onion_packet(payloads, onion_keys, &[0x42; 32]);
2345 // Just check the final packet encoding, as it includes all the per-hop vectors in it
2347 assert_eq!(packet.encode(), hex::decode("0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a716a996c7845c93d90e4ecbb9bde4ece2f69425c99e4bc820e44485455f135edc0d10f7d61ab590531cf08000179a333a347f8b4072f216400406bdf3bf038659793d4a1fd7b246979e3150a0a4cb052c9ec69acf0f48c3d39cd55675fe717cb7d80ce721caad69320c3a469a202f1e468c67eaf7a7cd8226d0fd32f7b48084dca885d56047694762b67021713ca673929c163ec36e04e40ca8e1c6d17569419d3039d9a1ec866abe044a9ad635778b961fc0776dc832b3a451bd5d35072d2269cf9b040f6b7a7dad84fb114ed413b1426cb96ceaf83825665ed5a1d002c1687f92465b49ed4c7f0218ff8c6c7dd7221d589c65b3b9aaa71a41484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565ae82cd3f4e3b24c76eaa5616c6111343306ab35c1fe5ca4a77c0e314ed7dba39d6f1e0de791719c241a939cc493bea2bae1c1e932679ea94d29084278513c77b899cc98059d06a27d171b0dbdf6bee13ddc4fc17a0c4d2827d488436b57baa167544138ca2e64a11b43ac8a06cd0c2fba2d4d900ed2d9205305e2d7383cc98dacb078133de5f6fb6bed2ef26ba92cea28aafc3b9948dd9ae5559e8bd6920b8cea462aa445ca6a95e0e7ba52961b181c79e73bd581821df2b10173727a810c92b83b5ba4a0403eb710d2ca10689a35bec6c3a708e9e92f7d78ff3c5d9989574b00c6736f84c199256e76e19e78f0c98a9d580b4a658c84fc8f2096c2fbea8f5f8c59d0fdacb3be2802ef802abbecb3aba4acaac69a0e965abd8981e9896b1f6ef9d60f7a164b371af869fd0e48073742825e9434fc54da837e120266d53302954843538ea7c6c3dbfb4ff3b2fdbe244437f2a153ccf7bdb4c92aa08102d4f3cff2ae5ef86fab4653595e6a5837fa2f3e29f27a9cde5966843fb847a4a61f1e76c281fe8bb2b0a181d096100db5a1a5ce7a910238251a43ca556712eaadea167fb4d7d75825e440f3ecd782036d7574df8bceacb397abefc5f5254d2722215c53ff54af8299aaaad642c6d72a14d27882d9bbd539e1cc7a527526ba89b8c037ad09120e98ab042d3e8652b31ae0e478516bfaf88efca9f3676ffe99d2819dcaeb7610a626695f53117665d267d3f7abebd6bbd6733f645c72c389f03855bdf1e4b8075b516569b118233a0f0971d24b83113c0b096f5216a207ca99a7cddc81c130923fe3d91e7508c9ac5f2e914ff5dccab9e558566fa14efb34ac98d878580814b94b73acbfde9072f30b881f7f0fff42d4045d1ace6322d86a97d164aa84d93a60498065cc7c20e636f5862dc81531a88c60305a2e59a985be327a6902e4bed986dbf4a0b50c217af0ea7fdf9ab37f9ea1a1aaa72f54cf40154ea9b269f1a7c09f9f43245109431a175d50e2db0132337baa0ef97eed0fcf20489da36b79a1172faccc2f7ded7c60e00694282d93359c4682135642bc81f433574aa8ef0c97b4ade7ca372c5ffc23c7eddd839bab4e0f14d6df15c9dbeab176bec8b5701cf054eb3072f6dadc98f88819042bf10c407516ee58bce33fbe3b3d86a54255e577db4598e30a135361528c101683a5fcde7e8ba53f3456254be8f45fe3a56120ae96ea3773631fcb3873aa3abd91bcff00bd38bd43697a2e789e00da6077482e7b1b1a677b5afae4c54e6cbdf7377b694eb7d7a5b913476a5be923322d3de06060fd5e819635232a2cf4f0731da13b8546d1d6d4f8d75b9fce6c2341a71b0ea6f780df54bfdb0dd5cd9855179f602f9172307c7268724c3618e6817abd793adc214a0dc0bc616816632f27ea336fb56dfd").unwrap());
2351 fn test_failure_packet_onion() {
2352 // Returning Errors test vectors from BOLT 4
2354 let onion_keys = build_test_onion_keys();
2355 let onion_error = ChannelManager::build_failure_packet(&onion_keys[4].shared_secret, 0x2002, &[0; 0]);
2356 assert_eq!(onion_error.encode(), hex::decode("4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap());
2358 let onion_packet_1 = ChannelManager::encrypt_failure_packet(&onion_keys[4].shared_secret, &onion_error.encode()[..]);
2359 assert_eq!(onion_packet_1.data, hex::decode("a5e6bd0c74cb347f10cce367f949098f2457d14c046fd8a22cb96efb30b0fdcda8cb9168b50f2fd45edd73c1b0c8b33002df376801ff58aaa94000bf8a86f92620f343baef38a580102395ae3abf9128d1047a0736ff9b83d456740ebbb4aeb3aa9737f18fb4afb4aa074fb26c4d702f42968888550a3bded8c05247e045b866baef0499f079fdaeef6538f31d44deafffdfd3afa2fb4ca9082b8f1c465371a9894dd8c243fb4847e004f5256b3e90e2edde4c9fb3082ddfe4d1e734cacd96ef0706bf63c9984e22dc98851bcccd1c3494351feb458c9c6af41c0044bea3c47552b1d992ae542b17a2d0bba1a096c78d169034ecb55b6e3a7263c26017f033031228833c1daefc0dedb8cf7c3e37c9c37ebfe42f3225c326e8bcfd338804c145b16e34e4").unwrap());
2361 let onion_packet_2 = ChannelManager::encrypt_failure_packet(&onion_keys[3].shared_secret, &onion_packet_1.data[..]);
2362 assert_eq!(onion_packet_2.data, hex::decode("c49a1ce81680f78f5f2000cda36268de34a3f0a0662f55b4e837c83a8773c22aa081bab1616a0011585323930fa5b9fae0c85770a2279ff59ec427ad1bbff9001c0cd1497004bd2a0f68b50704cf6d6a4bf3c8b6a0833399a24b3456961ba00736785112594f65b6b2d44d9f5ea4e49b5e1ec2af978cbe31c67114440ac51a62081df0ed46d4a3df295da0b0fe25c0115019f03f15ec86fabb4c852f83449e812f141a9395b3f70b766ebbd4ec2fae2b6955bd8f32684c15abfe8fd3a6261e52650e8807a92158d9f1463261a925e4bfba44bd20b166d532f0017185c3a6ac7957adefe45559e3072c8dc35abeba835a8cb01a71a15c736911126f27d46a36168ca5ef7dccd4e2886212602b181463e0dd30185c96348f9743a02aca8ec27c0b90dca270").unwrap());
2364 let onion_packet_3 = ChannelManager::encrypt_failure_packet(&onion_keys[2].shared_secret, &onion_packet_2.data[..]);
2365 assert_eq!(onion_packet_3.data, hex::decode("a5d3e8634cfe78b2307d87c6d90be6fe7855b4f2cc9b1dfb19e92e4b79103f61ff9ac25f412ddfb7466e74f81b3e545563cdd8f5524dae873de61d7bdfccd496af2584930d2b566b4f8d3881f8c043df92224f38cf094cfc09d92655989531524593ec6d6caec1863bdfaa79229b5020acc034cd6deeea1021c50586947b9b8e6faa83b81fbfa6133c0af5d6b07c017f7158fa94f0d206baf12dda6b68f785b773b360fd0497e16cc402d779c8d48d0fa6315536ef0660f3f4e1865f5b38ea49c7da4fd959de4e83ff3ab686f059a45c65ba2af4a6a79166aa0f496bf04d06987b6d2ea205bdb0d347718b9aeff5b61dfff344993a275b79717cd815b6ad4c0beb568c4ac9c36ff1c315ec1119a1993c4b61e6eaa0375e0aaf738ac691abd3263bf937e3").unwrap());
2367 let onion_packet_4 = ChannelManager::encrypt_failure_packet(&onion_keys[1].shared_secret, &onion_packet_3.data[..]);
2368 assert_eq!(onion_packet_4.data, hex::decode("aac3200c4968f56b21f53e5e374e3a2383ad2b1b6501bbcc45abc31e59b26881b7dfadbb56ec8dae8857add94e6702fb4c3a4de22e2e669e1ed926b04447fc73034bb730f4932acd62727b75348a648a1128744657ca6a4e713b9b646c3ca66cac02cdab44dd3439890ef3aaf61708714f7375349b8da541b2548d452d84de7084bb95b3ac2345201d624d31f4d52078aa0fa05a88b4e20202bd2b86ac5b52919ea305a8949de95e935eed0319cf3cf19ebea61d76ba92532497fcdc9411d06bcd4275094d0a4a3c5d3a945e43305a5a9256e333e1f64dbca5fcd4e03a39b9012d197506e06f29339dfee3331995b21615337ae060233d39befea925cc262873e0530408e6990f1cbd233a150ef7b004ff6166c70c68d9f8c853c1abca640b8660db2921").unwrap());
2370 let onion_packet_5 = ChannelManager::encrypt_failure_packet(&onion_keys[0].shared_secret, &onion_packet_4.data[..]);
2371 assert_eq!(onion_packet_5.data, hex::decode("9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d").unwrap());
2374 fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
2375 assert!(chain.does_match_tx(tx));
2376 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2377 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
2379 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2380 chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
2385 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
2386 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
2387 chan_monitor: Arc<test_utils::TestChannelMonitor>,
2388 node: Arc<ChannelManager>,
2390 network_payment_count: Rc<RefCell<u8>>,
2391 network_chan_count: Rc<RefCell<u32>>,
2393 impl Drop for Node {
2394 fn drop(&mut self) {
2395 // Check that we processed all pending events
2396 assert_eq!(self.node.get_and_clear_pending_events().len(), 0);
2397 assert_eq!(self.chan_monitor.added_monitors.lock().unwrap().len(), 0);
2401 fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2402 node_a.node.create_channel(node_b.node.get_our_node_id(), 100000, 10001, 42).unwrap();
2404 let events_1 = node_a.node.get_and_clear_pending_events();
2405 assert_eq!(events_1.len(), 1);
2406 let accept_chan = match events_1[0] {
2407 Event::SendOpenChannel { ref node_id, ref msg } => {
2408 assert_eq!(*node_id, node_b.node.get_our_node_id());
2409 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), msg).unwrap()
2411 _ => panic!("Unexpected event"),
2414 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &accept_chan).unwrap();
2416 let chan_id = *node_a.network_chan_count.borrow();
2420 let events_2 = node_a.node.get_and_clear_pending_events();
2421 assert_eq!(events_2.len(), 1);
2423 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
2424 assert_eq!(*channel_value_satoshis, 100000);
2425 assert_eq!(user_channel_id, 42);
2427 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
2428 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
2430 funding_output = OutPoint::new(Sha256dHash::from_data(&serialize(&tx).unwrap()[..]), 0);
2432 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
2433 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
2434 assert_eq!(added_monitors.len(), 1);
2435 assert_eq!(added_monitors[0].0, funding_output);
2436 added_monitors.clear();
2438 _ => panic!("Unexpected event"),
2441 let events_3 = node_a.node.get_and_clear_pending_events();
2442 assert_eq!(events_3.len(), 1);
2443 let funding_signed = match events_3[0] {
2444 Event::SendFundingCreated { ref node_id, ref msg } => {
2445 assert_eq!(*node_id, node_b.node.get_our_node_id());
2446 let res = node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), msg).unwrap();
2447 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
2448 assert_eq!(added_monitors.len(), 1);
2449 assert_eq!(added_monitors[0].0, funding_output);
2450 added_monitors.clear();
2453 _ => panic!("Unexpected event"),
2456 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &funding_signed).unwrap();
2458 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
2459 assert_eq!(added_monitors.len(), 1);
2460 assert_eq!(added_monitors[0].0, funding_output);
2461 added_monitors.clear();
2464 let events_4 = node_a.node.get_and_clear_pending_events();
2465 assert_eq!(events_4.len(), 1);
2467 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
2468 assert_eq!(user_channel_id, 42);
2469 assert_eq!(*funding_txo, funding_output);
2471 _ => panic!("Unexpected event"),
2474 confirm_transaction(&node_a.chain_monitor, &tx, chan_id);
2475 let events_5 = node_a.node.get_and_clear_pending_events();
2476 assert_eq!(events_5.len(), 1);
2478 Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
2479 assert_eq!(*node_id, node_b.node.get_our_node_id());
2480 assert!(announcement_sigs.is_none());
2481 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), msg).unwrap()
2483 _ => panic!("Unexpected event"),
2488 confirm_transaction(&node_b.chain_monitor, &tx, chan_id);
2489 let events_6 = node_b.node.get_and_clear_pending_events();
2490 assert_eq!(events_6.len(), 1);
2491 let as_announcement_sigs = match events_6[0] {
2492 Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
2493 assert_eq!(*node_id, node_a.node.get_our_node_id());
2494 channel_id = msg.channel_id.clone();
2495 let as_announcement_sigs = node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), msg).unwrap().unwrap();
2496 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &(*announcement_sigs).clone().unwrap()).unwrap();
2497 as_announcement_sigs
2499 _ => panic!("Unexpected event"),
2502 let events_7 = node_a.node.get_and_clear_pending_events();
2503 assert_eq!(events_7.len(), 1);
2504 let (announcement, as_update) = match events_7[0] {
2505 Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
2508 _ => panic!("Unexpected event"),
2511 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_announcement_sigs).unwrap();
2512 let events_8 = node_b.node.get_and_clear_pending_events();
2513 assert_eq!(events_8.len(), 1);
2514 let bs_update = match events_8[0] {
2515 Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
2516 assert!(*announcement == *msg);
2519 _ => panic!("Unexpected event"),
2522 *node_a.network_chan_count.borrow_mut() += 1;
2524 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone(), channel_id, tx)
2527 fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
2528 let chan_announcement = create_chan_between_nodes(&nodes[a], &nodes[b]);
2530 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
2531 node.router.handle_channel_update(&chan_announcement.1).unwrap();
2532 node.router.handle_channel_update(&chan_announcement.2).unwrap();
2534 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
2537 fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate) {
2538 let (node_a, broadcaster_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster) } else { (&outbound_node.node, &outbound_node.tx_broadcaster) };
2539 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
2542 node_a.close_channel(channel_id).unwrap();
2543 let events_1 = node_a.get_and_clear_pending_events();
2544 assert_eq!(events_1.len(), 1);
2545 let shutdown_a = match events_1[0] {
2546 Event::SendShutdown { ref node_id, ref msg } => {
2547 assert_eq!(node_id, &node_b.get_our_node_id());
2550 _ => panic!("Unexpected event"),
2553 let (shutdown_b, mut closing_signed_b) = node_b.handle_shutdown(&node_a.get_our_node_id(), &shutdown_a).unwrap();
2554 if !close_inbound_first {
2555 assert!(closing_signed_b.is_none());
2557 let (empty_a, mut closing_signed_a) = node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b.unwrap()).unwrap();
2558 assert!(empty_a.is_none());
2559 if close_inbound_first {
2560 assert!(closing_signed_a.is_none());
2561 closing_signed_a = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
2562 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
2563 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
2565 let empty_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
2566 assert!(empty_b.is_none());
2567 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
2568 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
2570 closing_signed_b = node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
2571 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
2572 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
2574 let empty_a2 = node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
2575 assert!(empty_a2.is_none());
2576 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
2577 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
2579 assert_eq!(tx_a, tx_b);
2580 let mut funding_tx_map = HashMap::new();
2581 funding_tx_map.insert(funding_tx.txid(), funding_tx);
2582 tx_a.verify(&funding_tx_map).unwrap();
2584 let events_2 = node_a.get_and_clear_pending_events();
2585 assert_eq!(events_2.len(), 1);
2586 let as_update = match events_2[0] {
2587 Event::BroadcastChannelUpdate { ref msg } => {
2590 _ => panic!("Unexpected event"),
2593 let events_3 = node_b.get_and_clear_pending_events();
2594 assert_eq!(events_3.len(), 1);
2595 let bs_update = match events_3[0] {
2596 Event::BroadcastChannelUpdate { ref msg } => {
2599 _ => panic!("Unexpected event"),
2602 (as_update, bs_update)
2607 msgs: Vec<msgs::UpdateAddHTLC>,
2608 commitment_msg: msgs::CommitmentSigned,
2611 fn from_event(event: Event) -> SendEvent {
2613 Event::UpdateHTLCs { node_id, updates: msgs::CommitmentUpdate { update_add_htlcs, update_fulfill_htlcs, update_fail_htlcs, update_fail_malformed_htlcs, commitment_signed } } => {
2614 assert!(update_fulfill_htlcs.is_empty());
2615 assert!(update_fail_htlcs.is_empty());
2616 assert!(update_fail_malformed_htlcs.is_empty());
2617 SendEvent { node_id: node_id, msgs: update_add_htlcs, commitment_msg: commitment_signed }
2619 _ => panic!("Unexpected event type!"),
2624 macro_rules! commitment_signed_dance {
2625 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
2628 let added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
2629 assert!(added_monitors.is_empty());
2631 let (as_revoke_and_ack, as_commitment_signed) = $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
2633 let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
2634 assert_eq!(added_monitors.len(), 1);
2635 added_monitors.clear();
2638 let added_monitors = $node_b.chan_monitor.added_monitors.lock().unwrap();
2639 assert!(added_monitors.is_empty());
2641 assert!($node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap().is_none());
2643 let mut added_monitors = $node_b.chan_monitor.added_monitors.lock().unwrap();
2644 assert_eq!(added_monitors.len(), 1);
2645 added_monitors.clear();
2647 let (bs_revoke_and_ack, bs_none) = $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed.unwrap()).unwrap();
2648 assert!(bs_none.is_none());
2650 let mut added_monitors = $node_b.chan_monitor.added_monitors.lock().unwrap();
2651 assert_eq!(added_monitors.len(), 1);
2652 added_monitors.clear();
2654 if $fail_backwards {
2655 assert!($node_a.node.get_and_clear_pending_events().is_empty());
2657 assert!($node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap().is_none());
2659 let mut added_monitors = $node_a.chan_monitor.added_monitors.lock().unwrap();
2660 if $fail_backwards {
2661 assert_eq!(added_monitors.len(), 2);
2662 assert!(added_monitors[0].0 != added_monitors[1].0);
2664 assert_eq!(added_monitors.len(), 1);
2666 added_monitors.clear();
2672 fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
2673 let our_payment_preimage = [*origin_node.network_payment_count.borrow(); 32];
2674 *origin_node.network_payment_count.borrow_mut() += 1;
2675 let our_payment_hash = {
2676 let mut sha = Sha256::new();
2677 sha.input(&our_payment_preimage[..]);
2678 let mut ret = [0; 32];
2679 sha.result(&mut ret);
2683 let mut payment_event = {
2684 origin_node.node.send_payment(route, our_payment_hash).unwrap();
2686 let mut added_monitors = origin_node.chan_monitor.added_monitors.lock().unwrap();
2687 assert_eq!(added_monitors.len(), 1);
2688 added_monitors.clear();
2691 let mut events = origin_node.node.get_and_clear_pending_events();
2692 assert_eq!(events.len(), 1);
2693 SendEvent::from_event(events.remove(0))
2695 let mut prev_node = origin_node;
2697 for (idx, &node) in expected_route.iter().enumerate() {
2698 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
2700 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2702 let added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
2703 assert_eq!(added_monitors.len(), 0);
2706 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
2708 let events_1 = node.node.get_and_clear_pending_events();
2709 assert_eq!(events_1.len(), 1);
2711 Event::PendingHTLCsForwardable { .. } => { },
2712 _ => panic!("Unexpected event"),
2715 node.node.channel_state.lock().unwrap().next_forward = Instant::now();
2716 node.node.process_pending_htlc_forwards();
2718 let mut events_2 = node.node.get_and_clear_pending_events();
2719 assert_eq!(events_2.len(), 1);
2720 if idx == expected_route.len() - 1 {
2722 Event::PaymentReceived { ref payment_hash, amt } => {
2723 assert_eq!(our_payment_hash, *payment_hash);
2724 assert_eq!(amt, recv_value);
2726 _ => panic!("Unexpected event"),
2730 let mut added_monitors = node.chan_monitor.added_monitors.lock().unwrap();
2731 assert_eq!(added_monitors.len(), 1);
2732 added_monitors.clear();
2734 payment_event = SendEvent::from_event(events_2.remove(0));
2735 assert_eq!(payment_event.msgs.len(), 1);
2741 (our_payment_preimage, our_payment_hash)
2744 fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: [u8; 32]) {
2745 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
2747 let mut added_monitors = expected_route.last().unwrap().chan_monitor.added_monitors.lock().unwrap();
2748 assert_eq!(added_monitors.len(), 1);
2749 added_monitors.clear();
2752 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
2753 macro_rules! update_fulfill_dance {
2754 ($node: expr, $prev_node: expr, $last_node: expr) => {
2756 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
2758 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
2760 assert_eq!(added_monitors.len(), 0);
2762 assert_eq!(added_monitors.len(), 1);
2764 added_monitors.clear();
2766 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
2771 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
2772 let mut prev_node = expected_route.last().unwrap();
2773 for (idx, node) in expected_route.iter().rev().enumerate() {
2774 assert_eq!(expected_next_node, node.node.get_our_node_id());
2775 if next_msgs.is_some() {
2776 update_fulfill_dance!(node, prev_node, false);
2779 let events = node.node.get_and_clear_pending_events();
2780 if !skip_last || idx != expected_route.len() - 1 {
2781 assert_eq!(events.len(), 1);
2783 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed } } => {
2784 assert!(update_add_htlcs.is_empty());
2785 assert_eq!(update_fulfill_htlcs.len(), 1);
2786 assert!(update_fail_htlcs.is_empty());
2787 assert!(update_fail_malformed_htlcs.is_empty());
2788 expected_next_node = node_id.clone();
2789 next_msgs = Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()));
2791 _ => panic!("Unexpected event"),
2794 assert!(events.is_empty());
2796 if !skip_last && idx == expected_route.len() - 1 {
2797 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2804 update_fulfill_dance!(origin_node, expected_route.first().unwrap(), true);
2805 let events = origin_node.node.get_and_clear_pending_events();
2806 assert_eq!(events.len(), 1);
2808 Event::PaymentSent { payment_preimage } => {
2809 assert_eq!(payment_preimage, our_payment_preimage);
2811 _ => panic!("Unexpected event"),
2816 fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: [u8; 32]) {
2817 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
2820 const TEST_FINAL_CLTV: u32 = 32;
2822 fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> ([u8; 32], [u8; 32]) {
2823 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();
2824 assert_eq!(route.hops.len(), expected_route.len());
2825 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
2826 assert_eq!(hop.pubkey, node.node.get_our_node_id());
2829 send_along_route(origin_node, route, expected_route, recv_value)
2832 fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
2833 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();
2834 assert_eq!(route.hops.len(), expected_route.len());
2835 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
2836 assert_eq!(hop.pubkey, node.node.get_our_node_id());
2839 let our_payment_preimage = [*origin_node.network_payment_count.borrow(); 32];
2840 *origin_node.network_payment_count.borrow_mut() += 1;
2841 let our_payment_hash = {
2842 let mut sha = Sha256::new();
2843 sha.input(&our_payment_preimage[..]);
2844 let mut ret = [0; 32];
2845 sha.result(&mut ret);
2849 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
2851 APIError::RouteError{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
2852 _ => panic!("Unknown error variants"),
2856 fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
2857 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
2858 claim_payment(&origin, expected_route, our_payment_preimage);
2861 fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: [u8; 32]) {
2862 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
2864 let mut added_monitors = expected_route.last().unwrap().chan_monitor.added_monitors.lock().unwrap();
2865 assert_eq!(added_monitors.len(), 1);
2866 added_monitors.clear();
2869 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
2870 macro_rules! update_fail_dance {
2871 ($node: expr, $prev_node: expr, $last_node: expr) => {
2873 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
2874 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
2879 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
2880 let mut prev_node = expected_route.last().unwrap();
2881 for (idx, node) in expected_route.iter().rev().enumerate() {
2882 assert_eq!(expected_next_node, node.node.get_our_node_id());
2883 if next_msgs.is_some() {
2884 // We may be the "last node" for the purpose of the commitment dance if we're
2885 // skipping the last node (implying it is disconnected) and we're the
2886 // second-to-last node!
2887 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
2890 let events = node.node.get_and_clear_pending_events();
2891 if !skip_last || idx != expected_route.len() - 1 {
2892 assert_eq!(events.len(), 1);
2894 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed } } => {
2895 assert!(update_add_htlcs.is_empty());
2896 assert!(update_fulfill_htlcs.is_empty());
2897 assert_eq!(update_fail_htlcs.len(), 1);
2898 assert!(update_fail_malformed_htlcs.is_empty());
2899 expected_next_node = node_id.clone();
2900 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
2902 _ => panic!("Unexpected event"),
2905 assert!(events.is_empty());
2907 if !skip_last && idx == expected_route.len() - 1 {
2908 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2915 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
2917 let events = origin_node.node.get_and_clear_pending_events();
2918 assert_eq!(events.len(), 1);
2920 Event::PaymentFailed { payment_hash } => {
2921 assert_eq!(payment_hash, our_payment_hash);
2923 _ => panic!("Unexpected event"),
2928 fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: [u8; 32]) {
2929 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
2932 fn create_network(node_count: usize) -> Vec<Node> {
2933 let mut nodes = Vec::new();
2934 let mut rng = thread_rng();
2935 let secp_ctx = Secp256k1::new();
2936 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
2938 let chan_count = Rc::new(RefCell::new(0));
2939 let payment_count = Rc::new(RefCell::new(0));
2941 for _ in 0..node_count {
2942 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
2943 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
2944 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
2945 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone()));
2947 let mut key_slice = [0; 32];
2948 rng.fill_bytes(&mut key_slice);
2949 SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
2951 let node = ChannelManager::new(node_id.clone(), 0, true, Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger)).unwrap();
2952 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &node_id), chain_monitor.clone(), Arc::clone(&logger));
2953 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router,
2954 network_payment_count: payment_count.clone(),
2955 network_chan_count: chan_count.clone(),
2963 fn fake_network_test() {
2964 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2965 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
2966 let nodes = create_network(4);
2968 // Create some initial channels
2969 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2970 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2971 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2973 // Rebalance the network a bit by relaying one payment through all the channels...
2974 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2975 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2976 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2977 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
2979 // Send some more payments
2980 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
2981 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
2982 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
2984 // Test failure packets
2985 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
2986 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
2988 // Add a new channel that skips 3
2989 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
2991 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
2992 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
2993 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2994 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2995 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2996 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2997 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
2999 // Do some rebalance loop payments, simultaneously
3000 let mut hops = Vec::with_capacity(3);
3001 hops.push(RouteHop {
3002 pubkey: nodes[2].node.get_our_node_id(),
3003 short_channel_id: chan_2.0.contents.short_channel_id,
3005 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
3007 hops.push(RouteHop {
3008 pubkey: nodes[3].node.get_our_node_id(),
3009 short_channel_id: chan_3.0.contents.short_channel_id,
3011 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
3013 hops.push(RouteHop {
3014 pubkey: nodes[1].node.get_our_node_id(),
3015 short_channel_id: chan_4.0.contents.short_channel_id,
3017 cltv_expiry_delta: TEST_FINAL_CLTV,
3019 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
3020 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
3021 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
3023 let mut hops = Vec::with_capacity(3);
3024 hops.push(RouteHop {
3025 pubkey: nodes[3].node.get_our_node_id(),
3026 short_channel_id: chan_4.0.contents.short_channel_id,
3028 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
3030 hops.push(RouteHop {
3031 pubkey: nodes[2].node.get_our_node_id(),
3032 short_channel_id: chan_3.0.contents.short_channel_id,
3034 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
3036 hops.push(RouteHop {
3037 pubkey: nodes[1].node.get_our_node_id(),
3038 short_channel_id: chan_2.0.contents.short_channel_id,
3040 cltv_expiry_delta: TEST_FINAL_CLTV,
3042 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
3043 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
3044 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
3046 // Claim the rebalances...
3047 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
3048 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
3050 // Add a duplicate new channel from 2 to 4
3051 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
3053 // Send some payments across both channels
3054 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3055 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3056 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
3058 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
3060 //TODO: Test that routes work again here as we've been notified that the channel is full
3062 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
3063 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
3064 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
3066 // Close down the channels...
3067 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
3068 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
3069 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
3070 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
3071 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
3075 fn duplicate_htlc_test() {
3076 // Test that we accept duplicate payment_hash HTLCs across the network and that
3077 // claiming/failing them are all separate and don't effect each other
3078 let mut nodes = create_network(6);
3080 // Create some initial channels to route via 3 to 4/5 from 0/1/2
3081 create_announced_chan_between_nodes(&nodes, 0, 3);
3082 create_announced_chan_between_nodes(&nodes, 1, 3);
3083 create_announced_chan_between_nodes(&nodes, 2, 3);
3084 create_announced_chan_between_nodes(&nodes, 3, 4);
3085 create_announced_chan_between_nodes(&nodes, 3, 5);
3087 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
3089 *nodes[0].network_payment_count.borrow_mut() -= 1;
3090 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
3092 *nodes[0].network_payment_count.borrow_mut() -= 1;
3093 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
3095 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
3096 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
3097 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
3100 #[derive(PartialEq)]
3101 enum HTLCType { NONE, TIMEOUT, SUCCESS }
3102 /// Tests that the given node has broadcast transactions for the given Channel
3104 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
3105 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
3106 /// broadcast and the revoked outputs were claimed.
3108 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
3109 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
3111 /// All broadcast transactions must be accounted for in one of the above three types of we'll
3113 fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
3114 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
3115 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
3117 let mut res = Vec::with_capacity(2);
3118 node_txn.retain(|tx| {
3119 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
3120 let mut funding_tx_map = HashMap::new();
3121 funding_tx_map.insert(chan.3.txid(), chan.3.clone());
3122 tx.verify(&funding_tx_map).unwrap();
3123 if commitment_tx.is_none() {
3124 res.push(tx.clone());
3129 if let Some(explicit_tx) = commitment_tx {
3130 res.push(explicit_tx.clone());
3133 assert_eq!(res.len(), 1);
3135 if has_htlc_tx != HTLCType::NONE {
3136 node_txn.retain(|tx| {
3137 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
3138 let mut funding_tx_map = HashMap::new();
3139 funding_tx_map.insert(res[0].txid(), res[0].clone());
3140 tx.verify(&funding_tx_map).unwrap();
3141 if has_htlc_tx == HTLCType::TIMEOUT {
3142 assert!(tx.lock_time != 0);
3144 assert!(tx.lock_time == 0);
3146 res.push(tx.clone());
3150 assert_eq!(res.len(), 2);
3153 assert!(node_txn.is_empty());
3157 /// Tests that the given node has broadcast a claim transaction against the provided revoked
3158 /// HTLC transaction.
3159 fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
3160 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
3161 assert_eq!(node_txn.len(), 1);
3162 node_txn.retain(|tx| {
3163 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
3164 let mut funding_tx_map = HashMap::new();
3165 funding_tx_map.insert(revoked_tx.txid(), revoked_tx.clone());
3166 tx.verify(&funding_tx_map).unwrap();
3170 assert!(node_txn.is_empty());
3173 fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
3174 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
3176 assert!(node_txn.len() >= 1);
3177 assert_eq!(node_txn[0].input.len(), 1);
3178 let mut found_prev = false;
3180 for tx in prev_txn {
3181 if node_txn[0].input[0].previous_output.txid == tx.txid() {
3182 let mut funding_tx_map = HashMap::new();
3183 funding_tx_map.insert(tx.txid(), tx.clone());
3184 node_txn[0].verify(&funding_tx_map).unwrap();
3186 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
3187 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
3193 assert!(found_prev);
3195 let mut res = Vec::new();
3196 mem::swap(&mut *node_txn, &mut res);
3200 fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
3201 let events_1 = nodes[a].node.get_and_clear_pending_events();
3202 assert_eq!(events_1.len(), 1);
3203 let as_update = match events_1[0] {
3204 Event::BroadcastChannelUpdate { ref msg } => {
3207 _ => panic!("Unexpected event"),
3210 let events_2 = nodes[b].node.get_and_clear_pending_events();
3211 assert_eq!(events_2.len(), 1);
3212 let bs_update = match events_2[0] {
3213 Event::BroadcastChannelUpdate { ref msg } => {
3216 _ => panic!("Unexpected event"),
3220 node.router.handle_channel_update(&as_update).unwrap();
3221 node.router.handle_channel_update(&bs_update).unwrap();
3226 fn channel_monitor_network_test() {
3227 // Simple test which builds a network of ChannelManagers, connects them to each other, and
3228 // tests that ChannelMonitor is able to recover from various states.
3229 let nodes = create_network(5);
3231 // Create some initial channels
3232 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3233 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3234 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
3235 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
3237 // Rebalance the network a bit by relaying one payment through all the channels...
3238 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
3239 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
3240 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
3241 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
3243 // Simple case with no pending HTLCs:
3244 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
3246 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
3247 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3248 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
3249 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
3251 get_announce_close_broadcast_events(&nodes, 0, 1);
3252 assert_eq!(nodes[0].node.list_channels().len(), 0);
3253 assert_eq!(nodes[1].node.list_channels().len(), 1);
3255 // One pending HTLC is discarded by the force-close:
3256 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
3258 // Simple case of one pending HTLC to HTLC-Timeout
3259 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
3261 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
3262 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3263 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
3264 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
3266 get_announce_close_broadcast_events(&nodes, 1, 2);
3267 assert_eq!(nodes[1].node.list_channels().len(), 0);
3268 assert_eq!(nodes[2].node.list_channels().len(), 1);
3270 macro_rules! claim_funds {
3271 ($node: expr, $prev_node: expr, $preimage: expr) => {
3273 assert!($node.node.claim_funds($preimage));
3275 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
3276 assert_eq!(added_monitors.len(), 1);
3277 added_monitors.clear();
3280 let events = $node.node.get_and_clear_pending_events();
3281 assert_eq!(events.len(), 1);
3283 Event::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
3284 assert!(update_add_htlcs.is_empty());
3285 assert!(update_fail_htlcs.is_empty());
3286 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
3288 _ => panic!("Unexpected event"),
3294 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
3295 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
3296 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
3298 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
3300 // Claim the payment on nodes[3], giving it knowledge of the preimage
3301 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
3303 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3304 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
3306 check_preimage_claim(&nodes[3], &node_txn);
3308 get_announce_close_broadcast_events(&nodes, 2, 3);
3309 assert_eq!(nodes[2].node.list_channels().len(), 0);
3310 assert_eq!(nodes[3].node.list_channels().len(), 1);
3312 // One pending HTLC to time out:
3313 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
3316 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3317 nodes[3].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
3318 for i in 2..TEST_FINAL_CLTV - 3 {
3319 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3320 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
3323 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
3325 // Claim the payment on nodes[4], giving it knowledge of the preimage
3326 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
3328 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3329 nodes[4].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
3330 for i in 2..TEST_FINAL_CLTV - 3 {
3331 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3332 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
3335 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
3337 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3338 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
3340 check_preimage_claim(&nodes[4], &node_txn);
3342 get_announce_close_broadcast_events(&nodes, 3, 4);
3343 assert_eq!(nodes[3].node.list_channels().len(), 0);
3344 assert_eq!(nodes[4].node.list_channels().len(), 0);
3346 // Create some new channels:
3347 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
3349 // A pending HTLC which will be revoked:
3350 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3351 // Get the will-be-revoked local txn from nodes[0]
3352 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
3353 // Revoke the old state
3354 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
3357 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3358 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3360 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3361 assert_eq!(node_txn.len(), 3);
3362 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
3363 assert_eq!(node_txn[0].input.len(), 1);
3365 let mut funding_tx_map = HashMap::new();
3366 funding_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
3367 node_txn[0].verify(&funding_tx_map).unwrap();
3368 node_txn.swap_remove(0);
3370 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
3372 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3373 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
3374 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3375 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
3376 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
3378 get_announce_close_broadcast_events(&nodes, 0, 1);
3379 assert_eq!(nodes[0].node.list_channels().len(), 0);
3380 assert_eq!(nodes[1].node.list_channels().len(), 0);
3384 fn test_htlc_ignore_latest_remote_commitment() {
3385 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3386 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3387 let nodes = create_network(2);
3388 create_announced_chan_between_nodes(&nodes, 0, 1);
3390 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3391 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3393 let events = nodes[0].node.get_and_clear_pending_events();
3394 assert_eq!(events.len(), 1);
3396 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
3397 assert_eq!(flags & 0b10, 0b10);
3399 _ => panic!("Unexpected event"),
3403 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3404 assert_eq!(node_txn.len(), 2);
3406 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3407 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
3410 let events = nodes[1].node.get_and_clear_pending_events();
3411 assert_eq!(events.len(), 1);
3413 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
3414 assert_eq!(flags & 0b10, 0b10);
3416 _ => panic!("Unexpected event"),
3420 // Duplicate the block_connected call since this may happen due to other listeners
3421 // registering new transactions
3422 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
3426 fn test_force_close_fail_back() {
3427 // Check which HTLCs are failed-backwards on channel force-closure
3428 let mut nodes = create_network(3);
3429 create_announced_chan_between_nodes(&nodes, 0, 1);
3430 create_announced_chan_between_nodes(&nodes, 1, 2);
3432 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
3434 let our_payment_preimage = [*nodes[0].network_payment_count.borrow(); 32];
3435 *nodes[0].network_payment_count.borrow_mut() += 1;
3436 let our_payment_hash = {
3437 let mut sha = Sha256::new();
3438 sha.input(&our_payment_preimage[..]);
3439 let mut ret = [0; 32];
3440 sha.result(&mut ret);
3444 let mut payment_event = {
3445 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
3447 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
3448 assert_eq!(added_monitors.len(), 1);
3449 added_monitors.clear();
3452 let mut events = nodes[0].node.get_and_clear_pending_events();
3453 assert_eq!(events.len(), 1);
3454 SendEvent::from_event(events.remove(0))
3457 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3458 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3460 let events_1 = nodes[1].node.get_and_clear_pending_events();
3461 assert_eq!(events_1.len(), 1);
3463 Event::PendingHTLCsForwardable { .. } => { },
3464 _ => panic!("Unexpected event"),
3467 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
3468 nodes[1].node.process_pending_htlc_forwards();
3470 let mut events_2 = nodes[1].node.get_and_clear_pending_events();
3471 assert_eq!(events_2.len(), 1);
3472 payment_event = SendEvent::from_event(events_2.remove(0));
3473 assert_eq!(payment_event.msgs.len(), 1);
3476 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
3477 assert_eq!(added_monitors.len(), 1);
3478 added_monitors.clear();
3481 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3482 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
3485 let mut added_monitors = nodes[2].chan_monitor.added_monitors.lock().unwrap();
3486 assert_eq!(added_monitors.len(), 1);
3487 added_monitors.clear();
3490 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3491 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3492 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3494 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3495 let events_3 = nodes[2].node.get_and_clear_pending_events();
3496 assert_eq!(events_3.len(), 1);
3498 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
3499 assert_eq!(flags & 0b10, 0b10);
3501 _ => panic!("Unexpected event"),
3505 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3506 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3507 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3508 // back to nodes[1] upon timeout otherwise.
3509 assert_eq!(node_txn.len(), 1);
3513 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3514 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
3516 let events_4 = nodes[1].node.get_and_clear_pending_events();
3517 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3518 assert_eq!(events_4.len(), 1);
3520 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
3521 assert_eq!(flags & 0b10, 0b10);
3523 _ => panic!("Unexpected event"),
3526 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3528 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3529 monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
3530 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3532 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
3533 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3534 assert_eq!(node_txn.len(), 1);
3535 assert_eq!(node_txn[0].input.len(), 1);
3536 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3537 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3538 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3539 let mut funding_tx_map = HashMap::new();
3540 funding_tx_map.insert(tx.txid(), tx);
3541 node_txn[0].verify(&funding_tx_map).unwrap();
3545 fn test_unconf_chan() {
3546 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3547 let nodes = create_network(2);
3548 create_announced_chan_between_nodes(&nodes, 0, 1);
3550 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3551 assert_eq!(channel_state.by_id.len(), 1);
3552 assert_eq!(channel_state.short_to_id.len(), 1);
3553 mem::drop(channel_state);
3555 let mut headers = Vec::new();
3556 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3557 headers.push(header.clone());
3559 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3560 headers.push(header.clone());
3562 while !headers.is_empty() {
3563 nodes[0].node.block_disconnected(&headers.pop().unwrap());
3566 let events = nodes[0].node.get_and_clear_pending_events();
3567 assert_eq!(events.len(), 1);
3569 Event::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { contents: msgs::UnsignedChannelUpdate { flags, .. }, .. } } => {
3570 assert_eq!(flags & 0b10, 0b10);
3572 _ => panic!("Unexpected event"),
3575 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3576 assert_eq!(channel_state.by_id.len(), 0);
3577 assert_eq!(channel_state.short_to_id.len(), 0);
3581 fn test_invalid_channel_announcement() {
3582 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3583 let secp_ctx = Secp256k1::new();
3584 let nodes = create_network(2);
3586 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
3588 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3589 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3590 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3591 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3593 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap() } );
3595 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
3596 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
3598 let as_network_key = nodes[0].node.get_our_node_id();
3599 let bs_network_key = nodes[1].node.get_our_node_id();
3601 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3603 let mut chan_announcement;
3605 macro_rules! dummy_unsigned_msg {
3607 msgs::UnsignedChannelAnnouncement {
3608 features: msgs::GlobalFeatures::new(),
3609 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3610 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3611 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3612 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3613 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3614 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3615 excess_data: Vec::new(),
3620 macro_rules! sign_msg {
3621 ($unsigned_msg: expr) => {
3622 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
3623 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
3624 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
3625 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].node.our_network_key);
3626 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].node.our_network_key);
3627 chan_announcement = msgs::ChannelAnnouncement {
3628 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3629 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3630 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3631 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3632 contents: $unsigned_msg
3637 let unsigned_msg = dummy_unsigned_msg!();
3638 sign_msg!(unsigned_msg);
3639 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3640 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap() } );
3642 // Configured with Network::Testnet
3643 let mut unsigned_msg = dummy_unsigned_msg!();
3644 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3645 sign_msg!(unsigned_msg);
3646 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3648 let mut unsigned_msg = dummy_unsigned_msg!();
3649 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
3650 sign_msg!(unsigned_msg);
3651 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());