]> git.bitcoin.ninja Git - rapid-gossip-sync-server/blob - src/verifier.rs
Bump LDK to 0.0.121/rust-bitcoin 0.30, bumping MSRV to 1.63
[rapid-gossip-sync-server] / src / verifier.rs
1 use std::io::ErrorKind;
2 use std::ops::Deref;
3 use std::sync::Arc;
4 use std::sync::Mutex;
5
6 use bitcoin::blockdata::constants::ChainHash;
7 use bitcoin::{BlockHash, TxOut};
8 use bitcoin::blockdata::block::Block;
9 use bitcoin::hashes::Hash;
10 use lightning::log_error;
11 use lightning::routing::gossip::{NetworkGraph, P2PGossipSync};
12 use lightning::routing::utxo::{UtxoFuture, UtxoLookup, UtxoResult, UtxoLookupError};
13 use lightning::util::logger::Logger;
14 use lightning_block_sync::{BlockData, BlockSource};
15 use lightning_block_sync::http::BinaryResponse;
16 use lightning_block_sync::rest::RestClient;
17
18 use crate::config;
19 use crate::types::GossipPeerManager;
20
21 pub(crate) struct ChainVerifier<L: Deref + Clone + Send + Sync + 'static> where L::Target: Logger {
22         rest_client: Arc<RestClient>,
23         graph: Arc<NetworkGraph<L>>,
24         outbound_gossiper: Arc<P2PGossipSync<Arc<NetworkGraph<L>>, Arc<Self>, L>>,
25         peer_handler: Mutex<Option<GossipPeerManager<L>>>,
26         logger: L
27 }
28
29 struct RestBinaryResponse(Vec<u8>);
30
31 impl<L: Deref + Clone + Send + Sync + 'static> ChainVerifier<L> where L::Target: Logger {
32         pub(crate) fn new(graph: Arc<NetworkGraph<L>>, outbound_gossiper: Arc<P2PGossipSync<Arc<NetworkGraph<L>>, Arc<Self>, L>>, logger: L) -> Self {
33                 ChainVerifier {
34                         rest_client: Arc::new(RestClient::new(config::bitcoin_rest_endpoint()).unwrap()),
35                         outbound_gossiper,
36                         graph,
37                         peer_handler: Mutex::new(None),
38                         logger
39                 }
40         }
41         pub(crate) fn set_ph(&self, peer_handler: GossipPeerManager<L>) {
42                 *self.peer_handler.lock().unwrap() = Some(peer_handler);
43         }
44
45         async fn retrieve_utxo(client: Arc<RestClient>, short_channel_id: u64, logger: L) -> Result<TxOut, UtxoLookupError> {
46                 let block_height = (short_channel_id >> 5 * 8) as u32; // block height is most significant three bytes
47                 let transaction_index = ((short_channel_id >> 2 * 8) & 0xffffff) as u32;
48                 let output_index = (short_channel_id & 0xffff) as u16;
49
50                 let mut block = Self::retrieve_block(client, block_height, logger.clone()).await?;
51                 if transaction_index as usize >= block.txdata.len() {
52                         log_error!(logger, "Could't find transaction {} in block {}", transaction_index, block_height);
53                         return Err(UtxoLookupError::UnknownTx);
54                 }
55                 let mut transaction = block.txdata.swap_remove(transaction_index as usize);
56                 if output_index as usize >= transaction.output.len() {
57                         log_error!(logger, "Could't find output {} in transaction {}", output_index, transaction.txid());
58                         return Err(UtxoLookupError::UnknownTx);
59                 }
60                 Ok(transaction.output.swap_remove(output_index as usize))
61         }
62
63         async fn retrieve_block(client: Arc<RestClient>, block_height: u32, logger: L) -> Result<Block, UtxoLookupError> {
64                 let uri = format!("blockhashbyheight/{}.bin", block_height);
65                 let block_hash_result =
66                         client.request_resource::<BinaryResponse, RestBinaryResponse>(&uri).await;
67                 let block_hash: Vec<u8> = block_hash_result.map_err(|error| {
68                         match error.kind() {
69                                 ErrorKind::InvalidData => {
70                                         // the response length was likely 0
71                                         log_error!(logger, "Could't find block hash at height {}: Invalid response! Please make sure the `-rest=1` flag is set.", block_height);
72                                 }
73                                 _ => {
74                                         log_error!(logger, "Could't find block hash at height {}: {}", block_height, error.to_string());
75                                 }
76                         }
77                         UtxoLookupError::UnknownChain
78                 })?.0;
79                 let block_hash = BlockHash::from_slice(&block_hash).unwrap();
80
81                 let block_result = client.get_block(&block_hash).await;
82                 match block_result {
83                         Ok(BlockData::FullBlock(block)) => {
84                                 Ok(block)
85                         },
86                         Ok(_) => unreachable!(),
87                         Err(error) => {
88                                 log_error!(logger, "Couldn't retrieve block {}: {:?} ({})", block_height, error, block_hash);
89                                 Err(UtxoLookupError::UnknownChain)
90                         }
91                 }
92         }
93 }
94
95 impl<L: Deref + Clone + Send + Sync + 'static> UtxoLookup for ChainVerifier<L> where L::Target: Logger {
96         fn get_utxo(&self, _genesis_hash: &ChainHash, short_channel_id: u64) -> UtxoResult {
97                 let res = UtxoFuture::new();
98                 let fut = res.clone();
99                 let graph_ref = Arc::clone(&self.graph);
100                 let client_ref = Arc::clone(&self.rest_client);
101                 let gossip_ref = Arc::clone(&self.outbound_gossiper);
102                 let pm_ref = self.peer_handler.lock().unwrap().clone();
103                 let logger_ref = self.logger.clone();
104                 tokio::spawn(async move {
105                         let res = Self::retrieve_utxo(client_ref, short_channel_id, logger_ref).await;
106                         fut.resolve(&*graph_ref, &*gossip_ref, res);
107                         if let Some(pm) = pm_ref { pm.process_events(); }
108                 });
109                 UtxoResult::Async(res)
110         }
111 }
112
113 impl TryInto<RestBinaryResponse> for BinaryResponse {
114         type Error = std::io::Error;
115
116         fn try_into(self) -> Result<RestBinaryResponse, Self::Error> {
117                 Ok(RestBinaryResponse(self.0))
118         }
119 }