Refactor and comment ComposeInitiatorHandshakeMessage

This commit is contained in:
eyedeekay
2025-03-24 19:36:14 -04:00
parent d401b06c0f
commit b153bfc050

View File

@ -28,20 +28,47 @@ func (c *NTCP2Session) ComposeInitiatorHandshakeMessage(
handshakeState *noise.HandshakeState,
err error,
) {
// Create session request
// Create session request with obfuscated ephemeral key
request, err := c.CreateSessionRequest()
if err != nil {
return nil, nil, nil, err
}
// Initialize negotiation data with NTCP2 protocol specifics
negotiationData = initNegotiationData(nil)
// Buffer for the complete message
buf := new(bytes.Buffer)
// Write obfuscated key
buf.Write(request.ObfuscatedKey)
// Write obfuscated key - this has already been obfuscated in CreateSessionRequest()
if _, err := buf.Write(request.ObfuscatedKey); err != nil {
return nil, nil, nil, err
}
// Write timestamp
binary.BigEndian.PutUint32(buf.Next(4), request.Timestamp)
// Create options block - 16 bytes
options := make([]byte, 16)
// Set network ID (2 for production I2P)
options[0] = 2
// Set protocol version (2 for NTCP2)
options[1] = NTCP_PROTOCOL_VERSION
// Set padding length (bytes 2-3, big endian)
binary.BigEndian.PutUint16(options[2:4], uint16(len(request.Padding)))
// Set message 3 part 2 length (bytes 4-5) - placeholder for now
// This is the size of the second AEAD frame in SessionConfirmed
binary.BigEndian.PutUint16(options[4:6], 0) // Will need to be updated with actual size
// Set timestamp (bytes 8-11, big endian)
binary.BigEndian.PutUint32(options[8:12], request.Timestamp)
// Reserved bytes (6-7, 12-15) should be set to 0
// Write options block
if _, err := buf.Write(options); err != nil {
return nil, nil, nil, err
}
// Initialize Noise
config := noise.Config{
@ -49,6 +76,7 @@ func (c *NTCP2Session) ComposeInitiatorHandshakeMessage(
Pattern: noise.HandshakeXK,
Initiator: true,
StaticKeypair: localStatic,
PeerStatic: remoteStatic, // Add the peer's static key
Random: rand.Reader,
}
@ -57,7 +85,8 @@ func (c *NTCP2Session) ComposeInitiatorHandshakeMessage(
return nil, nil, nil, err
}
// Create Noise message
// Create Noise message - this contains the encrypted payload (options block)
// WriteMessage encrypts the payload and returns the message
handshakeMessage, _, _, err = handshakeState.WriteMessage(nil, buf.Bytes())
if err != nil {
return nil, nil, nil, err
@ -66,6 +95,6 @@ func (c *NTCP2Session) ComposeInitiatorHandshakeMessage(
// Add padding
handshakeMessage = append(handshakeMessage, request.Padding...)
// Ensure entire message is written at once
return nil, handshakeMessage, handshakeState, nil
// Return the complete handshake message
return negotiationData, handshakeMessage, handshakeState, nil
}