Skip to content

Commit b35ab51

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 b23f728 commit b35ab51

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
@@ -419,7 +419,7 @@ where C::Target: chain::Filter,
419419
/// transactions relevant to the watched channels.
420420
pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
421421
Self {
422-
monitors: RwLock::new(HashMap::new()),
422+
monitors: RwLock::new(new_hash_map()),
423423
sync_persistence_id: AtomicCounter::new(),
424424
chain_source,
425425
broadcaster,

lightning/src/chain/channelmonitor.rs

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

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

12271227
Self::from_impl(ChannelMonitorImpl {
@@ -1247,17 +1247,17 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
12471247
on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
12481248

12491249
commitment_secrets: CounterpartyCommitmentSecrets::new(),
1250-
counterparty_claimable_outpoints: HashMap::new(),
1251-
counterparty_commitment_txn_on_chain: HashMap::new(),
1252-
counterparty_hash_commitment_number: HashMap::new(),
1253-
counterparty_fulfilled_htlcs: HashMap::new(),
1250+
counterparty_claimable_outpoints: new_hash_map(),
1251+
counterparty_commitment_txn_on_chain: new_hash_map(),
1252+
counterparty_hash_commitment_number: new_hash_map(),
1253+
counterparty_fulfilled_htlcs: new_hash_map(),
12541254

12551255
prev_holder_signed_commitment_tx: None,
12561256
current_holder_commitment_tx: holder_commitment_tx,
12571257
current_counterparty_commitment_number: 1 << 48,
12581258
current_holder_commitment_number,
12591259

1260-
payment_preimages: HashMap::new(),
1260+
payment_preimages: new_hash_map(),
12611261
pending_monitor_events: Vec::new(),
12621262
pending_events: Vec::new(),
12631263
is_processing_pending_events: false,
@@ -2154,7 +2154,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
21542154
/// HTLCs which were resolved on-chain (i.e. where the final HTLC resolution was done by an
21552155
/// event from this `ChannelMonitor`).
21562156
pub(crate) fn get_all_current_outbound_htlcs(&self) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
2157-
let mut res = HashMap::new();
2157+
let mut res = new_hash_map();
21582158
// Just examine the available counterparty commitment transactions. See docs on
21592159
// `fail_unbroadcast_htlcs`, below, for justification.
21602160
let us = self.inner.lock().unwrap();
@@ -2206,7 +2206,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
22062206
return self.get_all_current_outbound_htlcs();
22072207
}
22082208

2209-
let mut res = HashMap::new();
2209+
let mut res = new_hash_map();
22102210
macro_rules! walk_htlcs {
22112211
($holder_commitment: expr, $htlc_iter: expr) => {
22122212
for (htlc, source) in $htlc_iter {
@@ -3916,7 +3916,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
39163916
/// Filters a block's `txdata` for transactions spending watched outputs or for any child
39173917
/// transactions thereof.
39183918
fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
3919-
let mut matched_txn = HashSet::new();
3919+
let mut matched_txn = new_hash_set();
39203920
txdata.iter().filter(|&&(_, tx)| {
39213921
let mut matches = self.spends_watched_output(tx);
39223922
for input in tx.input.iter() {
@@ -4431,7 +4431,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
44314431
}
44324432

44334433
let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
4434-
let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
4434+
let mut counterparty_claimable_outpoints = hash_map_with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
44354435
for _ in 0..counterparty_claimable_outpoints_len {
44364436
let txid: Txid = Readable::read(reader)?;
44374437
let htlcs_count: u64 = Readable::read(reader)?;
@@ -4445,7 +4445,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
44454445
}
44464446

44474447
let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
4448-
let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
4448+
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));
44494449
for _ in 0..counterparty_commitment_txn_on_chain_len {
44504450
let txid: Txid = Readable::read(reader)?;
44514451
let commitment_number = <U48 as Readable>::read(reader)?.0;
@@ -4455,7 +4455,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
44554455
}
44564456

44574457
let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
4458-
let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
4458+
let mut counterparty_hash_commitment_number = hash_map_with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
44594459
for _ in 0..counterparty_hash_commitment_number_len {
44604460
let payment_hash: PaymentHash = Readable::read(reader)?;
44614461
let commitment_number = <U48 as Readable>::read(reader)?.0;
@@ -4478,7 +4478,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
44784478
let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
44794479

44804480
let payment_preimages_len: u64 = Readable::read(reader)?;
4481-
let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
4481+
let mut payment_preimages = hash_map_with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
44824482
for _ in 0..payment_preimages_len {
44834483
let preimage: PaymentPreimage = Readable::read(reader)?;
44844484
let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
@@ -4518,7 +4518,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
45184518
}
45194519

45204520
let outputs_to_watch_len: u64 = Readable::read(reader)?;
4521-
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>>())));
4521+
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>>())));
45224522
for _ in 0..outputs_to_watch_len {
45234523
let txid = Readable::read(reader)?;
45244524
let outputs_len: u64 = Readable::read(reader)?;
@@ -4560,7 +4560,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
45604560
let mut counterparty_node_id = None;
45614561
let mut confirmed_commitment_tx_counterparty_output = None;
45624562
let mut spendable_txids_confirmed = Some(Vec::new());
4563-
let mut counterparty_fulfilled_htlcs = Some(HashMap::new());
4563+
let mut counterparty_fulfilled_htlcs = Some(new_hash_map());
45644564
let mut initial_counterparty_commitment_info = None;
45654565
read_tlv_fields!(reader, {
45664566
(1, funding_spend_confirmed, option),

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
@@ -167,10 +167,40 @@ mod prelude {
167167
extern crate hashbrown;
168168

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

175205
pub use alloc::borrow::ToOwned;
176206
pub use alloc::string::ToString;

lightning/src/ln/channel.rs

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

64106410
#[cfg(any(test, fuzzing))]
6411-
historical_inbound_htlc_fulfills: HashSet::new(),
6411+
historical_inbound_htlc_fulfills: new_hash_set(),
64126412

64136413
channel_type,
64146414
channel_keys_id,
@@ -7209,7 +7209,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
72097209
channel_ready_event_emitted: false,
72107210

72117211
#[cfg(any(test, fuzzing))]
7212-
historical_inbound_htlc_fulfills: HashSet::new(),
7212+
historical_inbound_htlc_fulfills: new_hash_set(),
72137213

72147214
channel_type,
72157215
channel_keys_id,
@@ -8023,7 +8023,7 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
80238023
let channel_update_status = Readable::read(reader)?;
80248024

80258025
#[cfg(any(test, fuzzing))]
8026-
let mut historical_inbound_htlc_fulfills = HashSet::new();
8026+
let mut historical_inbound_htlc_fulfills = new_hash_set();
80278027
#[cfg(any(test, fuzzing))]
80288028
{
80298029
let htlc_fulfills_len: u64 = Readable::read(reader)?;

0 commit comments

Comments
 (0)