Skip to content

Commit 4d29caa

Browse files
committed
refactor: Use a real struct instead of conduit_and_remote_pubkey tuple
This makes the process_act() interface a bit cleaner on a successfully completed handshake.
1 parent 6952dd7 commit 4d29caa

File tree

5 files changed

+72
-50
lines changed

5 files changed

+72
-50
lines changed

fuzz/src/peer_crypt.rs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -177,15 +177,15 @@ fn do_completed_handshake_test(generator: &mut FuzzGen) -> Result<(), GeneratorF
177177
// The handshake should complete with any valid private keys
178178
let act2 = test_ctx.responder_handshake.process_act(&test_ctx.act1).unwrap().0.unwrap();
179179
let (act3, (mut initiator_conduit, responder_pubkey)) = match test_ctx.initiator_handshake.process_act(&act2) {
180-
Ok((Some(act3), Some((conduit, remote_pubkey)))) => {
181-
(act3, (conduit, remote_pubkey))
180+
Ok((Some(act3), Some(completed_handshake_info))) => {
181+
(act3, (completed_handshake_info.conduit, completed_handshake_info.their_node_id))
182182
}
183183
_ => panic!("handshake failed")
184184
};
185185

186186
let (mut responder_conduit, initiator_pubkey) = match test_ctx.responder_handshake.process_act(&act3) {
187-
Ok((None, Some((conduit, remote_pubkey)))) => {
188-
(conduit, remote_pubkey)
187+
Ok((None, Some(completed_handshake_info))) => {
188+
(completed_handshake_info.conduit, completed_handshake_info.their_node_id)
189189
}
190190
_ => panic!("handshake failed")
191191
};
@@ -276,12 +276,12 @@ fn do_handshake_test(generator: &mut FuzzGen) -> Result<(), GeneratorFinishedErr
276276
let act2_chunks = split_vec(generator, &act2)?;
277277

278278
let mut act3_option = None;
279-
let mut conduit_and_remote_pubkey_option = None;
279+
let mut initiator_completed_handshake_info_option = None;
280280
for partial_act2 in act2_chunks {
281281
match test_ctx.initiator_handshake.process_act(&partial_act2) {
282-
Ok((Some(act3), Some(conduit_and_remote_pubkey_option_inner))) => {
282+
Ok((Some(act3), Some(completed_handshake_info_option_inner))) => {
283283
act3_option = Some(act3);
284-
conduit_and_remote_pubkey_option = Some(conduit_and_remote_pubkey_option_inner);
284+
initiator_completed_handshake_info_option = Some(completed_handshake_info_option_inner);
285285

286286
// Valid conduit and pubkey indicates handshake is over
287287
break;
@@ -299,7 +299,7 @@ fn do_handshake_test(generator: &mut FuzzGen) -> Result<(), GeneratorFinishedErr
299299

300300
// Ensure we actually received act3 bytes, conduit, and remote pubkey from process_act()
301301
let act3 = act3_option.unwrap();
302-
let (mut initiator_conduit, responder_pubkey) = conduit_and_remote_pubkey_option.unwrap();
302+
let mut initiator_completed_handshake_info = initiator_completed_handshake_info_option.unwrap();
303303

304304
// Possibly generate bad data for act3
305305
let (mut act3, is_bad_data) = maybe_generate_bad_act(generator, act3)?;
@@ -313,11 +313,11 @@ fn do_handshake_test(generator: &mut FuzzGen) -> Result<(), GeneratorFinishedErr
313313
// Split act3 into between 1..7 chunks
314314
let act3_chunks = split_vec(generator, &act3)?;
315315

316-
let mut conduit_and_remote_pubkey_option = None;
316+
let mut responder_completed_handshake_info = None;
317317
for partial_act3 in act3_chunks {
318318
match test_ctx.responder_handshake.process_act(&partial_act3) {
319-
Ok((None, Some(conduit_and_remote_pubkey_option_inner))) => {
320-
conduit_and_remote_pubkey_option = Some(conduit_and_remote_pubkey_option_inner);
319+
Ok((None, Some(completed_handshake_info_inner))) => {
320+
responder_completed_handshake_info = Some(completed_handshake_info_inner);
321321

322322
// Valid conduit and pubkey indicates handshake is over
323323
break;
@@ -333,20 +333,20 @@ fn do_handshake_test(generator: &mut FuzzGen) -> Result<(), GeneratorFinishedErr
333333
};
334334
}
335335
// Ensure we actually received conduit and remote pubkey from process_act()
336-
let (mut responder_conduit, initiator_pubkey) = conduit_and_remote_pubkey_option.unwrap();
336+
let mut responder_completed_handshake_info = responder_completed_handshake_info.unwrap();
337337

338338
// The handshake should complete with each peer knowing the static_public_key of the remote peer
339-
if initiator_pubkey != test_ctx.initiator_static_public_key {
339+
if responder_completed_handshake_info.their_node_id != test_ctx.initiator_static_public_key {
340340
assert!(used_generated_data);
341341
return Ok(());
342342
}
343-
if responder_pubkey != test_ctx.responder_static_public_key {
343+
if initiator_completed_handshake_info.their_node_id != test_ctx.responder_static_public_key {
344344
assert!(used_generated_data);
345345
return Ok(());
346346
}
347347

348348
// The nodes should be able to communicate over the conduit
349-
do_conduit_tests(generator, &mut initiator_conduit, &mut responder_conduit, used_generated_data)
349+
do_conduit_tests(generator, &mut initiator_completed_handshake_info.conduit, &mut responder_completed_handshake_info.conduit, used_generated_data)
350350
}
351351

352352
#[inline]

lightning/src/ln/peers/handshake/mod.rs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ pub struct PeerHandshake {
2727
ready_to_process: bool,
2828
}
2929

30+
/// Container for the information returned from a successfully completed handshake
31+
pub struct CompletedHandshakeInfo {
32+
pub conduit: Conduit,
33+
pub their_node_id: PublicKey,
34+
}
35+
3036
impl IPeerHandshake for PeerHandshake {
3137
/// Instantiate a handshake given the peer's static public key. The ephemeral private key MUST
3238
/// generate a new session with strong cryptographic randomness.
@@ -66,8 +72,8 @@ impl IPeerHandshake for PeerHandshake {
6672
/// # Return values
6773
/// Returns a tuple with the following components:
6874
/// `.0`: Byte vector containing the next act to send back to the peer per the handshake protocol
69-
/// `.1`: Some(Conduit, PublicKey) if the handshake was just processed to completion and messages can now be encrypted and decrypted
70-
fn process_act(&mut self, input: &[u8]) -> Result<(Option<Vec<u8>>, Option<(Conduit, PublicKey)>), String> {
75+
/// `.1`: Some(CompleteHandshakeInfo) if the handshake was just processed to completion and messages can now be encrypted and decrypted
76+
fn process_act(&mut self, input: &[u8]) -> Result<(Option<Vec<u8>>, Option<CompletedHandshakeInfo>), String> {
7177
assert!(self.ready_to_process);
7278
let cur_state = self.state.take().unwrap();
7379

@@ -77,8 +83,8 @@ impl IPeerHandshake for PeerHandshake {
7783
};
7884

7985
let result = match next_state {
80-
HandshakeState::Complete(ref mut conduit_and_pubkey) => {
81-
Ok((act_option, conduit_and_pubkey.take()))
86+
HandshakeState::Complete(ref mut complete_handshake_info) => {
87+
Ok((act_option, complete_handshake_info.take()))
8288
},
8389
_ => { Ok((act_option, None)) }
8490
};
@@ -188,14 +194,14 @@ mod test {
188194
let mut test_ctx = TestCtx::new();
189195
let act2 = do_process_act_or_panic!(test_ctx.inbound_handshake, &test_ctx.act1);
190196

191-
let (act3, inbound_remote_pubkey) = if let (Some(act3), Some((_, remote_pubkey))) = test_ctx.outbound_handshake.process_act(&act2).unwrap() {
192-
(act3, remote_pubkey)
197+
let (act3, inbound_remote_pubkey) = if let (Some(act3), Some(completed_handshake_info)) = test_ctx.outbound_handshake.process_act(&act2).unwrap() {
198+
(act3, completed_handshake_info.their_node_id)
193199
} else {
194200
panic!();
195201
};
196202

197-
let outbound_remote_pubkey = if let (None, Some((_, remote_pubkey))) = test_ctx.inbound_handshake.process_act(&act3).unwrap() {
198-
remote_pubkey
203+
let outbound_remote_pubkey = if let (None, Some(completed_handshake_info)) = test_ctx.inbound_handshake.process_act(&act3).unwrap() {
204+
completed_handshake_info.their_node_id
199205
} else {
200206
panic!();
201207
};

lightning/src/ln/peers/handshake/states.rs

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use bitcoin::secp256k1::{SecretKey, PublicKey};
77
use ln::peers::{chacha, hkdf5869rfc};
88
use ln::peers::conduit::{Conduit, SymmetricKey};
99
use ln::peers::handshake::acts::{Act, ActBuilder, ACT_ONE_LENGTH, ACT_TWO_LENGTH, ACT_THREE_LENGTH, EMPTY_ACT_ONE, EMPTY_ACT_TWO, EMPTY_ACT_THREE};
10-
use ln::peers::handshake::IHandshakeState;
10+
use ln::peers::handshake::{CompletedHandshakeInfo, IHandshakeState};
1111

1212
// Alias type to help differentiate between temporary key and chaining key when passing bytes around
1313
type ChainingKey = [u8; 32];
@@ -28,7 +28,7 @@ pub(super) enum HandshakeState {
2828
ResponderAwaitingActOne(ResponderAwaitingActOneState),
2929
InitiatorAwaitingActTwo(InitiatorAwaitingActTwoState),
3030
ResponderAwaitingActThree(ResponderAwaitingActThreeState),
31-
Complete(Option<(Conduit, PublicKey)>),
31+
Complete(Option<CompletedHandshakeInfo>),
3232
}
3333

3434
// Enum dispatch for state machine. Single public interface can statically dispatch to all states
@@ -48,7 +48,7 @@ impl IHandshakeState for HandshakeState {
4848
HandshakeState::ResponderAwaitingActOne(state) => { state.next(input) },
4949
HandshakeState::InitiatorAwaitingActTwo(state) => { state.next(input) },
5050
HandshakeState::ResponderAwaitingActThree(state) => { state.next(input) },
51-
HandshakeState::Complete(_conduit) => { panic!("no acts left to process") }
51+
HandshakeState::Complete(_completed_handshake_info) => { panic!("no acts left to process") }
5252
}
5353
}
5454
}
@@ -310,7 +310,12 @@ impl IHandshakeState for InitiatorAwaitingActTwoState {
310310
act_three[0] = 0;
311311
Ok((
312312
Some(Act::Three(act_three)),
313-
HandshakeState::Complete(Some((conduit, responder_static_public_key)))
313+
HandshakeState::Complete(Some(
314+
CompletedHandshakeInfo {
315+
conduit,
316+
their_node_id: responder_static_public_key
317+
}
318+
))
314319
))
315320
}
316321
}
@@ -390,7 +395,12 @@ impl IHandshakeState for ResponderAwaitingActThreeState {
390395

391396
Ok((
392397
None,
393-
HandshakeState::Complete(Some((conduit, initiator_pubkey)))
398+
HandshakeState::Complete(Some(
399+
CompletedHandshakeInfo {
400+
conduit,
401+
their_node_id: initiator_pubkey
402+
}
403+
))
394404
))
395405
}
396406
}
@@ -684,15 +694,15 @@ mod test {
684694
let (_act1, awaiting_act_two_state) = do_next_or_panic!(test_ctx.initiator, &[]);
685695
let (act3, complete_state) = do_next_or_panic!(awaiting_act_two_state, &test_ctx.valid_act2);
686696

687-
let (conduit, remote_pubkey) = if let Complete(Some((conduit, remote_pubkey))) = complete_state {
688-
(conduit, remote_pubkey)
697+
let completed_handshake_info = if let Complete(Some(completed_handshake_info)) = complete_state {
698+
completed_handshake_info
689699
} else {
690700
panic!();
691701
};
692702

693703
assert_eq!(act3.as_ref(), test_ctx.valid_act3.as_slice());
694-
assert_eq!(remote_pubkey, test_ctx.responder_static_public_key);
695-
assert_eq!(0, conduit.decryptor.read_buffer_length());
704+
assert_eq!(completed_handshake_info.their_node_id, test_ctx.responder_static_public_key);
705+
assert_eq!(0, completed_handshake_info.conduit.decryptor.read_buffer_length());
696706
}
697707

698708
// Initiator::AwaitingActTwo -> Complete (segmented calls)
@@ -751,14 +761,14 @@ mod test {
751761
let test_ctx = TestCtx::new();
752762
let (_act2, awaiting_act_three_state) = do_next_or_panic!(test_ctx.responder, &test_ctx.valid_act1);
753763

754-
let (conduit, remote_pubkey) = if let (None, Complete(Some((conduit, remote_pubkey)))) = awaiting_act_three_state.next(&test_ctx.valid_act3).unwrap() {
755-
(conduit, remote_pubkey)
764+
let completed_handshake_info = if let (None, Complete(Some(completed_handshake_info))) = awaiting_act_three_state.next(&test_ctx.valid_act3).unwrap() {
765+
completed_handshake_info
756766
} else {
757767
panic!();
758768
};
759769

760-
assert_eq!(remote_pubkey, test_ctx.initiator_public_key);
761-
assert_eq!(0, conduit.decryptor.read_buffer_length());
770+
assert_eq!(completed_handshake_info.their_node_id, test_ctx.initiator_public_key);
771+
assert_eq!(0, completed_handshake_info.conduit.decryptor.read_buffer_length());
762772
}
763773

764774
// Responder::AwaitingActThree -> None (with extra bytes)
@@ -771,14 +781,14 @@ mod test {
771781
let mut act3 = test_ctx.valid_act3;
772782
act3.extend_from_slice(&[2; 16]);
773783

774-
let (conduit, remote_pubkey) = if let (None, Complete(Some((conduit, remote_pubkey)))) = awaiting_act_three_state.next(&act3).unwrap() {
775-
(conduit, remote_pubkey)
784+
let completed_handshake_info = if let (None, Complete(Some(completed_handshake_info))) = awaiting_act_three_state.next(&act3).unwrap() {
785+
completed_handshake_info
776786
} else {
777787
panic!();
778788
};
779789

780-
assert_eq!(remote_pubkey, test_ctx.initiator_public_key);
781-
assert_eq!(16, conduit.decryptor.read_buffer_length());
790+
assert_eq!(completed_handshake_info.their_node_id, test_ctx.initiator_public_key);
791+
assert_eq!(16, completed_handshake_info.conduit.decryptor.read_buffer_length());
782792
}
783793

784794
// Responder::AwaitingActThree -> Error (bad version bytes)

lightning/src/ln/peers/test_util.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use bitcoin::secp256k1::key::{PublicKey, SecretKey};
55

66
use ln::peers::conduit::Conduit;
77
use ln::peers::handler::{SocketDescriptor, ITransport, PeerHandleError, MessageQueuer};
8+
use ln::peers::handshake::CompletedHandshakeInfo;
89
use ln::peers::transport::{IPeerHandshake, PayloadQueuer};
910

1011
use std::rc::Rc;
@@ -42,7 +43,7 @@ impl IPeerHandshake for PeerHandshakeTestStubFail {
4243
PeerHandshakeTestStubFail { }
4344
}
4445

45-
fn process_act(&mut self, _input: &[u8]) -> Result<(Option<Vec<u8>>, Option<(Conduit, PublicKey)>), String> {
46+
fn process_act(&mut self, _input: &[u8]) -> Result<(Option<Vec<u8>>, Option<CompletedHandshakeInfo>), String> {
4647
Err("Oh no!".to_string())
4748
}
4849
}
@@ -68,7 +69,7 @@ impl IPeerHandshake for PeerHandshakeTestStubBytes {
6869
PeerHandshakeTestStubBytes { }
6970
}
7071

71-
fn process_act(&mut self, _input: &[u8]) -> Result<(Option<Vec<u8>>, Option<(Conduit, PublicKey)>), String> {
72+
fn process_act(&mut self, _input: &[u8]) -> Result<(Option<Vec<u8>>, Option<CompletedHandshakeInfo>), String> {
7273
Ok((Some(Self::RETURNED_BYTES[..].to_vec()), None))
7374
}
7475
}
@@ -89,13 +90,18 @@ impl IPeerHandshake for PeerHandshakeTestStubComplete {
8990
PeerHandshakeTestStubComplete { }
9091
}
9192

92-
fn process_act(&mut self, _input: &[u8]) -> Result<(Option<Vec<u8>>, Option<(Conduit, PublicKey)>), String> {
93+
fn process_act(&mut self, _input: &[u8]) -> Result<(Option<Vec<u8>>, Option<CompletedHandshakeInfo>), String> {
9394
let curve = secp256k1::Secp256k1::new();
9495
let private_key = SecretKey::from_slice(&[0x_21_u8; 32]).unwrap();
9596
let public_key = PublicKey::from_secret_key(&curve, &private_key);
9697
let conduit = Conduit::new([0;32], [0;32], [0;32]);
9798

98-
Ok((None, Some((conduit, public_key))))
99+
Ok((None, Some(
100+
CompletedHandshakeInfo {
101+
conduit,
102+
their_node_id: public_key
103+
}
104+
)))
99105
}
100106
}
101107

lightning/src/ln/peers/transport.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use bitcoin::secp256k1::{SecretKey, PublicKey};
44

55
use ln::peers::conduit::Conduit;
66
use ln::peers::handler::{ITransport, PeerHandleError, MessageQueuer};
7-
use ln::peers::handshake::PeerHandshake;
7+
use ln::peers::handshake::{CompletedHandshakeInfo, PeerHandshake};
88
use ln::{wire, msgs};
99
use ln::wire::{Encode, Message};
1010

@@ -25,7 +25,7 @@ pub trait IPeerHandshake {
2525

2626
/// Progress the handshake given bytes received from the peer. Returns Some(Conduit, PublicKey) when the handshake
2727
/// is complete.
28-
fn process_act(&mut self, input: &[u8]) -> Result<(Option<Vec<u8>>, Option<(Conduit, PublicKey)>), String>;
28+
fn process_act(&mut self, input: &[u8]) -> Result<(Option<Vec<u8>>, Option<CompletedHandshakeInfo>), String>;
2929
}
3030

3131
/// Trait representing a container that allows enqueuing of Vec<[u8]>. Used by Transport to enqueue
@@ -74,17 +74,17 @@ impl<PeerHandshakeImpl: IPeerHandshake> ITransport for Transport<PeerHandshakeIm
7474
match self.conduit {
7575
// Continue handshake
7676
None => {
77-
let (response_option, conduit_and_remote_pubkey_option) = self.handshake.process_act(input)?;
77+
let (response_option, completed_handshake_info_option) = self.handshake.process_act(input)?;
7878

7979
// Any response generated by the handshake sequence is put into the response buffer
8080
if let Some(response) = response_option {
8181
output_buffer.push_back(response.to_vec());
8282
}
8383

8484
// If handshake is complete change the state
85-
if let Some((conduit, remote_pubkey)) = conduit_and_remote_pubkey_option {
86-
self.conduit = Some(conduit);
87-
self.their_node_id = Some(remote_pubkey);
85+
if let Some(completed_handshake_info) = completed_handshake_info_option {
86+
self.conduit = Some(completed_handshake_info.conduit);
87+
self.their_node_id = Some(completed_handshake_info.their_node_id);
8888
Ok(true) // newly connected
8989
} else {
9090
Ok(false) // newly connected

0 commit comments

Comments
 (0)