1 //! When fetching gossip from peers, lightning nodes need to validate that gossip against the
2 //! current UTXO set. This module defines an implementation of the LDK API required to do so
3 //! against a [`BlockSource`] which implements a few additional methods for accessing the UTXO set.
5 use crate::{AsyncBlockSourceResult, BlockData, BlockSource, BlockSourceError};
7 use bitcoin::blockdata::block::Block;
8 use bitcoin::blockdata::constants::ChainHash;
9 use bitcoin::blockdata::transaction::{TxOut, OutPoint};
10 use bitcoin::hash_types::BlockHash;
12 use lightning::ln::peer_handler::APeerManager;
14 use lightning::routing::gossip::{NetworkGraph, P2PGossipSync};
15 use lightning::routing::utxo::{UtxoFuture, UtxoLookup, UtxoResult, UtxoLookupError};
17 use lightning::util::logger::Logger;
19 use std::sync::{Arc, Mutex};
20 use std::collections::VecDeque;
21 use std::future::Future;
26 /// A trait which extends [`BlockSource`] and can be queried to fetch the block at a given height
27 /// as well as whether a given output is unspent (i.e. a member of the current UTXO set).
29 /// Note that while this is implementable for a [`BlockSource`] which returns filtered block data
30 /// (i.e. [`BlockData::HeaderOnly`] for [`BlockSource::get_block`] requests), such an
31 /// implementation will reject all gossip as it is not fully able to verify the UTXOs referenced.
32 pub trait UtxoSource : BlockSource + 'static {
33 /// Fetches the block hash of the block at the given height.
35 /// This will, in turn, be passed to to [`BlockSource::get_block`] to fetch the block needed
36 /// for gossip validation.
37 fn get_block_hash_by_height<'a>(&'a self, block_height: u32) -> AsyncBlockSourceResult<'a, BlockHash>;
39 /// Returns true if the given output has *not* been spent, i.e. is a member of the current UTXO
41 fn is_output_unspent<'a>(&'a self, outpoint: OutPoint) -> AsyncBlockSourceResult<'a, bool>;
44 /// A generic trait which is able to spawn futures in the background.
46 /// If the `tokio` feature is enabled, this is implemented on `TokioSpawner` struct which
47 /// delegates to `tokio::spawn()`.
48 pub trait FutureSpawner : Send + Sync + 'static {
49 /// Spawns the given future as a background task.
51 /// This method MUST NOT block on the given future immediately.
52 fn spawn<T: Future<Output = ()> + Send + 'static>(&self, future: T);
55 #[cfg(feature = "tokio")]
56 /// A trivial [`FutureSpawner`] which delegates to `tokio::spawn`.
57 pub struct TokioSpawner;
58 #[cfg(feature = "tokio")]
59 impl FutureSpawner for TokioSpawner {
60 fn spawn<T: Future<Output = ()> + Send + 'static>(&self, future: T) {
65 /// A trivial future which joins two other futures and polls them at the same time, returning only
66 /// once both complete.
67 pub(crate) struct Joiner<
68 A: Future<Output=Result<(BlockHash, Option<u32>), BlockSourceError>> + Unpin,
69 B: Future<Output=Result<BlockHash, BlockSourceError>> + Unpin,
73 a_res: Option<(BlockHash, Option<u32>)>,
74 b_res: Option<BlockHash>,
78 A: Future<Output=Result<(BlockHash, Option<u32>), BlockSourceError>> + Unpin,
79 B: Future<Output=Result<BlockHash, BlockSourceError>> + Unpin,
81 fn new(a: A, b: B) -> Self { Self { a, b, a_res: None, b_res: None } }
85 A: Future<Output=Result<(BlockHash, Option<u32>), BlockSourceError>> + Unpin,
86 B: Future<Output=Result<BlockHash, BlockSourceError>> + Unpin,
87 > Future for Joiner<A, B> {
88 type Output = Result<((BlockHash, Option<u32>), BlockHash), BlockSourceError>;
89 fn poll(mut self: Pin<&mut Self>, ctx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
90 if self.a_res.is_none() {
91 match Pin::new(&mut self.a).poll(ctx) {
94 self.a_res = Some(ok);
96 return Poll::Ready(Err(res.unwrap_err()));
102 if self.b_res.is_none() {
103 match Pin::new(&mut self.b).poll(ctx) {
104 Poll::Ready(res) => {
105 if let Ok(ok) = res {
106 self.b_res = Some(ok);
108 return Poll::Ready(Err(res.unwrap_err()));
115 if let Some(b_res) = self.b_res {
116 if let Some(a_res) = self.a_res {
117 return Poll::Ready(Ok((a_res, b_res)))
124 /// A struct which wraps a [`UtxoSource`] and a few LDK objects and implements the LDK
125 /// [`UtxoLookup`] trait.
127 /// Note that if you're using this against a Bitcoin Core REST or RPC server, you likely wish to
128 /// increase the `rpcworkqueue` setting in Bitcoin Core as LDK attempts to parallelize requests (a
129 /// value of 1024 should more than suffice), and ensure you have sufficient file descriptors
130 /// available on both Bitcoin Core and your LDK application for each request to hold its own
132 pub struct GossipVerifier<S: FutureSpawner,
133 Blocks: Deref + Send + Sync + 'static + Clone,
134 L: Deref + Send + Sync + 'static,
136 Blocks::Target: UtxoSource,
140 peer_manager_wake: Arc<dyn Fn() + Send + Sync>,
141 gossiper: Arc<P2PGossipSync<Arc<NetworkGraph<L>>, Self, L>>,
143 block_cache: Arc<Mutex<VecDeque<(u32, Block)>>>,
146 const BLOCK_CACHE_SIZE: usize = 5;
148 impl<S: FutureSpawner,
149 Blocks: Deref + Send + Sync + Clone,
150 L: Deref + Send + Sync,
151 > GossipVerifier<S, Blocks, L> where
152 Blocks::Target: UtxoSource,
155 /// Constructs a new [`GossipVerifier`].
157 /// This is expected to be given to a [`P2PGossipSync`] (initially constructed with `None` for
158 /// the UTXO lookup) via [`P2PGossipSync::add_utxo_lookup`].
159 pub fn new<APM: Deref + Send + Sync + Clone + 'static>(
160 source: Blocks, spawn: S, gossiper: Arc<P2PGossipSync<Arc<NetworkGraph<L>>, Self, L>>, peer_manager: APM
161 ) -> Self where APM::Target: APeerManager {
162 let peer_manager_wake = Arc::new(move || peer_manager.as_ref().process_events());
164 source, spawn, gossiper, peer_manager_wake,
165 block_cache: Arc::new(Mutex::new(VecDeque::with_capacity(BLOCK_CACHE_SIZE))),
169 async fn retrieve_utxo(
170 source: Blocks, block_cache: Arc<Mutex<VecDeque<(u32, Block)>>>, short_channel_id: u64
171 ) -> Result<TxOut, UtxoLookupError> {
172 let block_height = (short_channel_id >> 5 * 8) as u32; // block height is most significant three bytes
173 let transaction_index = ((short_channel_id >> 2 * 8) & 0xffffff) as u32;
174 let output_index = (short_channel_id & 0xffff) as u16;
176 let (outpoint, output);
178 'tx_found: loop { // Used as a simple goto
179 macro_rules! process_block {
180 ($block: expr) => { {
181 if transaction_index as usize >= $block.txdata.len() {
182 return Err(UtxoLookupError::UnknownTx);
184 let transaction = &$block.txdata[transaction_index as usize];
185 if output_index as usize >= transaction.output.len() {
186 return Err(UtxoLookupError::UnknownTx);
189 outpoint = OutPoint::new(transaction.txid(), output_index.into());
190 output = transaction.output[output_index as usize].clone();
194 let recent_blocks = block_cache.lock().unwrap();
195 for (height, block) in recent_blocks.iter() {
196 if *height == block_height {
197 process_block!(block);
203 let ((_, tip_height_opt), block_hash) =
204 Joiner::new(source.get_best_block(), source.get_block_hash_by_height(block_height))
206 .map_err(|_| UtxoLookupError::UnknownTx)?;
207 if let Some(tip_height) = tip_height_opt {
208 // If the block doesn't yet have five confirmations, error out.
210 // The BOLT spec requires nodes wait for six confirmations before announcing a
211 // channel, and we give them one block of headroom in case we're delayed seeing a
213 if block_height + 5 > tip_height {
214 return Err(UtxoLookupError::UnknownTx);
217 let block_data = source.get_block(&block_hash).await
218 .map_err(|_| UtxoLookupError::UnknownTx)?;
219 let block = match block_data {
220 BlockData::HeaderOnly(_) => return Err(UtxoLookupError::UnknownTx),
221 BlockData::FullBlock(block) => block,
223 process_block!(block);
225 let mut recent_blocks = block_cache.lock().unwrap();
226 let mut insert = true;
227 for (height, _) in recent_blocks.iter() {
228 if *height == block_height {
233 if recent_blocks.len() >= BLOCK_CACHE_SIZE {
234 recent_blocks.pop_front();
236 recent_blocks.push_back((block_height, block));
241 let outpoint_unspent =
242 source.is_output_unspent(outpoint).await.map_err(|_| UtxoLookupError::UnknownTx)?;
243 if outpoint_unspent {
246 Err(UtxoLookupError::UnknownTx)
251 impl<S: FutureSpawner,
252 Blocks: Deref + Send + Sync + Clone,
253 L: Deref + Send + Sync,
254 > Deref for GossipVerifier<S, Blocks, L> where
255 Blocks::Target: UtxoSource,
259 fn deref(&self) -> &Self { self }
263 impl<S: FutureSpawner,
264 Blocks: Deref + Send + Sync + Clone,
265 L: Deref + Send + Sync,
266 > UtxoLookup for GossipVerifier<S, Blocks, L> where
267 Blocks::Target: UtxoSource,
270 fn get_utxo(&self, _chain_hash: &ChainHash, short_channel_id: u64) -> UtxoResult {
271 let res = UtxoFuture::new();
272 let fut = res.clone();
273 let source = self.source.clone();
274 let gossiper = Arc::clone(&self.gossiper);
275 let block_cache = Arc::clone(&self.block_cache);
276 let pmw = Arc::clone(&self.peer_manager_wake);
277 self.spawn.spawn(async move {
278 let res = Self::retrieve_utxo(source, block_cache, short_channel_id).await;
279 fut.resolve(gossiper.network_graph(), &*gossiper, res);
282 UtxoResult::Async(res)