Skip to content

Commit

Permalink
Implement chain::Access trait
Browse files Browse the repository at this point in the history
  • Loading branch information
tnull committed Sep 14, 2022
1 parent 4c62cd8 commit 30ed951
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 10 deletions.
48 changes: 45 additions & 3 deletions src/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@ use crate::logger::{
log_error, log_given_level, log_info, log_internal, log_trace, log_warn, FilesystemLogger,
Logger,
};
use crate::{scid_utils, LdkLiteConfig};

use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
use lightning::chain::WatchedOutput;
use lightning::chain::{Confirm, Filter};
use lightning::chain::{Access, AccessError, Confirm, Filter};

use bdk::blockchain::{Blockchain, EsploraBlockchain, GetBlockHash, GetHeight, GetTx};
use bdk::database::BatchDatabase;
use bdk::wallet::AddressIndex;
use bdk::{SignOptions, SyncOptions};

use bitcoin::{BlockHash, Script, Transaction, Txid};
use bitcoin::{BlockHash, Script, Transaction, TxOut, Txid};

use std::collections::HashSet;
use std::sync::{Arc, Mutex};
Expand All @@ -33,6 +34,7 @@ where
queued_outputs: Mutex<Vec<WatchedOutput>>,
watched_outputs: Mutex<Vec<WatchedOutput>>,
last_sync_height: Mutex<Option<u32>>,
config: Arc<LdkLiteConfig>,
logger: Arc<FilesystemLogger>,
}

Expand All @@ -41,7 +43,8 @@ where
D: BatchDatabase,
{
pub(crate) fn new(
blockchain: EsploraBlockchain, wallet: bdk::Wallet<D>, logger: Arc<FilesystemLogger>,
blockchain: EsploraBlockchain, wallet: bdk::Wallet<D>, config: Arc<LdkLiteConfig>,
logger: Arc<FilesystemLogger>,
) -> Self {
let wallet = Mutex::new(wallet);
let watched_transactions = Mutex::new(Vec::new());
Expand All @@ -57,6 +60,7 @@ where
queued_outputs,
watched_outputs,
last_sync_height,
config,
logger,
}
}
Expand Down Expand Up @@ -281,6 +285,44 @@ where
}
}

impl<D> Access for LdkLiteChainAccess<D>
where
D: BatchDatabase,
{
fn get_utxo(
&self, genesis_hash: &BlockHash, short_channel_id: u64,
) -> Result<TxOut, AccessError> {
if genesis_hash
!= &bitcoin::blockdata::constants::genesis_block(self.config.network)
.header
.block_hash()
{
return Err(AccessError::UnknownChain);
}

let block_height = scid_utils::block_from_scid(&short_channel_id);
let tx_index = scid_utils::tx_index_from_scid(&short_channel_id);
let vout = scid_utils::vout_from_scid(&short_channel_id);

let client = &*self.blockchain;
let block_hash = self
.blockchain
.get_block_hash(block_height.into())
.map_err(|_| AccessError::UnknownTx)?;
let txid = client
.get_txid_at_block_index(&block_hash, tx_index as usize)
.map_err(|_| AccessError::UnknownTx)?
.ok_or(AccessError::UnknownTx)?;
let tx = client
.get_tx(&txid)
.map_err(|_| AccessError::UnknownTx)?
.ok_or(AccessError::UnknownTx)?;
let tx_out = tx.output.get(vout as usize).ok_or(AccessError::UnknownTx)?;

Ok(tx_out.clone())
}
}

impl<D> Filter for LdkLiteChainAccess<D>
where
D: BatchDatabase,
Expand Down
22 changes: 15 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ mod error;
mod event;
mod hex_utils;
mod io_utils;
mod scid_utils;
mod logger;
mod peer_store;

Expand All @@ -45,7 +46,7 @@ use logger::{
};

use lightning::chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager, Recipient};
use lightning::chain::{chainmonitor, Access, BestBlock, Confirm, Filter, Watch};
use lightning::chain::{chainmonitor, BestBlock, Confirm, Filter, Watch};
use lightning::ln::channelmanager;
use lightning::ln::channelmanager::{
ChainParameters, ChannelManagerReadArgs, SimpleArcChannelManager,
Expand Down Expand Up @@ -227,8 +228,12 @@ impl LdkLiteBuilder {
let blockchain = EsploraBlockchain::new(&config.esplora_server_url, BDK_CLIENT_STOP_GAP)
.with_concurrency(BDK_CLIENT_CONCURRENCY);

let chain_access =
Arc::new(LdkLiteChainAccess::new(blockchain, bdk_wallet, Arc::clone(&logger)));
let chain_access = Arc::new(LdkLiteChainAccess::new(
blockchain,
bdk_wallet,
Arc::clone(&config),
Arc::clone(&logger),
));

// Step 3: Initialize Persist
let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
Expand Down Expand Up @@ -303,7 +308,7 @@ impl LdkLiteBuilder {
Arc::new(io_utils::read_network_graph(Arc::clone(&config), Arc::clone(&logger))?);
let gossip_sync = Arc::new(P2PGossipSync::new(
Arc::clone(&network_graph),
None::<Arc<dyn Access + Send + Sync>>,
Some(Arc::clone(&chain_access)),
Arc::clone(&logger),
));

Expand Down Expand Up @@ -963,7 +968,7 @@ type PeerManager = SimpleArcPeerManager<
ChainMonitor,
LdkLiteChainAccess<bdk::sled::Tree>,
LdkLiteChainAccess<bdk::sled::Tree>,
dyn Access + Send + Sync,
LdkLiteChainAccess<bdk::sled::Tree>,
FilesystemLogger,
>;

Expand All @@ -985,8 +990,11 @@ type InvoicePayer<F> = payment::InvoicePayer<
type Router = DefaultRouter<Arc<NetworkGraph>, Arc<FilesystemLogger>>;
type Scorer = ProbabilisticScorer<Arc<NetworkGraph>, Arc<FilesystemLogger>>;

type GossipSync =
P2PGossipSync<Arc<NetworkGraph>, Arc<dyn Access + Send + Sync>, Arc<FilesystemLogger>>;
type GossipSync = P2PGossipSync<
Arc<NetworkGraph>,
Arc<LdkLiteChainAccess<bdk::sled::Tree>>,
Arc<FilesystemLogger>,
>;

pub(crate) type NetworkGraph = gossip::NetworkGraph<Arc<FilesystemLogger>>;

Expand Down
33 changes: 33 additions & 0 deletions src/scid_utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copied from `rust-lightning`
//
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

/// Maximum transaction index that can be used in a `short_channel_id`.
/// This value is based on the 3-bytes available for tx index.
pub const MAX_SCID_TX_INDEX: u64 = 0x00ffffff;

/// Maximum vout index that can be used in a `short_channel_id`. This
/// value is based on the 2-bytes available for the vout index.
pub const MAX_SCID_VOUT_INDEX: u64 = 0xffff;

/// Extracts the block height (most significant 3-bytes) from the `short_channel_id`
pub fn block_from_scid(short_channel_id: &u64) -> u32 {
return (short_channel_id >> 40) as u32;
}

/// Extracts the tx index (bytes [2..4]) from the `short_channel_id`
pub fn tx_index_from_scid(short_channel_id: &u64) -> u32 {
return ((short_channel_id >> 16) & MAX_SCID_TX_INDEX) as u32;
}

/// Extracts the vout (bytes [0..2]) from the `short_channel_id`
pub fn vout_from_scid(short_channel_id: &u64) -> u16 {
return ((short_channel_id) & MAX_SCID_VOUT_INDEX) as u16;
}

0 comments on commit 30ed951

Please sign in to comment.