Skip to content

Commit 54f96ef

Browse files
committed
Use ChainHash instead of BlockHash as applicable
ChainHash is more appropriate for places where an arbitrary BlockHash is not desirable. This type was introduced in later versions of the bitcoin crate, thus BlockHash was used instead. Using ChainHash also makes it easier to check if ChannelManager is compatible with an Offer.
1 parent b1d3aa8 commit 54f96ef

File tree

19 files changed

+318
-316
lines changed

19 files changed

+318
-316
lines changed

fuzz/src/full_stack.rs

+2-2
Large diffs are not rendered by default.

fuzz/src/router.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77
// You may not use this file except in accordance with one or both of these
88
// licenses.
99

10+
use bitcoin::blockdata::constants::ChainHash;
1011
use bitcoin::blockdata::script::Builder;
1112
use bitcoin::blockdata::transaction::TxOut;
12-
use bitcoin::hash_types::BlockHash;
1313

1414
use lightning::blinded_path::{BlindedHop, BlindedPath};
1515
use lightning::chain::transaction::OutPoint;
@@ -89,7 +89,7 @@ struct FuzzChainSource<'a, 'b, Out: test_logger::Output> {
8989
net_graph: &'a NetworkGraph<&'b test_logger::TestLogger<Out>>,
9090
}
9191
impl<Out: test_logger::Output> UtxoLookup for FuzzChainSource<'_, '_, Out> {
92-
fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
92+
fn get_utxo(&self, _chain_hash: &ChainHash, _short_channel_id: u64) -> UtxoResult {
9393
let input_slice = self.input.get_slice(2);
9494
if input_slice.is_none() { return UtxoResult::Sync(Err(UtxoLookupError::UnknownTx)); }
9595
let input_slice = input_slice.unwrap();

lightning-block-sync/src/gossip.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use crate::{AsyncBlockSourceResult, BlockData, BlockSource, BlockSourceError};
66

77
use bitcoin::blockdata::block::Block;
8+
use bitcoin::blockdata::constants::ChainHash;
89
use bitcoin::blockdata::transaction::{TxOut, OutPoint};
910
use bitcoin::hash_types::BlockHash;
1011

@@ -302,7 +303,7 @@ impl<S: FutureSpawner,
302303
CMH::Target: CustomMessageHandler,
303304
NS::Target: NodeSigner,
304305
{
305-
fn get_utxo(&self, _genesis_hash: &BlockHash, short_channel_id: u64) -> UtxoResult {
306+
fn get_utxo(&self, _chain_hash: &ChainHash, short_channel_id: u64) -> UtxoResult {
306307
let res = UtxoFuture::new();
307308
let fut = res.clone();
308309
let source = self.source.clone();

lightning-net-tokio/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -630,7 +630,7 @@ mod tests {
630630
fn handle_error(&self, _their_node_id: &PublicKey, _msg: &ErrorMessage) {}
631631
fn provided_node_features(&self) -> NodeFeatures { NodeFeatures::empty() }
632632
fn provided_init_features(&self, _their_node_id: &PublicKey) -> InitFeatures { InitFeatures::empty() }
633-
fn get_genesis_hashes(&self) -> Option<Vec<ChainHash>> {
633+
fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
634634
Some(vec![ChainHash::using_genesis_block(Network::Testnet)])
635635
}
636636
}

lightning-rapid-gossip-sync/src/processing.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use core::cmp::max;
22
use core::ops::Deref;
33
use core::sync::atomic::Ordering;
44

5-
use bitcoin::BlockHash;
5+
use bitcoin::blockdata::constants::ChainHash;
66
use bitcoin::secp256k1::PublicKey;
77

88
use lightning::ln::msgs::{
@@ -67,9 +67,9 @@ impl<NG: Deref<Target=NetworkGraph<L>>, L: Deref> RapidGossipSync<NG, L> where L
6767
return Err(DecodeError::UnknownVersion.into());
6868
}
6969

70-
let chain_hash: BlockHash = Readable::read(read_cursor)?;
71-
let ng_genesis_hash = self.network_graph.get_genesis_hash();
72-
if chain_hash != ng_genesis_hash {
70+
let chain_hash: ChainHash = Readable::read(read_cursor)?;
71+
let ng_chain_hash = self.network_graph.get_chain_hash();
72+
if chain_hash != ng_chain_hash {
7373
return Err(
7474
LightningError {
7575
err: "Rapid Gossip Sync data's chain hash does not match the network graph's".to_owned(),

lightning/src/ln/channel.rs

+39-38
Large diffs are not rendered by default.

lightning/src/ln/channelmanager.rs

+29-29
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020
use bitcoin::blockdata::block::BlockHeader;
2121
use bitcoin::blockdata::transaction::Transaction;
22-
use bitcoin::blockdata::constants::{genesis_block, ChainHash};
22+
use bitcoin::blockdata::constants::ChainHash;
2323
use bitcoin::network::constants::Network;
2424

2525
use bitcoin::hashes::Hash;
@@ -1018,7 +1018,7 @@ where
10181018
L::Target: Logger,
10191019
{
10201020
default_configuration: UserConfig,
1021-
genesis_hash: BlockHash,
1021+
chain_hash: ChainHash,
10221022
fee_estimator: LowerBoundedFeeEstimator<F>,
10231023
chain_monitor: M,
10241024
tx_broadcaster: T,
@@ -2012,7 +2012,7 @@ macro_rules! emit_channel_ready_event {
20122012
macro_rules! handle_monitor_update_completion {
20132013
($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
20142014
let mut updates = $chan.monitor_updating_restored(&$self.logger,
2015-
&$self.node_signer, $self.genesis_hash, &$self.default_configuration,
2015+
&$self.node_signer, $self.chain_hash, &$self.default_configuration,
20162016
$self.best_block.read().unwrap().height());
20172017
let counterparty_node_id = $chan.context.get_counterparty_node_id();
20182018
let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
@@ -2258,7 +2258,7 @@ where
22582258
let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
22592259
ChannelManager {
22602260
default_configuration: config.clone(),
2261-
genesis_hash: genesis_block(params.network).header.block_hash(),
2261+
chain_hash: ChainHash::using_genesis_block(params.network),
22622262
fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
22632263
chain_monitor,
22642264
tx_broadcaster,
@@ -2317,7 +2317,7 @@ where
23172317
if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
23182318
outbound_scid_alias += 1;
23192319
} else {
2320-
outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2320+
outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
23212321
}
23222322
if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
23232323
break;
@@ -2387,7 +2387,7 @@ where
23872387
},
23882388
}
23892389
};
2390-
let res = channel.get_open_channel(self.genesis_hash.clone());
2390+
let res = channel.get_open_channel(self.chain_hash);
23912391

23922392
let temporary_channel_id = channel.context.channel_id();
23932393
match peer_state.channel_by_id.entry(temporary_channel_id) {
@@ -3103,8 +3103,8 @@ where
31033103
// Note that this is likely a timing oracle for detecting whether an scid is a
31043104
// phantom or an intercept.
31053105
if (self.default_configuration.accept_intercept_htlcs &&
3106-
fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.genesis_hash)) ||
3107-
fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.genesis_hash)
3106+
fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)) ||
3107+
fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)
31083108
{
31093109
None
31103110
} else {
@@ -3332,7 +3332,7 @@ where
33323332
};
33333333

33343334
let unsigned = msgs::UnsignedChannelUpdate {
3335-
chain_hash: self.genesis_hash,
3335+
chain_hash: self.chain_hash,
33363336
short_channel_id,
33373337
timestamp: chan.context.get_update_time_counter(),
33383338
flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
@@ -4250,7 +4250,7 @@ where
42504250
}
42514251
if let PendingHTLCRouting::Forward { onion_packet, .. } = routing {
42524252
let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
4253-
if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.genesis_hash) {
4253+
if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.chain_hash) {
42544254
let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
42554255
let next_hop = match onion_utils::decode_next_payment_hop(
42564256
phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac,
@@ -5876,7 +5876,7 @@ where
58765876
fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
58775877
// Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
58785878
// likely to be lost on restart!
5879-
if msg.chain_hash != self.genesis_hash {
5879+
if msg.chain_hash != self.chain_hash {
58805880
return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
58815881
}
58825882

@@ -6141,7 +6141,7 @@ where
61416141
hash_map::Entry::Occupied(mut chan_phase_entry) => {
61426142
if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
61436143
let announcement_sigs_opt = try_chan_phase_entry!(self, chan.channel_ready(&msg, &self.node_signer,
6144-
self.genesis_hash.clone(), &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan_phase_entry);
6144+
self.chain_hash, &self.default_configuration, &self.best_block.read().unwrap(), &self.logger), chan_phase_entry);
61456145
if let Some(announcement_sigs) = announcement_sigs_opt {
61466146
log_trace!(self.logger, "Sending announcement_signatures for channel {}", chan.context.channel_id());
61476147
peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
@@ -6518,7 +6518,7 @@ where
65186518
},
65196519
hash_map::Entry::Vacant(entry) => {
65206520
if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6521-
fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.genesis_hash)
6521+
fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.chain_hash)
65226522
{
65236523
let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).into_inner());
65246524
let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
@@ -6711,7 +6711,7 @@ where
67116711

67126712
peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
67136713
msg: try_chan_phase_entry!(self, chan.announcement_signatures(
6714-
&self.node_signer, self.genesis_hash.clone(), self.best_block.read().unwrap().height(),
6714+
&self.node_signer, self.chain_hash, self.best_block.read().unwrap().height(),
67156715
msg, &self.default_configuration
67166716
), chan_phase_entry),
67176717
// Note that announcement_signatures fails if the channel cannot be announced,
@@ -6799,7 +6799,7 @@ where
67996799
// freed HTLCs to fail backwards. If in the future we no longer drop pending
68006800
// add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
68016801
let responses = try_chan_phase_entry!(self, chan.channel_reestablish(
6802-
msg, &self.logger, &self.node_signer, self.genesis_hash,
6802+
msg, &self.logger, &self.node_signer, self.chain_hash,
68036803
&self.default_configuration, &*self.best_block.read().unwrap()), chan_phase_entry);
68046804
let mut channel_update = None;
68056805
if let Some(msg) = responses.shutdown_msg {
@@ -7179,7 +7179,7 @@ where
71797179
let best_block_height = self.best_block.read().unwrap().height();
71807180
let short_to_chan_info = self.short_to_chan_info.read().unwrap();
71817181
loop {
7182-
let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7182+
let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
71837183
// Ensure the generated scid doesn't conflict with a real channel.
71847184
match short_to_chan_info.get(&scid_candidate) {
71857185
Some(_) => continue,
@@ -7209,7 +7209,7 @@ where
72097209
let best_block_height = self.best_block.read().unwrap().height();
72107210
let short_to_chan_info = self.short_to_chan_info.read().unwrap();
72117211
loop {
7212-
let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.genesis_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
7212+
let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
72137213
// Ensure the generated scid doesn't conflict with a real channel.
72147214
if short_to_chan_info.contains_key(&scid_candidate) { continue }
72157215
return scid_candidate
@@ -7472,7 +7472,7 @@ where
74727472
*best_block = BestBlock::new(header.prev_blockhash, new_height)
74737473
}
74747474

7475-
self.do_chain_event(Some(new_height), |channel| channel.best_block_updated(new_height, header.time, self.genesis_hash.clone(), &self.node_signer, &self.default_configuration, &self.logger));
7475+
self.do_chain_event(Some(new_height), |channel| channel.best_block_updated(new_height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &self.logger));
74767476
}
74777477
}
74787478

@@ -7498,13 +7498,13 @@ where
74987498
let _persistence_guard =
74997499
PersistenceNotifierGuard::optionally_notify_skipping_background_events(
75007500
self, || -> NotifyOption { NotifyOption::DoPersist });
7501-
self.do_chain_event(Some(height), |channel| channel.transactions_confirmed(&block_hash, height, txdata, self.genesis_hash.clone(), &self.node_signer, &self.default_configuration, &self.logger)
7501+
self.do_chain_event(Some(height), |channel| channel.transactions_confirmed(&block_hash, height, txdata, self.chain_hash, &self.node_signer, &self.default_configuration, &self.logger)
75027502
.map(|(a, b)| (a, Vec::new(), b)));
75037503

75047504
let last_best_block_height = self.best_block.read().unwrap().height();
75057505
if height < last_best_block_height {
75067506
let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
7507-
self.do_chain_event(Some(last_best_block_height), |channel| channel.best_block_updated(last_best_block_height, timestamp as u32, self.genesis_hash.clone(), &self.node_signer, &self.default_configuration, &self.logger));
7507+
self.do_chain_event(Some(last_best_block_height), |channel| channel.best_block_updated(last_best_block_height, timestamp as u32, self.chain_hash, &self.node_signer, &self.default_configuration, &self.logger));
75087508
}
75097509
}
75107510

@@ -7521,7 +7521,7 @@ where
75217521
self, || -> NotifyOption { NotifyOption::DoPersist });
75227522
*self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
75237523

7524-
self.do_chain_event(Some(height), |channel| channel.best_block_updated(height, header.time, self.genesis_hash.clone(), &self.node_signer, &self.default_configuration, &self.logger));
7524+
self.do_chain_event(Some(height), |channel| channel.best_block_updated(height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &self.logger));
75257525

75267526
macro_rules! max_time {
75277527
($timestamp: expr) => {
@@ -7641,7 +7641,7 @@ where
76417641
msg: announcement_sigs,
76427642
});
76437643
if let Some(height) = height_opt {
7644-
if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.genesis_hash, height, &self.default_configuration) {
7644+
if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.chain_hash, height, &self.default_configuration) {
76457645
pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
76467646
msg: announcement,
76477647
// Note that announcement_signatures fails if the channel cannot be announced,
@@ -8251,7 +8251,7 @@ where
82518251
let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
82528252
let peer_state = &mut *peer_state_lock;
82538253
if let Some(ChannelPhase::UnfundedOutboundV1(chan)) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
8254-
if let Ok(msg) = chan.maybe_handle_error_without_close(self.genesis_hash, &self.fee_estimator) {
8254+
if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
82558255
peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
82568256
node_id: *counterparty_node_id,
82578257
msg,
@@ -8274,8 +8274,8 @@ where
82748274
provided_init_features(&self.default_configuration)
82758275
}
82768276

8277-
fn get_genesis_hashes(&self) -> Option<Vec<ChainHash>> {
8278-
Some(vec![ChainHash::from(&self.genesis_hash[..])])
8277+
fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
8278+
Some(vec![self.chain_hash])
82798279
}
82808280

82818281
fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
@@ -8820,7 +8820,7 @@ where
88208820

88218821
write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
88228822

8823-
self.genesis_hash.write(writer)?;
8823+
self.chain_hash.write(writer)?;
88248824
{
88258825
let best_block = self.best_block.read().unwrap();
88268826
best_block.height().write(writer)?;
@@ -9231,7 +9231,7 @@ where
92319231
fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
92329232
let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
92339233

9234-
let genesis_hash: BlockHash = Readable::read(reader)?;
9234+
let chain_hash: ChainHash = Readable::read(reader)?;
92359235
let best_block_height: u32 = Readable::read(reader)?;
92369236
let best_block_hash: BlockHash = Readable::read(reader)?;
92379237

@@ -9879,7 +9879,7 @@ where
98799879
let mut outbound_scid_alias;
98809880
loop {
98819881
outbound_scid_alias = fake_scid::Namespace::OutboundAlias
9882-
.get_fake_scid(best_block_height, &genesis_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
9882+
.get_fake_scid(best_block_height, &chain_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
98839883
if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
98849884
}
98859885
chan.context.set_outbound_scid_alias(outbound_scid_alias);
@@ -9993,7 +9993,7 @@ where
99939993
}
99949994

99959995
let channel_manager = ChannelManager {
9996-
genesis_hash,
9996+
chain_hash,
99979997
fee_estimator: bounded_fee_estimator,
99989998
chain_monitor: args.chain_monitor,
99999999
tx_broadcaster: args.tx_broadcaster,

lightning/src/ln/functional_tests.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ use crate::util::config::{UserConfig, MaxDustHTLCExposure};
4040
use bitcoin::hash_types::BlockHash;
4141
use bitcoin::blockdata::script::{Builder, Script};
4242
use bitcoin::blockdata::opcodes;
43-
use bitcoin::blockdata::constants::genesis_block;
43+
use bitcoin::blockdata::constants::ChainHash;
4444
use bitcoin::network::constants::Network;
4545
use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
4646
use bitcoin::OutPoint as BitcoinOutPoint;
@@ -5830,8 +5830,8 @@ fn bolt2_open_channel_sending_node_checks_part2() {
58305830
assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
58315831

58325832
// BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5833-
let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5834-
assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5833+
let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
5834+
assert_eq!(node0_to_1_send_open_channel.chain_hash, chain_hash);
58355835

58365836
// BOLT #2 spec: Sending node must set funding_pubkey, revocation_basepoint, htlc_basepoint, payment_basepoint, and delayed_payment_basepoint to valid DER-encoded, compressed, secp256k1 pubkeys.
58375837
assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());

0 commit comments

Comments
 (0)