1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! This module contains traits for LDK to access UTXOs to check gossip data is correct.
12 //! When lightning nodes gossip channel information, they resist DoS attacks by checking that each
13 //! channel matches a UTXO on-chain, requiring at least some marginal on-chain transacting in
14 //! order to announce a channel. This module handles that checking.
16 use bitcoin::{BlockHash, TxOut};
17 use bitcoin::hashes::hex::ToHex;
19 use crate::ln::chan_utils::make_funding_redeemscript_from_slices;
20 use crate::ln::msgs::{self, LightningError, ErrorAction};
21 use crate::routing::gossip::{NetworkGraph, NodeId};
22 use crate::util::logger::{Level, Logger};
23 use crate::util::ser::Writeable;
25 use crate::prelude::*;
27 use alloc::sync::{Arc, Weak};
28 use crate::sync::Mutex;
31 /// An error when accessing the chain via [`UtxoLookup`].
32 #[derive(Clone, Debug)]
33 pub enum UtxoLookupError {
34 /// The requested chain is unknown.
37 /// The requested transaction doesn't exist or hasn't confirmed.
41 /// The result of a [`UtxoLookup::get_utxo`] call. A call may resolve either synchronously,
42 /// returning the `Sync` variant, or asynchronously, returning an [`UtxoFuture`] in the `Async`
45 /// A result which was resolved synchronously. It either includes a [`TxOut`] for the output
46 /// requested or a [`UtxoLookupError`].
47 Sync(Result<TxOut, UtxoLookupError>),
48 /// A result which will be resolved asynchronously. It includes a [`UtxoFuture`], a `clone` of
49 /// which you must keep locally and call [`UtxoFuture::resolve`] on once the lookup completes.
51 /// Note that in order to avoid runaway memory usage, the number of parallel checks is limited,
52 /// but only fairly loosely. Because a pending checks block all message processing, leaving
53 /// checks pending for an extended time may cause DoS of other functions. It is recommended you
54 /// keep a tight timeout on lookups, on the order of a few seconds.
58 /// The `UtxoLookup` trait defines behavior for accessing on-chain UTXOs.
59 pub trait UtxoLookup {
60 /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
61 /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
64 /// [`short_channel_id`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id
65 fn get_utxo(&self, genesis_hash: &BlockHash, short_channel_id: u64) -> UtxoResult;
68 enum ChannelAnnouncement {
69 Full(msgs::ChannelAnnouncement),
70 Unsigned(msgs::UnsignedChannelAnnouncement),
74 complete: Option<Result<TxOut, UtxoLookupError>>,
75 channel_announce: Option<ChannelAnnouncement>,
78 /// Represents a future resolution of a [`UtxoLookup::get_utxo`] query resolving async.
80 /// See [`UtxoResult::Async`] and [`UtxoFuture::resolve`] for more info.
82 pub struct UtxoFuture {
83 state: Arc<Mutex<UtxoMessages>>,
86 /// A trivial implementation of [`UtxoLookup`] which is used to call back into the network graph
87 /// once we have a concrete resolution of a request.
88 struct UtxoResolver(Result<TxOut, UtxoLookupError>);
89 impl UtxoLookup for UtxoResolver {
90 fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
91 UtxoResult::Sync(self.0.clone())
96 /// Builds a new future for later resolution.
97 pub fn new() -> Self {
98 Self { state: Arc::new(Mutex::new(UtxoMessages {
100 channel_announce: None,
104 /// Resolves this future against the given `graph` and with the given `result`.
105 pub fn resolve<L: Deref>(&self, graph: &NetworkGraph<L>, result: Result<TxOut, UtxoLookupError>)
106 where L::Target: Logger {
108 let mut async_messages = self.state.lock().unwrap();
110 if async_messages.channel_announce.is_none() {
111 // We raced returning to `check_channel_announcement` which hasn't updated
112 // `channel_announce` yet. That's okay, we can set the `complete` field which it will
113 // check once it gets control again.
114 async_messages.complete = Some(result);
118 async_messages.channel_announce.take().unwrap()
121 // Now that we've updated our internal state, pass the pending messages back through the
122 // network graph with a different `UtxoLookup` which will resolve immediately.
123 // Note that we ignore errors as we don't disconnect peers anyway, so there's nothing to do
125 let resolver = UtxoResolver(result);
127 ChannelAnnouncement::Full(signed_msg) => {
128 let _ = graph.update_channel_from_announcement(&signed_msg, &Some(&resolver));
130 ChannelAnnouncement::Unsigned(msg) => {
131 let _ = graph.update_channel_from_unsigned_announcement(&msg, &Some(&resolver));
137 /// A set of messages which are pending UTXO lookups for processing.
138 pub(super) struct PendingChecks {
142 pub(super) fn new() -> Self {
146 pub(super) fn check_channel_announcement<U: Deref>(&self,
147 utxo_lookup: &Option<U>, msg: &msgs::UnsignedChannelAnnouncement,
148 full_msg: Option<&msgs::ChannelAnnouncement>
149 ) -> Result<Option<u64>, msgs::LightningError> where U::Target: UtxoLookup {
150 let handle_result = |res| {
152 Ok(TxOut { value, script_pubkey }) => {
153 let expected_script =
154 make_funding_redeemscript_from_slices(msg.bitcoin_key_1.as_slice(), msg.bitcoin_key_2.as_slice()).to_v0_p2wsh();
155 if script_pubkey != expected_script {
156 return Err(LightningError{
157 err: format!("Channel announcement key ({}) didn't match on-chain script ({})",
158 expected_script.to_hex(), script_pubkey.to_hex()),
159 action: ErrorAction::IgnoreError
164 Err(UtxoLookupError::UnknownChain) => {
166 err: format!("Channel announced on an unknown chain ({})",
167 msg.chain_hash.encode().to_hex()),
168 action: ErrorAction::IgnoreError
171 Err(UtxoLookupError::UnknownTx) => {
173 err: "Channel announced without corresponding UTXO entry".to_owned(),
174 action: ErrorAction::IgnoreError
182 // Tentatively accept, potentially exposing us to DoS attacks
185 &Some(ref utxo_lookup) => {
186 match utxo_lookup.get_utxo(&msg.chain_hash, msg.short_channel_id) {
187 UtxoResult::Sync(res) => handle_result(res),
188 UtxoResult::Async(future) => {
189 let mut async_messages = future.state.lock().unwrap();
190 if let Some(res) = async_messages.complete.take() {
191 // In the unlikely event the future resolved before we managed to get it,
192 // handle the result in-line.
195 async_messages.channel_announce = Some(
196 if let Some(msg) = full_msg { ChannelAnnouncement::Full(msg.clone()) }
197 else { ChannelAnnouncement::Unsigned(msg.clone()) });
199 err: "Channel being checked async".to_owned(),
200 action: ErrorAction::IgnoreAndLog(Level::Gossip),