+/// Signs a transaction created by build_htlc_transaction. If the transaction is an
+/// HTLC-Success transaction (ie htlc.offered is false), preimage must be set!
+pub(crate) fn sign_htlc_transaction<T: secp256k1::Signing>(tx: &mut Transaction, their_sig: &Signature, preimage: &Option<PaymentPreimage>, htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey, per_commitment_point: &PublicKey, htlc_base_key: &SecretKey, secp_ctx: &Secp256k1<T>) -> Result<(Signature, Script), ()> {
+ if tx.input.len() != 1 { return Err(()); }
+ if tx.input[0].witness.len() != 0 { return Err(()); }
+
+ let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&htlc, a_htlc_key, b_htlc_key, revocation_key);
+
+ let our_htlc_key = derive_private_key(secp_ctx, per_commitment_point, htlc_base_key).map_err(|_| ())?;
+ let sighash = hash_to_message!(&bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
+ let local_tx = PublicKey::from_secret_key(&secp_ctx, &our_htlc_key) == *a_htlc_key;
+ let our_sig = secp_ctx.sign(&sighash, &our_htlc_key);
+
+ tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
+
+ if local_tx { // b, then a
+ tx.input[0].witness.push(their_sig.serialize_der().to_vec());
+ tx.input[0].witness.push(our_sig.serialize_der().to_vec());
+ } else {
+ tx.input[0].witness.push(our_sig.serialize_der().to_vec());
+ tx.input[0].witness.push(their_sig.serialize_der().to_vec());
+ }
+ tx.input[0].witness[1].push(SigHashType::All as u8);
+ tx.input[0].witness[2].push(SigHashType::All as u8);
+
+ if htlc.offered {
+ tx.input[0].witness.push(Vec::new());
+ assert!(preimage.is_none());
+ } else {
+ tx.input[0].witness.push(preimage.unwrap().0.to_vec());
+ }
+
+ tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
+
+ Ok((our_sig, htlc_redeemscript))
+}
+