Skip to content

Commit 2036269

Browse files
committed
Implement WalletKeysManager
This implementation of `KeysInterface` allows to override the shutdown/destination scripts and forwards any other calls to an inner instance of `KeysManager` otherwise.
1 parent cca2687 commit 2036269

File tree

1 file changed

+137
-1
lines changed

1 file changed

+137
-1
lines changed

src/wallet.rs

Lines changed: 137 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,29 @@
11
use crate::logger::{
22
log_error, log_given_level, log_internal, log_trace, FilesystemLogger, Logger,
33
};
4+
45
use crate::Error;
56

67
use lightning::chain::chaininterface::{
78
BroadcasterInterface, ConfirmationTarget, FeeEstimator, FEERATE_FLOOR_SATS_PER_KW,
89
};
910

11+
use lightning::chain::keysinterface::{
12+
InMemorySigner, KeyMaterial, KeysInterface, KeysManager, Recipient, SpendableOutputDescriptor,
13+
};
14+
use lightning::ln::msgs::DecodeError;
15+
use lightning::ln::script::ShutdownScript;
16+
1017
use bdk::blockchain::{Blockchain, EsploraBlockchain};
1118
use bdk::database::BatchDatabase;
1219
use bdk::wallet::AddressIndex;
1320
use bdk::{FeeRate, SignOptions, SyncOptions};
1421

15-
use bitcoin::{Script, Transaction};
22+
use bitcoin::bech32::u5;
23+
use bitcoin::secp256k1::ecdh::SharedSecret;
24+
use bitcoin::secp256k1::ecdsa::RecoverableSignature;
25+
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey, Signing};
26+
use bitcoin::{Script, Transaction, TxOut};
1627

1728
use std::collections::HashMap;
1829
use std::sync::{Arc, Mutex, RwLock};
@@ -105,6 +116,10 @@ where
105116
Ok(address_info.address)
106117
}
107118

119+
pub(crate) fn get_balance(&self) -> Result<bdk::Balance, Error> {
120+
Ok(self.wallet.lock().unwrap().get_balance()?)
121+
}
122+
108123
fn estimate_fee_rate(&self, confirmation_target: ConfirmationTarget) -> FeeRate {
109124
let mut locked_fee_rate_cache = self.fee_rate_cache.lock().unwrap();
110125
let num_blocks = num_blocks_from_conf_target(confirmation_target);
@@ -199,3 +214,124 @@ fn fallback_fee_from_conf_target(confirmation_target: ConfirmationTarget) -> Fee
199214

200215
FeeRate::from_sat_per_kwu(sats_kwu as f32)
201216
}
217+
218+
/// Similar to [`KeysManager`], but overrides the destination and shutdown scripts so they are
219+
/// directly spendable by the BDK wallet.
220+
pub struct WalletKeysManager<D>
221+
where
222+
D: BatchDatabase,
223+
{
224+
inner: KeysManager,
225+
wallet: Arc<Wallet<D>>,
226+
}
227+
228+
impl<D> WalletKeysManager<D>
229+
where
230+
D: BatchDatabase,
231+
{
232+
/// Constructs a `WalletKeysManager` that
233+
///
234+
/// See [`KeysManager::new`] for more information on `seed`, `starting_time_secs`, and
235+
/// `starting_time_nanos`.
236+
pub fn new(
237+
seed: &[u8; 32], starting_time_secs: u64, starting_time_nanos: u32, wallet: Arc<Wallet<D>>,
238+
) -> Self {
239+
let inner = KeysManager::new(seed, starting_time_secs, starting_time_nanos);
240+
Self { inner, wallet }
241+
}
242+
243+
/// See [`KeysManager::spend_spendable_outputs`] for documentation on this method.
244+
pub fn spend_spendable_outputs<C: Signing>(
245+
&self, descriptors: &[&SpendableOutputDescriptor], outputs: Vec<TxOut>,
246+
change_destination_script: Script, feerate_sat_per_1000_weight: u32,
247+
secp_ctx: &Secp256k1<C>,
248+
) -> Result<Transaction, ()> {
249+
let only_non_static = &descriptors
250+
.iter()
251+
.map(|a| *a)
252+
.filter(|desc| {
253+
if let SpendableOutputDescriptor::StaticOutput { .. } = *desc {
254+
false
255+
} else {
256+
true
257+
}
258+
})
259+
.collect::<Vec<_>>();
260+
self.inner.spend_spendable_outputs(
261+
only_non_static,
262+
outputs,
263+
change_destination_script,
264+
feerate_sat_per_1000_weight,
265+
secp_ctx,
266+
)
267+
}
268+
}
269+
270+
impl<D> KeysInterface for WalletKeysManager<D>
271+
where
272+
D: BatchDatabase,
273+
{
274+
type Signer = InMemorySigner;
275+
276+
fn get_node_secret(&self, recipient: Recipient) -> Result<SecretKey, ()> {
277+
self.inner.get_node_secret(recipient)
278+
}
279+
280+
fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
281+
self.inner.get_node_id(recipient)
282+
}
283+
284+
fn ecdh(
285+
&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
286+
) -> Result<SharedSecret, ()> {
287+
self.inner.ecdh(recipient, other_key, tweak)
288+
}
289+
290+
fn get_inbound_payment_key_material(&self) -> KeyMaterial {
291+
self.inner.get_inbound_payment_key_material()
292+
}
293+
294+
fn get_destination_script(&self) -> Script {
295+
let address =
296+
self.wallet.get_new_address().expect("Failed to retrieve new address from wallet.");
297+
address.script_pubkey()
298+
}
299+
300+
fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
301+
let address =
302+
self.wallet.get_new_address().expect("Failed to retrieve new address from wallet.");
303+
match address.payload {
304+
bitcoin::util::address::Payload::WitnessProgram { version, program } => {
305+
return ShutdownScript::new_witness_program(version, &program)
306+
.expect("Invalid shutdown script.");
307+
}
308+
_ => panic!("Tried to use a non-witness address. This must not ever happen."),
309+
}
310+
}
311+
312+
fn generate_channel_keys_id(
313+
&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128,
314+
) -> [u8; 32] {
315+
self.inner.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
316+
}
317+
318+
fn derive_channel_signer(
319+
&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32],
320+
) -> Self::Signer {
321+
self.inner.derive_channel_signer(channel_value_satoshis, channel_keys_id)
322+
}
323+
324+
fn get_secure_random_bytes(&self) -> [u8; 32] {
325+
self.inner.get_secure_random_bytes()
326+
}
327+
328+
fn read_chan_signer(&self, reader: &[u8]) -> Result<Self::Signer, DecodeError> {
329+
self.inner.read_chan_signer(reader)
330+
}
331+
332+
fn sign_invoice(
333+
&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient,
334+
) -> Result<RecoverableSignature, ()> {
335+
self.inner.sign_invoice(hrp_bytes, invoice_data, recipient)
336+
}
337+
}

0 commit comments

Comments
 (0)