///|
/// Rotating cookie secret validity window in milliseconds (WireGuard §5.4.7: 2 minutes).
pub const COOKIE_REFRESH_MS : UInt64 = 120_000UL

///|
/// Stateful responder-side cookie generator and `mac2` validator (§5.4.7).
#derive(Debug, Eq)
pub struct CookieValidator {
  local_cookie_key : Bytes
  priv mut current_secret : Bytes
  priv mut secret_born_ms : UInt64
  priv mut nonce_counter : UInt64
}

///|
/// Create a `CookieValidator` bound to `local_static_public` and an initial 32-byte random `secret_seed`.
pub fn CookieValidator::new(
  local_static_public : BytesView,
  secret_seed : BytesView,
  now_ms : UInt64,
) -> CookieValidator raise ProtocolError {
  ensure_key32("local_static_public", local_static_public)
  ensure_key32("secret_seed", secret_seed)
  {
    local_cookie_key: compute_cookie_key(local_static_public),
    current_secret: secret_seed.to_owned(),
    secret_born_ms: now_ms,
    nonce_counter: 1UL,
  }
}

///|
fn CookieValidator::active_secret(
  self : CookieValidator,
  now_ms : UInt64,
) -> Bytes {
  if now_ms >= self.secret_born_ms &&
    now_ms - self.secret_born_ms >= COOKIE_REFRESH_MS {
    // Deterministicallyratchet secret via BLAKE2s KDF on 2-minute boundary
    self.current_secret = @crypto.kdf1(self.current_secret, b"cookie-ratchet")
    self.secret_born_ms = now_ms
  }
  self.current_secret
}

///|
/// Compute the 16-byte cookie `tau = Mac(R_m, peer_endpoint_bytes)` for `peer_endpoint_bytes` at `now_ms`.
pub fn CookieValidator::compute_cookie(
  self : CookieValidator,
  peer_endpoint_bytes : BytesView,
  now_ms : UInt64,
) -> Bytes {
  let secret = self.active_secret(now_ms)
  try! @crypto.wg_mac(secret, peer_endpoint_bytes)
}

///|
/// Verify `mac2` on an incoming `HandshakeInitiation` from `peer_endpoint_bytes`.
pub fn CookieValidator::verify_initiation_mac2(
  self : CookieValidator,
  msg : @packet.HandshakeInitiation,
  peer_endpoint_bytes : BytesView,
  now_ms : UInt64,
) -> Bool {
  let cookie = self.compute_cookie(peer_endpoint_bytes, now_ms)
  let prefix116 = @packet.HandshakeInitiation::encode_prefix_for_mac1(
    msg.sender_index,
    msg.unencrypted_ephemeral,
    msg.encrypted_static,
    msg.encrypted_timestamp,
  )
  let prefix132 = @crypto.concat2(prefix116, msg.mac1)
  let expected_mac2 = try! @crypto.wg_mac(cookie, prefix132)
  @crypto.ct_eq(msg.mac2, expected_mac2)
}

///|
/// Verify `mac2` on an incoming `HandshakeResponse` from `peer_endpoint_bytes`.
pub fn CookieValidator::verify_response_mac2(
  self : CookieValidator,
  msg : @packet.HandshakeResponse,
  peer_endpoint_bytes : BytesView,
  now_ms : UInt64,
) -> Bool {
  let cookie = self.compute_cookie(peer_endpoint_bytes, now_ms)
  let prefix60 = @packet.HandshakeResponse::encode_prefix_for_mac1(
    msg.sender_index,
    msg.receiver_index,
    msg.unencrypted_ephemeral,
    msg.encrypted_nothing,
  )
  let prefix76 = @crypto.concat2(prefix60, msg.mac1)
  let expected_mac2 = try! @crypto.wg_mac(cookie, prefix76)
  @crypto.ct_eq(msg.mac2, expected_mac2)
}

///|
/// Build a 64-byte `CookieReply` (Type 3) challenging the sender of a handshake packet whose `mac1` was valid
/// but whose `mac2` was missing or stale under load (§5.4.7).
pub fn CookieValidator::create_cookie_reply(
  self : CookieValidator,
  sender_index : UInt32,
  triggering_mac1 : BytesView,
  peer_endpoint_bytes : BytesView,
  now_ms : UInt64,
  explicit_nonce24? : BytesView,
) -> @packet.CookieReply raise ProtocolError {
  if triggering_mac1.length() != 16 {
    raise ProtocolError::InvalidKeyLength(
      field="triggering_mac1",
      actual=triggering_mac1.length(),
    )
  }
  let cookie = self.compute_cookie(peer_endpoint_bytes, now_ms)
  let nonce24 = match explicit_nonce24 {
    Some(n) => {
      if n.length() != 24 {
        raise ProtocolError::InvalidKeyLength(
          field="nonce24",
          actual=n.length(),
        )
      }
      n.to_owned()
    }
    None => {
      let n_buf = FixedArray::make(8, b'\x00')
      @crypto.write_u64_le(n_buf, 0, self.nonce_counter)
      self.nonce_counter = self.nonce_counter + 1UL
      let derived = @crypto.blake2s_256_pair(
        self.current_secret,
        Bytes::from_array(n_buf),
      )
      derived[:24].to_owned()
    }
  }
  let encrypted_cookie = @crypto.xchacha20_poly1305_seal(
    self.local_cookie_key,
    nonce24,
    cookie,
    triggering_mac1,
  ) catch {
    err => raise ProtocolError::Crypto(err)
  }
  { receiver_index: sender_index, nonce: nonce24, encrypted_cookie, }
}

///|
/// Decrypt and authenticate a received `CookieReply` (Type 3) using the remote peer's static public key
/// and the `mac1` of the handshake message we previously transmitted (§5.4.7).
pub fn consume_cookie_reply(
  reply : @packet.CookieReply,
  remote_static_public : BytesView,
  last_sent_mac1 : BytesView,
) -> Bytes raise ProtocolError {
  ensure_key32("remote_static_public", remote_static_public)
  if last_sent_mac1.length() != 16 {
    raise ProtocolError::InvalidKeyLength(
      field="last_sent_mac1",
      actual=last_sent_mac1.length(),
    )
  }
  let cookie_key = compute_cookie_key(remote_static_public)
  @crypto.xchacha20_poly1305_open(
    cookie_key,
    reply.nonce,
    reply.encrypted_cookie,
    last_sent_mac1,
  ) catch {
    _ => raise ProtocolError::HandshakeDecryptionFailed(stage="cookie_reply")
  }
}