net.i2p.router.transport.ntcp

## Class InboundEstablishState

- java.lang.Object
- - net.i2p.router.transport.ntcp.EstablishBase
  - - net.i2p.router.transport.ntcp.InboundEstablishState

- All Implemented Interfaces:
    EstablishState, NTCP2Payload.PayloadCallback

      class InboundEstablishState
      extends EstablishBase
      implements NTCP2Payload.PayloadCallback

  NTCP 2 inbound connection establishment state machine. Handles the server-side (Bob) of the NTCP 2 handshake process, including cryptographic operations, peer verification, and transition to the data phase.

  This class manages the complete inbound NTCP 2 connection lifecycle:

  - Receives and processes Alice's handshake messages (1 and 3)
  - Sends Bob's responses (messages 2 and 4)
  - Performs Noise protocol XK handshake with Elligator2
  - Validates peer RouterInfo and signatures
  - Establishes data phase keys (ChaChaPoly + SipHash)
  - Handles clock skew detection and peer banlisting

  State transitions:

       IB_INIT -> IB_NTCP2_INIT -> IB_NTCP2_GOT_X -> IB_NTCP2_GOT_PADDING
            -> IB_NTCP2_SENT_Y -> IB_NTCP2_GOT_RI -> VERIFIED

  Threading: All methods are synchronized. Caller must hold locks when invoking methods that modify state.

- - ### Nested Class Summary

    - ### Nested classes/interfaces inherited from class net.i2p.router.transport.ntcp.EstablishBase

      `EstablishBase.State`

  - ### Field Summary

    - ### Fields inherited from class net.i2p.router.transport.ntcp.EstablishBase

      `_con, _context, _log, _peerSkew, _prevEncrypted, _received, _state, _stateLock, _transport, _X, _Y, AES_SIZE, FAILED, MAX_RI_SIZE, MIN_RI_SIZE, STATES_DONE, VERIFIED, XY_SIZE`

  - ### Constructor Summary

    Constructors
    Constructor and Description
    `InboundEstablishState(RouterContext ctx, NTCPTransport transport, NTCPConnection con)`

  - ### Method Summary

    All Methods Static Methods Instance Methods Concrete Methods
    Modifier and Type | Method and Description
    --- | ---
    `protected void` | `fail(String reason, Exception e, boolean bySkew)` Handles handshake failure by transitioning to CORRUPT state and cleaning up.
    `int` | `getVersion()` Returns the NTCP protocol version this state machine handles.
    `void` | `gotDateTime(long time)` Illegal during handshake - date/time is only in the options, not a separate payload.
    `void` | `gotI2NP(I2NPMessage msg)` Illegal during handshake - I2NP messages are only in the data phase.
    `void` | `gotOptions(byte[] options, boolean isHandshake)` Receives and validates Alice's option preferences from message 3.
    `void` | `gotPadding(int paddingLength, int frameLength)` Receives padding information from message 3.
    `void` | `gotRI(RouterInfo ri, boolean isHandshake, boolean flood)` Validates Alice's RouterInfo and extracts the static key for comparison.
    `void` | `gotTermination(int reason, long lastReceived)` Illegal during handshake - termination is only valid after connection is established.
    `void` | `gotUnknown(int type, int len)` Illegal during handshake - unknown payload types should not appear.
    `static String` | `parseReason(int reasonCode)` Converts a termination reason code to a human-readable string.
    `void` | `receive(ByteBuffer src)` Entry point for receiving data on an inbound NTCP connection.
    `protected void` | `releaseBufs(boolean isVerified)` Releases buffers and resources held by this state machine.

    - ### Methods inherited from class net.i2p.router.transport.ntcp.EstablishBase

      `_x, changeState, close, fail, fail, isComplete, isCorrupt, prefix, prepareOutbound, toString`

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait`

- - ### Constructor Detail

    - #### InboundEstablishState

          public InboundEstablishState(RouterContext ctx,
                                       NTCPTransport transport,
                                       NTCPConnection con)

  - ### Method Detail

    - #### fail

          protected void fail(String reason,
                              Exception e,
                              boolean bySkew)

      Handles handshake failure by transitioning to CORRUPT state and cleaning up.

      Overrides the base implementation to additionally destroy the Noise handshake state for security.

      Overrides:
        `fail` in class `EstablishBase`
      Parameters:
        `reason` - the failure reason string
        `e` - the exception that caused the failure, or null
        `bySkew` - true if failure was due to clock skew (suppresses stat collection)

    - #### getVersion

          public int getVersion()

      Returns the NTCP protocol version this state machine handles.
      Specified by:
        `getVersion` in interface `EstablishState`
      Specified by:
        `getVersion` in class `EstablishBase`
      Returns:
        2 for NTCP 2, as this class only supports the NTCP 2 protocol

    - #### gotDateTime

          public void gotDateTime(long time)

      Illegal during handshake - date/time is only in the options, not a separate payload.
      Specified by:
        `gotDateTime` in interface `NTCP2Payload.PayloadCallback`
      Parameters:
        `time` - the timestamp

    - #### gotI2NP

          public void gotI2NP(I2NPMessage msg)

      Illegal during handshake - I2NP messages are only in the data phase.
      Specified by:
        `gotI2NP` in interface `NTCP2Payload.PayloadCallback`
      Parameters:
        `msg` - the I2NP message

    - #### gotOptions

          public void gotOptions(byte[] options,
                                 boolean isHandshake)

      Receives and validates Alice's option preferences from message 3.

      Parses the options byte array into an NTCP2Options object containing negotiated parameters like congestion control and flags.

      Specified by:
        `gotOptions` in interface `NTCP2Payload.PayloadCallback`
      Parameters:
        `options` - the options byte array from Alice
        `isHandshake` - always true; indicates this is during handshake processing

    - #### gotPadding

          public void gotPadding(int paddingLength,
                                 int frameLength)

      Receives padding information from message 3.

      NTCP 2 padding is handled differently - the actual padding data is not separately tracked in this implementation.

      Specified by:
        `gotPadding` in interface `NTCP2Payload.PayloadCallback`
      Parameters:
        `paddingLength` - the length of padding in the frame
        `frameLength` - the total length of the frame including padding

    - #### gotRI

          public void gotRI(RouterInfo ri,
                            boolean isHandshake,
                            boolean flood)
                     throws DataFormatException

      Validates Alice's RouterInfo and extracts the static key for comparison.

      This is a PayloadCallback method invoked during message 3 processing.

      Validations performed:

      - Ensures RouterInfo contains an NTCP2-capable address
      - Extracts and validates the "s" (static key) option
      - Compares static key against the Noise handshake public key
      - Verifies the peer's identity via verifyInbound()
      - Checks IP address consistency (RI-published vs. actual connection)
      - Validates router version, capabilities, and network ID
      - Stores RouterInfo in the network database

      Side effects:

      - Sets _msg3p2FailReason on validation failure
      - May banlist the peer hash and/or blocklist the IP
      - Stores RouterInfo in netdb
      - Sets _aliceIdent and calls con.setRemotePeer()
      Specified by:
        `gotRI` in interface `NTCP2Payload.PayloadCallback`
      Parameters:
        `ri` - Alice's RouterInfo from message 3
        `isHandshake` - always true; indicates this is during handshake processing
        `flood` - true if the RouterInfo should be flooded to the network
      Throws:
        `DataFormatException` - if validation fails (bad sig, no static key, key mismatch, IP mismatch, banned, etc.)

    - #### gotTermination

          public void gotTermination(int reason,
                                     long lastReceived)

      Illegal during handshake - termination is only valid after connection is established.
      Specified by:
        `gotTermination` in interface `NTCP2Payload.PayloadCallback`
      Parameters:
        `reason` - the termination reason code
        `lastReceived` - the number of bytes received when termination occurred

    - #### gotUnknown

          public void gotUnknown(int type,
                                 int len)

      Illegal during handshake - unknown payload types should not appear.
      Specified by:
        `gotUnknown` in interface `NTCP2Payload.PayloadCallback`
      Parameters:
        `type` - the unknown payload type
        `len` - the payload length

    - #### parseReason

          public static String parseReason(int reasonCode)

      Converts a termination reason code to a human-readable string.

      Reason codes are defined in NTCPConnection and used in termination messages to indicate why a connection failed.

      Parameters:
        `reasonCode` - the numeric reason code from NTCPConnection
      Returns:
        a descriptive string for the reason code

    - #### receive

          public void receive(ByteBuffer src)

      Entry point for receiving data on an inbound NTCP connection. Parses the contents of the buffer as part of the handshake.

      Delegates to receiveInbound() for actual processing. All data is copied out of the buffer as Reader.processRead() will return it to the pool.

      If there are additional data in the buffer after the handshake is complete, this EstablishState is responsible for passing it to NTCPConnection.

      Specified by:
        `receive` in interface `EstablishState`
      Overrides:
        `receive` in class `EstablishBase`
      Parameters:
        `src` - the ByteBuffer containing received data; caller must not modify position

    - #### releaseBufs

          protected void releaseBufs(boolean isVerified)

      Releases buffers and resources held by this state machine.

      Must be called exactly once when the handshake completes (success or failure). Caller must hold synchronization.

      Actions:

      - Releases _curEncrypted buffer if verification failed (passed to NTCPConnection on success)
      - Zeros out _X buffer for security
      - Releases _X and _msg3tmp buffers back to caches
      Overrides:
        `releaseBufs` in class `EstablishBase`
      Parameters:
        `isVerified` - true if handshake succeeded; false if it failed