///|
pub const WG_CONSTRUCTION_BYTES : Bytes = b"Noise_IKpsk2_25519_ChaChaPoly_BLAKE2s"

///|
pub const WG_IDENTIFIER_BYTES : Bytes = b"WireGuard v1 zx2c4 Jason@zx2c4.com"

///|
pub const WG_LABEL_MAC1 : Bytes = b"mac1----"

///|
pub const WG_LABEL_COOKIE : Bytes = b"cookie--"

///|
#derive(Debug, Eq)
pub(all) suberror ProtocolError {
  InvalidKeyLength(field~ : String, actual~ : Int32)
  InvalidMac1
  InvalidMac2
  CookieRequired
  HandshakeDecryptionFailed(stage~ : String)
  UnknownPeer(Bytes)
  ReplayedOrStaleTimestamp
  UnexpectedHandshakeResponse(UInt32)
  MalformedTimestamp
  Crypto(@crypto.CryptoError)
  Packet(@packet.PacketError)
  NoActiveSession
  UnknownReceiverIndex(UInt32)
  ReplayedOrTooOldPacket(UInt64)
  CounterExhausted
  InvalidSourceIp(@packet.IpAddr)
  UnroutableDestination(@packet.IpAddr)
}

///|
/// Derived directional transport session keys after a completed `Noise_IKpsk2` handshake (§5.4.5).
#derive(Debug, Eq)
pub(all) struct DerivedSessionKeys {
  local_index : UInt32
  remote_index : UInt32
  send_key : Bytes
  recv_key : Bytes
  is_initiator : Bool
}

///|
/// In-flight initiator half-handshake state awaiting a `HandshakeResponse` (§5.4.2).
#derive(Debug, Eq)
pub struct InitiatorHandshake {
  local_index : UInt32
  local_static_private : Bytes
  remote_static_public : Bytes
  ephemeral_private : Bytes
  preshared_key : Bytes
  chaining_key : Bytes
  hash : Bytes
  last_mac1 : Bytes
}

///|
/// Compute the initial Noise chaining key `C_0 = Hash(CONSTRUCTION)` and `H_0 = Hash(C_0 || IDENTIFIER)`.
pub fn initial_noise_state() -> (Bytes, Bytes) {
  let c0 = @crypto.blake2s_256(WG_CONSTRUCTION_BYTES)
  let h0 = @crypto.blake2s_256_pair(c0, WG_IDENTIFIER_BYTES)
  (c0, h0)
}

///|
/// Compute `Hash(LABEL_MAC1 || peer_static_public)` (32 bytes, §5.4.4).
pub fn compute_mac1_key(peer_static_public : BytesView) -> Bytes {
  @crypto.blake2s_256_pair(WG_LABEL_MAC1, peer_static_public)
}

///|
/// Compute `Hash(LABEL_COOKIE || peer_static_public)` (32 bytes, §5.4.7).
pub fn compute_cookie_key(peer_static_public : BytesView) -> Bytes {
  @crypto.blake2s_256_pair(WG_LABEL_COOKIE, peer_static_public)
}

///|
/// Verify `mac1` on a `HandshakeInitiation` against the receiver's static public key.
pub fn verify_initiation_mac1(
  msg : @packet.HandshakeInitiation,
  receiver_static_public : BytesView,
) -> Bool {
  let prefix = @packet.HandshakeInitiation::encode_prefix_for_mac1(
    msg.sender_index,
    msg.unencrypted_ephemeral,
    msg.encrypted_static,
    msg.encrypted_timestamp,
  )
  let mac1_key = compute_mac1_key(receiver_static_public)
  let expected = try! @crypto.wg_mac(mac1_key, prefix)
  @crypto.ct_eq(msg.mac1, expected)
}

///|
/// Verify `mac1` on a `HandshakeResponse` against the receiver's (initiator's) static public key.
pub fn verify_response_mac1(
  msg : @packet.HandshakeResponse,
  receiver_static_public : BytesView,
) -> Bool {
  let prefix = @packet.HandshakeResponse::encode_prefix_for_mac1(
    msg.sender_index,
    msg.receiver_index,
    msg.unencrypted_ephemeral,
    msg.encrypted_nothing,
  )
  let mac1_key = compute_mac1_key(receiver_static_public)
  let expected = try! @crypto.wg_mac(mac1_key, prefix)
  @crypto.ct_eq(msg.mac1, expected)
}

///|
fn normalize_psk(psk : BytesView?) -> Bytes raise ProtocolError {
  match psk {
    None => Bytes::from_array(FixedArray::make(32, b'\x00'))
    Some(q) => {
      if q.length() != 32 {
        raise ProtocolError::InvalidKeyLength(
          field="preshared_key",
          actual=q.length(),
        )
      }
      q.to_owned()
    }
  }
}

///|
fn ensure_key32(field : String, k : BytesView) -> Unit raise ProtocolError {
  if k.length() != 32 {
    raise ProtocolError::InvalidKeyLength(field~, actual=k.length())
  }
}

///|
/// Build a `HandshakeInitiation` (Type 1, 148 bytes) as the initiator (§5.4.2).
pub fn create_handshake_initiation(
  local_static_private : BytesView,
  remote_static_public : BytesView,
  ephemeral_private : BytesView,
  sender_index : UInt32,
  timestamp : Tai64n,
  preshared_key? : BytesView,
  cookie? : BytesView,
) -> (@packet.HandshakeInitiation, InitiatorHandshake) raise ProtocolError {
  ensure_key32("local_static_private", local_static_private)
  ensure_key32("remote_static_public", remote_static_public)
  ensure_key32("ephemeral_private", ephemeral_private)
  let psk = normalize_psk(preshared_key)

  let local_static_public = @crypto.x25519_public_key(local_static_private) catch {
    err => raise ProtocolError::Crypto(err)
  }
  let ephemeral_public = @crypto.x25519_public_key(ephemeral_private) catch {
    err => raise ProtocolError::Crypto(err)
  }

  let (c0, h0) = initial_noise_state()
  let mut c = c0
  let mut h = @crypto.blake2s_256_pair(h0, remote_static_public)

  // e
  c = @crypto.kdf1(c, ephemeral_public)
  h = @crypto.blake2s_256_pair(h, ephemeral_public)

  // es = DH(E_i^priv, S_r^pub)
  let dh_es = @crypto.x25519_dh(ephemeral_private, remote_static_public) catch {
    err => raise ProtocolError::Crypto(err)
  }
  let (c_es, k_es) = @crypto.kdf2(c, dh_es)
  c = c_es

  // s: encrypt S_i^pub
  let encrypted_static = @crypto.wg_aead_seal(k_es, 0UL, local_static_public, h) catch {
    err => raise ProtocolError::Crypto(err)
  }
  h = @crypto.blake2s_256_pair(h, encrypted_static)

  // ss = DH(S_i^priv, S_r^pub)
  let dh_ss = @crypto.x25519_dh(local_static_private, remote_static_public) catch {
    err => raise ProtocolError::Crypto(err)
  }
  let (c_ss, k_ss) = @crypto.kdf2(c, dh_ss)
  c = c_ss

  // timestamp payload
  let encrypted_timestamp = @crypto.wg_aead_seal(k_ss, 0UL, timestamp.raw, h) catch {
    err => raise ProtocolError::Crypto(err)
  }
  h = @crypto.blake2s_256_pair(h, encrypted_timestamp)

  // mac1 & mac2
  let prefix116 = @packet.HandshakeInitiation::encode_prefix_for_mac1(
    sender_index, ephemeral_public, encrypted_static, encrypted_timestamp,
  )
  let mac1_key = compute_mac1_key(remote_static_public)
  let mac1 = @crypto.wg_mac(mac1_key, prefix116) catch {
    err => raise ProtocolError::Crypto(err)
  }
  let mac2 = match cookie {
    None => Bytes::from_array(FixedArray::make(16, b'\x00'))
    Some(ck) => {
      if ck.length() != 16 {
        raise ProtocolError::InvalidKeyLength(
          field="cookie",
          actual=ck.length(),
        )
      }
      let prefix132 = @crypto.concat2(prefix116, mac1)
      @crypto.wg_mac(ck, prefix132) catch {
        err => raise ProtocolError::Crypto(err)
      }
    }
  }

  let msg : @packet.HandshakeInitiation = {
    sender_index,
    unencrypted_ephemeral: ephemeral_public,
    encrypted_static,
    encrypted_timestamp,
    mac1,
    mac2,
  }
  let state : InitiatorHandshake = {
    local_index: sender_index,
    local_static_private: local_static_private.to_owned(),
    remote_static_public: remote_static_public.to_owned(),
    ephemeral_private: ephemeral_private.to_owned(),
    preshared_key: psk,
    chaining_key: c,
    hash: h,
    last_mac1: mac1,
  }
  (msg, state)
}

///|
/// Decoded result of consuming a valid `HandshakeInitiation` on the responder prior to generating a response.
#derive(Debug, Eq)
pub(all) struct ConsumedInitiation {
  initiator_static_public : Bytes
  initiator_ephemeral_public : Bytes
  initiator_index : UInt32
  timestamp : Tai64n
  chaining_key : Bytes
  hash : Bytes
}

///|
/// Verify and decrypt a `HandshakeInitiation` on the responder (§5.4.2).
/// Validates `mac1` BEFORE performing any Curve25519 scalar multiplications.
pub fn consume_handshake_initiation(
  msg : @packet.HandshakeInitiation,
  responder_static_private : BytesView,
) -> ConsumedInitiation raise ProtocolError {
  ensure_key32("responder_static_private", responder_static_private)
  let responder_static_public = @crypto.x25519_public_key(
    responder_static_private,
  ) catch {
    err => raise ProtocolError::Crypto(err)
  }
  if !verify_initiation_mac1(msg, responder_static_public) {
    raise ProtocolError::InvalidMac1
  }

  let (c0, h0) = initial_noise_state()
  let mut c = c0
  let mut h = @crypto.blake2s_256_pair(h0, responder_static_public)

  // e
  c = @crypto.kdf1(c, msg.unencrypted_ephemeral)
  h = @crypto.blake2s_256_pair(h, msg.unencrypted_ephemeral)

  // es = DH(S_r^priv, E_i^pub)
  let dh_es = @crypto.x25519_dh(
    responder_static_private,
    msg.unencrypted_ephemeral,
  ) catch {
    err => raise ProtocolError::Crypto(err)
  }
  let (c_es, k_es) = @crypto.kdf2(c, dh_es)
  c = c_es

  // decrypt S_i^pub
  let initiator_static_public = @crypto.wg_aead_open(
    k_es,
    0UL,
    msg.encrypted_static,
    h,
  ) catch {
    _ => raise ProtocolError::HandshakeDecryptionFailed(stage="static_key")
  }
  h = @crypto.blake2s_256_pair(h, msg.encrypted_static)

  // ss = DH(S_r^priv, S_i^pub)
  let dh_ss = @crypto.x25519_dh(
    responder_static_private, initiator_static_public,
  ) catch {
    err => raise ProtocolError::Crypto(err)
  }
  let (c_ss, k_ss) = @crypto.kdf2(c, dh_ss)
  c = c_ss

  // decrypt timestamp
  let ts_bytes = @crypto.wg_aead_open(k_ss, 0UL, msg.encrypted_timestamp, h) catch {
    _ => raise ProtocolError::HandshakeDecryptionFailed(stage="timestamp")
  }
  h = @crypto.blake2s_256_pair(h, msg.encrypted_timestamp)
  let timestamp = Tai64n::from_bytes(ts_bytes)

  {
    initiator_static_public,
    initiator_ephemeral_public: msg.unencrypted_ephemeral,
    initiator_index: msg.sender_index,
    timestamp,
    chaining_key: c,
    hash: h,
  }
}

///|
/// Build a `HandshakeResponse` (Type 2, 92 bytes) and derive Responder `DerivedSessionKeys` (§5.4.3 & §5.4.5).
pub fn create_handshake_response(
  consumed : ConsumedInitiation,
  responder_ephemeral_private : BytesView,
  responder_index : UInt32,
  preshared_key? : BytesView,
  cookie? : BytesView,
) -> (@packet.HandshakeResponse, DerivedSessionKeys) raise ProtocolError {
  ensure_key32("responder_ephemeral_private", responder_ephemeral_private)
  let psk = normalize_psk(preshared_key)

  let responder_ephemeral_public = @crypto.x25519_public_key(
    responder_ephemeral_private,
  ) catch {
    err => raise ProtocolError::Crypto(err)
  }

  let mut c = consumed.chaining_key
  let mut h = consumed.hash

  // e
  c = @crypto.kdf1(c, responder_ephemeral_public)
  h = @crypto.blake2s_256_pair(h, responder_ephemeral_public)

  // ee = DH(E_r^priv, E_i^pub)
  let dh_ee = @crypto.x25519_dh(
    responder_ephemeral_private,
    consumed.initiator_ephemeral_public,
  ) catch {
    err => raise ProtocolError::Crypto(err)
  }
  c = @crypto.kdf1(c, dh_ee)

  // se = DH(E_r^priv, S_i^pub)
  let dh_se = @crypto.x25519_dh(
    responder_ephemeral_private,
    consumed.initiator_static_public,
  ) catch {
    err => raise ProtocolError::Crypto(err)
  }
  c = @crypto.kdf1(c, dh_se)

  // psk
  let (c_psk, tau, k_psk) = @crypto.kdf3(c, psk)
  c = c_psk
  h = @crypto.blake2s_256_pair(h, tau)

  // empty payload
  let encrypted_nothing = @crypto.wg_aead_seal(k_psk, 0UL, b"", h) catch {
    err => raise ProtocolError::Crypto(err)
  }
  h = @crypto.blake2s_256_pair(h, encrypted_nothing)
  ignore(h)

  // mac1 & mac2 (receiver is initiator: S_i^pub)
  let prefix60 = @packet.HandshakeResponse::encode_prefix_for_mac1(
    responder_index,
    consumed.initiator_index,
    responder_ephemeral_public,
    encrypted_nothing,
  )
  let mac1_key = compute_mac1_key(consumed.initiator_static_public)
  let mac1 = @crypto.wg_mac(mac1_key, prefix60) catch {
    err => raise ProtocolError::Crypto(err)
  }
  let mac2 = match cookie {
    None => Bytes::from_array(FixedArray::make(16, b'\x00'))
    Some(ck) => {
      if ck.length() != 16 {
        raise ProtocolError::InvalidKeyLength(
          field="cookie",
          actual=ck.length(),
        )
      }
      let prefix76 = @crypto.concat2(prefix60, mac1)
      @crypto.wg_mac(ck, prefix76) catch {
        err => raise ProtocolError::Crypto(err)
      }
    }
  }

  let (t_init_send, t_resp_send) = @crypto.kdf2(c, b"")
  let resp : @packet.HandshakeResponse = {
    sender_index: responder_index,
    receiver_index: consumed.initiator_index,
    unencrypted_ephemeral: responder_ephemeral_public,
    encrypted_nothing,
    mac1,
    mac2,
  }
  let keys : DerivedSessionKeys = {
    local_index: responder_index,
    remote_index: consumed.initiator_index,
    send_key: t_resp_send,
    recv_key: t_init_send,
    is_initiator: false,
  }
  (resp, keys)
}

///|
/// Verify and consume a `HandshakeResponse` on the initiator, deriving Initiator `DerivedSessionKeys` (§5.4.3 & §5.4.5).
pub fn consume_handshake_response(
  state : InitiatorHandshake,
  msg : @packet.HandshakeResponse,
) -> DerivedSessionKeys raise ProtocolError {
  if msg.receiver_index != state.local_index {
    raise ProtocolError::UnexpectedHandshakeResponse(msg.receiver_index)
  }
  let local_static_public = @crypto.x25519_public_key(
    state.local_static_private,
  ) catch {
    err => raise ProtocolError::Crypto(err)
  }
  if !verify_response_mac1(msg, local_static_public) {
    raise ProtocolError::InvalidMac1
  }

  let mut c = state.chaining_key
  let mut h = state.hash

  // e
  c = @crypto.kdf1(c, msg.unencrypted_ephemeral)
  h = @crypto.blake2s_256_pair(h, msg.unencrypted_ephemeral)

  // ee = DH(E_i^priv, E_r^pub)
  let dh_ee = @crypto.x25519_dh(
    state.ephemeral_private,
    msg.unencrypted_ephemeral,
  ) catch {
    err => raise ProtocolError::Crypto(err)
  }
  c = @crypto.kdf1(c, dh_ee)

  // se = DH(S_i^priv, E_r^pub)
  let dh_se = @crypto.x25519_dh(
    state.local_static_private,
    msg.unencrypted_ephemeral,
  ) catch {
    err => raise ProtocolError::Crypto(err)
  }
  c = @crypto.kdf1(c, dh_se)

  // psk
  let (c_psk, tau, k_psk) = @crypto.kdf3(c, state.preshared_key)
  c = c_psk
  h = @crypto.blake2s_256_pair(h, tau)

  // verify encrypted_nothing (0-byte plaintext + 16-byte Poly1305 tag)
  let empty_plain = @crypto.wg_aead_open(k_psk, 0UL, msg.encrypted_nothing, h) catch {
    _ => raise ProtocolError::HandshakeDecryptionFailed(stage="response_auth")
  }
  if empty_plain.length() != 0 {
    raise ProtocolError::HandshakeDecryptionFailed(stage="response_non_empty")
  }

  let (t_init_send, t_resp_send) = @crypto.kdf2(c, b"")
  {
    local_index: state.local_index,
    remote_index: msg.sender_index,
    send_key: t_init_send,
    recv_key: t_resp_send,
    is_initiator: true,
  }
}

///|
/// Encrypt and frame an inner IP packet (or empty keepalive `b""`) as a `TransportData` packet (§5.4.6).
pub fn seal_transport_packet(
  remote_index : UInt32,
  send_key : BytesView,
  counter : UInt64,
  inner_ip_or_empty : BytesView,
) -> @packet.TransportData raise ProtocolError {
  let padded = if inner_ip_or_empty.length() == 0 {
    b""
  } else {
    @packet.pad_inner_packet(inner_ip_or_empty)
  }
  let encrypted_packet = @crypto.wg_aead_seal(send_key, counter, padded, b"") catch {
    err => raise ProtocolError::Crypto(err)
  }
  { receiver_index: remote_index, counter, encrypted_packet, }
}

///|
/// Authenticate, decrypt, and strip WireGuard 16-byte padding from a `TransportData` packet (§5.4.6).
/// Returns `b""` for a valid authenticated 0-byte Keepalive frame.
pub fn open_transport_packet(
  recv_key : BytesView,
  pkt : @packet.TransportData,
) -> Bytes raise ProtocolError {
  let decrypted = @crypto.wg_aead_open(
    recv_key,
    pkt.counter,
    pkt.encrypted_packet,
    b"",
  ) catch {
    err => raise ProtocolError::Crypto(err)
  }
  if decrypted.length() == 0 {
    b""
  } else {
    let info = @packet.inspect_and_trim_inner_ip(decrypted) catch {
      err => raise ProtocolError::Packet(err)
    }
    info.trimmed_packet
  }
}