Skip to content

Commit 0297baa

Browse files
committed
Add util fn for creating a Transaction from spendable outputs
This adds a utility method, `KeysManager::spend_spendable_outputs`, which constructs a Transaction from a given set of `SpendableOutputDescriptor`s, deriving relevant keys as needed. It also adds methods which can sign individual inputs where channel-specific key derivation is required to `InMemoryChannelKeys`, making it easy to sign transaction inputs when a custom `KeysInterface` is used with `InMemoryChannelKeys`.
1 parent 9b7a229 commit 0297baa

File tree

1 file changed

+200
-2
lines changed

1 file changed

+200
-2
lines changed

lightning/src/chain/keysinterface.rs

Lines changed: 200 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@
1111
//! spendable on-chain outputs which the user owns and is responsible for using just as any other
1212
//! on-chain output which is theirs.
1313
14-
use bitcoin::blockdata::transaction::{Transaction, TxOut, SigHashType};
14+
use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
1515
use bitcoin::blockdata::script::{Script, Builder};
1616
use bitcoin::blockdata::opcodes;
17+
use bitcoin::consensus::Encodable;
18+
use bitcoin::consensus::encode::VarInt;
1719
use bitcoin::network::constants::Network;
1820
use bitcoin::util::bip32::{ExtendedPrivKey, ExtendedPubKey, ChildNumber};
1921
use bitcoin::util::bip143;
@@ -36,9 +38,10 @@ use ln::chan_utils;
3638
use ln::chan_utils::{HTLCOutputInCommitment, make_funding_redeemscript, ChannelPublicKeys, HolderCommitmentTransaction, ChannelTransactionParameters, CommitmentTransaction};
3739
use ln::msgs::UnsignedChannelAnnouncement;
3840

41+
use std::collections::HashSet;
3942
use std::sync::atomic::{AtomicUsize, Ordering};
4043
use std::io::Error;
41-
use ln::msgs::DecodeError;
44+
use ln::msgs::{DecodeError, MAX_VALUE_MSAT};
4245

4346
/// Information about a spendable output to a P2WSH script. See
4447
/// SpendableOutputDescriptor::DynamicOutputP2WSH for more details on how to spend this.
@@ -498,6 +501,63 @@ impl InMemoryChannelKeys {
498501
pub fn get_channel_parameters(&self) -> &ChannelTransactionParameters {
499502
self.channel_parameters.as_ref().unwrap()
500503
}
504+
505+
/// Sign the single input of spend_tx at index `input_idx` which spends the output
506+
/// described by descriptor.
507+
///
508+
/// Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
509+
/// or is not spending the outpoint described by `descriptor.outpoint`.
510+
///
511+
/// (C-not exported) as bindings don't support modifying a Transaction parameter
512+
pub fn sign_counterparty_payment_input<C: Signing>(&self, spend_tx: &mut Transaction, input_idx: usize, descriptor: &StaticCounterpartyPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<(), ()> {
513+
// TODO: We really should be taking the SigHashCache as a parameter here instead of
514+
// spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
515+
// so that we can check them. This requires upstream rust-bitcoin changes (as well as
516+
// bindings updates to support SigHashCache objects).
517+
if spend_tx.input.len() <= input_idx { return Err(()); }
518+
if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
519+
if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
520+
521+
let remotepubkey = self.pubkeys().payment_point;
522+
let witness_script = bitcoin::Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
523+
let sighash = hash_to_message!(&bip143::SigHashCache::new(&*spend_tx).signature_hash(input_idx, &witness_script, descriptor.output.value, SigHashType::All)[..]);
524+
let remotesig = secp_ctx.sign(&sighash, &self.payment_key);
525+
spend_tx.input[input_idx].witness.push(remotesig.serialize_der().to_vec());
526+
spend_tx.input[input_idx].witness[0].push(SigHashType::All as u8);
527+
spend_tx.input[input_idx].witness.push(remotepubkey.serialize().to_vec());
528+
Ok(())
529+
}
530+
531+
/// Sign the single input of spend_tx at index `input_idx` which spends the output
532+
/// described by descriptor.
533+
///
534+
/// Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
535+
/// is not spending the outpoint described by `descriptor.outpoint`, or does not have a
536+
/// sequence set to `descriptor.to_self_delay`.
537+
///
538+
/// (C-not exported) as bindings don't support modifying a Transaction parameter
539+
pub fn sign_dynamic_p2wsh_input<C: Signing>(&self, spend_tx: &mut Transaction, input_idx: usize, descriptor: &DynamicP2WSHOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<(), ()> {
540+
// TODO: We really should be taking the SigHashCache as a parameter here instead of
541+
// spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
542+
// so that we can check them. This requires upstream rust-bitcoin changes (as well as
543+
// bindings updates to support SigHashCache objects).
544+
if spend_tx.input.len() <= input_idx { return Err(()); }
545+
if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
546+
if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
547+
if spend_tx.input[input_idx].sequence != descriptor.to_self_delay as u32 { return Err(()); }
548+
549+
let delayed_payment_key = chan_utils::derive_private_key(&secp_ctx, &descriptor.per_commitment_point, &self.delayed_payment_base_key)
550+
.expect("We constructed the payment_base_key, so we can only fail here if the RNG is busted.");
551+
let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
552+
let witness_script = chan_utils::get_revokeable_redeemscript(&descriptor.revocation_pubkey, descriptor.to_self_delay, &delayed_payment_pubkey);
553+
let sighash = hash_to_message!(&bip143::SigHashCache::new(&*spend_tx).signature_hash(input_idx, &witness_script, descriptor.output.value, SigHashType::All)[..]);
554+
let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
555+
spend_tx.input[input_idx].witness.push(local_delayedsig.serialize_der().to_vec());
556+
spend_tx.input[input_idx].witness[0].push(SigHashType::All as u8);
557+
spend_tx.input[input_idx].witness.push(vec!()); //MINIMALIF
558+
spend_tx.input[input_idx].witness.push(witness_script.clone().into_bytes());
559+
Ok(())
560+
}
501561
}
502562

503563
impl ChannelKeys for InMemoryChannelKeys {
@@ -823,6 +883,144 @@ impl KeysManager {
823883
params.clone()
824884
)
825885
}
886+
887+
/// Creates a Transaction which spends the given descriptors to the given outputs, plus an
888+
/// output to the given change destination (if sufficient change value remains). The
889+
/// transaction will have a feerate, at least, of the given value.
890+
///
891+
/// Returns `Err(())` if the output value is greater than the input value minus required fee or
892+
/// if a descriptor was duplicated.
893+
///
894+
/// May panic if the `SpendableOutputDescriptor`s were not generated by Channels which used
895+
/// this KeysManager or one of the `InMemoryChannelKeys` created by this KeysManager.
896+
pub fn spend_spendable_outputs<C: Signing>(&self, descriptors: &[SpendableOutputDescriptor], outputs: Vec<TxOut>, change_destination_script: Script, feerate_sat_per_1000_weight: u32, secp_ctx: &Secp256k1<C>) -> Result<Transaction, ()> {
897+
let mut input = Vec::new();
898+
let mut input_value = 0;
899+
let mut witness_weight = 0;
900+
let mut output_set = HashSet::with_capacity(descriptors.len());
901+
for outp in descriptors {
902+
match outp {
903+
SpendableOutputDescriptor::StaticOutputCounterpartyPayment(descriptor) => {
904+
input.push(TxIn {
905+
previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
906+
script_sig: Script::new(),
907+
sequence: 0,
908+
witness: Vec::new(),
909+
});
910+
witness_weight += StaticCounterpartyPaymentOutputDescriptor::MAX_WITNESS_LENGTH;
911+
input_value += descriptor.output.value;
912+
if !output_set.insert(descriptor.outpoint) { return Err(()); }
913+
},
914+
SpendableOutputDescriptor::DynamicOutputP2WSH(descriptor) => {
915+
input.push(TxIn {
916+
previous_output: descriptor.outpoint.into_bitcoin_outpoint(),
917+
script_sig: Script::new(),
918+
sequence: descriptor.to_self_delay as u32,
919+
witness: Vec::new(),
920+
});
921+
witness_weight += DynamicP2WSHOutputDescriptor::MAX_WITNESS_LENGTH;
922+
input_value += descriptor.output.value;
923+
if !output_set.insert(descriptor.outpoint) { return Err(()); }
924+
},
925+
SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
926+
input.push(TxIn {
927+
previous_output: outpoint.into_bitcoin_outpoint(),
928+
script_sig: Script::new(),
929+
sequence: 0,
930+
witness: Vec::new(),
931+
});
932+
witness_weight += 1 + 73 + 34;
933+
input_value += output.value;
934+
if !output_set.insert(*outpoint) { return Err(()); }
935+
}
936+
}
937+
if input_value > MAX_VALUE_MSAT / 1000 { return Err(()); }
938+
}
939+
let mut output_value = 0;
940+
for output in outputs.iter() {
941+
output_value += output.value;
942+
if output_value >= input_value { return Err(()); }
943+
}
944+
let mut spend_tx = Transaction {
945+
version: 2,
946+
lock_time: 0,
947+
input,
948+
output: outputs,
949+
};
950+
951+
let mut change_output = TxOut {
952+
script_pubkey: change_destination_script,
953+
value: 0,
954+
};
955+
let change_len = change_output.consensus_encode(&mut std::io::sink()).unwrap();
956+
let mut weight_with_change: i64 = spend_tx.get_weight() as i64 + 2 + witness_weight as i64 + change_len as i64 * 4;
957+
// Include any extra bytes required to push an extra output.
958+
weight_with_change += (VarInt(spend_tx.output.len() as u64 + 1).len() - VarInt(spend_tx.output.len() as u64).len()) as i64 * 4;
959+
// When calculating weight, add two for the flag bytes
960+
let change_value: i64 = (input_value - output_value) as i64 - weight_with_change * feerate_sat_per_1000_weight as i64 / 1000;
961+
if change_value > 0 {
962+
change_output.value = change_value as u64;
963+
spend_tx.output.push(change_output);
964+
} else if (input_value - output_value) as i64 - (spend_tx.get_weight() as i64 + 2 + witness_weight as i64) * feerate_sat_per_1000_weight as i64 / 1000 < 0 {
965+
return Err(());
966+
}
967+
968+
spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + witness_weight + 3) as u64 * feerate_sat_per_1000_weight as u64 / 1000;
969+
970+
let mut keys_cache: Option<(InMemoryChannelKeys, (u64, u64))> = None;
971+
let mut input_idx = 0;
972+
for outp in descriptors {
973+
match outp {
974+
SpendableOutputDescriptor::StaticOutputCounterpartyPayment(descriptor) => {
975+
if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.key_derivation_params {
976+
keys_cache = Some((
977+
self.derive_channel_keys(descriptor.channel_value_satoshis, descriptor.key_derivation_params.0, descriptor.key_derivation_params.1),
978+
descriptor.key_derivation_params));
979+
}
980+
keys_cache.as_ref().unwrap().0.sign_counterparty_payment_input(&mut spend_tx, input_idx, &descriptor, &secp_ctx).unwrap();
981+
},
982+
SpendableOutputDescriptor::DynamicOutputP2WSH(descriptor) => {
983+
if keys_cache.is_none() || keys_cache.as_ref().unwrap().1 != descriptor.key_derivation_params {
984+
keys_cache = Some((
985+
self.derive_channel_keys(descriptor.channel_value_satoshis, descriptor.key_derivation_params.0, descriptor.key_derivation_params.1),
986+
descriptor.key_derivation_params));
987+
}
988+
keys_cache.as_ref().unwrap().0.sign_dynamic_p2wsh_input(&mut spend_tx, input_idx, &descriptor, &secp_ctx).unwrap();
989+
},
990+
SpendableOutputDescriptor::StaticOutput { ref output, .. } => {
991+
let derivation_idx = if output.script_pubkey == self.destination_script {
992+
1
993+
} else {
994+
2
995+
};
996+
let secret = {
997+
// Note that when we aren't serializing the key, network doesn't matter
998+
match ExtendedPrivKey::new_master(Network::Testnet, &self.seed) {
999+
Ok(master_key) => {
1000+
match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx(derivation_idx).expect("key space exhausted")) {
1001+
Ok(key) => key,
1002+
Err(_) => panic!("Your RNG is busted"),
1003+
}
1004+
}
1005+
Err(_) => panic!("Your rng is busted"),
1006+
}
1007+
};
1008+
let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
1009+
if derivation_idx == 2 {
1010+
assert_eq!(pubkey.key, self.shutdown_pubkey);
1011+
}
1012+
let witness_script = bitcoin::Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
1013+
let sighash = hash_to_message!(&bip143::SigHashCache::new(&spend_tx).signature_hash(input_idx, &witness_script, output.value, SigHashType::All)[..]);
1014+
let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
1015+
spend_tx.input[input_idx].witness.push(sig.serialize_der().to_vec());
1016+
spend_tx.input[input_idx].witness[0].push(SigHashType::All as u8);
1017+
spend_tx.input[input_idx].witness.push(pubkey.key.serialize().to_vec());
1018+
},
1019+
}
1020+
input_idx += 1;
1021+
}
1022+
Ok(spend_tx)
1023+
}
8261024
}
8271025

8281026
impl KeysInterface for KeysManager {

0 commit comments

Comments
 (0)