/*
 * NOSTR Crypto - Self-contained cryptographic functions
 * 
 * Embedded implementations of crypto primitives needed for NOSTR
 * No external dependencies except standard C library
 */

#include "nostr_crypto.h"
#include "nostr_core.h"  // For error constants
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

// Include our secp256k1 wrapper for elliptic curve operations
#include "nostr_secp256k1.h"

// Include our self-contained AES implementation for NIP-04
#include "nostr_aes.h"

// Include our ChaCha20 implementation for NIP-44
#include "nostr_chacha20.h"

// =============================================================================
// UTILITY FUNCTIONS
// =============================================================================

// Memory clearing utility - accepts const pointers for security clearing
static void memory_clear(const void *p, size_t len) {
    if (p && len) {
        // Cast away const for memset - this is safe for security clearing
        memset((void *)p, 0, len);
    }
}

// =============================================================================
// BASE64 ENCODING/DECODING
// =============================================================================

static const char base64_chars[] = 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static int base64_decode_char(char c) {
    if (c >= 'A' && c <= 'Z') return c - 'A';
    if (c >= 'a' && c <= 'z') return c - 'a' + 26;
    if (c >= '0' && c <= '9') return c - '0' + 52;
    if (c == '+') return 62;
    if (c == '/') return 63;
    return -1;
}

size_t base64_encode(const unsigned char* data, size_t len, char* output, size_t output_size) {
    size_t output_len = 0;
    size_t required_size = ((len + 2) / 3) * 4 + 1;  // Calculate required size
    size_t i;
    
    // CRITICAL FIX: Check if output buffer is large enough
    if (required_size > output_size) {
        return 0;  // Signal error - buffer too small
    }
    
    for (i = 0; i < len; i += 3) {
        uint32_t value = data[i] << 16;
        if (i + 1 < len) value |= data[i + 1] << 8;
        if (i + 2 < len) value |= data[i + 2];
        
        output[output_len++] = base64_chars[(value >> 18) & 63];
        output[output_len++] = base64_chars[(value >> 12) & 63];
        output[output_len++] = (i + 1 < len) ? base64_chars[(value >> 6) & 63] : '=';
        output[output_len++] = (i + 2 < len) ? base64_chars[value & 63] : '=';
    }
    
    output[output_len] = '\0';
    return output_len;
}

static size_t base64_decode(const char* input, unsigned char* output) {
    size_t input_len = strlen(input);
    size_t output_len = 0;
    size_t i;
    
    for (i = 0; i < input_len; i += 4) {
        int a = base64_decode_char(input[i]);
        int b = base64_decode_char(input[i + 1]);
        int c = (i + 2 < input_len && input[i + 2] != '=') ? base64_decode_char(input[i + 2]) : 0;
        int d = (i + 3 < input_len && input[i + 3] != '=') ? base64_decode_char(input[i + 3]) : 0;
        
        if (a == -1 || b == -1) return 0; // Invalid base64
        
        uint32_t value = (a << 18) | (b << 12) | (c << 6) | d;
        
        output[output_len++] = (value >> 16) & 0xFF;
        if (i + 2 < input_len && input[i + 2] != '=') {
            output[output_len++] = (value >> 8) & 0xFF;
        }
        if (i + 3 < input_len && input[i + 3] != '=') {
            output[output_len++] = value & 0xFF;
        }
    }
    
    return output_len;
}

// =============================================================================
// ECDH SHARED SECRET COMPUTATION
// =============================================================================

// Custom hash function for ECDH that just copies the X coordinate
// This is exactly what NIP-04 requires: "only the X coordinate of the shared point is used as the secret and it is NOT hashed"
static int ecdh_hash_function_copy_x(unsigned char* output, const unsigned char* x32, const unsigned char* y32, void* data) {
    (void)y32;  // Unused - we only want the X coordinate
    (void)data; // Unused
    
    // Copy the X coordinate directly (no hashing!)
    memcpy(output, x32, 32);
    return 1;
}

int ecdh_shared_secret(const unsigned char* private_key, 
                      const unsigned char* public_key_x, 
                      unsigned char* shared_secret) {
    if (!private_key || !public_key_x || !shared_secret) return -1;
    
    // NIP-04 ECDH: The key insight from the specification is that NOSTR requires
    // "only the X coordinate of the shared point is used as the secret and it is NOT hashed"
    //
    // libsecp256k1's default ECDH hashes the shared point with SHA256.
    // We need to use a custom hash function that just copies the X coordinate.
    //
    // This matches exactly what @noble/curves getSharedSecret() does:
    // 1. Always use 0x02 prefix (compressed format)
    // 2. Perform ECDH scalar multiplication 
    // 3. Extract only the X coordinate (bytes 1-33 from the compressed point)
    
    unsigned char compressed_pubkey[33];
    compressed_pubkey[0] = 0x02;  // Always use 0x02 prefix like nostr-tools
    memcpy(compressed_pubkey + 1, public_key_x, 32);
    
    // Parse the public key
    nostr_secp256k1_pubkey pubkey;
    if (nostr_secp256k1_ec_pubkey_parse(&pubkey, compressed_pubkey, 33) != 1) {
        return -1;
    }
    
    // Perform ECDH with our custom hash function that copies the X coordinate
    // This is the crucial fix: we pass ecdh_hash_function_copy_x instead of NULL
    if (nostr_secp256k1_ecdh(shared_secret, &pubkey, private_key, ecdh_hash_function_copy_x, NULL) != 1) {
        return -1;
    }
    
    return 0;
}

// =============================================================================
// SHA-256 IMPLEMENTATION
// =============================================================================

// SHA-256 constants
static const uint32_t K[64] = {
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};

#define ROTR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
#define CH(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
#define MAJ(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#define S0(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))
#define S1(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))
#define s0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ ((x) >> 3))
#define s1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ ((x) >> 10))

static void sha256_transform(uint32_t state[8], const uint8_t data[64]) {
    uint32_t a, b, c, d, e, f, g, h, i, t1, t2, W[64];

    for (i = 0; i < 16; ++i) {
        W[i] = (data[i * 4] << 24) | (data[i * 4 + 1] << 16) | (data[i * 4 + 2] << 8) | (data[i * 4 + 3]);
    }
    for (; i < 64; ++i) {
        W[i] = s1(W[i - 2]) + W[i - 7] + s0(W[i - 15]) + W[i - 16];
    }

    a = state[0];
    b = state[1];
    c = state[2];
    d = state[3];
    e = state[4];
    f = state[5];
    g = state[6];
    h = state[7];

    for (i = 0; i < 64; ++i) {
        t1 = h + S1(e) + CH(e, f, g) + K[i] + W[i];
        t2 = S0(a) + MAJ(a, b, c);
        h = g;
        g = f;
        f = e;
        e = d + t1;
        d = c;
        c = b;
        b = a;
        a = t1 + t2;
    }

    state[0] += a;
    state[1] += b;
    state[2] += c;
    state[3] += d;
    state[4] += e;
    state[5] += f;
    state[6] += g;
    state[7] += h;
}

int nostr_sha256(const unsigned char* data, size_t len, unsigned char* hash) {
    if (!data || !hash) return -1;

    uint32_t state[8] = {
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
        0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
    };

    uint64_t bitlen = len * 8;
    size_t i;
    uint8_t data_block[64];

    // Process complete 64-byte blocks
    for (i = 0; i + 64 <= len; i += 64) {
        sha256_transform(state, data + i);
    }

    // Handle remaining bytes and padding
    size_t remaining = len - i;
    memcpy(data_block, data + i, remaining);
    data_block[remaining] = 0x80;

    if (remaining >= 56) {
        memset(data_block + remaining + 1, 0, 64 - remaining - 1);
        sha256_transform(state, data_block);
        memset(data_block, 0, 56);
    } else {
        memset(data_block + remaining + 1, 0, 55 - remaining);
    }

    // Add length in bits as big-endian 64-bit integer
    for (i = 0; i < 8; ++i) {
        data_block[56 + i] = (bitlen >> (56 - i * 8)) & 0xff;
    }
    sha256_transform(state, data_block);

    // Convert state to output bytes
    for (i = 0; i < 8; ++i) {
        hash[i * 4] = (state[i] >> 24) & 0xff;
        hash[i * 4 + 1] = (state[i] >> 16) & 0xff;
        hash[i * 4 + 2] = (state[i] >> 8) & 0xff;
        hash[i * 4 + 3] = state[i] & 0xff;
    }

    return 0;
}

// =============================================================================
// HKDF IMPLEMENTATION (RFC 5869)
// =============================================================================

int nostr_hkdf_extract(const unsigned char* salt, size_t salt_len,
                      const unsigned char* ikm, size_t ikm_len,
                      unsigned char* prk) {
    if (!ikm || !prk) return -1;
    
    // If salt is NULL or empty, use zero-filled salt of hash length
    unsigned char zero_salt[32];
    if (!salt || salt_len == 0) {
        memset(zero_salt, 0, 32);
        salt = zero_salt;
        salt_len = 32;
    }
    
    // PRK = HMAC-Hash(salt, IKM)
    return nostr_hmac_sha256(salt, salt_len, ikm, ikm_len, prk);
}

int nostr_hkdf_expand(const unsigned char* prk, size_t prk_len,
                     const unsigned char* info, size_t info_len,
                     unsigned char* okm, size_t okm_len) {
    if (!prk || !okm || okm_len == 0) return -1;
    
    // Check maximum output length (255 * hash_len for SHA256)
    if (okm_len > 255 * 32) return -1;
    
    unsigned char* temp = malloc(32 + info_len + 1); // T(i) || info || counter
    if (!temp) return -1;
    
    unsigned char t_prev[32] = {0}; // T(0) = empty string
    size_t t_prev_len = 0;
    size_t offset = 0;
    
    for (uint8_t counter = 1; offset < okm_len; counter++) {
        // T(i) = HMAC-Hash(PRK, T(i-1) || info || i)
        size_t temp_len = 0;
        
        // Add T(i-1) if not empty
        if (t_prev_len > 0) {
            memcpy(temp, t_prev, t_prev_len);
            temp_len += t_prev_len;
        }
        
        // Add info
        if (info && info_len > 0) {
            memcpy(temp + temp_len, info, info_len);
            temp_len += info_len;
        }
        
        // Add counter
        temp[temp_len] = counter;
        temp_len++;
        
        // Compute HMAC
        unsigned char t_current[32];
        if (nostr_hmac_sha256(prk, prk_len, temp, temp_len, t_current) != 0) {
            free(temp);
            return -1;
        }
        
        // Copy to output
        size_t copy_len = (okm_len - offset < 32) ? (okm_len - offset) : 32;
        memcpy(okm + offset, t_current, copy_len);
        offset += copy_len;
        
        // Save for next iteration
        memcpy(t_prev, t_current, 32);
        t_prev_len = 32;
    }
    
    free(temp);
    return 0;
}

int nostr_hkdf(const unsigned char* salt, size_t salt_len,
              const unsigned char* ikm, size_t ikm_len,
              const unsigned char* info, size_t info_len,
              unsigned char* okm, size_t okm_len) {
    if (!ikm || !okm) return -1;
    
    // Step 1: Extract
    unsigned char prk[32];
    if (nostr_hkdf_extract(salt, salt_len, ikm, ikm_len, prk) != 0) {
        return -1;
    }
    
    // Step 2: Expand
    int result = nostr_hkdf_expand(prk, 32, info, info_len, okm, okm_len);
    
    // Clear PRK
    memory_clear(prk, 32);
    
    return result;
}

// =============================================================================
// NIP-44 IMPLEMENTATION
// =============================================================================

// Constant-time comparison (security critical)
static int constant_time_compare(const unsigned char* a, const unsigned char* b, size_t len) {
    unsigned char result = 0;
    for (size_t i = 0; i < len; i++) {
        result |= (a[i] ^ b[i]);
    }
    return result == 0;
}

// NIP-44 padding calculation (per spec)
static size_t calc_padded_len(size_t unpadded_len) {
    if (unpadded_len <= 32) {
        return 32;
    }
    
    size_t next_power = 1;
    while (next_power < unpadded_len) {
        next_power <<= 1;
    }
    
    size_t chunk = (next_power <= 256) ? 32 : (next_power / 8);
    return chunk * ((unpadded_len - 1) / chunk + 1);
}

// NIP-44 padding (per spec)
static unsigned char* pad_plaintext(const char* plaintext, size_t* padded_len) {
    size_t unpadded_len = strlen(plaintext);
    if (unpadded_len > 65535) {
        return NULL;
    }
    
    // NIP-44 allows empty messages (unpadded_len can be 0)
    *padded_len = calc_padded_len(unpadded_len + 2); // +2 for length prefix
    unsigned char* padded = malloc(*padded_len);
    if (!padded) return NULL;
    
    // Write length prefix (big-endian u16)
    padded[0] = (unpadded_len >> 8) & 0xFF;
    padded[1] = unpadded_len & 0xFF;
    
    // Copy plaintext (if any)
    if (unpadded_len > 0) {
        memcpy(padded + 2, plaintext, unpadded_len);
    }
    
    // Zero-fill padding
    memset(padded + 2 + unpadded_len, 0, *padded_len - 2 - unpadded_len);
    
    return padded;
}

// NIP-44 unpadding (per spec)  
static char* unpad_plaintext(const unsigned char* padded, size_t padded_len) {
    if (padded_len < 2) return NULL;
    
    // Read length prefix (big-endian u16)
    size_t unpadded_len = (padded[0] << 8) | padded[1];
    if (unpadded_len > padded_len - 2) {
        return NULL;
    }
    
    // Verify padding length matches expected
    size_t expected_padded_len = calc_padded_len(unpadded_len + 2);
    if (padded_len != expected_padded_len) {
        return NULL;
    }
    
    char* plaintext = malloc(unpadded_len + 1);
    if (!plaintext) return NULL;
    
    // Handle empty message case (unpadded_len can be 0)
    if (unpadded_len > 0) {
        memcpy(plaintext, padded + 2, unpadded_len);
    }
    plaintext[unpadded_len] = '\0';
    
    return plaintext;
}

int nostr_nip44_encrypt_with_nonce(const unsigned char* sender_private_key,
                                  const unsigned char* recipient_public_key,
                                  const char* plaintext,
                                  const unsigned char* nonce,
                                  char* output,
                                  size_t output_size) {
    if (!sender_private_key || !recipient_public_key || !plaintext || !nonce || !output) {
        return NOSTR_ERROR_INVALID_INPUT;
    }
    
    size_t plaintext_len = strlen(plaintext);
    if (plaintext_len > NOSTR_NIP44_MAX_PLAINTEXT_SIZE) {
        return NOSTR_ERROR_NIP44_BUFFER_TOO_SMALL;
    }
    
    // Step 1: Compute ECDH shared secret
    unsigned char shared_secret[32];
    if (ecdh_shared_secret(sender_private_key, recipient_public_key, shared_secret) != 0) {
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 2: Calculate conversation key (HKDF-extract with "nip44-v2" as salt)
    unsigned char conversation_key[32];
    const char* salt_str = "nip44-v2";
    if (nostr_hkdf_extract((const unsigned char*)salt_str, strlen(salt_str),
                          shared_secret, 32, conversation_key) != 0) {
        memory_clear(shared_secret, 32);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 3: Use provided nonce (for testing)
    // Copy nonce for consistency with existing code structure
    unsigned char nonce_copy[32];
    memcpy(nonce_copy, nonce, 32);
    
    // Step 4: Derive message keys (HKDF-expand with nonce as info)
    unsigned char message_keys[76]; // 32 chacha_key + 12 chacha_nonce + 32 hmac_key
    if (nostr_hkdf_expand(conversation_key, 32, nonce_copy, 32, message_keys, 76) != 0) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(nonce_copy, 32);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    unsigned char* chacha_key = message_keys;
    unsigned char* chacha_nonce = message_keys + 32;
    unsigned char* hmac_key = message_keys + 44;
    
    // Step 5: Pad plaintext according to NIP-44 spec
    size_t padded_len;
    unsigned char* padded_plaintext = pad_plaintext(plaintext, &padded_len);
    if (!padded_plaintext) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(nonce, 32);
        memory_clear(message_keys, 76);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 6: Encrypt using ChaCha20
    unsigned char* ciphertext = malloc(padded_len);
    if (!ciphertext) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(nonce, 32);
        memory_clear(message_keys, 76);
        memory_clear(padded_plaintext, padded_len);
        free(padded_plaintext);
        return NOSTR_ERROR_MEMORY_FAILED;
    }
    
    if (chacha20_encrypt(chacha_key, 0, chacha_nonce, padded_plaintext, ciphertext, padded_len) != 0) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(nonce, 32);
        memory_clear(message_keys, 76);
        memory_clear(padded_plaintext, padded_len);
        free(padded_plaintext);
        free(ciphertext);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 7: Compute HMAC with AAD (nonce + ciphertext)
    unsigned char* aad_data = malloc(32 + padded_len);
    if (!aad_data) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(nonce_copy, 32);
        memory_clear(message_keys, 76);
        memory_clear(padded_plaintext, padded_len);
        free(padded_plaintext);
        free(ciphertext);
        return NOSTR_ERROR_MEMORY_FAILED;
    }
    
    memcpy(aad_data, nonce_copy, 32);
    memcpy(aad_data + 32, ciphertext, padded_len);
    
    unsigned char mac[32];
    if (nostr_hmac_sha256(hmac_key, 32, aad_data, 32 + padded_len, mac) != 0) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(nonce, 32);
        memory_clear(message_keys, 76);
        memory_clear(padded_plaintext, padded_len);
        memory_clear(aad_data, 32 + padded_len);
        free(padded_plaintext);
        free(ciphertext);
        free(aad_data);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 8: Format as base64(version + nonce + ciphertext + mac)
    size_t payload_len = 1 + 32 + padded_len + 32; // version + nonce + ciphertext + mac
    unsigned char* payload = malloc(payload_len);
    if (!payload) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(nonce, 32);
        memory_clear(message_keys, 76);
        memory_clear(padded_plaintext, padded_len);
        memory_clear(aad_data, 32 + padded_len);
        free(padded_plaintext);
        free(ciphertext);
        free(aad_data);
        return NOSTR_ERROR_MEMORY_FAILED;
    }
    
    payload[0] = 0x02; // NIP-44 version 2
    memcpy(payload + 1, nonce_copy, 32);
    memcpy(payload + 33, ciphertext, padded_len);
    memcpy(payload + 33 + padded_len, mac, 32);
    
    // Base64 encode
    size_t b64_len = ((payload_len + 2) / 3) * 4 + 1;
    if (b64_len > output_size) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(nonce, 32);
        memory_clear(message_keys, 76);
        memory_clear(padded_plaintext, padded_len);
        memory_clear(aad_data, 32 + padded_len);
        memory_clear(payload, payload_len);
        free(padded_plaintext);
        free(ciphertext);
        free(aad_data);
        free(payload);
        return NOSTR_ERROR_NIP44_BUFFER_TOO_SMALL;
    }
    
    if (base64_encode(payload, payload_len, output, output_size) == 0) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(nonce, 32);
        memory_clear(message_keys, 76);
        memory_clear(padded_plaintext, padded_len);
        memory_clear(aad_data, 32 + padded_len);
        memory_clear(payload, payload_len);
        free(padded_plaintext);
        free(ciphertext);
        free(aad_data);
        free(payload);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Cleanup
    memory_clear(shared_secret, 32);
    memory_clear(conversation_key, 32);
    memory_clear(nonce_copy, 32);
    memory_clear(message_keys, 76);
    memory_clear(padded_plaintext, padded_len);
    memory_clear(aad_data, 32 + padded_len);
    memory_clear(payload, payload_len);
    free(padded_plaintext);
    free(ciphertext);
    free(aad_data);
    free(payload);
    
    return NOSTR_SUCCESS;
}

int nostr_nip44_encrypt(const unsigned char* sender_private_key,
                       const unsigned char* recipient_public_key,
                       const char* plaintext,
                       char* output,
                       size_t output_size) {
    // Generate random nonce and call the _with_nonce version
    unsigned char nonce[32];
    if (nostr_secp256k1_get_random_bytes(nonce, 32) != 1) {
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    return nostr_nip44_encrypt_with_nonce(sender_private_key, recipient_public_key, 
                                         plaintext, nonce, output, output_size);
}

int nostr_nip44_decrypt(const unsigned char* recipient_private_key,
                       const unsigned char* sender_public_key,
                       const char* encrypted_data,
                       char* output,
                       size_t output_size) {
    if (!recipient_private_key || !sender_public_key || !encrypted_data || !output) {
        return NOSTR_ERROR_INVALID_INPUT;
    }
    
    // Step 1: Base64 decode the encrypted data
    size_t max_payload_len = ((strlen(encrypted_data) + 3) / 4) * 3;
    unsigned char* payload = malloc(max_payload_len);
    if (!payload) {
        return NOSTR_ERROR_MEMORY_FAILED;
    }
    
    size_t payload_len = base64_decode(encrypted_data, payload);
    if (payload_len < 66) { // Minimum: version(1) + nonce(32) + mac(32) + 1 byte ciphertext
        free(payload);
        return NOSTR_ERROR_NIP44_INVALID_FORMAT;
    }
    
    // Step 2: Extract components (version + nonce + ciphertext + mac)
    if (payload[0] != 0x02) { // Check NIP-44 version
        free(payload);
        return NOSTR_ERROR_NIP44_INVALID_FORMAT;
    }
    
    unsigned char* nonce = payload + 1;
    size_t ciphertext_len = payload_len - 65; // payload - version - nonce - mac
    unsigned char* ciphertext = payload + 33;
    unsigned char* received_mac = payload + payload_len - 32;
    
    // Step 3: Compute ECDH shared secret
    unsigned char shared_secret[32];
    if (ecdh_shared_secret(recipient_private_key, sender_public_key, shared_secret) != 0) {
        memory_clear(payload, payload_len);
        free(payload);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 4: Calculate conversation key (HKDF-extract with "nip44-v2" as salt)
    unsigned char conversation_key[32];
    const char* salt_str = "nip44-v2";
    if (nostr_hkdf_extract((const unsigned char*)salt_str, strlen(salt_str),
                          shared_secret, 32, conversation_key) != 0) {
        memory_clear(shared_secret, 32);
        memory_clear(payload, payload_len);
        free(payload);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 5: Derive message keys (HKDF-expand with nonce as info)
    unsigned char message_keys[76]; // 32 chacha_key + 12 chacha_nonce + 32 hmac_key
    if (nostr_hkdf_expand(conversation_key, 32, nonce, 32, message_keys, 76) != 0) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(payload, payload_len);
        free(payload);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    unsigned char* chacha_key = message_keys;
    unsigned char* chacha_nonce = message_keys + 32;
    unsigned char* hmac_key = message_keys + 44;
    
    // Step 6: Verify HMAC with AAD (nonce + ciphertext)
    unsigned char* aad_data = malloc(32 + ciphertext_len);
    if (!aad_data) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(message_keys, 76);
        memory_clear(payload, payload_len);
        free(payload);
        return NOSTR_ERROR_MEMORY_FAILED;
    }
    
    memcpy(aad_data, nonce, 32);
    memcpy(aad_data + 32, ciphertext, ciphertext_len);
    
    unsigned char computed_mac[32];
    if (nostr_hmac_sha256(hmac_key, 32, aad_data, 32 + ciphertext_len, computed_mac) != 0) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(message_keys, 76);
        memory_clear(aad_data, 32 + ciphertext_len);
        memory_clear(payload, payload_len);
        free(aad_data);
        free(payload);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Constant-time MAC verification
    if (!constant_time_compare(received_mac, computed_mac, 32)) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(message_keys, 76);
        memory_clear(aad_data, 32 + ciphertext_len);
        memory_clear(payload, payload_len);
        free(aad_data);
        free(payload);
        return NOSTR_ERROR_NIP44_DECRYPT_FAILED;
    }
    
    // Step 7: Decrypt using ChaCha20
    unsigned char* padded_plaintext = malloc(ciphertext_len);
    if (!padded_plaintext) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(message_keys, 76);
        memory_clear(aad_data, 32 + ciphertext_len);
        memory_clear(payload, payload_len);
        free(aad_data);
        free(payload);
        return NOSTR_ERROR_MEMORY_FAILED;
    }
    
    if (chacha20_encrypt(chacha_key, 0, chacha_nonce, ciphertext, padded_plaintext, ciphertext_len) != 0) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(message_keys, 76);
        memory_clear(aad_data, 32 + ciphertext_len);
        memory_clear(payload, payload_len);
        free(aad_data);
        free(payload);
        free(padded_plaintext);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 8: Remove padding according to NIP-44 spec
    char* plaintext = unpad_plaintext(padded_plaintext, ciphertext_len);
    if (!plaintext) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(message_keys, 76);
        memory_clear(aad_data, 32 + ciphertext_len);
        memory_clear(payload, payload_len);
        memory_clear(padded_plaintext, ciphertext_len);
        free(aad_data);
        free(payload);
        free(padded_plaintext);
        return NOSTR_ERROR_NIP44_DECRYPT_FAILED;
    }
    
    // Step 9: Copy to output buffer
    size_t plaintext_len = strlen(plaintext);
    if (plaintext_len + 1 > output_size) {
        memory_clear(shared_secret, 32);
        memory_clear(conversation_key, 32);
        memory_clear(message_keys, 76);
        memory_clear(aad_data, 32 + ciphertext_len);
        memory_clear(payload, payload_len);
        memory_clear(padded_plaintext, ciphertext_len);
        memory_clear(plaintext, plaintext_len);
        free(aad_data);
        free(payload);
        free(padded_plaintext);
        free(plaintext);
        return NOSTR_ERROR_NIP44_BUFFER_TOO_SMALL;
    }
    
    strcpy(output, plaintext);
    
    // Cleanup
    memory_clear(shared_secret, 32);
    memory_clear(conversation_key, 32);
    memory_clear(message_keys, 76);
    memory_clear(aad_data, 32 + ciphertext_len);
    memory_clear(payload, payload_len);
    memory_clear(padded_plaintext, ciphertext_len);
    memory_clear(plaintext, plaintext_len);
    free(aad_data);
    free(payload);
    free(padded_plaintext);
    free(plaintext);
    
    return NOSTR_SUCCESS;
}

// =============================================================================
// AES-256-CBC ENCRYPTION/DECRYPTION USING TINYAES
// =============================================================================

static int aes_cbc_encrypt(const unsigned char* key, const unsigned char* iv,
                          const unsigned char* input, size_t input_len,
                          unsigned char* output) {
    if (!key || !iv || !input || !output || input_len % 16 != 0) {
        return -1;
    }
    
    // Initialize AES context with key and IV
    struct AES_ctx ctx;
    AES_init_ctx_iv(&ctx, key, iv);
    
    // Copy input to output (tinyAES works in-place)
    memcpy(output, input, input_len);
    
    // Encrypt using AES-256-CBC
    AES_CBC_encrypt_buffer(&ctx, output, input_len);
    
    return 0;
}

static int aes_cbc_decrypt(const unsigned char* key, const unsigned char* iv,
                          const unsigned char* input, size_t input_len,
                          unsigned char* output) {
    if (!key || !iv || !input || !output || input_len % 16 != 0) {
        return -1;
    }
    
    // Initialize AES context with key and IV
    struct AES_ctx ctx;
    AES_init_ctx_iv(&ctx, key, iv);
    
    // Copy input to output (tinyAES works in-place)
    memcpy(output, input, input_len);
    
    // Decrypt using AES-256-CBC
    AES_CBC_decrypt_buffer(&ctx, output, input_len);
    
    return 0;
}

// PKCS#7 padding functions
static size_t pkcs7_pad(unsigned char* data, size_t data_len, size_t block_size) {
    size_t padding = block_size - (data_len % block_size);
    for (size_t i = 0; i < padding; i++) {
        data[data_len + i] = (unsigned char)padding;
    }
    return data_len + padding;
}

static size_t pkcs7_unpad(unsigned char* data, size_t data_len) {
    if (data_len == 0) return 0;
    
    unsigned char padding = data[data_len - 1];
    if (padding == 0 || padding > 16) return 0; // Invalid padding
    
    // Verify padding
    for (size_t i = data_len - padding; i < data_len; i++) {
        if (data[i] != padding) return 0; // Invalid padding
    }
    
    return data_len - padding;
}

// =============================================================================
// NIP-04 IMPLEMENTATION
// =============================================================================

int nostr_nip04_encrypt(const unsigned char* sender_private_key,
                       const unsigned char* recipient_public_key, 
                       const char* plaintext,
                       char* output,
                       size_t output_size) {
    if (!sender_private_key || !recipient_public_key || !plaintext || !output) {
        return NOSTR_ERROR_INVALID_INPUT;
    }
    
    size_t plaintext_len = strlen(plaintext);
    
    if (plaintext_len > NOSTR_NIP04_MAX_PLAINTEXT_SIZE) {
        return NOSTR_ERROR_NIP04_BUFFER_TOO_SMALL;
    }
    
    // FIX: Calculate final size requirements EARLY before any allocations
    // CRITICAL: Account for PKCS#7 padding which ALWAYS adds 1-16 bytes
    // If plaintext_len is a multiple of 16, PKCS#7 adds a full 16-byte block
    size_t padded_len = ((plaintext_len / 16) + 1) * 16; // Always add one full block for PKCS#7
    size_t ciphertext_b64_max = ((padded_len + 2) / 3) * 4 + 1;
    size_t iv_b64_max = ((16 + 2) / 3) * 4 + 1;  // Always 25 bytes
    size_t estimated_result_len = ciphertext_b64_max + 4 + iv_b64_max;  // +4 for "?iv="
    
    // FIX: Check output buffer size BEFORE doing any work
    if (estimated_result_len > output_size) {
        return NOSTR_ERROR_NIP04_BUFFER_TOO_SMALL;
    }
    
    // Step 1: Compute ECDH shared secret
    unsigned char shared_secret[32];
    if (ecdh_shared_secret(sender_private_key, recipient_public_key, shared_secret) != 0) {
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 2: Generate random IV (16 bytes)
    unsigned char iv[16];
    if (nostr_secp256k1_get_random_bytes(iv, 16) != 1) {
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 3: Pad plaintext using PKCS#7
    unsigned char* padded_data = malloc(padded_len);
    if (!padded_data) {
        return NOSTR_ERROR_MEMORY_FAILED;
    }
    
    memcpy(padded_data, plaintext, plaintext_len);
    size_t actual_padded_len = pkcs7_pad(padded_data, plaintext_len, 16);
    
    // Step 4: Encrypt using AES-256-CBC
    unsigned char* ciphertext = malloc(padded_len);
    if (!ciphertext) {
        free(padded_data);
        return NOSTR_ERROR_MEMORY_FAILED;
    }
    
    if (aes_cbc_encrypt(shared_secret, iv, padded_data, actual_padded_len, ciphertext) != 0) {
        free(padded_data);
        free(ciphertext);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 5: Base64 encode ciphertext and IV
    size_t ciphertext_b64_len = ((actual_padded_len + 2) / 3) * 4 + 1;
    size_t iv_b64_len = ((16 + 2) / 3) * 4 + 1;
    
    char* ciphertext_b64 = malloc(ciphertext_b64_len);
    char* iv_b64 = malloc(iv_b64_len);
    
    if (!ciphertext_b64 || !iv_b64) {
        free(padded_data);
        free(ciphertext);
        free(ciphertext_b64);
        free(iv_b64);
        return NOSTR_ERROR_MEMORY_FAILED;
    }
    
    // FIX: Pass buffer sizes to base64_encode and check for success
    size_t ct_b64_len = base64_encode(ciphertext, actual_padded_len, ciphertext_b64, ciphertext_b64_len);
    size_t iv_b64_len_actual = base64_encode(iv, 16, iv_b64, iv_b64_len);
    
    // FIX: Check if encoding succeeded
    if (ct_b64_len == 0 || iv_b64_len_actual == 0) {
        free(padded_data);
        free(ciphertext);
        free(ciphertext_b64);
        free(iv_b64);
        memory_clear(shared_secret, 32);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 6: Format as "ciphertext?iv=iv_base64" - size check moved earlier, now guaranteed to fit
    size_t result_len = ct_b64_len + 4 + iv_b64_len_actual + 1; // +4 for "?iv=", +1 for null
    
    if (result_len > output_size) {
        free(padded_data);
        free(ciphertext);
        free(ciphertext_b64);
        free(iv_b64);
        memory_clear(shared_secret, 32);
        return NOSTR_ERROR_NIP04_BUFFER_TOO_SMALL;
    }
    
    snprintf(output, output_size, "%s?iv=%s", ciphertext_b64, iv_b64);
    
    // Cleanup
    memory_clear(shared_secret, 32);
    memory_clear(padded_data, padded_len);
    memory_clear(ciphertext, padded_len);
    free(padded_data);
    free(ciphertext);
    free(ciphertext_b64);
    free(iv_b64);
    
    return NOSTR_SUCCESS;
}

int nostr_nip04_decrypt(const unsigned char* recipient_private_key,
                       const unsigned char* sender_public_key,
                       const char* encrypted_data,
                       char* output,
                       size_t output_size) {
    if (!recipient_private_key || !sender_public_key || !encrypted_data || !output) {
        return NOSTR_ERROR_INVALID_INPUT;
    }
    
    // Step 1: Parse encrypted data format "ciphertext?iv=iv_base64"
    char* separator = strstr(encrypted_data, "?iv=");
    if (!separator) {
        return NOSTR_ERROR_NIP04_INVALID_FORMAT;
    }
    
    size_t ciphertext_b64_len = separator - encrypted_data;
    const char* iv_b64 = separator + 4; // Skip "?iv="
    
    if (ciphertext_b64_len == 0 || strlen(iv_b64) == 0) {
        return NOSTR_ERROR_NIP04_INVALID_FORMAT;
    }
    
    // Step 2: Create null-terminated copy of ciphertext base64
    char* ciphertext_b64 = malloc(ciphertext_b64_len + 1);
    if (!ciphertext_b64) {
        return NOSTR_ERROR_MEMORY_FAILED;
    }
    
    memcpy(ciphertext_b64, encrypted_data, ciphertext_b64_len);
    ciphertext_b64[ciphertext_b64_len] = '\0';
    
    // Step 3: Calculate proper buffer sizes for decoded data
    // Base64 decoding: 4 chars -> 3 bytes, so max decoded size is (len * 3) / 4
    size_t max_ciphertext_len = ((ciphertext_b64_len + 3) / 4) * 3;
    size_t max_iv_len = ((strlen(iv_b64) + 3) / 4) * 3;
    
    // Allocate buffers with proper sizes
    unsigned char* ciphertext = malloc(max_ciphertext_len);
    unsigned char* iv_buffer = malloc(max_iv_len);
    
    if (!ciphertext || !iv_buffer) {
        free(ciphertext_b64);
        free(ciphertext);
        free(iv_buffer);
        return NOSTR_ERROR_MEMORY_FAILED;
    }
    
    // Step 4: Base64 decode ciphertext and IV
    size_t ciphertext_len = base64_decode(ciphertext_b64, ciphertext);
    size_t iv_len = base64_decode(iv_b64, iv_buffer);
    
    if (ciphertext_len == 0 || iv_len != 16 || ciphertext_len % 16 != 0) {
        free(ciphertext_b64);
        free(ciphertext);
        free(iv_buffer);
        return NOSTR_ERROR_NIP04_INVALID_FORMAT;
    }
    
    // Copy IV to fixed-size buffer for safety
    unsigned char iv[16];
    memcpy(iv, iv_buffer, 16);
    free(iv_buffer);
    
    // Step 5: Compute ECDH shared secret
    unsigned char shared_secret[32];
    if (ecdh_shared_secret(recipient_private_key, sender_public_key, shared_secret) != 0) {
        free(ciphertext_b64);
        free(ciphertext);
        return NOSTR_ERROR_CRYPTO_FAILED;
    }
    
    // Step 6: Decrypt using AES-256-CBC
    unsigned char* plaintext_padded = malloc(ciphertext_len);
    if (!plaintext_padded) {
        free(ciphertext_b64);
        free(ciphertext);
        return NOSTR_ERROR_MEMORY_FAILED;
    }
    
    if (aes_cbc_decrypt(shared_secret, iv, ciphertext, ciphertext_len, plaintext_padded) != 0) {
        free(ciphertext_b64);
        free(ciphertext);
        free(plaintext_padded);
        return NOSTR_ERROR_NIP04_DECRYPT_FAILED;
    }
    
    // Step 7: Remove PKCS#7 padding
    size_t plaintext_len = pkcs7_unpad(plaintext_padded, ciphertext_len);
    if (plaintext_len == 0 || plaintext_len > ciphertext_len) {
        free(ciphertext_b64);
        free(ciphertext);
        free(plaintext_padded);
        return NOSTR_ERROR_NIP04_DECRYPT_FAILED;
    }
    
    // Step 8: Copy to output buffer and null-terminate
    if (plaintext_len + 1 > output_size) {
        free(ciphertext_b64);
        free(ciphertext);
        free(plaintext_padded);
        return NOSTR_ERROR_NIP04_BUFFER_TOO_SMALL;
    }
    
    memcpy(output, plaintext_padded, plaintext_len);
    output[plaintext_len] = '\0';
    
    // Cleanup
    memory_clear(shared_secret, 32);
    memory_clear(plaintext_padded, ciphertext_len);
    free(ciphertext_b64);
    free(ciphertext);
    free(plaintext_padded);
    
    return NOSTR_SUCCESS;
}

// =============================================================================
// HMAC IMPLEMENTATION
// =============================================================================

int nostr_hmac_sha256(const unsigned char* key, size_t key_len,
                      const unsigned char* data, size_t data_len,
                      unsigned char* output) {
    if (!key || !data || !output) return -1;

    uint8_t ikey[64], okey[64];
    uint8_t hash[32];
    size_t i;

    // Prepare key
    if (key_len > 64) {
        nostr_sha256(key, key_len, hash);
        memcpy(ikey, hash, 32);
        memset(ikey + 32, 0, 32);
    } else {
        memcpy(ikey, key, key_len);
        memset(ikey + key_len, 0, 64 - key_len);
    }

    // Create inner and outer keys
    memcpy(okey, ikey, 64);
    for (i = 0; i < 64; i++) {
        ikey[i] ^= 0x36;
        okey[i] ^= 0x5c;
    }

    // Inner hash: H(K XOR ipad, text)
    uint8_t* temp = malloc(64 + data_len);
    if (!temp) return -1;
    
    memcpy(temp, ikey, 64);
    memcpy(temp + 64, data, data_len);
    nostr_sha256(temp, 64 + data_len, hash);
    free(temp);

    // Outer hash: H(K XOR opad, inner_hash)
    temp = malloc(64 + 32);
    if (!temp) return -1;
    
    memcpy(temp, okey, 64);
    memcpy(temp + 64, hash, 32);
    nostr_sha256(temp, 64 + 32, output);
    free(temp);

    return 0;
}

// =============================================================================
// SHA-512 IMPLEMENTATION (for HMAC-SHA512 and PBKDF2)
// =============================================================================

// SHA-512 constants
static const uint64_t K512[80] = {
    0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
    0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
    0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
    0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
    0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
    0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
    0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
    0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
    0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
    0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
    0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
    0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
    0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
    0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
    0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
    0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
    0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
    0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
    0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
    0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL
};

#define ROTR64(x, n) (((x) >> (n)) | ((x) << (64 - (n))))
#define CH64(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
#define MAJ64(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#define S0_512(x) (ROTR64(x, 28) ^ ROTR64(x, 34) ^ ROTR64(x, 39))
#define S1_512(x) (ROTR64(x, 14) ^ ROTR64(x, 18) ^ ROTR64(x, 41))
#define s0_512(x) (ROTR64(x, 1) ^ ROTR64(x, 8) ^ ((x) >> 7))
#define s1_512(x) (ROTR64(x, 19) ^ ROTR64(x, 61) ^ ((x) >> 6))

static void sha512_transform(uint64_t state[8], const uint8_t data[128]) {
    uint64_t a, b, c, d, e, f, g, h, i, t1, t2, W[80];

    for (i = 0; i < 16; ++i) {
        W[i] = ((uint64_t)data[i * 8] << 56) | ((uint64_t)data[i * 8 + 1] << 48) |
               ((uint64_t)data[i * 8 + 2] << 40) | ((uint64_t)data[i * 8 + 3] << 32) |
               ((uint64_t)data[i * 8 + 4] << 24) | ((uint64_t)data[i * 8 + 5] << 16) |
               ((uint64_t)data[i * 8 + 6] << 8) | ((uint64_t)data[i * 8 + 7]);
    }
    for (; i < 80; ++i) {
        W[i] = s1_512(W[i - 2]) + W[i - 7] + s0_512(W[i - 15]) + W[i - 16];
    }

    a = state[0]; b = state[1]; c = state[2]; d = state[3];
    e = state[4]; f = state[5]; g = state[6]; h = state[7];

    for (i = 0; i < 80; ++i) {
        t1 = h + S1_512(e) + CH64(e, f, g) + K512[i] + W[i];
        t2 = S0_512(a) + MAJ64(a, b, c);
        h = g; g = f; f = e; e = d + t1;
        d = c; c = b; b = a; a = t1 + t2;
    }

    state[0] += a; state[1] += b; state[2] += c; state[3] += d;
    state[4] += e; state[5] += f; state[6] += g; state[7] += h;
}

int nostr_sha512(const unsigned char* data, size_t len, unsigned char* hash) {
    if (!data || !hash) return -1;

    uint64_t state[8] = {
        0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
        0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL
    };

    uint64_t bitlen = (uint64_t)len * 8;
    size_t i;
    uint8_t data_block[128];

    // Process complete 128-byte blocks
    for (i = 0; i + 128 <= len; i += 128) {
        sha512_transform(state, data + i);
    }

    // Handle remaining bytes and padding
    size_t remaining = len - i;
    memcpy(data_block, data + i, remaining);
    data_block[remaining] = 0x80;

    if (remaining >= 112) {
        memset(data_block + remaining + 1, 0, 128 - remaining - 1);
        sha512_transform(state, data_block);
        memset(data_block, 0, 120);
    } else {
        memset(data_block + remaining + 1, 0, 111 - remaining);
    }

    // Add length in bits as big-endian 128-bit integer (high 64 bits = 0, low 64 bits = bitlen)
    // First 8 bytes for high 64 bits (always 0 for our use case)
    memset(data_block + 112, 0, 8);
    // Last 8 bytes for low 64 bits
    for (i = 0; i < 8; ++i) {
        data_block[120 + i] = (bitlen >> (56 - i * 8)) & 0xff;
    }
    sha512_transform(state, data_block);

    // Convert state to output bytes
    for (i = 0; i < 8; ++i) {
        hash[i * 8] = (state[i] >> 56) & 0xff;
        hash[i * 8 + 1] = (state[i] >> 48) & 0xff;
        hash[i * 8 + 2] = (state[i] >> 40) & 0xff;
        hash[i * 8 + 3] = (state[i] >> 32) & 0xff;
        hash[i * 8 + 4] = (state[i] >> 24) & 0xff;
        hash[i * 8 + 5] = (state[i] >> 16) & 0xff;
        hash[i * 8 + 6] = (state[i] >> 8) & 0xff;
        hash[i * 8 + 7] = state[i] & 0xff;
    }

    return 0;
}

int nostr_hmac_sha512(const unsigned char* key, size_t key_len,
                      const unsigned char* data, size_t data_len,
                      unsigned char* output) {
    if (!key || !data || !output) return -1;

    uint8_t ikey[128], okey[128];
    uint8_t hash[64];
    size_t i;

    // Prepare key (exactly as libwally-core does)
    memset(ikey, 0, 128); // Clear the buffer first
    
    if (key_len > 128) {
        nostr_sha512(key, key_len, hash);
        memcpy(ikey, hash, 64);
        // Rest remains zero-filled
    } else {
        memcpy(ikey, key, key_len);
        // Rest remains zero-filled from memset above
    }

    // Create inner and outer keys
    memcpy(okey, ikey, 128);
    for (i = 0; i < 128; i++) {
        ikey[i] ^= 0x36;
        okey[i] ^= 0x5c;
    }

    // Inner hash: H(K XOR ipad, text)
    uint8_t* temp = malloc(128 + data_len);
    if (!temp) return -1;
    
    memcpy(temp, ikey, 128);
    memcpy(temp + 128, data, data_len);
    nostr_sha512(temp, 128 + data_len, hash);
    free(temp);

    // Outer hash: H(K XOR opad, inner_hash)
    temp = malloc(128 + 64);
    if (!temp) return -1;
    
    memcpy(temp, okey, 128);
    memcpy(temp + 128, hash, 64);
    nostr_sha512(temp, 128 + 64, output);
    free(temp);

    return 0;
}

// =============================================================================
// UTILITY FUNCTIONS (adapted from libwally-core)
// =============================================================================

// Endian conversion utilities (fixed to properly convert to big-endian)
static inline uint32_t cpu_to_be32(uint32_t native) {
    // Always convert to big-endian format regardless of host endianness
    return ((native & 0x000000ff) << 24) |
           ((native & 0x0000ff00) << 8) |
           ((native & 0x00ff0000) >> 8) |
           ((native & 0xff000000) >> 24);
}

// Simple alignment check (for memory optimization)
static inline int alignment_ok(const void *ptr, size_t alignment) {
    return (((uintptr_t)ptr) % alignment) == 0;
}

// Memory clearing utility
static void wally_clear(void *p, size_t len) {
    if (p && len) {
        memset(p, 0, len);
    }
}

// =============================================================================
// PBKDF2 IMPLEMENTATION (adapted from libwally-core)
// =============================================================================

int nostr_pbkdf2_hmac_sha512(const unsigned char* password, size_t password_len,
                             const unsigned char* salt, size_t salt_len,
                             int iterations,
                             unsigned char* output, size_t output_len) {
    if (!password || !salt || !output || iterations <= 0) return -1;
    
    // libwally-core compatibility: output length must be multiple of 64 bytes
    if (!output_len || output_len % 64) return -1;
    
    unsigned char *temp_salt = malloc(salt_len + 4);
    if (!temp_salt) return -1;
    
    memcpy(temp_salt, salt, salt_len);
    size_t temp_salt_len = salt_len + 4; // Add space for block number
    
    // Create working buffers
    unsigned char d1[64], d2[64], *sha_cp;
    unsigned char *bytes_out = output; // Track original output pointer
    
    // If output buffer is suitably aligned, we can work on it directly
    if (alignment_ok(output, sizeof(uint64_t))) {
        sha_cp = (unsigned char*)output;
    } else {
        sha_cp = d2;
    }
    
    // Process each 64-byte block (exactly as libwally-core does)
    for (size_t n = 0; n < output_len / 64; ++n) {
        uint32_t block = cpu_to_be32(n + 1); // Block number in big-endian
        
        // Copy block number to salt (exactly as libwally-core does)
        memcpy(temp_salt + salt_len, &block, 4);
        
        // First iteration: U1 = HMAC(password, salt || block)
        if (nostr_hmac_sha512(password, password_len, temp_salt, temp_salt_len, d1) != 0) {
            free(temp_salt);
            return -1;
        }
        
        // Initialize working buffer with U1
        memcpy(sha_cp, d1, 64);
        
        // Remaining iterations: Ui = HMAC(password, Ui-1), T = U1 XOR U2 XOR ... XOR Ui
        for (uint32_t c = 0; iterations && c < (uint32_t)iterations - 1; ++c) {
            if (nostr_hmac_sha512(password, password_len, d1, 64, d1) != 0) {
                free(temp_salt);
                return -1;
            }
            
            // XOR with accumulated result (exactly as libwally-core does)
            for (size_t j = 0; j < 64 / sizeof(uint64_t); ++j) {
                ((uint64_t*)sha_cp)[j] ^= ((uint64_t*)d1)[j];
            }
        }
        
        // Copy result to final output if we were using temporary buffer
        if (sha_cp == d2) {
            memcpy(bytes_out, sha_cp, 64);
        } else {
            sha_cp += 64; // Move to next 64-byte block
        }
        
        bytes_out += 64; // Always advance output pointer
    }
    
    // Clear sensitive data
    wally_clear(d1, sizeof(d1));
    wally_clear(d2, sizeof(d2));
    if (temp_salt) {
        wally_clear(temp_salt, temp_salt_len);
        free(temp_salt);
    }
    
    return 0;
}

// =============================================================================
// SECP256K1 ELLIPTIC CURVE IMPLEMENTATION
// =============================================================================


typedef struct {
    uint32_t d[8];
} secp256k1_scalar;

// Set scalar from bytes (big-endian)
static void scalar_set_b32(secp256k1_scalar* r, const unsigned char* b32) {
    for (int i = 0; i < 8; i++) {
        r->d[i] = (uint32_t)b32[31-i*4] | ((uint32_t)b32[30-i*4] << 8) |
                  ((uint32_t)b32[29-i*4] << 16) | ((uint32_t)b32[28-i*4] << 24);
    }
}

// Check if scalar is zero
static int scalar_is_zero(const secp256k1_scalar* a) {
    for (int i = 0; i < 8; i++) {
        if (a->d[i] != 0) return 0;
    }
    return 1;
}

// Compare two 256-bit numbers
static int scalar_cmp(const secp256k1_scalar* a, const secp256k1_scalar* b) {
    for (int i = 7; i >= 0; i--) {
        if (a->d[i] < b->d[i]) return -1;
        if (a->d[i] > b->d[i]) return 1;
    }
    return 0;
}

// =============================================================================
// RFC 6979 DETERMINISTIC NONCE GENERATION
// =============================================================================

// Check if a 32-byte value is a valid secp256k1 scalar (< curve order)
static int is_valid_scalar(const unsigned char* scalar) {
    secp256k1_scalar s, n;
    scalar_set_b32(&s, scalar);
    scalar_set_b32(&n, (const unsigned char*)"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"
                                            "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE"
                                            "\xBA\xAE\xDC\xE6\xAF\x48\xA0\x3B"
                                            "\xBF\xD2\x5E\x8C\xD0\x36\x41\x41");
    return !scalar_is_zero(&s) && scalar_cmp(&s, &n) < 0;
}

// RFC 6979 deterministic nonce generation for secp256k1
// Based on RFC 6979 Section 3.2
int nostr_rfc6979_generate_k(const unsigned char* private_key,
                            const unsigned char* message_hash,
                            unsigned char* k_out) {
    if (!private_key || !message_hash || !k_out) return -1;
    
    // Step a: h1 = message_hash (already provided)
    // Step b: V = 0x01 0x01 0x01 ... (32 bytes)
    unsigned char V[32];
    memset(V, 0x01, 32);
    
    // Step c: K = 0x00 0x00 0x00 ... (32 bytes)
    unsigned char K[32];
    memset(K, 0x00, 32);
    
    // Step d: K = HMAC_K(V || 0x00 || private_key || h1)
    unsigned char temp[32 + 1 + 32 + 32]; // V || 0x00 || private_key || h1
    memcpy(temp, V, 32);
    temp[32] = 0x00;
    memcpy(temp + 33, private_key, 32);
    memcpy(temp + 65, message_hash, 32);
    
    if (nostr_hmac_sha256(K, 32, temp, 97, K) != 0) return -1;
    
    // Step e: V = HMAC_K(V)
    if (nostr_hmac_sha256(K, 32, V, 32, V) != 0) return -1;
    
    // Step f: K = HMAC_K(V || 0x01 || private_key || h1)
    temp[32] = 0x01;
    if (nostr_hmac_sha256(K, 32, temp, 97, K) != 0) return -1;
    
    // Step g: V = HMAC_K(V)
    if (nostr_hmac_sha256(K, 32, V, 32, V) != 0) return -1;
    
    // Step h: Generate candidates until we find a valid one
    for (int attempts = 0; attempts < 1000; attempts++) {
        // Step h1: V = HMAC_K(V)
        if (nostr_hmac_sha256(K, 32, V, 32, V) != 0) return -1;
        
        // Step h2: Check if V is a valid scalar for secp256k1
        if (is_valid_scalar(V)) {
            memcpy(k_out, V, 32);
            return 0; // Success
        }
        
        // Step h3: K = HMAC_K(V || 0x00)
        unsigned char temp_h3[33];
        memcpy(temp_h3, V, 32);
        temp_h3[32] = 0x00;
        if (nostr_hmac_sha256(K, 32, temp_h3, 33, K) != 0) return -1;
        
        // V = HMAC_K(V)
        if (nostr_hmac_sha256(K, 32, V, 32, V) != 0) return -1;
    }
    
    return -1; // Failed to generate valid k after many attempts
}

int nostr_crypto_init(void) {
    return nostr_secp256k1_context_create() ? 0 : -1;
}

void nostr_crypto_cleanup(void) {
    nostr_secp256k1_context_destroy();
}

int nostr_ec_private_key_verify(const unsigned char* private_key) {
    if (!private_key) return -1;
    
    return nostr_secp256k1_ec_seckey_verify(private_key) ? 0 : -1;
}

int nostr_ec_public_key_from_private_key(const unsigned char* private_key,
                                        unsigned char* public_key) {
    if (!private_key || !public_key) return -1;
    
    // Verify private key first
    if (nostr_ec_private_key_verify(private_key) != 0) return -1;
    
    // Use secp256k1 to generate the public key
    nostr_secp256k1_pubkey pubkey;
    if (nostr_secp256k1_ec_pubkey_create(&pubkey, private_key) != 1) {
        return -1;
    }
    
    // Serialize the public key to compressed format
    unsigned char compressed_pubkey[33];
    if (nostr_secp256k1_ec_pubkey_serialize_compressed(compressed_pubkey, &pubkey) != 1) {
        return -1;
    }
    
    // NOSTR uses the 32-byte x-coordinate only (without the compression prefix)
    memcpy(public_key, compressed_pubkey + 1, 32);
    
    return 0;
}

int nostr_schnorr_sign(const unsigned char* private_key,
                       const unsigned char* hash,
                       unsigned char* signature) {
    if (!private_key || !hash || !signature) return -1;
    
    // Verify private key
    if (nostr_ec_private_key_verify(private_key) != 0) return -1;
    
    // Create keypair from private key
    nostr_secp256k1_keypair keypair;
    if (nostr_secp256k1_keypair_create(&keypair, private_key) != 1) {
        return -1;
    }
    
    // Create BIP-340 Schnorr signature using NULL auxiliary randomness
    // This makes libsecp256k1 use its internal RFC 6979 implementation
    // with proper BIP-340 parameters, matching other NOSTR implementations
    if (nostr_secp256k1_schnorrsig_sign32(signature, hash, &keypair, NULL) != 1) {
        return -1;
    }
    
    return 0;
}

// Legacy function name for backwards compatibility
int nostr_ec_sign(const unsigned char* private_key,
                  const unsigned char* hash,
                  unsigned char* signature) {
    // Forward to the new function with clearer naming
    return nostr_schnorr_sign(private_key, hash, signature);
}

// =============================================================================
// BIP39 MNEMONIC IMPLEMENTATION
// =============================================================================

// BIP39 English wordlist (complete 2048 words)
static const char* BIP39_WORDLIST[2048] = {
    "abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract",
    "absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid",
    "acoustic", "acquire", "across", "act", "action", "actor", "actress", "actual",
    "adapt", "add", "addict", "address", "adjust", "admit", "adult", "advance",
    "advice", "aerobic", "affair", "afford", "afraid", "again", "age", "agent",
    "agree", "ahead", "aim", "air", "airport", "aisle", "alarm", "album",
    "alcohol", "alert", "alien", "all", "alley", "allow", "almost", "alone",
    "alpha", "already", "also", "alter", "always", "amateur", "amazing", "among",
    "amount", "amused", "analyst", "anchor", "ancient", "anger", "angle", "angry",
    "animal", "ankle", "announce", "annual", "another", "answer", "antenna", "antique",
    "anxiety", "any", "apart", "apology", "appear", "apple", "approve", "april",
    "arch", "arctic", "area", "arena", "argue", "arm", "armed", "armor",
    "army", "around", "arrange", "arrest", "arrive", "arrow", "art", "artefact",
    "artist", "artwork", "ask", "aspect", "assault", "asset", "assist", "assume",
    "asthma", "athlete", "atom", "attack", "attend", "attitude", "attract", "auction",
    "audit", "august", "aunt", "author", "auto", "autumn", "average", "avocado",
    "avoid", "awake", "aware", "away", "awesome", "awful", "awkward", "axis",
    "baby", "bachelor", "bacon", "badge", "bag", "balance", "balcony", "ball",
    "bamboo", "banana", "banner", "bar", "barely", "bargain", "barrel", "base",
    "basic", "basket", "battle", "beach", "bean", "beauty", "because", "become",
    "beef", "before", "begin", "behave", "behind", "believe", "below", "belt",
    "bench", "benefit", "best", "betray", "better", "between", "beyond", "bicycle",
    "bid", "bike", "bind", "biology", "bird", "birth", "bitter", "black",
    "blade", "blame", "blanket", "blast", "bleak", "bless", "blind", "blood",
    "blossom", "blouse", "blue", "blur", "blush", "board", "boat", "body",
    "boil", "bomb", "bone", "bonus", "book", "boost", "border", "boring",
    "borrow", "boss", "bottom", "bounce", "box", "boy", "bracket", "brain",
    "brand", "brass", "brave", "bread", "breeze", "brick", "bridge", "brief",
    "bright", "bring", "brisk", "broccoli", "broken", "bronze", "broom", "brother",
    "brown", "brush", "bubble", "buddy", "budget", "buffalo", "build", "bulb",
    "bulk", "bullet", "bundle", "bunker", "burden", "burger", "burst", "bus",
    "business", "busy", "butter", "buyer", "buzz", "cabbage", "cabin", "cable",
    "cactus", "cage", "cake", "call", "calm", "camera", "camp", "can",
    "canal", "cancel", "candy", "cannon", "canoe", "canvas", "canyon", "capable",
    "capital", "captain", "car", "carbon", "card", "cargo", "carpet", "carry",
    "cart", "case", "cash", "casino", "castle", "casual", "cat", "catalog",
    "catch", "category", "cattle", "caught", "cause", "caution", "cave", "ceiling",
    "celery", "cement", "census", "century", "cereal", "certain", "chair", "chalk",
    "champion", "change", "chaos", "chapter", "charge", "chase", "chat", "cheap",
    "check", "cheese", "chef", "cherry", "chest", "chicken", "chief", "child",
    "chimney", "choice", "choose", "chronic", "chuckle", "chunk", "churn", "cigar",
    "cinnamon", "circle", "citizen", "city", "civil", "claim", "clap", "clarify",
    "claw", "clay", "clean", "clerk", "clever", "click", "client", "cliff",
    "climb", "clinic", "clip", "clock", "clog", "close", "cloth", "cloud",
    "clown", "club", "clump", "cluster", "clutch", "coach", "coast", "coconut",
    "code", "coffee", "coil", "coin", "collect", "color", "column", "combine",
    "come", "comfort", "comic", "common", "company", "concert", "conduct", "confirm",
    "congress", "connect", "consider", "control", "convince", "cook", "cool", "copper",
    "copy", "coral", "core", "corn", "correct", "cost", "cotton", "couch",
    "country", "couple", "course", "cousin", "cover", "coyote", "crack", "cradle",
    "craft", "cram", "crane", "crash", "crater", "crawl", "crazy", "cream",
    "credit", "creek", "crew", "cricket", "crime", "crisp", "critic", "crop",
    "cross", "crouch", "crowd", "crucial", "cruel", "cruise", "crumble", "crunch",
    "crush", "cry", "crystal", "cube", "culture", "cup", "cupboard", "curious",
    "current", "curtain", "curve", "cushion", "custom", "cute", "cycle", "dad",
    "damage", "damp", "dance", "danger", "daring", "dash", "daughter", "dawn",
    "day", "deal", "debate", "debris", "decade", "december", "decide", "decline",
    "decorate", "decrease", "deer", "defense", "define", "defy", "degree", "delay",
    "deliver", "demand", "demise", "denial", "dentist", "deny", "depart", "depend",
    "deposit", "depth", "deputy", "derive", "describe", "desert", "design", "desk",
    "despair", "destroy", "detail", "detect", "develop", "device", "devote", "diagram",
    "dial", "diamond", "diary", "dice", "diesel", "diet", "differ", "digital",
    "dignity", "dilemma", "dinner", "dinosaur", "direct", "dirt", "disagree", "discover",
    "disease", "dish", "dismiss", "disorder", "display", "distance", "divert", "divide",
    "divorce", "dizzy", "doctor", "document", "dog", "doll", "dolphin", "domain",
    "donate", "donkey", "donor", "door", "dose", "double", "dove", "draft",
    "dragon", "drama", "drastic", "draw", "dream", "dress", "drift", "drill",
    "drink", "drip", "drive", "drop", "drum", "dry", "duck", "dumb",
    "dune", "during", "dust", "dutch", "duty", "dwarf", "dynamic", "eager",
    "eagle", "early", "earn", "earth", "easily", "east", "easy", "echo",
    "ecology", "economy", "edge", "edit", "educate", "effort", "egg", "eight",
    "either", "elbow", "elder", "electric", "elegant", "element", "elephant", "elevator",
    "elite", "else", "embark", "embody", "embrace", "emerge", "emotion", "employ",
    "empower", "empty", "enable", "enact", "end", "endless", "endorse", "enemy",
    "energy", "enforce", "engage", "engine", "enhance", "enjoy", "enlist", "enough",
    "enrich", "enroll", "ensure", "enter", "entire", "entry", "envelope", "episode",
    "equal", "equip", "era", "erase", "erode", "erosion", "error", "erupt",
    "escape", "essay", "essence", "estate", "eternal", "ethics", "evidence", "evil",
    "evoke", "evolve", "exact", "example", "excess", "exchange", "excite", "exclude",
    "excuse", "execute", "exercise", "exhaust", "exhibit", "exile", "exist", "exit",
    "exotic", "expand", "expect", "expire", "explain", "expose", "express", "extend",
    "extra", "eye", "eyebrow", "fabric", "face", "faculty", "fade", "faint",
    "faith", "fall", "false", "fame", "family", "famous", "fan", "fancy",
    "fantasy", "farm", "fashion", "fat", "fatal", "father", "fatigue", "fault",
    "favorite", "feature", "february", "federal", "fee", "feed", "feel", "female",
    "fence", "festival", "fetch", "fever", "few", "fiber", "fiction", "field",
    "figure", "file", "film", "filter", "final", "find", "fine", "finger",
    "finish", "fire", "firm", "first", "fiscal", "fish", "fit", "fitness",
    "fix", "flag", "flame", "flash", "flat", "flavor", "flee", "flight",
    "flip", "float", "flock", "floor", "flower", "fluid", "flush", "fly",
    "foam", "focus", "fog", "foil", "fold", "follow", "food", "foot",
    "force", "forest", "forget", "fork", "fortune", "forum", "forward", "fossil",
    "foster", "found", "fox", "fragile", "frame", "frequent", "fresh", "friend",
    "fringe", "frog", "front", "frost", "frown", "frozen", "fruit", "fuel",
    "fun", "funny", "furnace", "fury", "future", "gadget", "gain", "galaxy",
    "gallery", "game", "gap", "garage", "garbage", "garden", "garlic", "garment",
    "gas", "gasp", "gate", "gather", "gauge", "gaze", "general", "genius",
    "genre", "gentle", "genuine", "gesture", "ghost", "giant", "gift", "giggle",
    "ginger", "giraffe", "girl", "give", "glad", "glance", "glare", "glass",
    "glide", "glimpse", "globe", "gloom", "glory", "glove", "glow", "glue",
    "goat", "goddess", "gold", "good", "goose", "gorilla", "gospel", "gossip",
    "govern", "gown", "grab", "grace", "grain", "grant", "grape", "grass",
    "gravity", "great", "green", "grid", "grief", "grit", "grocery", "group",
    "grow", "grunt", "guard", "guess", "guide", "guilt", "guitar", "gun",
    "gym", "habit", "hair", "half", "hammer", "hamster", "hand", "happy",
    "harbor", "hard", "harsh", "harvest", "hat", "have", "hawk", "hazard",
    "head", "health", "heart", "heavy", "hedgehog", "height", "hello", "helmet",
    "help", "hen", "hero", "hidden", "high", "hill", "hint", "hip",
    "hire", "history", "hobby", "hockey", "hold", "hole", "holiday", "hollow",
    "home", "honey", "hood", "hope", "horn", "horror", "horse", "hospital",
    "host", "hotel", "hour", "hover", "hub", "huge", "human", "humble",
    "humor", "hundred", "hungry", "hunt", "hurdle", "hurry", "hurt", "husband",
    "hybrid", "ice", "icon", "idea", "identify", "idle", "ignore", "ill",
    "illegal", "illness", "image", "imitate", "immense", "immune", "impact", "impose",
    "improve", "impulse", "inch", "include", "income", "increase", "index", "indicate",
    "indoor", "industry", "infant", "inflict", "inform", "inhale", "inherit", "initial",
    "inject", "injury", "inmate", "inner", "innocent", "input", "inquiry", "insane",
    "insect", "inside", "inspire", "install", "intact", "interest", "into", "invest",
    "invite", "involve", "iron", "island", "isolate", "issue", "item", "ivory",
    "jacket", "jaguar", "jar", "jazz", "jealous", "jeans", "jelly", "jewel",
    "job", "join", "joke", "journey", "joy", "judge", "juice", "jump",
    "jungle", "junior", "junk", "just", "kangaroo", "keen", "keep", "ketchup",
    "key", "kick", "kid", "kidney", "kind", "kingdom", "kiss", "kit",
    "kitchen", "kite", "kitten", "kiwi", "knee", "knife", "knock", "know",
    "lab", "label", "labor", "ladder", "lady", "lake", "lamp", "language",
    "laptop", "large", "later", "latin", "laugh", "laundry", "lava", "law",
    "lawn", "lawsuit", "layer", "lazy", "leader", "leaf", "learn", "leave",
    "lecture", "left", "leg", "legal", "legend", "leisure", "lemon", "lend",
    "length", "lens", "leopard", "lesson", "letter", "level", "liar", "liberty",
    "library", "license", "life", "lift", "light", "like", "limb", "limit",
    "link", "lion", "liquid", "list", "little", "live", "lizard", "load",
    "loan", "lobster", "local", "lock", "logic", "lonely", "long", "loop",
    "lottery", "loud", "lounge", "love", "loyal", "lucky", "luggage", "lumber",
    "lunar", "lunch", "luxury", "lyrics", "machine", "mad", "magic", "magnet",
    "maid", "mail", "main", "major", "make", "mammal", "man", "manage",
    "mandate", "mango", "mansion", "manual", "maple", "marble", "march", "margin",
    "marine", "market", "marriage", "mask", "mass", "master", "match", "material",
    "math", "matrix", "matter", "maximum", "maze", "meadow", "mean", "measure",
    "meat", "mechanic", "medal", "media", "melody", "melt", "member", "memory",
    "mention", "menu", "mercy", "merge", "merit", "merry", "mesh", "message",
    "metal", "method", "middle", "midnight", "milk", "million", "mimic", "mind",
    "minimum", "minor", "minute", "miracle", "mirror", "misery", "miss", "mistake",
    "mix", "mixed", "mixture", "mobile", "model", "modify", "mom", "moment",
    "monitor", "monkey", "monster", "month", "moon", "moral", "more", "morning",
    "mosquito", "mother", "motion", "motor", "mountain", "mouse", "move", "movie",
    "much", "muffin", "mule", "multiply", "muscle", "museum", "mushroom", "music",
    "must", "mutual", "myself", "mystery", "myth", "naive", "name", "napkin",
    "narrow", "nasty", "nation", "nature", "near", "neck", "need", "negative",
    "neglect", "neither", "nephew", "nerve", "nest", "net", "network", "neutral",
    "never", "news", "next", "nice", "night", "noble", "noise", "nominee",
    "noodle", "normal", "north", "nose", "notable", "note", "nothing", "notice",
    "novel", "now", "nuclear", "number", "nurse", "nut", "oak", "obey",
    "object", "oblige", "obscure", "observe", "obtain", "obvious", "occur", "ocean",
    "october", "odor", "off", "offer", "office", "often", "oil", "okay",
    "old", "olive", "olympic", "omit", "once", "one", "onion", "online",
    "only", "open", "opera", "opinion", "oppose", "option", "orange", "orbit",
    "orchard", "order", "ordinary", "organ", "orient", "original", "orphan", "ostrich",
    "other", "outdoor", "outer", "output", "outside", "oval", "oven", "over",
    "own", "owner", "oxygen", "oyster", "ozone", "pact", "paddle", "page",
    "pair", "palace", "palm", "panda", "panel", "panic", "panther", "paper",
    "parade", "parent", "park", "parrot", "party", "pass", "patch", "path",
    "patient", "patrol", "pattern", "pause", "pave", "payment", "peace", "peanut",
    "pear", "peasant", "pelican", "pen", "penalty", "pencil", "people", "pepper",
    "perfect", "permit", "person", "pet", "phone", "photo", "phrase", "physical",
    "piano", "picnic", "picture", "piece", "pig", "pigeon", "pill", "pilot",
    "pink", "pioneer", "pipe", "pistol", "pitch", "pizza", "place", "planet",
    "plastic", "plate", "play", "please", "pledge", "pluck", "plug", "plunge",
    "poem", "poet", "point", "polar", "pole", "police", "pond", "pony",
    "pool", "popular", "portion", "position", "possible", "post", "potato", "pottery",
    "poverty", "powder", "power", "practice", "praise", "predict", "prefer", "prepare",
    "present", "pretty", "prevent", "price", "pride", "primary", "print", "priority",
    "prison", "private", "prize", "problem", "process", "produce", "profit", "program",
    "project", "promote", "proof", "property", "prosper", "protect", "proud", "provide",
    "public", "pudding", "pull", "pulp", "pulse", "pumpkin", "punch", "pupil",
    "puppy", "purchase", "purity", "purpose", "purse", "push", "put", "puzzle",
    "pyramid", "quality", "quantum", "quarter", "question", "quick", "quit", "quiz",
    "quote", "rabbit", "raccoon", "race", "rack", "radar", "radio", "rail",
    "rain", "raise", "rally", "ramp", "ranch", "random", "range", "rapid",
    "rare", "rate", "rather", "raven", "raw", "razor", "ready", "real",
    "reason", "rebel", "rebuild", "recall", "receive", "recipe", "record", "recycle",
    "reduce", "reflect", "reform", "refuse", "region", "regret", "regular", "reject",
    "relax", "release", "relief", "rely", "remain", "remember", "remind", "remove",
    "render", "renew", "rent", "reopen", "repair", "repeat", "replace", "report",
    "require", "rescue", "resemble", "resist", "resource", "response", "result", "retire",
    "retreat", "return", "reunion", "reveal", "review", "reward", "rhythm", "rib",
    "ribbon", "rice", "rich", "ride", "ridge", "rifle", "right", "rigid",
    "ring", "riot", "ripple", "risk", "ritual", "rival", "river", "road",
    "roast", "robot", "robust", "rocket", "romance", "roof", "rookie", "room",
    "rose", "rotate", "rough", "round", "route", "royal", "rubber", "rude",
    "rug", "rule", "run", "runway", "rural", "sad", "saddle", "sadness",
    "safe", "sail", "salad", "salmon", "salon", "salt", "salute", "same",
    "sample", "sand", "satisfy", "satoshi", "sauce", "sausage", "save", "say",
    "scale", "scan", "scare", "scatter", "scene", "scheme", "school", "science",
    "scissors", "scorpion", "scout", "scrap", "screen", "script", "scrub", "sea",
    "search", "season", "seat", "second", "secret", "section", "security", "seed",
    "seek", "segment", "select", "sell", "seminar", "senior", "sense", "sentence",
    "series", "service", "session", "settle", "setup", "seven", "shadow", "shaft",
    "shallow", "share", "shed", "shell", "sheriff", "shield", "shift", "shine",
    "ship", "shiver", "shock", "shoe", "shoot", "shop", "short", "shoulder",
    "shove", "shrimp", "shrug", "shuffle", "shy", "sibling", "sick", "side",
    "siege", "sight", "sign", "silent", "silk", "silly", "silver", "similar",
    "simple", "since", "sing", "siren", "sister", "situate", "six", "size",
    "skate", "sketch", "ski", "skill", "skin", "skirt", "skull", "slab",
    "slam", "sleep", "slender", "slice", "slide", "slight", "slim", "slogan",
    "slot", "slow", "slush", "small", "smart", "smile", "smoke", "smooth",
    "snack", "snake", "snap", "sniff", "snow", "soap", "soccer", "social",
    "sock", "soda", "soft", "solar", "soldier", "solid", "solution", "solve",
    "someone", "song", "soon", "sorry", "sort", "soul", "sound", "soup",
    "source", "south", "space", "spare", "spatial", "spawn", "speak", "special",
    "speed", "spell", "spend", "sphere", "spice", "spider", "spike", "spin",
    "spirit", "split", "spoil", "sponsor", "spoon", "sport", "spot", "spray",
    "spread", "spring", "spy", "square", "squeeze", "squirrel", "stable", "stadium",
    "staff", "stage", "stairs", "stamp", "stand", "start", "state", "stay",
    "steak", "steel", "stem", "step", "stereo", "stick", "still", "sting",
    "stock", "stomach", "stone", "stool", "story", "stove", "strategy", "street",
    "strike", "strong", "struggle", "student", "stuff", "stumble", "style", "subject",
    "submit", "subway", "success", "such", "sudden", "suffer", "sugar", "suggest",
    "suit", "summer", "sun", "sunny", "sunset", "super", "supply", "supreme",
    "sure", "surface", "surge", "surprise", "surround", "survey", "suspect", "sustain",
    "swallow", "swamp", "swap", "swarm", "swear", "sweet", "swift", "swim",
    "swing", "switch", "sword", "symbol", "symptom", "syrup", "system", "table",
    "tackle", "tag", "tail", "talent", "talk", "tank", "tape", "target",
    "task", "taste", "tattoo", "taxi", "teach", "team", "tell", "ten",
    "tenant", "tennis", "tent", "term", "test", "text", "thank", "that",
    "theme", "then", "theory", "there", "they", "thing", "this", "thought",
    "three", "thrive", "throw", "thumb", "thunder", "ticket", "tide", "tiger",
    "tilt", "timber", "time", "tiny", "tip", "tired", "tissue", "title",
    "toast", "tobacco", "today", "toddler", "toe", "together", "toilet", "token",
    "tomato", "tomorrow", "tone", "tongue", "tonight", "tool", "tooth", "top",
    "topic", "topple", "torch", "tornado", "tortoise", "toss", "total", "tourist",
    "toward", "tower", "town", "toy", "track", "trade", "traffic", "tragic",
    "train", "transfer", "trap", "trash", "travel", "tray", "treat", "tree",
    "trend", "trial", "tribe", "trick", "trigger", "trim", "trip", "trophy",
    "trouble", "truck", "true", "truly", "trumpet", "trust", "truth", "try",
    "tube", "tuition", "tumble", "tuna", "tunnel", "turkey", "turn", "turtle",
    "twelve", "twenty", "twice", "twin", "twist", "two", "type", "typical",
    "ugly", "umbrella", "unable", "unaware", "uncle", "uncover", "under", "undo",
    "unfair", "unfold", "unhappy", "uniform", "unique", "unit", "universe", "unknown",
    "unlock", "until", "unusual", "unveil", "update", "upgrade", "uphold", "upon",
    "upper", "upset", "urban", "urge", "usage", "use", "used", "useful",
    "useless", "usual", "utility", "vacant", "vacuum", "vague", "valid", "valley",
    "valve", "van", "vanish", "vapor", "various", "vast", "vault", "vehicle",
    "velvet", "vendor", "venture", "venue", "verb", "verify", "version", "very",
    "vessel", "veteran", "viable", "vibrant", "vicious", "victory", "video", "view",
    "village", "vintage", "violin", "virtual", "virus", "visa", "visit", "visual",
    "vital", "vivid", "vocal", "voice", "void", "volcano", "volume", "vote",
    "voyage", "wage", "wagon", "wait", "walk", "wall", "walnut", "want",
    "warfare", "warm", "warrior", "wash", "wasp", "waste", "water", "wave",
    "way", "wealth", "weapon", "wear", "weasel", "weather", "web", "wedding",
    "weekend", "weird", "welcome", "west", "wet", "whale", "what", "wheat",
    "wheel", "when", "where", "whip", "whisper", "wide", "width", "wife",
    "wild", "will", "win", "window", "wine", "wing", "wink", "winner",
    "winter", "wire", "wisdom", "wise", "wish", "witness", "wolf", "woman",
    "wonder", "wood", "wool", "word", "work", "world", "worry", "worth",
    "wrap", "wreck", "wrestle", "wrist", "write", "wrong", "yard", "year",
    "yellow", "you", "young", "youth", "zebra", "zero", "zone", "zoo"
};

static int find_word_index(const char* word) {
    for (int i = 0; i < 2048; i++) {
        if (strcmp(word, BIP39_WORDLIST[i]) == 0) {
            return i;
        }
    }
    return -1;
}

int nostr_bip39_mnemonic_from_bytes(const unsigned char* entropy, size_t entropy_len,
                                   char* mnemonic) {
    if (!entropy || !mnemonic || entropy_len < 16 || entropy_len > 32) return -1;
    
    // Calculate checksum
    unsigned char hash[32];
    nostr_sha256(entropy, entropy_len, hash);
    
    // Combine entropy + checksum bits
    int total_bits = (int)entropy_len * 8 + (int)entropy_len / 4;
    int word_count = total_bits / 11;
    
    // Extract 11-bit groups for words
    mnemonic[0] = '\0';
    
    for (int i = 0; i < word_count; i++) {
        int bit_start = i * 11;
        int byte_start = bit_start / 8;
        int bit_offset = bit_start % 8;
        
        uint16_t word_index = 0;
        
        // Extract 11 bits across byte boundaries
        if (byte_start < (int)entropy_len) {
            word_index |= (entropy[byte_start] << (8 - bit_offset)) & 0x7FF;
        }
        if (byte_start + 1 < (int)entropy_len) {
            word_index |= (entropy[byte_start + 1] >> bit_offset) & ((1 << (11 - (8 - bit_offset))) - 1);
        } else if (bit_start + 11 > (int)entropy_len * 8) {
            // Use checksum bits
            int checksum_bits_needed = bit_start + 11 - (int)entropy_len * 8;
            word_index |= (hash[0] >> (8 - checksum_bits_needed)) & ((1 << checksum_bits_needed) - 1);
        }
        
        word_index &= 0x7FF; // 11 bits - now supports full 2048 word range
        
        if (i > 0) strcat(mnemonic, " ");
        strcat(mnemonic, BIP39_WORDLIST[word_index]);
    }
    
    return 0;
}

int nostr_bip39_mnemonic_validate(const char* mnemonic) {
    if (!mnemonic) return -1;
    
    // Count words
    char temp[1024];
    strncpy(temp, mnemonic, sizeof(temp) - 1);
    temp[sizeof(temp) - 1] = '\0';
    
    int word_count = 0;
    char* token = strtok(temp, " ");
    while (token != NULL) {
        if (find_word_index(token) == -1) return -1; // Invalid word
        word_count++;
        token = strtok(NULL, " ");
    }
    
    // Valid word counts for BIP39: 12, 15, 18, 21, 24
    if (word_count != 12 && word_count != 15 && word_count != 18 && 
        word_count != 21 && word_count != 24) {
        return -1;
    }
    
    return 0;
}

int nostr_bip39_mnemonic_to_seed(const char* mnemonic, const char* passphrase,
                                unsigned char* seed, size_t seed_len) {
    if (!mnemonic || !seed || seed_len != 64) return -1;
    
    // Handle NULL passphrase (libwally-core compatibility)
    if (!passphrase) passphrase = "";
    
    // Create salt: "mnemonic" + passphrase (exactly as libwally-core does)
    const char* prefix = "mnemonic";
    const size_t prefix_len = strlen(prefix);
    const size_t passphrase_len = strlen(passphrase);
    const size_t salt_len = prefix_len + passphrase_len;
    
    unsigned char* salt = malloc(salt_len);
    if (!salt) return -1;
    
    memcpy(salt, prefix, prefix_len);
    if (passphrase_len) {
        memcpy(salt + prefix_len, passphrase, passphrase_len);
    }
    
    // Use PBKDF2 with 2048 iterations (flags=0 for libwally-core compatibility)
    int result = nostr_pbkdf2_hmac_sha512((const unsigned char*)mnemonic, strlen(mnemonic),
                                         salt, salt_len, 2048, seed, seed_len);
    
    
    // Clear and free salt (libwally-core style)
    wally_clear(salt, salt_len);
    free(salt);
    
    return result;
}

// =============================================================================
// BIP32 HD WALLET IMPLEMENTATION
// =============================================================================

#define BIP32_HARDENED_KEY_LIMIT 0x80000000

int nostr_bip32_key_from_seed(const unsigned char* seed, size_t seed_len,
                             nostr_hd_key_t* master_key) {
    if (!seed || !master_key || seed_len < 16 || seed_len > 64) return -1;
    
    // HMAC-SHA512("Bitcoin seed", seed) - exactly as libwally-core does
    const char* key = "Bitcoin seed";
    unsigned char hmac[64];
    
    if (nostr_hmac_sha512((const unsigned char*)key, strlen(key), seed, seed_len, hmac) != 0) {
        return -1;
    }
    
    // Split result: first 32 bytes = private key, last 32 bytes = chain code
    memcpy(master_key->private_key, hmac, 32);
    memcpy(master_key->chain_code, hmac + 32, 32);
    
    // Verify private key using secp256k1
    if (nostr_secp256k1_ec_seckey_verify(master_key->private_key) != 1) {
        return -1;
    }
    
    // Generate corresponding public key
    if (nostr_ec_public_key_from_private_key(master_key->private_key, master_key->public_key + 1) != 0) {
        return -1;
    }
    
    // Add compression prefix (0x02 for even y, 0x03 for odd y - simplified to 0x02)
    master_key->public_key[0] = 0x02;
    
    master_key->depth = 0;
    master_key->parent_fingerprint = 0;
    master_key->child_number = 0;
    
    
    return 0;
}


int nostr_bip32_derive_child(const nostr_hd_key_t* parent_key, uint32_t child_number,
                            nostr_hd_key_t* child_key) {
    if (!parent_key || !child_key) return -1;
    
    // Clear child key structure
    memset(child_key, 0, sizeof(nostr_hd_key_t));
    
    // Check maximum depth
    if (parent_key->depth == 255) return -1;
    
    // Prepare data for HMAC (libwally-core approach)
    unsigned char data[37];
    size_t data_len;
    
    if (child_number >= BIP32_HARDENED_KEY_LIMIT) {
        // Hardened derivation: 0x00 || ser256(kpar) || ser32(i)
        data[0] = 0x00;
        memcpy(data + 1, parent_key->private_key, 32);
        data_len = 33;
    } else {
        // Non-hardened derivation: serP(point(kpar)) || ser32(i)
        memcpy(data, parent_key->public_key, 33);
        data_len = 33;
    }
    
    // Add child number as big-endian 32-bit (ser32(i))
    data[data_len] = (child_number >> 24) & 0xFF;
    data[data_len + 1] = (child_number >> 16) & 0xFF;
    data[data_len + 2] = (child_number >> 8) & 0xFF;
    data[data_len + 3] = child_number & 0xFF;
    data_len += 4;
    
    // I = HMAC-SHA512(Key = cpar, Data)
    unsigned char hmac[64];
    if (nostr_hmac_sha512(parent_key->chain_code, 32, data, data_len, hmac) != 0) {
        return -1;
    }
    
    // Split I into IL and IR (32 bytes each)
    // IR becomes the new chain code
    memcpy(child_key->chain_code, hmac + 32, 32);
    
    // The returned child key ki is parse256(IL) + kpar (mod n)
    // Copy parent private key first
    memcpy(child_key->private_key, parent_key->private_key, 32);
    
    // Use secp256k1's tweak_add function (libwally-core approach)
    if (nostr_secp256k1_ec_seckey_tweak_add(child_key->private_key, hmac) != 1) {
        // Invalid key: parse256(IL) ≥ n or ki = 0
        return -1;
    }
    
    // Verify the derived private key
    if (nostr_secp256k1_ec_seckey_verify(child_key->private_key) != 1) {
        return -1;
    }
    
    // Generate corresponding public key in compressed format
    nostr_secp256k1_pubkey pubkey;
    if (nostr_secp256k1_ec_pubkey_create(&pubkey, child_key->private_key) != 1) {
        return -1;
    }
    
    // Serialize to compressed format (33 bytes)
    if (nostr_secp256k1_ec_pubkey_serialize_compressed(child_key->public_key, &pubkey) != 1) {
        return -1;
    }
    
    // Set metadata
    child_key->depth = parent_key->depth + 1;
    child_key->child_number = child_number;
    
    // Calculate parent fingerprint (first 4 bytes of parent pubkey hash)
    unsigned char parent_hash[32];
    nostr_sha256(parent_key->public_key, 33, parent_hash);
    child_key->parent_fingerprint = (parent_hash[0] << 24) | (parent_hash[1] << 16) |
                                   (parent_hash[2] << 8) | parent_hash[3];
    
    
    return 0;
}

int nostr_bip32_derive_path(const nostr_hd_key_t* master_key, const uint32_t* path,
                           size_t path_len, nostr_hd_key_t* derived_key) {
    if (!master_key || !path || !derived_key || path_len == 0) return -1;
    
    // Start with master key
    *derived_key = *master_key;
    
    // Derive through each level
    for (size_t i = 0; i < path_len; i++) {
        nostr_hd_key_t temp_key = *derived_key;
        if (nostr_bip32_derive_child(&temp_key, path[i], derived_key) != 0) {
            return -1;
        }
    }
    
    return 0;
}
