Skip to content

Commit 79a0a0c

Browse files
committed
Migrate ChannelMonitor serialization to new ser framework(ish)
Sadly we can't straight up use the new serialization framework as we have a few different serialization variants, but that's OK, it looks identical and is just missing the Writeable impl
1 parent 28d0d44 commit 79a0a0c

File tree

3 files changed

+101
-72
lines changed

3 files changed

+101
-72
lines changed

fuzz/fuzz_targets/chanmon_deser_target.rs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,30 @@ extern crate lightning;
55

66
use lightning::ln::channelmonitor;
77
use lightning::util::reset_rng_state;
8-
use lightning::util::ser::Readable;
8+
use lightning::util::ser::{Readable, Writer};
99

1010
use std::io::Cursor;
1111

12+
struct VecWriter(Vec<u8>);
13+
impl Writer for VecWriter {
14+
fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
15+
self.0.extend_from_slice(buf);
16+
Ok(())
17+
}
18+
fn size_hint(&mut self, size: usize) {
19+
self.0.reserve_exact(size);
20+
}
21+
}
22+
1223
#[inline]
1324
pub fn do_test(data: &[u8]) {
1425
reset_rng_state();
1526
if let Ok(monitor) = channelmonitor::ChannelMonitor::read(&mut Cursor::new(data)) {
16-
assert!(channelmonitor::ChannelMonitor::read(&mut Cursor::new(&monitor.serialize_for_disk()[..])).unwrap() == monitor);
17-
monitor.serialize_for_watchtower();
27+
let mut w = VecWriter(Vec::new());
28+
monitor.write_for_disk(&mut w).unwrap();
29+
assert!(channelmonitor::ChannelMonitor::read(&mut Cursor::new(&w.0)).unwrap() == monitor);
30+
w.0.clear();
31+
monitor.write_for_watchtower(&mut w).unwrap();
1832
}
1933
}
2034

src/ln/channelmonitor.rs

Lines changed: 67 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ use ln::chan_utils;
2828
use ln::chan_utils::HTLCOutputInCommitment;
2929
use chain::chaininterface::{ChainListener, ChainWatchInterface, BroadcasterInterface};
3030
use chain::transaction::OutPoint;
31-
use util::ser::Readable;
31+
use util::ser::{Readable, Writer};
3232
use util::sha2::Sha256;
3333
use util::byte_utils;
3434

@@ -531,159 +531,160 @@ impl ChannelMonitor {
531531
}
532532

533533
/// Serializes into a vec, with various modes for the exposed pub fns
534-
fn serialize(&self, for_local_storage: bool) -> Vec<u8> {
535-
let mut res = Vec::new();
536-
res.push(SERIALIZATION_VERSION);
537-
res.push(MIN_SERIALIZATION_VERSION);
534+
fn write<W: Writer>(&self, writer: &mut W, for_local_storage: bool) -> Result<(), ::std::io::Error> {
535+
//TODO: We still write out all the serialization here manually instead of using the fancy
536+
//serialization framework we have, we should migrate things over to it.
537+
writer.write_all(&[SERIALIZATION_VERSION; 1])?;
538+
writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
538539

539540
match &self.funding_txo {
540541
&Some((ref outpoint, ref script)) => {
541-
res.extend_from_slice(&outpoint.txid[..]);
542-
res.extend_from_slice(&byte_utils::be16_to_array(outpoint.index));
543-
res.extend_from_slice(&byte_utils::be64_to_array(script.len() as u64));
544-
res.extend_from_slice(&script[..]);
542+
writer.write_all(&outpoint.txid[..])?;
543+
writer.write_all(&byte_utils::be16_to_array(outpoint.index))?;
544+
writer.write_all(&byte_utils::be64_to_array(script.len() as u64))?;
545+
writer.write_all(&script[..])?;
545546
},
546547
&None => {
547548
// We haven't even been initialized...not sure why anyone is serializing us, but
548549
// not much to give them.
549-
return res;
550+
return Ok(());
550551
},
551552
}
552553

553554
// Set in initial Channel-object creation, so should always be set by now:
554-
res.extend_from_slice(&byte_utils::be48_to_array(self.commitment_transaction_number_obscure_factor));
555+
writer.write_all(&byte_utils::be48_to_array(self.commitment_transaction_number_obscure_factor))?;
555556

556557
match self.key_storage {
557558
KeyStorage::PrivMode { ref revocation_base_key, ref htlc_base_key } => {
558-
res.push(0);
559-
res.extend_from_slice(&revocation_base_key[..]);
560-
res.extend_from_slice(&htlc_base_key[..]);
559+
writer.write_all(&[0; 1])?;
560+
writer.write_all(&revocation_base_key[..])?;
561+
writer.write_all(&htlc_base_key[..])?;
561562
},
562563
KeyStorage::SigsMode { .. } => unimplemented!(),
563564
}
564565

565-
res.extend_from_slice(&self.delayed_payment_base_key.serialize());
566-
res.extend_from_slice(&self.their_htlc_base_key.as_ref().unwrap().serialize());
567-
res.extend_from_slice(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize());
566+
writer.write_all(&self.delayed_payment_base_key.serialize())?;
567+
writer.write_all(&self.their_htlc_base_key.as_ref().unwrap().serialize())?;
568+
writer.write_all(&self.their_delayed_payment_base_key.as_ref().unwrap().serialize())?;
568569

569570
match self.their_cur_revocation_points {
570571
Some((idx, pubkey, second_option)) => {
571-
res.extend_from_slice(&byte_utils::be48_to_array(idx));
572-
res.extend_from_slice(&pubkey.serialize());
572+
writer.write_all(&byte_utils::be48_to_array(idx))?;
573+
writer.write_all(&pubkey.serialize())?;
573574
match second_option {
574575
Some(second_pubkey) => {
575-
res.extend_from_slice(&second_pubkey.serialize());
576+
writer.write_all(&second_pubkey.serialize())?;
576577
},
577578
None => {
578-
res.extend_from_slice(&[0; 33]);
579+
writer.write_all(&[0; 33])?;
579580
},
580581
}
581582
},
582583
None => {
583-
res.extend_from_slice(&byte_utils::be48_to_array(0));
584+
writer.write_all(&byte_utils::be48_to_array(0))?;
584585
},
585586
}
586587

587-
res.extend_from_slice(&byte_utils::be16_to_array(self.our_to_self_delay));
588-
res.extend_from_slice(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()));
588+
writer.write_all(&byte_utils::be16_to_array(self.our_to_self_delay))?;
589+
writer.write_all(&byte_utils::be16_to_array(self.their_to_self_delay.unwrap()))?;
589590

590591
for &(ref secret, ref idx) in self.old_secrets.iter() {
591-
res.extend_from_slice(secret);
592-
res.extend_from_slice(&byte_utils::be64_to_array(*idx));
592+
writer.write_all(secret)?;
593+
writer.write_all(&byte_utils::be64_to_array(*idx))?;
593594
}
594595

595596
macro_rules! serialize_htlc_in_commitment {
596597
($htlc_output: expr) => {
597-
res.push($htlc_output.offered as u8);
598-
res.extend_from_slice(&byte_utils::be64_to_array($htlc_output.amount_msat));
599-
res.extend_from_slice(&byte_utils::be32_to_array($htlc_output.cltv_expiry));
600-
res.extend_from_slice(&$htlc_output.payment_hash);
601-
res.extend_from_slice(&byte_utils::be32_to_array($htlc_output.transaction_output_index));
598+
writer.write_all(&[$htlc_output.offered as u8; 1])?;
599+
writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
600+
writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
601+
writer.write_all(&$htlc_output.payment_hash)?;
602+
writer.write_all(&byte_utils::be32_to_array($htlc_output.transaction_output_index))?;
602603
}
603604
}
604605

605-
res.extend_from_slice(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64));
606+
writer.write_all(&byte_utils::be64_to_array(self.remote_claimable_outpoints.len() as u64))?;
606607
for (txid, htlc_outputs) in self.remote_claimable_outpoints.iter() {
607-
res.extend_from_slice(&txid[..]);
608-
res.extend_from_slice(&byte_utils::be64_to_array(htlc_outputs.len() as u64));
608+
writer.write_all(&txid[..])?;
609+
writer.write_all(&byte_utils::be64_to_array(htlc_outputs.len() as u64))?;
609610
for htlc_output in htlc_outputs.iter() {
610611
serialize_htlc_in_commitment!(htlc_output);
611612
}
612613
}
613614

614615
{
615616
let remote_commitment_txn_on_chain = self.remote_commitment_txn_on_chain.lock().unwrap();
616-
res.extend_from_slice(&byte_utils::be64_to_array(remote_commitment_txn_on_chain.len() as u64));
617+
writer.write_all(&byte_utils::be64_to_array(remote_commitment_txn_on_chain.len() as u64))?;
617618
for (txid, commitment_number) in remote_commitment_txn_on_chain.iter() {
618-
res.extend_from_slice(&txid[..]);
619-
res.extend_from_slice(&byte_utils::be48_to_array(*commitment_number));
619+
writer.write_all(&txid[..])?;
620+
writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
620621
}
621622
}
622623

623624
if for_local_storage {
624-
res.extend_from_slice(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64));
625+
writer.write_all(&byte_utils::be64_to_array(self.remote_hash_commitment_number.len() as u64))?;
625626
for (payment_hash, commitment_number) in self.remote_hash_commitment_number.iter() {
626-
res.extend_from_slice(payment_hash);
627-
res.extend_from_slice(&byte_utils::be48_to_array(*commitment_number));
627+
writer.write_all(payment_hash)?;
628+
writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
628629
}
629630
} else {
630-
res.extend_from_slice(&byte_utils::be64_to_array(0));
631+
writer.write_all(&byte_utils::be64_to_array(0))?;
631632
}
632633

633634
macro_rules! serialize_local_tx {
634635
($local_tx: expr) => {
635636
let tx_ser = serialize::serialize(&$local_tx.tx).unwrap();
636-
res.extend_from_slice(&byte_utils::be64_to_array(tx_ser.len() as u64));
637-
res.extend_from_slice(&tx_ser);
637+
writer.write_all(&byte_utils::be64_to_array(tx_ser.len() as u64))?;
638+
writer.write_all(&tx_ser)?;
638639

639-
res.extend_from_slice(&$local_tx.revocation_key.serialize());
640-
res.extend_from_slice(&$local_tx.a_htlc_key.serialize());
641-
res.extend_from_slice(&$local_tx.b_htlc_key.serialize());
642-
res.extend_from_slice(&$local_tx.delayed_payment_key.serialize());
640+
writer.write_all(&$local_tx.revocation_key.serialize())?;
641+
writer.write_all(&$local_tx.a_htlc_key.serialize())?;
642+
writer.write_all(&$local_tx.b_htlc_key.serialize())?;
643+
writer.write_all(&$local_tx.delayed_payment_key.serialize())?;
643644

644-
res.extend_from_slice(&byte_utils::be64_to_array($local_tx.feerate_per_kw));
645-
res.extend_from_slice(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64));
645+
writer.write_all(&byte_utils::be64_to_array($local_tx.feerate_per_kw))?;
646+
writer.write_all(&byte_utils::be64_to_array($local_tx.htlc_outputs.len() as u64))?;
646647
for &(ref htlc_output, ref their_sig, ref our_sig) in $local_tx.htlc_outputs.iter() {
647648
serialize_htlc_in_commitment!(htlc_output);
648-
res.extend_from_slice(&their_sig.serialize_compact(&self.secp_ctx));
649-
res.extend_from_slice(&our_sig.serialize_compact(&self.secp_ctx));
649+
writer.write_all(&their_sig.serialize_compact(&self.secp_ctx))?;
650+
writer.write_all(&our_sig.serialize_compact(&self.secp_ctx))?;
650651
}
651652
}
652653
}
653654

654655
if let Some(ref prev_local_tx) = self.prev_local_signed_commitment_tx {
655-
res.push(1);
656+
writer.write_all(&[1; 1])?;
656657
serialize_local_tx!(prev_local_tx);
657658
} else {
658-
res.push(0);
659+
writer.write_all(&[0; 1])?;
659660
}
660661

661662
if let Some(ref cur_local_tx) = self.current_local_signed_commitment_tx {
662-
res.push(1);
663+
writer.write_all(&[1; 1])?;
663664
serialize_local_tx!(cur_local_tx);
664665
} else {
665-
res.push(0);
666+
writer.write_all(&[0; 1])?;
666667
}
667668

668-
res.extend_from_slice(&byte_utils::be64_to_array(self.payment_preimages.len() as u64));
669+
writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
669670
for payment_preimage in self.payment_preimages.values() {
670-
res.extend_from_slice(payment_preimage);
671+
writer.write_all(payment_preimage)?;
671672
}
672673

673-
res.extend_from_slice(&byte_utils::be64_to_array(self.destination_script.len() as u64));
674-
res.extend_from_slice(&self.destination_script[..]);
674+
writer.write_all(&byte_utils::be64_to_array(self.destination_script.len() as u64))?;
675+
writer.write_all(&self.destination_script[..])?;
675676

676-
res
677+
Ok(())
677678
}
678679

679-
/// Encodes this monitor into a byte array, suitable for writing to disk.
680-
pub fn serialize_for_disk(&self) -> Vec<u8> {
681-
self.serialize(true)
680+
/// Writes this monitor into the given writer, suitable for writing to disk.
681+
pub fn write_for_disk<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
682+
self.write(writer, true)
682683
}
683684

684-
/// Encodes this monitor into a byte array, suitable for sending to a remote watchtower
685-
pub fn serialize_for_watchtower(&self) -> Vec<u8> {
686-
self.serialize(false)
685+
/// Encodes this monitor into the given writer, suitable for sending to a remote watchtower
686+
pub fn write_for_watchtower<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
687+
self.write(writer, false)
687688
}
688689

689690
//TODO: Functions to serialize/deserialize (with different forms depending on which information

src/util/test_utils.rs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use ln::msgs;
66
use ln::msgs::{HandleError};
77
use util::events;
88
use util::logger::{Logger, Level, Record};
9-
use util::ser::Readable;
9+
use util::ser::{Readable, Writer};
1010

1111
use bitcoin::blockdata::transaction::Transaction;
1212

@@ -15,6 +15,17 @@ use secp256k1::PublicKey;
1515
use std::sync::{Arc,Mutex};
1616
use std::{mem};
1717

18+
struct VecWriter(Vec<u8>);
19+
impl Writer for VecWriter {
20+
fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
21+
self.0.extend_from_slice(buf);
22+
Ok(())
23+
}
24+
fn size_hint(&mut self, size: usize) {
25+
self.0.reserve_exact(size);
26+
}
27+
}
28+
1829
pub struct TestFeeEstimator {
1930
pub sat_per_kw: u64,
2031
}
@@ -40,8 +51,11 @@ impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
4051
fn add_update_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
4152
// At every point where we get a monitor update, we should be able to send a useful monitor
4253
// to a watchtower and disk...
43-
assert!(channelmonitor::ChannelMonitor::read(&mut ::std::io::Cursor::new(&monitor.serialize_for_disk()[..])).unwrap() == monitor);
44-
monitor.serialize_for_watchtower(); // This at least shouldn't crash...
54+
let mut w = VecWriter(Vec::new());
55+
monitor.write_for_disk(&mut w).unwrap();
56+
assert!(channelmonitor::ChannelMonitor::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == monitor);
57+
w.0.clear();
58+
monitor.write_for_watchtower(&mut w).unwrap(); // This at least shouldn't crash...
4559
self.added_monitors.lock().unwrap().push((funding_txo, monitor.clone()));
4660
self.simple_monitor.add_update_monitor(funding_txo, monitor)
4761
}

0 commit comments

Comments
 (0)