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