Skip to content

Commit 514d68f

Browse files
committed
Use utility methods to construct HashMaps and HashSets
In the next commit we'll bump the `hashbrown` version, which no longer randomizes its hasher by default. Thus, we'll need to call a different constructor in no-std builds from std builds. Here we do a quick prefactor to use wrappers for constructors instead of calling the tables directly to make the version bump changeset smaller.
1 parent 171674f commit 514d68f

22 files changed

+155
-131
lines changed

lightning/src/chain/chainmonitor.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@ where C::Target: chain::Filter,
420420
/// transactions relevant to the watched channels.
421421
pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
422422
Self {
423-
monitors: RwLock::new(HashMap::new()),
423+
monitors: RwLock::new(new_hash_map()),
424424
sync_persistence_id: AtomicCounter::new(),
425425
chain_source,
426426
broadcaster,

lightning/src/chain/channelmonitor.rs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1235,7 +1235,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
12351235
channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx
12361236
);
12371237

1238-
let mut outputs_to_watch = HashMap::new();
1238+
let mut outputs_to_watch = new_hash_map();
12391239
outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
12401240

12411241
Self::from_impl(ChannelMonitorImpl {
@@ -1262,17 +1262,17 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
12621262
on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
12631263

12641264
commitment_secrets: CounterpartyCommitmentSecrets::new(),
1265-
counterparty_claimable_outpoints: HashMap::new(),
1266-
counterparty_commitment_txn_on_chain: HashMap::new(),
1267-
counterparty_hash_commitment_number: HashMap::new(),
1268-
counterparty_fulfilled_htlcs: HashMap::new(),
1265+
counterparty_claimable_outpoints: new_hash_map(),
1266+
counterparty_commitment_txn_on_chain: new_hash_map(),
1267+
counterparty_hash_commitment_number: new_hash_map(),
1268+
counterparty_fulfilled_htlcs: new_hash_map(),
12691269

12701270
prev_holder_signed_commitment_tx: None,
12711271
current_holder_commitment_tx: holder_commitment_tx,
12721272
current_counterparty_commitment_number: 1 << 48,
12731273
current_holder_commitment_number,
12741274

1275-
payment_preimages: HashMap::new(),
1275+
payment_preimages: new_hash_map(),
12761276
pending_monitor_events: Vec::new(),
12771277
pending_events: Vec::new(),
12781278
is_processing_pending_events: false,
@@ -2174,7 +2174,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
21742174
/// HTLCs which were resolved on-chain (i.e. where the final HTLC resolution was done by an
21752175
/// event from this `ChannelMonitor`).
21762176
pub(crate) fn get_all_current_outbound_htlcs(&self) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
2177-
let mut res = HashMap::new();
2177+
let mut res = new_hash_map();
21782178
// Just examine the available counterparty commitment transactions. See docs on
21792179
// `fail_unbroadcast_htlcs`, below, for justification.
21802180
let us = self.inner.lock().unwrap();
@@ -2226,7 +2226,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
22262226
return self.get_all_current_outbound_htlcs();
22272227
}
22282228

2229-
let mut res = HashMap::new();
2229+
let mut res = new_hash_map();
22302230
macro_rules! walk_htlcs {
22312231
($holder_commitment: expr, $htlc_iter: expr) => {
22322232
for (htlc, source) in $htlc_iter {
@@ -3940,7 +3940,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
39403940
/// Filters a block's `txdata` for transactions spending watched outputs or for any child
39413941
/// transactions thereof.
39423942
fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
3943-
let mut matched_txn = HashSet::new();
3943+
let mut matched_txn = new_hash_set();
39443944
txdata.iter().filter(|&&(_, tx)| {
39453945
let mut matches = self.spends_watched_output(tx);
39463946
for input in tx.input.iter() {
@@ -4455,7 +4455,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
44554455
}
44564456

44574457
let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
4458-
let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
4458+
let mut counterparty_claimable_outpoints = hash_map_with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
44594459
for _ in 0..counterparty_claimable_outpoints_len {
44604460
let txid: Txid = Readable::read(reader)?;
44614461
let htlcs_count: u64 = Readable::read(reader)?;
@@ -4469,7 +4469,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
44694469
}
44704470

44714471
let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
4472-
let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
4472+
let mut counterparty_commitment_txn_on_chain = hash_map_with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
44734473
for _ in 0..counterparty_commitment_txn_on_chain_len {
44744474
let txid: Txid = Readable::read(reader)?;
44754475
let commitment_number = <U48 as Readable>::read(reader)?.0;
@@ -4479,7 +4479,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
44794479
}
44804480

44814481
let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
4482-
let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
4482+
let mut counterparty_hash_commitment_number = hash_map_with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
44834483
for _ in 0..counterparty_hash_commitment_number_len {
44844484
let payment_hash: PaymentHash = Readable::read(reader)?;
44854485
let commitment_number = <U48 as Readable>::read(reader)?.0;
@@ -4502,7 +4502,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
45024502
let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
45034503

45044504
let payment_preimages_len: u64 = Readable::read(reader)?;
4505-
let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
4505+
let mut payment_preimages = hash_map_with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
45064506
for _ in 0..payment_preimages_len {
45074507
let preimage: PaymentPreimage = Readable::read(reader)?;
45084508
let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
@@ -4542,7 +4542,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
45424542
}
45434543

45444544
let outputs_to_watch_len: u64 = Readable::read(reader)?;
4545-
let mut outputs_to_watch = HashMap::with_capacity(cmp::min(outputs_to_watch_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<Txid>() + mem::size_of::<u32>() + mem::size_of::<Vec<ScriptBuf>>())));
4545+
let mut outputs_to_watch = hash_map_with_capacity(cmp::min(outputs_to_watch_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<Txid>() + mem::size_of::<u32>() + mem::size_of::<Vec<ScriptBuf>>())));
45464546
for _ in 0..outputs_to_watch_len {
45474547
let txid = Readable::read(reader)?;
45484548
let outputs_len: u64 = Readable::read(reader)?;
@@ -4584,7 +4584,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
45844584
let mut counterparty_node_id = None;
45854585
let mut confirmed_commitment_tx_counterparty_output = None;
45864586
let mut spendable_txids_confirmed = Some(Vec::new());
4587-
let mut counterparty_fulfilled_htlcs = Some(HashMap::new());
4587+
let mut counterparty_fulfilled_htlcs = Some(new_hash_map());
45884588
let mut initial_counterparty_commitment_info = None;
45894589
let mut channel_id = None;
45904590
read_tlv_fields!(reader, {

lightning/src/chain/onchaintx.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -374,13 +374,13 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
374374
signer.provide_channel_parameters(&channel_parameters);
375375

376376
let pending_claim_requests_len: u64 = Readable::read(reader)?;
377-
let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
377+
let mut pending_claim_requests = hash_map_with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
378378
for _ in 0..pending_claim_requests_len {
379379
pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
380380
}
381381

382382
let claimable_outpoints_len: u64 = Readable::read(reader)?;
383-
let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
383+
let mut claimable_outpoints = hash_map_with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
384384
for _ in 0..claimable_outpoints_len {
385385
let outpoint = Readable::read(reader)?;
386386
let ancestor_claim_txid = Readable::read(reader)?;
@@ -445,8 +445,8 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
445445
prev_holder_commitment: None,
446446
signer,
447447
channel_transaction_parameters: channel_parameters,
448-
pending_claim_requests: HashMap::new(),
449-
claimable_outpoints: HashMap::new(),
448+
pending_claim_requests: new_hash_map(),
449+
claimable_outpoints: new_hash_map(),
450450
locktimed_packages: BTreeMap::new(),
451451
onchain_events_awaiting_threshold_conf: Vec::new(),
452452
pending_claim_events: Vec::new(),
@@ -834,7 +834,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
834834
F::Target: FeeEstimator,
835835
{
836836
log_debug!(logger, "Updating claims view at height {} with {} matched transactions in block {}", cur_height, txn_matched.len(), conf_height);
837-
let mut bump_candidates = HashMap::new();
837+
let mut bump_candidates = new_hash_map();
838838
for tx in txn_matched {
839839
// Scan all input to verify is one of the outpoint spent is of interest for us
840840
let mut claimed_outputs_material = Vec::new();
@@ -1020,7 +1020,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
10201020
where B::Target: BroadcasterInterface,
10211021
F::Target: FeeEstimator,
10221022
{
1023-
let mut bump_candidates = HashMap::new();
1023+
let mut bump_candidates = new_hash_map();
10241024
let onchain_events_awaiting_threshold_conf =
10251025
self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
10261026
for entry in onchain_events_awaiting_threshold_conf {

lightning/src/events/bump_transaction.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ where
391391
/// Returns a new instance backed by the given [`WalletSource`] that serves as an implementation
392392
/// of [`CoinSelectionSource`].
393393
pub fn new(source: W, logger: L) -> Self {
394-
Self { source, logger, locked_utxos: Mutex::new(HashMap::new()) }
394+
Self { source, logger, locked_utxos: Mutex::new(new_hash_map()) }
395395
}
396396

397397
/// Performs coin selection on the set of UTXOs obtained from

lightning/src/lib.rs

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,10 +169,40 @@ mod prelude {
169169
extern crate hashbrown;
170170

171171
pub use alloc::{vec, vec::Vec, string::String, collections::VecDeque, boxed::Box};
172+
173+
#[cfg(not(feature = "hashbrown"))]
174+
mod std_hashtables {
175+
pub(crate) use std::collections::{HashMap, HashSet, hash_map};
176+
177+
pub(crate) type OccupiedHashMapEntry<'a, K, V> =
178+
std::collections::hash_map::OccupiedEntry<'a, K, V>;
179+
pub(crate) type VacantHashMapEntry<'a, K, V> =
180+
std::collections::hash_map::VacantEntry<'a, K, V>;
181+
}
172182
#[cfg(not(feature = "hashbrown"))]
173-
pub use std::collections::{HashMap, HashSet, hash_map};
183+
pub(crate) use std_hashtables::*;
184+
185+
#[cfg(feature = "hashbrown")]
186+
mod hashbrown_tables {
187+
pub(crate) use hashbrown::{HashMap, HashSet, hash_map};
188+
189+
pub(crate) type OccupiedHashMapEntry<'a, K, V> =
190+
hashbrown::hash_map::OccupiedEntry<'a, K, V, hash_map::DefaultHashBuilder>;
191+
pub(crate) type VacantHashMapEntry<'a, K, V> =
192+
hashbrown::hash_map::VacantEntry<'a, K, V, hash_map::DefaultHashBuilder>;
193+
}
174194
#[cfg(feature = "hashbrown")]
175-
pub use self::hashbrown::{HashMap, HashSet, hash_map};
195+
pub(crate) use hashbrown_tables::*;
196+
197+
pub(crate) fn new_hash_map<K: core::hash::Hash + Eq, V>() -> HashMap<K, V> { HashMap::new() }
198+
pub(crate) fn hash_map_with_capacity<K: core::hash::Hash + Eq, V>(cap: usize) -> HashMap<K, V> {
199+
HashMap::with_capacity(cap)
200+
}
201+
202+
pub(crate) fn new_hash_set<K: core::hash::Hash + Eq>() -> HashSet<K> { HashSet::new() }
203+
pub(crate) fn hash_set_with_capacity<K: core::hash::Hash + Eq>(cap: usize) -> HashSet<K> {
204+
HashSet::with_capacity(cap)
205+
}
176206

177207
pub use alloc::borrow::ToOwned;
178208
pub use alloc::string::ToString;

lightning/src/ln/channel.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6431,7 +6431,7 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
64316431
channel_ready_event_emitted: false,
64326432

64336433
#[cfg(any(test, fuzzing))]
6434-
historical_inbound_htlc_fulfills: HashSet::new(),
6434+
historical_inbound_htlc_fulfills: new_hash_set(),
64356435

64366436
channel_type,
64376437
channel_keys_id,
@@ -7232,7 +7232,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
72327232
channel_ready_event_emitted: false,
72337233

72347234
#[cfg(any(test, fuzzing))]
7235-
historical_inbound_htlc_fulfills: HashSet::new(),
7235+
historical_inbound_htlc_fulfills: new_hash_set(),
72367236

72377237
channel_type,
72387238
channel_keys_id,
@@ -8048,7 +8048,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
80488048
let channel_update_status = Readable::read(reader)?;
80498049

80508050
#[cfg(any(test, fuzzing))]
8051-
let mut historical_inbound_htlc_fulfills = HashSet::new();
8051+
let mut historical_inbound_htlc_fulfills = new_hash_set();
80528052
#[cfg(any(test, fuzzing))]
80538053
{
80548054
let htlc_fulfills_len: u64 = Readable::read(reader)?;

0 commit comments

Comments
 (0)