/* Test for Phase 4 SLH-DSA-128s (FIPS 205) post-quantum hash-based signatures.
 *
 * Verifies:
 *   - SLH-DSA-128s keygen from seed: 32-byte pub, 64-byte priv
 *   - SLH-DSA-128s keygen determinism: same seed -> same keypair
 *   - SLH-DSA-128s sign/verify roundtrip: sign a message, verify passes
 *   - SLH-DSA-128s sign/verify with wrong message: verify fails
 *   - SLH-DSA-128s sign/verify with wrong key: verify fails
 *   - DRBG determinism: same seed -> same randombytes output
 *   - Integration: derive SLH-DSA-128s key from mnemonic via crypto_derive_one,
 *     sign data via sign_data verb through dispatcher, verify signature
 *   - Enforcement: sign_data allowed on pq-sig+slh-dsa-128s
 */
/* 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);
int mnemonic_generate(int word_count, char *out, size_t out_len);


/* 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);
const char *role_purpose_to_str(role_purpose_t p);
const char *role_curve_to_str(role_curve_t c);


/* from selector.h */


#define SELECTOR_OK                 0
#define SELECTOR_ERR_AMBIGUOUS     -1
#define SELECTOR_ERR_NOT_FOUND     -2
#define SELECTOR_ERR_NO_DEFAULT    -3

typedef struct {
    int has_role;
    char role_name[ROLE_NAME_MAX];
    int has_nostr_index;
    int nostr_index;
    int has_role_path;
    char role_path[ROLE_PATH_MAX];
} selector_request_t;

void selector_request_init(selector_request_t *req);
int selector_resolve(const selector_request_t *req, role_table_t *table, role_entry_t **out);
const char *selector_strerror(int err);


/* from enforcement.h */


#define ENFORCE_OK                0
#define ENFORCE_ERR_PURPOSE      -1
#define ENFORCE_ERR_CURVE        -2
#define ENFORCE_ERR_UNKNOWN_VERB -3

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

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

/* 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);
prompt_mode_t prompt_mode_from_str(const char *s);
const char *prompt_mode_to_str(prompt_mode_t m);


/* from pq_crypto.h */


/* Algorithm identifiers */
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;

/* Key sizes for each algorithm (compile-time constants) */
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);
/* 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 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;

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);
int crypto_derive_one(key_store_t *store, role_table_t *table, const mnemonic_state_t *mnemonic, int role_index);
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 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 */


typedef struct {
    role_table_t *role_table;
    mnemonic_state_t *mnemonic;
    key_store_t *key_store;
} 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);


/* NSIGNER_HEADERLESS_DECLS_END */

static key_store_t g_key_store;

static algorithm_key_cache_t g_alg_key_cache;

#include <nostr_core/nostr_common.h>
#include <nostr_core/utils.h>

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

/* SLH-DSA-128s key sizes (FIPS 205) */
#define SLH_DSA_128S_PUBKEY_BYTES  32
#define SLH_DSA_128S_PRIVKEY_BYTES 64
#define SLH_DSA_128S_SIG_BYTES     7856

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

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

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

static role_entry_t make_pq_sig_slh_dsa_128s_entry(const char *name, int idx) {
    role_entry_t e;
    memset(&e, 0, sizeof(e));
    strncpy(e.name, name, sizeof(e.name) - 1);
    strncpy(e.purpose_str, "pq-sig", sizeof(e.purpose_str) - 1);
    strncpy(e.curve_str, "slh-dsa-128s", sizeof(e.curve_str) - 1);
    e.purpose = role_purpose_from_str(e.purpose_str);
    e.curve = role_curve_from_str(e.curve_str);
    e.selector_type = SELECTOR_NOSTR_INDEX;
    e.nostr_index = idx;
    e.derived = 0;
    return e;
}

static role_entry_t make_nostr_secp_entry(const char *name, int idx) {
    role_entry_t e;
    memset(&e, 0, sizeof(e));
    strncpy(e.name, name, sizeof(e.name) - 1);
    strncpy(e.purpose_str, "nostr", sizeof(e.purpose_str) - 1);
    strncpy(e.curve_str, "secp256k1", sizeof(e.curve_str) - 1);
    e.purpose = role_purpose_from_str(e.purpose_str);
    e.curve = role_curve_from_str(e.curve_str);
    e.selector_type = SELECTOR_NOSTR_INDEX;
    e.nostr_index = idx;
    e.derived = 0;
    return e;
}

int main(void) {
    /* Test mnemonic (BIP-39 standard test vector). */
    const char *mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
    unsigned char seed[32];
    unsigned char *priv1, *pub1, *priv2, *pub2;
    unsigned char *sig;
    size_t sig_len;
    int rc;

    /* Allocate key buffers on the heap */
    priv1 = (unsigned char *)malloc(SLH_DSA_128S_PRIVKEY_BYTES);
    pub1 = (unsigned char *)malloc(SLH_DSA_128S_PUBKEY_BYTES);
    priv2 = (unsigned char *)malloc(SLH_DSA_128S_PRIVKEY_BYTES);
    pub2 = (unsigned char *)malloc(SLH_DSA_128S_PUBKEY_BYTES);
    sig = (unsigned char *)malloc(SLH_DSA_128S_SIG_BYTES);

    if (!priv1 || !pub1 || !priv2 || !pub2 || !sig) {
        printf("FAIL: memory allocation\n");
        return 1;
    }

    /* ---- DRBG determinism ---- */
    {
        unsigned char out1[64], out2[64];

        memset(seed, 0x42, 32);
        pq_drbg_init(seed, 32);
        rc = pq_drbg_randombytes(out1, 64);
        check_condition("DRBG randombytes succeeds", rc == 0);

        pq_drbg_zeroize();

        memset(seed, 0x42, 32);
        pq_drbg_init(seed, 32);
        rc = pq_drbg_randombytes(out2, 64);
        check_condition("DRBG randombytes succeeds (2nd)", rc == 0);

        check_condition("DRBG determinism (same seed -> same output)",
                        memcmp(out1, out2, 64) == 0);

        pq_drbg_zeroize();
    }

    /* ---- SLH-DSA-128s keygen from seed ---- */
    memset(seed, 0x42, 32);
    rc = crypto_slh_dsa_128s_keygen_from_seed(seed, 32, priv1, pub1);
    check_condition("SLH-DSA-128s keygen from seed succeeds", rc == 0);

    /* Keygen determinism: same seed -> same keypair */
    memset(seed, 0x42, 32);
    rc = crypto_slh_dsa_128s_keygen_from_seed(seed, 32, priv2, pub2);
    check_condition("SLH-DSA-128s keygen determinism (same seed -> same key)", rc == 0 &&
                    memcmp(priv1, priv2, SLH_DSA_128S_PRIVKEY_BYTES) == 0 &&
                    memcmp(pub1, pub2, SLH_DSA_128S_PUBKEY_BYTES) == 0);

    /* Different seed -> different keypair */
    memset(seed, 0x99, 32);
    rc = crypto_slh_dsa_128s_keygen_from_seed(seed, 32, priv2, pub2);
    check_condition("SLH-DSA-128s keygen different seed -> different key", rc == 0 &&
                    memcmp(pub1, pub2, SLH_DSA_128S_PUBKEY_BYTES) != 0);

    /* ---- SLH-DSA-128s sign/verify roundtrip ---- */
    memset(seed, 0x42, 32);
    crypto_slh_dsa_128s_keygen_from_seed(seed, 32, priv1, pub1);
    {
        const char *msg = "hello world";
        sig_len = SLH_DSA_128S_SIG_BYTES;
        rc = crypto_slh_dsa_128s_sign(priv1, SLH_DSA_128S_PRIVKEY_BYTES,
                                        (const unsigned char *)msg, strlen(msg),
                                        sig, &sig_len);
        check_condition("SLH-DSA-128s sign succeeds", rc == 0 && sig_len > 0);
        check_condition("SLH-DSA-128s signature is 7856 bytes", sig_len == SLH_DSA_128S_SIG_BYTES);

        rc = crypto_slh_dsa_128s_verify(pub1, SLH_DSA_128S_PUBKEY_BYTES,
                                          (const unsigned char *)msg, strlen(msg),
                                          sig, sig_len);
        check_condition("SLH-DSA-128s verify valid signature", rc == 0);

        /* Wrong message should fail */
        {
            const char *wrong_msg = "hello worle";
            rc = crypto_slh_dsa_128s_verify(pub1, SLH_DSA_128S_PUBKEY_BYTES,
                                              (const unsigned char *)wrong_msg, strlen(wrong_msg),
                                              sig, sig_len);
            check_condition("SLH-DSA-128s verify wrong message -> invalid", rc == 1);
        }

        /* Wrong key should fail */
        memset(seed, 0xAB, 32);
        crypto_slh_dsa_128s_keygen_from_seed(seed, 32, priv2, pub2);
        rc = crypto_slh_dsa_128s_verify(pub2, SLH_DSA_128S_PUBKEY_BYTES,
                                          (const unsigned char *)msg, strlen(msg),
                                          sig, sig_len);
        check_condition("SLH-DSA-128s verify wrong key -> invalid", rc == 1);
    }

    /* ---- Integration: derive SLH-DSA-128s key via crypto_derive_all ---- */
    {
        role_table_t table;
        role_entry_t pq_role;
        static mnemonic_state_t mnemonic_state;
            int derived;

        role_table_init(&table);
        pq_role = make_pq_sig_slh_dsa_128s_entry("pq_main", 0);
        role_table_add(&table, &pq_role);

        mnemonic_init(&mnemonic_state);
        mnemonic_load(&mnemonic_state, mnemonic);

        memset(&g_key_store, 0, sizeof(g_key_store));
        alg_key_cache_init(&g_alg_key_cache);
        derived = crypto_derive_all(&g_key_store, &table, &mnemonic_state);
        check_condition("crypto_derive_all derives SLH-DSA-128s key", derived == 1);

        {
            const char *pub_hex = crypto_get_pubkey_hex(&g_key_store, 0);
            /* 32 bytes hex-encoded = 64 hex chars + null */
            check_condition("SLH-DSA-128s derived pubkey hex is 64 chars",
                            pub_hex != NULL && strlen(pub_hex) == 64);
        }

        {
            const unsigned char *priv = crypto_get_private_key(&g_key_store, 0);
            check_condition("SLH-DSA-128s derived private key not NULL", priv != NULL);
        }

        /* Determinism: re-derive and check same key */
        {
            static key_store_t key_store2;
            memset(&key_store2, 0, sizeof(key_store2));
            crypto_derive_all(&key_store2, &table, &mnemonic_state);
            {
                const char *pub_hex1 = crypto_get_pubkey_hex(&g_key_store, 0);
                const char *pub_hex2 = crypto_get_pubkey_hex(&key_store2, 0);
                check_condition("SLH-DSA-128s derivation determinism (same mnemonic -> same key)",
                                pub_hex1 != NULL && pub_hex2 != NULL &&
                                strcmp(pub_hex1, pub_hex2) == 0);
            }
            crypto_wipe(&key_store2);
        }

        crypto_wipe(&g_key_store);
        mnemonic_unload(&mnemonic_state);
    }

    /* ---- Integration: sign_data via dispatcher ---- */
    {
        role_table_t table;
        role_entry_t pq_role;
        static mnemonic_state_t mnemonic_state;
        dispatcher_ctx_t dispatcher;
        char *resp;
        const char *msg_hex = "68656c6c6f20776f726c64"; /* "hello world" in hex */
        char request[512];

        role_table_init(&table);
        pq_role = make_pq_sig_slh_dsa_128s_entry("pq_main", 0);
        role_table_add(&table, &pq_role);

        mnemonic_init(&mnemonic_state);
        mnemonic_load(&mnemonic_state, mnemonic);

        memset(&g_key_store, 0, sizeof(g_key_store));
        alg_key_cache_init(&g_alg_key_cache);
        crypto_derive_all(&g_key_store, &table, &mnemonic_state);

        dispatcher_init(&dispatcher, &table, &mnemonic_state, &g_key_store, &g_alg_key_cache);

        /* sign_data request */
        snprintf(request, sizeof(request),
                 "{\"id\":\"test1\",\"method\":\"sign_data\",\"params\":[\"%s\",{\"role\":\"pq_main\"}]}",
                 msg_hex);
        resp = dispatcher_handle_request(&dispatcher, request);
        check_condition("sign_data via dispatcher returns result",
                        resp != NULL && response_has(resp, "\"result\""));
        check_condition("sign_data result contains signature",
                        resp != NULL && response_has(resp, "signature"));
        check_condition("sign_data result contains algorithm slh-dsa-128s",
                        resp != NULL && response_has(resp, "slh-dsa-128s"));
        free(resp);

        crypto_wipe(&g_key_store);
        mnemonic_unload(&mnemonic_state);
    }

    /* ---- Integration: verify_signature roundtrip via dispatcher ---- */
    {
        role_table_t table;
        role_entry_t pq_role;
        static mnemonic_state_t mnemonic_state;
        dispatcher_ctx_t dispatcher;
        char *sign_resp, *verify_resp;
        const char *msg_hex = "68656c6c6f20776f726c64"; /* "hello world" */
        char sign_req[512];
        /* SLH-DSA-128s sig is 7856 bytes = 15712 hex chars. The verify request
         * needs: JSON overhead + msg_hex (22) + sig_hex (15712) + options ~50
         * = ~16000 bytes. Use 20000 to be safe. */
        char *verify_req = (char *)malloc(20000);
        cJSON *sign_json, *result_item, *sig_item;
        const char *sig_str = NULL;

        role_table_init(&table);
        pq_role = make_pq_sig_slh_dsa_128s_entry("pq_main", 0);
        role_table_add(&table, &pq_role);

        mnemonic_init(&mnemonic_state);
        mnemonic_load(&mnemonic_state, mnemonic);

        memset(&g_key_store, 0, sizeof(g_key_store));
        alg_key_cache_init(&g_alg_key_cache);
        crypto_derive_all(&g_key_store, &table, &mnemonic_state);
        dispatcher_init(&dispatcher, &table, &mnemonic_state, &g_key_store, &g_alg_key_cache);

        /* Sign */
        snprintf(sign_req, sizeof(sign_req),
                 "{\"id\":\"s1\",\"method\":\"sign_data\",\"params\":[\"%s\",{\"role\":\"pq_main\"}]}",
                 msg_hex);
        sign_resp = dispatcher_handle_request(&dispatcher, sign_req);
        check_condition("verify roundtrip: sign_data succeeds", sign_resp != NULL);

        /* Extract signature from result */
        if (sign_resp != NULL) {
            sign_json = cJSON_Parse(sign_resp);
            if (sign_json != NULL) {
                result_item = cJSON_GetObjectItemCaseSensitive(sign_json, "result");
                if (cJSON_IsString(result_item)) {
                    cJSON *result_obj = cJSON_Parse(result_item->valuestring);
                    if (result_obj != NULL) {
                        sig_item = cJSON_GetObjectItemCaseSensitive(result_obj, "signature");
                        if (cJSON_IsString(sig_item)) {
                            sig_str = strdup(sig_item->valuestring);
                        }
                        cJSON_Delete(result_obj);
                    }
                }
                cJSON_Delete(sign_json);
            }
        }
        check_condition("verify roundtrip: extracted signature hex", sig_str != NULL);

        /* Verify */
        if (sig_str != NULL && verify_req != NULL) {
            snprintf(verify_req, 20000,
                     "{\"id\":\"v1\",\"method\":\"verify_signature\",\"params\":[\"%s\",\"%s\",{\"role\":\"pq_main\"}]}",
                     msg_hex, sig_str);
            verify_resp = dispatcher_handle_request(&dispatcher, verify_req);
            check_condition("verify_signature returns valid:true",
                            verify_resp != NULL && response_has(verify_resp, "valid") &&
                            response_has(verify_resp, "true"));
            free(verify_resp);

            /* Verify with wrong message */
            snprintf(verify_req, 20000,
                     "{\"id\":\"v2\",\"method\":\"verify_signature\",\"params\":[\"00ff\",\"%s\",{\"role\":\"pq_main\"}]}",
                     sig_str);
            verify_resp = dispatcher_handle_request(&dispatcher, verify_req);
            check_condition("verify_signature wrong msg returns valid:false",
                            verify_resp != NULL && response_has(verify_resp, "valid") &&
                            response_has(verify_resp, "false"));
            free(verify_resp);

            free((void *)sig_str);
        } else {
            check_condition("verify_signature returns valid:true", 0);
            check_condition("verify_signature wrong msg returns valid:false", 0);
        }

        free(verify_req);
        free(sign_resp);
        crypto_wipe(&g_key_store);
        mnemonic_unload(&mnemonic_state);
    }

    /* ---- Enforcement: sign_data on pq-sig+slh-dsa-128s ---- */
    {
        role_entry_t pq_sig = make_pq_sig_slh_dsa_128s_entry("pq", 0);
        role_entry_t nostr_secp = make_nostr_secp_entry("nostr", 0);

        check_condition("enforce sign_data + pq-sig/slh-dsa-128s -> OK",
                        enforce_verb_role(VERB_SIGN_DATA, &pq_sig) == ENFORCE_OK);

        check_condition("enforce sign_data + nostr/secp256k1 -> PURPOSE err",
                        enforce_verb_role(VERB_SIGN_DATA, &nostr_secp) == ENFORCE_ERR_PURPOSE);

        check_condition("enforce verify_signature + pq-sig/slh-dsa-128s -> OK",
                        enforce_verb_role(VERB_VERIFY_SIG, &pq_sig) == ENFORCE_OK);
    }

    /* ---- Cleanup ---- */
    free(priv1);
    free(pub1);
    free(priv2);
    free(pub2);
    free(sig);

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