Skip to content

Commit 4eb70fd

Browse files
committed
Use HashMaps as, well, HashMaps (don't iter for key match)
1 parent ac9a2c8 commit 4eb70fd

File tree

1 file changed

+41
-53
lines changed

1 file changed

+41
-53
lines changed

lightning/src/ln/interactivetxs.rs

Lines changed: 41 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,6 @@ struct NegotiationContext {
9090
outputs: HashMap<SerialId, TxOut>,
9191
tx_locktime: AbsoluteLockTime,
9292
feerate_sat_per_kw: u32,
93-
to_remote_value_satoshis: u64,
9493
}
9594

9695
impl NegotiationContext {
@@ -177,23 +176,27 @@ impl NegotiationContext {
177176
} else {
178177
return Err(AbortReason::PrevTxOutInvalid);
179178
};
180-
if self.inputs.iter().any(|(serial_id, _)| *serial_id == msg.serial_id) {
181-
// The receiving node:
182-
// - MUST fail the negotiation if:
183-
// - the `serial_id` is already included in the transaction
184-
return Err(AbortReason::DuplicateSerialId);
185-
}
186-
let prev_outpoint = OutPoint { txid, vout: msg.prevtx_out };
187-
self.inputs.entry(msg.serial_id).or_insert_with(|| TxInputWithPrevOutput {
188-
input: TxIn {
189-
previous_output: prev_outpoint.clone(),
190-
sequence: Sequence(msg.sequence),
191-
..Default::default()
179+
match self.inputs.entry(msg.serial_id) {
180+
hash_map::Entry::Occupied(_) => {
181+
// The receiving node:
182+
// - MUST fail the negotiation if:
183+
// - the `serial_id` is already included in the transaction
184+
Err(AbortReason::DuplicateSerialId)
192185
},
193-
prev_output: prev_out,
194-
});
195-
self.prevtx_outpoints.insert(prev_outpoint);
196-
Ok(())
186+
hash_map::Entry::Vacant(entry) => {
187+
let prev_outpoint = OutPoint { txid, vout: msg.prevtx_out };
188+
entry.insert(TxInputWithPrevOutput {
189+
input: TxIn {
190+
previous_output: prev_outpoint,
191+
sequence: Sequence(msg.sequence),
192+
..Default::default()
193+
},
194+
prev_output: prev_out,
195+
});
196+
self.prevtx_outpoints.insert(prev_outpoint);
197+
Ok(())
198+
},
199+
}
197200
}
198201

199202
fn received_tx_remove_input(&mut self, msg: &msgs::TxRemoveInput) -> Result<(), AbortReason> {
@@ -263,23 +266,25 @@ impl NegotiationContext {
263266
return Err(AbortReason::InvalidOutputScript);
264267
}
265268

266-
if self.outputs.iter().any(|(serial_id, _)| *serial_id == msg.serial_id) {
267-
// The receiving node:
268-
// - MUST fail the negotiation if:
269-
// - the `serial_id` is already included in the transaction
270-
return Err(AbortReason::DuplicateSerialId);
269+
match self.outputs.entry(msg.serial_id) {
270+
hash_map::Entry::Occupied(_) => {
271+
// The receiving node:
272+
// - MUST fail the negotiation if:
273+
// - the `serial_id` is already included in the transaction
274+
Err(AbortReason::DuplicateSerialId)
275+
},
276+
hash_map::Entry::Vacant(entry) => {
277+
entry.insert(TxOut { value: msg.sats, script_pubkey: msg.script.clone() });
278+
Ok(())
279+
},
271280
}
272-
273-
let output = TxOut { value: msg.sats, script_pubkey: msg.script.clone() };
274-
self.outputs.entry(msg.serial_id).or_insert(output);
275-
Ok(())
276281
}
277282

278283
fn received_tx_remove_output(&mut self, msg: &msgs::TxRemoveOutput) -> Result<(), AbortReason> {
279284
if !self.is_serial_id_valid_for_counterparty(&msg.serial_id) {
280285
return Err(AbortReason::IncorrectSerialIdParity);
281286
}
282-
if let Some(_) = self.outputs.remove(&msg.serial_id) {
287+
if self.outputs.remove(&msg.serial_id).is_some() {
283288
Ok(())
284289
} else {
285290
// The receiving node:
@@ -299,7 +304,7 @@ impl NegotiationContext {
299304
};
300305
debug_assert!((msg.prevtx_out as usize) < tx.output.len());
301306
let prev_output = &tx.output[msg.prevtx_out as usize];
302-
self.prevtx_outpoints.insert(input.previous_output.clone());
307+
self.prevtx_outpoints.insert(input.previous_output);
303308
self.inputs.insert(
304309
msg.serial_id,
305310
TxInputWithPrevOutput { input, prev_output: prev_output.clone() },
@@ -333,11 +338,7 @@ impl NegotiationContext {
333338
for output in self.counterparty_outputs_contributed() {
334339
counterparty_outputs_value = counterparty_outputs_value.saturating_add(output.value);
335340
}
336-
// ...actually the counterparty might be splicing out, so that their balance also contributes
337-
// to the total input value.
338-
if counterparty_inputs_value.saturating_add(self.to_remote_value_satoshis)
339-
< counterparty_outputs_value
340-
{
341+
if counterparty_inputs_value < counterparty_outputs_value {
341342
return Err(AbortReason::OutputsValueExceedsInputsValue);
342343
}
343344

@@ -596,10 +597,7 @@ macro_rules! define_state_machine_transitions {
596597
}
597598

598599
impl StateMachine {
599-
fn new(
600-
feerate_sat_per_kw: u32, is_initiator: bool, tx_locktime: AbsoluteLockTime,
601-
to_remote_value_satoshis: u64,
602-
) -> Self {
600+
fn new(feerate_sat_per_kw: u32, is_initiator: bool, tx_locktime: AbsoluteLockTime) -> Self {
603601
let context = NegotiationContext {
604602
tx_locktime,
605603
holder_is_initiator: is_initiator,
@@ -609,7 +607,6 @@ impl StateMachine {
609607
prevtx_outpoints: new_hash_set(),
610608
outputs: new_hash_map(),
611609
feerate_sat_per_kw,
612-
to_remote_value_satoshis,
613610
};
614611
if is_initiator {
615612
Self::ReceivedChangeMsg(ReceivedChangeMsg(context))
@@ -717,26 +714,19 @@ pub enum HandleTxCompleteValue {
717714
impl InteractiveTxConstructor {
718715
/// Instantiates a new `InteractiveTxConstructor`.
719716
///
720-
/// If this is for a dual_funded channel then the `to_remote_value_satoshis` parameter should be set
721-
/// to zero.
722-
///
723717
/// A tuple is returned containing the newly instantiate `InteractiveTxConstructor` and optionally
724718
/// an initial wrapped `Tx_` message which the holder needs to send to the counterparty.
725719
pub fn new<ES: Deref>(
726720
entropy_source: &ES, channel_id: ChannelId, feerate_sat_per_kw: u32, is_initiator: bool,
727721
funding_tx_locktime: AbsoluteLockTime,
728722
inputs_to_contribute: Vec<(TxIn, TransactionU16LenLimited)>,
729-
outputs_to_contribute: Vec<TxOut>, to_remote_value_satoshis: u64,
723+
outputs_to_contribute: Vec<TxOut>,
730724
) -> (Self, Option<InteractiveTxMessageSend>)
731725
where
732726
ES::Target: EntropySource,
733727
{
734-
let state_machine = StateMachine::new(
735-
feerate_sat_per_kw,
736-
is_initiator,
737-
funding_tx_locktime,
738-
to_remote_value_satoshis,
739-
);
728+
let state_machine =
729+
StateMachine::new(feerate_sat_per_kw, is_initiator, funding_tx_locktime);
740730
let mut inputs_to_contribute: Vec<(SerialId, TxIn, TransactionU16LenLimited)> =
741731
inputs_to_contribute
742732
.into_iter()
@@ -841,7 +831,7 @@ impl InteractiveTxConstructor {
841831
match &self.state_machine {
842832
StateMachine::ReceivedTxComplete(_) => {
843833
let msg_send = self.maybe_send_message()?;
844-
return match &self.state_machine {
834+
match &self.state_machine {
845835
StateMachine::NegotiationComplete(s) => {
846836
Ok(HandleTxCompleteValue::SendTxComplete(msg_send, s.0.clone()))
847837
},
@@ -850,9 +840,9 @@ impl InteractiveTxConstructor {
850840
}, // We either had an input or output to contribute.
851841
_ => {
852842
debug_assert!(false, "We cannot transition to any other states after receiving `tx_complete` and responding");
853-
return Err(AbortReason::InvalidStateTransition);
843+
Err(AbortReason::InvalidStateTransition)
854844
},
855-
};
845+
}
856846
},
857847
StateMachine::NegotiationComplete(s) => {
858848
Ok(HandleTxCompleteValue::NegotiationComplete(s.0.clone()))
@@ -965,7 +955,6 @@ mod tests {
965955
tx_locktime,
966956
session.inputs_a,
967957
session.outputs_a,
968-
0,
969958
);
970959
let (mut constructor_b, first_message_b) = InteractiveTxConstructor::new(
971960
entropy_source,
@@ -975,7 +964,6 @@ mod tests {
975964
tx_locktime,
976965
session.inputs_b,
977966
session.outputs_b,
978-
0,
979967
);
980968

981969
let handle_message_send =

0 commit comments

Comments
 (0)