/* NSIGNER_HEADERLESS_DECLS_BEGIN */
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
#include <cJSON.h>
#include "otp_pad.h"
#include "libotppad.h"

/* from secure_mem.h */


/*
 * Secure memory buffer — mlock'd, zeroized on free.
 * Used for mnemonic phrases, private keys, and any sensitive material.
 */
typedef struct {
    void *data;       /* pointer to locked allocation */
    size_t size;      /* usable size in bytes */
    int locked;       /* 1 if mlock succeeded */
} secure_buf_t;

/* Allocate a secure buffer of `size` bytes. Returns 0 on success, -1 on failure. */
int secure_buf_alloc(secure_buf_t *buf, size_t size);

/* Zeroize and free a secure buffer. Always succeeds (idempotent). */
void secure_buf_free(secure_buf_t *buf);

/* Zeroize `len` bytes at `ptr` in a way the compiler cannot optimize away. */
void secure_memzero(void *ptr, size_t len);


/* from mnemonic.h */


/* Maximum mnemonic length: 24 words * 10 chars avg + spaces + null = 256 is safe */
#define MNEMONIC_MAX_LEN 256

/*
 * Mnemonic state — holds the loaded mnemonic in secure memory.
 * Only one mnemonic is active at a time per process.
 */
typedef struct {
    secure_buf_t buf;       /* secure storage for the mnemonic string */
    int loaded;             /* 1 if a mnemonic is currently loaded */
    int word_count;         /* 12, 15, 18, 21, or 24 */
} mnemonic_state_t;

/* Initialize mnemonic state (must be called before use). */
void mnemonic_init(mnemonic_state_t *state);

/* Load a mnemonic string into secure memory. Validates word count (12/15/18/21/24).
 * Returns 0 on success, -1 on invalid input, -2 on memory error. */
int mnemonic_load(mnemonic_state_t *state, const char *phrase);

/* Zeroize and unload the mnemonic. Idempotent. */
void mnemonic_unload(mnemonic_state_t *state);

/* Check if a mnemonic is currently loaded. */
int mnemonic_is_loaded(const mnemonic_state_t *state);

/* Get the mnemonic string (only valid while loaded). Returns NULL if not loaded. */
const char *mnemonic_get_phrase(const mnemonic_state_t *state);

/* Generate a new BIP-39 mnemonic phrase (12/15/18/21/24 words) into out.
 * Returns 0 on success, -1 on invalid arguments or generation failure. */
int mnemonic_generate(int word_count, char *out, size_t out_len);


/* from role_table.h */


/* Maximum limits */
#define ROLE_NAME_MAX 64
#define ROLE_PATH_MAX 128
#define ROLE_PURPOSE_MAX 32
#define ROLE_CURVE_MAX 16
#define ROLE_PUBKEY_HEX_MAX 66 /* 64 hex chars + null + pad */
#define ROLE_TABLE_MAX_ENTRIES 256

/* Purpose enum for fast comparison (string form kept for config/display) */
typedef enum {
    PURPOSE_NOSTR = 0,
    PURPOSE_BITCOIN,
    PURPOSE_SSH,
    PURPOSE_AGE,
    PURPOSE_FIPS,
    PURPOSE_PQ_SIG,      /* post-quantum signatures (ML-DSA, SLH-DSA) */
    PURPOSE_PQ_KEM,      /* post-quantum key encapsulation (ML-KEM) */
    PURPOSE_UNKNOWN
} role_purpose_t;

/* Curve enum */
typedef enum {
    CURVE_SECP256K1 = 0,
    CURVE_ED25519,
    CURVE_X25519,
    CURVE_ML_DSA_65,
    CURVE_SLH_DSA_128S,
    CURVE_ML_KEM_768,
    CURVE_UNKNOWN
} role_curve_t;

/* Selector type — how this role's key is addressed */
typedef enum {
    SELECTOR_NOSTR_INDEX, /* uses nostr_index shorthand */
    SELECTOR_ROLE_PATH    /* uses explicit full path */
} role_selector_type_t;

/* A single role entry */
typedef struct {
    char name[ROLE_NAME_MAX];
    char purpose_str[ROLE_PURPOSE_MAX];
    char curve_str[ROLE_CURVE_MAX];
    role_purpose_t purpose;
    role_curve_t curve;
    role_selector_type_t selector_type;
    int nostr_index;                         /* valid if selector_type == SELECTOR_NOSTR_INDEX */
    char role_path[ROLE_PATH_MAX];           /* valid if selector_type == SELECTOR_ROLE_PATH */
    char pubkey_hex[ROLE_PUBKEY_HEX_MAX];    /* filled after derivation, empty until then */
    int derived;                             /* 1 if pubkey_hex has been populated */
} role_entry_t;

/* The role table */
typedef struct {
    role_entry_t entries[ROLE_TABLE_MAX_ENTRIES];
    int count;
} role_table_t;

/* Initialize an empty role table */
void role_table_init(role_table_t *table);

/* Add a role entry. Returns 0 on success, -1 if table full, -2 if name duplicate. */
int role_table_add(role_table_t *table, const role_entry_t *entry);

/* Find a role by name. Returns pointer to entry or NULL. */
role_entry_t *role_table_find_by_name(role_table_t *table, const char *name);

/* Find a role by nostr_index. Returns pointer or NULL. */
role_entry_t *role_table_find_by_nostr_index(role_table_t *table, int index);

/* Find a role by role_path. Returns pointer or NULL. */
role_entry_t *role_table_find_by_path(role_table_t *table, const char *path);

/* Get the default role (named "main"). Returns pointer or NULL if no "main" role. */
role_entry_t *role_table_get_default(role_table_t *table);

/* Parse purpose string to enum */
role_purpose_t role_purpose_from_str(const char *s);

/* Parse curve string to enum */
role_curve_t role_curve_from_str(const char *s);

/* Purpose enum to string */
const char *role_purpose_to_str(role_purpose_t p);

/* Curve enum to string */
const char *role_curve_to_str(role_curve_t c);


/* from selector.h */


/* Error codes for selector resolution */
#define SELECTOR_OK                 0
#define SELECTOR_ERR_AMBIGUOUS     -1   /* multiple selectors specified */
#define SELECTOR_ERR_NOT_FOUND     -2   /* no matching role in table */
#define SELECTOR_ERR_NO_DEFAULT    -3   /* no selector given and no "main" role exists */

/* Parsed selector from a request's options object */
typedef struct {
    int has_role;          /* 1 if "role" field was present */
    char role_name[ROLE_NAME_MAX];

    int has_nostr_index;   /* 1 if "nostr_index" field was present */
    int nostr_index;

    int has_role_path;     /* 1 if "role_path" field was present */
    char role_path[ROLE_PATH_MAX];
} selector_request_t;

/* Initialize a selector request (all fields zeroed/unset) */
void selector_request_init(selector_request_t *req);

/*
 * Resolve a selector request against the role table.
 * On success (returns SELECTOR_OK), *out points to the matched role_entry_t.
 * On failure, returns one of the SELECTOR_ERR_* codes and *out is NULL.
 */
int selector_resolve(const selector_request_t *req, role_table_t *table, role_entry_t **out);

/*
 * Return a human-readable error string for a selector error code.
 */
const char *selector_strerror(int err);


/* from enforcement.h */


/* Error codes */
#define ENFORCE_OK                0
#define ENFORCE_ERR_PURPOSE      -1 /* purpose mismatch */
#define ENFORCE_ERR_CURVE        -2 /* curve mismatch */
#define ENFORCE_ERR_UNKNOWN_VERB -3 /* verb not recognized */
#define ENFORCE_ERR_ALGORITHM  -4 /* algorithm not valid for verb */

/* New algorithm-based verb defines (algorithm is a parameter, not implicit) */
#define VERB_SIGN              "sign"
#define VERB_VERIFY            "verify"
#define VERB_ENCAPSULATE       "encapsulate"
#define VERB_DECAPSULATE       "decapsulate"
#define VERB_DERIVE_SHARED     "derive_shared_secret"

#define ENFORCE_ERR_ALGORITHM  -4 /* algorithm not valid for verb */

/* New algorithm-based verb defines (algorithm is a parameter, not implicit) */
#define VERB_SIGN              "sign"
#define VERB_VERIFY            "verify"
#define VERB_ENCAPSULATE       "encapsulate"
#define VERB_DECAPSULATE       "decapsulate"
#define VERB_DERIVE_SHARED     "derive_shared_secret"


/* Known verbs */
#define VERB_SIGN_EVENT     "sign_event"
#define VERB_GET_PUBLIC_KEY "get_public_key"
#define VERB_NIP44_ENCRYPT  "nip44_encrypt"
#define VERB_NIP44_DECRYPT  "nip44_decrypt"
#define VERB_NIP04_ENCRYPT  "nip04_encrypt"
#define VERB_NIP04_DECRYPT  "nip04_decrypt"
#define VERB_MINE_EVENT     "mine_event"
#define VERB_SIGN_DATA      "sign_data"
#define VERB_VERIFY_SIG     "verify_signature"
#define VERB_SSH_SIGN       "ssh_sign"
#define VERB_KEM_ENCAPS     "kem_encapsulate"
#define VERB_KEM_DECAPS     "kem_decapsulate"
#define VERB_OTP_ENCRYPT    "otp_encrypt"
#define VERB_OTP_DECRYPT    "otp_decrypt"

/*
 * Check whether `verb` is allowed to execute against `role`.
 * Returns ENFORCE_OK if allowed, or an ENFORCE_ERR_* code.
 *
 * The enforcement rules are:
 *   - All nostr verbs (sign_event, get_public_key, nip44_*, nip04_*) require:
 *     purpose == PURPOSE_NOSTR and curve == CURVE_SECP256K1
 *   - Unknown verbs return ENFORCE_ERR_UNKNOWN_VERB (fail-closed).
 */
int enforce_verb_role(const char *verb, const role_entry_t *role);

/*
 * Return a human-readable error string for an enforcement error code.
 */
const char *enforce_strerror(int err);


/* from policy.h */


#define POLICY_MAX_ENTRIES    32
#define POLICY_MAX_VERBS      16
#define POLICY_MAX_ROLES      16
#define POLICY_MAX_PURPOSES   8
#define POLICY_VERB_MAX_LEN   32
#define POLICY_CALLER_MAX_LEN 160
#define POLICY_MAX_ALGS       16
#define POLICY_MAX_ALGS       16

/* Prompt behavior */
typedef enum {
    PROMPT_NEVER = 0,
    PROMPT_FIRST_PER_BOOT,
    PROMPT_EVERY_REQUEST,
    PROMPT_DENY
} prompt_mode_t;

typedef enum {
    POLICY_SOURCE_DEFAULT = 0,   /* the catch-all entry */
    POLICY_SOURCE_PREAPPROVE,    /* from --preapprove CLI flag */
    POLICY_SOURCE_SESSION_GRANT  /* from prompt [a] during session */
} policy_source_t;

/* A single policy entry */
typedef struct {
    char caller[POLICY_CALLER_MAX_LEN];   /* e.g. "uid:1000" or "*" for any */
    char verbs[POLICY_MAX_VERBS][POLICY_VERB_MAX_LEN];
    int verb_count;
    char roles[POLICY_MAX_ROLES][ROLE_NAME_MAX];
    int role_count;
    char purposes[POLICY_MAX_PURPOSES][ROLE_PURPOSE_MAX];
    int purpose_count;
    /* Algorithm-based (new) */
    char algorithms[16][32];  /* algorithm names; POLICY_MAX_ALGS */
    int alg_count;
    int index_min;            /* -1 = any */
    int index_max;            /* -1 = any */
    /* Common */
    prompt_mode_t prompt;
    policy_source_t source;
} policy_entry_t;

/* Policy table */
typedef struct {
    policy_entry_t entries[POLICY_MAX_ENTRIES];
    int count;
} policy_table_t;

/* Policy check result */
#define POLICY_ALLOW     0
#define POLICY_DENY     -1
#define POLICY_PROMPT   -2   /* would need user confirmation */
#define POLICY_NO_MATCH -3   /* no policy entry matched (fail-closed = deny) */

/* Initialize policy table */
void policy_table_init(policy_table_t *table);

/* Initialize default policy: allow same-uid, deny others */
void policy_init_default(policy_table_t *table, uid_t owner_uid);

/* Add a policy entry. Returns 0 on success, -1 if full. */
int policy_table_add(policy_table_t *table, const policy_entry_t *entry);

/*
 * Check whether caller_id is allowed to invoke `verb` on `role_name` with given `purpose`.
 * Returns POLICY_ALLOW, POLICY_DENY, POLICY_PROMPT, or POLICY_NO_MATCH.
 */
int policy_check(const policy_table_t *table, const char *caller_id,
                 const char *verb, const char *role_name, const char *purpose,
                 policy_source_t *out_source);

/* Check whether caller_id is allowed to invoke `verb` with the given
 * algorithm and index (algorithm-based policy). Returns POLICY_ALLOW,
 * POLICY_DENY, POLICY_PROMPT, or POLICY_NO_MATCH. */
int policy_check_algorithm(const policy_table_t *table, const char *caller_id,
                           const char *verb, const char *algorithm, int index,
                           policy_source_t *out_source);

/* Check whether caller_id is allowed to invoke `verb` with the given
 * algorithm and index (algorithm-based policy). Returns POLICY_ALLOW,
 * POLICY_DENY, POLICY_PROMPT, or POLICY_NO_MATCH. */
int policy_check_algorithm(const policy_table_t *table, const char *caller_id,
                           const char *verb, const char *algorithm, int index,
                           policy_source_t *out_source);

/* Parse prompt mode from string */
prompt_mode_t prompt_mode_from_str(const char *s);

/* Prompt mode to string */
const char *prompt_mode_to_str(prompt_mode_t m);


/* from pq_crypto.h */


/* Algorithm identifiers */
typedef enum {
    CRYPTO_ALG_SECP256K1 = 0,   /* existing, Nostr */
    CRYPTO_ALG_ED25519,         /* new, SSH signatures */
    CRYPTO_ALG_X25519,          /* new, key agreement */
    CRYPTO_ALG_ML_DSA_65,       /* new, PQ signatures */
    CRYPTO_ALG_SLH_DSA_128S,    /* new, PQ signatures */
    CRYPTO_ALG_ML_KEM_768,      /* new, PQ KEM */
    CRYPTO_ALG_UNKNOWN
} crypto_alg_t;

/* Key sizes for each algorithm (compile-time constants) */
typedef struct {
    size_t priv_key_len;
    size_t pub_key_len;
    size_t sig_len;           /* 0 for KEM */
    size_t ciphertext_len;    /* 0 for signatures */
    size_t shared_secret_len; /* 0 for signatures */
} crypto_alg_sizes_t;

/* Get size info for an algorithm. Returns NULL for CRYPTO_ALG_UNKNOWN. */
const crypto_alg_sizes_t *crypto_alg_get_sizes(crypto_alg_t alg);

/* Map role_curve_t + role_purpose_t to crypto_alg_t.
 * Returns CRYPTO_ALG_UNKNOWN for unsupported combinations. */
crypto_alg_t crypto_alg_from_role(role_curve_t curve, role_purpose_t purpose);

/* Convert crypto_alg_t to string. Returns NULL for unknown. */
const char *crypto_alg_to_str(crypto_alg_t alg);

/* Parse string to crypto_alg_t. Returns CRYPTO_ALG_UNKNOWN for unrecognized. */
crypto_alg_t crypto_alg_from_str(const char *s);

/* ed25519: derive keypair from a 32-byte seed.
 * priv_out and pub_out must be at least 32 bytes each.
 * Returns 0 on success, -1 on error. */
int crypto_ed25519_keygen_from_seed(const unsigned char *seed, size_t seed_len,
                                     unsigned char *priv_out, unsigned char *pub_out);

/* ed25519: sign a message. priv is 32-byte private key.
 * sig_out must be at least 64 bytes. Returns 0 on success, -1 on error. */
int crypto_ed25519_sign(const unsigned char *priv, size_t priv_len,
                         const unsigned char *msg, size_t msg_len,
                         unsigned char *sig_out, size_t *sig_out_len);

/* ed25519: verify a signature. pub is 32-byte public key.
 * Returns 0 on valid, 1 on invalid, -1 on error. */
int crypto_ed25519_verify(const unsigned char *pub, size_t pub_len,
                           const unsigned char *msg, size_t msg_len,
                           const unsigned char *sig, size_t sig_len);

/* x25519: derive keypair from a 32-byte seed.
 * priv_out and pub_out must be at least 32 bytes each.
 * Returns 0 on success, -1 on error. */
int crypto_x25519_keygen_from_seed(const unsigned char *seed, size_t seed_len,
                                    unsigned char *priv_out, unsigned char *pub_out);

/* x25519: derive shared secret from our private key and peer's public key.
 * shared_out must be at least 32 bytes. Returns 0 on success, -1 on error. */
int crypto_x25519_ecdh(const unsigned char *our_priv, size_t priv_len,
                        const unsigned char *peer_pub, size_t pub_len,
                        unsigned char *shared_out, size_t *shared_out_len);

/* Derive a 32-byte seed from a mnemonic using a BIP-44 path (SLIP-0010).
 * seed_out must be at least 32 bytes. Returns 0 on success, -1 on error. */
int crypto_derive_seed_from_mnemonic(const char *mnemonic, const char *path,
                                      unsigned char *seed_out, size_t seed_out_len);
/* ML-DSA-65: generate keypair from a 32-byte seed (deterministic).
 * priv_out must be at least 4032 bytes, pub_out at least 1952 bytes.
 * Returns 0 on success, -1 on error. */
int crypto_ml_dsa_65_keygen_from_seed(const unsigned char *seed, size_t seed_len,
                                       unsigned char *priv_out, unsigned char *pub_out);

/* ML-DSA-65: sign a message. priv is 4032-byte private key.
 * sig_out must be at least 3309 bytes. Returns 0 on success, -1 on error. */
int crypto_ml_dsa_65_sign(const unsigned char *priv, size_t priv_len,
                           const unsigned char *msg, size_t msg_len,
                           unsigned char *sig_out, size_t *sig_out_len);

/* ML-DSA-65: verify a signature. pub is 1952-byte public key.
 * Returns 0 on valid, 1 on invalid, -1 on error. */
int crypto_ml_dsa_65_verify(const unsigned char *pub, size_t pub_len,
                             const unsigned char *msg, size_t msg_len,
                             const unsigned char *sig, size_t sig_len);


/* SLH-DSA-128s: generate keypair from a 32-byte seed (deterministic).
 * priv_out must be at least 64 bytes, pub_out at least 32 bytes.
 * Returns 0 on success, -1 on error. */
int crypto_slh_dsa_128s_keygen_from_seed(const unsigned char *seed, size_t seed_len,
                                           unsigned char *priv_out, unsigned char *pub_out);

/* SLH-DSA-128s: sign a message. priv is 64-byte private key.
 * sig_out must be at least 7856 bytes. Returns 0 on success, -1 on error. */
int crypto_slh_dsa_128s_sign(const unsigned char *priv, size_t priv_len,
                               const unsigned char *msg, size_t msg_len,
                               unsigned char *sig_out, size_t *sig_out_len);
/* SLH-DSA-128s: verify a signature. pub is 32-byte public key.
* Returns 0 on valid, 1 on invalid, -1 on error. */
int crypto_slh_dsa_128s_verify(const unsigned char *pub, size_t pub_len,
                                const unsigned char *msg, size_t msg_len,
                                const unsigned char *sig, size_t sig_len);

/* ML-KEM-768: generate keypair from a 32-byte seed (deterministic). */
int crypto_ml_kem_768_keygen_from_seed(const unsigned char *seed, size_t seed_len,
                                         unsigned char *priv_out, unsigned char *pub_out);

/* ML-KEM-768: encapsulate. pub is 1184-byte public key.
 * ct_out must be at least 1088 bytes, ss_out at least 32 bytes. */
int crypto_ml_kem_768_encaps(const unsigned char *pub, size_t pub_len,
                               unsigned char *ct_out, unsigned char *ss_out);

/* ML-KEM-768: decapsulate. priv is 2400-byte secret key, ct is 1088-byte ciphertext. */
int crypto_ml_kem_768_decaps(const unsigned char *priv, size_t priv_len,
                               const unsigned char *ct, size_t ct_len,
                               unsigned char *ss_out);

/* Deterministic PRNG for PQ keygen (replaces PQClean randombytes()). */
void pq_drbg_init(const unsigned char *seed, size_t seed_len);
int  pq_drbg_randombytes(unsigned char *buf, size_t len);
void pq_drbg_zeroize(void);



/* from crypto.h */


/* Per-role derived key material (stored in secure memory) */
typedef struct {
    secure_buf_t private_key;   /* mlock'd, variable size per algorithm */
    secure_buf_t public_key;    /* mlock'd, variable size per algorithm */
    char pubkey_hex[8192];      /* hex-encoded public key (PQ pubkeys are large) */
    char npub[128];             /* bech32 npub (secp256k1 only, empty for others) */
    crypto_alg_t alg;           /* which algorithm this key was derived for */
    int valid;
} derived_key_t;

/* Key store — holds derived keys for all roles */
typedef struct {
    derived_key_t keys[ROLE_TABLE_MAX_ENTRIES];
    int count;
} key_store_t;

/* Derive keys for all roles in the table using the loaded mnemonic.
 * Populates key_store and sets role->pubkey_hex and role->derived for each role.
 * Only derives for roles with purpose=nostr and curve=secp256k1 (for now).
 * Returns number of keys derived, or -1 on error. */
int crypto_derive_all(key_store_t *store, role_table_t *table, const mnemonic_state_t *mnemonic);

/* Get the derived private key for a role (by table index). Returns NULL if not derived. */
const unsigned char *crypto_get_private_key(const key_store_t *store, int role_index);

/* Get the derived public key hex for a role. Returns NULL if not derived. */
const char *crypto_get_pubkey_hex(const key_store_t *store, int role_index);

/* Sign a Nostr event. event_json is the unsigned event JSON string.
 * Returns a newly-allocated string containing the signed event JSON, or NULL on error.
 * Caller must free() the returned string. */
char *crypto_sign_event(const key_store_t *store, int role_index, const char *event_json);

/* Mine a Nostr event with NIP-13 proof-of-work, then sign it.
 * Returns a newly-allocated JSON string with result object, or NULL on error.
 * Caller must free() the returned string. */
char *crypto_mine_event(const key_store_t *store, int role_index,
                        const char *event_json, int difficulty,
                        int threads, int timeout_sec);

/* NIP-44 encrypt/decrypt */
char *crypto_nip44_encrypt(const key_store_t *store, int role_index,
                           const char *recipient_pubkey_hex, const char *plaintext);
char *crypto_nip44_decrypt(const key_store_t *store, int role_index,
                           const char *sender_pubkey_hex, const char *ciphertext);

/* NIP-04 encrypt/decrypt */
char *crypto_nip04_encrypt(const key_store_t *store, int role_index,
                           const char *recipient_pubkey_hex, const char *plaintext);
char *crypto_nip04_decrypt(const key_store_t *store, int role_index,
                           const char *sender_pubkey_hex, const char *ciphertext);

/* Zeroize all derived keys in the store. */
void crypto_wipe(key_store_t *store);



/* from alg_api.h */


/* Check whether a verb is valid for an algorithm (algorithm-based enforcement).
 * Returns ENFORCE_OK, ENFORCE_ERR_ALGORITHM, or ENFORCE_ERR_UNKNOWN_VERB.
 * Does NOT check purpose — purpose is irrelevant for the new verbs. */
int enforce_verb_algorithm(const char *verb, crypto_alg_t alg);

/* secp256k1 Schnorr (BIP-340) sign arbitrary bytes.
 * priv is 32-byte scalar, pub is 32-byte x-only pubkey, sig_out is 64 bytes.
 * Hashes the message with SHA-256 before signing (like Nostr event signing).
 * Returns 0 on success, -1 on error. */
int crypto_secp256k1_schnorr_sign(const unsigned char *priv, size_t priv_len,
                                    const unsigned char *msg, size_t msg_len,
                                    unsigned char *sig_out, size_t *sig_out_len);

/* secp256k1 Schnorr (BIP-340) verify.
 * pub is 32-byte x-only pubkey, sig is 64 bytes.
 * Returns 0 on valid, 1 on invalid, -1 on error. */
int crypto_secp256k1_schnorr_verify(const unsigned char *pub, size_t pub_len,
                                      const unsigned char *msg, size_t msg_len,
                                      const unsigned char *sig, size_t sig_len);

/* secp256k1 ECDSA sign arbitrary bytes.
 * priv is 32-byte scalar, sig_out must be at least 64 bytes (compact DER r||s).
 * Hashes the message with SHA-256 before signing.
 * Returns 0 on success, -1 on error. */
int crypto_secp256k1_ecdsa_sign(const unsigned char *priv, size_t priv_len,
                                  const unsigned char *msg, size_t msg_len,
                                  unsigned char *sig_out, size_t *sig_out_len);

/* secp256k1 ECDSA verify.
 * pub is 32-byte x-only pubkey (converted internally to compressed form).
 * sig is 64-byte compact (r||s). Returns 0 on valid, 1 on invalid, -1 on error. */
int crypto_secp256k1_ecdsa_verify(const unsigned char *pub, size_t pub_len,
                                    const unsigned char *msg, size_t msg_len,
                                    const unsigned char *sig, size_t sig_len);

/* ---- Algorithm key cache ----
 * On-demand key derivation by algorithm+index, separate from the role-based
 * key_store. Holds up to ALG_KEY_CACHE_MAX derived keys in secure memory.
 * When full, the oldest entry is evicted (FIFO). */

#define ALG_KEY_CACHE_MAX 32

typedef struct {
    crypto_alg_t alg;
    int index;
    secure_buf_t private_key;
    secure_buf_t public_key;
    char pubkey_hex[8192];
    char key_id[17];
    int valid;
} alg_key_entry_t;

typedef struct {
    alg_key_entry_t entries[ALG_KEY_CACHE_MAX];
    int count;
} algorithm_key_cache_t;

/* Initialize an empty cache. */
void alg_key_cache_init(algorithm_key_cache_t *cache);

/* Zeroize and free all entries. Idempotent. */
void alg_key_cache_wipe(algorithm_key_cache_t *cache);

/* Look up a cached entry by (alg, index). Returns NULL if not present. */
const alg_key_entry_t *alg_key_cache_get(algorithm_key_cache_t *cache, crypto_alg_t alg, int index);

/* Derive a key on-demand by (alg, index) and store it in the cache.
 * Uses the standard derivation path for the algorithm.
 * Returns 0 on success, -1 on error. */
int alg_key_cache_derive(algorithm_key_cache_t *cache, const mnemonic_state_t *mnemonic, crypto_alg_t alg, int index);


/* from dispatcher.h */


/* Dispatcher context — holds references to shared state */
typedef struct {
    role_table_t *role_table;
    mnemonic_state_t *mnemonic;
    key_store_t *key_store;
    algorithm_key_cache_t *alg_key_cache;  /* algorithm-based on-demand keys */
} dispatcher_ctx_t;

/* Initialize dispatcher context */
void dispatcher_init(dispatcher_ctx_t *ctx, role_table_t *table, mnemonic_state_t *mnemonic, key_store_t *key_store, algorithm_key_cache_t *alg_key_cache);

/*
 * Process a JSON-RPC request string and produce a JSON-RPC response string.
 *
 * The caller owns the returned string and must free() it.
 * Returns NULL only on catastrophic allocation failure.
 *
 * Response format on success:
 *   { "id": "...", "result": "..." }
 *
 * Response format on error:
 *   { "id": "...", "error": { "code": <int>, "message": "..." } }
 *
 * Error codes:
 *   -32700  Parse error (invalid JSON)
 *   -32600  Invalid request (missing id/method/params)
 *   -32601  Method not found (unknown verb after enforcement)
 *   -32602  Invalid params
 *   1001    ambiguous_role_selector
 *   1002    unknown_role
 *   1003    no_default_role
 *   1004    purpose_mismatch
 *   1005    curve_mismatch
 *   1006    mnemonic_not_loaded
 */
char *dispatcher_handle_request(dispatcher_ctx_t *ctx, const char *json_request);


/* from server.h */


#define SERVER_SOCKET_NAME_MAX 108
#define SERVER_MAX_MSG_SIZE    16777216

/* Caller identity */
typedef struct {
    uid_t uid;
    gid_t gid;
    pid_t pid;
    char caller_id[POLICY_CALLER_MAX_LEN];  /* "uid:<n>" */
} caller_identity_t;

/* Server context */
typedef struct {
    char socket_name[SERVER_SOCKET_NAME_MAX]; /* abstract namespace name (without \0 prefix) */
    char last_error[256];
    int listen_fd;
    int running;
    dispatcher_ctx_t *dispatcher;
    policy_table_t *policy;
    int socket_name_explicit;
} server_ctx_t;

/* Initialize server context. socket_name is the abstract namespace name (e.g. "nsigner").
 * socket_name_explicit should be non-zero when provided via --socket-name override. */
void server_init(server_ctx_t *ctx, const char *socket_name, int socket_name_explicit,
                 dispatcher_ctx_t *dispatcher, policy_table_t *policy);

/* Start listening. Returns 0 on success, -1 on error. */
int server_start(server_ctx_t *ctx);

/* Get human-readable description of last server error. */
const char *server_last_error(const server_ctx_t *ctx);

/* Handle one pending connection (non-blocking). Returns 1 if handled, 0 if nothing pending, -1 on error.
 * activity_cb is called with a description string for the TUI activity log. */
typedef void (*server_activity_cb)(const char *message, void *user_data);
int server_handle_one(server_ctx_t *ctx, server_activity_cb cb, void *cb_data);

/* Stop server and close socket */
void server_stop(server_ctx_t *ctx);

/* Extract caller identity from connected fd */
int server_get_caller(int fd, caller_identity_t *out);


/* from socket_name.h */


/*
 * Generate random socket name in format: nsigner_<word1>_<word2>
 * Returns 0 on success, -1 on error.
 */
int socket_name_random(char *out, size_t out_len);


/* from main.h */
/*
 * nsigner main header - version information
 *
 * Version macros are auto-updated by increment_and_push.sh.
 */


/* Version information (auto-updated by build/version tooling) */
#define NSIGNER_VERSION_MAJOR 0
#define NSIGNER_VERSION_MINOR 0
#define NSIGNER_VERSION_PATCH 2
#define NSIGNER_VERSION "v0.0.2"


/* NSIGNER_HEADERLESS_DECLS_END */

#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <nostr_core/utils.h>

static char *make_error_response(const char *id, int code, const char *message) {
    cJSON *root = NULL;
    cJSON *err = NULL;
    cJSON *id_item = NULL;
    char *out = NULL;

    root = cJSON_CreateObject();
    if (root == NULL) {
        return NULL;
    }

    if (id == NULL) {
        id = "null";
    }

    id_item = cJSON_CreateString(id);
    if (id_item == NULL) {
        cJSON_Delete(root);
        return NULL;
    }
    cJSON_AddItemToObject(root, "id", id_item);

    err = cJSON_CreateObject();
    if (err == NULL) {
        cJSON_Delete(root);
        return NULL;
    }

    cJSON_AddNumberToObject(err, "code", code);
    cJSON_AddStringToObject(err, "message", (message != NULL) ? message : "error");
    cJSON_AddItemToObject(root, "error", err);

    out = cJSON_PrintUnformatted(root);
    cJSON_Delete(root);
    return out;
}

static char *make_success_response(const char *id, const char *result) {
    cJSON *root = NULL;
    cJSON *id_item = NULL;
    char *out = NULL;

    root = cJSON_CreateObject();
    if (root == NULL) {
        return NULL;
    }

    if (id == NULL) {
        id = "null";
    }

    id_item = cJSON_CreateString(id);
    if (id_item == NULL) {
        cJSON_Delete(root);
        return NULL;
    }
    cJSON_AddItemToObject(root, "id", id_item);

    if (!cJSON_AddStringToObject(root, "result", (result != NULL) ? result : "")) {
        cJSON_Delete(root);
        return NULL;
    }

    out = cJSON_PrintUnformatted(root);
    cJSON_Delete(root);
    return out;
}

void dispatcher_init(dispatcher_ctx_t *ctx, role_table_t *table, mnemonic_state_t *mnemonic, key_store_t *key_store, algorithm_key_cache_t *alg_key_cache) {
    if (ctx == NULL) {
        return;
    }

    ctx->role_table = table;
    ctx->mnemonic = mnemonic;
    ctx->key_store = key_store;
    ctx->alg_key_cache = alg_key_cache;
}

/* ---- Algorithm-based verb helpers ----
 *
 * These helpers handle the new algorithm-based verbs (sign, verify,
 * encapsulate, decapsulate, derive_shared_secret) and the algorithm-based
 * path for get_public_key. They use the algorithm_key_cache for on-demand
 * key derivation, bypassing the role table entirely.
 *
 * Returns a newly-allocated response string (caller frees), or NULL if
 * the verb is not an algorithm-based verb (so the caller falls through
 * to the role-based path).
 */

/* Check whether a method name is an algorithm-based verb (new or alias). */
static int is_algorithm_verb(const char *method) {
    if (method == NULL) return 0;
    return (strcmp(method, VERB_SIGN) == 0 ||
            strcmp(method, VERB_VERIFY) == 0 ||
            strcmp(method, VERB_ENCAPSULATE) == 0 ||
            strcmp(method, VERB_DECAPSULATE) == 0 ||
            strcmp(method, VERB_DERIVE_SHARED) == 0 ||
            /* aliases */
            strcmp(method, VERB_SIGN_DATA) == 0 ||
            strcmp(method, VERB_SSH_SIGN) == 0 ||
            strcmp(method, VERB_VERIFY_SIG) == 0 ||
            strcmp(method, VERB_KEM_ENCAPS) == 0 ||
            strcmp(method, VERB_KEM_DECAPS) == 0);
}

/* Map an alias verb to its canonical algorithm-based verb name.
 * Returns the canonical verb, or the original if not an alias. */
static const char *canonical_alg_verb(const char *method) {
    if (method == NULL) return method;
    if (strcmp(method, VERB_SIGN_DATA) == 0) return VERB_SIGN;
    if (strcmp(method, VERB_SSH_SIGN) == 0) return VERB_SIGN;
    if (strcmp(method, VERB_VERIFY_SIG) == 0) return VERB_VERIFY;
    if (strcmp(method, VERB_KEM_ENCAPS) == 0) return VERB_ENCAPSULATE;
    if (strcmp(method, VERB_KEM_DECAPS) == 0) return VERB_DECAPSULATE;
    return method;
}

/* Parse the algorithm string from the options object.
 * Returns CRYPTO_ALG_UNKNOWN if not present or invalid. */
static crypto_alg_t parse_algorithm_option(cJSON *options_item) {
    cJSON *alg_item;

    if (!cJSON_IsObject(options_item)) {
        return CRYPTO_ALG_UNKNOWN;
    }
    alg_item = cJSON_GetObjectItemCaseSensitive(options_item, "algorithm");
    if (!cJSON_IsString(alg_item) || alg_item->valuestring == NULL) {
        return CRYPTO_ALG_UNKNOWN;
    }
    return crypto_alg_from_str(alg_item->valuestring);
}

/* Parse the index from the options object. Returns 0 if not present
 * (index defaults to 0). */
static int parse_index_option(cJSON *options_item) {
    cJSON *idx_item;

    if (!cJSON_IsObject(options_item)) {
        return 0;
    }
    idx_item = cJSON_GetObjectItemCaseSensitive(options_item, "index");
    if (cJSON_IsNumber(idx_item)) {
        return idx_item->valueint;
    }
    return 0;
}

/* Build a structured JSON result object for algorithm-based responses.
 * Returns a newly-allocated string (caller frees), or NULL on error. */
static char *build_alg_result_json(const char *alg_name, const char *key_id,
                                     const char *field_name, const char *field_value) {
    cJSON *obj = cJSON_CreateObject();
    char *out;

    if (obj == NULL) return NULL;
    cJSON_AddStringToObject(obj, "algorithm", (alg_name != NULL) ? alg_name : "unknown");
    if (key_id != NULL && key_id[0] != '\0') {
        cJSON_AddStringToObject(obj, "key_id", key_id);
    }
    if (field_name != NULL && field_value != NULL) {
        cJSON_AddStringToObject(obj, field_name, field_value);
    }
    out = cJSON_PrintUnformatted(obj);
    cJSON_Delete(obj);
    return out;
}

/* Main algorithm-based verb handler. Returns a response string (caller
 * frees) if the verb was handled, or NULL if the verb is not algorithm-
 * based (caller should fall through to role-based path). */
static char *handle_algorithm_verb(dispatcher_ctx_t *ctx, const char *id_str,
                                     const char *method, cJSON *params_item,
                                     cJSON *options_item) {
    const char *canonical;
    crypto_alg_t alg;
    int index;
    int enforce_rc;
    const char *alg_name;
    const alg_key_entry_t *key_entry;
    const crypto_alg_sizes_t *sz;

    if (!is_algorithm_verb(method) && strcmp(method, VERB_GET_PUBLIC_KEY) != 0) {
        return NULL;  /* not an algorithm-based verb */
    }

    canonical = canonical_alg_verb(method);

    /* Parse algorithm and index from options. */
    alg = parse_algorithm_option(options_item);

    /* For aliases that imply a specific algorithm, default if not given. */
    if (alg == CRYPTO_ALG_UNKNOWN) {
        if (strcmp(method, VERB_SSH_SIGN) == 0) {
            alg = CRYPTO_ALG_ED25519;
        } else if (strcmp(method, VERB_KEM_ENCAPS) == 0 ||
                   strcmp(method, VERB_KEM_DECAPS) == 0) {
            alg = CRYPTO_ALG_ML_KEM_768;
        }
    }

    if (alg == CRYPTO_ALG_UNKNOWN) {
        return make_error_response(id_str, -32602, "missing_or_invalid_algorithm");
    }

    index = parse_index_option(options_item);

    /* Enforcement: check verb+algorithm validity. */
    enforce_rc = enforce_verb_algorithm(canonical, alg);
    if (enforce_rc != ENFORCE_OK) {
        if (enforce_rc == ENFORCE_ERR_ALGORITHM) {
            return make_error_response(id_str, 1010, "algorithm_not_supported_for_verb");
        }
        return make_error_response(id_str, -32601, "method_not_found");
    }

    /* Mnemonic must be loaded for any key operation. */
    if (!mnemonic_is_loaded(ctx->mnemonic)) {
        return make_error_response(id_str, 1006, "mnemonic_not_loaded");
    }

    /* Algorithm key cache must be available. */
    if (ctx->alg_key_cache == NULL) {
        return make_error_response(id_str, -32600, "algorithm_cache_unavailable");
    }

    alg_name = crypto_alg_to_str(alg);
    sz = crypto_alg_get_sizes(alg);
    if (sz == NULL) {
        return make_error_response(id_str, -32602, "invalid_algorithm");
    }

    /* ---- get_public_key (algorithm-based path) ---- */
    if (strcmp(canonical, VERB_GET_PUBLIC_KEY) == 0) {
        if (alg_key_cache_derive(ctx->alg_key_cache, ctx->mnemonic, alg, index) != 0) {
            return make_error_response(id_str, -32602, "key_derivation_failed");
        }
        key_entry = alg_key_cache_get(ctx->alg_key_cache, alg, index);
        if (key_entry == NULL) {
            return make_error_response(id_str, -32602, "key_derivation_failed");
        }
        {
            char *result = build_alg_result_json(alg_name, key_entry->key_id,
                                                    "public_key", key_entry->pubkey_hex);
            if (result == NULL) {
                return make_error_response(id_str, -32602, "invalid_params");
            }
            return make_success_response(id_str, result);
        }
    }

    /* ---- sign ---- */
    if (strcmp(canonical, VERB_SIGN) == 0) {
        cJSON *msg_hex_item = cJSON_GetArrayItem(params_item, 0);
        const char *msg_hex;
        unsigned char *msg_bytes = NULL;
        size_t msg_len = 0;
        unsigned char sig[7856];  /* large enough for all signature algorithms */
        size_t sig_len = 0;
        int sign_rc = -1;
        char *sig_hex;
        char *result;
        const unsigned char *priv;

        if (!cJSON_IsString(msg_hex_item) || msg_hex_item->valuestring == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        msg_hex = msg_hex_item->valuestring;

        /* Derive the key on demand. */
        if (alg_key_cache_derive(ctx->alg_key_cache, ctx->mnemonic, alg, index) != 0) {
            return make_error_response(id_str, -32602, "key_derivation_failed");
        }
        key_entry = alg_key_cache_get(ctx->alg_key_cache, alg, index);
        if (key_entry == NULL || !key_entry->valid) {
            return make_error_response(id_str, -32602, "key_derivation_failed");
        }
        priv = (const unsigned char *)key_entry->private_key.data;

        /* Decode hex message. */
        msg_len = strlen(msg_hex) / 2;
        if (msg_len == 0) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        msg_bytes = (unsigned char *)malloc(msg_len);
        if (msg_bytes == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        if (nostr_hex_to_bytes(msg_hex, msg_bytes, msg_len) != 0) {
            free(msg_bytes);
            return make_error_response(id_str, -32602, "invalid_params");
        }

        sig_len = sz->sig_len;

        /* For secp256k1, check the optional "scheme" parameter. */
        if (alg == CRYPTO_ALG_SECP256K1) {
            const char *scheme = "schnorr";  /* default */
            cJSON *scheme_item = NULL;

            if (cJSON_IsObject(options_item)) {
                scheme_item = cJSON_GetObjectItemCaseSensitive(options_item, "scheme");
                if (cJSON_IsString(scheme_item) && scheme_item->valuestring != NULL) {
                    scheme = scheme_item->valuestring;
                }
            }

            if (strcmp(scheme, "ecdsa") == 0) {
                sign_rc = crypto_secp256k1_ecdsa_sign(priv, sz->priv_key_len,
                                                        msg_bytes, msg_len,
                                                        sig, &sig_len);
            } else {
                /* default: schnorr */
                sign_rc = crypto_secp256k1_schnorr_sign(priv, sz->priv_key_len,
                                                          msg_bytes, msg_len,
                                                          sig, &sig_len);
            }
        } else if (alg == CRYPTO_ALG_ED25519) {
            sign_rc = crypto_ed25519_sign(priv, sz->priv_key_len,
                                            msg_bytes, msg_len,
                                            sig, &sig_len);
        } else if (alg == CRYPTO_ALG_ML_DSA_65) {
            sign_rc = crypto_ml_dsa_65_sign(priv, sz->priv_key_len,
                                              msg_bytes, msg_len,
                                              sig, &sig_len);
        } else if (alg == CRYPTO_ALG_SLH_DSA_128S) {
            sign_rc = crypto_slh_dsa_128s_sign(priv, sz->priv_key_len,
                                                  msg_bytes, msg_len,
                                                  sig, &sig_len);
        } else {
            free(msg_bytes);
            return make_error_response(id_str, 1010, "algorithm_not_supported_for_verb");
        }

        free(msg_bytes);

        if (sign_rc != 0) {
            return make_error_response(id_str, -32602, "signing_failed");
        }

        sig_hex = (char *)malloc(sig_len * 2 + 1);
        if (sig_hex == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        nostr_bytes_to_hex(sig, sig_len, sig_hex);

        result = build_alg_result_json(alg_name, key_entry->key_id,
                                          "signature", sig_hex);
        free(sig_hex);
        if (result == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        return make_success_response(id_str, result);
    }

    /* ---- verify ---- */
    if (strcmp(canonical, VERB_VERIFY) == 0) {
        cJSON *msg_hex_item = cJSON_GetArrayItem(params_item, 0);
        cJSON *sig_hex_item = cJSON_GetArrayItem(params_item, 1);
        const char *msg_hex;
        const char *sig_hex;
        unsigned char *msg_bytes = NULL;
        unsigned char *sig_bytes = NULL;
        size_t msg_len = 0;
        size_t sig_len = 0;
        int verify_rc = -1;
        const unsigned char *pub;
        cJSON *result_obj;
        char *out;

        if (!cJSON_IsString(msg_hex_item) || msg_hex_item->valuestring == NULL ||
            !cJSON_IsString(sig_hex_item) || sig_hex_item->valuestring == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        msg_hex = msg_hex_item->valuestring;
        sig_hex = sig_hex_item->valuestring;

        /* Derive the key on demand (to get the public key). */
        if (alg_key_cache_derive(ctx->alg_key_cache, ctx->mnemonic, alg, index) != 0) {
            return make_error_response(id_str, -32602, "key_derivation_failed");
        }
        key_entry = alg_key_cache_get(ctx->alg_key_cache, alg, index);
        if (key_entry == NULL || !key_entry->valid) {
            return make_error_response(id_str, -32602, "key_derivation_failed");
        }
        pub = (const unsigned char *)key_entry->public_key.data;

        msg_len = strlen(msg_hex) / 2;
        sig_len = strlen(sig_hex) / 2;
        if (msg_len == 0 || sig_len == 0) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        msg_bytes = (unsigned char *)malloc(msg_len);
        sig_bytes = (unsigned char *)malloc(sig_len);
        if (msg_bytes == NULL || sig_bytes == NULL) {
            free(msg_bytes); free(sig_bytes);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        if (nostr_hex_to_bytes(msg_hex, msg_bytes, msg_len) != 0 ||
            nostr_hex_to_bytes(sig_hex, sig_bytes, sig_len) != 0) {
            free(msg_bytes); free(sig_bytes);
            return make_error_response(id_str, -32602, "invalid_params");
        }

        if (alg == CRYPTO_ALG_SECP256K1) {
            const char *scheme = "schnorr";
            cJSON *scheme_item = NULL;

            if (cJSON_IsObject(options_item)) {
                scheme_item = cJSON_GetObjectItemCaseSensitive(options_item, "scheme");
                if (cJSON_IsString(scheme_item) && scheme_item->valuestring != NULL) {
                    scheme = scheme_item->valuestring;
                }
            }

            if (strcmp(scheme, "ecdsa") == 0) {
                verify_rc = crypto_secp256k1_ecdsa_verify(pub, sz->pub_key_len,
                                                            msg_bytes, msg_len,
                                                            sig_bytes, sig_len);
            } else {
                verify_rc = crypto_secp256k1_schnorr_verify(pub, sz->pub_key_len,
                                                              msg_bytes, msg_len,
                                                              sig_bytes, sig_len);
            }
        } else if (alg == CRYPTO_ALG_ED25519) {
            verify_rc = crypto_ed25519_verify(pub, sz->pub_key_len,
                                                msg_bytes, msg_len,
                                                sig_bytes, sig_len);
        } else if (alg == CRYPTO_ALG_ML_DSA_65) {
            verify_rc = crypto_ml_dsa_65_verify(pub, sz->pub_key_len,
                                                  msg_bytes, msg_len,
                                                  sig_bytes, sig_len);
        } else if (alg == CRYPTO_ALG_SLH_DSA_128S) {
            verify_rc = crypto_slh_dsa_128s_verify(pub, sz->pub_key_len,
                                                      msg_bytes, msg_len,
                                                      sig_bytes, sig_len);
        } else {
            free(msg_bytes); free(sig_bytes);
            return make_error_response(id_str, 1010, "algorithm_not_supported_for_verb");
        }

        free(msg_bytes);
        free(sig_bytes);

        result_obj = cJSON_CreateObject();
        if (result_obj == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        cJSON_AddBoolToObject(result_obj, "valid", (verify_rc == 0) ? 1 : 0);
        cJSON_AddStringToObject(result_obj, "algorithm",
                                  (alg_name != NULL) ? alg_name : "unknown");
        out = cJSON_PrintUnformatted(result_obj);
        cJSON_Delete(result_obj);
        if (out == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        return make_success_response(id_str, out);
    }

    /* ---- encapsulate (ML-KEM-768) ---- */
    if (strcmp(canonical, VERB_ENCAPSULATE) == 0) {
        cJSON *pub_hex_item = cJSON_GetArrayItem(params_item, 0);
        const char *pub_hex;
        unsigned char *pub = NULL;
        unsigned char ct[1088];
        unsigned char ss[32];
        char *ct_hex;
        char *ss_hex;
        cJSON *result_obj;
        char *out;

        if (!cJSON_IsString(pub_hex_item) || pub_hex_item->valuestring == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        pub_hex = pub_hex_item->valuestring;

        if (strlen(pub_hex) != sz->pub_key_len * 2) {
            return make_error_response(id_str, -32602, "invalid_pubkey_length");
        }
        pub = (unsigned char *)malloc(sz->pub_key_len);
        if (pub == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        if (nostr_hex_to_bytes(pub_hex, pub, sz->pub_key_len) != 0) {
            free(pub);
            return make_error_response(id_str, -32602, "invalid_pubkey_hex");
        }

        if (crypto_ml_kem_768_encaps(pub, sz->pub_key_len, ct, ss) != 0) {
            free(pub);
            return make_error_response(id_str, -32602, "encaps_failed");
        }
        free(pub);

        result_obj = cJSON_CreateObject();
        if (result_obj == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        ct_hex = (char *)malloc(sz->ciphertext_len * 2 + 1);
        ss_hex = (char *)malloc(sz->shared_secret_len * 2 + 1);
        if (ct_hex == NULL || ss_hex == NULL) {
            free(ct_hex); free(ss_hex);
            cJSON_Delete(result_obj);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        nostr_bytes_to_hex(ct, sz->ciphertext_len, ct_hex);
        nostr_bytes_to_hex(ss, sz->shared_secret_len, ss_hex);
        cJSON_AddStringToObject(result_obj, "ciphertext", ct_hex);
        cJSON_AddStringToObject(result_obj, "shared_secret", ss_hex);
        cJSON_AddStringToObject(result_obj, "algorithm", "ml-kem-768");
        free(ct_hex); free(ss_hex);

        out = cJSON_PrintUnformatted(result_obj);
        cJSON_Delete(result_obj);
        if (out == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        return make_success_response(id_str, out);
    }

    /* ---- decapsulate (ML-KEM-768) ---- */
    if (strcmp(canonical, VERB_DECAPSULATE) == 0) {
        cJSON *ct_hex_item = cJSON_GetArrayItem(params_item, 0);
        const char *ct_hex;
        unsigned char *ct = NULL;
        unsigned char ss[32];
        const unsigned char *priv;
        char *ss_hex;
        cJSON *result_obj;
        char *out;

        if (!cJSON_IsString(ct_hex_item) || ct_hex_item->valuestring == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        ct_hex = ct_hex_item->valuestring;

        /* Derive the ML-KEM key on demand. */
        if (alg_key_cache_derive(ctx->alg_key_cache, ctx->mnemonic, alg, index) != 0) {
            return make_error_response(id_str, -32602, "key_derivation_failed");
        }
        key_entry = alg_key_cache_get(ctx->alg_key_cache, alg, index);
        if (key_entry == NULL || !key_entry->valid) {
            return make_error_response(id_str, -32602, "key_derivation_failed");
        }
        priv = (const unsigned char *)key_entry->private_key.data;

        if (strlen(ct_hex) != sz->ciphertext_len * 2) {
            return make_error_response(id_str, -32602, "invalid_ciphertext_length");
        }
        ct = (unsigned char *)malloc(sz->ciphertext_len);
        if (ct == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        if (nostr_hex_to_bytes(ct_hex, ct, sz->ciphertext_len) != 0) {
            free(ct);
            return make_error_response(id_str, -32602, "invalid_ciphertext_hex");
        }

        if (crypto_ml_kem_768_decaps(priv, sz->priv_key_len, ct, sz->ciphertext_len, ss) != 0) {
            free(ct);
            return make_error_response(id_str, -32602, "decaps_failed");
        }
        free(ct);

        result_obj = cJSON_CreateObject();
        if (result_obj == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        ss_hex = (char *)malloc(sz->shared_secret_len * 2 + 1);
        if (ss_hex == NULL) {
            cJSON_Delete(result_obj);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        nostr_bytes_to_hex(ss, sz->shared_secret_len, ss_hex);
        cJSON_AddStringToObject(result_obj, "shared_secret", ss_hex);
        cJSON_AddStringToObject(result_obj, "algorithm", "ml-kem-768");
        free(ss_hex);

        out = cJSON_PrintUnformatted(result_obj);
        cJSON_Delete(result_obj);
        if (out == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        return make_success_response(id_str, out);
    }

    /* ---- derive_shared_secret (x25519) ---- */
    if (strcmp(canonical, VERB_DERIVE_SHARED) == 0) {
        cJSON *peer_hex_item = cJSON_GetArrayItem(params_item, 0);
        const char *peer_hex;
        unsigned char *peer_pub = NULL;
        unsigned char shared[32];
        size_t shared_len = 32;
        const unsigned char *priv;
        char *ss_hex;
        cJSON *result_obj;
        char *out;

        if (!cJSON_IsString(peer_hex_item) || peer_hex_item->valuestring == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        peer_hex = peer_hex_item->valuestring;

        /* Derive the x25519 key on demand. */
        if (alg_key_cache_derive(ctx->alg_key_cache, ctx->mnemonic, alg, index) != 0) {
            return make_error_response(id_str, -32602, "key_derivation_failed");
        }
        key_entry = alg_key_cache_get(ctx->alg_key_cache, alg, index);
        if (key_entry == NULL || !key_entry->valid) {
            return make_error_response(id_str, -32602, "key_derivation_failed");
        }
        priv = (const unsigned char *)key_entry->private_key.data;

        if (strlen(peer_hex) != sz->pub_key_len * 2) {
            return make_error_response(id_str, -32602, "invalid_pubkey_length");
        }
        peer_pub = (unsigned char *)malloc(sz->pub_key_len);
        if (peer_pub == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        if (nostr_hex_to_bytes(peer_hex, peer_pub, sz->pub_key_len) != 0) {
            free(peer_pub);
            return make_error_response(id_str, -32602, "invalid_pubkey_hex");
        }

        if (crypto_x25519_ecdh(priv, sz->priv_key_len,
                                 peer_pub, sz->pub_key_len,
                                 shared, &shared_len) != 0) {
            free(peer_pub);
            return make_error_response(id_str, -32602, "ecdh_failed");
        }
        free(peer_pub);

        result_obj = cJSON_CreateObject();
        if (result_obj == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        ss_hex = (char *)malloc(shared_len * 2 + 1);
        if (ss_hex == NULL) {
            cJSON_Delete(result_obj);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        nostr_bytes_to_hex(shared, shared_len, ss_hex);
        cJSON_AddStringToObject(result_obj, "shared_secret", ss_hex);
        cJSON_AddStringToObject(result_obj, "algorithm", "x25519");
        free(ss_hex);

        out = cJSON_PrintUnformatted(result_obj);
        cJSON_Delete(result_obj);
        if (out == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        return make_success_response(id_str, out);
    }

    /* Should not reach here (is_algorithm_verb filtered). */
    return make_error_response(id_str, -32601, "method_not_found");
}

/* ---- OTP verb handler ----
 *
 * Handles otp_encrypt and otp_decrypt. These verbs operate on the bound OTP
 * pad (one pad per session) and do not use the role table or mnemonic.
 *
 * Request shapes (see plans/otp_nostr_integration.md):
 *   otp_encrypt: params = [ "<plaintext-base64>", { "encoding": "ascii|binary" } ]
 *   otp_decrypt: params = [ "<ciphertext>", { "encoding": "ascii|binary" } ]
 *
 * The ciphertext for otp_decrypt is either an ASCII-armored string (encoding
 * "ascii") or a base64-encoded binary .otp blob (encoding "binary"). If
 * encoding is omitted, auto-detection by magic bytes is used.
 *
 * Results are returned as a JSON object string:
 *   otp_encrypt: {"ciphertext":"<ascii-armor-or-base64-blob>","encoding":"...",
 *                 "pad_chksum":"<64hex>","pad_offset_before":N,"pad_offset_after":M}
 *   otp_decrypt: {"plaintext":"<base64>","encoding":"..."}
 */
static char *handle_otp_verb(const char *id_str, const char *method,
                              cJSON *params_item, cJSON *options_item) {
    const char *encoding = NULL;
    cJSON *payload_item = cJSON_GetArrayItem(params_item, 0);

    if (!cJSON_IsString(payload_item) || payload_item->valuestring == NULL) {
        return make_error_response(id_str, -32602, "invalid_params");
    }

    /* Parse encoding option. */
    if (cJSON_IsObject(options_item)) {
        cJSON *enc = cJSON_GetObjectItemCaseSensitive(options_item, "encoding");
        if (cJSON_IsString(enc) && enc->valuestring != NULL) {
            encoding = enc->valuestring;
        }
    }

    if (!otp_pad_is_bound()) {
        return make_error_response(id_str, -32601, "otp_pad_not_bound");
    }

    if (strcmp(method, VERB_OTP_ENCRYPT) == 0) {
        /* Decode base64 plaintext. */
        int pt_len = 0;
        unsigned char *pt = otppad_base64_decode(payload_item->valuestring, &pt_len);
        if (pt == NULL) {
            return make_error_response(id_str, -32602, "invalid_plaintext_base64");
        }

        uint64_t off_before = otp_pad_current_offset();
        char *out_payload = NULL;
        size_t out_len = 0;
        uint64_t off_after = 0;
        int rc = otp_pad_encrypt(pt, (size_t)pt_len, encoding,
                                 &out_payload, &out_len, &off_after);
        secure_memzero(pt, (size_t)pt_len);
        free(pt);
        if (rc != 0) {
            return make_error_response(id_str, -32602, "otp_encrypt_failed");
        }

        /* Build result object. */
        cJSON *result_obj = cJSON_CreateObject();
        if (result_obj == NULL) {
            secure_memzero(out_payload, out_len);
            free(out_payload);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        const char *enc_used = (encoding && strcmp(encoding, "binary") == 0)
                                   ? "binary" : "ascii";

        /* For binary encoding, out_payload is raw bytes (may contain NULs),
         * so base64-encode it for the JSON string. For ASCII, it's already a
         * NUL-terminated string. */
        char *ciphertext_json = NULL;
        if (strcmp(enc_used, "binary") == 0) {
            ciphertext_json = otppad_base64_encode((const unsigned char *)out_payload,
                                                    (int)out_len);
            secure_memzero(out_payload, out_len);
            free(out_payload);
            if (ciphertext_json == NULL) {
                cJSON_Delete(result_obj);
                return make_error_response(id_str, -32602, "invalid_params");
            }
        } else {
            ciphertext_json = out_payload;  /* NUL-terminated, take ownership */
        }

        cJSON_AddStringToObject(result_obj, "ciphertext", ciphertext_json);
        cJSON_AddStringToObject(result_obj, "encoding", enc_used);
        cJSON_AddStringToObject(result_obj, "pad_chksum", otp_pad_chksum());
        cJSON_AddNumberToObject(result_obj, "pad_offset_before", (double)off_before);
        cJSON_AddNumberToObject(result_obj, "pad_offset_after", (double)off_after);

        char *out = cJSON_PrintUnformatted(result_obj);
        cJSON_Delete(result_obj);
        if (strcmp(enc_used, "binary") == 0) {
            /* ciphertext_json was base64-encoded by us. */
            free(ciphertext_json);
        } else {
            secure_memzero(ciphertext_json, out_len);
            free(ciphertext_json);
        }
        if (out == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        return make_success_response(id_str, out);
    } else if (strcmp(method, VERB_OTP_DECRYPT) == 0) {
        unsigned char *pt = NULL;
        size_t pt_len = 0;
        int rc;

        /* For binary encoding, the input is a base64-encoded .otp blob;
         * decode it to raw bytes first. For ASCII, the input is the
         * NUL-terminated armor string. */
        if (encoding && strcmp(encoding, "binary") == 0) {
            int bin_len = 0;
            unsigned char *bin = otppad_base64_decode(payload_item->valuestring,
                                                       &bin_len);
            if (bin == NULL) {
                return make_error_response(id_str, -32602,
                                           "invalid_ciphertext_base64");
            }
            rc = otp_pad_decrypt((const char *)bin, (size_t)bin_len, encoding,
                                 &pt, &pt_len);
            secure_memzero(bin, (size_t)bin_len);
            free(bin);
        } else {
            size_t input_len = strlen(payload_item->valuestring);
            rc = otp_pad_decrypt(payload_item->valuestring, input_len, encoding,
                                 &pt, &pt_len);
        }
        if (rc != 0) {
            return make_error_response(id_str, -32602, "otp_decrypt_failed");
        }

        /* Base64-encode the plaintext for the JSON result. */
        char *pt_b64 = otppad_base64_encode(pt, (int)pt_len);
        secure_memzero(pt, pt_len);
        free(pt);
        if (pt_b64 == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }

        cJSON *result_obj = cJSON_CreateObject();
        if (result_obj == NULL) {
            free(pt_b64);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        cJSON_AddStringToObject(result_obj, "plaintext", pt_b64);
        cJSON_AddStringToObject(result_obj, "pad_chksum", otp_pad_chksum());
        free(pt_b64);

        char *out = cJSON_PrintUnformatted(result_obj);
        cJSON_Delete(result_obj);
        if (out == NULL) {
            return make_error_response(id_str, -32602, "invalid_params");
        }
        return make_success_response(id_str, out);
    }

    return make_error_response(id_str, -32601, "method_not_found");
}

char *dispatcher_handle_request(dispatcher_ctx_t *ctx, const char *json_request) {
    cJSON *root = NULL;
    cJSON *method_item;
    cJSON *params_item;
    cJSON *id_item;
    cJSON *options_item;
    cJSON *tmp;
    const char *id_str = "null";
    char id_copy[256];
    const char *method;
    selector_request_t selector_req;
    role_entry_t *role = NULL;
    int rc;
    const char *result = NULL;
    char *owned_result = NULL;
    ptrdiff_t role_index_diff;
    int role_index;
    crypto_alg_t alg;

    if (ctx == NULL || ctx->role_table == NULL || ctx->mnemonic == NULL || ctx->key_store == NULL || json_request == NULL) {
        return make_error_response("null", -32600, "invalid_request");
    }

    root = cJSON_Parse(json_request);
    if (root == NULL) {
        return make_error_response("null", -32700, "parse_error");
    }

    id_copy[0] = '\0';
    id_item = cJSON_GetObjectItemCaseSensitive(root, "id");
    if (cJSON_IsString(id_item) && id_item->valuestring != NULL) {
        strncpy(id_copy, id_item->valuestring, sizeof(id_copy) - 1);
        id_copy[sizeof(id_copy) - 1] = '\0';
        id_str = id_copy;
    }

    method_item = cJSON_GetObjectItemCaseSensitive(root, "method");
    if (!cJSON_IsString(method_item) || method_item->valuestring == NULL) {
        cJSON_Delete(root);
        return make_error_response(id_str, -32600, "invalid_request");
    }
    method = method_item->valuestring;

    params_item = cJSON_GetObjectItemCaseSensitive(root, "params");
    if (!cJSON_IsArray(params_item)) {
        cJSON_Delete(root);
        return make_error_response(id_str, -32600, "invalid_request");
    }

    selector_request_init(&selector_req);

    {
        int params_count = cJSON_GetArraySize(params_item);
        options_item = (params_count > 0) ? cJSON_GetArrayItem(params_item, params_count - 1) : NULL;
    }

    /* ---- Algorithm-based verb routing ----
     *
     * The new algorithm-based verbs (sign, verify, encapsulate, decapsulate,
     * derive_shared_secret) and their aliases (sign_data, ssh_sign,
     * verify_signature, kem_encapsulate, kem_decapsulate) are handled here,
     * BEFORE the role-based selector resolution. They use the algorithm_key_cache
     * for on-demand key derivation and do not need a role table entry.
     *
     * get_public_key is special: if the options contain an "algorithm" field,
     * it takes the algorithm-based path; otherwise it falls through to the
     * role-based path (backward compatibility). */
    /* New algorithm-based verbs (sign, verify, encapsulate, decapsulate,
     * derive_shared_secret) always take the algorithm-based path.
     * Old verb aliases (sign_data, ssh_sign, verify_signature, kem_encapsulate,
     * kem_decapsulate) only take the algorithm-based path if the "algorithm"
     * parameter is present; otherwise they fall through to the role-based
     * path for backward compatibility. */
    if (is_algorithm_verb(method)) {
        int is_new_verb = (strcmp(method, VERB_SIGN) == 0 ||
                           strcmp(method, VERB_VERIFY) == 0 ||
                           strcmp(method, VERB_ENCAPSULATE) == 0 ||
                           strcmp(method, VERB_DECAPSULATE) == 0 ||
                           strcmp(method, VERB_DERIVE_SHARED) == 0);
        int has_algorithm_opt = 0;

        if (cJSON_IsObject(options_item)) {
            cJSON *alg_check = cJSON_GetObjectItemCaseSensitive(options_item, "algorithm");
            if (cJSON_IsString(alg_check) && alg_check->valuestring != NULL) {
                has_algorithm_opt = 1;
            }
        }

        if (is_new_verb || has_algorithm_opt) {
            char *alg_response = handle_algorithm_verb(ctx, id_str, method,
                                                         params_item, options_item);
            cJSON_Delete(root);
            return alg_response;
        }
        /* Old alias without algorithm= → fall through to role-based path */
    }

    if (strcmp(method, VERB_GET_PUBLIC_KEY) == 0 && cJSON_IsObject(options_item)) {
        cJSON *alg_check = cJSON_GetObjectItemCaseSensitive(options_item, "algorithm");
        if (cJSON_IsString(alg_check) && alg_check->valuestring != NULL) {
            /* Algorithm-based get_public_key path. */
            char *alg_response = handle_algorithm_verb(ctx, id_str, VERB_GET_PUBLIC_KEY,
                                                         params_item, options_item);
            cJSON_Delete(root);
            return alg_response;
        }
    }

    /* ---- OTP verb routing ----
     *
     * otp_encrypt and otp_decrypt do not use the role table or the mnemonic;
     * they operate on the bound OTP pad (one pad per session, bound at
     * startup via --otp-pad-dir / --otp-pad). Route them before role
     * resolution. */
    if (strcmp(method, VERB_OTP_ENCRYPT) == 0 ||
        strcmp(method, VERB_OTP_DECRYPT) == 0) {
        char *otp_response = handle_otp_verb(id_str, method, params_item, options_item);
        cJSON_Delete(root);
        return otp_response;
    }

    if (cJSON_IsObject(options_item)) {
        tmp = cJSON_GetObjectItemCaseSensitive(options_item, "role");
        if (tmp != NULL) {
            if (!cJSON_IsString(tmp) || tmp->valuestring == NULL) {
                cJSON_Delete(root);
                return make_error_response(id_str, -32602, "invalid_params");
            }
            selector_req.has_role = 1;
            strncpy(selector_req.role_name, tmp->valuestring, sizeof(selector_req.role_name) - 1);
            selector_req.role_name[sizeof(selector_req.role_name) - 1] = '\0';
        }

        tmp = cJSON_GetObjectItemCaseSensitive(options_item, "nostr_index");
        if (tmp != NULL) {
            if (!cJSON_IsNumber(tmp)) {
                cJSON_Delete(root);
                return make_error_response(id_str, -32602, "invalid_params");
            }
            selector_req.has_nostr_index = 1;
            selector_req.nostr_index = tmp->valueint;
        }

        tmp = cJSON_GetObjectItemCaseSensitive(options_item, "role_path");
        if (tmp != NULL) {
            if (!cJSON_IsString(tmp) || tmp->valuestring == NULL) {
                cJSON_Delete(root);
                return make_error_response(id_str, -32602, "invalid_params");
            }
            selector_req.has_role_path = 1;
            strncpy(selector_req.role_path, tmp->valuestring, sizeof(selector_req.role_path) - 1);
            selector_req.role_path[sizeof(selector_req.role_path) - 1] = '\0';
        }
    }

    rc = selector_resolve(&selector_req, ctx->role_table, &role);
    if (rc != SELECTOR_OK) {
        cJSON_Delete(root);
        if (rc == SELECTOR_ERR_AMBIGUOUS) {
            return make_error_response(id_str, 1001, "ambiguous_role_selector");
        }
        if (rc == SELECTOR_ERR_NOT_FOUND) {
            return make_error_response(id_str, 1002, "unknown_role");
        }
        if (rc == SELECTOR_ERR_NO_DEFAULT) {
            return make_error_response(id_str, 1003, "no_default_role");
        }
        return make_error_response(id_str, -32602, "invalid_params");
    }

    rc = enforce_verb_role(method, role);
    if (rc != ENFORCE_OK) {
        cJSON_Delete(root);
        if (rc == ENFORCE_ERR_PURPOSE) {
            return make_error_response(id_str, 1004, "purpose_mismatch");
        }
        if (rc == ENFORCE_ERR_CURVE) {
            return make_error_response(id_str, 1005, "curve_mismatch");
        }
        if (rc == ENFORCE_ERR_UNKNOWN_VERB) {
            return make_error_response(id_str, -32601, "method_not_found");
        }
        return make_error_response(id_str, -32601, "method_not_found");
    }

    if (!mnemonic_is_loaded(ctx->mnemonic)) {
        cJSON_Delete(root);
        return make_error_response(id_str, 1006, "mnemonic_not_loaded");
    }

    role_index_diff = role - &ctx->role_table->entries[0];
    if (role_index_diff < 0 || role_index_diff >= ROLE_TABLE_MAX_ENTRIES) {
        cJSON_Delete(root);
        return make_error_response(id_str, -32600, "invalid_request");
    }
    role_index = (int)role_index_diff;

    if (strcmp(method, VERB_GET_PUBLIC_KEY) == 0) {
        /* get_public_key: returns the role's public key.
         *
         * For secp256k1 (backward compatibility): the result is a plain hex
         * string (the existing format) unless the client requests the
         * structured format via the options field {"format":"structured"}.
         *
         * For all other algorithms (ed25519, x25519, ML-DSA-65,
         * SLH-DSA-128s, ML-KEM-768): the result is a structured JSON object
         * serialized as a string:
         *   {"algorithm":"<alg>","public_key":"<hex>","key_id":"<16 hex>"}
         *
         * The key_id is the first 16 hex characters of the public key — a
         * short display identifier (similar to an SSH key fingerprint).
         *
         * The full (untruncated) public key is read from the key_store via
         * crypto_get_pubkey_hex(), because role->pubkey_hex is only
         * ROLE_PUBKEY_HEX_MAX (66) bytes — too small for PQ pubkeys.
         */
        alg = crypto_alg_from_role(role->curve, role->purpose);
        if (role->derived && alg != CRYPTO_ALG_SECP256K1 &&
            alg != CRYPTO_ALG_UNKNOWN) {
            /* Non-secp256k1: always structured. */
            cJSON *pk_obj = cJSON_CreateObject();
            const char *alg_name;
            const char *pub_hex = crypto_get_pubkey_hex(ctx->key_store, role_index);
            char key_id[17];

            if (pk_obj == NULL) {
                cJSON_Delete(root);
                return make_error_response(id_str, -32602, "invalid_params");
            }

            alg_name = crypto_alg_to_str(alg);
            cJSON_AddStringToObject(pk_obj, "algorithm",
                                     (alg_name != NULL) ? alg_name : "unknown");
            cJSON_AddStringToObject(pk_obj, "public_key",
                                     (pub_hex != NULL) ? pub_hex : "");

            /* key_id = first 16 hex chars of pubkey (or empty if too short). */
            if (pub_hex != NULL && strlen(pub_hex) >= 16) {
                memcpy(key_id, pub_hex, 16);
                key_id[16] = '\0';
            } else {
                key_id[0] = '\0';
            }
            cJSON_AddStringToObject(pk_obj, "key_id", key_id);

            owned_result = cJSON_PrintUnformatted(pk_obj);
            cJSON_Delete(pk_obj);
            if (owned_result == NULL) {
                cJSON_Delete(root);
                return make_error_response(id_str, -32602, "invalid_params");
            }
            result = owned_result;
        } else if (role->derived && alg == CRYPTO_ALG_SECP256K1) {
            /* secp256k1: plain hex by default, structured if requested.
             * role->pubkey_hex is large enough for secp256k1 (64 hex chars). */
            int want_structured = 0;
            cJSON *fmt_item = NULL;

            if (cJSON_IsObject(options_item)) {
                fmt_item = cJSON_GetObjectItemCaseSensitive(options_item, "format");
                if (cJSON_IsString(fmt_item) && fmt_item->valuestring != NULL &&
                    strcmp(fmt_item->valuestring, "structured") == 0) {
                    want_structured = 1;
                }
            }

            if (want_structured) {
                cJSON *pk_obj = cJSON_CreateObject();
                const char *pub_hex = role->pubkey_hex;
                char key_id[17];

                if (pk_obj == NULL) {
                    cJSON_Delete(root);
                    return make_error_response(id_str, -32602, "invalid_params");
                }
                cJSON_AddStringToObject(pk_obj, "algorithm", "secp256k1");
                cJSON_AddStringToObject(pk_obj, "public_key",
                                         (pub_hex != NULL) ? pub_hex : "");
                if (pub_hex != NULL && strlen(pub_hex) >= 16) {
                    memcpy(key_id, pub_hex, 16);
                    key_id[16] = '\0';
                } else {
                    key_id[0] = '\0';
                }
                cJSON_AddStringToObject(pk_obj, "key_id", key_id);

                owned_result = cJSON_PrintUnformatted(pk_obj);
                cJSON_Delete(pk_obj);
                if (owned_result == NULL) {
                    cJSON_Delete(root);
                    return make_error_response(id_str, -32602, "invalid_params");
                }
                result = owned_result;
            } else {
                /* Backward-compatible plain hex string. */
                result = role->pubkey_hex;
            }
        } else {
            /* Not yet derived, or unknown algorithm. */
            result = "not_yet_derived";
        }
    } else if (strcmp(method, VERB_SIGN_EVENT) == 0) {
        cJSON *event_item = cJSON_GetArrayItem(params_item, 0);
        if (!cJSON_IsString(event_item) || event_item->valuestring == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }

        owned_result = crypto_sign_event(ctx->key_store, role_index, event_item->valuestring);
        if (owned_result == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        result = owned_result;
    } else if (strcmp(method, VERB_MINE_EVENT) == 0) {
        cJSON *event_item = cJSON_GetArrayItem(params_item, 0);
        cJSON *diff_item = NULL;
        cJSON *threads_item = NULL;
        cJSON *timeout_item = NULL;
        int difficulty = 0;
        int threads = 1;
        int timeout_sec = 0;
        int has_difficulty = 0;
        int has_timeout = 0;

        if (!cJSON_IsString(event_item) || event_item->valuestring == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }

        /* Extract mining options from the options object (last param) */
        if (cJSON_IsObject(options_item)) {
            diff_item = cJSON_GetObjectItemCaseSensitive(options_item, "difficulty");
            if (cJSON_IsNumber(diff_item)) {
                difficulty = diff_item->valueint;
                has_difficulty = 1;
            }

            threads_item = cJSON_GetObjectItemCaseSensitive(options_item, "threads");
            if (cJSON_IsNumber(threads_item)) {
                threads = threads_item->valueint;
            }

            timeout_item = cJSON_GetObjectItemCaseSensitive(options_item, "timeout_sec");
            if (cJSON_IsNumber(timeout_item)) {
                timeout_sec = timeout_item->valueint;
                has_timeout = 1;
            }
        }

        /* At least one of difficulty or timeout_sec must be specified */
        if (!has_difficulty && !has_timeout) {
            cJSON_Delete(root);
            return make_error_response(id_str, 1007, "no_termination_condition");
        }

        /* Clamp threads to 1..32 */
        if (threads < 1) threads = 1;
        if (threads > 32) threads = 32;

        owned_result = crypto_mine_event(ctx->key_store, role_index,
                                         event_item->valuestring,
                                         difficulty, threads, timeout_sec);
        if (owned_result == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, 1008, "mining_failed");
        }
        result = owned_result;
    } else if (strcmp(method, VERB_NIP44_ENCRYPT) == 0) {
        cJSON *peer_item = cJSON_GetArrayItem(params_item, 0);
        cJSON *msg_item = cJSON_GetArrayItem(params_item, 1);
        if (!cJSON_IsString(peer_item) || peer_item->valuestring == NULL ||
            !cJSON_IsString(msg_item) || msg_item->valuestring == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        owned_result = crypto_nip44_encrypt(ctx->key_store, role_index, peer_item->valuestring, msg_item->valuestring);
        if (owned_result == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        result = owned_result;
    } else if (strcmp(method, VERB_NIP44_DECRYPT) == 0) {
        cJSON *peer_item = cJSON_GetArrayItem(params_item, 0);
        cJSON *msg_item = cJSON_GetArrayItem(params_item, 1);
        if (!cJSON_IsString(peer_item) || peer_item->valuestring == NULL ||
            !cJSON_IsString(msg_item) || msg_item->valuestring == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        owned_result = crypto_nip44_decrypt(ctx->key_store, role_index, peer_item->valuestring, msg_item->valuestring);
        if (owned_result == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        result = owned_result;
    } else if (strcmp(method, VERB_NIP04_ENCRYPT) == 0) {
        cJSON *peer_item = cJSON_GetArrayItem(params_item, 0);
        cJSON *msg_item = cJSON_GetArrayItem(params_item, 1);
        if (!cJSON_IsString(peer_item) || peer_item->valuestring == NULL ||
            !cJSON_IsString(msg_item) || msg_item->valuestring == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        owned_result = crypto_nip04_encrypt(ctx->key_store, role_index, peer_item->valuestring, msg_item->valuestring);
        if (owned_result == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        result = owned_result;
    } else if (strcmp(method, VERB_NIP04_DECRYPT) == 0) {
        cJSON *peer_item = cJSON_GetArrayItem(params_item, 0);
        cJSON *msg_item = cJSON_GetArrayItem(params_item, 1);
        if (!cJSON_IsString(peer_item) || peer_item->valuestring == NULL ||
            !cJSON_IsString(msg_item) || msg_item->valuestring == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        owned_result = crypto_nip04_decrypt(ctx->key_store, role_index, peer_item->valuestring, msg_item->valuestring);
        if (owned_result == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        result = owned_result;
    } else if (strcmp(method, VERB_SIGN_DATA) == 0 ||
               strcmp(method, VERB_SSH_SIGN) == 0) {
        /* sign_data / ssh_sign: params = [message_bytes_hex, options]
         * Sign the decoded message bytes with the role's key.
         * Returns {"signature":"<hex>","algorithm":"<alg_name>"}.
         * Currently only ed25519 is implemented; PQ algorithms return
         * not_yet_implemented. */
        cJSON *msg_hex_item = cJSON_GetArrayItem(params_item, 0);
        const char *msg_hex;
        unsigned char *msg_bytes = NULL;
        size_t msg_len = 0;
        const unsigned char *priv_key;
        const crypto_alg_sizes_t *sz;
        unsigned char sig[7856]; /* large enough for ed25519 (64), ML-DSA-65 (3309), SLH-DSA-128s (7856) */
        size_t sig_len = 0;
        cJSON *result_obj = NULL;
        const char *alg_name;

        if (!cJSON_IsString(msg_hex_item) || msg_hex_item->valuestring == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        msg_hex = msg_hex_item->valuestring;

        /* Get the derived key for this role. */
        priv_key = crypto_get_private_key(ctx->key_store, role_index);
        if (priv_key == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "key_not_derived");
        }

        /* Determine the algorithm from the role. */
        alg = crypto_alg_from_role(role->curve, role->purpose);
        sz = crypto_alg_get_sizes(alg);
        if (sz == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }

        /* Only ed25519, ML-DSA-65, and SLH-DSA-128s are implemented for sign_data. */
        if (alg != CRYPTO_ALG_ED25519 && alg != CRYPTO_ALG_ML_DSA_65 &&
            alg != CRYPTO_ALG_SLH_DSA_128S) {
            cJSON_Delete(root);
            return make_error_response(id_str, 1009, "not_yet_implemented");
        }

        /* Decode hex message to bytes. */
        msg_len = strlen(msg_hex) / 2;
        if (msg_len == 0) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        msg_bytes = (unsigned char *)malloc(msg_len);
        if (msg_bytes == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        if (nostr_hex_to_bytes(msg_hex, msg_bytes, msg_len) != 0) {
            free(msg_bytes);
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }

        sig_len = sz->sig_len;
        if (alg == CRYPTO_ALG_ML_DSA_65) {
            /* ML-DSA-65 signing (deterministic, FIPS 204) */
            if (crypto_ml_dsa_65_sign(priv_key, sz->priv_key_len,
                                       msg_bytes, msg_len,
                                       sig, &sig_len) != 0) {
                free(msg_bytes);
                cJSON_Delete(root);
                return make_error_response(id_str, -32602, "signing_failed");
            }
        } else if (alg == CRYPTO_ALG_SLH_DSA_128S) {
            /* SLH-DSA-128s signing (deterministic, FIPS 205) */
            if (crypto_slh_dsa_128s_sign(priv_key, sz->priv_key_len,
                                           msg_bytes, msg_len,
                                           sig, &sig_len) != 0) {
                free(msg_bytes);
                cJSON_Delete(root);
                return make_error_response(id_str, -32602, "signing_failed");
            }
        } else {
            /* ed25519 signing */
            if (crypto_ed25519_sign(priv_key, sz->priv_key_len,
                                     msg_bytes, msg_len,
                                     sig, &sig_len) != 0) {
                free(msg_bytes);
                cJSON_Delete(root);
                return make_error_response(id_str, -32602, "signing_failed");
            }
        }
        free(msg_bytes);

        /* Build result JSON: {"signature":"<hex>","algorithm":"<alg_name>"} */
        result_obj = cJSON_CreateObject();
        if (result_obj == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }

        {
            char *sig_hex = (char *)malloc(sig_len * 2 + 1);
            if (sig_hex == NULL) {
                cJSON_Delete(result_obj);
                cJSON_Delete(root);
                return make_error_response(id_str, -32602, "invalid_params");
            }
            nostr_bytes_to_hex(sig, sig_len, sig_hex);
            cJSON_AddStringToObject(result_obj, "signature", sig_hex);
            free(sig_hex);
        }

        alg_name = crypto_alg_to_str(alg);
        cJSON_AddStringToObject(result_obj, "algorithm",
                                 (alg_name != NULL) ? alg_name : "unknown");

        owned_result = cJSON_PrintUnformatted(result_obj);
        cJSON_Delete(result_obj);
        if (owned_result == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        result = owned_result;
    } else if (strcmp(method, VERB_VERIFY_SIG) == 0) {
        /* verify_signature: params = [message_bytes_hex, signature_hex, options]
         * Verify the signature. Returns {"valid":true/false}. */
        cJSON *msg_hex_item = cJSON_GetArrayItem(params_item, 0);
        cJSON *sig_hex_item = cJSON_GetArrayItem(params_item, 1);
        const char *msg_hex;
        const char *sig_hex;
        unsigned char *msg_bytes = NULL;
        unsigned char *sig_bytes = NULL;
        size_t msg_len = 0;
        size_t sig_len = 0;
        const char *pub_hex;
        unsigned char *pub = NULL;
        size_t pub_hex_len;
        const crypto_alg_sizes_t *sz;
        int verify_rc;
        cJSON *result_obj = NULL;

        if (!cJSON_IsString(msg_hex_item) || msg_hex_item->valuestring == NULL ||
            !cJSON_IsString(sig_hex_item) || sig_hex_item->valuestring == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        msg_hex = msg_hex_item->valuestring;
        sig_hex = sig_hex_item->valuestring;

        alg = crypto_alg_from_role(role->curve, role->purpose);
        sz = crypto_alg_get_sizes(alg);
        if (sz == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }

        if (alg != CRYPTO_ALG_ED25519 && alg != CRYPTO_ALG_ML_DSA_65 &&
            alg != CRYPTO_ALG_SLH_DSA_128S) {
            cJSON_Delete(root);
            return make_error_response(id_str, 1009, "not_yet_implemented");
        }

        /* Get the public key hex for this role. */
        pub_hex = crypto_get_pubkey_hex(ctx->key_store, role_index);
        if (pub_hex == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "key_not_derived");
        }
        pub_hex_len = strlen(pub_hex);
        /* Check pub_hex length matches expected (2 * pub_key_len) */
        if (pub_hex_len != sz->pub_key_len * 2) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "key_not_derived");
        }
        pub = (unsigned char *)malloc(sz->pub_key_len);
        if (pub == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        if (nostr_hex_to_bytes(pub_hex, pub, sz->pub_key_len) != 0) {
            free(pub);
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }

        /* Decode message and signature from hex. */
        msg_len = strlen(msg_hex) / 2;
        sig_len = strlen(sig_hex) / 2;
        if (msg_len == 0 || sig_len == 0) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        msg_bytes = (unsigned char *)malloc(msg_len);
        sig_bytes = (unsigned char *)malloc(sig_len);
        if (msg_bytes == NULL || sig_bytes == NULL) {
            free(msg_bytes);
            free(sig_bytes);
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        if (nostr_hex_to_bytes(msg_hex, msg_bytes, msg_len) != 0 ||
            nostr_hex_to_bytes(sig_hex, sig_bytes, sig_len) != 0) {
            free(msg_bytes);
            free(sig_bytes);
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }

        if (alg == CRYPTO_ALG_ML_DSA_65) {
            verify_rc = crypto_ml_dsa_65_verify(pub, sz->pub_key_len,
                                                 msg_bytes, msg_len,
                                                 sig_bytes, sig_len);
        } else if (alg == CRYPTO_ALG_SLH_DSA_128S) {
            verify_rc = crypto_slh_dsa_128s_verify(pub, sz->pub_key_len,
                                                     msg_bytes, msg_len,
                                                     sig_bytes, sig_len);
        } else {
            verify_rc = crypto_ed25519_verify(pub, sz->pub_key_len,
                                               msg_bytes, msg_len,
                                               sig_bytes, sig_len);
        }
        free(pub);
        free(msg_bytes);
        free(sig_bytes);

        result_obj = cJSON_CreateObject();
        if (result_obj == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        cJSON_AddBoolToObject(result_obj, "valid", (verify_rc == 0) ? 1 : 0);

        owned_result = cJSON_PrintUnformatted(result_obj);
        cJSON_Delete(result_obj);
        if (owned_result == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        result = owned_result;
    } else if (strcmp(method, VERB_KEM_ENCAPS) == 0) {
        /* kem_encapsulate: params = [peer_pubkey_hex, options]
         * Encapsulate with the peer's ML-KEM-768 public key.
         * Returns {"ciphertext":"<hex>","shared_secret":"<hex>","algorithm":"ml-kem-768"} */
        cJSON *pub_hex_item = cJSON_GetArrayItem(params_item, 0);
        const char *pub_hex;
        unsigned char *pub = NULL;
        unsigned char ct[1088];
        unsigned char ss[32];
        cJSON *result_obj = NULL;
        const crypto_alg_sizes_t *sz;

        if (!cJSON_IsString(pub_hex_item) || pub_hex_item->valuestring == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        pub_hex = pub_hex_item->valuestring;

        alg = crypto_alg_from_role(role->curve, role->purpose);
        sz = crypto_alg_get_sizes(alg);
        if (sz == NULL || alg != CRYPTO_ALG_ML_KEM_768) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }

        /* Decode hex public key (1184 bytes = 2368 hex chars) */
        if (strlen(pub_hex) != sz->pub_key_len * 2) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_pubkey_length");
        }
        pub = (unsigned char *)malloc(sz->pub_key_len);
        if (pub == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        if (nostr_hex_to_bytes(pub_hex, pub, sz->pub_key_len) != 0) {
            free(pub);
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_pubkey_hex");
        }

        if (crypto_ml_kem_768_encaps(pub, sz->pub_key_len, ct, ss) != 0) {
            free(pub);
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "encaps_failed");
        }
        free(pub);

        /* Build result JSON */
        result_obj = cJSON_CreateObject();
        if (result_obj == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        {
            char *ct_hex = (char *)malloc(sz->ciphertext_len * 2 + 1);
            char *ss_hex = (char *)malloc(sz->shared_secret_len * 2 + 1);
            if (ct_hex == NULL || ss_hex == NULL) {
                free(ct_hex); free(ss_hex);
                cJSON_Delete(result_obj);
                cJSON_Delete(root);
                return make_error_response(id_str, -32602, "invalid_params");
            }
            nostr_bytes_to_hex(ct, sz->ciphertext_len, ct_hex);
            nostr_bytes_to_hex(ss, sz->shared_secret_len, ss_hex);
            cJSON_AddStringToObject(result_obj, "ciphertext", ct_hex);
            cJSON_AddStringToObject(result_obj, "shared_secret", ss_hex);
            free(ct_hex); free(ss_hex);
        }
        cJSON_AddStringToObject(result_obj, "algorithm", "ml-kem-768");

        owned_result = cJSON_PrintUnformatted(result_obj);
        cJSON_Delete(result_obj);
        if (owned_result == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        result = owned_result;
    } else if (strcmp(method, VERB_KEM_DECAPS) == 0) {
        /* kem_decapsulate: params = [ciphertext_hex, options]
         * Decapsulate using the role's ML-KEM-768 private key.
         * Returns {"shared_secret":"<hex>","algorithm":"ml-kem-768"} */
        cJSON *ct_hex_item = cJSON_GetArrayItem(params_item, 0);
        const char *ct_hex;
        unsigned char *ct = NULL;
        unsigned char ss[32];
        const unsigned char *priv_key;
        const crypto_alg_sizes_t *sz;
        cJSON *result_obj = NULL;

        if (!cJSON_IsString(ct_hex_item) || ct_hex_item->valuestring == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        ct_hex = ct_hex_item->valuestring;

        alg = crypto_alg_from_role(role->curve, role->purpose);
        sz = crypto_alg_get_sizes(alg);
        if (sz == NULL || alg != CRYPTO_ALG_ML_KEM_768) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }

        /* Get the role's private key */
        priv_key = crypto_get_private_key(ctx->key_store, role_index);
        if (priv_key == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "key_not_derived");
        }

        /* Decode hex ciphertext (1088 bytes = 2176 hex chars) */
        if (strlen(ct_hex) != sz->ciphertext_len * 2) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_ciphertext_length");
        }
        ct = (unsigned char *)malloc(sz->ciphertext_len);
        if (ct == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        if (nostr_hex_to_bytes(ct_hex, ct, sz->ciphertext_len) != 0) {
            free(ct);
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_ciphertext_hex");
        }

        if (crypto_ml_kem_768_decaps(priv_key, sz->priv_key_len,
                                       ct, sz->ciphertext_len, ss) != 0) {
            free(ct);
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "decaps_failed");
        }
        free(ct);

        /* Build result JSON */
        result_obj = cJSON_CreateObject();
        if (result_obj == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        {
            char *ss_hex = (char *)malloc(sz->shared_secret_len * 2 + 1);
            if (ss_hex == NULL) {
                cJSON_Delete(result_obj);
                cJSON_Delete(root);
                return make_error_response(id_str, -32602, "invalid_params");
            }
            nostr_bytes_to_hex(ss, sz->shared_secret_len, ss_hex);
            cJSON_AddStringToObject(result_obj, "shared_secret", ss_hex);
            free(ss_hex);
        }
        cJSON_AddStringToObject(result_obj, "algorithm", "ml-kem-768");

        owned_result = cJSON_PrintUnformatted(result_obj);
        cJSON_Delete(result_obj);
        if (owned_result == NULL) {
            cJSON_Delete(root);
            return make_error_response(id_str, -32602, "invalid_params");
        }
        result = owned_result;
    } else {
        cJSON_Delete(root);
        return make_error_response(id_str, -32601, "method_not_found");
    }

    cJSON_Delete(root);
    {
        char *response = make_success_response(id_str, result);
        free(owned_result);
        return response;
    }
}
