///|
/// One COSE_recipient (RFC 9052 §5.1). A leaf has no `recipients`.
/// An intermediate recipient's `ciphertext` wraps the parent key with a KEK
/// that is obtained from its nested recipients, one layer at a time.
///
/// `direct` (-6) is only legal as a leaf: ciphertext is `h''`, and the
/// identified key is the next layer's key. AES-KW (-3/-4/-5) wraps the next
/// layer's key. Both require a zero-length protected bstr.
pub(all) struct Recipient {
  protected_header : Protected
  unprotected : Header
  ciphertext : Bytes?
  recipients : Array[Recipient]
} derive(Eq)

///|
pub extend Recipient with Eq::{equal}

///|
#deprecated("Use `!=` instead", skip_current_package=true)
#doc(hidden)
pub extend Recipient with Eq::{not_equal}

///|
/// One layer of recipient construction.
///
/// A leaf uses `key` as the preshared secret. An intermediate uses `key` as
/// the KEK that wraps the parent key; `recipients` wrap that KEK and cannot
/// be empty. `direct` cannot have nested recipients.
pub(all) struct RecipientInput {
  prot : Header
  unprotected : Header
  key : CoseKey
  recipients : Array[RecipientInput]
  /// Sender private key. Ephemeral for ECDH-ES, static for ECDH-SS.
  agreement : CoseKey?
  /// OAEP seed. Required when sealing RSAES-OAEP.
  seed : Bytes?
}

///|
let recipient_max_depth : Int32 = 8

///|
let recipient_max_nodes : Int32 = 32

///|
fn header_kid(header : Header) -> Bytes? {
  header.kid
}

///|
fn recipient_kid(recipient : Recipient) -> Bytes? {
  match header_kid(recipient.unprotected) {
    Some(kid) => Some(kid)
    None => header_kid(recipient.protected_header.header)
  }
}

///|
fn kid_matches(key : CoseKey, recipient : Recipient) -> Bool {
  match (key.kid(), recipient_kid(recipient)) {
    (Some(left), Some(right)) => bytes_eq(left, right)
    _ => true
  }
}

///|
fn note_recipient(nodes : Array[Int32]) -> Unit raise CoseError {
  nodes[0] = nodes[0] + 1
  if nodes[0] > recipient_max_nodes {
    raise BadStructure("too many recipients")
  }
}

///|
fn is_direct_alg(alg : CoseAlg) -> Bool {
  match alg.normalize() {
    CoseAlg::Direct => true
    other => is_hkdf_direct(other) || is_ecdh_direct(other)
  }
}

///|
fn is_rsa_oaep(alg : CoseAlg) -> Bool {
  match alg.normalize() {
    CoseAlg::RsaesOaepSha1
    | CoseAlg::RsaesOaepSha256
    | CoseAlg::RsaesOaepSha512 => true
    _ => false
  }
}

///|
fn rsa_hash(alg : CoseAlg) -> @lib.RsaHash raise CoseError {
  match alg.normalize() {
    CoseAlg::RsaesOaepSha1 => @lib.rsa_hash_sha1
    CoseAlg::RsaesOaepSha256 => @lib.rsa_hash_sha256
    CoseAlg::RsaesOaepSha512 => @lib.rsa_hash_sha512
    other => raise UnsupportedAlg(other.name())
  }
}

///|
fn rsa_key_ops(key : CoseKey, seal : Bool) -> Unit raise CoseError {
  let ops = match key {
    CoseKey::Rsa(rsa) => rsa.key_ops
    _ => raise AlgMismatch("RSAES-OAEP requires an RSA key")
  }
  if ops.length() == 0 {
    return
  }
  let primary : Int32 = if seal { 5 } else { 6 }
  let alternate : Int32 = if seal { 3 } else { 4 }
  for i = 0; i < ops.length(); i = i + 1 {
    if ops[i] == primary || ops[i] == alternate {
      return
    }
  }
  raise BadStructure("key_ops does not allow RSAES-OAEP")
}

///|
fn rsa_oaep_seal(
  key : CoseKey,
  cek : Bytes,
  seed : Bytes,
  alg : CoseAlg,
) -> Bytes raise CoseError {
  match key {
    CoseKey::Rsa(rsa) => {
      let hash = rsa_hash(alg)
      match @lib.rsa_oaep_encrypt_with_or(cek, rsa.n, rsa.e, seed, b"", hash) {
        Ok(ct) => ct
        Err(msg) => raise BadStructure(msg)
      }
    }
    _ => raise AlgMismatch("RSAES-OAEP requires an RSA key")
  }
}

///|
fn rsa_oaep_open(
  key : CoseKey,
  ciphertext : Bytes?,
  alg : CoseAlg,
) -> Bytes raise CoseError {
  let wrapped = match ciphertext {
    Some(value) =>
      if value.length() == 0 {
        raise BadStructure("RSAES-OAEP recipient is missing ciphertext")
      } else {
        value
      }
    None => raise BadStructure("RSAES-OAEP recipient is missing ciphertext")
  }
  match key {
    CoseKey::Rsa(rsa) =>
      match rsa.d {
        Some(d) => {
          let hash = rsa_hash(alg)
          match @lib.rsa_oaep_decrypt_with_or(wrapped, rsa.n, d, b"", hash) {
            Ok(cek) => cek
            Err(_) => raise DecryptionFailed
          }
        }
        None => raise BadStructure("RSA private key is missing d")
      }
    _ => raise AlgMismatch("RSAES-OAEP requires an RSA key")
  }
}

///|
fn is_kw_alg(alg : CoseAlg) -> Bool {
  match alg.normalize() {
    CoseAlg::A128KW | CoseAlg::A192KW | CoseAlg::A256KW => true
    _ => false
  }
}

///|
fn header_is_empty(header : Header) -> Bool {
  if header.alg is Some(_) {
    return false
  }
  if header.crit.length() != 0 {
    return false
  }
  if header.content_type is Some(_) {
    return false
  }
  if header.kid is Some(_) {
    return false
  }
  if header.iv is Some(_) {
    return false
  }
  if header.partial_iv is Some(_) {
    return false
  }
  if header.salt is Some(_) {
    return false
  }
  if header.party_u_id is Some(_) {
    return false
  }
  if header.party_u_nonce is Some(_) {
    return false
  }
  if header.party_u_other is Some(_) {
    return false
  }
  if header.party_v_id is Some(_) {
    return false
  }
  if header.party_v_nonce is Some(_) {
    return false
  }
  if header.party_v_other is Some(_) {
    return false
  }
  if header.epk is Some(_) {
    return false
  }
  if header.static_key is Some(_) {
    return false
  }
  if header.static_kid is Some(_) {
    return false
  }
  header.rest.length() == 0
}

///|
fn require_empty_protected(
  recipient : Recipient,
  alg : CoseAlg,
) -> Unit raise CoseError {
  // RFC 9052 §3: an empty protected map may be h'' or h'a0'.
  // RFC 9052 §5.4 / §8.5.1 / §8.5.2 and RFC 9053 §6.1.1 / §6.2.1
  // require the map itself to be empty for direct and AES-KW.
  // The received bstr is kept either way.
  let bare_direct = alg.normalize() == CoseAlg::Direct
  if (bare_direct || is_kw_alg(alg)) &&
    !header_is_empty(recipient.protected_header.header) {
    raise BadStructure("direct and AES Key Wrap protected map must be empty")
  }
}

///|
fn kw_key_ops(key : CoseKey, seal : Bool) -> Unit raise CoseError {
  let ops = match key {
    CoseKey::Sym(sym) => sym.key_ops
    _ => raise AlgMismatch("AES Key Wrap requires a symmetric key")
  }
  if ops.length() == 0 {
    return
  }
  let primary : Int32 = if seal { 5 } else { 6 }
  let alternate : Int32 = if seal { 3 } else { 4 }
  for i = 0; i < ops.length(); i = i + 1 {
    if ops[i] == primary || ops[i] == alternate {
      return
    }
  }
  raise BadStructure("key_ops does not allow AES Key Wrap")
}

///|
fn reject_mixed_recipient_modes(algs : Array[CoseAlg]) -> Unit raise CoseError {
  let mut direct = false
  let mut other = false
  for i = 0; i < algs.length(); i = i + 1 {
    if is_direct_alg(algs[i]) {
      direct = true
    } else {
      other = true
    }
  }
  if direct && other {
    raise BadStructure("direct recipient must be the only mode at this layer")
  }
}

///|
fn input_alg(input : RecipientInput) -> CoseAlg raise CoseError {
  match input.unprotected.alg {
    Some(value) => value.normalize()
    None => raise BadStructure("recipient alg is missing")
  }
}

///|
fn seal_recipient(
  input : RecipientInput,
  parent_key : Bytes,
  parent_alg : CoseAlg,
  depth : Int32,
  nodes : Array[Int32],
) -> Recipient raise CoseError {
  if depth > recipient_max_depth {
    raise BadStructure("recipient nesting is too deep")
  }
  note_recipient(nodes)
  let alg = input_alg(input)
  check_key_alg(input.key.algorithm(), alg)
  let protected_header = Protected::from_header(input.prot)
  reject_shared_header_labels(protected_header.header, input.unprotected)
  if input.recipients.length() > 0 {
    if is_direct_alg(alg) || is_ecdh_wrap(alg) || is_rsa_oaep(alg) {
      raise BadStructure(
        "this recipient algorithm cannot have nested recipients",
      )
    }
    if !is_kw_alg(alg) {
      raise UnsupportedAlg(alg.name())
    }
    let child_algs : Array[CoseAlg] = []
    for i = 0; i < input.recipients.length(); i = i + 1 {
      child_algs.push(input_alg(input.recipients[i]))
    }
    reject_mixed_recipient_modes(child_algs)
    kw_key_ops(input.key, true)
    let kek = symmetric_key(input.key)
    let nested : Array[Recipient] = []
    for i = 0; i < input.recipients.length(); i = i + 1 {
      nested.push(
        seal_recipient(input.recipients[i], kek, alg, depth + 1, nodes),
      )
    }
    {
      protected_header,
      unprotected: input.unprotected,
      ciphertext: Some(kw_wrap(alg, kek, parent_key)),
      recipients: nested,
    }
  } else if alg.normalize() == CoseAlg::Direct {
    if !bytes_eq(symmetric_key(input.key), parent_key) {
      raise BadStructure("direct recipient key is not the next layer key")
    }
    {
      protected_header,
      unprotected: input.unprotected,
      ciphertext: Some(bytes_empty()),
      recipients: [],
    }
  } else if is_kw_alg(alg) {
    kw_key_ops(input.key, true)
    {
      protected_header,
      unprotected: input.unprotected,
      ciphertext: Some(kw_wrap(alg, symmetric_key(input.key), parent_key)),
      recipients: [],
    }
  } else if is_rsa_oaep(alg) {
    rsa_key_ops(input.key, true)
    let seed = match input.seed {
      Some(value) => value
      None => raise BadStructure("RSAES-OAEP seed is missing")
    }
    {
      protected_header,
      unprotected: input.unprotected,
      ciphertext: Some(rsa_oaep_seal(input.key, parent_key, seed, alg)),
      recipients: [],
    }
  } else if is_hkdf_direct(alg) || is_ecdh_direct(alg) || is_ecdh_wrap(alg) {
    seal_kdf_recipient(input, alg, protected_header, parent_key, parent_alg)
  } else {
    raise UnsupportedAlg(alg.name())
  }
}

///|
fn seal_kdf_recipient(
  input : RecipientInput,
  alg : CoseAlg,
  protected_header : Protected,
  parent_key : Bytes,
  parent_alg : CoseAlg,
) -> Recipient raise CoseError {
  let static_agreement = !is_ephemeral(alg)
  if is_hkdf_direct(alg) || (static_agreement && !is_hkdf_direct(alg)) {
    require_kdf_uniqueness(protected_header.header, input.unprotected)
  }
  let mut unprot = input.unprotected
  let ikm = if is_hkdf_direct(alg) {
    derive_key_ops(input.key, true)
    symmetric_key(input.key)
  } else {
    let agreement = match input.agreement {
      Some(key) => key
      None => raise BadStructure("ECDH sender private key is missing")
    }
    check_key_alg(agreement.algorithm(), alg)
    derive_key_ops(agreement, true)
    derive_key_ops(input.key, false)
    let shared = ecdh_shared(agreement, input.key)
    let public_key = ecdh_public_key(agreement)
    if is_ephemeral(alg) {
      match prefer_key(protected_header.header.epk, unprot.epk) {
        Some(existing) =>
          if !keys_equal_public(existing, public_key) {
            raise BadStructure("ephemeral key does not match the sender scalar")
          }
        None => unprot = { ..unprot, epk: Some(public_key), }
      }
    } else {
      match prefer_key(protected_header.header.static_key, unprot.static_key) {
        Some(existing) =>
          if !keys_equal_public(existing, public_key) {
            raise BadStructure("static key does not match the sender scalar")
          }
        None => unprot = { ..unprot, static_key: Some(public_key), }
      }
    }
    shared
  }
  let context_alg = if is_ecdh_wrap(alg) {
    ecdh_wrap_alg(alg)
  } else {
    parent_alg
  }
  let key_len = if is_ecdh_wrap(alg) {
    ecdh_wrap_len(alg)
  } else {
    material_len(parent_alg)
  }
  let derived = kdf_material(
    alg,
    protected_header.header,
    unprot,
    protected_header.raw,
    ikm,
    context_alg,
    key_len,
    None,
    None,
  )
  if is_ecdh_wrap(alg) {
    {
      protected_header,
      unprotected: unprot,
      ciphertext: Some(kw_wrap(context_alg, derived, parent_key)),
      recipients: [],
    }
  } else if bytes_eq(derived, parent_key) {
    {
      protected_header,
      unprotected: unprot,
      ciphertext: Some(bytes_empty()),
      recipients: [],
    }
  } else {
    raise BadStructure("derived key does not match the next layer key")
  }
}

///|
fn seal_recipients(
  inputs : Array[RecipientInput],
  parent_key : Bytes,
  parent_alg : CoseAlg,
) -> Array[Recipient] raise CoseError {
  if inputs.length() == 0 {
    raise BadStructure("COSE message needs at least one recipient")
  }
  let algs : Array[CoseAlg] = []
  for i = 0; i < inputs.length(); i = i + 1 {
    algs.push(input_alg(inputs[i]))
  }
  reject_mixed_recipient_modes(algs)
  let nodes = [0]
  let built : Array[Recipient] = []
  for i = 0; i < inputs.length(); i = i + 1 {
    built.push(seal_recipient(inputs[i], parent_key, parent_alg, 1, nodes))
  }
  built
}

///|
fn decode_recipient_list(
  value : @cbor.CborValue,
  depth : Int32,
  nodes : Array[Int32],
) -> Array[Recipient] raise CoseError {
  match cbor_unwrap(value) {
    @cbor.Array(rows) => {
      if rows.length() == 0 {
        raise BadStructure("nested recipients must not be empty")
      }
      let out : Array[Recipient] = []
      for i = 0; i < rows.length(); i = i + 1 {
        out.push(decode_recipient(rows[i], depth, nodes))
      }
      out
    }
    _ => raise BadStructure("recipients must be an array")
  }
}

///|
fn decode_recipient(
  value : @cbor.CborValue,
  depth : Int32,
  nodes : Array[Int32],
) -> Recipient raise CoseError {
  if depth > recipient_max_depth {
    raise BadStructure("recipient nesting is too deep")
  }
  note_recipient(nodes)
  match cbor_unwrap(value) {
    @cbor.Array(row) => {
      if row.length() != 3 && row.length() != 4 {
        raise BadStructure("COSE_recipient must have 3 or 4 items")
      }
      let raw = cbor_bstr_field(row[0], "recipient protected header")
      let ciphertext = match cbor_unwrap(row[2]) {
        @cbor.Bytes(b) => Some(b)
        @cbor.Simple(22) => None
        _ => raise BadStructure("recipient ciphertext must be a bstr or null")
      }
      let protected_header = Protected::from_raw(raw)
      let unprotected = Header::from_cbor(row[1])
      reject_shared_header_labels(protected_header.header, unprotected)
      let nested = if row.length() == 3 {
        []
      } else {
        decode_recipient_list(row[3], depth + 1, nodes)
      }
      { protected_header, unprotected, ciphertext, recipients: nested, }
    }
    _ => raise BadStructure("COSE_recipient must be an array")
  }
}

///|
fn decode_recipients(
  value : @cbor.CborValue,
) -> Array[Recipient] raise CoseError {
  decode_recipient_list(value, 1, [0])
}

///|
fn encode_recipient(recipient : Recipient) -> @cbor.CborValue {
  let items : Array[@cbor.CborValue] = [
    @cbor.Bytes(recipient.protected_header.raw),
    recipient.unprotected.to_cbor(),
    payload_to_cbor(recipient.ciphertext),
  ]
  if recipient.recipients.length() > 0 {
    items.push(encode_recipients(recipient.recipients))
  }
  @cbor.Array(items)
}

///|
fn encode_recipients(recipients : Array[Recipient]) -> @cbor.CborValue {
  let rows : Array[@cbor.CborValue] = []
  for i = 0; i < recipients.length(); i = i + 1 {
    rows.push(encode_recipient(recipients[i]))
  }
  @cbor.Array(rows)
}

///|
fn unwrap_kw(
  alg : CoseAlg,
  kek : Bytes,
  ciphertext : Bytes?,
) -> Bytes raise CoseError {
  match ciphertext {
    Some(wrapped) =>
      if wrapped.length() == 0 {
        raise BadStructure("AES Key Wrap recipient is missing ciphertext")
      } else {
        kw_unwrap(alg, kek, wrapped)
      }
    None => raise BadStructure("AES Key Wrap recipient is missing ciphertext")
  }
}

///|
fn direct_key(key : CoseKey, ciphertext : Bytes?) -> Bytes raise CoseError {
  match ciphertext {
    Some(raw) =>
      if raw.length() != 0 {
        raise BadStructure("direct recipient ciphertext must be empty")
      }
    None => raise BadStructure("direct recipient ciphertext must be h''")
  }
  symmetric_key(key)
}

///|
fn remember_error(errors : Array[CoseError], err : CoseError) -> Unit {
  match err {
    BadStructure(msg) =>
      if msg == "no recipient matched the key" && errors.length() != 0 {
        return
      }
    _ => ()
  }
  if errors.length() == 0 {
    errors.push(err)
  } else {
    errors[0] = err
  }
}

///|
fn collect_layer(
  recipients : Array[Recipient],
  keys : Array[CoseKey],
  depth : Int32,
  found : Array[Bytes],
  matched : Array[Int32],
  errors : Array[CoseError],
  nodes : Array[Int32],
  parent_alg : CoseAlg?,
) -> Unit raise CoseError {
  if depth > recipient_max_depth {
    raise BadStructure("recipient nesting is too deep")
  }
  let algs : Array[CoseAlg] = []
  for i = 0; i < recipients.length(); i = i + 1 {
    algs.push(
      resolve_alg(
        recipients[i].protected_header.header,
        recipients[i].unprotected,
      ),
    )
  }
  reject_mixed_recipient_modes(algs)
  for i = 0; i < recipients.length(); i = i + 1 {
    collect_recipient(
      recipients[i],
      keys,
      depth,
      found,
      matched,
      nodes,
      parent_alg,
    ) catch {
      err => remember_error(errors, err)
    }
  }
}

///|
fn collect_recipient(
  recipient : Recipient,
  keys : Array[CoseKey],
  depth : Int32,
  found : Array[Bytes],
  matched : Array[Int32],
  nodes : Array[Int32],
  parent_alg : CoseAlg?,
) -> Unit raise CoseError {
  note_recipient(nodes)
  let alg = resolve_alg(
    recipient.protected_header.header,
    recipient.unprotected,
  )
  require_empty_protected(recipient, alg)
  if recipient.recipients.length() > 0 {
    if is_direct_alg(alg) {
      raise BadStructure("direct recipient cannot have nested recipients")
    }
    if !is_kw_alg(alg) {
      raise UnsupportedAlg(alg.name())
    }
    // The KEK is the output of the next recipient layer. It is not a leaf key.
    let keks : Array[Bytes] = []
    let child_matched = [0]
    let child_errors : Array[CoseError] = []
    collect_layer(
      recipient.recipients,
      keys,
      depth + 1,
      keks,
      child_matched,
      child_errors,
      nodes,
      Some(alg),
    )
    if child_matched[0] != 0 {
      matched[0] = 1
    }
    if keks.length() == 0 {
      if child_errors.length() == 0 {
        raise BadStructure("no recipient matched the key")
      }
      raise child_errors[0]
    }
    let mut opened = false
    for i = 0; i < keks.length(); i = i + 1 {
      try {
        found.push(unwrap_kw(alg, keks[i], recipient.ciphertext))
        opened = true
      } catch {
        _ => ()
      }
    }
    if !opened {
      raise DecryptionFailed
    }
  } else if alg.normalize() == CoseAlg::Direct {
    let mut saw = false
    let mut opened = false
    let mut failed : CoseError = DecryptionFailed
    for i = 0; i < keys.length(); i = i + 1 {
      if !kid_matches(keys[i], recipient) {
        continue
      }
      saw = true
      matched[0] = 1
      try {
        check_key_alg(keys[i].algorithm(), alg)
        found.push(direct_key(keys[i], recipient.ciphertext))
        opened = true
      } catch {
        err => failed = err
      }
    }
    if !saw {
      raise BadStructure("no recipient matched the key")
    }
    if !opened {
      raise failed
    }
  } else if is_kw_alg(alg) {
    let mut saw = false
    let mut opened = false
    let mut failed : CoseError = DecryptionFailed
    for i = 0; i < keys.length(); i = i + 1 {
      if !kid_matches(keys[i], recipient) {
        continue
      }
      saw = true
      matched[0] = 1
      try {
        check_key_alg(keys[i].algorithm(), alg)
        kw_key_ops(keys[i], false)
        found.push(unwrap_kw(alg, symmetric_key(keys[i]), recipient.ciphertext))
        opened = true
      } catch {
        err => failed = err
      }
    }
    if !saw {
      raise BadStructure("no recipient matched the key")
    }
    if !opened {
      raise failed
    }
  } else if is_rsa_oaep(alg) {
    let mut saw = false
    let mut opened = false
    let mut failed : CoseError = DecryptionFailed
    for i = 0; i < keys.length(); i = i + 1 {
      if !kid_matches(keys[i], recipient) {
        continue
      }
      saw = true
      matched[0] = 1
      try {
        check_key_alg(keys[i].algorithm(), alg)
        rsa_key_ops(keys[i], false)
        found.push(rsa_oaep_open(keys[i], recipient.ciphertext, alg))
        opened = true
      } catch {
        err => failed = err
      }
    }
    if !saw {
      raise BadStructure("no recipient matched the key")
    }
    if !opened {
      raise failed
    }
  } else if is_hkdf_direct(alg) || is_ecdh_direct(alg) || is_ecdh_wrap(alg) {
    open_kdf_recipient(recipient, alg, keys, parent_alg, found, matched)
  } else {
    raise UnsupportedAlg(alg.name())
  }
}

///|
fn sender_public(
  recipient : Recipient,
  alg : CoseAlg,
  keys : Array[CoseKey],
) -> CoseKey raise CoseError {
  if is_ephemeral(alg) {
    match
      prefer_key(
        recipient.protected_header.header.epk,
        recipient.unprotected.epk,
      ) {
      Some(key) => key
      None => raise BadStructure("ECDH-ES ephemeral key is missing")
    }
  } else {
    match
      prefer_key(
        recipient.protected_header.header.static_key,
        recipient.unprotected.static_key,
      ) {
      Some(key) => key
      None => {
        let kid = prefer_bytes(
          recipient.protected_header.header.static_kid,
          recipient.unprotected.static_kid,
        )
        match kid {
          None => raise BadStructure("ECDH-SS static key is missing")
          Some(want) => {
            for i = 0; i < keys.length(); i = i + 1 {
              match keys[i].kid() {
                Some(have) => if bytes_eq(have, want) { return keys[i] }
                None => ()
              }
            }
            raise BadStructure("ECDH-SS static key is missing")
          }
        }
      }
    }
  }
}

///|
fn push_derived(
  alg : CoseAlg,
  recipient : Recipient,
  ikm : Bytes,
  parent_alg : CoseAlg?,
  found : Array[Bytes],
) -> Unit raise CoseError {
  let context_alg = if is_ecdh_wrap(alg) {
    ecdh_wrap_alg(alg)
  } else {
    match parent_alg {
      Some(value) => value
      None => raise BadStructure("missing alg header")
    }
  }
  let key_len = if is_ecdh_wrap(alg) {
    ecdh_wrap_len(alg)
  } else {
    match parent_alg {
      Some(value) => material_len(value)
      None => raise BadStructure("missing alg header")
    }
  }
  let derived = kdf_material(
    alg,
    recipient.protected_header.header,
    recipient.unprotected,
    recipient.protected_header.raw,
    ikm,
    context_alg,
    key_len,
    None,
    None,
  )
  if is_ecdh_wrap(alg) {
    found.push(unwrap_kw(context_alg, derived, recipient.ciphertext))
  } else {
    if !is_direct_alg(alg) {
      raise UnsupportedAlg(alg.name())
    }
    match recipient.ciphertext {
      Some(raw) =>
        if raw.length() != 0 {
          raise BadStructure("direct recipient ciphertext must be empty")
        }
      None => raise BadStructure("direct recipient ciphertext must be h''")
    }
    found.push(derived)
  }
}

///|
fn open_kdf_recipient(
  recipient : Recipient,
  alg : CoseAlg,
  keys : Array[CoseKey],
  parent_alg : CoseAlg?,
  found : Array[Bytes],
  matched : Array[Int32],
) -> Unit raise CoseError {
  if is_hkdf_direct(alg) || !is_ephemeral(alg) {
    require_kdf_uniqueness(
      recipient.protected_header.header,
      recipient.unprotected,
    )
  }
  if is_hkdf_direct(alg) {
    let mut saw = false
    let mut opened = false
    let mut failed : CoseError = DecryptionFailed
    for i = 0; i < keys.length(); i = i + 1 {
      if !kid_matches(keys[i], recipient) {
        continue
      }
      saw = true
      matched[0] = 1
      try {
        check_key_alg(keys[i].algorithm(), alg)
        derive_key_ops(keys[i], true)
        push_derived(alg, recipient, symmetric_key(keys[i]), parent_alg, found)
        opened = true
      } catch {
        err => failed = err
      }
    }
    if !saw {
      raise BadStructure("no recipient matched the key")
    }
    if !opened {
      raise failed
    }
  } else {
    let peer = sender_public(recipient, alg, keys)
    let mut saw = false
    let mut opened = false
    let mut failed : CoseError = DecryptionFailed
    for i = 0; i < keys.length(); i = i + 1 {
      if !kid_matches(keys[i], recipient) {
        continue
      }
      saw = true
      matched[0] = 1
      try {
        check_key_alg(keys[i].algorithm(), alg)
        derive_key_ops(keys[i], true)
        let shared = ecdh_shared(keys[i], peer)
        push_derived(alg, recipient, shared, parent_alg, found)
        opened = true
      } catch {
        err => failed = err
      }
    }
    if !saw {
      raise BadStructure("no recipient matched the key")
    }
    if !opened {
      raise failed
    }
  }
}

///|
fn content_keys(
  recipients : Array[Recipient],
  keys : Array[CoseKey],
  parent_alg : CoseAlg?,
) -> Array[Bytes] raise CoseError {
  if keys.length() == 0 {
    raise BadStructure("no recipient key")
  }
  let found : Array[Bytes] = []
  let matched = [0]
  let errors : Array[CoseError] = []
  collect_layer(recipients, keys, 1, found, matched, errors, [0], parent_alg)
  if found.length() == 0 {
    if errors.length() != 0 {
      raise errors[0]
    }
    if matched[0] == 0 {
      raise BadStructure("no recipient matched the key")
    }
    raise DecryptionFailed
  }
  found
}

///|
fn base_iv_for(keys : Array[CoseKey], cek : Bytes) -> Bytes? {
  for i = 0; i < keys.length(); i = i + 1 {
    match keys[i] {
      CoseKey::Sym(sym) => if bytes_eq(sym.k, cek) { return sym.base_iv }
      _ => ()
    }
  }
  None
}