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