Skip to content

Commit c1c43f2

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 1651ed9 commit c1c43f2

File tree

1 file changed

+146
-1
lines changed

1 file changed

+146
-1
lines changed

src/wallet.rs

+146-1
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,30 @@
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+
EntropySource, InMemorySigner, KeyMaterial, KeysInterface, KeysManager, NodeSigner, Recipient,
13+
SignerProvider, SpendableOutputDescriptor,
14+
};
15+
use lightning::ln::msgs::DecodeError;
16+
use lightning::ln::script::ShutdownScript;
17+
1018
use bdk::blockchain::{Blockchain, EsploraBlockchain};
1119
use bdk::database::BatchDatabase;
1220
use bdk::wallet::AddressIndex;
1321
use bdk::{FeeRate, SignOptions, SyncOptions};
1422

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

1729
use std::collections::HashMap;
1830
use std::sync::{Arc, Mutex, RwLock};
@@ -203,3 +215,136 @@ fn fallback_fee_from_conf_target(confirmation_target: ConfirmationTarget) -> Fee
203215

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

0 commit comments

Comments
 (0)