Skip to content

Commit 2933900

Browse files
committed
f - Use BestBlock in ChannelMonitor
1 parent d5c6057 commit 2933900

File tree

3 files changed

+28
-37
lines changed

3 files changed

+28
-37
lines changed

lightning/src/chain/channelmonitor.rs

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ use bitcoin::secp256k1;
3737
use ln::msgs::DecodeError;
3838
use ln::chan_utils;
3939
use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCType, ChannelTransactionParameters, HolderCommitmentTransaction};
40-
use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
40+
use ln::channelmanager::{BestBlock, HTLCSource, PaymentPreimage, PaymentHash};
4141
use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
4242
use chain;
4343
use chain::WatchedOutput;
@@ -737,13 +737,12 @@ pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
737737
// remote monitor out-of-order with regards to the block view.
738738
holder_tx_signed: bool,
739739

740-
// We simply modify last_block_hash in Channel's block_connected so that serialization is
740+
// We simply modify best_block in Channel's block_connected so that serialization is
741741
// consistent but hopefully the users' copy handles block_connected in a consistent way.
742742
// (we do *not*, however, update them in update_monitor to ensure any local user copies keep
743-
// their last_block_hash from its state and not based on updated copies that didn't run through
743+
// their best_block from its state and not based on updated copies that didn't run through
744744
// the full block_connected).
745-
last_block_hash: BlockHash,
746-
last_block_height: u32,
745+
best_block: BestBlock,
747746

748747
secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
749748
}
@@ -956,8 +955,8 @@ impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
956955
event.write(writer)?;
957956
}
958957

959-
self.last_block_hash.write(writer)?;
960-
writer.write_all(&byte_utils::be32_to_array(self.last_block_height))?;
958+
self.best_block.block_hash().write(writer)?;
959+
writer.write_all(&byte_utils::be32_to_array(self.best_block.height()))?;
961960

962961
writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
963962
for ref entry in self.onchain_events_waiting_threshold_conf.iter() {
@@ -1001,7 +1000,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
10011000
funding_redeemscript: Script, channel_value_satoshis: u64,
10021001
commitment_transaction_number_obscure_factor: u64,
10031002
initial_holder_commitment_tx: HolderCommitmentTransaction,
1004-
last_block_hash: BlockHash, last_block_height: u32) -> ChannelMonitor<Signer> {
1003+
best_block: BestBlock) -> ChannelMonitor<Signer> {
10051004

10061005
assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
10071006
let our_channel_close_key_hash = WPubkeyHash::hash(&shutdown_pubkey.serialize());
@@ -1088,8 +1087,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
10881087
lockdown_from_offchain: false,
10891088
holder_tx_signed: false,
10901089

1091-
last_block_hash,
1092-
last_block_height,
1090+
best_block,
10931091

10941092
secp_ctx,
10951093
}),
@@ -2129,8 +2127,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
21292127
}
21302128

21312129
self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, Some(height), &&*broadcaster, &&*fee_estimator, &&*logger);
2132-
self.last_block_hash = block_hash;
2133-
self.last_block_height = height;
2130+
self.best_block = BestBlock::new(block_hash, height);
21342131

21352132
// Determine new outputs to watch by comparing against previously known outputs to watch,
21362133
// updating the latter in the process.
@@ -2169,8 +2166,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
21692166

21702167
self.onchain_tx_handler.block_disconnected(height, broadcaster, fee_estimator, logger);
21712168

2172-
self.last_block_hash = header.prev_blockhash;
2173-
self.last_block_height = height - 1;
2169+
self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
21742170
}
21752171

21762172
/// Filters a block's `txdata` for transactions spending watched outputs or for any child
@@ -2741,8 +2737,7 @@ impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
27412737
}
27422738
}
27432739

2744-
let last_block_hash: BlockHash = Readable::read(reader)?;
2745-
let last_block_height: u32 = Readable::read(reader)?;
2740+
let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
27462741

27472742
let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
27482743
let mut onchain_events_waiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
@@ -2789,7 +2784,7 @@ impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
27892784
let mut secp_ctx = Secp256k1::new();
27902785
secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
27912786

2792-
Ok((last_block_hash.clone(), ChannelMonitor {
2787+
Ok((best_block.block_hash(), ChannelMonitor {
27932788
inner: Mutex::new(ChannelMonitorImpl {
27942789
latest_update_id,
27952790
commitment_transaction_number_obscure_factor,
@@ -2834,8 +2829,7 @@ impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
28342829
lockdown_from_offchain,
28352830
holder_tx_signed,
28362831

2837-
last_block_hash,
2838-
last_block_height,
2832+
best_block,
28392833

28402834
secp_ctx,
28412835
}),
@@ -2845,7 +2839,6 @@ impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
28452839

28462840
#[cfg(test)]
28472841
mod tests {
2848-
use bitcoin::blockdata::constants::genesis_block;
28492842
use bitcoin::blockdata::script::{Script, Builder};
28502843
use bitcoin::blockdata::opcodes;
28512844
use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
@@ -2859,7 +2852,7 @@ mod tests {
28592852
use hex;
28602853
use chain::channelmonitor::ChannelMonitor;
28612854
use chain::transaction::OutPoint;
2862-
use ln::channelmanager::{PaymentPreimage, PaymentHash};
2855+
use ln::channelmanager::{BestBlock, PaymentPreimage, PaymentHash};
28632856
use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
28642857
use ln::chan_utils;
28652858
use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
@@ -2955,14 +2948,13 @@ mod tests {
29552948
};
29562949
// Prune with one old state and a holder commitment tx holding a few overlaps with the
29572950
// old state.
2958-
let last_block_hash = genesis_block(Network::Testnet).block_hash();
2959-
let last_block_height = 0;
2951+
let best_block = BestBlock::from_genesis(Network::Testnet);
29602952
let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
29612953
&PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0, &Script::new(),
29622954
(OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
29632955
&channel_parameters,
29642956
Script::new(), 46, 0,
2965-
HolderCommitmentTransaction::dummy(), last_block_hash, last_block_height);
2957+
HolderCommitmentTransaction::dummy(), best_block);
29662958

29672959
monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
29682960
let dummy_txid = dummy_tx.txid();

lightning/src/ln/channel.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use bitcoin::secp256k1;
2424
use ln::features::{ChannelFeatures, InitFeatures};
2525
use ln::msgs;
2626
use ln::msgs::{DecodeError, OptionalField, DataLossProtect};
27-
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, MAX_LOCAL_BREAKDOWN_TIMEOUT};
27+
use ln::channelmanager::{BestBlock, PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, MAX_LOCAL_BREAKDOWN_TIMEOUT};
2828
use ln::chan_utils::{CounterpartyCommitmentSecrets, TxCreationKeys, HTLCOutputInCommitment, HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT, make_funding_redeemscript, ChannelPublicKeys, CommitmentTransaction, HolderCommitmentTransaction, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, MAX_HTLCS, get_commitment_transaction_number_obscure_factor};
2929
use ln::chan_utils;
3030
use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
@@ -1529,7 +1529,7 @@ impl<Signer: Sign> Channel<Signer> {
15291529
&self.get_counterparty_pubkeys().funding_pubkey
15301530
}
15311531

1532-
pub fn funding_created<L: Deref>(&mut self, msg: &msgs::FundingCreated, last_block_hash: BlockHash, last_block_height: u32, logger: &L) -> Result<(msgs::FundingSigned, ChannelMonitor<Signer>), ChannelError> where L::Target: Logger {
1532+
pub fn funding_created<L: Deref>(&mut self, msg: &msgs::FundingCreated, best_block: BestBlock, logger: &L) -> Result<(msgs::FundingSigned, ChannelMonitor<Signer>), ChannelError> where L::Target: Logger {
15331533
if self.is_outbound() {
15341534
return Err(ChannelError::Close("Received funding_created for an outbound channel?".to_owned()));
15351535
}
@@ -1583,7 +1583,7 @@ impl<Signer: Sign> Channel<Signer> {
15831583
&self.channel_transaction_parameters,
15841584
funding_redeemscript.clone(), self.channel_value_satoshis,
15851585
obscure_factor,
1586-
holder_commitment_tx, last_block_hash, last_block_height);
1586+
holder_commitment_tx, best_block);
15871587

15881588
channel_monitor.provide_latest_counterparty_commitment_tx(counterparty_initial_commitment_txid, Vec::new(), self.cur_counterparty_commitment_transaction_number, self.counterparty_cur_commitment_point.unwrap(), logger);
15891589

@@ -1600,7 +1600,7 @@ impl<Signer: Sign> Channel<Signer> {
16001600

16011601
/// Handles a funding_signed message from the remote end.
16021602
/// If this call is successful, broadcast the funding transaction (and not before!)
1603-
pub fn funding_signed<L: Deref>(&mut self, msg: &msgs::FundingSigned, last_block_hash: BlockHash, last_block_height: u32, logger: &L) -> Result<ChannelMonitor<Signer>, ChannelError> where L::Target: Logger {
1603+
pub fn funding_signed<L: Deref>(&mut self, msg: &msgs::FundingSigned, best_block: BestBlock, logger: &L) -> Result<ChannelMonitor<Signer>, ChannelError> where L::Target: Logger {
16041604
if !self.is_outbound() {
16051605
return Err(ChannelError::Close("Received funding_signed for an inbound channel?".to_owned()));
16061606
}
@@ -1653,7 +1653,7 @@ impl<Signer: Sign> Channel<Signer> {
16531653
&self.channel_transaction_parameters,
16541654
funding_redeemscript.clone(), self.channel_value_satoshis,
16551655
obscure_factor,
1656-
holder_commitment_tx, last_block_hash, last_block_height);
1656+
holder_commitment_tx, best_block);
16571657

16581658
channel_monitor.provide_latest_counterparty_commitment_tx(counterparty_initial_bitcoin_tx.txid, Vec::new(), self.cur_counterparty_commitment_transaction_number, self.counterparty_cur_commitment_point.unwrap(), logger);
16591659

@@ -4791,7 +4791,7 @@ mod tests {
47914791
use bitcoin::network::constants::Network;
47924792
use bitcoin::hashes::hex::FromHex;
47934793
use hex;
4794-
use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
4794+
use ln::channelmanager::{BestBlock, HTLCSource, PaymentPreimage, PaymentHash};
47954795
use ln::channel::{Channel,Sign,InboundHTLCOutput,OutboundHTLCOutput,InboundHTLCState,OutboundHTLCState,HTLCOutputInCommitment,HTLCCandidate,HTLCInitiator,TxCreationKeys};
47964796
use ln::channel::MAX_FUNDING_SATOSHIS;
47974797
use ln::features::InitFeatures;
@@ -5004,9 +5004,8 @@ mod tests {
50045004
let secp_ctx = Secp256k1::new();
50055005
let seed = [42; 32];
50065006
let network = Network::Testnet;
5007-
let chain_hash = genesis_block(network).header.block_hash();
5008-
let last_block_hash = chain_hash;
5009-
let last_block_height = 0;
5007+
let best_block = BestBlock::from_genesis(network);
5008+
let chain_hash = best_block.block_hash();
50105009
let keys_provider = test_utils::TestKeysInterface::new(&seed, network);
50115010

50125011
// Go through the flow of opening a channel between two nodes.
@@ -5032,10 +5031,10 @@ mod tests {
50325031
}]};
50335032
let funding_outpoint = OutPoint{ txid: tx.txid(), index: 0 };
50345033
let funding_created_msg = node_a_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap();
5035-
let (funding_signed_msg, _) = node_b_chan.funding_created(&funding_created_msg, last_block_hash, last_block_height, &&logger).unwrap();
5034+
let (funding_signed_msg, _) = node_b_chan.funding_created(&funding_created_msg, best_block, &&logger).unwrap();
50365035

50375036
// Node B --> Node A: funding signed
5038-
let _ = node_a_chan.funding_signed(&funding_signed_msg, last_block_hash, last_block_height, &&logger);
5037+
let _ = node_a_chan.funding_signed(&funding_signed_msg, best_block, &&logger);
50395038

50405039
// Now disconnect the two nodes and check that the commitment point in
50415040
// Node B's channel_reestablish message is sane.

lightning/src/ln/channelmanager.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2509,7 +2509,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
25092509
if chan.get().get_counterparty_node_id() != *counterparty_node_id {
25102510
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.temporary_channel_id));
25112511
}
2512-
(try_chan_entry!(self, chan.get_mut().funding_created(msg, best_block.block_hash(), best_block.height(), &self.logger), channel_state, chan), chan.remove())
2512+
(try_chan_entry!(self, chan.get_mut().funding_created(msg, best_block, &self.logger), channel_state, chan), chan.remove())
25132513
},
25142514
hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.temporary_channel_id))
25152515
}
@@ -2566,7 +2566,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
25662566
if chan.get().get_counterparty_node_id() != *counterparty_node_id {
25672567
return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a message for a channel from the wrong node!".to_owned(), msg.channel_id));
25682568
}
2569-
let monitor = match chan.get_mut().funding_signed(&msg, best_block.block_hash(), best_block.height(), &self.logger) {
2569+
let monitor = match chan.get_mut().funding_signed(&msg, best_block, &self.logger) {
25702570
Ok(update) => update,
25712571
Err(e) => try_chan_entry!(self, Err(e), channel_state, chan),
25722572
};

0 commit comments

Comments
 (0)