+impl InMemorySigner {
+ /// Create a new InMemorySigner
+ pub fn new<C: Signing>(
+ secp_ctx: &Secp256k1<C>,
+ node_secret: SecretKey,
+ funding_key: SecretKey,
+ revocation_base_key: SecretKey,
+ payment_key: SecretKey,
+ delayed_payment_base_key: SecretKey,
+ htlc_base_key: SecretKey,
+ commitment_seed: [u8; 32],
+ channel_value_satoshis: u64,
+ channel_keys_id: [u8; 32]) -> InMemorySigner {
+ let holder_channel_pubkeys =
+ InMemorySigner::make_holder_keys(secp_ctx, &funding_key, &revocation_base_key,
+ &payment_key, &delayed_payment_base_key,
+ &htlc_base_key);
+ InMemorySigner {
+ funding_key,
+ revocation_base_key,
+ payment_key,
+ delayed_payment_base_key,
+ htlc_base_key,
+ commitment_seed,
+ node_secret,
+ channel_value_satoshis,
+ holder_channel_pubkeys,
+ channel_parameters: None,
+ channel_keys_id,
+ }
+ }
+
+ fn make_holder_keys<C: Signing>(secp_ctx: &Secp256k1<C>,
+ funding_key: &SecretKey,
+ revocation_base_key: &SecretKey,
+ payment_key: &SecretKey,
+ delayed_payment_base_key: &SecretKey,
+ htlc_base_key: &SecretKey) -> ChannelPublicKeys {
+ let from_secret = |s: &SecretKey| PublicKey::from_secret_key(secp_ctx, s);
+ ChannelPublicKeys {
+ funding_pubkey: from_secret(&funding_key),
+ revocation_basepoint: from_secret(&revocation_base_key),
+ payment_point: from_secret(&payment_key),
+ delayed_payment_basepoint: from_secret(&delayed_payment_base_key),
+ htlc_basepoint: from_secret(&htlc_base_key),
+ }
+ }
+
+ /// Counterparty pubkeys.
+ /// Will panic if ready_channel wasn't called.
+ pub fn counterparty_pubkeys(&self) -> &ChannelPublicKeys { &self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().pubkeys }
+
+ /// The contest_delay value specified by our counterparty and applied on holder-broadcastable
+ /// transactions, ie the amount of time that we have to wait to recover our funds if we
+ /// broadcast a transaction.
+ /// Will panic if ready_channel wasn't called.
+ pub fn counterparty_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().counterparty_parameters.as_ref().unwrap().selected_contest_delay }
+
+ /// The contest_delay value specified by us and applied on transactions broadcastable
+ /// by our counterparty, ie the amount of time that they have to wait to recover their funds
+ /// if they broadcast a transaction.
+ /// Will panic if ready_channel wasn't called.
+ pub fn holder_selected_contest_delay(&self) -> u16 { self.get_channel_parameters().holder_selected_contest_delay }
+
+ /// Whether the holder is the initiator
+ /// Will panic if ready_channel wasn't called.
+ pub fn is_outbound(&self) -> bool { self.get_channel_parameters().is_outbound_from_holder }
+
+ /// Funding outpoint
+ /// Will panic if ready_channel wasn't called.
+ pub fn funding_outpoint(&self) -> &OutPoint { self.get_channel_parameters().funding_outpoint.as_ref().unwrap() }
+
+ /// Obtain a ChannelTransactionParameters for this channel, to be used when verifying or
+ /// building transactions.
+ ///
+ /// Will panic if ready_channel wasn't called.
+ pub fn get_channel_parameters(&self) -> &ChannelTransactionParameters {
+ self.channel_parameters.as_ref().unwrap()
+ }
+
+ /// Whether anchors should be used.
+ /// Will panic if ready_channel wasn't called.
+ pub fn opt_anchors(&self) -> bool {
+ self.get_channel_parameters().opt_anchors.is_some()
+ }
+
+ /// Sign the single input of spend_tx at index `input_idx` which spends the output
+ /// described by descriptor, returning the witness stack for the input.
+ ///
+ /// Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
+ /// is not spending the outpoint described by `descriptor.outpoint`,
+ /// or if an output descriptor script_pubkey does not match the one we can spend.
+ pub fn sign_counterparty_payment_input<C: Signing>(&self, spend_tx: &Transaction, input_idx: usize, descriptor: &StaticPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<Vec<Vec<u8>>, ()> {
+ // TODO: We really should be taking the SigHashCache as a parameter here instead of
+ // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
+ // so that we can check them. This requires upstream rust-bitcoin changes (as well as
+ // bindings updates to support SigHashCache objects).
+ if spend_tx.input.len() <= input_idx { return Err(()); }
+ if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
+ if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
+
+ let remotepubkey = self.pubkeys().payment_point;
+ let witness_script = bitcoin::Address::p2pkh(&::bitcoin::PublicKey{compressed: true, inner: remotepubkey}, Network::Testnet).script_pubkey();
+ let sighash = hash_to_message!(&sighash::SighashCache::new(spend_tx).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
+ let remotesig = sign(secp_ctx, &sighash, &self.payment_key);
+ let payment_script = bitcoin::Address::p2wpkh(&::bitcoin::PublicKey{compressed: true, inner: remotepubkey}, Network::Bitcoin).unwrap().script_pubkey();
+
+ if payment_script != descriptor.output.script_pubkey { return Err(()); }
+
+ let mut witness = Vec::with_capacity(2);
+ witness.push(remotesig.serialize_der().to_vec());
+ witness[0].push(EcdsaSighashType::All as u8);
+ witness.push(remotepubkey.serialize().to_vec());
+ Ok(witness)
+ }
+
+ /// Sign the single input of spend_tx at index `input_idx` which spends the output
+ /// described by descriptor, returning the witness stack for the input.
+ ///
+ /// Returns an Err if the input at input_idx does not exist, has a non-empty script_sig,
+ /// is not spending the outpoint described by `descriptor.outpoint`, does not have a
+ /// sequence set to `descriptor.to_self_delay`, or if an output descriptor
+ /// script_pubkey does not match the one we can spend.
+ pub fn sign_dynamic_p2wsh_input<C: Signing>(&self, spend_tx: &Transaction, input_idx: usize, descriptor: &DelayedPaymentOutputDescriptor, secp_ctx: &Secp256k1<C>) -> Result<Vec<Vec<u8>>, ()> {
+ // TODO: We really should be taking the SigHashCache as a parameter here instead of
+ // spend_tx, but ideally the SigHashCache would expose the transaction's inputs read-only
+ // so that we can check them. This requires upstream rust-bitcoin changes (as well as
+ // bindings updates to support SigHashCache objects).
+ if spend_tx.input.len() <= input_idx { return Err(()); }
+ if !spend_tx.input[input_idx].script_sig.is_empty() { return Err(()); }
+ if spend_tx.input[input_idx].previous_output != descriptor.outpoint.into_bitcoin_outpoint() { return Err(()); }
+ if spend_tx.input[input_idx].sequence != descriptor.to_self_delay as u32 { return Err(()); }
+
+ let delayed_payment_key = chan_utils::derive_private_key(&secp_ctx, &descriptor.per_commitment_point, &self.delayed_payment_base_key)
+ .expect("We constructed the payment_base_key, so we can only fail here if the RNG is busted.");
+ let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
+ let witness_script = chan_utils::get_revokeable_redeemscript(&descriptor.revocation_pubkey, descriptor.to_self_delay, &delayed_payment_pubkey);
+ let sighash = hash_to_message!(&sighash::SighashCache::new(spend_tx).segwit_signature_hash(input_idx, &witness_script, descriptor.output.value, EcdsaSighashType::All).unwrap()[..]);
+ let local_delayedsig = sign(secp_ctx, &sighash, &delayed_payment_key);
+ let payment_script = bitcoin::Address::p2wsh(&witness_script, Network::Bitcoin).script_pubkey();
+
+ if descriptor.output.script_pubkey != payment_script { return Err(()); }
+
+ let mut witness = Vec::with_capacity(3);
+ witness.push(local_delayedsig.serialize_der().to_vec());
+ witness[0].push(EcdsaSighashType::All as u8);
+ witness.push(vec!()); //MINIMALIF
+ witness.push(witness_script.clone().into_bytes());
+ Ok(witness)
+ }
+}
+
+impl BaseSign for InMemorySigner {
+ fn get_per_commitment_point(&self, idx: u64, secp_ctx: &Secp256k1<secp256k1::All>) -> PublicKey {
+ let commitment_secret = SecretKey::from_slice(&chan_utils::build_commitment_secret(&self.commitment_seed, idx)).unwrap();
+ PublicKey::from_secret_key(secp_ctx, &commitment_secret)
+ }
+
+ fn release_commitment_secret(&self, idx: u64) -> [u8; 32] {
+ chan_utils::build_commitment_secret(&self.commitment_seed, idx)
+ }
+
+ fn validate_holder_commitment(&self, _holder_tx: &HolderCommitmentTransaction, _preimages: Vec<PaymentPreimage>) -> Result<(), ()> {
+ Ok(())
+ }
+
+ fn pubkeys(&self) -> &ChannelPublicKeys { &self.holder_channel_pubkeys }
+ fn channel_keys_id(&self) -> [u8; 32] { self.channel_keys_id }
+
+ fn sign_counterparty_commitment(&self, commitment_tx: &CommitmentTransaction, _preimages: Vec<PaymentPreimage>, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
+ let trusted_tx = commitment_tx.trust();
+ let keys = trusted_tx.keys();
+
+ let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
+ let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
+
+ let built_tx = trusted_tx.built_transaction();
+ let commitment_sig = built_tx.sign(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx);
+ let commitment_txid = built_tx.txid;
+
+ let mut htlc_sigs = Vec::with_capacity(commitment_tx.htlcs().len());
+ for htlc in commitment_tx.htlcs() {
+ let htlc_tx = chan_utils::build_htlc_transaction(&commitment_txid, commitment_tx.feerate_per_kw(), self.holder_selected_contest_delay(), htlc, self.opt_anchors(), &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
+ let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, self.opt_anchors(), &keys);
+ let htlc_sighashtype = if self.opt_anchors() { EcdsaSighashType::SinglePlusAnyoneCanPay } else { EcdsaSighashType::All };
+ let htlc_sighash = hash_to_message!(&sighash::SighashCache::new(&htlc_tx).segwit_signature_hash(0, &htlc_redeemscript, htlc.amount_msat / 1000, htlc_sighashtype).unwrap()[..]);
+ let holder_htlc_key = chan_utils::derive_private_key(&secp_ctx, &keys.per_commitment_point, &self.htlc_base_key).map_err(|_| ())?;
+ htlc_sigs.push(sign(secp_ctx, &htlc_sighash, &holder_htlc_key));
+ }
+
+ Ok((commitment_sig, htlc_sigs))
+ }
+
+ fn validate_counterparty_revocation(&self, _idx: u64, _secret: &SecretKey) -> Result<(), ()> {
+ Ok(())
+ }
+
+ fn sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
+ let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
+ let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
+ let trusted_tx = commitment_tx.trust();
+ let sig = trusted_tx.built_transaction().sign(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, secp_ctx);
+ let channel_parameters = self.get_channel_parameters();
+ let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), secp_ctx)?;
+ Ok((sig, htlc_sigs))
+ }
+
+ #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
+ fn unsafe_sign_holder_commitment_and_htlcs(&self, commitment_tx: &HolderCommitmentTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<(Signature, Vec<Signature>), ()> {
+ let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
+ let funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
+ let trusted_tx = commitment_tx.trust();
+ let sig = trusted_tx.built_transaction().sign(&self.funding_key, &funding_redeemscript, self.channel_value_satoshis, secp_ctx);
+ let channel_parameters = self.get_channel_parameters();
+ let htlc_sigs = trusted_tx.get_htlc_sigs(&self.htlc_base_key, &channel_parameters.as_holder_broadcastable(), secp_ctx)?;
+ Ok((sig, htlc_sigs))
+ }
+
+ fn sign_justice_revoked_output(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
+ let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key).map_err(|_| ())?;
+ let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
+ let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint).map_err(|_| ())?;
+ let witness_script = {
+ let counterparty_delayedpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().delayed_payment_basepoint).map_err(|_| ())?;
+ chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.holder_selected_contest_delay(), &counterparty_delayedpubkey)
+ };
+ let mut sighash_parts = sighash::SighashCache::new(justice_tx);
+ let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
+ return Ok(sign(secp_ctx, &sighash, &revocation_key))
+ }
+
+ fn sign_justice_revoked_htlc(&self, justice_tx: &Transaction, input: usize, amount: u64, per_commitment_key: &SecretKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
+ let revocation_key = chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_key, &self.revocation_base_key).map_err(|_| ())?;
+ let per_commitment_point = PublicKey::from_secret_key(secp_ctx, &per_commitment_key);
+ let revocation_pubkey = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint).map_err(|_| ())?;
+ let witness_script = {
+ let counterparty_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint).map_err(|_| ())?;
+ let holder_htlcpubkey = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint).map_err(|_| ())?;
+ chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.opt_anchors(), &counterparty_htlcpubkey, &holder_htlcpubkey, &revocation_pubkey)
+ };
+ let mut sighash_parts = sighash::SighashCache::new(justice_tx);
+ let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
+ return Ok(sign(secp_ctx, &sighash, &revocation_key))
+ }
+
+ fn sign_counterparty_htlc_transaction(&self, htlc_tx: &Transaction, input: usize, amount: u64, per_commitment_point: &PublicKey, htlc: &HTLCOutputInCommitment, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
+ if let Ok(htlc_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &self.htlc_base_key) {
+ let witness_script = if let Ok(revocation_pubkey) = chan_utils::derive_public_revocation_key(&secp_ctx, &per_commitment_point, &self.pubkeys().revocation_basepoint) {
+ if let Ok(counterparty_htlcpubkey) = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.counterparty_pubkeys().htlc_basepoint) {
+ if let Ok(htlcpubkey) = chan_utils::derive_public_key(&secp_ctx, &per_commitment_point, &self.pubkeys().htlc_basepoint) {
+ chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, self.opt_anchors(), &counterparty_htlcpubkey, &htlcpubkey, &revocation_pubkey)
+ } else { return Err(()) }
+ } else { return Err(()) }
+ } else { return Err(()) };
+ let mut sighash_parts = sighash::SighashCache::new(htlc_tx);
+ let sighash = hash_to_message!(&sighash_parts.segwit_signature_hash(input, &witness_script, amount, EcdsaSighashType::All).unwrap()[..]);
+ return Ok(sign(secp_ctx, &sighash, &htlc_key))
+ }
+ Err(())
+ }
+
+ fn sign_closing_transaction(&self, closing_tx: &ClosingTransaction, secp_ctx: &Secp256k1<secp256k1::All>) -> Result<Signature, ()> {
+ let funding_pubkey = PublicKey::from_secret_key(secp_ctx, &self.funding_key);
+ let channel_funding_redeemscript = make_funding_redeemscript(&funding_pubkey, &self.counterparty_pubkeys().funding_pubkey);
+ Ok(closing_tx.trust().sign(&self.funding_key, &channel_funding_redeemscript, self.channel_value_satoshis, secp_ctx))
+ }
+
+ fn sign_channel_announcement(&self, msg: &UnsignedChannelAnnouncement, secp_ctx: &Secp256k1<secp256k1::All>)
+ -> Result<(Signature, Signature), ()> {
+ let msghash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
+ Ok((sign(secp_ctx, &msghash, &self.node_secret), sign(secp_ctx, &msghash, &self.funding_key)))
+ }
+
+ fn ready_channel(&mut self, channel_parameters: &ChannelTransactionParameters) {
+ assert!(self.channel_parameters.is_none(), "Acceptance already noted");
+ assert!(channel_parameters.is_populated(), "Channel parameters must be fully populated");
+ self.channel_parameters = Some(channel_parameters.clone());
+ }
+}
+
+const SERIALIZATION_VERSION: u8 = 1;
+const MIN_SERIALIZATION_VERSION: u8 = 1;
+
+impl Sign for InMemorySigner {}
+
+impl Writeable for InMemorySigner {
+ fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
+ write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
+
+ self.funding_key.write(writer)?;
+ self.revocation_base_key.write(writer)?;
+ self.payment_key.write(writer)?;
+ self.delayed_payment_base_key.write(writer)?;
+ self.htlc_base_key.write(writer)?;
+ self.commitment_seed.write(writer)?;
+ self.channel_parameters.write(writer)?;
+ self.channel_value_satoshis.write(writer)?;
+ self.channel_keys_id.write(writer)?;
+
+ write_tlv_fields!(writer, {});
+
+ Ok(())
+ }
+}
+
+impl ReadableArgs<SecretKey> for InMemorySigner {
+ fn read<R: io::Read>(reader: &mut R, node_secret: SecretKey) -> Result<Self, DecodeError> {
+ let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
+
+ let funding_key = Readable::read(reader)?;
+ let revocation_base_key = Readable::read(reader)?;
+ let payment_key = Readable::read(reader)?;
+ let delayed_payment_base_key = Readable::read(reader)?;
+ let htlc_base_key = Readable::read(reader)?;
+ let commitment_seed = Readable::read(reader)?;
+ let counterparty_channel_data = Readable::read(reader)?;
+ let channel_value_satoshis = Readable::read(reader)?;
+ let secp_ctx = Secp256k1::signing_only();
+ let holder_channel_pubkeys =
+ InMemorySigner::make_holder_keys(&secp_ctx, &funding_key, &revocation_base_key,
+ &payment_key, &delayed_payment_base_key,
+ &htlc_base_key);
+ let keys_id = Readable::read(reader)?;
+
+ read_tlv_fields!(reader, {});
+
+ Ok(InMemorySigner {
+ funding_key,
+ revocation_base_key,
+ payment_key,
+ delayed_payment_base_key,
+ htlc_base_key,
+ node_secret,
+ commitment_seed,
+ channel_value_satoshis,
+ holder_channel_pubkeys,
+ channel_parameters: counterparty_channel_data,
+ channel_keys_id: keys_id,
+ })
+ }
+}