bip324 0.10.0

Encrypted transport for the bitcoin P2P protocol as specified by BIP 324
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
// SPDX-License-Identifier: CC0-1.0

//! High-level synchronous interfaces for establishing
//! BIP-324 encrypted connections over Read/Write IO transports.
//! For asynchronous support, see the `futures` module.
//!
//! # Performance Note
//!
//! The BIP-324 protocol performs many small reads (3-byte length prefixes,
//! 16-byte terminators, etc.). For optimal performance, wrap your reader
//! in a [`std::io::BufReader`].
//!
//! # Example
//!
//! ```no_run
//! use std::net::TcpStream;
//! use std::io::BufReader;
//! use bip324::io::{Protocol, Payload};
//! use bip324::{Network, Role};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Connect to a Bitcoin node
//! let stream = TcpStream::connect("127.0.0.1:8333")?;
//!
//! // Split the stream for reading and writing
//! let reader = BufReader::new(stream.try_clone()?);
//! let writer = stream;
//!
//! // Establish BIP-324 encrypted connection
//! let mut protocol = Protocol::new(
//!     Network::Bitcoin,
//!     Role::Initiator,
//!     None,  // no garbage bytes
//!     None,  // no decoy packets
//!     reader,
//!     writer,
//! )?;
//!
//! // Send and receive encrypted messages
//! protocol.write(&Payload::genuine(b"Hello, world!"))?;
//! let response = protocol.read()?;
//! println!("Received {} bytes", response.contents().len());
//! # Ok(())
//! # }
//! ```

use core::fmt;
use std::io::{Chain, Cursor, Read, Write};
use std::vec;
use std::vec::Vec;

use bitcoin::Network;

use crate::{
    handshake::{self, GarbageResult, VersionResult},
    Error, Handshake, InboundCipher, OutboundCipher, PacketType, Role,
    MAX_PACKET_SIZE_FOR_ALLOCATION, NUM_ELLIGATOR_SWIFT_BYTES, NUM_GARBAGE_TERMINTOR_BYTES,
    NUM_LENGTH_BYTES,
};

/// A reader that chains unconsumed handshake data with the underlying stream.
///
/// This type is returned from the handshake process and ensures that any
/// unread bytes from the handshake (such as partial packets in the garbage buffer)
/// are read before data from the underlying stream.
pub struct ProtocolSessionReader<R> {
    inner: Chain<Cursor<Vec<u8>>, R>,
}

impl<R> ProtocolSessionReader<R> {
    /// Create a new session reader from leftover handshake bytes and the underlying reader.
    fn new(leftover: Vec<u8>, reader: R) -> Self
    where
        R: Read,
    {
        Self {
            inner: Cursor::new(leftover).chain(reader),
        }
    }
}

impl<R: Read> Read for ProtocolSessionReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.inner.read(buf)
    }
}

/// A decrypted payload including its header byte.
#[derive(Clone)]
pub struct Payload {
    data: PayloadData,
}

/// Avoid any O(n) re-allocations and  byte copying
/// on the read and write paths by storing the data in its current form.
#[derive(Clone)]
enum PayloadData {
    /// Data from decryption [header_byte, ...contents].
    Decrypted(Vec<u8>),
    /// Data for writing, header + contents stored separately.
    Parts { header: u8, contents: Vec<u8> },
}

impl Payload {
    /// Create a genuine message payload for writing.
    ///
    /// # Arguments
    ///
    /// * `contents` - The message contents to be sent (without header byte).
    pub fn genuine(contents: impl Into<Vec<u8>>) -> Self {
        Self {
            data: PayloadData::Parts {
                header: PacketType::Genuine.to_byte(),
                contents: contents.into(),
            },
        }
    }

    /// Create a decoy payload for writing.
    ///
    /// # Arguments
    ///
    /// * `contents` - The decoy data to be sent (without header byte).
    pub fn decoy(contents: impl Into<Vec<u8>>) -> Self {
        Self {
            data: PayloadData::Parts {
                header: PacketType::Decoy.to_byte(),
                contents: contents.into(),
            },
        }
    }

    /// Create from decrypted data (header + contents).
    ///
    /// # Invariants
    ///
    /// The internal data vector must always contain at least one byte (the header byte).
    /// This invariant is maintained by the decrypt functions which validate that
    /// ciphertext contains at least `NUM_TAG_BYTES + NUM_HEADER_BYTES` before
    /// attempting decryption.
    pub(crate) fn decrypted(data: Vec<u8>) -> Self {
        debug_assert!(
            !data.is_empty(),
            "Payload data must contain at least the header byte"
        );
        Self {
            data: PayloadData::Decrypted(data),
        }
    }

    /// Get the contents (everything after header byte).
    pub fn contents(&self) -> &[u8] {
        match &self.data {
            PayloadData::Decrypted(data) => &data[1..],
            PayloadData::Parts { contents, .. } => contents,
        }
    }

    /// Get the packet type from header byte.
    pub fn packet_type(&self) -> PacketType {
        match &self.data {
            PayloadData::Decrypted(data) => PacketType::from_byte(&data[0]),
            PayloadData::Parts { header, .. } => PacketType::from_byte(header),
        }
    }
}

/// High level error type for the protocol interface.
#[derive(Debug)]
pub enum ProtocolError {
    /// Wrap all IO errors with suggestion for next step on failure.
    Io(std::io::Error, ProtocolFailureSuggestion),
    /// Internal protocol specific errors.
    Internal(Error),
}

/// Suggest to caller next step on protocol failure.
#[derive(Debug)]
pub enum ProtocolFailureSuggestion {
    /// Caller could attempt to retry the connection with protocol V1 if desired.
    RetryV1,
    /// Caller should not attempt to retry connection.
    Abort,
}

impl From<std::io::Error> for ProtocolError {
    fn from(error: std::io::Error) -> Self {
        // Detect IO errors which possibly mean the remote doesn't understand
        // the V2 protocol and immediately closed the connection.
        let suggestion = match error.kind() {
            // The remote force closed the connection.
            std::io::ErrorKind::ConnectionReset
            // A more general error than ConnectionReset, but could be caused
            // by the remote closing the connection.
            | std::io::ErrorKind::ConnectionAborted
            // End of file read errors can occur if the remote closes the connection,
            // but the local system reads due to timing issues.
            | std::io::ErrorKind::UnexpectedEof => ProtocolFailureSuggestion::RetryV1,
            _ => ProtocolFailureSuggestion::Abort,
        };

        ProtocolError::Io(error, suggestion)
    }
}

impl From<Error> for ProtocolError {
    fn from(error: Error) -> Self {
        ProtocolError::Internal(error)
    }
}

impl ProtocolError {
    /// Create an EOF error that suggests retrying with V1 protocol.
    ///
    /// This is used when the remote peer closes the connection during handshake,
    /// which often indicates they don't support the V2 protocol.
    pub fn eof() -> Self {
        ProtocolError::Io(
            std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "Remote peer closed connection during handshake",
            ),
            ProtocolFailureSuggestion::RetryV1,
        )
    }
}

impl std::error::Error for ProtocolError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ProtocolError::Io(e, _) => Some(e),
            ProtocolError::Internal(e) => Some(e),
        }
    }
}

impl fmt::Display for ProtocolError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProtocolError::Io(e, suggestion) => {
                write!(
                    f,
                    "IO error: {}. Suggestion: {}.",
                    e,
                    match suggestion {
                        ProtocolFailureSuggestion::RetryV1 => "Retry with V1 protocol",
                        ProtocolFailureSuggestion::Abort => "Abort, do not retry",
                    }
                )
            }
            ProtocolError::Internal(e) => write!(f, "Internal error: {e}."),
        }
    }
}

/// Perform a BIP-324 handshake and return ready-to-use session components.
///
/// # Arguments
///
/// * `network` - Network which both parties are operating on.
/// * `role` - Role in handshake, initiator or responder.
/// * `garbage` - Optional garbage bytes to send in handshake.
/// * `decoys` - Optional decoy packet contents to send in handshake.
/// * `reader` - Buffer to read packets sent by peer (takes ownership).
/// * `writer` - Buffer to write packets to peer (takes mutable reference).
///
/// # Reader Transformation
///
/// The I/O reader is transformed in order to handle possible over-read
/// scenarios while attempting to detect the remote's garbage terminator.
///
/// # Returns
///
/// A `Result` containing:
///   * `Ok((InboundCipher, OutboundCipher, ProtocolSessionReader<R>))`: Ready-to-use session components.
///   * `Err(ProtocolError)`: An error that occurred during the handshake.
///
/// # Errors
///
/// * `Io` - Includes a flag for if the remote probably only understands the V1 protocol.
pub fn handshake<R, W>(
    network: Network,
    role: Role,
    garbage: Option<Vec<u8>>,
    decoys: Option<Vec<Vec<u8>>>,
    reader: R,
    writer: &mut W,
) -> Result<(InboundCipher, OutboundCipher, ProtocolSessionReader<R>), ProtocolError>
where
    R: Read,
    W: Write,
{
    let handshake = Handshake::<handshake::Initialized>::new(network, role)?;
    handshake_with_initialized(handshake, garbage, decoys, reader, writer)
}

/// Perform a BIP-324 handshake and return ready-to-use session components.
///
/// # Arguments
///
/// * `handshake` - Initialized handshake including its role and rng.
/// * `garbage` - Optional garbage bytes to send in handshake.
/// * `decoys` - Optional decoy packet contents to send in handshake.
/// * `reader` - Buffer to read packets sent by peer (takes ownership).
/// * `writer` - Buffer to write packets to peer (takes mutable reference).
///
/// # Reader Transformation
///
/// The I/O reader is transformed in order to handle possible over-read
/// scenarios while attempting to detect the remote's garbage terminator.
///
/// # Returns
///
/// A `Result` containing:
///   * `Ok((InboundCipher, OutboundCipher, ProtocolSessionReader<R>))`: Ready-to-use session components.
///   * `Err(ProtocolError)`: An error that occurred during the handshake.
///
/// # Errors
///
/// * `Io` - Includes a flag for if the remote probably only understands the V1 protocol.
fn handshake_with_initialized<R, W>(
    handshake: Handshake<handshake::Initialized>,
    garbage: Option<Vec<u8>>,
    decoys: Option<Vec<Vec<u8>>>,
    mut reader: R,
    writer: &mut W,
) -> Result<(InboundCipher, OutboundCipher, ProtocolSessionReader<R>), ProtocolError>
where
    R: Read,
    W: Write,
{
    // Convert to references for the lower-level handshake methods.
    let garbage_ref = garbage.as_deref();
    // Convert Vec<Vec<u8>> to &[&[u8]] if present. Need the intermediate Vec<&[u8]> value
    // to ensure the vector of references lives through the function.
    let decoy_refs: Option<Vec<&[u8]>> = decoys
        .as_ref()
        .map(|vecs| vecs.iter().map(Vec::as_slice).collect());
    let decoys_ref = decoy_refs.as_deref();

    // Send local public key and optional garbage.
    let key_buffer_len = Handshake::<handshake::Initialized>::send_key_len(garbage_ref);
    let mut key_buffer = vec![0u8; key_buffer_len];
    let handshake = handshake.send_key(garbage_ref, &mut key_buffer)?;
    writer.write_all(&key_buffer)?;
    writer.flush()?;

    // Read remote's public key.
    let mut remote_ellswift_buffer = [0u8; NUM_ELLIGATOR_SWIFT_BYTES];
    reader.read_exact(&mut remote_ellswift_buffer)?;
    let handshake = handshake.receive_key(remote_ellswift_buffer)?;

    // Send garbage terminator, decoys, and version.
    let version_buffer_len = Handshake::<handshake::ReceivedKey>::send_version_len(decoys_ref);
    let mut version_buffer = vec![0u8; version_buffer_len];
    let handshake = handshake.send_version(&mut version_buffer, decoys_ref)?;
    writer.write_all(&version_buffer)?;
    writer.flush()?;

    // Receive and process garbage terminator
    let mut garbage_buffer = vec![0u8; NUM_GARBAGE_TERMINTOR_BYTES];
    reader.read_exact(&mut garbage_buffer)?;

    let mut handshake = handshake;
    let (mut handshake, garbage_bytes) = loop {
        match handshake.receive_garbage(&garbage_buffer) {
            Ok(GarbageResult::FoundGarbage {
                handshake,
                consumed_bytes,
            }) => {
                break (handshake, consumed_bytes);
            }
            Ok(GarbageResult::NeedMoreData(h)) => {
                handshake = h;
                // The 256 bytes is a bit arbitrary. There is a max of 4095, but not sure
                // all of that should be allocated right away.
                let mut temp = vec![0u8; 256];
                match reader.read(&mut temp) {
                    Ok(0) => return Err(ProtocolError::eof()),
                    Ok(n) => {
                        garbage_buffer.extend_from_slice(&temp[..n]);
                    }
                    Err(e) => return Err(ProtocolError::from(e)),
                }
            }
            Err(e) => return Err(ProtocolError::Internal(e)),
        }
    };

    // Process remaining bytes for decoy packets and version.
    let leftover_bytes = garbage_buffer[garbage_bytes..].to_vec();
    let mut session_reader = ProtocolSessionReader::new(leftover_bytes, reader);
    let mut length_bytes = [0u8; NUM_LENGTH_BYTES];
    loop {
        // Decrypt packet length.
        session_reader.read_exact(&mut length_bytes)?;
        let packet_len = handshake.decrypt_packet_len(length_bytes)?;
        if packet_len > MAX_PACKET_SIZE_FOR_ALLOCATION {
            return Err(ProtocolError::Internal(Error::PacketTooBig));
        }

        // Process packet.
        let mut packet_bytes = vec![0u8; packet_len];
        session_reader.read_exact(&mut packet_bytes)?;
        match handshake.receive_version(&mut packet_bytes) {
            Ok(VersionResult::Complete { cipher }) => {
                let (inbound_cipher, outbound_cipher) = cipher.into_split();
                return Ok((inbound_cipher, outbound_cipher, session_reader));
            }
            Ok(VersionResult::Decoy(h)) => {
                handshake = h;
            }
            Err(e) => return Err(ProtocolError::Internal(e)),
        }
    }
}

/// A synchronous protocol session with handshake and send/receive packet management.
pub struct Protocol<R, W> {
    reader: ProtocolReader<R>,
    writer: ProtocolWriter<W>,
}

impl<R, W> Protocol<R, W>
where
    R: Read,
    W: Write,
{
    /// New protocol session which completes the initial handshake and returns a handler.
    ///
    /// # Performance Note
    ///
    /// For optimal performance, wrap your `reader` in a [`std::io::BufReader`].
    /// The protocol makes many small reads during handshake and operation.
    ///
    /// # Arguments
    ///
    /// * `network` - Network which both parties are operating on.
    /// * `role` - Role in handshake, initiator or responder.
    /// * `garbage` - Optional garbage bytes to send in handshake.
    /// * `decoys` - Optional decoy packet contents to send in handshake.
    /// * `reader` - Buffer to read packets sent by peer (takes ownership).
    /// * `writer` - Buffer to write packets to peer (takes ownership).
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    ///   * `Ok(Protocol)`: An initialized protocol handler.
    ///   * `Err(ProtocolError)`: An error that occurred during the handshake.
    ///
    /// # Errors
    ///
    /// * `Io` - Includes a flag for if the remote probably only understands the V1 protocol.
    pub fn new(
        network: Network,
        role: Role,
        garbage: Option<Vec<u8>>,
        decoys: Option<Vec<Vec<u8>>>,
        reader: R,
        mut writer: W,
    ) -> Result<Protocol<R, W>, ProtocolError> {
        let (inbound_cipher, outbound_cipher, session_reader) =
            handshake(network, role, garbage, decoys, reader, &mut writer)?;

        Ok(Protocol {
            reader: ProtocolReader {
                inbound_cipher,
                reader: session_reader,
            },
            writer: ProtocolWriter {
                outbound_cipher,
                writer,
            },
        })
    }

    /// Split the protocol into a separate reader and writer.
    pub fn into_split(self) -> (ProtocolReader<R>, ProtocolWriter<W>) {
        (self.reader, self.writer)
    }

    /// Read and decrypt a packet from the underlying reader.
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    ///   * `Ok(Payload)`: A decrypted payload with packet type.
    ///   * `Err(ProtocolError)`: An error that occurred during the read or decryption.
    pub fn read(&mut self) -> Result<Payload, ProtocolError> {
        self.reader.read()
    }

    /// Encrypt and write a packet to the underlying writer.
    ///
    /// # Arguments
    ///
    /// * `payload` - The payload to encrypt and send.
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    ///   * `Ok()`: On successful payload encryption and packet send.
    ///   * `Err(ProtocolError)`: An error that occurred during the encryption or write.
    pub fn write(&mut self, payload: &Payload) -> Result<(), ProtocolError> {
        self.writer.write(payload)
    }
}

/// Manages a buffer to automatically decrypt contents of received packets.
pub struct ProtocolReader<R> {
    inbound_cipher: InboundCipher,
    reader: ProtocolSessionReader<R>,
}

impl<R> ProtocolReader<R>
where
    R: Read,
{
    /// Decrypt contents of received packet from the internal reader.
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    ///   * `Ok(Payload)`: A decrypted payload with packet type.
    ///   * `Err(ProtocolError)`: An error that occurred during the read or decryption.
    pub fn read(&mut self) -> Result<Payload, ProtocolError> {
        // Read packet length.
        let mut length_bytes = [0u8; NUM_LENGTH_BYTES];
        self.reader.read_exact(&mut length_bytes)?;
        let packet_bytes_len = self.inbound_cipher.decrypt_packet_len(length_bytes);

        // Read packet data.
        let mut packet_bytes = vec![0u8; packet_bytes_len];
        self.reader.read_exact(&mut packet_bytes)?;
        let (_, plaintext_buffer) = self.inbound_cipher.decrypt_to_vec(&packet_bytes, None)?;

        Ok(Payload::decrypted(plaintext_buffer))
    }

    /// Consume the protocol reader in exchange for the underlying reader and cipher.
    pub fn into_inner(self) -> (InboundCipher, ProtocolSessionReader<R>) {
        (self.inbound_cipher, self.reader)
    }
}

/// Manages a buffer to automatically encrypt and send contents in packets.
pub struct ProtocolWriter<W> {
    outbound_cipher: OutboundCipher,
    writer: W,
}

impl<W> ProtocolWriter<W>
where
    W: Write,
{
    /// Encrypt payload and write packet to the internal writer.
    ///
    /// # Arguments
    ///
    /// * `payload` - The payload to encrypt and send.
    ///
    /// # Returns
    ///
    /// A `Result` containing:
    ///   * `Ok()`: On successful payload encryption and packet send.
    ///   * `Err(ProtocolError)`: An error that occurred during the encryption or write.
    pub fn write(&mut self, payload: &Payload) -> Result<(), ProtocolError> {
        let packet_buffer =
            self.outbound_cipher
                .encrypt_to_vec(payload.contents(), payload.packet_type(), None);
        self.writer.write_all(&packet_buffer)?;
        self.writer.flush()?;
        Ok(())
    }

    /// Consume the protocol writer in exchange for the underlying writer and cipher.
    pub fn into_inner(self) -> (OutboundCipher, W) {
        (self.outbound_cipher, self.writer)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::{rngs::StdRng, SeedableRng};
    use std::io::Cursor;

    /// Generate deterministic handshake messages for testing.
    /// Returns the complete handshake message (key + garbage + version) for the specified role.
    fn generate_handshake_messages(
        local_seed: u64,
        remote_seed: u64,
        local_role: Role,
        garbage: Option<&[u8]>,
        decoys: Option<&[&[u8]]>,
    ) -> Vec<u8> {
        let secp = bitcoin::secp256k1::Secp256k1::new();

        // Create both parties.
        let mut local_rng = StdRng::seed_from_u64(local_seed);
        let local_handshake = Handshake::<handshake::Initialized>::new_with_rng(
            Network::Bitcoin,
            local_role,
            &mut local_rng,
            &secp,
        )
        .unwrap();

        let mut remote_rng = StdRng::seed_from_u64(remote_seed);
        let remote_role = match local_role {
            Role::Initiator => Role::Responder,
            Role::Responder => Role::Initiator,
        };
        let remote_handshake = Handshake::<handshake::Initialized>::new_with_rng(
            Network::Bitcoin,
            remote_role,
            &mut remote_rng,
            &secp,
        )
        .unwrap();

        // Exchange keys.
        let mut local_key_buffer =
            vec![0u8; Handshake::<handshake::Initialized>::send_key_len(garbage)];
        let local_handshake = local_handshake
            .send_key(garbage, &mut local_key_buffer)
            .unwrap();

        let mut remote_key_buffer = vec![0u8; NUM_ELLIGATOR_SWIFT_BYTES];
        remote_handshake
            .send_key(None, &mut remote_key_buffer)
            .unwrap();

        let local_handshake = local_handshake
            .receive_key(
                remote_key_buffer[..NUM_ELLIGATOR_SWIFT_BYTES]
                    .try_into()
                    .unwrap(),
            )
            .unwrap();

        let mut local_version_buffer =
            vec![0u8; Handshake::<handshake::ReceivedKey>::send_version_len(decoys)];
        local_handshake
            .send_version(&mut local_version_buffer, decoys)
            .unwrap();

        // Return complete message: key + garbage + version.
        let garbage_bytes = garbage.map(|g| g.to_vec()).unwrap_or_default();
        [
            &local_key_buffer[..NUM_ELLIGATOR_SWIFT_BYTES],
            &garbage_bytes[..],
            &local_version_buffer[..],
        ]
        .concat()
    }

    #[test]
    fn test_handshake_session_reader() {
        let mut init_rng = StdRng::seed_from_u64(42);
        let secp = bitcoin::secp256k1::Secp256k1::new();
        let init_handshake = Handshake::<handshake::Initialized>::new_with_rng(
            Network::Bitcoin,
            Role::Initiator,
            &mut init_rng,
            &secp,
        )
        .unwrap();

        // Generate responder messages with garbage and decoys.
        let resp_garbage = b"responder garbage";
        let resp_decoys: &[&[u8]] = &[b"decoy1", b"another decoy packet"];
        let mut messages = generate_handshake_messages(
            1042,
            42,
            Role::Responder,
            Some(resp_garbage),
            Some(resp_decoys),
        );

        // Add one extra byte that should be left for the session reader.
        let session_byte = 0x42u8;
        messages.push(session_byte);

        let reader = Cursor::new(messages);
        let mut writer = Vec::new();

        let result = handshake_with_initialized(init_handshake, None, None, reader, &mut writer);

        // Verify the session reader contains exactly the extra byte we added.
        let (_, _, mut session_reader) = result.unwrap();
        let mut buffer = [0u8; 1];
        match session_reader.read(&mut buffer) {
            Ok(1) => {
                assert_eq!(
                    buffer[0], session_byte,
                    "Session reader should contain the extra byte"
                );
            }
            Ok(n) => panic!("Expected to read 1 byte but read {}", n),
            Err(e) => panic!("Unexpected error reading from session reader: {}", e),
        }
    }

    #[test]
    fn test_handshake_packet_too_big_protection() {
        // Verifies that the handshake properly rejects packets
        // that would require excessive memory allocation.

        let mut init_rng = StdRng::seed_from_u64(42);
        let secp = bitcoin::secp256k1::Secp256k1::new();
        let init_handshake = Handshake::<handshake::Initialized>::new_with_rng(
            Network::Bitcoin,
            Role::Initiator,
            &mut init_rng,
            &secp,
        )
        .unwrap();

        let large_decoy = vec![0; MAX_PACKET_SIZE_FOR_ALLOCATION + 1];
        let resp_decoys: &[&[u8]] = &[large_decoy.as_slice()];
        let messages =
            generate_handshake_messages(1042, 42, Role::Responder, None, Some(resp_decoys));

        let reader = Cursor::new(messages);
        let mut writer = Vec::new();

        let result = handshake_with_initialized(init_handshake, None, None, reader, &mut writer);
        assert!(matches!(
            result,
            Err(ProtocolError::Internal(Error::PacketTooBig))
        ));
    }
}