Skip to content

Commit 97716a4

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 43f1d2d commit 97716a4

File tree

1 file changed

+138
-1
lines changed

1 file changed

+138
-1
lines changed

src/wallet.rs

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

0 commit comments

Comments
 (0)