/* test_algorithm_api.c — Tests for the algorithm-based API.
 *
 * Tests the new verbs: sign, verify, encapsulate, decapsulate,
 * derive_shared_secret, and the algorithm-based get_public_key.
 * Also tests old verb aliases and enforcement.
 */

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

/* from secure_mem.h */
typedef struct {
    void *data;
    size_t size;
    int locked;
} secure_buf_t;
int secure_buf_alloc(secure_buf_t *buf, size_t size);
void secure_buf_free(secure_buf_t *buf);
void secure_memzero(void *ptr, size_t len);

/* from mnemonic.h */
#define MNEMONIC_MAX_LEN 256
typedef struct {
    secure_buf_t buf;
    int loaded;
    int word_count;
} mnemonic_state_t;
void mnemonic_init(mnemonic_state_t *state);
int mnemonic_load(mnemonic_state_t *state, const char *phrase);
void mnemonic_unload(mnemonic_state_t *state);
int mnemonic_is_loaded(const mnemonic_state_t *state);
const char *mnemonic_get_phrase(const mnemonic_state_t *state);

/* from role_table.h */
#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
#define ROLE_TABLE_MAX_ENTRIES 256
typedef enum { PURPOSE_NOSTR=0, PURPOSE_BITCOIN, PURPOSE_SSH, PURPOSE_AGE, PURPOSE_FIPS, PURPOSE_PQ_SIG, PURPOSE_PQ_KEM, PURPOSE_UNKNOWN } role_purpose_t;
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;
typedef enum { SELECTOR_NOSTR_INDEX, SELECTOR_ROLE_PATH } role_selector_type_t;
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;
    char role_path[ROLE_PATH_MAX];
    char pubkey_hex[ROLE_PUBKEY_HEX_MAX];
    int derived;
} role_entry_t;
typedef struct { role_entry_t entries[ROLE_TABLE_MAX_ENTRIES]; int count; } role_table_t;
void role_table_init(role_table_t *table);
int role_table_add(role_table_t *table, const role_entry_t *entry);
role_entry_t *role_table_find_by_name(role_table_t *table, const char *name);
role_purpose_t role_purpose_from_str(const char *s);
role_curve_t role_curve_from_str(const char *s);

/* from enforcement.h */
#define ENFORCE_OK                0
#define ENFORCE_ERR_PURPOSE      -1
#define ENFORCE_ERR_CURVE        -2
#define ENFORCE_ERR_UNKNOWN_VERB -3
#define ENFORCE_ERR_ALGORITHM  -4
#define VERB_SIGN              "sign"
#define VERB_VERIFY            "verify"
#define VERB_ENCAPSULATE       "encapsulate"
#define VERB_DECAPSULATE       "decapsulate"
#define VERB_DERIVE_SHARED     "derive_shared_secret"
#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"
int enforce_verb_role(const char *verb, const role_entry_t *role);
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
typedef enum { PROMPT_NEVER=0, PROMPT_FIRST_PER_BOOT, PROMPT_EVERY_REQUEST, PROMPT_DENY } prompt_mode_t;
typedef enum { POLICY_SOURCE_DEFAULT=0, POLICY_SOURCE_PREAPPROVE, POLICY_SOURCE_SESSION_GRANT } policy_source_t;
typedef struct {
    char caller[POLICY_CALLER_MAX_LEN];
    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;
    char algorithms[16][32];
    int alg_count;
    int index_min;
    int index_max;
    prompt_mode_t prompt;
    policy_source_t source;
} policy_entry_t;
typedef struct { policy_entry_t entries[POLICY_MAX_ENTRIES]; int count; } policy_table_t;
#define POLICY_ALLOW     0
#define POLICY_DENY     -1
#define POLICY_PROMPT   -2
#define POLICY_NO_MATCH -3
void policy_table_init(policy_table_t *table);
void policy_init_default(policy_table_t *table, uid_t owner_uid);
int policy_table_add(policy_table_t *table, const policy_entry_t *entry);
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);
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);

/* from pq_crypto.h */
typedef enum { CRYPTO_ALG_SECP256K1=0, CRYPTO_ALG_ED25519, CRYPTO_ALG_X25519, CRYPTO_ALG_ML_DSA_65, CRYPTO_ALG_SLH_DSA_128S, CRYPTO_ALG_ML_KEM_768, CRYPTO_ALG_UNKNOWN } crypto_alg_t;
typedef struct { size_t priv_key_len; size_t pub_key_len; size_t sig_len; size_t ciphertext_len; size_t shared_secret_len; } crypto_alg_sizes_t;
const crypto_alg_sizes_t *crypto_alg_get_sizes(crypto_alg_t alg);
crypto_alg_t crypto_alg_from_role(role_curve_t curve, role_purpose_t purpose);
const char *crypto_alg_to_str(crypto_alg_t alg);
crypto_alg_t crypto_alg_from_str(const char *s);
int crypto_ed25519_keygen_from_seed(const unsigned char *seed, size_t seed_len, unsigned char *priv_out, unsigned char *pub_out);
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);
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);
int crypto_x25519_keygen_from_seed(const unsigned char *seed, size_t seed_len, unsigned char *priv_out, unsigned char *pub_out);
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);
int crypto_derive_seed_from_mnemonic(const char *mnemonic, const char *path, unsigned char *seed_out, size_t seed_out_len);
int crypto_ml_dsa_65_keygen_from_seed(const unsigned char *seed, size_t seed_len, unsigned char *priv_out, unsigned char *pub_out);
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);
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);
int crypto_slh_dsa_128s_keygen_from_seed(const unsigned char *seed, size_t seed_len, unsigned char *priv_out, unsigned char *pub_out);
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);
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);
int crypto_ml_kem_768_keygen_from_seed(const unsigned char *seed, size_t seed_len, unsigned char *priv_out, unsigned char *pub_out);
int crypto_ml_kem_768_encaps(const unsigned char *pub, size_t pub_len, unsigned char *ct_out, unsigned char *ss_out);
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);
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 */
int enforce_verb_algorithm(const char *verb, crypto_alg_t alg);
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);
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);
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);
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);
#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;
void alg_key_cache_init(algorithm_key_cache_t *cache);
void alg_key_cache_wipe(algorithm_key_cache_t *cache);
const alg_key_entry_t *alg_key_cache_get(algorithm_key_cache_t *cache, crypto_alg_t alg, int index);
int alg_key_cache_derive(algorithm_key_cache_t *cache, const mnemonic_state_t *mnemonic, crypto_alg_t alg, int index);

/* from crypto.h */
typedef struct {
    secure_buf_t private_key;
    secure_buf_t public_key;
    char pubkey_hex[8192];
    char npub[128];
    crypto_alg_t alg;
    int valid;
} derived_key_t;
typedef struct { derived_key_t keys[ROLE_TABLE_MAX_ENTRIES]; int count; } key_store_t;
int crypto_derive_all(key_store_t *store, role_table_t *table, const mnemonic_state_t *mnemonic);
const unsigned char *crypto_get_private_key(const key_store_t *store, int role_index);
const char *crypto_get_pubkey_hex(const key_store_t *store, int role_index);
char *crypto_sign_event(const key_store_t *store, int role_index, const char *event_json);
void crypto_wipe(key_store_t *store);

/* from dispatcher.h */
typedef struct {
    role_table_t *role_table;
    mnemonic_state_t *mnemonic;
    key_store_t *key_store;
    algorithm_key_cache_t *alg_key_cache;
} dispatcher_ctx_t;
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);
char *dispatcher_handle_request(dispatcher_ctx_t *ctx, const char *json_request);

/* from main.h */
#define NSIGNER_VERSION "v0.0.2"
/* NSIGNER_HEADERLESS_DECLS_END */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <nostr_core/utils.h>
#include <nostr_core/nostr_common.h>

static int g_passes = 0;
static int g_total = 0;

static void check(const char *name, int condition) {
    g_total++;
    if (condition) {
        printf("PASS: %s\n", name);
        g_passes++;
    } else {
        printf("FAIL: %s\n", name);
    }
}

static int resp_has(const char *resp, const char *needle) {
    return (resp != NULL && needle != NULL && strstr(resp, needle) != NULL);
}

/* Extract a string field from a JSON result object embedded in a response.
 * The response format is {"id":"...","result":"{...}"} where the result
 * value is a JSON string. This extracts the result string, parses it,
 * and returns the value of the given field. Caller must free. */
static char *extract_result_field(const char *response, const char *field) {
    cJSON *root, *result_item, *result_obj, *field_item;
    char *out = NULL;

    if (response == NULL || field == NULL) return NULL;

    root = cJSON_Parse(response);
    if (root == NULL) return NULL;

    result_item = cJSON_GetObjectItemCaseSensitive(root, "result");
    if (!cJSON_IsString(result_item) || result_item->valuestring == NULL) {
        cJSON_Delete(root);
        return NULL;
    }

    result_obj = cJSON_Parse(result_item->valuestring);
    if (result_obj == NULL) {
        cJSON_Delete(root);
        return NULL;
    }

    field_item = cJSON_GetObjectItemCaseSensitive(result_obj, field);
    if (cJSON_IsString(field_item) && field_item->valuestring != NULL) {
        out = strdup(field_item->valuestring);
    }

    cJSON_Delete(result_obj);
    cJSON_Delete(root);
    return out;
}

static int extract_result_bool(const char *response, const char *field) {
    cJSON *root, *result_item, *result_obj, *field_item;
    int val = -1;

    if (response == NULL || field == NULL) return -1;

    root = cJSON_Parse(response);
    if (root == NULL) return -1;

    result_item = cJSON_GetObjectItemCaseSensitive(root, "result");
    if (!cJSON_IsString(result_item) || result_item->valuestring == NULL) {
        cJSON_Delete(root);
        return -1;
    }

    result_obj = cJSON_Parse(result_item->valuestring);
    if (result_obj == NULL) {
        cJSON_Delete(root);
        return -1;
    }

    field_item = cJSON_GetObjectItemCaseSensitive(result_obj, field);
    if (cJSON_IsBool(field_item)) {
        val = cJSON_IsTrue(field_item) ? 1 : 0;
    }

    cJSON_Delete(result_obj);
    cJSON_Delete(root);
    return val;
}

/* File-level statics to avoid stack overflow (key_store_t is ~2.1MB) */
static key_store_t g_key_store;
static algorithm_key_cache_t g_alg_key_cache;
static mnemonic_state_t g_mnemonic;
static role_table_t g_role_table;
static dispatcher_ctx_t g_dispatcher;

int main(void) {
    const char *valid_12 = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
    char *resp;
    char *sig_hex;
    char *pub_hex;
    char *ct_hex;
    char *ss_hex1;
    char *ss_hex2;
    char *shared_hex;
    char request[32768];
    int rc;

    /* ---- Setup ---- */
    role_table_init(&g_role_table);
    {
        role_entry_t main_role;
        memset(&main_role, 0, sizeof(main_role));
        strncpy(main_role.name, "main", sizeof(main_role.name) - 1);
        strncpy(main_role.purpose_str, "nostr", sizeof(main_role.purpose_str) - 1);
        strncpy(main_role.curve_str, "secp256k1", sizeof(main_role.curve_str) - 1);
        main_role.purpose = role_purpose_from_str("nostr");
        main_role.curve = role_curve_from_str("secp256k1");
        main_role.selector_type = SELECTOR_NOSTR_INDEX;
        main_role.nostr_index = 0;
        role_table_add(&g_role_table, &main_role);
    }

    mnemonic_init(&g_mnemonic);
    rc = mnemonic_load(&g_mnemonic, valid_12);
    check("mnemonic_load succeeds", rc == 0);

    memset(&g_key_store, 0, sizeof(g_key_store));
    alg_key_cache_init(&g_alg_key_cache);

    rc = nostr_init();
    check("nostr_init succeeds", rc == 0);

    crypto_derive_all(&g_key_store, &g_role_table, &g_mnemonic);

    dispatcher_init(&g_dispatcher, &g_role_table, &g_mnemonic, &g_key_store, &g_alg_key_cache);

    /* ---- Enforcement tests ---- */
    check("enforce sign + ed25519 -> OK",
          enforce_verb_algorithm(VERB_SIGN, CRYPTO_ALG_ED25519) == ENFORCE_OK);
    check("enforce sign + secp256k1 -> OK",
          enforce_verb_algorithm(VERB_SIGN, CRYPTO_ALG_SECP256K1) == ENFORCE_OK);
    check("enforce sign + ml-dsa-65 -> OK",
          enforce_verb_algorithm(VERB_SIGN, CRYPTO_ALG_ML_DSA_65) == ENFORCE_OK);
    check("enforce sign + slh-dsa-128s -> OK",
          enforce_verb_algorithm(VERB_SIGN, CRYPTO_ALG_SLH_DSA_128S) == ENFORCE_OK);
    check("enforce sign + x25519 -> ALGORITHM err",
          enforce_verb_algorithm(VERB_SIGN, CRYPTO_ALG_X25519) == ENFORCE_ERR_ALGORITHM);
    check("enforce sign + ml-kem-768 -> ALGORITHM err",
          enforce_verb_algorithm(VERB_SIGN, CRYPTO_ALG_ML_KEM_768) == ENFORCE_ERR_ALGORITHM);
    check("enforce encapsulate + ml-kem-768 -> OK",
          enforce_verb_algorithm(VERB_ENCAPSULATE, CRYPTO_ALG_ML_KEM_768) == ENFORCE_OK);
    check("enforce encapsulate + ed25519 -> ALGORITHM err",
          enforce_verb_algorithm(VERB_ENCAPSULATE, CRYPTO_ALG_ED25519) == ENFORCE_ERR_ALGORITHM);
    check("enforce decapsulate + ml-kem-768 -> OK",
          enforce_verb_algorithm(VERB_DECAPSULATE, CRYPTO_ALG_ML_KEM_768) == ENFORCE_OK);
    check("enforce derive_shared_secret + x25519 -> OK",
          enforce_verb_algorithm(VERB_DERIVE_SHARED, CRYPTO_ALG_X25519) == ENFORCE_OK);
    check("enforce derive_shared_secret + ed25519 -> ALGORITHM err",
          enforce_verb_algorithm(VERB_DERIVE_SHARED, CRYPTO_ALG_ED25519) == ENFORCE_ERR_ALGORITHM);
    check("enforce get_public_key + any alg -> OK",
          enforce_verb_algorithm(VERB_GET_PUBLIC_KEY, CRYPTO_ALG_ED25519) == ENFORCE_OK);
    check("enforce sign_event + secp256k1 -> OK",
          enforce_verb_algorithm(VERB_SIGN_EVENT, CRYPTO_ALG_SECP256K1) == ENFORCE_OK);
    check("enforce sign_event + ed25519 -> ALGORITHM err",
          enforce_verb_algorithm(VERB_SIGN_EVENT, CRYPTO_ALG_ED25519) == ENFORCE_ERR_ALGORITHM);

    /* ---- get_public_key with algorithm parameter ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"gpk1\",\"method\":\"get_public_key\",\"params\":[{\"algorithm\":\"ed25519\",\"index\":0}]}");
    check("get_public_key algorithm=ed25519 returns result",
          resp_has(resp, "\"result\""));
    check("get_public_key algorithm=ed25519 has algorithm field",
          resp_has(resp, "ed25519"));
    check("get_public_key algorithm=ed25519 has public_key field",
          resp_has(resp, "public_key"));
    check("get_public_key algorithm=ed25519 has key_id field",
          resp_has(resp, "key_id"));
    free(resp);

    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"gpk2\",\"method\":\"get_public_key\",\"params\":[{\"algorithm\":\"ml-dsa-65\",\"index\":0}]}");
    check("get_public_key algorithm=ml-dsa-65 returns result",
          resp_has(resp, "\"result\""));
    check("get_public_key algorithm=ml-dsa-65 has algorithm field",
          resp_has(resp, "ml-dsa-65"));
    free(resp);

    /* ---- sign + verify roundtrip: ed25519 ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"s1\",\"method\":\"sign\",\"params\":[\"68656c6c6f\",{\"algorithm\":\"ed25519\",\"index\":0}]}");
    check("sign ed25519 returns result",
          resp_has(resp, "\"result\""));
    check("sign ed25519 has signature field",
          resp_has(resp, "signature"));
    check("sign ed25519 has algorithm ed25519",
          resp_has(resp, "ed25519"));
    check("sign ed25519 has key_id",
          resp_has(resp, "key_id"));
    sig_hex = extract_result_field(resp, "signature");
    free(resp);
    check("sign ed25519 extracted signature", sig_hex != NULL && strlen(sig_hex) > 0);

    if (sig_hex) {
        snprintf(request, sizeof(request),
            "{\"id\":\"v1\",\"method\":\"verify\",\"params\":[\"68656c6c6f\",\"%s\",{\"algorithm\":\"ed25519\",\"index\":0}]}",
            sig_hex);
        resp = dispatcher_handle_request(&g_dispatcher, request);
        check("verify ed25519 returns result", resp_has(resp, "\"result\""));
        check("verify ed25519 valid:true", extract_result_bool(resp, "valid") == 1);
        free(resp);

        /* verify with wrong message */
        snprintf(request, sizeof(request),
            "{\"id\":\"v2\",\"method\":\"verify\",\"params\":[\"776f726c64\",\"%s\",{\"algorithm\":\"ed25519\",\"index\":0}]}",
            sig_hex);
        resp = dispatcher_handle_request(&g_dispatcher, request);
        check("verify ed25519 wrong msg valid:false", extract_result_bool(resp, "valid") == 0);
        free(resp);

        free(sig_hex);
    }

    /* ---- sign + verify roundtrip: ml-dsa-65 ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"s2\",\"method\":\"sign\",\"params\":[\"68656c6c6f\",{\"algorithm\":\"ml-dsa-65\",\"index\":0}]}");
    check("sign ml-dsa-65 returns result", resp_has(resp, "\"result\""));
    check("sign ml-dsa-65 has signature", resp_has(resp, "signature"));
    sig_hex = extract_result_field(resp, "signature");
    free(resp);
    check("sign ml-dsa-65 extracted signature", sig_hex != NULL && strlen(sig_hex) > 0);

    if (sig_hex) {
        snprintf(request, sizeof(request),
            "{\"id\":\"v3\",\"method\":\"verify\",\"params\":[\"68656c6c6f\",\"%s\",{\"algorithm\":\"ml-dsa-65\",\"index\":0}]}",
            sig_hex);
        resp = dispatcher_handle_request(&g_dispatcher, request);
        check("verify ml-dsa-65 valid:true", extract_result_bool(resp, "valid") == 1);
        free(resp);
        free(sig_hex);
    }

    /* ---- sign + verify roundtrip: slh-dsa-128s ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"s3\",\"method\":\"sign\",\"params\":[\"68656c6c6f\",{\"algorithm\":\"slh-dsa-128s\",\"index\":0}]}");
    check("sign slh-dsa-128s returns result", resp_has(resp, "\"result\""));
    sig_hex = extract_result_field(resp, "signature");
    free(resp);
    check("sign slh-dsa-128s extracted signature", sig_hex != NULL && strlen(sig_hex) > 0);

    if (sig_hex) {
        snprintf(request, sizeof(request),
            "{\"id\":\"v4\",\"method\":\"verify\",\"params\":[\"68656c6c6f\",\"%s\",{\"algorithm\":\"slh-dsa-128s\",\"index\":0}]}",
            sig_hex);
        resp = dispatcher_handle_request(&g_dispatcher, request);
        check("verify slh-dsa-128s valid:true", extract_result_bool(resp, "valid") == 1);
        free(resp);
        free(sig_hex);
    }

    /* ---- sign + verify roundtrip: secp256k1 schnorr ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"s4\",\"method\":\"sign\",\"params\":[\"68656c6c6f\",{\"algorithm\":\"secp256k1\",\"index\":0,\"scheme\":\"schnorr\"}]}");
    check("sign secp256k1 schnorr returns result", resp_has(resp, "\"result\""));
    sig_hex = extract_result_field(resp, "signature");
    free(resp);
    check("sign secp256k1 schnorr extracted signature", sig_hex != NULL && strlen(sig_hex) == 128);

    if (sig_hex) {
        snprintf(request, sizeof(request),
            "{\"id\":\"v5\",\"method\":\"verify\",\"params\":[\"68656c6c6f\",\"%s\",{\"algorithm\":\"secp256k1\",\"index\":0,\"scheme\":\"schnorr\"}]}",
            sig_hex);
        resp = dispatcher_handle_request(&g_dispatcher, request);
        check("verify secp256k1 schnorr valid:true", extract_result_bool(resp, "valid") == 1);
        free(resp);
        free(sig_hex);
    }

    /* ---- sign + verify roundtrip: secp256k1 ecdsa ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"s5\",\"method\":\"sign\",\"params\":[\"68656c6c6f\",{\"algorithm\":\"secp256k1\",\"index\":0,\"scheme\":\"ecdsa\"}]}");
    check("sign secp256k1 ecdsa returns result", resp_has(resp, "\"result\""));
    sig_hex = extract_result_field(resp, "signature");
    free(resp);
    check("sign secp256k1 ecdsa extracted signature", sig_hex != NULL && strlen(sig_hex) == 128);

    if (sig_hex) {
        snprintf(request, sizeof(request),
            "{\"id\":\"v6\",\"method\":\"verify\",\"params\":[\"68656c6c6f\",\"%s\",{\"algorithm\":\"secp256k1\",\"index\":0,\"scheme\":\"ecdsa\"}]}",
            sig_hex);
        resp = dispatcher_handle_request(&g_dispatcher, request);
        check("verify secp256k1 ecdsa valid:true", extract_result_bool(resp, "valid") == 1);
        free(resp);
        free(sig_hex);
    }

    /* ---- encapsulate + decapsulate: ml-kem-768 ---- */
    /* First get our ML-KEM public key */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"gpk3\",\"method\":\"get_public_key\",\"params\":[{\"algorithm\":\"ml-kem-768\",\"index\":0}]}");
    pub_hex = extract_result_field(resp, "public_key");
    check("get_public_key ml-kem-768 returns public_key", pub_hex != NULL && strlen(pub_hex) > 0);
    free(resp);

    if (pub_hex) {
        /* Encapsulate with our own public key (for testing) */
        snprintf(request, sizeof(request),
            "{\"id\":\"e1\",\"method\":\"encapsulate\",\"params\":[\"%s\",{\"algorithm\":\"ml-kem-768\"}]}",
            pub_hex);
        resp = dispatcher_handle_request(&g_dispatcher, request);
        check("encapsulate ml-kem-768 returns result", resp_has(resp, "\"result\""));
        check("encapsulate ml-kem-768 has ciphertext", resp_has(resp, "ciphertext"));
        check("encapsulate ml-kem-768 has shared_secret", resp_has(resp, "shared_secret"));
        ct_hex = extract_result_field(resp, "ciphertext");
        ss_hex1 = extract_result_field(resp, "shared_secret");
        free(resp);
        check("encapsulate extracted ciphertext", ct_hex != NULL && strlen(ct_hex) > 0);
        check("encapsulate extracted shared_secret", ss_hex1 != NULL && strlen(ss_hex1) > 0);

        if (ct_hex) {
            /* Decapsulate with our private key */
            snprintf(request, sizeof(request),
                "{\"id\":\"d1\",\"method\":\"decapsulate\",\"params\":[\"%s\",{\"algorithm\":\"ml-kem-768\",\"index\":0}]}",
                ct_hex);
            resp = dispatcher_handle_request(&g_dispatcher, request);
            check("decapsulate ml-kem-768 returns result", resp_has(resp, "\"result\""));
            check("decapsulate ml-kem-768 has shared_secret", resp_has(resp, "shared_secret"));
            ss_hex2 = extract_result_field(resp, "shared_secret");
            free(resp);
            check("decapsulate extracted shared_secret", ss_hex2 != NULL);

            /* Verify the shared secrets match */
            if (ss_hex1 && ss_hex2) {
                check("encapsulate/decapsulate shared secrets match",
                      strcmp(ss_hex1, ss_hex2) == 0);
            }
            free(ss_hex2);
        }
        free(ct_hex);
        free(ss_hex1);
        free(pub_hex);
    }

    /* ---- derive_shared_secret: x25519 ---- */
    /* Get our x25519 public key */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"gpk4\",\"method\":\"get_public_key\",\"params\":[{\"algorithm\":\"x25519\",\"index\":0}]}");
    pub_hex = extract_result_field(resp, "public_key");
    check("get_public_key x25519 returns public_key", pub_hex != NULL && strlen(pub_hex) > 0);
    free(resp);

    if (pub_hex) {
        /* Derive shared secret with our own public key (for testing) */
        snprintf(request, sizeof(request),
            "{\"id\":\"dss1\",\"method\":\"derive_shared_secret\",\"params\":[\"%s\",{\"algorithm\":\"x25519\",\"index\":0}]}",
            pub_hex);
        resp = dispatcher_handle_request(&g_dispatcher, request);
        check("derive_shared_secret x25519 returns result", resp_has(resp, "\"result\""));
        check("derive_shared_secret x25519 has shared_secret", resp_has(resp, "shared_secret"));
        check("derive_shared_secret x25519 has algorithm x25519", resp_has(resp, "x25519"));
        shared_hex = extract_result_field(resp, "shared_secret");
        free(resp);
        check("derive_shared_secret extracted shared_secret", shared_hex != NULL && strlen(shared_hex) == 64);
        free(shared_hex);
        free(pub_hex);
    }

    /* ---- Enforcement via dispatcher: sign with x25519 fails ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"err1\",\"method\":\"sign\",\"params\":[\"68656c6c6f\",{\"algorithm\":\"x25519\",\"index\":0}]}");
    check("sign x25519 returns algorithm error",
          resp_has(resp, "algorithm_not_supported_for_verb") || resp_has(resp, "\"code\":1010"));
    free(resp);

    /* ---- Enforcement via dispatcher: encapsulate with ed25519 fails ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"err2\",\"method\":\"encapsulate\",\"params\":[\"abcd\",{\"algorithm\":\"ed25519\"}]}");
    check("encapsulate ed25519 returns algorithm error",
          resp_has(resp, "algorithm_not_supported_for_verb") || resp_has(resp, "\"code\":1010"));
    free(resp);

    /* ---- Old verb alias: sign_data with algorithm=ed25519 ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"alias1\",\"method\":\"sign_data\",\"params\":[\"68656c6c6f\",{\"algorithm\":\"ed25519\",\"index\":0}]}");
    check("sign_data alias with algorithm=ed25519 returns result",
          resp_has(resp, "\"result\""));
    check("sign_data alias has signature",
          resp_has(resp, "signature"));
    free(resp);

    /* ---- Old verb alias: ssh_sign with algorithm=ed25519 ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"alias2\",\"method\":\"ssh_sign\",\"params\":[\"68656c6c6f\",{\"algorithm\":\"ed25519\",\"index\":0}]}");
    check("ssh_sign alias with algorithm=ed25519 returns result",
          resp_has(resp, "\"result\""));
    free(resp);

    /* ---- Old verb alias: kem_encapsulate with algorithm=ml-kem-768 ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"gpk5\",\"method\":\"get_public_key\",\"params\":[{\"algorithm\":\"ml-kem-768\",\"index\":1}]}");
    pub_hex = extract_result_field(resp, "public_key");
    free(resp);
    if (pub_hex) {
        snprintf(request, sizeof(request),
            "{\"id\":\"alias3\",\"method\":\"kem_encapsulate\",\"params\":[\"%s\",{\"algorithm\":\"ml-kem-768\"}]}",
            pub_hex);
        resp = dispatcher_handle_request(&g_dispatcher, request);
        check("kem_encapsulate alias with algorithm=ml-kem-768 returns result",
              resp_has(resp, "\"result\""));
        check("kem_encapsulate alias has ciphertext",
              resp_has(resp, "ciphertext"));
        free(resp);
        free(pub_hex);
    }

    /* ---- Backward compat: sign_event with role still works ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"bc1\",\"method\":\"sign_event\",\"params\":[\"{\\\"kind\\\":1,\\\"content\\\":\\\"hello\\\",\\\"tags\\\":[]}\",{\"role\":\"main\"}]}");
    check("sign_event with role=main (backward compat) returns signed event",
          resp_has(resp, "pubkey") && resp_has(resp, "sig"));
    free(resp);

    /* ---- Backward compat: get_public_key with role still works ---- */
    resp = dispatcher_handle_request(&g_dispatcher,
        "{\"id\":\"bc2\",\"method\":\"get_public_key\",\"params\":[{\"role\":\"main\"}]}");
    check("get_public_key with role=main (backward compat) returns hex",
          resp_has(resp, "\"result\""));
    free(resp);

    /* ---- Policy: algorithm-based preapprove ---- */
    {
        policy_table_t policy;
        policy_entry_t entry;
        policy_source_t src;

        policy_init_default(&policy, 1000);

        /* Add algorithm-based preapprove entry */
        memset(&entry, 0, sizeof(entry));
        strncpy(entry.caller, "uid:1000", sizeof(entry.caller) - 1);
        strncpy(entry.algorithms[0], "ed25519", sizeof(entry.algorithms[0]) - 1);
        entry.alg_count = 1;
        entry.index_min = 0;
        entry.index_max = 4;
        strncpy(entry.verbs[0], "sign", sizeof(entry.verbs[0]) - 1);
        strncpy(entry.verbs[1], "verify", sizeof(entry.verbs[1]) - 1);
        entry.verb_count = 2;
        entry.prompt = PROMPT_NEVER;
        entry.source = POLICY_SOURCE_PREAPPROVE;
        policy_table_add(&policy, &entry);

        /* Check: allowed */
        rc = policy_check_algorithm(&policy, "uid:1000", "sign", "ed25519", 0, &src);
        check("policy_check_algorithm: sign ed25519 idx=0 -> ALLOW", rc == POLICY_ALLOW);

        rc = policy_check_algorithm(&policy, "uid:1000", "sign", "ed25519", 3, &src);
        check("policy_check_algorithm: sign ed25519 idx=3 -> ALLOW", rc == POLICY_ALLOW);

        /* Check: index out of range */
        rc = policy_check_algorithm(&policy, "uid:1000", "sign", "ed25519", 5, &src);
        check("policy_check_algorithm: sign ed25519 idx=5 -> NO_MATCH", rc == POLICY_NO_MATCH);

        /* Check: wrong algorithm */
        rc = policy_check_algorithm(&policy, "uid:1000", "sign", "ml-dsa-65", 0, &src);
        check("policy_check_algorithm: sign ml-dsa-65 -> NO_MATCH", rc == POLICY_NO_MATCH);

        /* Check: wrong verb */
        rc = policy_check_algorithm(&policy, "uid:1000", "encapsulate", "ed25519", 0, &src);
        check("policy_check_algorithm: encapsulate ed25519 -> NO_MATCH", rc == POLICY_NO_MATCH);

        /* Check: wrong caller */
        rc = policy_check_algorithm(&policy, "uid:2000", "sign", "ed25519", 0, &src);
        check("policy_check_algorithm: wrong caller -> NO_MATCH", rc == POLICY_NO_MATCH);
    }

    /* ---- Cleanup ---- */
    crypto_wipe(&g_key_store);
    alg_key_cache_wipe(&g_alg_key_cache);
    nostr_cleanup();
    mnemonic_unload(&g_mnemonic);

    printf("%d/%d tests passed\n", g_passes, g_total);
    return (g_passes == g_total) ? 0 : 1;
}
