1 //! The top-level channel management and payment tracking stuff lives here.
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
7 //! It does not manage routing logic (see ln::router for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
11 use bitcoin::blockdata::block::BlockHeader;
12 use bitcoin::blockdata::transaction::Transaction;
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::network::constants::Network;
15 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
17 use bitcoin_hashes::{Hash, HashEngine};
18 use bitcoin_hashes::hmac::{Hmac, HmacEngine};
19 use bitcoin_hashes::sha256::Hash as Sha256;
20 use bitcoin_hashes::cmp::fixed_time_eq;
22 use secp256k1::key::{SecretKey,PublicKey};
23 use secp256k1::Secp256k1;
24 use secp256k1::ecdh::SharedSecret;
27 use chain::chaininterface::{BroadcasterInterface,ChainListener,ChainWatchInterface,FeeEstimator};
28 use chain::transaction::OutPoint;
29 use ln::channel::{Channel, ChannelError};
30 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, ManyChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, HTLC_FAIL_ANTI_REORG_DELAY};
31 use ln::router::Route;
34 use ln::msgs::{ChannelMessageHandler, DecodeError, HandleError};
35 use chain::keysinterface::KeysInterface;
36 use util::config::UserConfig;
37 use util::{byte_utils, events, rng};
38 use util::ser::{Readable, ReadableArgs, Writeable, Writer};
39 use util::chacha20::ChaCha20;
40 use util::logger::Logger;
41 use util::errors::APIError;
44 use std::collections::{HashMap, hash_map, HashSet};
46 use std::sync::{Arc, Mutex, MutexGuard, RwLock};
47 use std::sync::atomic::{AtomicUsize, Ordering};
48 use std::time::{Instant,Duration};
50 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
52 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
53 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
54 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
56 // When a Channel forwards an HTLC to its peer, it will give us back the PendingForwardHTLCInfo
57 // which we will use to construct an outbound HTLC, with a relevant HTLCSource::PreviousHopData
58 // filled in to indicate where it came from (which we can use to either fail-backwards or fulfill
59 // the HTLC backwards along the relevant path).
60 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
61 // our payment, which we can use to decode errors or inform the user that the payment was sent.
62 /// Stores the info we will need to send when we want to forward an HTLC onwards
63 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
64 pub(super) struct PendingForwardHTLCInfo {
65 onion_packet: Option<msgs::OnionPacket>,
66 incoming_shared_secret: [u8; 32],
67 payment_hash: PaymentHash,
68 short_channel_id: u64,
69 pub(super) amt_to_forward: u64,
70 pub(super) outgoing_cltv_value: u32,
73 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
74 pub(super) enum HTLCFailureMsg {
75 Relay(msgs::UpdateFailHTLC),
76 Malformed(msgs::UpdateFailMalformedHTLC),
79 /// Stores whether we can't forward an HTLC or relevant forwarding info
80 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
81 pub(super) enum PendingHTLCStatus {
82 Forward(PendingForwardHTLCInfo),
86 /// Tracks the inbound corresponding to an outbound HTLC
87 #[derive(Clone, PartialEq)]
88 pub(super) struct HTLCPreviousHopData {
89 short_channel_id: u64,
91 incoming_packet_shared_secret: [u8; 32],
94 /// Tracks the inbound corresponding to an outbound HTLC
95 #[derive(Clone, PartialEq)]
96 pub(super) enum HTLCSource {
97 PreviousHopData(HTLCPreviousHopData),
100 session_priv: SecretKey,
101 /// Technically we can recalculate this from the route, but we cache it here to avoid
102 /// doing a double-pass on route when we get a failure back
103 first_hop_htlc_msat: u64,
108 pub fn dummy() -> Self {
109 HTLCSource::OutboundRoute {
110 route: Route { hops: Vec::new() },
111 session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
112 first_hop_htlc_msat: 0,
117 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
118 pub(super) enum HTLCFailReason {
120 err: msgs::OnionErrorPacket,
128 /// payment_hash type, use to cross-lock hop
129 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
130 pub struct PaymentHash(pub [u8;32]);
131 /// payment_preimage type, use to route payment between hop
132 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
133 pub struct PaymentPreimage(pub [u8;32]);
135 type ShutdownResult = (Vec<Transaction>, Vec<(HTLCSource, PaymentHash)>);
137 /// Error type returned across the channel_state mutex boundary. When an Err is generated for a
138 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
139 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
140 /// channel_state lock. We then return the set of things that need to be done outside the lock in
141 /// this struct and call handle_error!() on it.
143 struct MsgHandleErrInternal {
144 err: msgs::HandleError,
145 shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
147 impl MsgHandleErrInternal {
149 fn send_err_msg_no_close(err: &'static str, channel_id: [u8; 32]) -> Self {
153 action: Some(msgs::ErrorAction::SendErrorMessage {
154 msg: msgs::ErrorMessage {
156 data: err.to_string()
160 shutdown_finish: None,
164 fn ignore_no_close(err: &'static str) -> Self {
168 action: Some(msgs::ErrorAction::IgnoreError),
170 shutdown_finish: None,
174 fn from_no_close(err: msgs::HandleError) -> Self {
175 Self { err, shutdown_finish: None }
178 fn from_finish_shutdown(err: &'static str, channel_id: [u8; 32], shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
182 action: Some(msgs::ErrorAction::SendErrorMessage {
183 msg: msgs::ErrorMessage {
185 data: err.to_string()
189 shutdown_finish: Some((shutdown_res, channel_update)),
193 fn from_chan_no_close(err: ChannelError, channel_id: [u8; 32]) -> Self {
196 ChannelError::Ignore(msg) => HandleError {
198 action: Some(msgs::ErrorAction::IgnoreError),
200 ChannelError::Close(msg) => HandleError {
202 action: Some(msgs::ErrorAction::SendErrorMessage {
203 msg: msgs::ErrorMessage {
205 data: msg.to_string()
210 shutdown_finish: None,
215 /// We hold back HTLCs we intend to relay for a random interval in the range (this, 5*this). This
216 /// provides some limited amount of privacy. Ideally this would range from somewhere like 1 second
217 /// to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly. We could
218 /// probably increase this significantly.
219 const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u32 = 50;
221 pub(super) enum HTLCForwardInfo {
223 prev_short_channel_id: u64,
225 forward_info: PendingForwardHTLCInfo,
229 err_packet: msgs::OnionErrorPacket,
233 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
234 /// be sent in the order they appear in the return value, however sometimes the order needs to be
235 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
236 /// they were originally sent). In those cases, this enum is also returned.
237 #[derive(Clone, PartialEq)]
238 pub(super) enum RAACommitmentOrder {
239 /// Send the CommitmentUpdate messages first
241 /// Send the RevokeAndACK message first
245 // Note this is only exposed in cfg(test):
246 pub(super) struct ChannelHolder {
247 pub(super) by_id: HashMap<[u8; 32], Channel>,
248 pub(super) short_to_id: HashMap<u64, [u8; 32]>,
249 pub(super) next_forward: Instant,
250 /// short channel id -> forward infos. Key of 0 means payments received
251 /// Note that while this is held in the same mutex as the channels themselves, no consistency
252 /// guarantees are made about there existing a channel with the short id here, nor the short
253 /// ids in the PendingForwardHTLCInfo!
254 pub(super) forward_htlcs: HashMap<u64, Vec<HTLCForwardInfo>>,
255 /// Note that while this is held in the same mutex as the channels themselves, no consistency
256 /// guarantees are made about the channels given here actually existing anymore by the time you
258 pub(super) claimable_htlcs: HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
259 /// Messages to send to peers - pushed to in the same lock that they are generated in (except
260 /// for broadcast messages, where ordering isn't as strict).
261 pub(super) pending_msg_events: Vec<events::MessageSendEvent>,
263 pub(super) struct MutChannelHolder<'a> {
264 pub(super) by_id: &'a mut HashMap<[u8; 32], Channel>,
265 pub(super) short_to_id: &'a mut HashMap<u64, [u8; 32]>,
266 pub(super) next_forward: &'a mut Instant,
267 pub(super) forward_htlcs: &'a mut HashMap<u64, Vec<HTLCForwardInfo>>,
268 pub(super) claimable_htlcs: &'a mut HashMap<PaymentHash, Vec<HTLCPreviousHopData>>,
269 pub(super) pending_msg_events: &'a mut Vec<events::MessageSendEvent>,
272 pub(super) fn borrow_parts(&mut self) -> MutChannelHolder {
274 by_id: &mut self.by_id,
275 short_to_id: &mut self.short_to_id,
276 next_forward: &mut self.next_forward,
277 forward_htlcs: &mut self.forward_htlcs,
278 claimable_htlcs: &mut self.claimable_htlcs,
279 pending_msg_events: &mut self.pending_msg_events,
284 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
285 const ERR: () = "You need at least 32 bit pointers (well, usize, but we'll assume they're the same) for ChannelManager::latest_block_height";
287 /// Manager which keeps track of a number of channels and sends messages to the appropriate
288 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
290 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
291 /// to individual Channels.
293 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
294 /// all peers during write/read (though does not modify this instance, only the instance being
295 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
296 /// called funding_transaction_generated for outbound channels).
298 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
299 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
300 /// returning from ManyChannelMonitor::add_update_monitor, with ChannelManagers, writing updates
301 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
302 /// the serialization process). If the deserialized version is out-of-date compared to the
303 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
304 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
306 /// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
307 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
308 /// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
309 /// block_connected() to step towards your best block) upon deserialization before using the
311 pub struct ChannelManager {
312 default_configuration: UserConfig,
313 genesis_hash: Sha256dHash,
314 fee_estimator: Arc<FeeEstimator>,
315 monitor: Arc<ManyChannelMonitor>,
316 chain_monitor: Arc<ChainWatchInterface>,
317 tx_broadcaster: Arc<BroadcasterInterface>,
320 pub(super) latest_block_height: AtomicUsize,
322 latest_block_height: AtomicUsize,
323 last_block_hash: Mutex<Sha256dHash>,
324 secp_ctx: Secp256k1<secp256k1::All>,
327 pub(super) channel_state: Mutex<ChannelHolder>,
329 channel_state: Mutex<ChannelHolder>,
330 our_network_key: SecretKey,
332 pending_events: Mutex<Vec<events::Event>>,
333 /// Used when we have to take a BIG lock to make sure everything is self-consistent.
334 /// Essentially just when we're serializing ourselves out.
335 /// Taken first everywhere where we are making changes before any other locks.
336 total_consistency_lock: RwLock<()>,
338 keys_manager: Arc<KeysInterface>,
343 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
344 /// HTLC's CLTV. This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
345 /// ie the node we forwarded the payment on to should always have enough room to reliably time out
346 /// the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
347 /// CLTV_CLAIM_BUFFER point (we static assert that its at least 3 blocks more).
348 const CLTV_EXPIRY_DELTA: u16 = 6 * 12; //TODO?
349 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 6 * 24 * 7; //TODO?
351 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + 2*HTLC_FAIL_TIMEOUT_BLOCKS +
352 // HTLC_FAIL_ANTI_REORG_DELAY, ie that if the next-hop peer fails the HTLC within
353 // HTLC_FAIL_TIMEOUT_BLOCKS then we'll still have HTLC_FAIL_TIMEOUT_BLOCKS left to fail it
354 // backwards ourselves before hitting the CLTV_CLAIM_BUFFER point and failing the channel
355 // on-chain to time out the HTLC.
358 const CHECK_CLTV_EXPIRY_SANITY: u32 = CLTV_EXPIRY_DELTA as u32 - 2*HTLC_FAIL_TIMEOUT_BLOCKS - CLTV_CLAIM_BUFFER - HTLC_FAIL_ANTI_REORG_DELAY;
360 // Check for ability of an attacker to make us fail on-chain by delaying inbound claim. See
361 // ChannelMontior::would_broadcast_at_height for a description of why this is needed.
364 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = CLTV_EXPIRY_DELTA as u32 - HTLC_FAIL_TIMEOUT_BLOCKS - 2*CLTV_CLAIM_BUFFER;
366 macro_rules! secp_call {
367 ( $res: expr, $err: expr ) => {
370 Err(_) => return Err($err),
375 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
376 pub struct ChannelDetails {
377 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
378 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
379 /// Note that this means this value is *not* persistent - it can change once during the
380 /// lifetime of the channel.
381 pub channel_id: [u8; 32],
382 /// The position of the funding transaction in the chain. None if the funding transaction has
383 /// not yet been confirmed and the channel fully opened.
384 pub short_channel_id: Option<u64>,
385 /// The node_id of our counterparty
386 pub remote_network_id: PublicKey,
387 /// The value, in satoshis, of this channel as appears in the funding output
388 pub channel_value_satoshis: u64,
389 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
393 macro_rules! handle_error {
394 ($self: ident, $internal: expr) => {
397 Err(MsgHandleErrInternal { err, shutdown_finish }) => {
398 if let Some((shutdown_res, update_option)) = shutdown_finish {
399 $self.finish_force_close_channel(shutdown_res);
400 if let Some(update) = update_option {
401 let mut channel_state = $self.channel_state.lock().unwrap();
402 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
413 macro_rules! break_chan_entry {
414 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
417 Err(ChannelError::Ignore(msg)) => {
418 break Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
420 Err(ChannelError::Close(msg)) => {
421 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
422 let (channel_id, mut chan) = $entry.remove_entry();
423 if let Some(short_id) = chan.get_short_channel_id() {
424 $channel_state.short_to_id.remove(&short_id);
426 break Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
432 macro_rules! try_chan_entry {
433 ($self: ident, $res: expr, $channel_state: expr, $entry: expr) => {
436 Err(ChannelError::Ignore(msg)) => {
437 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), $entry.key().clone()))
439 Err(ChannelError::Close(msg)) => {
440 log_trace!($self, "Closing channel {} due to Close-required error: {}", log_bytes!($entry.key()[..]), msg);
441 let (channel_id, mut chan) = $entry.remove_entry();
442 if let Some(short_id) = chan.get_short_channel_id() {
443 $channel_state.short_to_id.remove(&short_id);
445 return Err(MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
451 macro_rules! return_monitor_err {
452 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
453 return_monitor_err!($self, $err, $channel_state, $entry, $action_type, $resend_raa, $resend_commitment, Vec::new(), Vec::new())
455 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr, $failed_forwards: expr, $failed_fails: expr) => {
457 ChannelMonitorUpdateErr::PermanentFailure => {
458 let (channel_id, mut chan) = $entry.remove_entry();
459 if let Some(short_id) = chan.get_short_channel_id() {
460 $channel_state.short_to_id.remove(&short_id);
462 // TODO: $failed_fails is dropped here, which will cause other channels to hit the
463 // chain in a confused state! We need to move them into the ChannelMonitor which
464 // will be responsible for failing backwards once things confirm on-chain.
465 // It's ok that we drop $failed_forwards here - at this point we'd rather they
466 // broadcast HTLC-Timeout and pay the associated fees to get their funds back than
467 // us bother trying to claim it just to forward on to another peer. If we're
468 // splitting hairs we'd prefer to claim payments that were to us, but we haven't
469 // given up the preimage yet, so might as well just wait until the payment is
470 // retried, avoiding the on-chain fees.
471 return Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
473 ChannelMonitorUpdateErr::TemporaryFailure => {
474 $entry.get_mut().monitor_update_failed($action_type, $resend_raa, $resend_commitment, $failed_forwards, $failed_fails);
475 return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore("Failed to update ChannelMonitor"), *$entry.key()));
481 // Does not break in case of TemporaryFailure!
482 macro_rules! maybe_break_monitor_err {
483 ($self: ident, $err: expr, $channel_state: expr, $entry: expr, $action_type: path, $resend_raa: expr, $resend_commitment: expr) => {
485 ChannelMonitorUpdateErr::PermanentFailure => {
486 let (channel_id, mut chan) = $entry.remove_entry();
487 if let Some(short_id) = chan.get_short_channel_id() {
488 $channel_state.short_to_id.remove(&short_id);
490 break Err(MsgHandleErrInternal::from_finish_shutdown("ChannelMonitor storage failure", channel_id, chan.force_shutdown(), $self.get_channel_update(&chan).ok()))
492 ChannelMonitorUpdateErr::TemporaryFailure => {
493 $entry.get_mut().monitor_update_failed($action_type, $resend_raa, $resend_commitment, Vec::new(), Vec::new());
499 impl ChannelManager {
500 /// Constructs a new ChannelManager to hold several channels and route between them.
502 /// This is the main "logic hub" for all channel-related actions, and implements
503 /// ChannelMessageHandler.
505 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
507 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
508 pub fn new(network: Network, feeest: Arc<FeeEstimator>, monitor: Arc<ManyChannelMonitor>, chain_monitor: Arc<ChainWatchInterface>, tx_broadcaster: Arc<BroadcasterInterface>, logger: Arc<Logger>,keys_manager: Arc<KeysInterface>, config: UserConfig) -> Result<Arc<ChannelManager>, secp256k1::Error> {
509 let secp_ctx = Secp256k1::new();
511 let res = Arc::new(ChannelManager {
512 default_configuration: config.clone(),
513 genesis_hash: genesis_block(network).header.bitcoin_hash(),
514 fee_estimator: feeest.clone(),
515 monitor: monitor.clone(),
519 latest_block_height: AtomicUsize::new(0), //TODO: Get an init value
520 last_block_hash: Mutex::new(Default::default()),
523 channel_state: Mutex::new(ChannelHolder{
524 by_id: HashMap::new(),
525 short_to_id: HashMap::new(),
526 next_forward: Instant::now(),
527 forward_htlcs: HashMap::new(),
528 claimable_htlcs: HashMap::new(),
529 pending_msg_events: Vec::new(),
531 our_network_key: keys_manager.get_node_secret(),
533 pending_events: Mutex::new(Vec::new()),
534 total_consistency_lock: RwLock::new(()),
540 let weak_res = Arc::downgrade(&res);
541 res.chain_monitor.register_listener(weak_res);
545 /// Creates a new outbound channel to the given remote node and with the given value.
547 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
548 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
549 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
550 /// may wish to avoid using 0 for user_id here.
552 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
553 /// PeerManager::process_events afterwards.
555 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
556 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
557 pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_id: u64) -> Result<(), APIError> {
558 if channel_value_satoshis < 1000 {
559 return Err(APIError::APIMisuseError { err: "channel_value must be at least 1000 satoshis" });
562 let channel = Channel::new_outbound(&*self.fee_estimator, &self.keys_manager, their_network_key, channel_value_satoshis, push_msat, user_id, Arc::clone(&self.logger), &self.default_configuration)?;
563 let res = channel.get_open_channel(self.genesis_hash.clone(), &*self.fee_estimator);
565 let _ = self.total_consistency_lock.read().unwrap();
566 let mut channel_state = self.channel_state.lock().unwrap();
567 match channel_state.by_id.entry(channel.channel_id()) {
568 hash_map::Entry::Occupied(_) => {
569 if cfg!(feature = "fuzztarget") {
570 return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG" });
572 panic!("RNG is bad???");
575 hash_map::Entry::Vacant(entry) => { entry.insert(channel); }
577 channel_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
578 node_id: their_network_key,
584 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
585 /// more information.
586 pub fn list_channels(&self) -> Vec<ChannelDetails> {
587 let channel_state = self.channel_state.lock().unwrap();
588 let mut res = Vec::with_capacity(channel_state.by_id.len());
589 for (channel_id, channel) in channel_state.by_id.iter() {
590 res.push(ChannelDetails {
591 channel_id: (*channel_id).clone(),
592 short_channel_id: channel.get_short_channel_id(),
593 remote_network_id: channel.get_their_node_id(),
594 channel_value_satoshis: channel.get_value_satoshis(),
595 user_id: channel.get_user_id(),
601 /// Gets the list of usable channels, in random order. Useful as an argument to
602 /// Router::get_route to ensure non-announced channels are used.
603 pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
604 let channel_state = self.channel_state.lock().unwrap();
605 let mut res = Vec::with_capacity(channel_state.by_id.len());
606 for (channel_id, channel) in channel_state.by_id.iter() {
607 // Note we use is_live here instead of usable which leads to somewhat confused
608 // internal/external nomenclature, but that's ok cause that's probably what the user
609 // really wanted anyway.
610 if channel.is_live() {
611 res.push(ChannelDetails {
612 channel_id: (*channel_id).clone(),
613 short_channel_id: channel.get_short_channel_id(),
614 remote_network_id: channel.get_their_node_id(),
615 channel_value_satoshis: channel.get_value_satoshis(),
616 user_id: channel.get_user_id(),
623 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
624 /// will be accepted on the given channel, and after additional timeout/the closing of all
625 /// pending HTLCs, the channel will be closed on chain.
627 /// May generate a SendShutdown message event on success, which should be relayed.
628 pub fn close_channel(&self, channel_id: &[u8; 32]) -> Result<(), APIError> {
629 let _ = self.total_consistency_lock.read().unwrap();
631 let (mut failed_htlcs, chan_option) = {
632 let mut channel_state_lock = self.channel_state.lock().unwrap();
633 let channel_state = channel_state_lock.borrow_parts();
634 match channel_state.by_id.entry(channel_id.clone()) {
635 hash_map::Entry::Occupied(mut chan_entry) => {
636 let (shutdown_msg, failed_htlcs) = chan_entry.get_mut().get_shutdown()?;
637 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
638 node_id: chan_entry.get().get_their_node_id(),
641 if chan_entry.get().is_shutdown() {
642 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
643 channel_state.short_to_id.remove(&short_id);
645 (failed_htlcs, Some(chan_entry.remove_entry().1))
646 } else { (failed_htlcs, None) }
648 hash_map::Entry::Vacant(_) => return Err(APIError::ChannelUnavailable{err: "No such channel"})
651 for htlc_source in failed_htlcs.drain(..) {
652 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
654 let chan_update = if let Some(chan) = chan_option {
655 if let Ok(update) = self.get_channel_update(&chan) {
660 if let Some(update) = chan_update {
661 let mut channel_state = self.channel_state.lock().unwrap();
662 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
671 fn finish_force_close_channel(&self, shutdown_res: ShutdownResult) {
672 let (local_txn, mut failed_htlcs) = shutdown_res;
673 log_trace!(self, "Finishing force-closure of channel with {} transactions to broadcast and {} HTLCs to fail", local_txn.len(), failed_htlcs.len());
674 for htlc_source in failed_htlcs.drain(..) {
675 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
677 for tx in local_txn {
678 self.tx_broadcaster.broadcast_transaction(&tx);
682 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
683 /// the chain and rejecting new HTLCs on the given channel.
684 pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
685 let _ = self.total_consistency_lock.read().unwrap();
688 let mut channel_state_lock = self.channel_state.lock().unwrap();
689 let channel_state = channel_state_lock.borrow_parts();
690 if let Some(chan) = channel_state.by_id.remove(channel_id) {
691 if let Some(short_id) = chan.get_short_channel_id() {
692 channel_state.short_to_id.remove(&short_id);
699 log_trace!(self, "Force-closing channel {}", log_bytes!(channel_id[..]));
700 self.finish_force_close_channel(chan.force_shutdown());
701 if let Ok(update) = self.get_channel_update(&chan) {
702 let mut channel_state = self.channel_state.lock().unwrap();
703 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
709 /// Force close all channels, immediately broadcasting the latest local commitment transaction
710 /// for each to the chain and rejecting new HTLCs on each.
711 pub fn force_close_all_channels(&self) {
712 for chan in self.list_channels() {
713 self.force_close_channel(&chan.channel_id);
717 const ZERO:[u8; 65] = [0; 65];
718 fn decode_update_add_htlc_onion(&self, msg: &msgs::UpdateAddHTLC) -> (PendingHTLCStatus, MutexGuard<ChannelHolder>) {
719 macro_rules! return_malformed_err {
720 ($msg: expr, $err_code: expr) => {
722 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
723 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
724 channel_id: msg.channel_id,
725 htlc_id: msg.htlc_id,
726 sha256_of_onion: Sha256::hash(&msg.onion_routing_packet.hop_data).into_inner(),
727 failure_code: $err_code,
728 })), self.channel_state.lock().unwrap());
733 if let Err(_) = msg.onion_routing_packet.public_key {
734 return_malformed_err!("invalid ephemeral pubkey", 0x8000 | 0x4000 | 6);
737 let shared_secret = {
738 let mut arr = [0; 32];
739 arr.copy_from_slice(&SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &self.our_network_key)[..]);
742 let (rho, mu) = onion_utils::gen_rho_mu_from_shared_secret(&shared_secret);
744 if msg.onion_routing_packet.version != 0 {
745 //TODO: Spec doesn't indicate if we should only hash hop_data here (and in other
746 //sha256_of_onion error data packets), or the entire onion_routing_packet. Either way,
747 //the hash doesn't really serve any purpuse - in the case of hashing all data, the
748 //receiving node would have to brute force to figure out which version was put in the
749 //packet by the node that send us the message, in the case of hashing the hop_data, the
750 //node knows the HMAC matched, so they already know what is there...
751 return_malformed_err!("Unknown onion packet version", 0x8000 | 0x4000 | 4);
754 let mut hmac = HmacEngine::<Sha256>::new(&mu);
755 hmac.input(&msg.onion_routing_packet.hop_data);
756 hmac.input(&msg.payment_hash.0[..]);
757 if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &msg.onion_routing_packet.hmac) {
758 return_malformed_err!("HMAC Check failed", 0x8000 | 0x4000 | 5);
761 let mut channel_state = None;
762 macro_rules! return_err {
763 ($msg: expr, $err_code: expr, $data: expr) => {
765 log_info!(self, "Failed to accept/forward incoming HTLC: {}", $msg);
766 if channel_state.is_none() {
767 channel_state = Some(self.channel_state.lock().unwrap());
769 return (PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
770 channel_id: msg.channel_id,
771 htlc_id: msg.htlc_id,
772 reason: onion_utils::build_first_hop_failure_packet(&shared_secret, $err_code, $data),
773 })), channel_state.unwrap());
778 let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
779 let next_hop_data = {
780 let mut decoded = [0; 65];
781 chacha.process(&msg.onion_routing_packet.hop_data[0..65], &mut decoded);
782 match msgs::OnionHopData::read(&mut Cursor::new(&decoded[..])) {
784 let error_code = match err {
785 msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
786 _ => 0x2000 | 2, // Should never happen
788 return_err!("Unable to decode our hop data", error_code, &[0;0]);
794 let pending_forward_info = if next_hop_data.hmac == [0; 32] {
796 // final_expiry_too_soon
797 if (msg.cltv_expiry as u64) < self.latest_block_height.load(Ordering::Acquire) as u64 + (CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS) as u64 {
798 return_err!("The final CLTV expiry is too soon to handle", 17, &[0;0]);
800 // final_incorrect_htlc_amount
801 if next_hop_data.data.amt_to_forward > msg.amount_msat {
802 return_err!("Upstream node sent less than we were supposed to receive in payment", 19, &byte_utils::be64_to_array(msg.amount_msat));
804 // final_incorrect_cltv_expiry
805 if next_hop_data.data.outgoing_cltv_value != msg.cltv_expiry {
806 return_err!("Upstream node set CLTV to the wrong value", 18, &byte_utils::be32_to_array(msg.cltv_expiry));
809 // Note that we could obviously respond immediately with an update_fulfill_htlc
810 // message, however that would leak that we are the recipient of this payment, so
811 // instead we stay symmetric with the forwarding case, only responding (after a
812 // delay) once they've send us a commitment_signed!
814 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
816 payment_hash: msg.payment_hash.clone(),
818 incoming_shared_secret: shared_secret,
819 amt_to_forward: next_hop_data.data.amt_to_forward,
820 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
823 let mut new_packet_data = [0; 20*65];
824 chacha.process(&msg.onion_routing_packet.hop_data[65..], &mut new_packet_data[0..19*65]);
825 chacha.process(&ChannelManager::ZERO[..], &mut new_packet_data[19*65..]);
827 let mut new_pubkey = msg.onion_routing_packet.public_key.unwrap();
829 let blinding_factor = {
830 let mut sha = Sha256::engine();
831 sha.input(&new_pubkey.serialize()[..]);
832 sha.input(&shared_secret);
833 Sha256::from_engine(sha).into_inner()
836 let public_key = if let Err(e) = new_pubkey.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
838 } else { Ok(new_pubkey) };
840 let outgoing_packet = msgs::OnionPacket {
843 hop_data: new_packet_data,
844 hmac: next_hop_data.hmac.clone(),
847 PendingHTLCStatus::Forward(PendingForwardHTLCInfo {
848 onion_packet: Some(outgoing_packet),
849 payment_hash: msg.payment_hash.clone(),
850 short_channel_id: next_hop_data.data.short_channel_id,
851 incoming_shared_secret: shared_secret,
852 amt_to_forward: next_hop_data.data.amt_to_forward,
853 outgoing_cltv_value: next_hop_data.data.outgoing_cltv_value,
857 channel_state = Some(self.channel_state.lock().unwrap());
858 if let &PendingHTLCStatus::Forward(PendingForwardHTLCInfo { ref onion_packet, ref short_channel_id, ref amt_to_forward, ref outgoing_cltv_value, .. }) = &pending_forward_info {
859 if onion_packet.is_some() { // If short_channel_id is 0 here, we'll reject them in the body here
860 let id_option = channel_state.as_ref().unwrap().short_to_id.get(&short_channel_id).cloned();
861 let forwarding_id = match id_option {
862 None => { // unknown_next_peer
863 return_err!("Don't have available channel for forwarding as requested.", 0x4000 | 10, &[0;0]);
865 Some(id) => id.clone(),
867 if let Some((err, code, chan_update)) = loop {
868 let chan = channel_state.as_mut().unwrap().by_id.get_mut(&forwarding_id).unwrap();
870 // Note that we could technically not return an error yet here and just hope
871 // that the connection is reestablished or monitor updated by the time we get
872 // around to doing the actual forward, but better to fail early if we can and
873 // hopefully an attacker trying to path-trace payments cannot make this occur
874 // on a small/per-node/per-channel scale.
875 if !chan.is_live() { // channel_disabled
876 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 20, Some(self.get_channel_update(chan).unwrap())));
878 if *amt_to_forward < chan.get_their_htlc_minimum_msat() { // amount_below_minimum
879 break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, Some(self.get_channel_update(chan).unwrap())));
881 let fee = amt_to_forward.checked_mul(chan.get_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) });
882 if fee.is_none() || msg.amount_msat < fee.unwrap() || (msg.amount_msat - fee.unwrap()) < *amt_to_forward { // fee_insufficient
883 break Some(("Prior hop has deviated from specified fees parameters or origin node has obsolete ones", 0x1000 | 12, Some(self.get_channel_update(chan).unwrap())));
885 if (msg.cltv_expiry as u64) < (*outgoing_cltv_value) as u64 + CLTV_EXPIRY_DELTA as u64 { // incorrect_cltv_expiry
886 break Some(("Forwarding node has tampered with the intended HTLC values or origin node has an obsolete cltv_expiry_delta", 0x1000 | 13, Some(self.get_channel_update(chan).unwrap())));
888 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
889 // We want to have at least HTLC_FAIL_TIMEOUT_BLOCKS to fail prior to going on chain CLAIM_BUFFER blocks before expiration
890 if msg.cltv_expiry <= cur_height + CLTV_CLAIM_BUFFER + HTLC_FAIL_TIMEOUT_BLOCKS as u32 { // expiry_too_soon
891 break Some(("CLTV expiry is too close", 0x1000 | 14, Some(self.get_channel_update(chan).unwrap())));
893 if msg.cltv_expiry > cur_height + CLTV_FAR_FAR_AWAY as u32 { // expiry_too_far
894 break Some(("CLTV expiry is too far in the future", 21, None));
899 let mut res = Vec::with_capacity(8 + 128);
900 if let Some(chan_update) = chan_update {
901 if code == 0x1000 | 11 || code == 0x1000 | 12 {
902 res.extend_from_slice(&byte_utils::be64_to_array(msg.amount_msat));
904 else if code == 0x1000 | 13 {
905 res.extend_from_slice(&byte_utils::be32_to_array(msg.cltv_expiry));
907 else if code == 0x1000 | 20 {
908 res.extend_from_slice(&byte_utils::be16_to_array(chan_update.contents.flags));
910 res.extend_from_slice(&chan_update.encode_with_len()[..]);
912 return_err!(err, code, &res[..]);
917 (pending_forward_info, channel_state.unwrap())
920 /// only fails if the channel does not yet have an assigned short_id
921 /// May be called with channel_state already locked!
922 fn get_channel_update(&self, chan: &Channel) -> Result<msgs::ChannelUpdate, HandleError> {
923 let short_channel_id = match chan.get_short_channel_id() {
924 None => return Err(HandleError{err: "Channel not yet established", action: None}),
928 let were_node_one = PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key).serialize()[..] < chan.get_their_node_id().serialize()[..];
930 let unsigned = msgs::UnsignedChannelUpdate {
931 chain_hash: self.genesis_hash,
932 short_channel_id: short_channel_id,
933 timestamp: chan.get_channel_update_count(),
934 flags: (!were_node_one) as u16 | ((!chan.is_live() as u16) << 1),
935 cltv_expiry_delta: CLTV_EXPIRY_DELTA,
936 htlc_minimum_msat: chan.get_our_htlc_minimum_msat(),
937 fee_base_msat: chan.get_our_fee_base_msat(&*self.fee_estimator),
938 fee_proportional_millionths: chan.get_fee_proportional_millionths(),
939 excess_data: Vec::new(),
942 let msg_hash = Sha256dHash::from_data(&unsigned.encode()[..]);
943 let sig = self.secp_ctx.sign(&hash_to_message!(&msg_hash[..]), &self.our_network_key);
945 Ok(msgs::ChannelUpdate {
951 /// Sends a payment along a given route.
953 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
954 /// fields for more info.
956 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
957 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
958 /// next hop knows the preimage to payment_hash they can claim an additional amount as
959 /// specified in the last hop in the route! Thus, you should probably do your own
960 /// payment_preimage tracking (which you should already be doing as they represent "proof of
961 /// payment") and prevent double-sends yourself.
963 /// May generate a SendHTLCs message event on success, which should be relayed.
965 /// Raises APIError::RoutError when invalid route or forward parameter
966 /// (cltv_delta, fee, node public key) is specified.
967 /// Raises APIError::ChannelUnavailable if the next-hop channel is not available for updates
968 /// (including due to previous monitor update failure or new permanent monitor update failure).
969 /// Raised APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
970 /// relevant updates.
972 /// In case of APIError::RouteError/APIError::ChannelUnavailable, the payment send has failed
973 /// and you may wish to retry via a different route immediately.
974 /// In case of APIError::MonitorUpdateFailed, the commitment update has been irrevocably
975 /// committed on our end and we're just waiting for a monitor update to send it. Do NOT retry
976 /// the payment via a different route unless you intend to pay twice!
977 pub fn send_payment(&self, route: Route, payment_hash: PaymentHash) -> Result<(), APIError> {
978 if route.hops.len() < 1 || route.hops.len() > 20 {
979 return Err(APIError::RouteError{err: "Route didn't go anywhere/had bogus size"});
981 let our_node_id = self.get_our_node_id();
982 for (idx, hop) in route.hops.iter().enumerate() {
983 if idx != route.hops.len() - 1 && hop.pubkey == our_node_id {
984 return Err(APIError::RouteError{err: "Route went through us but wasn't a simple rebalance loop to us"});
988 let session_priv = self.keys_manager.get_session_key();
990 let cur_height = self.latest_block_height.load(Ordering::Acquire) as u32 + 1;
992 let onion_keys = secp_call!(onion_utils::construct_onion_keys(&self.secp_ctx, &route, &session_priv),
993 APIError::RouteError{err: "Pubkey along hop was maliciously selected"});
994 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height)?;
995 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
997 let _ = self.total_consistency_lock.read().unwrap();
999 let err: Result<(), _> = loop {
1000 let mut channel_lock = self.channel_state.lock().unwrap();
1002 let id = match channel_lock.short_to_id.get(&route.hops.first().unwrap().short_channel_id) {
1003 None => return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!"}),
1004 Some(id) => id.clone(),
1007 let channel_state = channel_lock.borrow_parts();
1008 if let hash_map::Entry::Occupied(mut chan) = channel_state.by_id.entry(id) {
1010 if chan.get().get_their_node_id() != route.hops.first().unwrap().pubkey {
1011 return Err(APIError::RouteError{err: "Node ID mismatch on first hop!"});
1013 if !chan.get().is_live() {
1014 return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected/pending monitor update!"});
1016 break_chan_entry!(self, chan.get_mut().send_htlc_and_commit(htlc_msat, payment_hash.clone(), htlc_cltv, HTLCSource::OutboundRoute {
1017 route: route.clone(),
1018 session_priv: session_priv.clone(),
1019 first_hop_htlc_msat: htlc_msat,
1020 }, onion_packet), channel_state, chan)
1022 Some((update_add, commitment_signed, chan_monitor)) => {
1023 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1024 maybe_break_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, true);
1025 // Note that MonitorUpdateFailed here indicates (per function docs)
1026 // that we will resent the commitment update once we unfree monitor
1027 // updating, so we have to take special care that we don't return
1028 // something else in case we will resend later!
1029 return Err(APIError::MonitorUpdateFailed);
1032 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1033 node_id: route.hops.first().unwrap().pubkey,
1034 updates: msgs::CommitmentUpdate {
1035 update_add_htlcs: vec![update_add],
1036 update_fulfill_htlcs: Vec::new(),
1037 update_fail_htlcs: Vec::new(),
1038 update_fail_malformed_htlcs: Vec::new(),
1046 } else { unreachable!(); }
1050 match handle_error!(self, err) {
1051 Ok(_) => unreachable!(),
1053 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
1055 log_error!(self, "Got bad keys: {}!", e.err);
1056 let mut channel_state = self.channel_state.lock().unwrap();
1057 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1058 node_id: route.hops.first().unwrap().pubkey,
1062 Err(APIError::ChannelUnavailable { err: e.err })
1067 /// Call this upon creation of a funding transaction for the given channel.
1069 /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
1070 /// or your counterparty can steal your funds!
1072 /// Panics if a funding transaction has already been provided for this channel.
1074 /// May panic if the funding_txo is duplicative with some other channel (note that this should
1075 /// be trivially prevented by using unique funding transaction keys per-channel).
1076 pub fn funding_transaction_generated(&self, temporary_channel_id: &[u8; 32], funding_txo: OutPoint) {
1077 let _ = self.total_consistency_lock.read().unwrap();
1079 let (chan, msg, chan_monitor) = {
1081 let mut channel_state = self.channel_state.lock().unwrap();
1082 match channel_state.by_id.remove(temporary_channel_id) {
1084 (chan.get_outbound_funding_created(funding_txo)
1085 .map_err(|e| if let ChannelError::Close(msg) = e {
1086 MsgHandleErrInternal::from_finish_shutdown(msg, chan.channel_id(), chan.force_shutdown(), None)
1087 } else { unreachable!(); })
1093 match handle_error!(self, res) {
1094 Ok(funding_msg) => {
1095 (chan, funding_msg.0, funding_msg.1)
1098 log_error!(self, "Got bad signatures: {}!", e.err);
1099 let mut channel_state = self.channel_state.lock().unwrap();
1100 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
1101 node_id: chan.get_their_node_id(),
1108 // Because we have exclusive ownership of the channel here we can release the channel_state
1109 // lock before add_update_monitor
1110 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1114 let mut channel_state = self.channel_state.lock().unwrap();
1115 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
1116 node_id: chan.get_their_node_id(),
1119 match channel_state.by_id.entry(chan.channel_id()) {
1120 hash_map::Entry::Occupied(_) => {
1121 panic!("Generated duplicate funding txid?");
1123 hash_map::Entry::Vacant(e) => {
1129 fn get_announcement_sigs(&self, chan: &Channel) -> Option<msgs::AnnouncementSignatures> {
1130 if !chan.should_announce() { return None }
1132 let (announcement, our_bitcoin_sig) = match chan.get_channel_announcement(self.get_our_node_id(), self.genesis_hash.clone()) {
1134 Err(_) => return None, // Only in case of state precondition violations eg channel is closing
1136 let msghash = hash_to_message!(&Sha256dHash::from_data(&announcement.encode()[..])[..]);
1137 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
1139 Some(msgs::AnnouncementSignatures {
1140 channel_id: chan.channel_id(),
1141 short_channel_id: chan.get_short_channel_id().unwrap(),
1142 node_signature: our_node_sig,
1143 bitcoin_signature: our_bitcoin_sig,
1147 /// Processes HTLCs which are pending waiting on random forward delay.
1149 /// Should only really ever be called in response to an PendingHTLCsForwardable event.
1150 /// Will likely generate further events.
1151 pub fn process_pending_htlc_forwards(&self) {
1152 let _ = self.total_consistency_lock.read().unwrap();
1154 let mut new_events = Vec::new();
1155 let mut failed_forwards = Vec::new();
1157 let mut channel_state_lock = self.channel_state.lock().unwrap();
1158 let channel_state = channel_state_lock.borrow_parts();
1160 if cfg!(not(feature = "fuzztarget")) && Instant::now() < *channel_state.next_forward {
1164 for (short_chan_id, mut pending_forwards) in channel_state.forward_htlcs.drain() {
1165 if short_chan_id != 0 {
1166 let forward_chan_id = match channel_state.short_to_id.get(&short_chan_id) {
1167 Some(chan_id) => chan_id.clone(),
1169 failed_forwards.reserve(pending_forwards.len());
1170 for forward_info in pending_forwards.drain(..) {
1171 match forward_info {
1172 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info } => {
1173 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1174 short_channel_id: prev_short_channel_id,
1175 htlc_id: prev_htlc_id,
1176 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1178 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x4000 | 10, None));
1180 HTLCForwardInfo::FailHTLC { .. } => {
1181 // Channel went away before we could fail it. This implies
1182 // the channel is now on chain and our counterparty is
1183 // trying to broadcast the HTLC-Timeout, but that's their
1184 // problem, not ours.
1191 let forward_chan = &mut channel_state.by_id.get_mut(&forward_chan_id).unwrap();
1193 let mut add_htlc_msgs = Vec::new();
1194 let mut fail_htlc_msgs = Vec::new();
1195 for forward_info in pending_forwards.drain(..) {
1196 match forward_info {
1197 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info } => {
1198 log_trace!(self, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", log_bytes!(forward_info.payment_hash.0), prev_short_channel_id, short_chan_id);
1199 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
1200 short_channel_id: prev_short_channel_id,
1201 htlc_id: prev_htlc_id,
1202 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1204 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()) {
1206 if let ChannelError::Ignore(msg) = e {
1207 log_trace!(self, "Failed to forward HTLC with payment_hash {}: {}", log_bytes!(forward_info.payment_hash.0), msg);
1209 panic!("Stated return value requirements in send_htlc() were not met");
1211 let chan_update = self.get_channel_update(forward_chan).unwrap();
1212 failed_forwards.push((htlc_source, forward_info.payment_hash, 0x1000 | 7, Some(chan_update)));
1217 Some(msg) => { add_htlc_msgs.push(msg); },
1219 // Nothing to do here...we're waiting on a remote
1220 // revoke_and_ack before we can add anymore HTLCs. The Channel
1221 // will automatically handle building the update_add_htlc and
1222 // commitment_signed messages when we can.
1223 // TODO: Do some kind of timer to set the channel as !is_live()
1224 // as we don't really want others relying on us relaying through
1225 // this channel currently :/.
1231 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
1232 log_trace!(self, "Failing HTLC back to channel with short id {} after delay", short_chan_id);
1233 match forward_chan.get_update_fail_htlc(htlc_id, err_packet) {
1235 if let ChannelError::Ignore(msg) = e {
1236 log_trace!(self, "Failed to fail backwards to short_id {}: {}", short_chan_id, msg);
1238 panic!("Stated return value requirements in get_update_fail_htlc() were not met");
1240 // fail-backs are best-effort, we probably already have one
1241 // pending, and if not that's OK, if not, the channel is on
1242 // the chain and sending the HTLC-Timeout is their problem.
1245 Ok(Some(msg)) => { fail_htlc_msgs.push(msg); },
1247 // Nothing to do here...we're waiting on a remote
1248 // revoke_and_ack before we can update the commitment
1249 // transaction. The Channel will automatically handle
1250 // building the update_fail_htlc and commitment_signed
1251 // messages when we can.
1252 // We don't need any kind of timer here as they should fail
1253 // the channel onto the chain if they can't get our
1254 // update_fail_htlc in time, its not our problem.
1261 if !add_htlc_msgs.is_empty() || !fail_htlc_msgs.is_empty() {
1262 let (commitment_msg, monitor) = match forward_chan.send_commitment() {
1265 if let ChannelError::Ignore(_) = e {
1266 panic!("Stated return value requirements in send_commitment() were not met");
1268 //TODO: Handle...this is bad!
1272 if let Err(_e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
1275 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1276 node_id: forward_chan.get_their_node_id(),
1277 updates: msgs::CommitmentUpdate {
1278 update_add_htlcs: add_htlc_msgs,
1279 update_fulfill_htlcs: Vec::new(),
1280 update_fail_htlcs: fail_htlc_msgs,
1281 update_fail_malformed_htlcs: Vec::new(),
1283 commitment_signed: commitment_msg,
1288 for forward_info in pending_forwards.drain(..) {
1289 match forward_info {
1290 HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info } => {
1291 let prev_hop_data = HTLCPreviousHopData {
1292 short_channel_id: prev_short_channel_id,
1293 htlc_id: prev_htlc_id,
1294 incoming_packet_shared_secret: forward_info.incoming_shared_secret,
1296 match channel_state.claimable_htlcs.entry(forward_info.payment_hash) {
1297 hash_map::Entry::Occupied(mut entry) => entry.get_mut().push(prev_hop_data),
1298 hash_map::Entry::Vacant(entry) => { entry.insert(vec![prev_hop_data]); },
1300 new_events.push(events::Event::PaymentReceived {
1301 payment_hash: forward_info.payment_hash,
1302 amt: forward_info.amt_to_forward,
1305 HTLCForwardInfo::FailHTLC { .. } => {
1306 panic!("Got pending fail of our own HTLC");
1314 for (htlc_source, payment_hash, failure_code, update) in failed_forwards.drain(..) {
1316 None => self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code, data: Vec::new() }),
1317 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() }),
1321 if new_events.is_empty() { return }
1322 let mut events = self.pending_events.lock().unwrap();
1323 events.append(&mut new_events);
1326 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
1327 /// after a PaymentReceived event.
1328 /// expected_value is the value you expected the payment to be for (not the amount it actually
1329 /// was for from the PaymentReceived event).
1330 pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash, expected_value: u64) -> bool {
1331 let _ = self.total_consistency_lock.read().unwrap();
1333 let mut channel_state = Some(self.channel_state.lock().unwrap());
1334 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(payment_hash);
1335 if let Some(mut sources) = removed_source {
1336 for htlc_with_hash in sources.drain(..) {
1337 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1338 self.fail_htlc_backwards_internal(channel_state.take().unwrap(),
1339 HTLCSource::PreviousHopData(htlc_with_hash), payment_hash,
1340 HTLCFailReason::Reason { failure_code: 0x4000 | 15, data: byte_utils::be64_to_array(expected_value).to_vec() });
1346 /// Fails an HTLC backwards to the sender of it to us.
1347 /// Note that while we take a channel_state lock as input, we do *not* assume consistency here.
1348 /// There are several callsites that do stupid things like loop over a list of payment_hashes
1349 /// to fail and take the channel_state lock for each iteration (as we take ownership and may
1350 /// drop it). In other words, no assumptions are made that entries in claimable_htlcs point to
1351 /// still-available channels.
1352 fn fail_htlc_backwards_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_hash: &PaymentHash, onion_error: HTLCFailReason) {
1353 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
1354 //identify whether we sent it or not based on the (I presume) very different runtime
1355 //between the branches here. We should make this async and move it into the forward HTLCs
1358 HTLCSource::OutboundRoute { ref route, .. } => {
1359 log_trace!(self, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1360 mem::drop(channel_state_lock);
1361 match &onion_error {
1362 &HTLCFailReason::ErrorPacket { ref err } => {
1364 let (channel_update, payment_retryable, onion_error_code) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
1366 let (channel_update, payment_retryable, _) = onion_utils::process_onion_failure(&self.secp_ctx, &self.logger, &source, err.data.clone());
1367 // TODO: If we decided to blame ourselves (or one of our channels) in
1368 // process_onion_failure we should close that channel as it implies our
1369 // next-hop is needlessly blaming us!
1370 if let Some(update) = channel_update {
1371 self.channel_state.lock().unwrap().pending_msg_events.push(
1372 events::MessageSendEvent::PaymentFailureNetworkUpdate {
1377 self.pending_events.lock().unwrap().push(
1378 events::Event::PaymentFailed {
1379 payment_hash: payment_hash.clone(),
1380 rejected_by_dest: !payment_retryable,
1382 error_code: onion_error_code
1386 &HTLCFailReason::Reason {
1390 // we get a fail_malformed_htlc from the first hop
1391 // TODO: We'd like to generate a PaymentFailureNetworkUpdate for temporary
1392 // failures here, but that would be insufficient as Router::get_route
1393 // generally ignores its view of our own channels as we provide them via
1395 // TODO: For non-temporary failures, we really should be closing the
1396 // channel here as we apparently can't relay through them anyway.
1397 self.pending_events.lock().unwrap().push(
1398 events::Event::PaymentFailed {
1399 payment_hash: payment_hash.clone(),
1400 rejected_by_dest: route.hops.len() == 1,
1402 error_code: Some(*failure_code),
1408 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, incoming_packet_shared_secret }) => {
1409 let err_packet = match onion_error {
1410 HTLCFailReason::Reason { failure_code, data } => {
1411 log_trace!(self, "Failing HTLC with payment_hash {} backwards from us with code {}", log_bytes!(payment_hash.0), failure_code);
1412 let packet = onion_utils::build_failure_packet(&incoming_packet_shared_secret, failure_code, &data[..]).encode();
1413 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &packet)
1415 HTLCFailReason::ErrorPacket { err } => {
1416 log_trace!(self, "Failing HTLC with payment_hash {} backwards with pre-built ErrorPacket", log_bytes!(payment_hash.0));
1417 onion_utils::encrypt_failure_packet(&incoming_packet_shared_secret, &err.data)
1421 let mut forward_event = None;
1422 if channel_state_lock.forward_htlcs.is_empty() {
1423 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));
1424 channel_state_lock.next_forward = forward_event.unwrap();
1426 match channel_state_lock.forward_htlcs.entry(short_channel_id) {
1427 hash_map::Entry::Occupied(mut entry) => {
1428 entry.get_mut().push(HTLCForwardInfo::FailHTLC { htlc_id, err_packet });
1430 hash_map::Entry::Vacant(entry) => {
1431 entry.insert(vec!(HTLCForwardInfo::FailHTLC { htlc_id, err_packet }));
1434 mem::drop(channel_state_lock);
1435 if let Some(time) = forward_event {
1436 let mut pending_events = self.pending_events.lock().unwrap();
1437 pending_events.push(events::Event::PendingHTLCsForwardable {
1438 time_forwardable: time
1445 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
1446 /// generating message events for the net layer to claim the payment, if possible. Thus, you
1447 /// should probably kick the net layer to go send messages if this returns true!
1449 /// May panic if called except in response to a PaymentReceived event.
1450 pub fn claim_funds(&self, payment_preimage: PaymentPreimage) -> bool {
1451 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1453 let _ = self.total_consistency_lock.read().unwrap();
1455 let mut channel_state = Some(self.channel_state.lock().unwrap());
1456 let removed_source = channel_state.as_mut().unwrap().claimable_htlcs.remove(&payment_hash);
1457 if let Some(mut sources) = removed_source {
1458 for htlc_with_hash in sources.drain(..) {
1459 if channel_state.is_none() { channel_state = Some(self.channel_state.lock().unwrap()); }
1460 self.claim_funds_internal(channel_state.take().unwrap(), HTLCSource::PreviousHopData(htlc_with_hash), payment_preimage);
1465 fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder>, source: HTLCSource, payment_preimage: PaymentPreimage) {
1467 HTLCSource::OutboundRoute { .. } => {
1468 mem::drop(channel_state_lock);
1469 let mut pending_events = self.pending_events.lock().unwrap();
1470 pending_events.push(events::Event::PaymentSent {
1474 HTLCSource::PreviousHopData(HTLCPreviousHopData { short_channel_id, htlc_id, .. }) => {
1475 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
1476 let channel_state = channel_state_lock.borrow_parts();
1478 let chan_id = match channel_state.short_to_id.get(&short_channel_id) {
1479 Some(chan_id) => chan_id.clone(),
1481 // TODO: There is probably a channel manager somewhere that needs to
1482 // learn the preimage as the channel already hit the chain and that's
1488 let chan = channel_state.by_id.get_mut(&chan_id).unwrap();
1489 match chan.get_update_fulfill_htlc_and_commit(htlc_id, payment_preimage) {
1490 Ok((msgs, monitor_option)) => {
1491 if let Some(chan_monitor) = monitor_option {
1492 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1493 unimplemented!();// but def dont push the event...
1496 if let Some((msg, commitment_signed)) = msgs {
1497 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1498 node_id: chan.get_their_node_id(),
1499 updates: msgs::CommitmentUpdate {
1500 update_add_htlcs: Vec::new(),
1501 update_fulfill_htlcs: vec![msg],
1502 update_fail_htlcs: Vec::new(),
1503 update_fail_malformed_htlcs: Vec::new(),
1511 // TODO: There is probably a channel manager somewhere that needs to
1512 // learn the preimage as the channel may be about to hit the chain.
1513 //TODO: Do something with e?
1521 /// Gets the node_id held by this ChannelManager
1522 pub fn get_our_node_id(&self) -> PublicKey {
1523 PublicKey::from_secret_key(&self.secp_ctx, &self.our_network_key)
1526 /// Used to restore channels to normal operation after a
1527 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
1529 pub fn test_restore_channel_monitor(&self) {
1530 let mut close_results = Vec::new();
1531 let mut htlc_forwards = Vec::new();
1532 let mut htlc_failures = Vec::new();
1533 let _ = self.total_consistency_lock.read().unwrap();
1536 let mut channel_lock = self.channel_state.lock().unwrap();
1537 let channel_state = channel_lock.borrow_parts();
1538 let short_to_id = channel_state.short_to_id;
1539 let pending_msg_events = channel_state.pending_msg_events;
1540 channel_state.by_id.retain(|_, channel| {
1541 if channel.is_awaiting_monitor_update() {
1542 let chan_monitor = channel.channel_monitor();
1543 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1545 ChannelMonitorUpdateErr::PermanentFailure => {
1546 // TODO: There may be some pending HTLCs that we intended to fail
1547 // backwards when a monitor update failed. We should make sure
1548 // knowledge of those gets moved into the appropriate in-memory
1549 // ChannelMonitor and they get failed backwards once we get
1550 // on-chain confirmations.
1551 // Note I think #198 addresses this, so once its merged a test
1552 // should be written.
1553 if let Some(short_id) = channel.get_short_channel_id() {
1554 short_to_id.remove(&short_id);
1556 close_results.push(channel.force_shutdown());
1557 if let Ok(update) = self.get_channel_update(&channel) {
1558 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1564 ChannelMonitorUpdateErr::TemporaryFailure => true,
1567 let (raa, commitment_update, order, pending_forwards, mut pending_failures) = channel.monitor_updating_restored();
1568 if !pending_forwards.is_empty() {
1569 htlc_forwards.push((channel.get_short_channel_id().expect("We can't have pending forwards before funding confirmation"), pending_forwards));
1571 htlc_failures.append(&mut pending_failures);
1573 macro_rules! handle_cs { () => {
1574 if let Some(update) = commitment_update {
1575 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1576 node_id: channel.get_their_node_id(),
1581 macro_rules! handle_raa { () => {
1582 if let Some(revoke_and_ack) = raa {
1583 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1584 node_id: channel.get_their_node_id(),
1585 msg: revoke_and_ack,
1590 RAACommitmentOrder::CommitmentFirst => {
1594 RAACommitmentOrder::RevokeAndACKFirst => {
1605 for failure in htlc_failures.drain(..) {
1606 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
1608 self.forward_htlcs(&mut htlc_forwards[..]);
1610 for res in close_results.drain(..) {
1611 self.finish_force_close_channel(res);
1615 fn internal_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
1616 if msg.chain_hash != self.genesis_hash {
1617 return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash", msg.temporary_channel_id.clone()));
1620 let channel = Channel::new_from_req(&*self.fee_estimator, &self.keys_manager, their_node_id.clone(), msg, 0, Arc::clone(&self.logger), &self.default_configuration)
1621 .map_err(|e| MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id))?;
1622 let mut channel_state_lock = self.channel_state.lock().unwrap();
1623 let channel_state = channel_state_lock.borrow_parts();
1624 match channel_state.by_id.entry(channel.channel_id()) {
1625 hash_map::Entry::Occupied(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision!", msg.temporary_channel_id.clone())),
1626 hash_map::Entry::Vacant(entry) => {
1627 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
1628 node_id: their_node_id.clone(),
1629 msg: channel.get_accept_channel(),
1631 entry.insert(channel);
1637 fn internal_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
1638 let (value, output_script, user_id) = {
1639 let mut channel_lock = self.channel_state.lock().unwrap();
1640 let channel_state = channel_lock.borrow_parts();
1641 match channel_state.by_id.entry(msg.temporary_channel_id) {
1642 hash_map::Entry::Occupied(mut chan) => {
1643 if chan.get().get_their_node_id() != *their_node_id {
1644 //TODO: see issue #153, need a consistent behavior on obnoxious behavior from random node
1645 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1647 try_chan_entry!(self, chan.get_mut().accept_channel(&msg, &self.default_configuration), channel_state, chan);
1648 (chan.get().get_value_satoshis(), chan.get().get_funding_redeemscript().to_v0_p2wsh(), chan.get().get_user_id())
1650 //TODO: same as above
1651 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1654 let mut pending_events = self.pending_events.lock().unwrap();
1655 pending_events.push(events::Event::FundingGenerationReady {
1656 temporary_channel_id: msg.temporary_channel_id,
1657 channel_value_satoshis: value,
1658 output_script: output_script,
1659 user_channel_id: user_id,
1664 fn internal_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
1665 let ((funding_msg, monitor_update), chan) = {
1666 let mut channel_lock = self.channel_state.lock().unwrap();
1667 let channel_state = channel_lock.borrow_parts();
1668 match channel_state.by_id.entry(msg.temporary_channel_id.clone()) {
1669 hash_map::Entry::Occupied(mut chan) => {
1670 if chan.get().get_their_node_id() != *their_node_id {
1671 //TODO: here and below MsgHandleErrInternal, #153 case
1672 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.temporary_channel_id));
1674 (try_chan_entry!(self, chan.get_mut().funding_created(msg), channel_state, chan), chan.remove())
1676 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.temporary_channel_id))
1679 // Because we have exclusive ownership of the channel here we can release the channel_state
1680 // lock before add_update_monitor
1681 if let Err(_e) = self.monitor.add_update_monitor(monitor_update.get_funding_txo().unwrap(), monitor_update) {
1684 let mut channel_state_lock = self.channel_state.lock().unwrap();
1685 let channel_state = channel_state_lock.borrow_parts();
1686 match channel_state.by_id.entry(funding_msg.channel_id) {
1687 hash_map::Entry::Occupied(_) => {
1688 return Err(MsgHandleErrInternal::send_err_msg_no_close("Already had channel with the new channel_id", funding_msg.channel_id))
1690 hash_map::Entry::Vacant(e) => {
1691 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
1692 node_id: their_node_id.clone(),
1701 fn internal_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
1702 let (funding_txo, user_id) = {
1703 let mut channel_lock = self.channel_state.lock().unwrap();
1704 let channel_state = channel_lock.borrow_parts();
1705 match channel_state.by_id.entry(msg.channel_id) {
1706 hash_map::Entry::Occupied(mut chan) => {
1707 if chan.get().get_their_node_id() != *their_node_id {
1708 //TODO: here and below MsgHandleErrInternal, #153 case
1709 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1711 let chan_monitor = try_chan_entry!(self, chan.get_mut().funding_signed(&msg), channel_state, chan);
1712 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1715 (chan.get().get_funding_txo().unwrap(), chan.get().get_user_id())
1717 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1720 let mut pending_events = self.pending_events.lock().unwrap();
1721 pending_events.push(events::Event::FundingBroadcastSafe {
1722 funding_txo: funding_txo,
1723 user_channel_id: user_id,
1728 fn internal_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), MsgHandleErrInternal> {
1729 let mut channel_state_lock = self.channel_state.lock().unwrap();
1730 let channel_state = channel_state_lock.borrow_parts();
1731 match channel_state.by_id.entry(msg.channel_id) {
1732 hash_map::Entry::Occupied(mut chan) => {
1733 if chan.get().get_their_node_id() != *their_node_id {
1734 //TODO: here and below MsgHandleErrInternal, #153 case
1735 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1737 try_chan_entry!(self, chan.get_mut().funding_locked(&msg), channel_state, chan);
1738 if let Some(announcement_sigs) = self.get_announcement_sigs(chan.get()) {
1739 channel_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
1740 node_id: their_node_id.clone(),
1741 msg: announcement_sigs,
1746 hash_map::Entry::Vacant(_) => Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1750 fn internal_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
1751 let (mut dropped_htlcs, chan_option) = {
1752 let mut channel_state_lock = self.channel_state.lock().unwrap();
1753 let channel_state = channel_state_lock.borrow_parts();
1755 match channel_state.by_id.entry(msg.channel_id.clone()) {
1756 hash_map::Entry::Occupied(mut chan_entry) => {
1757 if chan_entry.get().get_their_node_id() != *their_node_id {
1758 //TODO: here and below MsgHandleErrInternal, #153 case
1759 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1761 let (shutdown, closing_signed, dropped_htlcs) = try_chan_entry!(self, chan_entry.get_mut().shutdown(&*self.fee_estimator, &msg), channel_state, chan_entry);
1762 if let Some(msg) = shutdown {
1763 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
1764 node_id: their_node_id.clone(),
1768 if let Some(msg) = closing_signed {
1769 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1770 node_id: their_node_id.clone(),
1774 if chan_entry.get().is_shutdown() {
1775 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1776 channel_state.short_to_id.remove(&short_id);
1778 (dropped_htlcs, Some(chan_entry.remove_entry().1))
1779 } else { (dropped_htlcs, None) }
1781 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1784 for htlc_source in dropped_htlcs.drain(..) {
1785 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source.0, &htlc_source.1, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
1787 if let Some(chan) = chan_option {
1788 if let Ok(update) = self.get_channel_update(&chan) {
1789 let mut channel_state = self.channel_state.lock().unwrap();
1790 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1798 fn internal_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
1799 let (tx, chan_option) = {
1800 let mut channel_state_lock = self.channel_state.lock().unwrap();
1801 let channel_state = channel_state_lock.borrow_parts();
1802 match channel_state.by_id.entry(msg.channel_id.clone()) {
1803 hash_map::Entry::Occupied(mut chan_entry) => {
1804 if chan_entry.get().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 let (closing_signed, tx) = try_chan_entry!(self, chan_entry.get_mut().closing_signed(&*self.fee_estimator, &msg), channel_state, chan_entry);
1809 if let Some(msg) = closing_signed {
1810 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1811 node_id: their_node_id.clone(),
1816 // We're done with this channel, we've got a signed closing transaction and
1817 // will send the closing_signed back to the remote peer upon return. This
1818 // also implies there are no pending HTLCs left on the channel, so we can
1819 // fully delete it from tracking (the channel monitor is still around to
1820 // watch for old state broadcasts)!
1821 if let Some(short_id) = chan_entry.get().get_short_channel_id() {
1822 channel_state.short_to_id.remove(&short_id);
1824 (tx, Some(chan_entry.remove_entry().1))
1825 } else { (tx, None) }
1827 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1830 if let Some(broadcast_tx) = tx {
1831 self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
1833 if let Some(chan) = chan_option {
1834 if let Ok(update) = self.get_channel_update(&chan) {
1835 let mut channel_state = self.channel_state.lock().unwrap();
1836 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
1844 fn internal_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
1845 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
1846 //determine the state of the payment based on our response/if we forward anything/the time
1847 //we take to respond. We should take care to avoid allowing such an attack.
1849 //TODO: There exists a further attack where a node may garble the onion data, forward it to
1850 //us repeatedly garbled in different ways, and compare our error messages, which are
1851 //encrypted with the same key. Its not immediately obvious how to usefully exploit that,
1852 //but we should prevent it anyway.
1854 let (mut pending_forward_info, mut channel_state_lock) = self.decode_update_add_htlc_onion(msg);
1855 let channel_state = channel_state_lock.borrow_parts();
1857 match channel_state.by_id.entry(msg.channel_id) {
1858 hash_map::Entry::Occupied(mut chan) => {
1859 if chan.get().get_their_node_id() != *their_node_id {
1860 //TODO: here MsgHandleErrInternal, #153 case
1861 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1863 if !chan.get().is_usable() {
1864 // If the update_add is completely bogus, the call will Err and we will close,
1865 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
1866 // want to reject the new HTLC and fail it backwards instead of forwarding.
1867 if let PendingHTLCStatus::Forward(PendingForwardHTLCInfo { incoming_shared_secret, .. }) = pending_forward_info {
1868 let chan_update = self.get_channel_update(chan.get());
1869 pending_forward_info = PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
1870 channel_id: msg.channel_id,
1871 htlc_id: msg.htlc_id,
1872 reason: if let Ok(update) = chan_update {
1873 // TODO: Note that |20 is defined as "channel FROM the processing
1874 // node has been disabled" (emphasis mine), which seems to imply
1875 // that we can't return |20 for an inbound channel being disabled.
1876 // This probably needs a spec update but should definitely be
1878 onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x1000|20, &{
1879 let mut res = Vec::with_capacity(8 + 128);
1880 res.extend_from_slice(&byte_utils::be16_to_array(update.contents.flags));
1881 res.extend_from_slice(&update.encode_with_len()[..]);
1885 // This can only happen if the channel isn't in the fully-funded
1886 // state yet, implying our counterparty is trying to route payments
1887 // over the channel back to themselves (cause no one else should
1888 // know the short_id is a lightning channel yet). We should have no
1889 // problem just calling this unknown_next_peer
1890 onion_utils::build_first_hop_failure_packet(&incoming_shared_secret, 0x4000|10, &[])
1895 try_chan_entry!(self, chan.get_mut().update_add_htlc(&msg, pending_forward_info), channel_state, chan);
1897 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1902 fn internal_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
1903 let mut channel_lock = self.channel_state.lock().unwrap();
1905 let channel_state = channel_lock.borrow_parts();
1906 match channel_state.by_id.entry(msg.channel_id) {
1907 hash_map::Entry::Occupied(mut chan) => {
1908 if chan.get().get_their_node_id() != *their_node_id {
1909 //TODO: here and below MsgHandleErrInternal, #153 case
1910 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1912 try_chan_entry!(self, chan.get_mut().update_fulfill_htlc(&msg), channel_state, chan)
1914 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1917 self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
1921 fn internal_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
1922 let mut channel_lock = self.channel_state.lock().unwrap();
1923 let channel_state = channel_lock.borrow_parts();
1924 match channel_state.by_id.entry(msg.channel_id) {
1925 hash_map::Entry::Occupied(mut chan) => {
1926 if chan.get().get_their_node_id() != *their_node_id {
1927 //TODO: here and below MsgHandleErrInternal, #153 case
1928 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1930 try_chan_entry!(self, chan.get_mut().update_fail_htlc(&msg, HTLCFailReason::ErrorPacket { err: msg.reason.clone() }), channel_state, chan);
1932 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1937 fn internal_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
1938 let mut channel_lock = self.channel_state.lock().unwrap();
1939 let channel_state = channel_lock.borrow_parts();
1940 match channel_state.by_id.entry(msg.channel_id) {
1941 hash_map::Entry::Occupied(mut chan) => {
1942 if chan.get().get_their_node_id() != *their_node_id {
1943 //TODO: here and below MsgHandleErrInternal, #153 case
1944 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1946 if (msg.failure_code & 0x8000) == 0 {
1947 try_chan_entry!(self, Err(ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set")), channel_state, chan);
1949 try_chan_entry!(self, chan.get_mut().update_fail_malformed_htlc(&msg, HTLCFailReason::Reason { failure_code: msg.failure_code, data: Vec::new() }), channel_state, chan);
1952 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
1956 fn internal_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
1957 let mut channel_state_lock = self.channel_state.lock().unwrap();
1958 let channel_state = channel_state_lock.borrow_parts();
1959 match channel_state.by_id.entry(msg.channel_id) {
1960 hash_map::Entry::Occupied(mut chan) => {
1961 if chan.get().get_their_node_id() != *their_node_id {
1962 //TODO: here and below MsgHandleErrInternal, #153 case
1963 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
1965 let (revoke_and_ack, commitment_signed, closing_signed, chan_monitor) =
1966 try_chan_entry!(self, chan.get_mut().commitment_signed(&msg, &*self.fee_estimator), channel_state, chan);
1967 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
1968 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::RevokeAndACKFirst, true, commitment_signed.is_some());
1969 //TODO: Rebroadcast closing_signed if present on monitor update restoration
1971 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
1972 node_id: their_node_id.clone(),
1973 msg: revoke_and_ack,
1975 if let Some(msg) = commitment_signed {
1976 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
1977 node_id: their_node_id.clone(),
1978 updates: msgs::CommitmentUpdate {
1979 update_add_htlcs: Vec::new(),
1980 update_fulfill_htlcs: Vec::new(),
1981 update_fail_htlcs: Vec::new(),
1982 update_fail_malformed_htlcs: Vec::new(),
1984 commitment_signed: msg,
1988 if let Some(msg) = closing_signed {
1989 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
1990 node_id: their_node_id.clone(),
1996 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2001 fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, Vec<(PendingForwardHTLCInfo, u64)>)]) {
2002 for &mut (prev_short_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
2003 let mut forward_event = None;
2004 if !pending_forwards.is_empty() {
2005 let mut channel_state = self.channel_state.lock().unwrap();
2006 if channel_state.forward_htlcs.is_empty() {
2007 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));
2008 channel_state.next_forward = forward_event.unwrap();
2010 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
2011 match channel_state.forward_htlcs.entry(forward_info.short_channel_id) {
2012 hash_map::Entry::Occupied(mut entry) => {
2013 entry.get_mut().push(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info });
2015 hash_map::Entry::Vacant(entry) => {
2016 entry.insert(vec!(HTLCForwardInfo::AddHTLC { prev_short_channel_id, prev_htlc_id, forward_info }));
2021 match forward_event {
2023 let mut pending_events = self.pending_events.lock().unwrap();
2024 pending_events.push(events::Event::PendingHTLCsForwardable {
2025 time_forwardable: time
2033 fn internal_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
2034 let (pending_forwards, mut pending_failures, short_channel_id) = {
2035 let mut channel_state_lock = self.channel_state.lock().unwrap();
2036 let channel_state = channel_state_lock.borrow_parts();
2037 match channel_state.by_id.entry(msg.channel_id) {
2038 hash_map::Entry::Occupied(mut chan) => {
2039 if chan.get().get_their_node_id() != *their_node_id {
2040 //TODO: here and below MsgHandleErrInternal, #153 case
2041 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2043 let was_frozen_for_monitor = chan.get().is_awaiting_monitor_update();
2044 let (commitment_update, pending_forwards, pending_failures, closing_signed, chan_monitor) =
2045 try_chan_entry!(self, chan.get_mut().revoke_and_ack(&msg, &*self.fee_estimator), channel_state, chan);
2046 if let Err(e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2047 if was_frozen_for_monitor {
2048 assert!(commitment_update.is_none() && closing_signed.is_none() && pending_forwards.is_empty() && pending_failures.is_empty());
2049 return Err(MsgHandleErrInternal::ignore_no_close("Previous monitor update failure prevented responses to RAA"));
2051 return_monitor_err!(self, e, channel_state, chan, RAACommitmentOrder::CommitmentFirst, false, commitment_update.is_some(), pending_forwards, pending_failures);
2054 if let Some(updates) = commitment_update {
2055 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2056 node_id: their_node_id.clone(),
2060 if let Some(msg) = closing_signed {
2061 channel_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
2062 node_id: their_node_id.clone(),
2066 (pending_forwards, pending_failures, chan.get().get_short_channel_id().expect("RAA should only work on a short-id-available channel"))
2068 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2071 for failure in pending_failures.drain(..) {
2072 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), failure.0, &failure.1, failure.2);
2074 self.forward_htlcs(&mut [(short_channel_id, pending_forwards)]);
2079 fn internal_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
2080 let mut channel_lock = self.channel_state.lock().unwrap();
2081 let channel_state = channel_lock.borrow_parts();
2082 match channel_state.by_id.entry(msg.channel_id) {
2083 hash_map::Entry::Occupied(mut chan) => {
2084 if chan.get().get_their_node_id() != *their_node_id {
2085 //TODO: here and below MsgHandleErrInternal, #153 case
2086 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2088 try_chan_entry!(self, chan.get_mut().update_fee(&*self.fee_estimator, &msg), channel_state, chan);
2090 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2095 fn internal_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
2096 let mut channel_state_lock = self.channel_state.lock().unwrap();
2097 let channel_state = channel_state_lock.borrow_parts();
2099 match channel_state.by_id.entry(msg.channel_id) {
2100 hash_map::Entry::Occupied(mut chan) => {
2101 if chan.get().get_their_node_id() != *their_node_id {
2102 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2104 if !chan.get().is_usable() {
2105 return Err(MsgHandleErrInternal::from_no_close(HandleError{err: "Got an announcement_signatures before we were ready for it", action: Some(msgs::ErrorAction::IgnoreError)}));
2108 let our_node_id = self.get_our_node_id();
2109 let (announcement, our_bitcoin_sig) =
2110 try_chan_entry!(self, chan.get_mut().get_channel_announcement(our_node_id.clone(), self.genesis_hash.clone()), channel_state, chan);
2112 let were_node_one = announcement.node_id_1 == our_node_id;
2113 let msghash = hash_to_message!(&Sha256dHash::from_data(&announcement.encode()[..])[..]);
2114 if self.secp_ctx.verify(&msghash, &msg.node_signature, if were_node_one { &announcement.node_id_2 } else { &announcement.node_id_1 }).is_err() ||
2115 self.secp_ctx.verify(&msghash, &msg.bitcoin_signature, if were_node_one { &announcement.bitcoin_key_2 } else { &announcement.bitcoin_key_1 }).is_err() {
2116 try_chan_entry!(self, Err(ChannelError::Close("Bad announcement_signatures node_signature")), channel_state, chan);
2119 let our_node_sig = self.secp_ctx.sign(&msghash, &self.our_network_key);
2121 channel_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
2122 msg: msgs::ChannelAnnouncement {
2123 node_signature_1: if were_node_one { our_node_sig } else { msg.node_signature },
2124 node_signature_2: if were_node_one { msg.node_signature } else { our_node_sig },
2125 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { msg.bitcoin_signature },
2126 bitcoin_signature_2: if were_node_one { msg.bitcoin_signature } else { our_bitcoin_sig },
2127 contents: announcement,
2129 update_msg: self.get_channel_update(chan.get()).unwrap(), // can only fail if we're not in a ready state
2132 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2137 fn internal_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), MsgHandleErrInternal> {
2138 let mut channel_state_lock = self.channel_state.lock().unwrap();
2139 let channel_state = channel_state_lock.borrow_parts();
2141 match channel_state.by_id.entry(msg.channel_id) {
2142 hash_map::Entry::Occupied(mut chan) => {
2143 if chan.get().get_their_node_id() != *their_node_id {
2144 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!", msg.channel_id));
2146 let (funding_locked, revoke_and_ack, commitment_update, channel_monitor, mut order, shutdown) =
2147 try_chan_entry!(self, chan.get_mut().channel_reestablish(msg), channel_state, chan);
2148 if let Some(monitor) = channel_monitor {
2149 if let Err(e) = self.monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor) {
2150 // channel_reestablish doesn't guarantee the order it returns is sensical
2151 // for the messages it returns, but if we're setting what messages to
2152 // re-transmit on monitor update success, we need to make sure it is sane.
2153 if revoke_and_ack.is_none() {
2154 order = RAACommitmentOrder::CommitmentFirst;
2156 if commitment_update.is_none() {
2157 order = RAACommitmentOrder::RevokeAndACKFirst;
2159 return_monitor_err!(self, e, channel_state, chan, order, revoke_and_ack.is_some(), commitment_update.is_some());
2160 //TODO: Resend the funding_locked if needed once we get the monitor running again
2163 if let Some(msg) = funding_locked {
2164 channel_state.pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2165 node_id: their_node_id.clone(),
2169 macro_rules! send_raa { () => {
2170 if let Some(msg) = revoke_and_ack {
2171 channel_state.pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
2172 node_id: their_node_id.clone(),
2177 macro_rules! send_cu { () => {
2178 if let Some(updates) = commitment_update {
2179 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2180 node_id: their_node_id.clone(),
2186 RAACommitmentOrder::RevokeAndACKFirst => {
2190 RAACommitmentOrder::CommitmentFirst => {
2195 if let Some(msg) = shutdown {
2196 channel_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2197 node_id: their_node_id.clone(),
2203 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel", msg.channel_id))
2207 /// Begin Update fee process. Allowed only on an outbound channel.
2208 /// If successful, will generate a UpdateHTLCs event, so you should probably poll
2209 /// PeerManager::process_events afterwards.
2210 /// Note: This API is likely to change!
2212 pub fn update_fee(&self, channel_id: [u8;32], feerate_per_kw: u64) -> Result<(), APIError> {
2213 let _ = self.total_consistency_lock.read().unwrap();
2215 let err: Result<(), _> = loop {
2216 let mut channel_state_lock = self.channel_state.lock().unwrap();
2217 let channel_state = channel_state_lock.borrow_parts();
2219 match channel_state.by_id.entry(channel_id) {
2220 hash_map::Entry::Vacant(_) => return Err(APIError::APIMisuseError{err: "Failed to find corresponding channel"}),
2221 hash_map::Entry::Occupied(mut chan) => {
2222 if !chan.get().is_outbound() {
2223 return Err(APIError::APIMisuseError{err: "update_fee cannot be sent for an inbound channel"});
2225 if chan.get().is_awaiting_monitor_update() {
2226 return Err(APIError::MonitorUpdateFailed);
2228 if !chan.get().is_live() {
2229 return Err(APIError::ChannelUnavailable{err: "Channel is either not yet fully established or peer is currently disconnected"});
2231 their_node_id = chan.get().get_their_node_id();
2232 if let Some((update_fee, commitment_signed, chan_monitor)) =
2233 break_chan_entry!(self, chan.get_mut().send_update_fee_and_commit(feerate_per_kw), channel_state, chan)
2235 if let Err(_e) = self.monitor.add_update_monitor(chan_monitor.get_funding_txo().unwrap(), chan_monitor) {
2238 channel_state.pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
2239 node_id: chan.get().get_their_node_id(),
2240 updates: msgs::CommitmentUpdate {
2241 update_add_htlcs: Vec::new(),
2242 update_fulfill_htlcs: Vec::new(),
2243 update_fail_htlcs: Vec::new(),
2244 update_fail_malformed_htlcs: Vec::new(),
2245 update_fee: Some(update_fee),
2255 match handle_error!(self, err) {
2256 Ok(_) => unreachable!(),
2258 if let Some(msgs::ErrorAction::IgnoreError) = e.action {
2260 log_error!(self, "Got bad keys: {}!", e.err);
2261 let mut channel_state = self.channel_state.lock().unwrap();
2262 channel_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
2263 node_id: their_node_id,
2267 Err(APIError::APIMisuseError { err: e.err })
2273 impl events::MessageSendEventsProvider for ChannelManager {
2274 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2275 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2276 // user to serialize a ChannelManager with pending events in it and lose those events on
2277 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2279 //TODO: This behavior should be documented.
2280 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2281 if let Some(preimage) = htlc_update.payment_preimage {
2282 log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2283 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2285 log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2286 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2291 let mut ret = Vec::new();
2292 let mut channel_state = self.channel_state.lock().unwrap();
2293 mem::swap(&mut ret, &mut channel_state.pending_msg_events);
2298 impl events::EventsProvider for ChannelManager {
2299 fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
2300 // TODO: Event release to users and serialization is currently race-y: its very easy for a
2301 // user to serialize a ChannelManager with pending events in it and lose those events on
2302 // restart. This is doubly true for the fail/fulfill-backs from monitor events!
2304 //TODO: This behavior should be documented.
2305 for htlc_update in self.monitor.fetch_pending_htlc_updated() {
2306 if let Some(preimage) = htlc_update.payment_preimage {
2307 log_trace!(self, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2308 self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2310 log_trace!(self, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2311 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2316 let mut ret = Vec::new();
2317 let mut pending_events = self.pending_events.lock().unwrap();
2318 mem::swap(&mut ret, &mut *pending_events);
2323 impl ChainListener for ChannelManager {
2324 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
2325 let header_hash = header.bitcoin_hash();
2326 log_trace!(self, "Block {} at height {} connected with {} txn matched", header_hash, height, txn_matched.len());
2327 let _ = self.total_consistency_lock.read().unwrap();
2328 let mut failed_channels = Vec::new();
2330 let mut channel_lock = self.channel_state.lock().unwrap();
2331 let channel_state = channel_lock.borrow_parts();
2332 let short_to_id = channel_state.short_to_id;
2333 let pending_msg_events = channel_state.pending_msg_events;
2334 channel_state.by_id.retain(|_, channel| {
2335 let chan_res = channel.block_connected(header, height, txn_matched, indexes_of_txn_matched);
2336 if let Ok(Some(funding_locked)) = chan_res {
2337 pending_msg_events.push(events::MessageSendEvent::SendFundingLocked {
2338 node_id: channel.get_their_node_id(),
2339 msg: funding_locked,
2341 if let Some(announcement_sigs) = self.get_announcement_sigs(channel) {
2342 pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
2343 node_id: channel.get_their_node_id(),
2344 msg: announcement_sigs,
2347 short_to_id.insert(channel.get_short_channel_id().unwrap(), channel.channel_id());
2348 } else if let Err(e) = chan_res {
2349 pending_msg_events.push(events::MessageSendEvent::HandleError {
2350 node_id: channel.get_their_node_id(),
2351 action: Some(msgs::ErrorAction::SendErrorMessage { msg: e }),
2355 if let Some(funding_txo) = channel.get_funding_txo() {
2356 for tx in txn_matched {
2357 for inp in tx.input.iter() {
2358 if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
2359 log_trace!(self, "Detected channel-closing tx {} spending {}:{}, closing channel {}", tx.txid(), inp.previous_output.txid, inp.previous_output.vout, log_bytes!(channel.channel_id()));
2360 if let Some(short_id) = channel.get_short_channel_id() {
2361 short_to_id.remove(&short_id);
2363 // It looks like our counterparty went on-chain. We go ahead and
2364 // broadcast our latest local state as well here, just in case its
2365 // some kind of SPV attack, though we expect these to be dropped.
2366 failed_channels.push(channel.force_shutdown());
2367 if let Ok(update) = self.get_channel_update(&channel) {
2368 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2377 if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height) {
2378 if let Some(short_id) = channel.get_short_channel_id() {
2379 short_to_id.remove(&short_id);
2381 failed_channels.push(channel.force_shutdown());
2382 // If would_broadcast_at_height() is true, the channel_monitor will broadcast
2383 // the latest local tx for us, so we should skip that here (it doesn't really
2384 // hurt anything, but does make tests a bit simpler).
2385 failed_channels.last_mut().unwrap().0 = Vec::new();
2386 if let Ok(update) = self.get_channel_update(&channel) {
2387 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2396 for failure in failed_channels.drain(..) {
2397 self.finish_force_close_channel(failure);
2399 self.latest_block_height.store(height as usize, Ordering::Release);
2400 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header_hash;
2403 /// We force-close the channel without letting our counterparty participate in the shutdown
2404 fn block_disconnected(&self, header: &BlockHeader) {
2405 let _ = self.total_consistency_lock.read().unwrap();
2406 let mut failed_channels = Vec::new();
2408 let mut channel_lock = self.channel_state.lock().unwrap();
2409 let channel_state = channel_lock.borrow_parts();
2410 let short_to_id = channel_state.short_to_id;
2411 let pending_msg_events = channel_state.pending_msg_events;
2412 channel_state.by_id.retain(|_, v| {
2413 if v.block_disconnected(header) {
2414 if let Some(short_id) = v.get_short_channel_id() {
2415 short_to_id.remove(&short_id);
2417 failed_channels.push(v.force_shutdown());
2418 if let Ok(update) = self.get_channel_update(&v) {
2419 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2429 for failure in failed_channels.drain(..) {
2430 self.finish_force_close_channel(failure);
2432 self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
2433 *self.last_block_hash.try_lock().expect("block_(dis)connected must not be called in parallel") = header.bitcoin_hash();
2437 impl ChannelMessageHandler for ChannelManager {
2438 //TODO: Handle errors and close channel (or so)
2439 fn handle_open_channel(&self, their_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), HandleError> {
2440 let _ = self.total_consistency_lock.read().unwrap();
2441 handle_error!(self, self.internal_open_channel(their_node_id, msg))
2444 fn handle_accept_channel(&self, their_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
2445 let _ = self.total_consistency_lock.read().unwrap();
2446 handle_error!(self, self.internal_accept_channel(their_node_id, msg))
2449 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), HandleError> {
2450 let _ = self.total_consistency_lock.read().unwrap();
2451 handle_error!(self, self.internal_funding_created(their_node_id, msg))
2454 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), HandleError> {
2455 let _ = self.total_consistency_lock.read().unwrap();
2456 handle_error!(self, self.internal_funding_signed(their_node_id, msg))
2459 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) -> Result<(), HandleError> {
2460 let _ = self.total_consistency_lock.read().unwrap();
2461 handle_error!(self, self.internal_funding_locked(their_node_id, msg))
2464 fn handle_shutdown(&self, their_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), HandleError> {
2465 let _ = self.total_consistency_lock.read().unwrap();
2466 handle_error!(self, self.internal_shutdown(their_node_id, msg))
2469 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
2470 let _ = self.total_consistency_lock.read().unwrap();
2471 handle_error!(self, self.internal_closing_signed(their_node_id, msg))
2474 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), msgs::HandleError> {
2475 let _ = self.total_consistency_lock.read().unwrap();
2476 handle_error!(self, self.internal_update_add_htlc(their_node_id, msg))
2479 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
2480 let _ = self.total_consistency_lock.read().unwrap();
2481 handle_error!(self, self.internal_update_fulfill_htlc(their_node_id, msg))
2484 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
2485 let _ = self.total_consistency_lock.read().unwrap();
2486 handle_error!(self, self.internal_update_fail_htlc(their_node_id, msg))
2489 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
2490 let _ = self.total_consistency_lock.read().unwrap();
2491 handle_error!(self, self.internal_update_fail_malformed_htlc(their_node_id, msg))
2494 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
2495 let _ = self.total_consistency_lock.read().unwrap();
2496 handle_error!(self, self.internal_commitment_signed(their_node_id, msg))
2499 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
2500 let _ = self.total_consistency_lock.read().unwrap();
2501 handle_error!(self, self.internal_revoke_and_ack(their_node_id, msg))
2504 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), HandleError> {
2505 let _ = self.total_consistency_lock.read().unwrap();
2506 handle_error!(self, self.internal_update_fee(their_node_id, msg))
2509 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
2510 let _ = self.total_consistency_lock.read().unwrap();
2511 handle_error!(self, self.internal_announcement_signatures(their_node_id, msg))
2514 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
2515 let _ = self.total_consistency_lock.read().unwrap();
2516 handle_error!(self, self.internal_channel_reestablish(their_node_id, msg))
2519 fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
2520 let _ = self.total_consistency_lock.read().unwrap();
2521 let mut failed_channels = Vec::new();
2522 let mut failed_payments = Vec::new();
2524 let mut channel_state_lock = self.channel_state.lock().unwrap();
2525 let channel_state = channel_state_lock.borrow_parts();
2526 let short_to_id = channel_state.short_to_id;
2527 let pending_msg_events = channel_state.pending_msg_events;
2528 if no_connection_possible {
2529 log_debug!(self, "Failing all channels with {} due to no_connection_possible", log_pubkey!(their_node_id));
2530 channel_state.by_id.retain(|_, chan| {
2531 if chan.get_their_node_id() == *their_node_id {
2532 if let Some(short_id) = chan.get_short_channel_id() {
2533 short_to_id.remove(&short_id);
2535 failed_channels.push(chan.force_shutdown());
2536 if let Ok(update) = self.get_channel_update(&chan) {
2537 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2547 log_debug!(self, "Marking channels with {} disconnected and generating channel_updates", log_pubkey!(their_node_id));
2548 channel_state.by_id.retain(|_, chan| {
2549 if chan.get_their_node_id() == *their_node_id {
2550 //TODO: mark channel disabled (and maybe announce such after a timeout).
2551 let failed_adds = chan.remove_uncommitted_htlcs_and_mark_paused();
2552 if !failed_adds.is_empty() {
2553 let chan_update = self.get_channel_update(&chan).map(|u| u.encode_with_len()).unwrap(); // Cannot add/recv HTLCs before we have a short_id so unwrap is safe
2554 failed_payments.push((chan_update, failed_adds));
2556 if chan.is_shutdown() {
2557 if let Some(short_id) = chan.get_short_channel_id() {
2558 short_to_id.remove(&short_id);
2567 for failure in failed_channels.drain(..) {
2568 self.finish_force_close_channel(failure);
2570 for (chan_update, mut htlc_sources) in failed_payments {
2571 for (htlc_source, payment_hash) in htlc_sources.drain(..) {
2572 self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_source, &payment_hash, HTLCFailReason::Reason { failure_code: 0x1000 | 7, data: chan_update.clone() });
2577 fn peer_connected(&self, their_node_id: &PublicKey) {
2578 log_debug!(self, "Generating channel_reestablish events for {}", log_pubkey!(their_node_id));
2580 let _ = self.total_consistency_lock.read().unwrap();
2581 let mut channel_state_lock = self.channel_state.lock().unwrap();
2582 let channel_state = channel_state_lock.borrow_parts();
2583 let pending_msg_events = channel_state.pending_msg_events;
2584 channel_state.by_id.retain(|_, chan| {
2585 if chan.get_their_node_id() == *their_node_id {
2586 if !chan.have_received_message() {
2587 // If we created this (outbound) channel while we were disconnected from the
2588 // peer we probably failed to send the open_channel message, which is now
2589 // lost. We can't have had anything pending related to this channel, so we just
2593 pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
2594 node_id: chan.get_their_node_id(),
2595 msg: chan.get_channel_reestablish(),
2601 //TODO: Also re-broadcast announcement_signatures
2604 fn handle_error(&self, their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
2605 let _ = self.total_consistency_lock.read().unwrap();
2607 if msg.channel_id == [0; 32] {
2608 for chan in self.list_channels() {
2609 if chan.remote_network_id == *their_node_id {
2610 self.force_close_channel(&chan.channel_id);
2614 self.force_close_channel(&msg.channel_id);
2619 const SERIALIZATION_VERSION: u8 = 1;
2620 const MIN_SERIALIZATION_VERSION: u8 = 1;
2622 impl Writeable for PendingForwardHTLCInfo {
2623 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2624 if let &Some(ref onion) = &self.onion_packet {
2626 onion.write(writer)?;
2630 self.incoming_shared_secret.write(writer)?;
2631 self.payment_hash.write(writer)?;
2632 self.short_channel_id.write(writer)?;
2633 self.amt_to_forward.write(writer)?;
2634 self.outgoing_cltv_value.write(writer)?;
2639 impl<R: ::std::io::Read> Readable<R> for PendingForwardHTLCInfo {
2640 fn read(reader: &mut R) -> Result<PendingForwardHTLCInfo, DecodeError> {
2641 let onion_packet = match <u8 as Readable<R>>::read(reader)? {
2643 1 => Some(msgs::OnionPacket::read(reader)?),
2644 _ => return Err(DecodeError::InvalidValue),
2646 Ok(PendingForwardHTLCInfo {
2648 incoming_shared_secret: Readable::read(reader)?,
2649 payment_hash: Readable::read(reader)?,
2650 short_channel_id: Readable::read(reader)?,
2651 amt_to_forward: Readable::read(reader)?,
2652 outgoing_cltv_value: Readable::read(reader)?,
2657 impl Writeable for HTLCFailureMsg {
2658 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2660 &HTLCFailureMsg::Relay(ref fail_msg) => {
2662 fail_msg.write(writer)?;
2664 &HTLCFailureMsg::Malformed(ref fail_msg) => {
2666 fail_msg.write(writer)?;
2673 impl<R: ::std::io::Read> Readable<R> for HTLCFailureMsg {
2674 fn read(reader: &mut R) -> Result<HTLCFailureMsg, DecodeError> {
2675 match <u8 as Readable<R>>::read(reader)? {
2676 0 => Ok(HTLCFailureMsg::Relay(Readable::read(reader)?)),
2677 1 => Ok(HTLCFailureMsg::Malformed(Readable::read(reader)?)),
2678 _ => Err(DecodeError::InvalidValue),
2683 impl Writeable for PendingHTLCStatus {
2684 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2686 &PendingHTLCStatus::Forward(ref forward_info) => {
2688 forward_info.write(writer)?;
2690 &PendingHTLCStatus::Fail(ref fail_msg) => {
2692 fail_msg.write(writer)?;
2699 impl<R: ::std::io::Read> Readable<R> for PendingHTLCStatus {
2700 fn read(reader: &mut R) -> Result<PendingHTLCStatus, DecodeError> {
2701 match <u8 as Readable<R>>::read(reader)? {
2702 0 => Ok(PendingHTLCStatus::Forward(Readable::read(reader)?)),
2703 1 => Ok(PendingHTLCStatus::Fail(Readable::read(reader)?)),
2704 _ => Err(DecodeError::InvalidValue),
2709 impl_writeable!(HTLCPreviousHopData, 0, {
2712 incoming_packet_shared_secret
2715 impl Writeable for HTLCSource {
2716 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2718 &HTLCSource::PreviousHopData(ref hop_data) => {
2720 hop_data.write(writer)?;
2722 &HTLCSource::OutboundRoute { ref route, ref session_priv, ref first_hop_htlc_msat } => {
2724 route.write(writer)?;
2725 session_priv.write(writer)?;
2726 first_hop_htlc_msat.write(writer)?;
2733 impl<R: ::std::io::Read> Readable<R> for HTLCSource {
2734 fn read(reader: &mut R) -> Result<HTLCSource, DecodeError> {
2735 match <u8 as Readable<R>>::read(reader)? {
2736 0 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
2737 1 => Ok(HTLCSource::OutboundRoute {
2738 route: Readable::read(reader)?,
2739 session_priv: Readable::read(reader)?,
2740 first_hop_htlc_msat: Readable::read(reader)?,
2742 _ => Err(DecodeError::InvalidValue),
2747 impl Writeable for HTLCFailReason {
2748 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2750 &HTLCFailReason::ErrorPacket { ref err } => {
2754 &HTLCFailReason::Reason { ref failure_code, ref data } => {
2756 failure_code.write(writer)?;
2757 data.write(writer)?;
2764 impl<R: ::std::io::Read> Readable<R> for HTLCFailReason {
2765 fn read(reader: &mut R) -> Result<HTLCFailReason, DecodeError> {
2766 match <u8 as Readable<R>>::read(reader)? {
2767 0 => Ok(HTLCFailReason::ErrorPacket { err: Readable::read(reader)? }),
2768 1 => Ok(HTLCFailReason::Reason {
2769 failure_code: Readable::read(reader)?,
2770 data: Readable::read(reader)?,
2772 _ => Err(DecodeError::InvalidValue),
2777 impl Writeable for HTLCForwardInfo {
2778 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2780 &HTLCForwardInfo::AddHTLC { ref prev_short_channel_id, ref prev_htlc_id, ref forward_info } => {
2782 prev_short_channel_id.write(writer)?;
2783 prev_htlc_id.write(writer)?;
2784 forward_info.write(writer)?;
2786 &HTLCForwardInfo::FailHTLC { ref htlc_id, ref err_packet } => {
2788 htlc_id.write(writer)?;
2789 err_packet.write(writer)?;
2796 impl<R: ::std::io::Read> Readable<R> for HTLCForwardInfo {
2797 fn read(reader: &mut R) -> Result<HTLCForwardInfo, DecodeError> {
2798 match <u8 as Readable<R>>::read(reader)? {
2799 0 => Ok(HTLCForwardInfo::AddHTLC {
2800 prev_short_channel_id: Readable::read(reader)?,
2801 prev_htlc_id: Readable::read(reader)?,
2802 forward_info: Readable::read(reader)?,
2804 1 => Ok(HTLCForwardInfo::FailHTLC {
2805 htlc_id: Readable::read(reader)?,
2806 err_packet: Readable::read(reader)?,
2808 _ => Err(DecodeError::InvalidValue),
2813 impl Writeable for ChannelManager {
2814 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
2815 let _ = self.total_consistency_lock.write().unwrap();
2817 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
2818 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
2820 self.genesis_hash.write(writer)?;
2821 (self.latest_block_height.load(Ordering::Acquire) as u32).write(writer)?;
2822 self.last_block_hash.lock().unwrap().write(writer)?;
2824 let channel_state = self.channel_state.lock().unwrap();
2825 let mut unfunded_channels = 0;
2826 for (_, channel) in channel_state.by_id.iter() {
2827 if !channel.is_funding_initiated() {
2828 unfunded_channels += 1;
2831 ((channel_state.by_id.len() - unfunded_channels) as u64).write(writer)?;
2832 for (_, channel) in channel_state.by_id.iter() {
2833 if channel.is_funding_initiated() {
2834 channel.write(writer)?;
2838 (channel_state.forward_htlcs.len() as u64).write(writer)?;
2839 for (short_channel_id, pending_forwards) in channel_state.forward_htlcs.iter() {
2840 short_channel_id.write(writer)?;
2841 (pending_forwards.len() as u64).write(writer)?;
2842 for forward in pending_forwards {
2843 forward.write(writer)?;
2847 (channel_state.claimable_htlcs.len() as u64).write(writer)?;
2848 for (payment_hash, previous_hops) in channel_state.claimable_htlcs.iter() {
2849 payment_hash.write(writer)?;
2850 (previous_hops.len() as u64).write(writer)?;
2851 for previous_hop in previous_hops {
2852 previous_hop.write(writer)?;
2860 /// Arguments for the creation of a ChannelManager that are not deserialized.
2862 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
2864 /// 1) Deserialize all stored ChannelMonitors.
2865 /// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
2866 /// ChannelManager)>::read(reader, args).
2867 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
2868 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
2869 /// 3) Register all relevant ChannelMonitor outpoints with your chain watch mechanism using
2870 /// ChannelMonitor::get_monitored_outpoints and ChannelMonitor::get_funding_txo().
2871 /// 4) Reconnect blocks on your ChannelMonitors.
2872 /// 5) Move the ChannelMonitors into your local ManyChannelMonitor.
2873 /// 6) Disconnect/connect blocks on the ChannelManager.
2874 /// 7) Register the new ChannelManager with your ChainWatchInterface (this does not happen
2875 /// automatically as it does in ChannelManager::new()).
2876 pub struct ChannelManagerReadArgs<'a> {
2877 /// The keys provider which will give us relevant keys. Some keys will be loaded during
2878 /// deserialization.
2879 pub keys_manager: Arc<KeysInterface>,
2881 /// The fee_estimator for use in the ChannelManager in the future.
2883 /// No calls to the FeeEstimator will be made during deserialization.
2884 pub fee_estimator: Arc<FeeEstimator>,
2885 /// The ManyChannelMonitor for use in the ChannelManager in the future.
2887 /// No calls to the ManyChannelMonitor will be made during deserialization. It is assumed that
2888 /// you have deserialized ChannelMonitors separately and will add them to your
2889 /// ManyChannelMonitor after deserializing this ChannelManager.
2890 pub monitor: Arc<ManyChannelMonitor>,
2891 /// The ChainWatchInterface for use in the ChannelManager in the future.
2893 /// No calls to the ChainWatchInterface will be made during deserialization.
2894 pub chain_monitor: Arc<ChainWatchInterface>,
2895 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
2896 /// used to broadcast the latest local commitment transactions of channels which must be
2897 /// force-closed during deserialization.
2898 pub tx_broadcaster: Arc<BroadcasterInterface>,
2899 /// The Logger for use in the ChannelManager and which may be used to log information during
2900 /// deserialization.
2901 pub logger: Arc<Logger>,
2902 /// Default settings used for new channels. Any existing channels will continue to use the
2903 /// runtime settings which were stored when the ChannelManager was serialized.
2904 pub default_config: UserConfig,
2906 /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
2907 /// value.get_funding_txo() should be the key).
2909 /// If a monitor is inconsistent with the channel state during deserialization the channel will
2910 /// be force-closed using the data in the channelmonitor and the Channel will be dropped. This
2911 /// is true for missing channels as well. If there is a monitor missing for which we find
2912 /// channel data Err(DecodeError::InvalidValue) will be returned.
2914 /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
2916 pub channel_monitors: &'a HashMap<OutPoint, &'a ChannelMonitor>,
2919 impl<'a, R : ::std::io::Read> ReadableArgs<R, ChannelManagerReadArgs<'a>> for (Sha256dHash, ChannelManager) {
2920 fn read(reader: &mut R, args: ChannelManagerReadArgs<'a>) -> Result<Self, DecodeError> {
2921 let _ver: u8 = Readable::read(reader)?;
2922 let min_ver: u8 = Readable::read(reader)?;
2923 if min_ver > SERIALIZATION_VERSION {
2924 return Err(DecodeError::UnknownVersion);
2927 let genesis_hash: Sha256dHash = Readable::read(reader)?;
2928 let latest_block_height: u32 = Readable::read(reader)?;
2929 let last_block_hash: Sha256dHash = Readable::read(reader)?;
2931 let mut closed_channels = Vec::new();
2933 let channel_count: u64 = Readable::read(reader)?;
2934 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
2935 let mut by_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
2936 let mut short_to_id = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
2937 for _ in 0..channel_count {
2938 let mut channel: Channel = ReadableArgs::read(reader, args.logger.clone())?;
2939 if channel.last_block_connected != last_block_hash {
2940 return Err(DecodeError::InvalidValue);
2943 let funding_txo = channel.channel_monitor().get_funding_txo().ok_or(DecodeError::InvalidValue)?;
2944 funding_txo_set.insert(funding_txo.clone());
2945 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
2946 if channel.get_cur_local_commitment_transaction_number() != monitor.get_cur_local_commitment_number() ||
2947 channel.get_revoked_remote_commitment_transaction_number() != monitor.get_min_seen_secret() ||
2948 channel.get_cur_remote_commitment_transaction_number() != monitor.get_cur_remote_commitment_number() {
2949 let mut force_close_res = channel.force_shutdown();
2950 force_close_res.0 = monitor.get_latest_local_commitment_txn();
2951 closed_channels.push(force_close_res);
2953 if let Some(short_channel_id) = channel.get_short_channel_id() {
2954 short_to_id.insert(short_channel_id, channel.channel_id());
2956 by_id.insert(channel.channel_id(), channel);
2959 return Err(DecodeError::InvalidValue);
2963 for (ref funding_txo, ref monitor) in args.channel_monitors.iter() {
2964 if !funding_txo_set.contains(funding_txo) {
2965 closed_channels.push((monitor.get_latest_local_commitment_txn(), Vec::new()));
2969 let forward_htlcs_count: u64 = Readable::read(reader)?;
2970 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
2971 for _ in 0..forward_htlcs_count {
2972 let short_channel_id = Readable::read(reader)?;
2973 let pending_forwards_count: u64 = Readable::read(reader)?;
2974 let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, 128));
2975 for _ in 0..pending_forwards_count {
2976 pending_forwards.push(Readable::read(reader)?);
2978 forward_htlcs.insert(short_channel_id, pending_forwards);
2981 let claimable_htlcs_count: u64 = Readable::read(reader)?;
2982 let mut claimable_htlcs = HashMap::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
2983 for _ in 0..claimable_htlcs_count {
2984 let payment_hash = Readable::read(reader)?;
2985 let previous_hops_len: u64 = Readable::read(reader)?;
2986 let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, 2));
2987 for _ in 0..previous_hops_len {
2988 previous_hops.push(Readable::read(reader)?);
2990 claimable_htlcs.insert(payment_hash, previous_hops);
2993 let channel_manager = ChannelManager {
2995 fee_estimator: args.fee_estimator,
2996 monitor: args.monitor,
2997 chain_monitor: args.chain_monitor,
2998 tx_broadcaster: args.tx_broadcaster,
3000 latest_block_height: AtomicUsize::new(latest_block_height as usize),
3001 last_block_hash: Mutex::new(last_block_hash),
3002 secp_ctx: Secp256k1::new(),
3004 channel_state: Mutex::new(ChannelHolder {
3007 next_forward: Instant::now(),
3010 pending_msg_events: Vec::new(),
3012 our_network_key: args.keys_manager.get_node_secret(),
3014 pending_events: Mutex::new(Vec::new()),
3015 total_consistency_lock: RwLock::new(()),
3016 keys_manager: args.keys_manager,
3017 logger: args.logger,
3018 default_configuration: args.default_config,
3021 for close_res in closed_channels.drain(..) {
3022 channel_manager.finish_force_close_channel(close_res);
3023 //TODO: Broadcast channel update for closed channels, but only after we've made a
3024 //connection or two.
3027 Ok((last_block_hash.clone(), channel_manager))