Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lightning/src/chain/chainmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,14 +98,16 @@ impl MonitorUpdateId {
///
/// Third-party watchtowers may be built as a part of an implementation of this trait, with the
/// advantage that you can control whether to resume channel operation depending on if an update
/// has been persisted to a watchtower. For this, you may find the following methods useful:
/// [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// has been persisted to a watchtower. A utility for tracking and building signed justice
/// transactions is provided in the [`util::watchtower`] module. Otherwise, you may find the
/// following methods useful: [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// [`ChannelMonitor::counterparty_commitment_txs_from_update`],
/// [`ChannelMonitor::sign_to_local_justice_tx`], [`TrustedCommitmentTransaction::revokeable_output_index`],
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`].
///
/// [`TrustedCommitmentTransaction::revokeable_output_index`]: crate::ln::chan_utils::TrustedCommitmentTransaction::revokeable_output_index
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`]: crate::ln::chan_utils::TrustedCommitmentTransaction::build_to_local_justice_tx
/// [`util::watchtower`]: crate::util::watchtower
pub trait Persist<ChannelSigner: WriteableEcdsaChannelSigner> {
/// Persist a new channel's data in response to a [`chain::Watch::watch_channel`] call. This is
/// called by [`ChannelManager`] for new channels, or may be called directly, e.g. on startup.
Expand Down
41 changes: 0 additions & 41 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -8404,47 +8404,6 @@ where
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}
impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

impl_writeable_tlv_based_enum!(ChannelShutdownState,
(0, NotShuttingDown) => {},
(2, ShutdownInitiated) => {},
Expand Down
1 change: 1 addition & 0 deletions lightning/src/util/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ pub mod invoice;
pub mod persist;
pub mod string;
pub mod wakers;
pub mod watchtower;

pub(crate) mod atomic_counter;
pub(crate) mod byte_utils;
Expand Down
75 changes: 74 additions & 1 deletion lightning/src/util/ser.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,12 +13,14 @@
//! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
//! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor

use crate::events::Event;
use crate::ln::channelmanager::EventCompletionAction;
use crate::prelude::*;
use crate::io::{self, Read, Seek, Write};
use crate::io_extras::{copy, sink};
use core::hash::Hash;
use crate::sync::Mutex;
use core::cmp;
use core::{cmp, mem};
use core::convert::TryFrom;
use core::ops::Deref;

Expand All@@ -45,6 +47,7 @@ use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};

use crate::util::byte_utils::{be48_to_array, slice_to_be48};
use crate::util::string::UntrustedString;
use crate::util::watchtower::UnsignedJusticeData;

/// serialization buffer size
pub const MAX_BUF_SIZE: usize = 64 * 1024;
Expand DownExpand Up@@ -785,6 +788,75 @@ where T: Readable + Eq + Hash
}
}

// VecDeques
impl Writeable for VecDeque<UnsignedJusticeData> {
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
CollectionLength(self.len() as u64).write(w)?;
for elem in self.iter() {
elem.write(w)?;
}
Ok(())
}
}

impl Readable for VecDeque<UnsignedJusticeData> {
#[inline]
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
let len: CollectionLength = Readable::read(r)?;
let mut ret = VecDeque::with_capacity(cmp::min(
len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<UnsignedJusticeData>()));
for _ in 0..len.0 {
if let Some(val) = MaybeReadable::read(r)? {
ret.push_back(val);
}
}
Ok(ret)
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO its a bit weird to move stuff that's only used in one file into ser.rs, I'd kinda rather keep it with the struct definition.

fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}

impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

// Vectors
macro_rules! impl_writeable_for_vec {
($ty: ty $(, $name: ident)*) => {
Expand DownExpand Up@@ -848,6 +920,7 @@ impl Readable for Vec<u8> {
}
}

impl_for_vec!(u32);
impl_for_vec!(ecdsa::Signature);
impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
Expand Down
87 changes: 20 additions & 67 deletions lightning/src/util/test_utils.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,7 +22,6 @@ use crate::events;
use crate::events::bump_transaction::{WalletSource, Utxo};
use crate::ln::ChannelId;
use crate::ln::channelmanager;
use crate::ln::chan_utils::CommitmentTransaction;
use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
use crate::ln::{msgs, wire};
use crate::ln::msgs::LightningError;
Expand All@@ -38,6 +37,7 @@ use crate::util::config::UserConfig;
use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState};
use crate::util::logger::{Logger, Level, Record};
use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
use crate::util::watchtower::JusticeTxTracker;

use bitcoin::EcdsaSighashType;
use bitcoin::blockdata::constants::ChainHash;
Expand All@@ -61,7 +61,6 @@ use regex;
use crate::io;
use crate::prelude::*;
use core::cell::RefCell;
use core::ops::Deref;
use core::time::Duration;
use crate::sync::{Mutex, Arc};
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
Expand DownExpand Up@@ -276,50 +275,30 @@ impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
}
}

struct JusticeTxData {
justice_tx: Transaction,
value: u64,
commitment_number: u64,
}

pub(crate) struct WatchtowerPersister {
persister: TestPersister,
/// Upon a new commitment_signed, we'll get a
/// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
/// amount, and commitment number so we can build the justice tx after our counterparty
/// revokes it.
unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
/// `ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo`. We'll use our utility
/// object `JusticeTxTracker` to build and sign the justice tx.
justice_tx_tracker: RefCell<JusticeTxTracker>,
/// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
/// tx which would be used to provide a watchtower with the data it needs.
watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
destination_script: Script,
signed_justice_txs: RefCell<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
}

impl WatchtowerPersister {
pub(crate) fn new(destination_script: Script) -> Self {
WatchtowerPersister {
persister: TestPersister::new(),
unsigned_justice_tx_data: Mutex::new(HashMap::new()),
watchtower_state: Mutex::new(HashMap::new()),
destination_script,
justice_tx_tracker: RefCell::new(JusticeTxTracker::new(vec![FEERATE_FLOOR_SATS_PER_KW],
destination_script)),
signed_justice_txs: RefCell::new(HashMap::new()),
}
}

pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
-> Option<Transaction> {
self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}

fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
-> Option<JusticeTxData> {
let trusted_tx = counterparty_commitment_tx.trust();
let output_idx = trusted_tx.revokeable_output_index()?;
let built_tx = trusted_tx.built_transaction();
let value = built_tx.transaction.output[output_idx as usize].value;
let justice_tx = trusted_tx.build_to_local_justice_tx(
FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
let commitment_number = counterparty_commitment_tx.commitment_number();
Some(JusticeTxData { justice_tx, value, commitment_number })
self.signed_justice_txs.borrow().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}
}

Expand All@@ -328,20 +307,8 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.persist_new_channel(funding_txo, data, id);

assert!(self.unsigned_justice_tx_data.lock().unwrap()
.insert(funding_txo, VecDeque::new()).is_none());
assert!(self.watchtower_state.lock().unwrap()
.insert(funding_txo, HashMap::new()).is_none());

let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
.expect("First and only call expects Some");
if let Some(justice_data)
= self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
self.unsigned_justice_tx_data.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.push_back(justice_data);
}
self.justice_tx_tracker.borrow_mut().add_new_channel(funding_txo, data);
assert!(self.signed_justice_txs.borrow_mut().insert(funding_txo, HashMap::new()).is_none());
res
}

Expand All@@ -350,29 +317,15 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);

if let Some(update) = update {
let commitment_txs = data.counterparty_commitment_txs_from_update(update);
let justice_datas = commitment_txs.into_iter()
.filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
channel_state.extend(justice_datas);

while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
let input_idx = 0;
let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
Ok(signed_justice_tx) => {
let dup = self.watchtower_state.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.insert(commitment_txid, signed_justice_tx);
assert!(dup.is_none());
channel_state.pop_front();
},
Err(_) => break,
}
}
let signed_justice_txs = match update {
Some(update) =>
self.justice_tx_tracker.borrow_mut().process_update(funding_txo, data, update),
None => vec![],
};
for tx in signed_justice_txs {
let commitment_txid = tx.input[0].previous_output.txid;
self.signed_justice_txs.borrow_mut()
.get_mut(&funding_txo).unwrap().insert(commitment_txid, tx);
}
res
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lightning/src/chain/chainmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,14 +98,16 @@ impl MonitorUpdateId {
///
/// Third-party watchtowers may be built as a part of an implementation of this trait, with the
/// advantage that you can control whether to resume channel operation depending on if an update
/// has been persisted to a watchtower. For this, you may find the following methods useful:
/// [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// has been persisted to a watchtower. A utility for tracking and building signed justice
/// transactions is provided in the [`util::watchtower`] module. Otherwise, you may find the
/// following methods useful: [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// [`ChannelMonitor::counterparty_commitment_txs_from_update`],
/// [`ChannelMonitor::sign_to_local_justice_tx`], [`TrustedCommitmentTransaction::revokeable_output_index`],
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`].
///
/// [`TrustedCommitmentTransaction::revokeable_output_index`]: crate::ln::chan_utils::TrustedCommitmentTransaction::revokeable_output_index
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`]: crate::ln::chan_utils::TrustedCommitmentTransaction::build_to_local_justice_tx
/// [`util::watchtower`]: crate::util::watchtower
pub trait Persist<ChannelSigner: WriteableEcdsaChannelSigner> {
/// Persist a new channel's data in response to a [`chain::Watch::watch_channel`] call. This is
/// called by [`ChannelManager`] for new channels, or may be called directly, e.g. on startup.
Expand Down
41 changes: 0 additions & 41 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -8404,47 +8404,6 @@ where
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}
impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

impl_writeable_tlv_based_enum!(ChannelShutdownState,
(0, NotShuttingDown) => {},
(2, ShutdownInitiated) => {},
Expand Down
1 change: 1 addition & 0 deletions lightning/src/util/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ pub mod invoice;
pub mod persist;
pub mod string;
pub mod wakers;
pub mod watchtower;

pub(crate) mod atomic_counter;
pub(crate) mod byte_utils;
Expand Down
75 changes: 74 additions & 1 deletion lightning/src/util/ser.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,12 +13,14 @@
//! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
//! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor

use crate::events::Event;
use crate::ln::channelmanager::EventCompletionAction;
use crate::prelude::*;
use crate::io::{self, Read, Seek, Write};
use crate::io_extras::{copy, sink};
use core::hash::Hash;
use crate::sync::Mutex;
use core::cmp;
use core::{cmp, mem};
use core::convert::TryFrom;
use core::ops::Deref;

Expand All@@ -45,6 +47,7 @@ use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};

use crate::util::byte_utils::{be48_to_array, slice_to_be48};
use crate::util::string::UntrustedString;
use crate::util::watchtower::UnsignedJusticeData;

/// serialization buffer size
pub const MAX_BUF_SIZE: usize = 64 * 1024;
Expand DownExpand Up@@ -785,6 +788,75 @@ where T: Readable + Eq + Hash
}
}

// VecDeques
impl Writeable for VecDeque<UnsignedJusticeData> {
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
CollectionLength(self.len() as u64).write(w)?;
for elem in self.iter() {
elem.write(w)?;
}
Ok(())
}
}

impl Readable for VecDeque<UnsignedJusticeData> {
#[inline]
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
let len: CollectionLength = Readable::read(r)?;
let mut ret = VecDeque::with_capacity(cmp::min(
len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<UnsignedJusticeData>()));
for _ in 0..len.0 {
if let Some(val) = MaybeReadable::read(r)? {
ret.push_back(val);
}
}
Ok(ret)
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO its a bit weird to move stuff that's only used in one file into ser.rs, I'd kinda rather keep it with the struct definition.

fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}

impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

// Vectors
macro_rules! impl_writeable_for_vec {
($ty: ty $(, $name: ident)*) => {
Expand DownExpand Up@@ -848,6 +920,7 @@ impl Readable for Vec<u8> {
}
}

impl_for_vec!(u32);
impl_for_vec!(ecdsa::Signature);
impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
Expand Down
87 changes: 20 additions & 67 deletions lightning/src/util/test_utils.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,7 +22,6 @@ use crate::events;
use crate::events::bump_transaction::{WalletSource, Utxo};
use crate::ln::ChannelId;
use crate::ln::channelmanager;
use crate::ln::chan_utils::CommitmentTransaction;
use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
use crate::ln::{msgs, wire};
use crate::ln::msgs::LightningError;
Expand All@@ -38,6 +37,7 @@ use crate::util::config::UserConfig;
use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState};
use crate::util::logger::{Logger, Level, Record};
use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
use crate::util::watchtower::JusticeTxTracker;

use bitcoin::EcdsaSighashType;
use bitcoin::blockdata::constants::ChainHash;
Expand All@@ -61,7 +61,6 @@ use regex;
use crate::io;
use crate::prelude::*;
use core::cell::RefCell;
use core::ops::Deref;
use core::time::Duration;
use crate::sync::{Mutex, Arc};
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
Expand DownExpand Up@@ -276,50 +275,30 @@ impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
}
}

struct JusticeTxData {
justice_tx: Transaction,
value: u64,
commitment_number: u64,
}

pub(crate) struct WatchtowerPersister {
persister: TestPersister,
/// Upon a new commitment_signed, we'll get a
/// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
/// amount, and commitment number so we can build the justice tx after our counterparty
/// revokes it.
unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
/// `ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo`. We'll use our utility
/// object `JusticeTxTracker` to build and sign the justice tx.
justice_tx_tracker: RefCell<JusticeTxTracker>,
/// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
/// tx which would be used to provide a watchtower with the data it needs.
watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
destination_script: Script,
signed_justice_txs: RefCell<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
}

impl WatchtowerPersister {
pub(crate) fn new(destination_script: Script) -> Self {
WatchtowerPersister {
persister: TestPersister::new(),
unsigned_justice_tx_data: Mutex::new(HashMap::new()),
watchtower_state: Mutex::new(HashMap::new()),
destination_script,
justice_tx_tracker: RefCell::new(JusticeTxTracker::new(vec![FEERATE_FLOOR_SATS_PER_KW],
destination_script)),
signed_justice_txs: RefCell::new(HashMap::new()),
}
}

pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
-> Option<Transaction> {
self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}

fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
-> Option<JusticeTxData> {
let trusted_tx = counterparty_commitment_tx.trust();
let output_idx = trusted_tx.revokeable_output_index()?;
let built_tx = trusted_tx.built_transaction();
let value = built_tx.transaction.output[output_idx as usize].value;
let justice_tx = trusted_tx.build_to_local_justice_tx(
FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
let commitment_number = counterparty_commitment_tx.commitment_number();
Some(JusticeTxData { justice_tx, value, commitment_number })
self.signed_justice_txs.borrow().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}
}

Expand All@@ -328,20 +307,8 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.persist_new_channel(funding_txo, data, id);

assert!(self.unsigned_justice_tx_data.lock().unwrap()
.insert(funding_txo, VecDeque::new()).is_none());
assert!(self.watchtower_state.lock().unwrap()
.insert(funding_txo, HashMap::new()).is_none());

let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
.expect("First and only call expects Some");
if let Some(justice_data)
= self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
self.unsigned_justice_tx_data.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.push_back(justice_data);
}
self.justice_tx_tracker.borrow_mut().add_new_channel(funding_txo, data);
assert!(self.signed_justice_txs.borrow_mut().insert(funding_txo, HashMap::new()).is_none());
res
}

Expand All@@ -350,29 +317,15 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);

if let Some(update) = update {
let commitment_txs = data.counterparty_commitment_txs_from_update(update);
let justice_datas = commitment_txs.into_iter()
.filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
channel_state.extend(justice_datas);

while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
let input_idx = 0;
let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
Ok(signed_justice_tx) => {
let dup = self.watchtower_state.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.insert(commitment_txid, signed_justice_tx);
assert!(dup.is_none());
channel_state.pop_front();
},
Err(_) => break,
}
}
let signed_justice_txs = match update {
Some(update) =>
self.justice_tx_tracker.borrow_mut().process_update(funding_txo, data, update),
None => vec![],
};
for tx in signed_justice_txs {
let commitment_txid = tx.input[0].previous_output.txid;
self.signed_justice_txs.borrow_mut()
.get_mut(&funding_txo).unwrap().insert(commitment_txid, tx);
}
res
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lightning/src/chain/chainmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,14 +98,16 @@ impl MonitorUpdateId {
///
/// Third-party watchtowers may be built as a part of an implementation of this trait, with the
/// advantage that you can control whether to resume channel operation depending on if an update
/// has been persisted to a watchtower. For this, you may find the following methods useful:
/// [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// has been persisted to a watchtower. A utility for tracking and building signed justice
/// transactions is provided in the [`util::watchtower`] module. Otherwise, you may find the
/// following methods useful: [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// [`ChannelMonitor::counterparty_commitment_txs_from_update`],
/// [`ChannelMonitor::sign_to_local_justice_tx`], [`TrustedCommitmentTransaction::revokeable_output_index`],
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`].
///
/// [`TrustedCommitmentTransaction::revokeable_output_index`]: crate::ln::chan_utils::TrustedCommitmentTransaction::revokeable_output_index
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`]: crate::ln::chan_utils::TrustedCommitmentTransaction::build_to_local_justice_tx
/// [`util::watchtower`]: crate::util::watchtower
pub trait Persist<ChannelSigner: WriteableEcdsaChannelSigner> {
/// Persist a new channel's data in response to a [`chain::Watch::watch_channel`] call. This is
/// called by [`ChannelManager`] for new channels, or may be called directly, e.g. on startup.
Expand Down
41 changes: 0 additions & 41 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -8404,47 +8404,6 @@ where
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}
impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

impl_writeable_tlv_based_enum!(ChannelShutdownState,
(0, NotShuttingDown) => {},
(2, ShutdownInitiated) => {},
Expand Down
1 change: 1 addition & 0 deletions lightning/src/util/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ pub mod invoice;
pub mod persist;
pub mod string;
pub mod wakers;
pub mod watchtower;

pub(crate) mod atomic_counter;
pub(crate) mod byte_utils;
Expand Down
75 changes: 74 additions & 1 deletion lightning/src/util/ser.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,12 +13,14 @@
//! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
//! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor

use crate::events::Event;
use crate::ln::channelmanager::EventCompletionAction;
use crate::prelude::*;
use crate::io::{self, Read, Seek, Write};
use crate::io_extras::{copy, sink};
use core::hash::Hash;
use crate::sync::Mutex;
use core::cmp;
use core::{cmp, mem};
use core::convert::TryFrom;
use core::ops::Deref;

Expand All@@ -45,6 +47,7 @@ use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};

use crate::util::byte_utils::{be48_to_array, slice_to_be48};
use crate::util::string::UntrustedString;
use crate::util::watchtower::UnsignedJusticeData;

/// serialization buffer size
pub const MAX_BUF_SIZE: usize = 64 * 1024;
Expand DownExpand Up@@ -785,6 +788,75 @@ where T: Readable + Eq + Hash
}
}

// VecDeques
impl Writeable for VecDeque<UnsignedJusticeData> {
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
CollectionLength(self.len() as u64).write(w)?;
for elem in self.iter() {
elem.write(w)?;
}
Ok(())
}
}

impl Readable for VecDeque<UnsignedJusticeData> {
#[inline]
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
let len: CollectionLength = Readable::read(r)?;
let mut ret = VecDeque::with_capacity(cmp::min(
len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<UnsignedJusticeData>()));
for _ in 0..len.0 {
if let Some(val) = MaybeReadable::read(r)? {
ret.push_back(val);
}
}
Ok(ret)
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO its a bit weird to move stuff that's only used in one file into ser.rs, I'd kinda rather keep it with the struct definition.

fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}

impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

// Vectors
macro_rules! impl_writeable_for_vec {
($ty: ty $(, $name: ident)*) => {
Expand DownExpand Up@@ -848,6 +920,7 @@ impl Readable for Vec<u8> {
}
}

impl_for_vec!(u32);
impl_for_vec!(ecdsa::Signature);
impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
Expand Down
87 changes: 20 additions & 67 deletions lightning/src/util/test_utils.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,7 +22,6 @@ use crate::events;
use crate::events::bump_transaction::{WalletSource, Utxo};
use crate::ln::ChannelId;
use crate::ln::channelmanager;
use crate::ln::chan_utils::CommitmentTransaction;
use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
use crate::ln::{msgs, wire};
use crate::ln::msgs::LightningError;
Expand All@@ -38,6 +37,7 @@ use crate::util::config::UserConfig;
use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState};
use crate::util::logger::{Logger, Level, Record};
use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
use crate::util::watchtower::JusticeTxTracker;

use bitcoin::EcdsaSighashType;
use bitcoin::blockdata::constants::ChainHash;
Expand All@@ -61,7 +61,6 @@ use regex;
use crate::io;
use crate::prelude::*;
use core::cell::RefCell;
use core::ops::Deref;
use core::time::Duration;
use crate::sync::{Mutex, Arc};
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
Expand DownExpand Up@@ -276,50 +275,30 @@ impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
}
}

struct JusticeTxData {
justice_tx: Transaction,
value: u64,
commitment_number: u64,
}

pub(crate) struct WatchtowerPersister {
persister: TestPersister,
/// Upon a new commitment_signed, we'll get a
/// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
/// amount, and commitment number so we can build the justice tx after our counterparty
/// revokes it.
unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
/// `ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo`. We'll use our utility
/// object `JusticeTxTracker` to build and sign the justice tx.
justice_tx_tracker: RefCell<JusticeTxTracker>,
/// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
/// tx which would be used to provide a watchtower with the data it needs.
watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
destination_script: Script,
signed_justice_txs: RefCell<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
}

impl WatchtowerPersister {
pub(crate) fn new(destination_script: Script) -> Self {
WatchtowerPersister {
persister: TestPersister::new(),
unsigned_justice_tx_data: Mutex::new(HashMap::new()),
watchtower_state: Mutex::new(HashMap::new()),
destination_script,
justice_tx_tracker: RefCell::new(JusticeTxTracker::new(vec![FEERATE_FLOOR_SATS_PER_KW],
destination_script)),
signed_justice_txs: RefCell::new(HashMap::new()),
}
}

pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
-> Option<Transaction> {
self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}

fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
-> Option<JusticeTxData> {
let trusted_tx = counterparty_commitment_tx.trust();
let output_idx = trusted_tx.revokeable_output_index()?;
let built_tx = trusted_tx.built_transaction();
let value = built_tx.transaction.output[output_idx as usize].value;
let justice_tx = trusted_tx.build_to_local_justice_tx(
FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
let commitment_number = counterparty_commitment_tx.commitment_number();
Some(JusticeTxData { justice_tx, value, commitment_number })
self.signed_justice_txs.borrow().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}
}

Expand All@@ -328,20 +307,8 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.persist_new_channel(funding_txo, data, id);

assert!(self.unsigned_justice_tx_data.lock().unwrap()
.insert(funding_txo, VecDeque::new()).is_none());
assert!(self.watchtower_state.lock().unwrap()
.insert(funding_txo, HashMap::new()).is_none());

let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
.expect("First and only call expects Some");
if let Some(justice_data)
= self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
self.unsigned_justice_tx_data.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.push_back(justice_data);
}
self.justice_tx_tracker.borrow_mut().add_new_channel(funding_txo, data);
assert!(self.signed_justice_txs.borrow_mut().insert(funding_txo, HashMap::new()).is_none());
res
}

Expand All@@ -350,29 +317,15 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);

if let Some(update) = update {
let commitment_txs = data.counterparty_commitment_txs_from_update(update);
let justice_datas = commitment_txs.into_iter()
.filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
channel_state.extend(justice_datas);

while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
let input_idx = 0;
let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
Ok(signed_justice_tx) => {
let dup = self.watchtower_state.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.insert(commitment_txid, signed_justice_tx);
assert!(dup.is_none());
channel_state.pop_front();
},
Err(_) => break,
}
}
let signed_justice_txs = match update {
Some(update) =>
self.justice_tx_tracker.borrow_mut().process_update(funding_txo, data, update),
None => vec![],
};
for tx in signed_justice_txs {
let commitment_txid = tx.input[0].previous_output.txid;
self.signed_justice_txs.borrow_mut()
.get_mut(&funding_txo).unwrap().insert(commitment_txid, tx);
}
res
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lightning/src/chain/chainmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,14 +98,16 @@ impl MonitorUpdateId {
///
/// Third-party watchtowers may be built as a part of an implementation of this trait, with the
/// advantage that you can control whether to resume channel operation depending on if an update
/// has been persisted to a watchtower. For this, you may find the following methods useful:
/// [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// has been persisted to a watchtower. A utility for tracking and building signed justice
/// transactions is provided in the [`util::watchtower`] module. Otherwise, you may find the
/// following methods useful: [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// [`ChannelMonitor::counterparty_commitment_txs_from_update`],
/// [`ChannelMonitor::sign_to_local_justice_tx`], [`TrustedCommitmentTransaction::revokeable_output_index`],
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`].
///
/// [`TrustedCommitmentTransaction::revokeable_output_index`]: crate::ln::chan_utils::TrustedCommitmentTransaction::revokeable_output_index
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`]: crate::ln::chan_utils::TrustedCommitmentTransaction::build_to_local_justice_tx
/// [`util::watchtower`]: crate::util::watchtower
pub trait Persist<ChannelSigner: WriteableEcdsaChannelSigner> {
/// Persist a new channel's data in response to a [`chain::Watch::watch_channel`] call. This is
/// called by [`ChannelManager`] for new channels, or may be called directly, e.g. on startup.
Expand Down
41 changes: 0 additions & 41 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -8404,47 +8404,6 @@ where
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}
impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

impl_writeable_tlv_based_enum!(ChannelShutdownState,
(0, NotShuttingDown) => {},
(2, ShutdownInitiated) => {},
Expand Down
1 change: 1 addition & 0 deletions lightning/src/util/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ pub mod invoice;
pub mod persist;
pub mod string;
pub mod wakers;
pub mod watchtower;

pub(crate) mod atomic_counter;
pub(crate) mod byte_utils;
Expand Down
75 changes: 74 additions & 1 deletion lightning/src/util/ser.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,12 +13,14 @@
//! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
//! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor

use crate::events::Event;
use crate::ln::channelmanager::EventCompletionAction;
use crate::prelude::*;
use crate::io::{self, Read, Seek, Write};
use crate::io_extras::{copy, sink};
use core::hash::Hash;
use crate::sync::Mutex;
use core::cmp;
use core::{cmp, mem};
use core::convert::TryFrom;
use core::ops::Deref;

Expand All@@ -45,6 +47,7 @@ use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};

use crate::util::byte_utils::{be48_to_array, slice_to_be48};
use crate::util::string::UntrustedString;
use crate::util::watchtower::UnsignedJusticeData;

/// serialization buffer size
pub const MAX_BUF_SIZE: usize = 64 * 1024;
Expand DownExpand Up@@ -785,6 +788,75 @@ where T: Readable + Eq + Hash
}
}

// VecDeques
impl Writeable for VecDeque<UnsignedJusticeData> {
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
CollectionLength(self.len() as u64).write(w)?;
for elem in self.iter() {
elem.write(w)?;
}
Ok(())
}
}

impl Readable for VecDeque<UnsignedJusticeData> {
#[inline]
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
let len: CollectionLength = Readable::read(r)?;
let mut ret = VecDeque::with_capacity(cmp::min(
len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<UnsignedJusticeData>()));
for _ in 0..len.0 {
if let Some(val) = MaybeReadable::read(r)? {
ret.push_back(val);
}
}
Ok(ret)
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO its a bit weird to move stuff that's only used in one file into ser.rs, I'd kinda rather keep it with the struct definition.

fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}

impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

// Vectors
macro_rules! impl_writeable_for_vec {
($ty: ty $(, $name: ident)*) => {
Expand DownExpand Up@@ -848,6 +920,7 @@ impl Readable for Vec<u8> {
}
}

impl_for_vec!(u32);
impl_for_vec!(ecdsa::Signature);
impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
Expand Down
87 changes: 20 additions & 67 deletions lightning/src/util/test_utils.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,7 +22,6 @@ use crate::events;
use crate::events::bump_transaction::{WalletSource, Utxo};
use crate::ln::ChannelId;
use crate::ln::channelmanager;
use crate::ln::chan_utils::CommitmentTransaction;
use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
use crate::ln::{msgs, wire};
use crate::ln::msgs::LightningError;
Expand All@@ -38,6 +37,7 @@ use crate::util::config::UserConfig;
use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState};
use crate::util::logger::{Logger, Level, Record};
use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
use crate::util::watchtower::JusticeTxTracker;

use bitcoin::EcdsaSighashType;
use bitcoin::blockdata::constants::ChainHash;
Expand All@@ -61,7 +61,6 @@ use regex;
use crate::io;
use crate::prelude::*;
use core::cell::RefCell;
use core::ops::Deref;
use core::time::Duration;
use crate::sync::{Mutex, Arc};
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
Expand DownExpand Up@@ -276,50 +275,30 @@ impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
}
}

struct JusticeTxData {
justice_tx: Transaction,
value: u64,
commitment_number: u64,
}

pub(crate) struct WatchtowerPersister {
persister: TestPersister,
/// Upon a new commitment_signed, we'll get a
/// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
/// amount, and commitment number so we can build the justice tx after our counterparty
/// revokes it.
unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
/// `ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo`. We'll use our utility
/// object `JusticeTxTracker` to build and sign the justice tx.
justice_tx_tracker: RefCell<JusticeTxTracker>,
/// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
/// tx which would be used to provide a watchtower with the data it needs.
watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
destination_script: Script,
signed_justice_txs: RefCell<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
}

impl WatchtowerPersister {
pub(crate) fn new(destination_script: Script) -> Self {
WatchtowerPersister {
persister: TestPersister::new(),
unsigned_justice_tx_data: Mutex::new(HashMap::new()),
watchtower_state: Mutex::new(HashMap::new()),
destination_script,
justice_tx_tracker: RefCell::new(JusticeTxTracker::new(vec![FEERATE_FLOOR_SATS_PER_KW],
destination_script)),
signed_justice_txs: RefCell::new(HashMap::new()),
}
}

pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
-> Option<Transaction> {
self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}

fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
-> Option<JusticeTxData> {
let trusted_tx = counterparty_commitment_tx.trust();
let output_idx = trusted_tx.revokeable_output_index()?;
let built_tx = trusted_tx.built_transaction();
let value = built_tx.transaction.output[output_idx as usize].value;
let justice_tx = trusted_tx.build_to_local_justice_tx(
FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
let commitment_number = counterparty_commitment_tx.commitment_number();
Some(JusticeTxData { justice_tx, value, commitment_number })
self.signed_justice_txs.borrow().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}
}

Expand All@@ -328,20 +307,8 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.persist_new_channel(funding_txo, data, id);

assert!(self.unsigned_justice_tx_data.lock().unwrap()
.insert(funding_txo, VecDeque::new()).is_none());
assert!(self.watchtower_state.lock().unwrap()
.insert(funding_txo, HashMap::new()).is_none());

let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
.expect("First and only call expects Some");
if let Some(justice_data)
= self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
self.unsigned_justice_tx_data.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.push_back(justice_data);
}
self.justice_tx_tracker.borrow_mut().add_new_channel(funding_txo, data);
assert!(self.signed_justice_txs.borrow_mut().insert(funding_txo, HashMap::new()).is_none());
res
}

Expand All@@ -350,29 +317,15 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);

if let Some(update) = update {
let commitment_txs = data.counterparty_commitment_txs_from_update(update);
let justice_datas = commitment_txs.into_iter()
.filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
channel_state.extend(justice_datas);

while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
let input_idx = 0;
let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
Ok(signed_justice_tx) => {
let dup = self.watchtower_state.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.insert(commitment_txid, signed_justice_tx);
assert!(dup.is_none());
channel_state.pop_front();
},
Err(_) => break,
}
}
let signed_justice_txs = match update {
Some(update) =>
self.justice_tx_tracker.borrow_mut().process_update(funding_txo, data, update),
None => vec![],
};
for tx in signed_justice_txs {
let commitment_txid = tx.input[0].previous_output.txid;
self.signed_justice_txs.borrow_mut()
.get_mut(&funding_txo).unwrap().insert(commitment_txid, tx);
}
res
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lightning/src/chain/chainmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,14 +98,16 @@ impl MonitorUpdateId {
///
/// Third-party watchtowers may be built as a part of an implementation of this trait, with the
/// advantage that you can control whether to resume channel operation depending on if an update
/// has been persisted to a watchtower. For this, you may find the following methods useful:
/// [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// has been persisted to a watchtower. A utility for tracking and building signed justice
/// transactions is provided in the [`util::watchtower`] module. Otherwise, you may find the
/// following methods useful: [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// [`ChannelMonitor::counterparty_commitment_txs_from_update`],
/// [`ChannelMonitor::sign_to_local_justice_tx`], [`TrustedCommitmentTransaction::revokeable_output_index`],
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`].
///
/// [`TrustedCommitmentTransaction::revokeable_output_index`]: crate::ln::chan_utils::TrustedCommitmentTransaction::revokeable_output_index
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`]: crate::ln::chan_utils::TrustedCommitmentTransaction::build_to_local_justice_tx
/// [`util::watchtower`]: crate::util::watchtower
pub trait Persist<ChannelSigner: WriteableEcdsaChannelSigner> {
/// Persist a new channel's data in response to a [`chain::Watch::watch_channel`] call. This is
/// called by [`ChannelManager`] for new channels, or may be called directly, e.g. on startup.
Expand Down
41 changes: 0 additions & 41 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -8404,47 +8404,6 @@ where
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}
impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

impl_writeable_tlv_based_enum!(ChannelShutdownState,
(0, NotShuttingDown) => {},
(2, ShutdownInitiated) => {},
Expand Down
1 change: 1 addition & 0 deletions lightning/src/util/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ pub mod invoice;
pub mod persist;
pub mod string;
pub mod wakers;
pub mod watchtower;

pub(crate) mod atomic_counter;
pub(crate) mod byte_utils;
Expand Down
75 changes: 74 additions & 1 deletion lightning/src/util/ser.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,12 +13,14 @@
//! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
//! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor

use crate::events::Event;
use crate::ln::channelmanager::EventCompletionAction;
use crate::prelude::*;
use crate::io::{self, Read, Seek, Write};
use crate::io_extras::{copy, sink};
use core::hash::Hash;
use crate::sync::Mutex;
use core::cmp;
use core::{cmp, mem};
use core::convert::TryFrom;
use core::ops::Deref;

Expand All@@ -45,6 +47,7 @@ use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};

use crate::util::byte_utils::{be48_to_array, slice_to_be48};
use crate::util::string::UntrustedString;
use crate::util::watchtower::UnsignedJusticeData;

/// serialization buffer size
pub const MAX_BUF_SIZE: usize = 64 * 1024;
Expand DownExpand Up@@ -785,6 +788,75 @@ where T: Readable + Eq + Hash
}
}

// VecDeques
impl Writeable for VecDeque<UnsignedJusticeData> {
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
CollectionLength(self.len() as u64).write(w)?;
for elem in self.iter() {
elem.write(w)?;
}
Ok(())
}
}

impl Readable for VecDeque<UnsignedJusticeData> {
#[inline]
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
let len: CollectionLength = Readable::read(r)?;
let mut ret = VecDeque::with_capacity(cmp::min(
len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<UnsignedJusticeData>()));
for _ in 0..len.0 {
if let Some(val) = MaybeReadable::read(r)? {
ret.push_back(val);
}
}
Ok(ret)
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO its a bit weird to move stuff that's only used in one file into ser.rs, I'd kinda rather keep it with the struct definition.

fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}

impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

// Vectors
macro_rules! impl_writeable_for_vec {
($ty: ty $(, $name: ident)*) => {
Expand DownExpand Up@@ -848,6 +920,7 @@ impl Readable for Vec<u8> {
}
}

impl_for_vec!(u32);
impl_for_vec!(ecdsa::Signature);
impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
Expand Down
87 changes: 20 additions & 67 deletions lightning/src/util/test_utils.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,7 +22,6 @@ use crate::events;
use crate::events::bump_transaction::{WalletSource, Utxo};
use crate::ln::ChannelId;
use crate::ln::channelmanager;
use crate::ln::chan_utils::CommitmentTransaction;
use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
use crate::ln::{msgs, wire};
use crate::ln::msgs::LightningError;
Expand All@@ -38,6 +37,7 @@ use crate::util::config::UserConfig;
use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState};
use crate::util::logger::{Logger, Level, Record};
use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
use crate::util::watchtower::JusticeTxTracker;

use bitcoin::EcdsaSighashType;
use bitcoin::blockdata::constants::ChainHash;
Expand All@@ -61,7 +61,6 @@ use regex;
use crate::io;
use crate::prelude::*;
use core::cell::RefCell;
use core::ops::Deref;
use core::time::Duration;
use crate::sync::{Mutex, Arc};
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
Expand DownExpand Up@@ -276,50 +275,30 @@ impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
}
}

struct JusticeTxData {
justice_tx: Transaction,
value: u64,
commitment_number: u64,
}

pub(crate) struct WatchtowerPersister {
persister: TestPersister,
/// Upon a new commitment_signed, we'll get a
/// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
/// amount, and commitment number so we can build the justice tx after our counterparty
/// revokes it.
unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
/// `ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo`. We'll use our utility
/// object `JusticeTxTracker` to build and sign the justice tx.
justice_tx_tracker: RefCell<JusticeTxTracker>,
/// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
/// tx which would be used to provide a watchtower with the data it needs.
watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
destination_script: Script,
signed_justice_txs: RefCell<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
}

impl WatchtowerPersister {
pub(crate) fn new(destination_script: Script) -> Self {
WatchtowerPersister {
persister: TestPersister::new(),
unsigned_justice_tx_data: Mutex::new(HashMap::new()),
watchtower_state: Mutex::new(HashMap::new()),
destination_script,
justice_tx_tracker: RefCell::new(JusticeTxTracker::new(vec![FEERATE_FLOOR_SATS_PER_KW],
destination_script)),
signed_justice_txs: RefCell::new(HashMap::new()),
}
}

pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
-> Option<Transaction> {
self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}

fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
-> Option<JusticeTxData> {
let trusted_tx = counterparty_commitment_tx.trust();
let output_idx = trusted_tx.revokeable_output_index()?;
let built_tx = trusted_tx.built_transaction();
let value = built_tx.transaction.output[output_idx as usize].value;
let justice_tx = trusted_tx.build_to_local_justice_tx(
FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
let commitment_number = counterparty_commitment_tx.commitment_number();
Some(JusticeTxData { justice_tx, value, commitment_number })
self.signed_justice_txs.borrow().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}
}

Expand All@@ -328,20 +307,8 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.persist_new_channel(funding_txo, data, id);

assert!(self.unsigned_justice_tx_data.lock().unwrap()
.insert(funding_txo, VecDeque::new()).is_none());
assert!(self.watchtower_state.lock().unwrap()
.insert(funding_txo, HashMap::new()).is_none());

let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
.expect("First and only call expects Some");
if let Some(justice_data)
= self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
self.unsigned_justice_tx_data.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.push_back(justice_data);
}
self.justice_tx_tracker.borrow_mut().add_new_channel(funding_txo, data);
assert!(self.signed_justice_txs.borrow_mut().insert(funding_txo, HashMap::new()).is_none());
res
}

Expand All@@ -350,29 +317,15 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);

if let Some(update) = update {
let commitment_txs = data.counterparty_commitment_txs_from_update(update);
let justice_datas = commitment_txs.into_iter()
.filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
channel_state.extend(justice_datas);

while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
let input_idx = 0;
let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
Ok(signed_justice_tx) => {
let dup = self.watchtower_state.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.insert(commitment_txid, signed_justice_tx);
assert!(dup.is_none());
channel_state.pop_front();
},
Err(_) => break,
}
}
let signed_justice_txs = match update {
Some(update) =>
self.justice_tx_tracker.borrow_mut().process_update(funding_txo, data, update),
None => vec![],
};
for tx in signed_justice_txs {
let commitment_txid = tx.input[0].previous_output.txid;
self.signed_justice_txs.borrow_mut()
.get_mut(&funding_txo).unwrap().insert(commitment_txid, tx);
}
res
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lightning/src/chain/chainmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,14 +98,16 @@ impl MonitorUpdateId {
///
/// Third-party watchtowers may be built as a part of an implementation of this trait, with the
/// advantage that you can control whether to resume channel operation depending on if an update
/// has been persisted to a watchtower. For this, you may find the following methods useful:
/// [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// has been persisted to a watchtower. A utility for tracking and building signed justice
/// transactions is provided in the [`util::watchtower`] module. Otherwise, you may find the
/// following methods useful: [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// [`ChannelMonitor::counterparty_commitment_txs_from_update`],
/// [`ChannelMonitor::sign_to_local_justice_tx`], [`TrustedCommitmentTransaction::revokeable_output_index`],
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`].
///
/// [`TrustedCommitmentTransaction::revokeable_output_index`]: crate::ln::chan_utils::TrustedCommitmentTransaction::revokeable_output_index
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`]: crate::ln::chan_utils::TrustedCommitmentTransaction::build_to_local_justice_tx
/// [`util::watchtower`]: crate::util::watchtower
pub trait Persist<ChannelSigner: WriteableEcdsaChannelSigner> {
/// Persist a new channel's data in response to a [`chain::Watch::watch_channel`] call. This is
/// called by [`ChannelManager`] for new channels, or may be called directly, e.g. on startup.
Expand Down
41 changes: 0 additions & 41 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -8404,47 +8404,6 @@ where
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}
impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

impl_writeable_tlv_based_enum!(ChannelShutdownState,
(0, NotShuttingDown) => {},
(2, ShutdownInitiated) => {},
Expand Down
1 change: 1 addition & 0 deletions lightning/src/util/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ pub mod invoice;
pub mod persist;
pub mod string;
pub mod wakers;
pub mod watchtower;

pub(crate) mod atomic_counter;
pub(crate) mod byte_utils;
Expand Down
75 changes: 74 additions & 1 deletion lightning/src/util/ser.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,12 +13,14 @@
//! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
//! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor

use crate::events::Event;
use crate::ln::channelmanager::EventCompletionAction;
use crate::prelude::*;
use crate::io::{self, Read, Seek, Write};
use crate::io_extras::{copy, sink};
use core::hash::Hash;
use crate::sync::Mutex;
use core::cmp;
use core::{cmp, mem};
use core::convert::TryFrom;
use core::ops::Deref;

Expand All@@ -45,6 +47,7 @@ use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};

use crate::util::byte_utils::{be48_to_array, slice_to_be48};
use crate::util::string::UntrustedString;
use crate::util::watchtower::UnsignedJusticeData;

/// serialization buffer size
pub const MAX_BUF_SIZE: usize = 64 * 1024;
Expand DownExpand Up@@ -785,6 +788,75 @@ where T: Readable + Eq + Hash
}
}

// VecDeques
impl Writeable for VecDeque<UnsignedJusticeData> {
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
CollectionLength(self.len() as u64).write(w)?;
for elem in self.iter() {
elem.write(w)?;
}
Ok(())
}
}

impl Readable for VecDeque<UnsignedJusticeData> {
#[inline]
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
let len: CollectionLength = Readable::read(r)?;
let mut ret = VecDeque::with_capacity(cmp::min(
len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<UnsignedJusticeData>()));
for _ in 0..len.0 {
if let Some(val) = MaybeReadable::read(r)? {
ret.push_back(val);
}
}
Ok(ret)
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO its a bit weird to move stuff that's only used in one file into ser.rs, I'd kinda rather keep it with the struct definition.

fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}

impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

// Vectors
macro_rules! impl_writeable_for_vec {
($ty: ty $(, $name: ident)*) => {
Expand DownExpand Up@@ -848,6 +920,7 @@ impl Readable for Vec<u8> {
}
}

impl_for_vec!(u32);
impl_for_vec!(ecdsa::Signature);
impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
Expand Down
87 changes: 20 additions & 67 deletions lightning/src/util/test_utils.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,7 +22,6 @@ use crate::events;
use crate::events::bump_transaction::{WalletSource, Utxo};
use crate::ln::ChannelId;
use crate::ln::channelmanager;
use crate::ln::chan_utils::CommitmentTransaction;
use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
use crate::ln::{msgs, wire};
use crate::ln::msgs::LightningError;
Expand All@@ -38,6 +37,7 @@ use crate::util::config::UserConfig;
use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState};
use crate::util::logger::{Logger, Level, Record};
use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
use crate::util::watchtower::JusticeTxTracker;

use bitcoin::EcdsaSighashType;
use bitcoin::blockdata::constants::ChainHash;
Expand All@@ -61,7 +61,6 @@ use regex;
use crate::io;
use crate::prelude::*;
use core::cell::RefCell;
use core::ops::Deref;
use core::time::Duration;
use crate::sync::{Mutex, Arc};
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
Expand DownExpand Up@@ -276,50 +275,30 @@ impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
}
}

struct JusticeTxData {
justice_tx: Transaction,
value: u64,
commitment_number: u64,
}

pub(crate) struct WatchtowerPersister {
persister: TestPersister,
/// Upon a new commitment_signed, we'll get a
/// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
/// amount, and commitment number so we can build the justice tx after our counterparty
/// revokes it.
unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
/// `ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo`. We'll use our utility
/// object `JusticeTxTracker` to build and sign the justice tx.
justice_tx_tracker: RefCell<JusticeTxTracker>,
/// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
/// tx which would be used to provide a watchtower with the data it needs.
watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
destination_script: Script,
signed_justice_txs: RefCell<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
}

impl WatchtowerPersister {
pub(crate) fn new(destination_script: Script) -> Self {
WatchtowerPersister {
persister: TestPersister::new(),
unsigned_justice_tx_data: Mutex::new(HashMap::new()),
watchtower_state: Mutex::new(HashMap::new()),
destination_script,
justice_tx_tracker: RefCell::new(JusticeTxTracker::new(vec![FEERATE_FLOOR_SATS_PER_KW],
destination_script)),
signed_justice_txs: RefCell::new(HashMap::new()),
}
}

pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
-> Option<Transaction> {
self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}

fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
-> Option<JusticeTxData> {
let trusted_tx = counterparty_commitment_tx.trust();
let output_idx = trusted_tx.revokeable_output_index()?;
let built_tx = trusted_tx.built_transaction();
let value = built_tx.transaction.output[output_idx as usize].value;
let justice_tx = trusted_tx.build_to_local_justice_tx(
FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
let commitment_number = counterparty_commitment_tx.commitment_number();
Some(JusticeTxData { justice_tx, value, commitment_number })
self.signed_justice_txs.borrow().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}
}

Expand All@@ -328,20 +307,8 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.persist_new_channel(funding_txo, data, id);

assert!(self.unsigned_justice_tx_data.lock().unwrap()
.insert(funding_txo, VecDeque::new()).is_none());
assert!(self.watchtower_state.lock().unwrap()
.insert(funding_txo, HashMap::new()).is_none());

let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
.expect("First and only call expects Some");
if let Some(justice_data)
= self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
self.unsigned_justice_tx_data.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.push_back(justice_data);
}
self.justice_tx_tracker.borrow_mut().add_new_channel(funding_txo, data);
assert!(self.signed_justice_txs.borrow_mut().insert(funding_txo, HashMap::new()).is_none());
res
}

Expand All@@ -350,29 +317,15 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);

if let Some(update) = update {
let commitment_txs = data.counterparty_commitment_txs_from_update(update);
let justice_datas = commitment_txs.into_iter()
.filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
channel_state.extend(justice_datas);

while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
let input_idx = 0;
let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
Ok(signed_justice_tx) => {
let dup = self.watchtower_state.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.insert(commitment_txid, signed_justice_tx);
assert!(dup.is_none());
channel_state.pop_front();
},
Err(_) => break,
}
}
let signed_justice_txs = match update {
Some(update) =>
self.justice_tx_tracker.borrow_mut().process_update(funding_txo, data, update),
None => vec![],
};
for tx in signed_justice_txs {
let commitment_txid = tx.input[0].previous_output.txid;
self.signed_justice_txs.borrow_mut()
.get_mut(&funding_txo).unwrap().insert(commitment_txid, tx);
}
res
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lightning/src/chain/chainmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,14 +98,16 @@ impl MonitorUpdateId {
///
/// Third-party watchtowers may be built as a part of an implementation of this trait, with the
/// advantage that you can control whether to resume channel operation depending on if an update
/// has been persisted to a watchtower. For this, you may find the following methods useful:
/// [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// has been persisted to a watchtower. A utility for tracking and building signed justice
/// transactions is provided in the [`util::watchtower`] module. Otherwise, you may find the
/// following methods useful: [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// [`ChannelMonitor::counterparty_commitment_txs_from_update`],
/// [`ChannelMonitor::sign_to_local_justice_tx`], [`TrustedCommitmentTransaction::revokeable_output_index`],
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`].
///
/// [`TrustedCommitmentTransaction::revokeable_output_index`]: crate::ln::chan_utils::TrustedCommitmentTransaction::revokeable_output_index
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`]: crate::ln::chan_utils::TrustedCommitmentTransaction::build_to_local_justice_tx
/// [`util::watchtower`]: crate::util::watchtower
pub trait Persist<ChannelSigner: WriteableEcdsaChannelSigner> {
/// Persist a new channel's data in response to a [`chain::Watch::watch_channel`] call. This is
/// called by [`ChannelManager`] for new channels, or may be called directly, e.g. on startup.
Expand Down
41 changes: 0 additions & 41 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -8404,47 +8404,6 @@ where
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}
impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

impl_writeable_tlv_based_enum!(ChannelShutdownState,
(0, NotShuttingDown) => {},
(2, ShutdownInitiated) => {},
Expand Down
1 change: 1 addition & 0 deletions lightning/src/util/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ pub mod invoice;
pub mod persist;
pub mod string;
pub mod wakers;
pub mod watchtower;

pub(crate) mod atomic_counter;
pub(crate) mod byte_utils;
Expand Down
75 changes: 74 additions & 1 deletion lightning/src/util/ser.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,12 +13,14 @@
//! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
//! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor

use crate::events::Event;
use crate::ln::channelmanager::EventCompletionAction;
use crate::prelude::*;
use crate::io::{self, Read, Seek, Write};
use crate::io_extras::{copy, sink};
use core::hash::Hash;
use crate::sync::Mutex;
use core::cmp;
use core::{cmp, mem};
use core::convert::TryFrom;
use core::ops::Deref;

Expand All@@ -45,6 +47,7 @@ use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};

use crate::util::byte_utils::{be48_to_array, slice_to_be48};
use crate::util::string::UntrustedString;
use crate::util::watchtower::UnsignedJusticeData;

/// serialization buffer size
pub const MAX_BUF_SIZE: usize = 64 * 1024;
Expand DownExpand Up@@ -785,6 +788,75 @@ where T: Readable + Eq + Hash
}
}

// VecDeques
impl Writeable for VecDeque<UnsignedJusticeData> {
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
CollectionLength(self.len() as u64).write(w)?;
for elem in self.iter() {
elem.write(w)?;
}
Ok(())
}
}

impl Readable for VecDeque<UnsignedJusticeData> {
#[inline]
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
let len: CollectionLength = Readable::read(r)?;
let mut ret = VecDeque::with_capacity(cmp::min(
len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<UnsignedJusticeData>()));
for _ in 0..len.0 {
if let Some(val) = MaybeReadable::read(r)? {
ret.push_back(val);
}
}
Ok(ret)
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO its a bit weird to move stuff that's only used in one file into ser.rs, I'd kinda rather keep it with the struct definition.

fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}

impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

// Vectors
macro_rules! impl_writeable_for_vec {
($ty: ty $(, $name: ident)*) => {
Expand DownExpand Up@@ -848,6 +920,7 @@ impl Readable for Vec<u8> {
}
}

impl_for_vec!(u32);
impl_for_vec!(ecdsa::Signature);
impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
Expand Down
87 changes: 20 additions & 67 deletions lightning/src/util/test_utils.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,7 +22,6 @@ use crate::events;
use crate::events::bump_transaction::{WalletSource, Utxo};
use crate::ln::ChannelId;
use crate::ln::channelmanager;
use crate::ln::chan_utils::CommitmentTransaction;
use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
use crate::ln::{msgs, wire};
use crate::ln::msgs::LightningError;
Expand All@@ -38,6 +37,7 @@ use crate::util::config::UserConfig;
use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState};
use crate::util::logger::{Logger, Level, Record};
use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
use crate::util::watchtower::JusticeTxTracker;

use bitcoin::EcdsaSighashType;
use bitcoin::blockdata::constants::ChainHash;
Expand All@@ -61,7 +61,6 @@ use regex;
use crate::io;
use crate::prelude::*;
use core::cell::RefCell;
use core::ops::Deref;
use core::time::Duration;
use crate::sync::{Mutex, Arc};
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
Expand DownExpand Up@@ -276,50 +275,30 @@ impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
}
}

struct JusticeTxData {
justice_tx: Transaction,
value: u64,
commitment_number: u64,
}

pub(crate) struct WatchtowerPersister {
persister: TestPersister,
/// Upon a new commitment_signed, we'll get a
/// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
/// amount, and commitment number so we can build the justice tx after our counterparty
/// revokes it.
unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
/// `ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo`. We'll use our utility
/// object `JusticeTxTracker` to build and sign the justice tx.
justice_tx_tracker: RefCell<JusticeTxTracker>,
/// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
/// tx which would be used to provide a watchtower with the data it needs.
watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
destination_script: Script,
signed_justice_txs: RefCell<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
}

impl WatchtowerPersister {
pub(crate) fn new(destination_script: Script) -> Self {
WatchtowerPersister {
persister: TestPersister::new(),
unsigned_justice_tx_data: Mutex::new(HashMap::new()),
watchtower_state: Mutex::new(HashMap::new()),
destination_script,
justice_tx_tracker: RefCell::new(JusticeTxTracker::new(vec![FEERATE_FLOOR_SATS_PER_KW],
destination_script)),
signed_justice_txs: RefCell::new(HashMap::new()),
}
}

pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
-> Option<Transaction> {
self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}

fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
-> Option<JusticeTxData> {
let trusted_tx = counterparty_commitment_tx.trust();
let output_idx = trusted_tx.revokeable_output_index()?;
let built_tx = trusted_tx.built_transaction();
let value = built_tx.transaction.output[output_idx as usize].value;
let justice_tx = trusted_tx.build_to_local_justice_tx(
FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
let commitment_number = counterparty_commitment_tx.commitment_number();
Some(JusticeTxData { justice_tx, value, commitment_number })
self.signed_justice_txs.borrow().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}
}

Expand All@@ -328,20 +307,8 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.persist_new_channel(funding_txo, data, id);

assert!(self.unsigned_justice_tx_data.lock().unwrap()
.insert(funding_txo, VecDeque::new()).is_none());
assert!(self.watchtower_state.lock().unwrap()
.insert(funding_txo, HashMap::new()).is_none());

let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
.expect("First and only call expects Some");
if let Some(justice_data)
= self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
self.unsigned_justice_tx_data.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.push_back(justice_data);
}
self.justice_tx_tracker.borrow_mut().add_new_channel(funding_txo, data);
assert!(self.signed_justice_txs.borrow_mut().insert(funding_txo, HashMap::new()).is_none());
res
}

Expand All@@ -350,29 +317,15 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);

if let Some(update) = update {
let commitment_txs = data.counterparty_commitment_txs_from_update(update);
let justice_datas = commitment_txs.into_iter()
.filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
channel_state.extend(justice_datas);

while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
let input_idx = 0;
let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
Ok(signed_justice_tx) => {
let dup = self.watchtower_state.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.insert(commitment_txid, signed_justice_tx);
assert!(dup.is_none());
channel_state.pop_front();
},
Err(_) => break,
}
}
let signed_justice_txs = match update {
Some(update) =>
self.justice_tx_tracker.borrow_mut().process_update(funding_txo, data, update),
None => vec![],
};
for tx in signed_justice_txs {
let commitment_txid = tx.input[0].previous_output.txid;
self.signed_justice_txs.borrow_mut()
.get_mut(&funding_txo).unwrap().insert(commitment_txid, tx);
}
res
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lightning/src/chain/chainmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,14 +98,16 @@ impl MonitorUpdateId {
///
/// Third-party watchtowers may be built as a part of an implementation of this trait, with the
/// advantage that you can control whether to resume channel operation depending on if an update
/// has been persisted to a watchtower. For this, you may find the following methods useful:
/// [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// has been persisted to a watchtower. A utility for tracking and building signed justice
/// transactions is provided in the [`util::watchtower`] module. Otherwise, you may find the
/// following methods useful: [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// [`ChannelMonitor::counterparty_commitment_txs_from_update`],
/// [`ChannelMonitor::sign_to_local_justice_tx`], [`TrustedCommitmentTransaction::revokeable_output_index`],
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`].
///
/// [`TrustedCommitmentTransaction::revokeable_output_index`]: crate::ln::chan_utils::TrustedCommitmentTransaction::revokeable_output_index
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`]: crate::ln::chan_utils::TrustedCommitmentTransaction::build_to_local_justice_tx
/// [`util::watchtower`]: crate::util::watchtower
pub trait Persist<ChannelSigner: WriteableEcdsaChannelSigner> {
/// Persist a new channel's data in response to a [`chain::Watch::watch_channel`] call. This is
/// called by [`ChannelManager`] for new channels, or may be called directly, e.g. on startup.
Expand Down
41 changes: 0 additions & 41 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -8404,47 +8404,6 @@ where
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}
impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

impl_writeable_tlv_based_enum!(ChannelShutdownState,
(0, NotShuttingDown) => {},
(2, ShutdownInitiated) => {},
Expand Down
1 change: 1 addition & 0 deletions lightning/src/util/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,6 +22,7 @@ pub mod invoice;
pub mod persist;
pub mod string;
pub mod wakers;
pub mod watchtower;

pub(crate) mod atomic_counter;
pub(crate) mod byte_utils;
Expand Down
75 changes: 74 additions & 1 deletion lightning/src/util/ser.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,12 +13,14 @@
//! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
//! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor

use crate::events::Event;
use crate::ln::channelmanager::EventCompletionAction;
use crate::prelude::*;
use crate::io::{self, Read, Seek, Write};
use crate::io_extras::{copy, sink};
use core::hash::Hash;
use crate::sync::Mutex;
use core::cmp;
use core::{cmp, mem};
use core::convert::TryFrom;
use core::ops::Deref;

Expand All@@ -45,6 +47,7 @@ use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};

use crate::util::byte_utils::{be48_to_array, slice_to_be48};
use crate::util::string::UntrustedString;
use crate::util::watchtower::UnsignedJusticeData;

/// serialization buffer size
pub const MAX_BUF_SIZE: usize = 64 * 1024;
Expand DownExpand Up@@ -785,6 +788,75 @@ where T: Readable + Eq + Hash
}
}

// VecDeques
impl Writeable for VecDeque<UnsignedJusticeData> {
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
CollectionLength(self.len() as u64).write(w)?;
for elem in self.iter() {
elem.write(w)?;
}
Ok(())
}
}

impl Readable for VecDeque<UnsignedJusticeData> {
#[inline]
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
let len: CollectionLength = Readable::read(r)?;
let mut ret = VecDeque::with_capacity(cmp::min(
len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<UnsignedJusticeData>()));
for _ in 0..len.0 {
if let Some(val) = MaybeReadable::read(r)? {
ret.push_back(val);
}
}
Ok(ret)
}
}

impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO its a bit weird to move stuff that's only used in one file into ser.rs, I'd kinda rather keep it with the struct definition.

fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
(self.len() as u64).write(w)?;
for (event, action) in self.iter() {
event.write(w)?;
action.write(w)?;
#[cfg(debug_assertions)] {
// Events are MaybeReadable, in some cases indicating that they shouldn't actually
// be persisted and are regenerated on restart. However, if such an event has a
// post-event-handling action we'll write nothing for the event and would have to
// either forget the action or fail on deserialization (which we do below). Thus,
// check that the event is sane here.
let event_encoded = event.encode();
let event_read: Option<Event> =
MaybeReadable::read(&mut &event_encoded[..]).unwrap();
if action.is_some() { assert!(event_read.is_some()); }
}
}
Ok(())
}
}

impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
let len: u64 = Readable::read(reader)?;
const MAX_ALLOC_SIZE: u64 = 1024 * 16;
let mut events: Self = VecDeque::with_capacity(cmp::min(
MAX_ALLOC_SIZE/mem::size_of::<(Event, Option<EventCompletionAction>)>() as u64,
len) as usize);
for _ in 0..len {
let ev_opt = MaybeReadable::read(reader)?;
let action = Readable::read(reader)?;
if let Some(ev) = ev_opt {
events.push_back((ev, action));
} else if action.is_some() {
return Err(DecodeError::InvalidValue);
}
}
Ok(events)
}
}

// Vectors
macro_rules! impl_writeable_for_vec {
($ty: ty $(, $name: ident)*) => {
Expand DownExpand Up@@ -848,6 +920,7 @@ impl Readable for Vec<u8> {
}
}

impl_for_vec!(u32);
impl_for_vec!(ecdsa::Signature);
impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
Expand Down
87 changes: 20 additions & 67 deletions lightning/src/util/test_utils.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,7 +22,6 @@ use crate::events;
use crate::events::bump_transaction::{WalletSource, Utxo};
use crate::ln::ChannelId;
use crate::ln::channelmanager;
use crate::ln::chan_utils::CommitmentTransaction;
use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
use crate::ln::{msgs, wire};
use crate::ln::msgs::LightningError;
Expand All@@ -38,6 +37,7 @@ use crate::util::config::UserConfig;
use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState};
use crate::util::logger::{Logger, Level, Record};
use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
use crate::util::watchtower::JusticeTxTracker;

use bitcoin::EcdsaSighashType;
use bitcoin::blockdata::constants::ChainHash;
Expand All@@ -61,7 +61,6 @@ use regex;
use crate::io;
use crate::prelude::*;
use core::cell::RefCell;
use core::ops::Deref;
use core::time::Duration;
use crate::sync::{Mutex, Arc};
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
Expand DownExpand Up@@ -276,50 +275,30 @@ impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
}
}

struct JusticeTxData {
justice_tx: Transaction,
value: u64,
commitment_number: u64,
}

pub(crate) struct WatchtowerPersister {
persister: TestPersister,
/// Upon a new commitment_signed, we'll get a
/// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
/// amount, and commitment number so we can build the justice tx after our counterparty
/// revokes it.
unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
/// `ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo`. We'll use our utility
/// object `JusticeTxTracker` to build and sign the justice tx.
justice_tx_tracker: RefCell<JusticeTxTracker>,
/// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
/// tx which would be used to provide a watchtower with the data it needs.
watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
destination_script: Script,
signed_justice_txs: RefCell<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
}

impl WatchtowerPersister {
pub(crate) fn new(destination_script: Script) -> Self {
WatchtowerPersister {
persister: TestPersister::new(),
unsigned_justice_tx_data: Mutex::new(HashMap::new()),
watchtower_state: Mutex::new(HashMap::new()),
destination_script,
justice_tx_tracker: RefCell::new(JusticeTxTracker::new(vec![FEERATE_FLOOR_SATS_PER_KW],
destination_script)),
signed_justice_txs: RefCell::new(HashMap::new()),
}
}

pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
-> Option<Transaction> {
self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}

fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
-> Option<JusticeTxData> {
let trusted_tx = counterparty_commitment_tx.trust();
let output_idx = trusted_tx.revokeable_output_index()?;
let built_tx = trusted_tx.built_transaction();
let value = built_tx.transaction.output[output_idx as usize].value;
let justice_tx = trusted_tx.build_to_local_justice_tx(
FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
let commitment_number = counterparty_commitment_tx.commitment_number();
Some(JusticeTxData { justice_tx, value, commitment_number })
self.signed_justice_txs.borrow().get(&funding_txo).unwrap().get(commitment_txid).cloned()
}
}

Expand All@@ -328,20 +307,8 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.persist_new_channel(funding_txo, data, id);

assert!(self.unsigned_justice_tx_data.lock().unwrap()
.insert(funding_txo, VecDeque::new()).is_none());
assert!(self.watchtower_state.lock().unwrap()
.insert(funding_txo, HashMap::new()).is_none());

let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
.expect("First and only call expects Some");
if let Some(justice_data)
= self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
self.unsigned_justice_tx_data.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.push_back(justice_data);
}
self.justice_tx_tracker.borrow_mut().add_new_channel(funding_txo, data);
assert!(self.signed_justice_txs.borrow_mut().insert(funding_txo, HashMap::new()).is_none());
res
}

Expand All@@ -350,29 +317,15 @@ impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> fo
data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
) -> chain::ChannelMonitorUpdateStatus {
let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);

if let Some(update) = update {
let commitment_txs = data.counterparty_commitment_txs_from_update(update);
let justice_datas = commitment_txs.into_iter()
.filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
channel_state.extend(justice_datas);

while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
let input_idx = 0;
let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
Ok(signed_justice_tx) => {
let dup = self.watchtower_state.lock().unwrap()
.get_mut(&funding_txo).unwrap()
.insert(commitment_txid, signed_justice_tx);
assert!(dup.is_none());
channel_state.pop_front();
},
Err(_) => break,
}
}
let signed_justice_txs = match update {
Some(update) =>
self.justice_tx_tracker.borrow_mut().process_update(funding_txo, data, update),
None => vec![],
};
for tx in signed_justice_txs {
let commitment_txid = tx.input[0].previous_output.txid;
self.signed_justice_txs.borrow_mut()
.get_mut(&funding_txo).unwrap().insert(commitment_txid, tx);
}
res
}
Expand Down
Loading