Use ChannelPublicKeys in Channel
[rust-lightning] / lightning / src / ln / chan_utils.rs
1 //! Various utilities for building scripts and deriving keys related to channels. These are
2 //! largely of interest for those implementing chain::keysinterface::ChannelKeys message signing
3 //! by hand.
4
5 use bitcoin::blockdata::script::{Script,Builder};
6 use bitcoin::blockdata::opcodes;
7 use bitcoin::blockdata::transaction::{TxIn,TxOut,OutPoint,Transaction, SigHashType};
8 use bitcoin::consensus::encode::{self, Decodable, Encodable};
9 use bitcoin::util::bip143;
10
11 use bitcoin_hashes::{Hash, HashEngine};
12 use bitcoin_hashes::sha256::Hash as Sha256;
13 use bitcoin_hashes::ripemd160::Hash as Ripemd160;
14 use bitcoin_hashes::hash160::Hash as Hash160;
15 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
16
17 use ln::channelmanager::{PaymentHash, PaymentPreimage};
18 use ln::msgs::DecodeError;
19 use util::ser::{Readable, Writeable, Writer, WriterWriteAdaptor};
20
21 use secp256k1::key::{SecretKey, PublicKey};
22 use secp256k1::{Secp256k1, Signature};
23 use secp256k1;
24
25 pub(super) const HTLC_SUCCESS_TX_WEIGHT: u64 = 703;
26 pub(super) const HTLC_TIMEOUT_TX_WEIGHT: u64 = 663;
27
28 // Various functions for key derivation and transaction creation for use within channels. Primarily
29 // used in Channel and ChannelMonitor.
30
31 pub(super) fn build_commitment_secret(commitment_seed: &[u8; 32], idx: u64) -> [u8; 32] {
32         let mut res: [u8; 32] = commitment_seed.clone();
33         for i in 0..48 {
34                 let bitpos = 47 - i;
35                 if idx & (1 << bitpos) == (1 << bitpos) {
36                         res[bitpos / 8] ^= 1 << (bitpos & 7);
37                         res = Sha256::hash(&res).into_inner();
38                 }
39         }
40         res
41 }
42
43 /// Derives a per-commitment-transaction private key (eg an htlc key or payment key) from the base
44 /// private key for that type of key and the per_commitment_point (available in TxCreationKeys)
45 pub fn derive_private_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
46         let mut sha = Sha256::engine();
47         sha.input(&per_commitment_point.serialize());
48         sha.input(&PublicKey::from_secret_key(&secp_ctx, &base_secret).serialize());
49         let res = Sha256::from_engine(sha).into_inner();
50
51         let mut key = base_secret.clone();
52         key.add_assign(&res)?;
53         Ok(key)
54 }
55
56 pub(super) fn derive_public_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
57         let mut sha = Sha256::engine();
58         sha.input(&per_commitment_point.serialize());
59         sha.input(&base_point.serialize());
60         let res = Sha256::from_engine(sha).into_inner();
61
62         let hashkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&res)?);
63         base_point.combine(&hashkey)
64 }
65
66 /// Derives a revocation key from its constituent parts.
67 /// Note that this is infallible iff we trust that at least one of the two input keys are randomly
68 /// generated (ie our own).
69 pub(super) fn derive_private_revocation_key<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, per_commitment_secret: &SecretKey, revocation_base_secret: &SecretKey) -> Result<SecretKey, secp256k1::Error> {
70         let revocation_base_point = PublicKey::from_secret_key(&secp_ctx, &revocation_base_secret);
71         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
72
73         let rev_append_commit_hash_key = {
74                 let mut sha = Sha256::engine();
75                 sha.input(&revocation_base_point.serialize());
76                 sha.input(&per_commitment_point.serialize());
77
78                 Sha256::from_engine(sha).into_inner()
79         };
80         let commit_append_rev_hash_key = {
81                 let mut sha = Sha256::engine();
82                 sha.input(&per_commitment_point.serialize());
83                 sha.input(&revocation_base_point.serialize());
84
85                 Sha256::from_engine(sha).into_inner()
86         };
87
88         let mut part_a = revocation_base_secret.clone();
89         part_a.mul_assign(&rev_append_commit_hash_key)?;
90         let mut part_b = per_commitment_secret.clone();
91         part_b.mul_assign(&commit_append_rev_hash_key)?;
92         part_a.add_assign(&part_b[..])?;
93         Ok(part_a)
94 }
95
96 pub(super) fn derive_public_revocation_key<T: secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, revocation_base_point: &PublicKey) -> Result<PublicKey, secp256k1::Error> {
97         let rev_append_commit_hash_key = {
98                 let mut sha = Sha256::engine();
99                 sha.input(&revocation_base_point.serialize());
100                 sha.input(&per_commitment_point.serialize());
101
102                 Sha256::from_engine(sha).into_inner()
103         };
104         let commit_append_rev_hash_key = {
105                 let mut sha = Sha256::engine();
106                 sha.input(&per_commitment_point.serialize());
107                 sha.input(&revocation_base_point.serialize());
108
109                 Sha256::from_engine(sha).into_inner()
110         };
111
112         let mut part_a = revocation_base_point.clone();
113         part_a.mul_assign(&secp_ctx, &rev_append_commit_hash_key)?;
114         let mut part_b = per_commitment_point.clone();
115         part_b.mul_assign(&secp_ctx, &commit_append_rev_hash_key)?;
116         part_a.combine(&part_b)
117 }
118
119 /// The set of public keys which are used in the creation of one commitment transaction.
120 /// These are derived from the channel base keys and per-commitment data.
121 #[derive(PartialEq)]
122 pub struct TxCreationKeys {
123         /// The per-commitment public key which was used to derive the other keys.
124         pub per_commitment_point: PublicKey,
125         /// The revocation key which is used to allow the owner of the commitment transaction to
126         /// provide their counterparty the ability to punish them if they broadcast an old state.
127         pub(crate) revocation_key: PublicKey,
128         /// A's HTLC Key
129         pub(crate) a_htlc_key: PublicKey,
130         /// B's HTLC Key
131         pub(crate) b_htlc_key: PublicKey,
132         /// A's Payment Key (which isn't allowed to be spent from for some delay)
133         pub(crate) a_delayed_payment_key: PublicKey,
134         /// B's Payment Key
135         pub(crate) b_payment_key: PublicKey,
136 }
137
138 /// One counterparty's public keys which do not change over the life of a channel.
139 #[derive(Clone)]
140 pub struct ChannelPublicKeys {
141         /// The public key which is used to sign all commitment transactions, as it appears in the
142         /// on-chain channel lock-in 2-of-2 multisig output.
143         pub funding_pubkey: PublicKey,
144         /// The base point which is used (with derive_public_revocation_key) to derive per-commitment
145         /// revocation keys. The per-commitment revocation private key is then revealed by the owner of
146         /// a commitment transaction so that their counterparty can claim all available funds if they
147         /// broadcast an old state.
148         pub revocation_basepoint: PublicKey,
149         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
150         /// public key which receives immediately-spendable non-HTLC-encumbered funds.
151         pub payment_basepoint: PublicKey,
152         /// The base point which is used (with derive_public_key) to derive a per-commitment payment
153         /// public key which receives non-HTLC-encumbered funds which are only available for spending
154         /// after some delay (or can be claimed via the revocation path).
155         pub delayed_payment_basepoint: PublicKey,
156         /// The base point which is used (with derive_public_key) to derive a per-commitment public key
157         /// which is used to encumber HTLC-in-flight outputs.
158         pub htlc_basepoint: PublicKey,
159 }
160
161 impl_writeable!(ChannelPublicKeys, 33*5, {
162         funding_pubkey,
163         revocation_basepoint,
164         payment_basepoint,
165         delayed_payment_basepoint,
166         htlc_basepoint
167 });
168
169
170 impl TxCreationKeys {
171         pub(crate) fn new<T: secp256k1::Signing + secp256k1::Verification>(secp_ctx: &Secp256k1<T>, per_commitment_point: &PublicKey, a_delayed_payment_base: &PublicKey, a_htlc_base: &PublicKey, b_revocation_base: &PublicKey, b_payment_base: &PublicKey, b_htlc_base: &PublicKey) -> Result<TxCreationKeys, secp256k1::Error> {
172                 Ok(TxCreationKeys {
173                         per_commitment_point: per_commitment_point.clone(),
174                         revocation_key: derive_public_revocation_key(&secp_ctx, &per_commitment_point, &b_revocation_base)?,
175                         a_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_htlc_base)?,
176                         b_htlc_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_htlc_base)?,
177                         a_delayed_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &a_delayed_payment_base)?,
178                         b_payment_key: derive_public_key(&secp_ctx, &per_commitment_point, &b_payment_base)?,
179                 })
180         }
181 }
182
183 /// Gets the "to_local" output redeemscript, ie the script which is time-locked or spendable by
184 /// the revocation key
185 pub(super) fn get_revokeable_redeemscript(revocation_key: &PublicKey, to_self_delay: u16, delayed_payment_key: &PublicKey) -> Script {
186         Builder::new().push_opcode(opcodes::all::OP_IF)
187                       .push_slice(&revocation_key.serialize())
188                       .push_opcode(opcodes::all::OP_ELSE)
189                       .push_int(to_self_delay as i64)
190                       .push_opcode(opcodes::all::OP_CSV)
191                       .push_opcode(opcodes::all::OP_DROP)
192                       .push_slice(&delayed_payment_key.serialize())
193                       .push_opcode(opcodes::all::OP_ENDIF)
194                       .push_opcode(opcodes::all::OP_CHECKSIG)
195                       .into_script()
196 }
197
198 #[derive(Clone, PartialEq)]
199 /// Information about an HTLC as it appears in a commitment transaction
200 pub struct HTLCOutputInCommitment {
201         /// Whether the HTLC was "offered" (ie outbound in relation to this commitment transaction).
202         /// Note that this is not the same as whether it is ountbound *from us*. To determine that you
203         /// need to compare this value to whether the commitment transaction in question is that of
204         /// the remote party or our own.
205         pub offered: bool,
206         /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is
207         /// this divided by 1000.
208         pub amount_msat: u64,
209         /// The CLTV lock-time at which this HTLC expires.
210         pub cltv_expiry: u32,
211         /// The hash of the preimage which unlocks this HTLC.
212         pub payment_hash: PaymentHash,
213         /// The position within the commitment transactions' outputs. This may be None if the value is
214         /// below the dust limit (in which case no output appears in the commitment transaction and the
215         /// value is spent to additional transaction fees).
216         pub transaction_output_index: Option<u32>,
217 }
218
219 #[inline]
220 pub(super) fn get_htlc_redeemscript_with_explicit_keys(htlc: &HTLCOutputInCommitment, a_htlc_key: &PublicKey, b_htlc_key: &PublicKey, revocation_key: &PublicKey) -> Script {
221         let payment_hash160 = Ripemd160::hash(&htlc.payment_hash.0[..]).into_inner();
222         if htlc.offered {
223                 Builder::new().push_opcode(opcodes::all::OP_DUP)
224                               .push_opcode(opcodes::all::OP_HASH160)
225                               .push_slice(&Hash160::hash(&revocation_key.serialize())[..])
226                               .push_opcode(opcodes::all::OP_EQUAL)
227                               .push_opcode(opcodes::all::OP_IF)
228                               .push_opcode(opcodes::all::OP_CHECKSIG)
229                               .push_opcode(opcodes::all::OP_ELSE)
230                               .push_slice(&b_htlc_key.serialize()[..])
231                               .push_opcode(opcodes::all::OP_SWAP)
232                               .push_opcode(opcodes::all::OP_SIZE)
233                               .push_int(32)
234                               .push_opcode(opcodes::all::OP_EQUAL)
235                               .push_opcode(opcodes::all::OP_NOTIF)
236                               .push_opcode(opcodes::all::OP_DROP)
237                               .push_int(2)
238                               .push_opcode(opcodes::all::OP_SWAP)
239                               .push_slice(&a_htlc_key.serialize()[..])
240                               .push_int(2)
241                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
242                               .push_opcode(opcodes::all::OP_ELSE)
243                               .push_opcode(opcodes::all::OP_HASH160)
244                               .push_slice(&payment_hash160)
245                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
246                               .push_opcode(opcodes::all::OP_CHECKSIG)
247                               .push_opcode(opcodes::all::OP_ENDIF)
248                               .push_opcode(opcodes::all::OP_ENDIF)
249                               .into_script()
250         } else {
251                 Builder::new().push_opcode(opcodes::all::OP_DUP)
252                               .push_opcode(opcodes::all::OP_HASH160)
253                               .push_slice(&Hash160::hash(&revocation_key.serialize())[..])
254                               .push_opcode(opcodes::all::OP_EQUAL)
255                               .push_opcode(opcodes::all::OP_IF)
256                               .push_opcode(opcodes::all::OP_CHECKSIG)
257                               .push_opcode(opcodes::all::OP_ELSE)
258                               .push_slice(&b_htlc_key.serialize()[..])
259                               .push_opcode(opcodes::all::OP_SWAP)
260                               .push_opcode(opcodes::all::OP_SIZE)
261                               .push_int(32)
262                               .push_opcode(opcodes::all::OP_EQUAL)
263                               .push_opcode(opcodes::all::OP_IF)
264                               .push_opcode(opcodes::all::OP_HASH160)
265                               .push_slice(&payment_hash160)
266                               .push_opcode(opcodes::all::OP_EQUALVERIFY)
267                               .push_int(2)
268                               .push_opcode(opcodes::all::OP_SWAP)
269                               .push_slice(&a_htlc_key.serialize()[..])
270                               .push_int(2)
271                               .push_opcode(opcodes::all::OP_CHECKMULTISIG)
272                               .push_opcode(opcodes::all::OP_ELSE)
273                               .push_opcode(opcodes::all::OP_DROP)
274                               .push_int(htlc.cltv_expiry as i64)
275                               .push_opcode(opcodes::all::OP_CLTV)
276                               .push_opcode(opcodes::all::OP_DROP)
277                               .push_opcode(opcodes::all::OP_CHECKSIG)
278                               .push_opcode(opcodes::all::OP_ENDIF)
279                               .push_opcode(opcodes::all::OP_ENDIF)
280                               .into_script()
281         }
282 }
283
284 /// note here that 'a_revocation_key' is generated using b_revocation_basepoint and a's
285 /// commitment secret. 'htlc' does *not* need to have its previous_output_index filled.
286 #[inline]
287 pub fn get_htlc_redeemscript(htlc: &HTLCOutputInCommitment, keys: &TxCreationKeys) -> Script {
288         get_htlc_redeemscript_with_explicit_keys(htlc, &keys.a_htlc_key, &keys.b_htlc_key, &keys.revocation_key)
289 }
290
291 /// Gets the redeemscript for a funding output from the two funding public keys.
292 /// Note that the order of funding public keys does not matter.
293 pub fn make_funding_redeemscript(a: &PublicKey, b: &PublicKey) -> Script {
294         let our_funding_key = a.serialize();
295         let their_funding_key = b.serialize();
296
297         let builder = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2);
298         if our_funding_key[..] < their_funding_key[..] {
299                 builder.push_slice(&our_funding_key)
300                         .push_slice(&their_funding_key)
301         } else {
302                 builder.push_slice(&their_funding_key)
303                         .push_slice(&our_funding_key)
304         }.push_opcode(opcodes::all::OP_PUSHNUM_2).push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script()
305 }
306
307 /// panics if htlc.transaction_output_index.is_none()!
308 pub fn build_htlc_transaction(prev_hash: &Sha256dHash, feerate_per_kw: u64, to_self_delay: u16, htlc: &HTLCOutputInCommitment, a_delayed_payment_key: &PublicKey, revocation_key: &PublicKey) -> Transaction {
309         let mut txins: Vec<TxIn> = Vec::new();
310         txins.push(TxIn {
311                 previous_output: OutPoint {
312                         txid: prev_hash.clone(),
313                         vout: htlc.transaction_output_index.expect("Can't build an HTLC transaction for a dust output"),
314                 },
315                 script_sig: Script::new(),
316                 sequence: 0,
317                 witness: Vec::new(),
318         });
319
320         let total_fee = if htlc.offered {
321                         feerate_per_kw * HTLC_TIMEOUT_TX_WEIGHT / 1000
322                 } else {
323                         feerate_per_kw * HTLC_SUCCESS_TX_WEIGHT / 1000
324                 };
325
326         let mut txouts: Vec<TxOut> = Vec::new();
327         txouts.push(TxOut {
328                 script_pubkey: get_revokeable_redeemscript(revocation_key, to_self_delay, a_delayed_payment_key).to_v0_p2wsh(),
329                 value: htlc.amount_msat / 1000 - total_fee //TODO: BOLT 3 does not specify if we should add amount_msat before dividing or if we should divide by 1000 before subtracting (as we do here)
330         });
331
332         Transaction {
333                 version: 2,
334                 lock_time: if htlc.offered { htlc.cltv_expiry } else { 0 },
335                 input: txins,
336                 output: txouts,
337         }
338 }
339
340 /// Signs a transaction created by build_htlc_transaction. If the transaction is an
341 /// HTLC-Success transaction (ie htlc.offered is false), preimage must be set!
342 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), ()> {
343         if tx.input.len() != 1 { return Err(()); }
344         if tx.input[0].witness.len() != 0 { return Err(()); }
345
346         let htlc_redeemscript = get_htlc_redeemscript_with_explicit_keys(&htlc, a_htlc_key, b_htlc_key, revocation_key);
347
348         let our_htlc_key = derive_private_key(secp_ctx, per_commitment_point, htlc_base_key).map_err(|_| ())?;
349         let sighash = hash_to_message!(&bip143::SighashComponents::new(&tx).sighash_all(&tx.input[0], &htlc_redeemscript, htlc.amount_msat / 1000)[..]);
350         let local_tx = PublicKey::from_secret_key(&secp_ctx, &our_htlc_key) == *a_htlc_key;
351         let our_sig = secp_ctx.sign(&sighash, &our_htlc_key);
352
353         tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
354
355         if local_tx { // b, then a
356                 tx.input[0].witness.push(their_sig.serialize_der().to_vec());
357                 tx.input[0].witness.push(our_sig.serialize_der().to_vec());
358         } else {
359                 tx.input[0].witness.push(our_sig.serialize_der().to_vec());
360                 tx.input[0].witness.push(their_sig.serialize_der().to_vec());
361         }
362         tx.input[0].witness[1].push(SigHashType::All as u8);
363         tx.input[0].witness[2].push(SigHashType::All as u8);
364
365         if htlc.offered {
366                 tx.input[0].witness.push(Vec::new());
367                 assert!(preimage.is_none());
368         } else {
369                 tx.input[0].witness.push(preimage.unwrap().0.to_vec());
370         }
371
372         tx.input[0].witness.push(htlc_redeemscript.as_bytes().to_vec());
373
374         Ok((our_sig, htlc_redeemscript))
375 }
376
377 #[derive(Clone)]
378 /// We use this to track local commitment transactions and put off signing them until we are ready
379 /// to broadcast. Eventually this will require a signer which is possibly external, but for now we
380 /// just pass in the SecretKeys required.
381 pub(crate) struct LocalCommitmentTransaction {
382         tx: Transaction
383 }
384 impl LocalCommitmentTransaction {
385         #[cfg(test)]
386         pub fn dummy() -> Self {
387                 Self { tx: Transaction {
388                         version: 2,
389                         input: Vec::new(),
390                         output: Vec::new(),
391                         lock_time: 0,
392                 } }
393         }
394
395         pub fn new_missing_local_sig(mut tx: Transaction, their_sig: &Signature, our_funding_key: &PublicKey, their_funding_key: &PublicKey) -> LocalCommitmentTransaction {
396                 if tx.input.len() != 1 { panic!("Tried to store a commitment transaction that had input count != 1!"); }
397                 if tx.input[0].witness.len() != 0 { panic!("Tried to store a signed commitment transaction?"); }
398
399                 tx.input[0].witness.push(Vec::new()); // First is the multisig dummy
400
401                 if our_funding_key.serialize()[..] < their_funding_key.serialize()[..] {
402                         tx.input[0].witness.push(Vec::new());
403                         tx.input[0].witness.push(their_sig.serialize_der().to_vec());
404                         tx.input[0].witness[2].push(SigHashType::All as u8);
405                 } else {
406                         tx.input[0].witness.push(their_sig.serialize_der().to_vec());
407                         tx.input[0].witness[1].push(SigHashType::All as u8);
408                         tx.input[0].witness.push(Vec::new());
409                 }
410
411                 Self { tx }
412         }
413
414         pub fn txid(&self) -> Sha256dHash {
415                 self.tx.txid()
416         }
417
418         pub fn has_local_sig(&self) -> bool {
419                 if self.tx.input.len() != 1 { panic!("Commitment transactions must have input count == 1!"); }
420                 if self.tx.input[0].witness.len() == 4 {
421                         assert!(!self.tx.input[0].witness[1].is_empty());
422                         assert!(!self.tx.input[0].witness[2].is_empty());
423                         true
424                 } else {
425                         assert_eq!(self.tx.input[0].witness.len(), 3);
426                         assert!(self.tx.input[0].witness[0].is_empty());
427                         assert!(self.tx.input[0].witness[1].is_empty() || self.tx.input[0].witness[2].is_empty());
428                         false
429                 }
430         }
431
432         pub fn add_local_sig<T: secp256k1::Signing>(&mut self, funding_key: &SecretKey, funding_redeemscript: &Script, channel_value_satoshis: u64, secp_ctx: &Secp256k1<T>) {
433                 if self.has_local_sig() { return; }
434                 let sighash = hash_to_message!(&bip143::SighashComponents::new(&self.tx)
435                         .sighash_all(&self.tx.input[0], funding_redeemscript, channel_value_satoshis)[..]);
436                 let our_sig = secp_ctx.sign(&sighash, funding_key);
437
438                 if self.tx.input[0].witness[1].is_empty() {
439                         self.tx.input[0].witness[1] = our_sig.serialize_der().to_vec();
440                         self.tx.input[0].witness[1].push(SigHashType::All as u8);
441                 } else {
442                         self.tx.input[0].witness[2] = our_sig.serialize_der().to_vec();
443                         self.tx.input[0].witness[2].push(SigHashType::All as u8);
444                 }
445
446                 self.tx.input[0].witness.push(funding_redeemscript.as_bytes().to_vec());
447         }
448
449         pub fn without_valid_witness(&self) -> &Transaction { &self.tx }
450         pub fn with_valid_witness(&self) -> &Transaction {
451                 assert!(self.has_local_sig());
452                 &self.tx
453         }
454 }
455 impl PartialEq for LocalCommitmentTransaction {
456         // We dont care whether we are signed in equality comparison
457         fn eq(&self, o: &Self) -> bool {
458                 self.txid() == o.txid()
459         }
460 }
461 impl Writeable for LocalCommitmentTransaction {
462         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
463                 if let Err(e) = self.tx.consensus_encode(&mut WriterWriteAdaptor(writer)) {
464                         match e {
465                                 encode::Error::Io(e) => return Err(e),
466                                 _ => panic!("local tx must have been well-formed!"),
467                         }
468                 }
469                 Ok(())
470         }
471 }
472 impl<R: ::std::io::Read> Readable<R> for LocalCommitmentTransaction {
473         fn read(reader: &mut R) -> Result<Self, DecodeError> {
474                 let tx = match Transaction::consensus_decode(reader.by_ref()) {
475                         Ok(tx) => tx,
476                         Err(e) => match e {
477                                 encode::Error::Io(ioe) => return Err(DecodeError::Io(ioe)),
478                                 _ => return Err(DecodeError::InvalidValue),
479                         },
480                 };
481
482                 if tx.input.len() != 1 {
483                         // Ensure tx didn't hit the 0-input ambiguity case.
484                         return Err(DecodeError::InvalidValue);
485                 }
486                 Ok(Self { tx })
487         }
488 }