#define _GNU_SOURCE

/* NSIGNER_HEADERLESS_DECLS_BEGIN */
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
#include <cJSON.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"

/* 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"

/*
 * Check whether `verb` is allowed to execute against `role`.
 * Returns ENFORCE_OK if allowed, or an ENFORCE_ERR_* code.
 */
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

/* 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);

/* 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).
 * priv_out must be at least 2400 bytes, pub_out at least 1184 bytes.
 * Returns 0 on success, -1 on error. */
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.
 * Returns 0 on success, -1 on error. */
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.
 * ss_out must be at least 32 bytes. Returns 0 on success, -1 on error. */
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 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 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.
 * 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);

/* Derive key for exactly one role index. Returns 0 on success, -1 on error. */
int crypto_derive_one(key_store_t *store, role_table_t *table, const mnemonic_state_t *mnemonic, int role_index);

/* 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.
 * event_json is the unsigned event JSON string.
 * difficulty: target leading zero bits (0 = no target, mine for full timeout)
 * threads: number of mining threads (1..32)
 * timeout_sec: time budget in seconds (0 = use 600s safety default)
 * Returns a newly-allocated JSON string containing a result object:
 *   {"event":"<signed event json>","achieved_difficulty":N,"target_difficulty":N,
 *    "target_reached":bool,"elapsed_sec":N,"attempts":N}
 * Returns 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);

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


/* 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.
 */
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];
    char last_error[256];
    int listen_fd;
    int running;
    dispatcher_ctx_t *dispatcher;
    policy_table_t *policy;
    int socket_name_explicit;
} server_ctx_t;

void server_init(server_ctx_t *ctx, const char *socket_name, int socket_name_explicit,
                 dispatcher_ctx_t *dispatcher, policy_table_t *policy);
int server_start(server_ctx_t *ctx);
const char *server_last_error(const server_ctx_t *ctx);
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);
void server_stop(server_ctx_t *ctx);
int server_get_caller(int fd, caller_identity_t *out);


/* from socket_name.h */


int socket_name_random(char *out, size_t out_len);


/* from main.h */


#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 <nostr_core/nostr_common.h>
#include <nostr_core/nip001.h>
#include <nostr_core/nip004.h>
#include <nostr_core/nip006.h>
#include <nostr_core/nip013.h>
#include <nostr_core/nip019.h>
#include <nostr_core/nip044.h>
#include <nostr_core/utils.h>

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

#define NSIGNER_ENCRYPT_OUTPUT_MAX 65536

/*
 * Derive a secp256k1 (Nostr) key for a role into the variable-length
 * derived_key_t.  Returns 0 on success, -1 on failure.
 */
static int derive_secp256k1(derived_key_t *dst, const role_entry_t *role,
                            const mnemonic_state_t *mnemonic) {
    unsigned char priv[32];
    unsigned char pub[32];
    const crypto_alg_sizes_t *sz;

    sz = crypto_alg_get_sizes(CRYPTO_ALG_SECP256K1);
    if (sz == NULL) {
        return -1;
    }

    if (secure_buf_alloc(&dst->private_key, sz->priv_key_len) != 0) {
        return -1;
    }
    if (secure_buf_alloc(&dst->public_key, sz->pub_key_len) != 0) {
        secure_buf_free(&dst->private_key);
        return -1;
    }

    if (nostr_derive_keys_from_mnemonic(mnemonic_get_phrase(mnemonic),
                                        role->nostr_index, priv, pub) != 0) {
        secure_memzero(priv, sizeof(priv));
        secure_memzero(pub, sizeof(pub));
        secure_buf_free(&dst->private_key);
        secure_buf_free(&dst->public_key);
        return -1;
    }

    memcpy(dst->private_key.data, priv, sz->priv_key_len);
    memcpy(dst->public_key.data, pub, sz->pub_key_len);

    nostr_bytes_to_hex((const unsigned char *)dst->public_key.data,
                       sz->pub_key_len, dst->pubkey_hex);
    dst->npub[0] = '\0';
    (void)nostr_key_to_bech32(pub, "npub", dst->npub);

    dst->alg = CRYPTO_ALG_SECP256K1;
    dst->valid = 1;

    secure_memzero(priv, sizeof(priv));
    secure_memzero(pub, sizeof(pub));
    return 0;
}

/*
 * Derive an ed25519 key for a role using SLIP-0010 derivation from the
 * mnemonic.  The path is m/44'/102001'/<n>'/0'/0' (all hardened).
 * Returns 0 on success, -1 on failure.
 */
static int derive_ed25519(derived_key_t *dst, const role_entry_t *role,
                           const mnemonic_state_t *mnemonic) {
    unsigned char seed[32];
    unsigned char priv[32];
    unsigned char pub[32];
    const crypto_alg_sizes_t *sz;
    char path[ROLE_PATH_MAX];

    sz = crypto_alg_get_sizes(CRYPTO_ALG_ED25519);
    if (sz == NULL) {
        return -1;
    }

    if (secure_buf_alloc(&dst->private_key, sz->priv_key_len) != 0) {
        return -1;
    }
    if (secure_buf_alloc(&dst->public_key, sz->pub_key_len) != 0) {
        secure_buf_free(&dst->private_key);
        return -1;
    }

    snprintf(path, sizeof(path), "m/44'/102001'/%d'/0'/0'", role->nostr_index);

    if (crypto_derive_seed_from_mnemonic(mnemonic_get_phrase(mnemonic), path,
                                          seed, sizeof(seed)) != 0) {
        secure_buf_free(&dst->private_key);
        secure_buf_free(&dst->public_key);
        return -1;
    }

    if (crypto_ed25519_keygen_from_seed(seed, sizeof(seed), priv, pub) != 0) {
        secure_memzero(seed, sizeof(seed));
        secure_buf_free(&dst->private_key);
        secure_buf_free(&dst->public_key);
        return -1;
    }

    memcpy(dst->private_key.data, priv, sz->priv_key_len);
    memcpy(dst->public_key.data, pub, sz->pub_key_len);

    nostr_bytes_to_hex((const unsigned char *)dst->public_key.data,
                       sz->pub_key_len, dst->pubkey_hex);
    dst->npub[0] = '\0';

    dst->alg = CRYPTO_ALG_ED25519;
    dst->valid = 1;

    secure_memzero(seed, sizeof(seed));
    secure_memzero(priv, sizeof(priv));
    secure_memzero(pub, sizeof(pub));
    return 0;
}

/*
 * Derive an x25519 key for a role using SLIP-0010 derivation from the
 * mnemonic.  The path is m/44'/102002'/<n>'/0'/0' (all hardened).
 * Returns 0 on success, -1 on failure.
 */
static int derive_x25519(derived_key_t *dst, const role_entry_t *role,
                          const mnemonic_state_t *mnemonic) {
    unsigned char seed[32];
    unsigned char priv[32];
    unsigned char pub[32];
    const crypto_alg_sizes_t *sz;
    char path[ROLE_PATH_MAX];

    sz = crypto_alg_get_sizes(CRYPTO_ALG_X25519);
    if (sz == NULL) {
        return -1;
    }

    if (secure_buf_alloc(&dst->private_key, sz->priv_key_len) != 0) {
        return -1;
    }
    if (secure_buf_alloc(&dst->public_key, sz->pub_key_len) != 0) {
        secure_buf_free(&dst->private_key);
        return -1;
    }

    snprintf(path, sizeof(path), "m/44'/102002'/%d'/0'/0'", role->nostr_index);

    if (crypto_derive_seed_from_mnemonic(mnemonic_get_phrase(mnemonic), path,
                                          seed, sizeof(seed)) != 0) {
        secure_buf_free(&dst->private_key);
        secure_buf_free(&dst->public_key);
        return -1;
    }

    if (crypto_x25519_keygen_from_seed(seed, sizeof(seed), priv, pub) != 0) {
        secure_memzero(seed, sizeof(seed));
        secure_buf_free(&dst->private_key);
        secure_buf_free(&dst->public_key);
        return -1;
    }

    memcpy(dst->private_key.data, priv, sz->priv_key_len);
    memcpy(dst->public_key.data, pub, sz->pub_key_len);

    nostr_bytes_to_hex((const unsigned char *)dst->public_key.data,
                       sz->pub_key_len, dst->pubkey_hex);
    dst->npub[0] = '\0';

    dst->alg = CRYPTO_ALG_X25519;
    dst->valid = 1;

    secure_memzero(seed, sizeof(seed));
    secure_memzero(priv, sizeof(priv));
    secure_memzero(pub, sizeof(pub));
    return 0;
}

/*
 * Derive an ML-DSA-65 key for a role using SLIP-0010 derivation from the
 * mnemonic.  The path is m/44'/102003'/<n>'/0'/0' (all hardened).
 * Returns 0 on success, -1 on failure.
 */
static int derive_ml_dsa_65(derived_key_t *dst, const role_entry_t *role,
                             const mnemonic_state_t *mnemonic) {
    unsigned char seed[32];
    const crypto_alg_sizes_t *sz;
    char path[ROLE_PATH_MAX];

    sz = crypto_alg_get_sizes(CRYPTO_ALG_ML_DSA_65);
    if (sz == NULL) {
        return -1;
    }

    if (secure_buf_alloc(&dst->private_key, sz->priv_key_len) != 0) {
        return -1;
    }
    if (secure_buf_alloc(&dst->public_key, sz->pub_key_len) != 0) {
        secure_buf_free(&dst->private_key);
        return -1;
    }

    snprintf(path, sizeof(path), "m/44'/102003'/%d'/0'/0'", role->nostr_index);

    if (crypto_derive_seed_from_mnemonic(mnemonic_get_phrase(mnemonic), path,
                                          seed, sizeof(seed)) != 0) {
        secure_buf_free(&dst->private_key);
        secure_buf_free(&dst->public_key);
        return -1;
    }

    if (crypto_ml_dsa_65_keygen_from_seed(seed, sizeof(seed),
                                           (unsigned char *)dst->private_key.data,
                                           (unsigned char *)dst->public_key.data) != 0) {
        secure_memzero(seed, sizeof(seed));
        secure_buf_free(&dst->private_key);
        secure_buf_free(&dst->public_key);
        return -1;
    }

    nostr_bytes_to_hex((const unsigned char *)dst->public_key.data,
                       sz->pub_key_len, dst->pubkey_hex);
    dst->npub[0] = '\0';

    dst->alg = CRYPTO_ALG_ML_DSA_65;
    dst->valid = 1;

    secure_memzero(seed, sizeof(seed));
    return 0;
}

/*
 * Derive an SLH-DSA-128s key for a role using SLIP-0010 derivation from the
 * mnemonic.  The path is m/44'/102004'/<n>'/0'/0' (all hardened).
 * Returns 0 on success, -1 on failure.
 */
static int derive_slh_dsa_128s(derived_key_t *dst, const role_entry_t *role,
                                 const mnemonic_state_t *mnemonic) {
    unsigned char seed[32];
    const crypto_alg_sizes_t *sz;
    char path[ROLE_PATH_MAX];

    sz = crypto_alg_get_sizes(CRYPTO_ALG_SLH_DSA_128S);
    if (sz == NULL) {
        return -1;
    }

    if (secure_buf_alloc(&dst->private_key, sz->priv_key_len) != 0) {
        return -1;
    }
    if (secure_buf_alloc(&dst->public_key, sz->pub_key_len) != 0) {
        secure_buf_free(&dst->private_key);
        return -1;
    }

    snprintf(path, sizeof(path), "m/44'/102004'/%d'/0'/0'", role->nostr_index);

    if (crypto_derive_seed_from_mnemonic(mnemonic_get_phrase(mnemonic), path,
                                          seed, sizeof(seed)) != 0) {
        secure_buf_free(&dst->private_key);
        secure_buf_free(&dst->public_key);
        return -1;
    }

    if (crypto_slh_dsa_128s_keygen_from_seed(seed, sizeof(seed),
                                                (unsigned char *)dst->private_key.data,
                                                (unsigned char *)dst->public_key.data) != 0) {
        secure_memzero(seed, sizeof(seed));
        secure_buf_free(&dst->private_key);
        secure_buf_free(&dst->public_key);
        return -1;
    }

    nostr_bytes_to_hex((const unsigned char *)dst->public_key.data,
                       sz->pub_key_len, dst->pubkey_hex);
    dst->npub[0] = '\0';

    dst->alg = CRYPTO_ALG_SLH_DSA_128S;
    dst->valid = 1;

    secure_memzero(seed, sizeof(seed));
    return 0;
}

/*
 * Derive an ML-KEM-768 key for a role using SLIP-0010 derivation from the
 * mnemonic.  The path is m/44'/102005'/<n>'/0'/0' (all hardened).
 * Returns 0 on success, -1 on failure.
 */
static int derive_ml_kem_768(derived_key_t *dst, const role_entry_t *role,
                               const mnemonic_state_t *mnemonic) {
    unsigned char seed[32];
    const crypto_alg_sizes_t *sz;
    char path[ROLE_PATH_MAX];

    sz = crypto_alg_get_sizes(CRYPTO_ALG_ML_KEM_768);
    if (sz == NULL) {
        return -1;
    }

    if (secure_buf_alloc(&dst->private_key, sz->priv_key_len) != 0) {
        return -1;
    }
    if (secure_buf_alloc(&dst->public_key, sz->pub_key_len) != 0) {
        secure_buf_free(&dst->private_key);
        return -1;
    }

    snprintf(path, sizeof(path), "m/44'/102005'/%d'/0'/0'", role->nostr_index);

    if (crypto_derive_seed_from_mnemonic(mnemonic_get_phrase(mnemonic), path,
                                          seed, sizeof(seed)) != 0) {
        secure_buf_free(&dst->private_key);
        secure_buf_free(&dst->public_key);
        return -1;
    }

    if (crypto_ml_kem_768_keygen_from_seed(seed, sizeof(seed),
                                              (unsigned char *)dst->private_key.data,
                                              (unsigned char *)dst->public_key.data) != 0) {
        secure_memzero(seed, sizeof(seed));
        secure_buf_free(&dst->private_key);
        secure_buf_free(&dst->public_key);
        return -1;
    }

    nostr_bytes_to_hex((const unsigned char *)dst->public_key.data,
                       sz->pub_key_len, dst->pubkey_hex);
    dst->npub[0] = '\0';

    dst->alg = CRYPTO_ALG_ML_KEM_768;
    dst->valid = 1;

    secure_memzero(seed, sizeof(seed));
    return 0;
}

/*
 * Derive a key for a single role into `dst` using the algorithm selected
 * by crypto_alg_from_role().  Returns 0 on success, -1 if the algorithm
 * is unsupported/unknown or derivation fails.
 */
static int derive_for_role(derived_key_t *dst, const role_entry_t *role,
                           const mnemonic_state_t *mnemonic) {
    crypto_alg_t alg;

    alg = crypto_alg_from_role(role->curve, role->purpose);
    if (alg == CRYPTO_ALG_UNKNOWN) {
        return -1;
    }

    switch (alg) {
        case CRYPTO_ALG_SECP256K1:
            return derive_secp256k1(dst, role, mnemonic);
        case CRYPTO_ALG_ED25519:
            return derive_ed25519(dst, role, mnemonic);
        case CRYPTO_ALG_X25519:
            return derive_x25519(dst, role, mnemonic);
        case CRYPTO_ALG_ML_DSA_65:
            return derive_ml_dsa_65(dst, role, mnemonic);
        case CRYPTO_ALG_SLH_DSA_128S:
            return derive_slh_dsa_128s(dst, role, mnemonic);
        case CRYPTO_ALG_ML_KEM_768:
            return derive_ml_kem_768(dst, role, mnemonic);
        case CRYPTO_ALG_UNKNOWN:
        default:
            return -1;
    }
}

int crypto_derive_all(key_store_t *store, role_table_t *table, const mnemonic_state_t *mnemonic) {
    int i;
    int derived_count;

    if (store == NULL || table == NULL || mnemonic == NULL) {
        return -1;
    }

    if (!mnemonic_is_loaded(mnemonic)) {
        return -1;
    }

    crypto_wipe(store);
    derived_count = 0;

    for (i = 0; i < table->count; ++i) {
        role_entry_t *role = &table->entries[i];
        derived_key_t *dst = &store->keys[i];

        role->derived = 0;
        role->pubkey_hex[0] = '\0';

        if (role->selector_type != SELECTOR_NOSTR_INDEX) {
            continue;
        }

        if (derive_for_role(dst, role, mnemonic) != 0) {
            continue;
        }

        strncpy(role->pubkey_hex, dst->pubkey_hex, sizeof(role->pubkey_hex) - 1);
        role->pubkey_hex[sizeof(role->pubkey_hex) - 1] = '\0';
        role->derived = 1;

        derived_count++;
    }

    store->count = table->count;
    return derived_count;
}

int crypto_derive_one(key_store_t *store, role_table_t *table, const mnemonic_state_t *mnemonic, int role_index) {
    role_entry_t *role;
    derived_key_t *dst;

    if (store == NULL || table == NULL || mnemonic == NULL) {
        return -1;
    }

    if (!mnemonic_is_loaded(mnemonic)) {
        return -1;
    }

    if (role_index < 0 || role_index >= table->count || role_index >= ROLE_TABLE_MAX_ENTRIES) {
        return -1;
    }

    role = &table->entries[role_index];
    dst = &store->keys[role_index];

    role->derived = 0;
    role->pubkey_hex[0] = '\0';

    secure_buf_free(&dst->private_key);
    secure_buf_free(&dst->public_key);
    secure_memzero(dst->pubkey_hex, sizeof(dst->pubkey_hex));
    secure_memzero(dst->npub, sizeof(dst->npub));
    dst->alg = CRYPTO_ALG_UNKNOWN;
    dst->valid = 0;

    if (role->selector_type != SELECTOR_NOSTR_INDEX) {
        return -1;
    }

    if (derive_for_role(dst, role, mnemonic) != 0) {
        return -1;
    }

    strncpy(role->pubkey_hex, dst->pubkey_hex, sizeof(role->pubkey_hex) - 1);
    role->pubkey_hex[sizeof(role->pubkey_hex) - 1] = '\0';
    role->derived = 1;

    if (store->count < table->count) {
        store->count = table->count;
    }

    return 0;
}

const unsigned char *crypto_get_private_key(const key_store_t *store, int role_index) {
    if (store == NULL || role_index < 0 || role_index >= ROLE_TABLE_MAX_ENTRIES) {
        return NULL;
    }

    if (!store->keys[role_index].valid || store->keys[role_index].private_key.data == NULL) {
        return NULL;
    }

    return (const unsigned char *)store->keys[role_index].private_key.data;
}

const char *crypto_get_pubkey_hex(const key_store_t *store, int role_index) {
    if (store == NULL || role_index < 0 || role_index >= ROLE_TABLE_MAX_ENTRIES) {
        return NULL;
    }

    if (!store->keys[role_index].valid) {
        return NULL;
    }

    return store->keys[role_index].pubkey_hex;
}

char *crypto_sign_event(const key_store_t *store, int role_index, const char *event_json) {
    const unsigned char *private_key;
    cJSON *parsed = NULL;
    cJSON *kind_item;
    cJSON *content_item;
    cJSON *tags_item;
    cJSON *created_at_item;
    cJSON *tags_for_sign = NULL;
    int kind;
    const char *content;
    time_t timestamp = 0;
    cJSON *signed_event = NULL;
    char *out = NULL;

    if (event_json == NULL) {
        return NULL;
    }

    private_key = crypto_get_private_key(store, role_index);
    if (private_key == NULL) {
        return NULL;
    }

    parsed = cJSON_Parse(event_json);
    if (parsed == NULL || !cJSON_IsObject(parsed)) {
        cJSON_Delete(parsed);
        return NULL;
    }

    kind_item = cJSON_GetObjectItemCaseSensitive(parsed, "kind");
    content_item = cJSON_GetObjectItemCaseSensitive(parsed, "content");
    tags_item = cJSON_GetObjectItemCaseSensitive(parsed, "tags");
    created_at_item = cJSON_GetObjectItemCaseSensitive(parsed, "created_at");

    if (!cJSON_IsNumber(kind_item) || !cJSON_IsString(content_item) || content_item->valuestring == NULL) {
        cJSON_Delete(parsed);
        return NULL;
    }

    kind = kind_item->valueint;
    content = content_item->valuestring;

    if (cJSON_IsNumber(created_at_item)) {
        timestamp = (time_t)created_at_item->valuedouble;
    }

    if (cJSON_IsArray(tags_item)) {
        tags_for_sign = cJSON_Duplicate(tags_item, 1);
        if (tags_for_sign == NULL) {
            cJSON_Delete(parsed);
            return NULL;
        }
    }

    signed_event = nostr_create_and_sign_event(kind, content, tags_for_sign, private_key, timestamp);
    cJSON_Delete(tags_for_sign);
    cJSON_Delete(parsed);

    if (signed_event == NULL) {
        return NULL;
    }

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

/* ---- mine_result_t and miner_run are defined in miner.c ---- */
typedef struct {
    cJSON *best_event;
    int    achieved_difficulty;
    int    target_difficulty;
    int    target_reached;
    int    elapsed_sec;
    uint64_t total_attempts;
} mine_result_t;

int miner_run(cJSON *event, const unsigned char *private_key,
              int target_difficulty, int thread_count, int timeout_sec,
              mine_result_t *result);

char *crypto_mine_event(const key_store_t *store, int role_index,
                        const char *event_json, int difficulty,
                        int threads, int timeout_sec) {
    const unsigned char *private_key;
    cJSON *parsed = NULL;
    mine_result_t result;
    char *event_str = NULL;
    cJSON *result_obj = NULL;
    char *out = NULL;

    if (event_json == NULL) {
        return NULL;
    }

    private_key = crypto_get_private_key(store, role_index);
    if (private_key == NULL) {
        return NULL;
    }

    parsed = cJSON_Parse(event_json);
    if (parsed == NULL || !cJSON_IsObject(parsed)) {
        cJSON_Delete(parsed);
        return NULL;
    }

    memset(&result, 0, sizeof(result));
    if (miner_run(parsed, private_key, difficulty, threads, timeout_sec, &result) != 0) {
        cJSON_Delete(parsed);
        return NULL;
    }

    if (result.best_event == NULL) {
        cJSON_Delete(parsed);
        return NULL;
    }

    event_str = cJSON_PrintUnformatted(result.best_event);
    cJSON_Delete(result.best_event);
    cJSON_Delete(parsed);

    if (event_str == NULL) {
        return NULL;
    }

    result_obj = cJSON_CreateObject();
    if (result_obj == NULL) {
        free(event_str);
        return NULL;
    }

    cJSON_AddItemToObject(result_obj, "event", cJSON_CreateString(event_str));
    free(event_str);

    cJSON_AddNumberToObject(result_obj, "achieved_difficulty", result.achieved_difficulty);
    cJSON_AddNumberToObject(result_obj, "target_difficulty", result.target_difficulty);
    cJSON_AddBoolToObject(result_obj, "target_reached", result.target_reached);
    cJSON_AddNumberToObject(result_obj, "elapsed_sec", result.elapsed_sec);
    cJSON_AddNumberToObject(result_obj, "attempts", (double)result.total_attempts);

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

static int parse_hex_pubkey32(const char *hex, unsigned char out[32]) {
    if (hex == NULL || out == NULL || strlen(hex) != 64) {
        return -1;
    }
    if (nostr_hex_to_bytes(hex, out, 32) != 0) {
        return -1;
    }
    return 0;
}

char *crypto_nip44_encrypt(const key_store_t *store, int role_index,
                           const char *recipient_pubkey_hex, const char *plaintext) {
    const unsigned char *private_key;
    unsigned char recipient_pub[32];
    char *out;

    if (plaintext == NULL || recipient_pubkey_hex == NULL) {
        return NULL;
    }

    private_key = crypto_get_private_key(store, role_index);
    if (private_key == NULL || parse_hex_pubkey32(recipient_pubkey_hex, recipient_pub) != 0) {
        return NULL;
    }

    out = (char *)malloc(NSIGNER_ENCRYPT_OUTPUT_MAX);
    if (out == NULL) {
        return NULL;
    }
    out[0] = '\0';

    if (nostr_nip44_encrypt(private_key, recipient_pub, plaintext, out, NSIGNER_ENCRYPT_OUTPUT_MAX) != 0) {
        free(out);
        return NULL;
    }

    return out;
}

char *crypto_nip44_decrypt(const key_store_t *store, int role_index,
                           const char *sender_pubkey_hex, const char *ciphertext) {
    const unsigned char *private_key;
    unsigned char sender_pub[32];
    char *out;

    if (ciphertext == NULL || sender_pubkey_hex == NULL) {
        return NULL;
    }

    private_key = crypto_get_private_key(store, role_index);
    if (private_key == NULL || parse_hex_pubkey32(sender_pubkey_hex, sender_pub) != 0) {
        return NULL;
    }

    out = (char *)malloc(NSIGNER_ENCRYPT_OUTPUT_MAX);
    if (out == NULL) {
        return NULL;
    }
    out[0] = '\0';

    if (nostr_nip44_decrypt(private_key, sender_pub, ciphertext, out, NSIGNER_ENCRYPT_OUTPUT_MAX) != 0) {
        free(out);
        return NULL;
    }

    return out;
}

char *crypto_nip04_encrypt(const key_store_t *store, int role_index,
                           const char *recipient_pubkey_hex, const char *plaintext) {
    const unsigned char *private_key;
    unsigned char recipient_pub[32];
    char *out;

    if (plaintext == NULL || recipient_pubkey_hex == NULL) {
        return NULL;
    }

    private_key = crypto_get_private_key(store, role_index);
    if (private_key == NULL || parse_hex_pubkey32(recipient_pubkey_hex, recipient_pub) != 0) {
        return NULL;
    }

    out = (char *)malloc(NSIGNER_ENCRYPT_OUTPUT_MAX);
    if (out == NULL) {
        return NULL;
    }
    out[0] = '\0';

    if (nostr_nip04_encrypt(private_key, recipient_pub, plaintext, out, NSIGNER_ENCRYPT_OUTPUT_MAX) != 0) {
        free(out);
        return NULL;
    }

    return out;
}

char *crypto_nip04_decrypt(const key_store_t *store, int role_index,
                           const char *sender_pubkey_hex, const char *ciphertext) {
    const unsigned char *private_key;
    unsigned char sender_pub[32];
    char *out;

    if (ciphertext == NULL || sender_pubkey_hex == NULL) {
        return NULL;
    }

    private_key = crypto_get_private_key(store, role_index);
    if (private_key == NULL || parse_hex_pubkey32(sender_pubkey_hex, sender_pub) != 0) {
        return NULL;
    }

    out = (char *)malloc(NSIGNER_ENCRYPT_OUTPUT_MAX);
    if (out == NULL) {
        return NULL;
    }
    out[0] = '\0';

    if (nostr_nip04_decrypt(private_key, sender_pub, ciphertext, out, NSIGNER_ENCRYPT_OUTPUT_MAX) != 0) {
        free(out);
        return NULL;
    }

    return out;
}

void crypto_wipe(key_store_t *store) {
    int i;

    if (store == NULL) {
        return;
    }

    for (i = 0; i < ROLE_TABLE_MAX_ENTRIES; ++i) {
        secure_buf_free(&store->keys[i].private_key);
        secure_buf_free(&store->keys[i].public_key);
        secure_memzero(store->keys[i].pubkey_hex, sizeof(store->keys[i].pubkey_hex));
        secure_memzero(store->keys[i].npub, sizeof(store->keys[i].npub));
        store->keys[i].alg = CRYPTO_ALG_UNKNOWN;
        store->keys[i].valid = 0;
    }

    store->count = 0;
}

/* ===========================================================================
 * Algorithm key cache — on-demand key derivation by (algorithm, index).
 * ========================================================================== */

static int alg_key_derive_entry(alg_key_entry_t *entry,
                                  const mnemonic_state_t *mnemonic,
                                  crypto_alg_t alg, int index) {
    unsigned char seed[32];
    const crypto_alg_sizes_t *sz;
    char path[ROLE_PATH_MAX];
    int path_cointype;

    if (entry == NULL || mnemonic == NULL) {
        return -1;
    }

    sz = crypto_alg_get_sizes(alg);
    if (sz == NULL) {
        return -1;
    }

    secure_buf_free(&entry->private_key);
    secure_buf_free(&entry->public_key);
    secure_memzero(entry->pubkey_hex, sizeof(entry->pubkey_hex));
    secure_memzero(entry->key_id, sizeof(entry->key_id));
    entry->valid = 0;
    entry->alg = CRYPTO_ALG_UNKNOWN;
    entry->index = 0;

    if (secure_buf_alloc(&entry->private_key, sz->priv_key_len) != 0) {
        return -1;
    }
    if (secure_buf_alloc(&entry->public_key, sz->pub_key_len) != 0) {
        secure_buf_free(&entry->private_key);
        return -1;
    }

    if (alg == CRYPTO_ALG_SECP256K1) {
        if (nostr_derive_keys_from_mnemonic(mnemonic_get_phrase(mnemonic),
                                            index,
                                            (unsigned char *)entry->private_key.data,
                                            (unsigned char *)entry->public_key.data) != 0) {
            secure_buf_free(&entry->private_key);
            secure_buf_free(&entry->public_key);
            return -1;
        }
    } else {
        switch (alg) {
            case CRYPTO_ALG_ED25519:      path_cointype = 102001; break;
            case CRYPTO_ALG_X25519:       path_cointype = 102002; break;
            case CRYPTO_ALG_ML_DSA_65:    path_cointype = 102003; break;
            case CRYPTO_ALG_SLH_DSA_128S: path_cointype = 102004; break;
            case CRYPTO_ALG_ML_KEM_768:   path_cointype = 102005; break;
            default:
                secure_buf_free(&entry->private_key);
                secure_buf_free(&entry->public_key);
                return -1;
        }

        snprintf(path, sizeof(path), "m/44'/%d'/%d'/0'/0'", path_cointype, index);

        if (crypto_derive_seed_from_mnemonic(mnemonic_get_phrase(mnemonic), path,
                                              seed, sizeof(seed)) != 0) {
            secure_buf_free(&entry->private_key);
            secure_buf_free(&entry->public_key);
            return -1;
        }

        switch (alg) {
            case CRYPTO_ALG_ED25519:
                if (crypto_ed25519_keygen_from_seed(seed, sizeof(seed),
                                                      (unsigned char *)entry->private_key.data,
                                                      (unsigned char *)entry->public_key.data) != 0) {
                    secure_memzero(seed, sizeof(seed));
                    secure_buf_free(&entry->private_key);
                    secure_buf_free(&entry->public_key);
                    return -1;
                }
                break;
            case CRYPTO_ALG_X25519:
                if (crypto_x25519_keygen_from_seed(seed, sizeof(seed),
                                                      (unsigned char *)entry->private_key.data,
                                                      (unsigned char *)entry->public_key.data) != 0) {
                    secure_memzero(seed, sizeof(seed));
                    secure_buf_free(&entry->private_key);
                    secure_buf_free(&entry->public_key);
                    return -1;
                }
                break;
            case CRYPTO_ALG_ML_DSA_65:
                if (crypto_ml_dsa_65_keygen_from_seed(seed, sizeof(seed),
                                                        (unsigned char *)entry->private_key.data,
                                                        (unsigned char *)entry->public_key.data) != 0) {
                    secure_memzero(seed, sizeof(seed));
                    secure_buf_free(&entry->private_key);
                    secure_buf_free(&entry->public_key);
                    return -1;
                }
                break;
            case CRYPTO_ALG_SLH_DSA_128S:
                if (crypto_slh_dsa_128s_keygen_from_seed(seed, sizeof(seed),
                                                            (unsigned char *)entry->private_key.data,
                                                            (unsigned char *)entry->public_key.data) != 0) {
                    secure_memzero(seed, sizeof(seed));
                    secure_buf_free(&entry->private_key);
                    secure_buf_free(&entry->public_key);
                    return -1;
                }
                break;
            case CRYPTO_ALG_ML_KEM_768:
                if (crypto_ml_kem_768_keygen_from_seed(seed, sizeof(seed),
                                                          (unsigned char *)entry->private_key.data,
                                                          (unsigned char *)entry->public_key.data) != 0) {
                    secure_memzero(seed, sizeof(seed));
                    secure_buf_free(&entry->private_key);
                    secure_buf_free(&entry->public_key);
                    return -1;
                }
                break;
            default:
                secure_memzero(seed, sizeof(seed));
                secure_buf_free(&entry->private_key);
                secure_buf_free(&entry->public_key);
                return -1;
        }
        secure_memzero(seed, sizeof(seed));
    }

    nostr_bytes_to_hex((const unsigned char *)entry->public_key.data,
                       sz->pub_key_len, entry->pubkey_hex);

    if (strlen(entry->pubkey_hex) >= 16) {
        memcpy(entry->key_id, entry->pubkey_hex, 16);
        entry->key_id[16] = '\0';
    } else {
        entry->key_id[0] = '\0';
    }

    entry->alg = alg;
    entry->index = index;
    entry->valid = 1;

    return 0;
}

void alg_key_cache_init(algorithm_key_cache_t *cache) {
    if (cache == NULL) {
        return;
    }
    memset(cache, 0, sizeof(*cache));
}

void alg_key_cache_wipe(algorithm_key_cache_t *cache) {
    int i;

    if (cache == NULL) {
        return;
    }

    for (i = 0; i < ALG_KEY_CACHE_MAX; ++i) {
        secure_buf_free(&cache->entries[i].private_key);
        secure_buf_free(&cache->entries[i].public_key);
        secure_memzero(cache->entries[i].pubkey_hex, sizeof(cache->entries[i].pubkey_hex));
        secure_memzero(cache->entries[i].key_id, sizeof(cache->entries[i].key_id));
        cache->entries[i].alg = CRYPTO_ALG_UNKNOWN;
        cache->entries[i].index = 0;
        cache->entries[i].valid = 0;
    }

    cache->count = 0;
}

const alg_key_entry_t *alg_key_cache_get(algorithm_key_cache_t *cache, crypto_alg_t alg, int index) {
    int i;

    if (cache == NULL) {
        return NULL;
    }

    for (i = 0; i < cache->count && i < ALG_KEY_CACHE_MAX; ++i) {
        if (cache->entries[i].valid &&
            cache->entries[i].alg == alg &&
            cache->entries[i].index == index) {
            return &cache->entries[i];
        }
    }

    return NULL;
}

int alg_key_cache_derive(algorithm_key_cache_t *cache, const mnemonic_state_t *mnemonic, crypto_alg_t alg, int index) {
    int slot;

    if (cache == NULL || mnemonic == NULL) {
        return -1;
    }

    if (!mnemonic_is_loaded(mnemonic)) {
        return -1;
    }

    if (alg_key_cache_get(cache, alg, index) != NULL) {
        return 0;
    }

    if (cache->count >= ALG_KEY_CACHE_MAX) {
        secure_buf_free(&cache->entries[0].private_key);
        secure_buf_free(&cache->entries[0].public_key);
        secure_memzero(&cache->entries[0], sizeof(cache->entries[0]));

        memmove(&cache->entries[0], &cache->entries[1],
                (ALG_KEY_CACHE_MAX - 1) * sizeof(alg_key_entry_t));

        memset(&cache->entries[ALG_KEY_CACHE_MAX - 1], 0, sizeof(alg_key_entry_t));
        slot = ALG_KEY_CACHE_MAX - 1;
        cache->count = ALG_KEY_CACHE_MAX;
    } else {
        slot = cache->count;
        cache->count++;
    }

    if (alg_key_derive_entry(&cache->entries[slot], mnemonic, alg, index) != 0) {
        cache->count = slot;
        memset(&cache->entries[slot], 0, sizeof(cache->entries[slot]));
        return -1;
    }

    return 0;
}
