Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
df50ca1273 | ||
|
|
2ce2ecbbfb | ||
|
|
57ecbf0c11 | ||
|
|
e87d7364ff | ||
|
|
0b2cca6549 | ||
|
|
fca1a8077d | ||
|
|
2c128a6295 | ||
|
|
24903b8c90 | ||
|
|
c6896eebb4 |
@@ -0,0 +1,7 @@
|
||||
---
|
||||
description: "Increments and pushes the repo"
|
||||
---
|
||||
|
||||
Run increment_and_push.sh followed in the command line with a good description of the changes that were made.
|
||||
|
||||
For example: ./increment_and_push.sh "Fixed that nasty bug"
|
||||
+33
-11
@@ -6,17 +6,18 @@ This document describes the public API for the Nostr Relay Pool implementation i
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| [`nostr_relay_pool_create()`](nostr_core/core_relay_pool.c:219) | Create and initialize a new relay pool |
|
||||
| [`nostr_relay_pool_destroy()`](nostr_core/core_relay_pool.c:304) | Destroy pool and cleanup all resources |
|
||||
| [`nostr_relay_pool_add_relay()`](nostr_core/core_relay_pool.c:229) | Add a relay URL to the pool |
|
||||
| [`nostr_relay_pool_remove_relay()`](nostr_core/core_relay_pool.c:273) | Remove a relay URL from the pool |
|
||||
| [`nostr_relay_pool_subscribe()`](nostr_core/core_relay_pool.c:399) | Create async subscription with callbacks |
|
||||
| [`nostr_relay_pool_create()`](nostr_core/core_relay_pool.c:594) | Create and initialize a new relay pool |
|
||||
| [`nostr_relay_pool_destroy()`](nostr_core/core_relay_pool.c:733) | Destroy pool and cleanup all resources |
|
||||
| [`nostr_relay_pool_add_relay()`](nostr_core/core_relay_pool.c:648) | Add a relay URL to the pool |
|
||||
| [`nostr_relay_pool_remove_relay()`](nostr_core/core_relay_pool.c:702) | Remove a relay URL from the pool |
|
||||
| [`nostr_relay_pool_set_auth()`](nostr_core/core_relay_pool.c:616) | Configure pool-wide NIP-42 authentication key and enable flag |
|
||||
| [`nostr_relay_pool_subscribe()`](nostr_core/core_relay_pool.c:778) | Create async subscription with callbacks |
|
||||
| [`nostr_pool_subscription_close()`](nostr_core/core_relay_pool.c:491) | Close subscription and free resources |
|
||||
| [`nostr_relay_pool_run()`](nostr_core/core_relay_pool.c:1192) | Run event loop for specified timeout |
|
||||
| [`nostr_relay_pool_poll()`](nostr_core/core_relay_pool.c:1232) | Single iteration poll and dispatch |
|
||||
| [`nostr_relay_pool_query_sync()`](nostr_core/core_relay_pool.c:695) | Synchronous query returning event array |
|
||||
| [`nostr_relay_pool_get_event()`](nostr_core/core_relay_pool.c:825) | Get single most recent event |
|
||||
| [`nostr_relay_pool_publish()`](nostr_core/core_relay_pool.c:866) | Publish event and wait for OK responses |
|
||||
| [`nostr_relay_pool_publish_async()`](nostr_core/core_relay_pool.c:866) | Publish event with async callbacks |
|
||||
| [`nostr_relay_pool_get_relay_status()`](nostr_core/core_relay_pool.c:944) | Get connection status for a relay |
|
||||
| [`nostr_relay_pool_list_relays()`](nostr_core/core_relay_pool.c:960) | List all relays and their statuses |
|
||||
| [`nostr_relay_pool_get_relay_stats()`](nostr_core/core_relay_pool.c:992) | Get detailed statistics for a relay |
|
||||
@@ -71,6 +72,26 @@ void cleanup_pool(nostr_relay_pool_t* pool) {
|
||||
|
||||
## Relay Management
|
||||
|
||||
### Configure Pool Authentication (NIP-42)
|
||||
**Function:** [`nostr_relay_pool_set_auth()`](nostr_core/core_relay_pool.c:616)
|
||||
```c
|
||||
int nostr_relay_pool_set_auth(nostr_relay_pool_t* pool, const unsigned char* private_key, int enable);
|
||||
```
|
||||
|
||||
**Description:**
|
||||
- Sets a pool-wide private key used to sign NIP-42 `AUTH` responses.
|
||||
- Enables/disables NIP-42 handling for all relays in the pool.
|
||||
- Propagates auth-enabled state to existing relay connections.
|
||||
|
||||
**Example:**
|
||||
```c
|
||||
unsigned char privkey[32];
|
||||
nostr_hex_to_bytes("91ba716fa9e7ea2fcbad360cf4f8e0d312f73984da63d90f524ad61a6a1e7dbe", privkey, 32);
|
||||
|
||||
nostr_relay_pool_t* pool = nostr_relay_pool_create(nostr_pool_reconnect_config_default());
|
||||
nostr_relay_pool_set_auth(pool, privkey, 1); // enable NIP-42 auto AUTH handling
|
||||
```
|
||||
|
||||
### Add Relay
|
||||
**Function:** [`nostr_relay_pool_add_relay()`](nostr_core/core_relay_pool.c:229)
|
||||
```c
|
||||
@@ -438,9 +459,9 @@ int get_latest_note_from_pubkey(nostr_relay_pool_t* pool, const char* pubkey_hex
|
||||
```
|
||||
|
||||
### Publish Event
|
||||
**Function:** [`nostr_relay_pool_publish()`](nostr_core/core_relay_pool.c:866)
|
||||
**Function:** [`nostr_relay_pool_publish_async()`](nostr_core/core_relay_pool.c:866)
|
||||
```c
|
||||
int nostr_relay_pool_publish(
|
||||
int nostr_relay_pool_publish_async(
|
||||
nostr_relay_pool_t* pool,
|
||||
const char** relay_urls,
|
||||
int relay_count,
|
||||
@@ -471,8 +492,8 @@ int publish_text_note(nostr_relay_pool_t* pool, const char* content) {
|
||||
|
||||
printf("Publishing note: %s\n", content);
|
||||
|
||||
int success_count = nostr_relay_pool_publish(
|
||||
pool, relay_urls, 3, event);
|
||||
int success_count = nostr_relay_pool_publish_async(
|
||||
pool, relay_urls, 3, event, my_callback, user_data);
|
||||
|
||||
cJSON_Delete(event);
|
||||
|
||||
@@ -751,5 +772,6 @@ int main() {
|
||||
- **Memory ownership**: The pool duplicates filters and URLs internally. Caller owns returned events and must free them.
|
||||
- **Event deduplication** is applied pool-wide using a circular buffer of 1000 event IDs.
|
||||
- **Ping functionality** is currently disabled in this build.
|
||||
- **NIP-42 behavior**: With [`nostr_relay_pool_set_auth()`](nostr_core/core_relay_pool.c:616) enabled, the pool will respond to relay `AUTH` challenges automatically using [`nostr_nip42_create_auth_event()`](nostr_core/nip042.c:26) and [`nostr_nip42_create_auth_message()`](nostr_core/nip042.c:84).
|
||||
- **Reconnection** happens on-demand when sending, but active subscriptions are not automatically re-sent after reconnect.
|
||||
- **Polling model**: You must drive the event loop via [`nostr_relay_pool_run()`](nostr_core/core_relay_pool.c:1192) or [`nostr_relay_pool_poll()`](nostr_core/core_relay_pool.c:1232) to receive events.
|
||||
- **Polling model**: You must drive the event loop via [`nostr_relay_pool_run()`](nostr_core/core_relay_pool.c:1745) or [`nostr_relay_pool_poll()`](nostr_core/core_relay_pool.c:1785) to receive events.
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
A C library for NOSTR protocol implementation. Work in progress.
|
||||
|
||||
[](VERSION)
|
||||
[](VERSION)
|
||||
[](#license)
|
||||
[](#building)
|
||||
|
||||
@@ -53,7 +53,7 @@ A C library for NOSTR protocol implementation. Work in progress.
|
||||
- [x] [NIP-42](nips/42.md) - Authentication of clients to relays
|
||||
- [x] [NIP-44](nips/44.md) - Versioned Encryption
|
||||
- [ ] [NIP-45](nips/45.md) - Counting results
|
||||
- [ ] [NIP-46](nips/46.md) - Nostr Connect
|
||||
- [x] [NIP-46](nips/46.md) - Nostr Remote Signing
|
||||
- [ ] [NIP-47](nips/47.md) - Wallet Connect
|
||||
- [ ] [NIP-48](nips/48.md) - Proxy Tags
|
||||
- [ ] [NIP-49](nips/49.md) - Private Key Encryption
|
||||
@@ -96,7 +96,7 @@ A C library for NOSTR protocol implementation. Work in progress.
|
||||
|
||||
**Legend:** ✅ Fully Implemented | ⚠️ Partial Implementation | ❌ Not Implemented
|
||||
|
||||
**Implementation Summary:** 12 of 96+ NIPs fully implemented (12.5%)
|
||||
**Implementation Summary:** 13 of 96+ NIPs fully implemented (13.5%)
|
||||
|
||||
|
||||
## 📦 Quick Start
|
||||
@@ -111,12 +111,12 @@ A C library for NOSTR protocol implementation. Work in progress.
|
||||
|
||||
2. **Build the library:**
|
||||
```bash
|
||||
./build.sh lib
|
||||
./build.sh
|
||||
```
|
||||
|
||||
3. **Run examples:**
|
||||
3. **Build and run examples:**
|
||||
```bash
|
||||
./build.sh examples
|
||||
./build.sh -e
|
||||
./examples/simple_keygen
|
||||
```
|
||||
|
||||
@@ -161,7 +161,7 @@ int main() {
|
||||
|
||||
**Compile and run:**
|
||||
```bash
|
||||
gcc example.c -o example ./libnostr_core.a -lm
|
||||
gcc example.c -o example ./libnostr_core_x64.a -lz -ldl -lpthread -lm -lssl -lcrypto -lcurl -lsecp256k1
|
||||
./example
|
||||
```
|
||||
|
||||
@@ -170,27 +170,13 @@ gcc example.c -o example ./libnostr_core.a -lm
|
||||
### Build Targets
|
||||
|
||||
```bash
|
||||
./build.sh lib # Build static library (default)
|
||||
./build.sh examples # Build examples
|
||||
./build.sh test # Run test suite
|
||||
./build.sh clean # Clean build artifacts
|
||||
./build.sh install # Install to system
|
||||
```
|
||||
|
||||
### Manual Building
|
||||
|
||||
```bash
|
||||
# Build static library
|
||||
make
|
||||
|
||||
# Build examples
|
||||
make examples
|
||||
|
||||
# Run tests
|
||||
make test-crypto
|
||||
|
||||
# Clean
|
||||
make clean
|
||||
./build.sh # Build static library (default)
|
||||
./build.sh --nips=all # Force build with all available NIPs
|
||||
./build.sh -t # Build all test executables in tests/
|
||||
./build.sh -e # Build all examples in examples/
|
||||
./build.sh -t -e # Build library + tests + examples
|
||||
./build.sh --nips=46 # Build specifically with NIP-046 support
|
||||
./build.sh --help # Show all options
|
||||
```
|
||||
|
||||
### Dependencies
|
||||
@@ -306,6 +292,7 @@ publish_result_t* synchronous_publish_event_with_progress(const char** relay_url
|
||||
nostr_pool_reconnect_config_t* config = nostr_pool_reconnect_config_default();
|
||||
nostr_relay_pool_t* nostr_relay_pool_create(nostr_pool_reconnect_config_t* config);
|
||||
int nostr_relay_pool_add_relay(nostr_relay_pool_t* pool, const char* relay_url);
|
||||
int nostr_relay_pool_set_auth(nostr_relay_pool_t* pool, const unsigned char* private_key, int enable);
|
||||
void nostr_relay_pool_destroy(nostr_relay_pool_t* pool);
|
||||
|
||||
// Subscribe to events (with auto-reconnection)
|
||||
@@ -314,7 +301,12 @@ nostr_pool_subscription_t* nostr_relay_pool_subscribe(
|
||||
void (*on_event)(cJSON* event, const char* relay_url, void* user_data),
|
||||
void (*on_eose)(void* user_data), void* user_data, int close_on_eose);
|
||||
|
||||
// Run event loop (handles reconnection automatically)
|
||||
// Enable NIP-42 auth (auto-responds to relay AUTH challenges)
|
||||
unsigned char private_key[32];
|
||||
nostr_hex_to_bytes("91ba716fa9e7ea2fcbad360cf4f8e0d312f73984da63d90f524ad61a6a1e7dbe", private_key, 32);
|
||||
nostr_relay_pool_set_auth(pool, private_key, 1);
|
||||
|
||||
// Run event loop (handles reconnection + incoming AUTH/NOTICE/OK messages)
|
||||
int nostr_relay_pool_run(nostr_relay_pool_t* pool, int timeout_ms);
|
||||
int nostr_relay_pool_poll(nostr_relay_pool_t* pool, int timeout_ms);
|
||||
|
||||
@@ -364,11 +356,14 @@ The library includes comprehensive examples:
|
||||
- **`mnemonic_derivation`** - NIP-06 key derivation
|
||||
- **`utility_functions`** - General utility demonstrations
|
||||
- **`input_detection`** - Input type detection and processing
|
||||
- **`relay_pool`** - Interactive relay pool and subscription testing
|
||||
- **`send_nip17_dm`** - NIP-17 private direct message send flow
|
||||
- **`nip46_remote_signer`** - NIP-46 remote signer flow and bunker URL generation
|
||||
- **`version_test`** - Library version information
|
||||
|
||||
Run all examples:
|
||||
Build all examples:
|
||||
```bash
|
||||
./build.sh examples
|
||||
./build.sh -e
|
||||
ls -la examples/
|
||||
```
|
||||
|
||||
@@ -377,28 +372,19 @@ ls -la examples/
|
||||
The library includes extensive tests:
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
./build.sh test
|
||||
# Build all test executables
|
||||
./build.sh -t
|
||||
|
||||
# Individual test categories
|
||||
cd tests && make test
|
||||
# Run the new NIP-46 test
|
||||
./tests/nip46_test
|
||||
|
||||
# Interactive relay pool testing
|
||||
cd tests && ./pool_test
|
||||
# Run selected tests
|
||||
./tests/nip44_test
|
||||
./tests/nip42_test
|
||||
./tests/nip17_test
|
||||
```
|
||||
|
||||
**Test Categories:**
|
||||
- **Core Functionality**: `simple_init_test`, `header_test`
|
||||
- **Cryptography**: `chacha20_test`, `nostr_crypto_test`
|
||||
- **NIP-04 Encryption**: `nip04_test`
|
||||
- **NIP-05 Identifiers**: `nip05_test`
|
||||
- **NIP-11 Relay Info**: `nip11_test`
|
||||
- **NIP-44 Encryption**: `nip44_test`, `nip44_debug_test`
|
||||
- **Key Derivation**: `nostr_test_bip32`
|
||||
- **Relay Communication**: `relay_pool_test`, `sync_test`
|
||||
- **HTTP/WebSocket**: `http_test`, `wss_test`
|
||||
- **Proof of Work**: `test_pow_loop`
|
||||
- **Interactive Pool Testing**: `pool_test` (menu-driven interface with reconnection testing)
|
||||
**Current test binaries live in [`tests/`](tests/) and are generated from `*_test.c` sources.**
|
||||
|
||||
## 🏗️ Integration
|
||||
|
||||
@@ -408,7 +394,7 @@ cd tests && ./pool_test
|
||||
|
||||
2. **Copy required files to your project:**
|
||||
```bash
|
||||
cp libnostr_core.a /path/to/your/project/
|
||||
cp libnostr_core_x64.a /path/to/your/project/
|
||||
cp nostr_core/nostr_core.h /path/to/your/project/
|
||||
```
|
||||
|
||||
@@ -443,7 +429,7 @@ The `libnostr_core.a` library now uses **system dependencies** for all major cry
|
||||
|
||||
**Complete linking example:**
|
||||
```bash
|
||||
gcc your_app.c ./libnostr_core.a -lssl -lcrypto -lcurl -lsecp256k1 -lm -o your_app
|
||||
gcc your_app.c ./libnostr_core_x64.a -lz -ldl -lpthread -lm -lssl -lcrypto -lcurl -lsecp256k1 -o your_app
|
||||
```
|
||||
|
||||
**Check system dependencies:**
|
||||
@@ -490,24 +476,24 @@ make arm64
|
||||
|
||||
## 📄 Documentation
|
||||
|
||||
- **[LIBRARY_USAGE.md](LIBRARY_USAGE.md)** - Detailed integration guide
|
||||
- **[EXPORT_GUIDE.md](EXPORT_GUIDE.md)** - Library export instructions
|
||||
- **[AUTOMATIC_VERSIONING.md](AUTOMATIC_VERSIONING.md)** - Version management
|
||||
- **API Reference** - Complete documentation in `nostr_core/nostr_core.h`
|
||||
- **[POOL_API.md](POOL_API.md)** - Relay pool API notes
|
||||
- **[nostr_websocket/README.md](nostr_websocket/README.md)** - WebSocket module details
|
||||
- **[nostr_websocket/EXPORT_GUIDE.md](nostr_websocket/EXPORT_GUIDE.md)** - WebSocket export instructions
|
||||
- **API Reference** - Complete documentation in [`nostr_core/nostr_core.h`](nostr_core/nostr_core.h)
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
1. Fork the repository
|
||||
2. Create a feature branch: `git checkout -b feature/amazing-feature`
|
||||
3. Make your changes and add tests
|
||||
4. Run the test suite: `./build.sh test`
|
||||
4. Build tests and run key suites: `./build.sh -t && ./tests/nip46_test`
|
||||
5. Commit your changes: `git commit -m 'Add amazing feature'`
|
||||
6. Push to the branch: `git push origin feature/amazing-feature`
|
||||
7. Open a Pull Request
|
||||
|
||||
## 📈 Version History
|
||||
|
||||
Current version: **0.2.1**
|
||||
Current version: **0.4.8**
|
||||
|
||||
The library uses automatic semantic versioning based on Git tags. Each build increments the patch version automatically.
|
||||
|
||||
@@ -520,10 +506,11 @@ The library uses automatic semantic versioning based on Git tags. Each build inc
|
||||
- **Comprehensive Testing**: Extensive test suite and error handling
|
||||
|
||||
**Version Timeline:**
|
||||
- `v0.2.x` - Current development releases with enhanced NIP support
|
||||
- `v0.4.x` - Current development releases with relay pool and expanded NIP support
|
||||
- `v0.2.x` - Earlier OpenSSL-based development releases
|
||||
- `v0.1.x` - Initial development releases
|
||||
- Focus on core protocol implementation and OpenSSL-based crypto
|
||||
- Full NIP-01, NIP-04, NIP-05, NIP-06, NIP-11, NIP-13, NIP-17, NIP-19, NIP-42, NIP-44, NIP-59 support
|
||||
- Full NIP-01, NIP-04, NIP-05, NIP-06, NIP-11, NIP-13, NIP-17, NIP-19, NIP-21, NIP-42, NIP-44, NIP-46, NIP-59 support
|
||||
|
||||
## 🐛 Troubleshooting
|
||||
|
||||
@@ -531,21 +518,29 @@ The library uses automatic semantic versioning based on Git tags. Each build inc
|
||||
|
||||
**Build fails with secp256k1 errors:**
|
||||
```bash
|
||||
# Install secp256k1 with Schnorr support
|
||||
sudo apt install libsecp256k1-dev # Ubuntu/Debian
|
||||
# or
|
||||
sudo yum install libsecp256k1-devel # CentOS/RHEL
|
||||
# or
|
||||
brew install secp256k1 # macOS
|
||||
|
||||
# If still failing, build from source with Schnorr support:
|
||||
git clone https://github.com/bitcoin-core/secp256k1.git
|
||||
cd secp256k1
|
||||
./autogen.sh
|
||||
./configure --enable-module-schnorrsig --enable-module-ecdh
|
||||
make
|
||||
cd ..
|
||||
./build.sh lib
|
||||
sudo make install
|
||||
```
|
||||
|
||||
**Library too large:**
|
||||
The x64 library is intentionally large (~15MB) because it includes all secp256k1 cryptographic functions and OpenSSL for complete self-containment. The ARM64 library is smaller (~2.4MB) as it links against system OpenSSL.
|
||||
**Library size:**
|
||||
The library is small (~500KB) as it links against system libraries (secp256k1, OpenSSL, curl) rather than including them statically. This keeps the binary size manageable while maintaining full functionality.
|
||||
|
||||
**Linking errors:**
|
||||
Make sure to include the math library:
|
||||
```bash
|
||||
gcc your_code.c ./libnostr_core.a -lm # Note the -lm flag
|
||||
gcc your_code.c ./libnostr_core_x64.a -lz -ldl -lpthread -lm -lssl -lcrypto -lcurl -lsecp256k1
|
||||
```
|
||||
|
||||
### Getting Help
|
||||
|
||||
@@ -145,6 +145,7 @@ if [ "$HELP" = true ]; then
|
||||
echo " 021 - nostr: URI scheme"
|
||||
echo " 042 - Authentication of clients to relays"
|
||||
echo " 044 - Encryption (modern)"
|
||||
echo " 046 - Remote signing"
|
||||
echo " 059 - Gift Wrap"
|
||||
echo ""
|
||||
echo "Examples:"
|
||||
@@ -176,7 +177,7 @@ if [ "$CURRENT_DIR" != "nostr_core_lib" ]; then
|
||||
echo " cd nostr_core_lib"
|
||||
echo " ./build.sh"
|
||||
echo " cd .."
|
||||
echo " gcc your_app.c nostr_core_lib/libnostr_core_x64.a -lz -ldl -lpthread -lm -lssl -lcrypto -lcurl -o your_app"
|
||||
echo " gcc your_app.c nostr_core_lib/libnostr_core_x64.a -lz -ldl -lpthread -lm -lssl -lcrypto -lcurl -lsecp256k1 -o your_app"
|
||||
echo ""
|
||||
exit 1
|
||||
fi
|
||||
@@ -194,7 +195,7 @@ print_info "Auto-detecting needed NIPs from your source code..."
|
||||
NEEDED_NIPS=""
|
||||
if [ -n "$FORCE_NIPS" ]; then
|
||||
if [ "$FORCE_NIPS" = "all" ]; then
|
||||
NEEDED_NIPS="001 004 005 006 011 013 017 019 042 044 059"
|
||||
NEEDED_NIPS="001 004 005 006 011 013 017 019 042 044 046 059"
|
||||
print_info "Forced: Building all available NIPs"
|
||||
else
|
||||
# Convert comma-separated list to space-separated with 3-digit format
|
||||
@@ -213,7 +214,7 @@ else
|
||||
# Check for nostr_core.h (includes everything)
|
||||
if grep -q '#include[[:space:]]*["\<]nostr_core\.h["\>]' *.c 2>/dev/null; then
|
||||
print_info "Found #include \"nostr_core.h\" - building all NIPs"
|
||||
NEEDED_NIPS="001 004 005 006 011 013 019 042 044"
|
||||
NEEDED_NIPS="001 004 005 006 011 013 019 042 044 046 059"
|
||||
elif [ -n "$DETECTED" ]; then
|
||||
NEEDED_NIPS="$DETECTED"
|
||||
print_success "Auto-detected NIPs: $(echo $NEEDED_NIPS | tr ' ' ',')"
|
||||
@@ -231,7 +232,7 @@ fi
|
||||
|
||||
# If building tests or examples, include all NIPs to ensure compatibility
|
||||
if ([ "$BUILD_TESTS" = true ] || [ "$BUILD_EXAMPLES" = true ]) && [ -z "$FORCE_NIPS" ]; then
|
||||
NEEDED_NIPS="001 004 005 006 011 013 017 019 021 042 044 059"
|
||||
NEEDED_NIPS="001 004 005 006 011 013 017 019 021 042 044 046 059"
|
||||
print_info "Building tests/examples - including all available NIPs for compatibility"
|
||||
fi
|
||||
|
||||
@@ -522,6 +523,7 @@ for nip in $NEEDED_NIPS; do
|
||||
021) NIP_DESCRIPTIONS="$NIP_DESCRIPTIONS NIP-021(URI)" ;;
|
||||
042) NIP_DESCRIPTIONS="$NIP_DESCRIPTIONS NIP-042(Auth)" ;;
|
||||
044) NIP_DESCRIPTIONS="$NIP_DESCRIPTIONS NIP-044(Encrypt)" ;;
|
||||
046) NIP_DESCRIPTIONS="$NIP_DESCRIPTIONS NIP-046(Remote-Signing)" ;;
|
||||
059) NIP_DESCRIPTIONS="$NIP_DESCRIPTIONS NIP-059(Gift-Wrap)" ;;
|
||||
esac
|
||||
else
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
/*
|
||||
* NIP-46 Remote Signer Example
|
||||
*
|
||||
* Demonstrates signer session setup, bunker URL generation,
|
||||
* request parsing, request handling, and encrypted response event creation.
|
||||
*/
|
||||
|
||||
#include "../nostr_core/nostr_core.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static int parse_hex_key(const char* hex, unsigned char out[32]) {
|
||||
if (!hex || strlen(hex) != 64) return -1;
|
||||
return nostr_hex_to_bytes(hex, out, 32);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 3) {
|
||||
fprintf(stderr, "Usage: %s <signer_privkey_hex> <user_privkey_hex> [relay_url]\n", argv[0]);
|
||||
fprintf(stderr, "Example: %s <64hex> <64hex> wss://relay.example.com\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char* relay = (argc >= 4) ? argv[3] : "wss://relay.example.com";
|
||||
|
||||
unsigned char signer_sk[32];
|
||||
unsigned char user_sk[32];
|
||||
if (parse_hex_key(argv[1], signer_sk) != 0 || parse_hex_key(argv[2], user_sk) != 0) {
|
||||
fprintf(stderr, "Invalid private key hex; expected 64 hex characters for each key\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (nostr_init() != NOSTR_SUCCESS) {
|
||||
fprintf(stderr, "Failed to initialize nostr library\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char* relays[] = { relay };
|
||||
nostr_nip46_signer_session_t signer;
|
||||
int rc = nostr_nip46_signer_session_init(&signer, signer_sk, user_sk, relays, 1);
|
||||
if (rc != NOSTR_SUCCESS) {
|
||||
fprintf(stderr, "signer init failed: %s\n", nostr_strerror(rc));
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
char bunker_url[1024];
|
||||
rc = nostr_nip46_signer_create_bunker_url(&signer, "demo-secret", bunker_url, sizeof(bunker_url));
|
||||
if (rc != NOSTR_SUCCESS) {
|
||||
fprintf(stderr, "failed to create bunker url: %s\n", nostr_strerror(rc));
|
||||
nostr_nip46_signer_session_destroy(&signer);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("NIP-46 signer initialized\n");
|
||||
printf("Signer pubkey: %s\n", signer.signer_pubkey_hex);
|
||||
printf("User pubkey: %s\n", signer.user_pubkey_hex);
|
||||
printf("Relay: %s\n", relay);
|
||||
printf("Bunker URL: %s\n\n", bunker_url);
|
||||
|
||||
// Simulate receiving a connect request and producing a response
|
||||
const char* connect_params[] = { signer.signer_pubkey_hex, "demo-secret", "sign_event:1,get_public_key" };
|
||||
nostr_nip46_request_t req;
|
||||
rc = nostr_nip46_create_request("demo-req-1", NOSTR_NIP46_METHOD_CONNECT, connect_params, 3, &req);
|
||||
if (rc != NOSTR_SUCCESS) {
|
||||
fprintf(stderr, "failed to create demo request: %s\n", nostr_strerror(rc));
|
||||
nostr_nip46_signer_session_destroy(&signer);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
nostr_nip46_response_t resp;
|
||||
rc = nostr_nip46_signer_handle_request(&signer, &req, &resp);
|
||||
if (rc != NOSTR_SUCCESS) {
|
||||
fprintf(stderr, "failed to handle demo request: %s\n", nostr_strerror(rc));
|
||||
nostr_nip46_free_request(&req);
|
||||
nostr_nip46_signer_session_destroy(&signer);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("Handled method: %s\n", req.method_str);
|
||||
printf("Response result: %s\n", resp.result ? resp.result : "<none>");
|
||||
printf("Response error: %s\n", resp.error ? resp.error : "<none>");
|
||||
|
||||
// Simulate building encrypted response event back to a client
|
||||
unsigned char client_sk[32];
|
||||
unsigned char client_pk[32];
|
||||
memset(client_sk, 0, sizeof(client_sk));
|
||||
client_sk[31] = 1; // deterministic demo key
|
||||
if (nostr_ec_public_key_from_private_key(client_sk, client_pk) != 0) {
|
||||
fprintf(stderr, "failed to derive demo client pubkey\n");
|
||||
nostr_nip46_free_response(&resp);
|
||||
nostr_nip46_free_request(&req);
|
||||
nostr_nip46_signer_session_destroy(&signer);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
cJSON* response_event = nostr_nip46_create_response_event(&resp, signer.signer_private_key, client_pk, 0);
|
||||
if (!response_event) {
|
||||
fprintf(stderr, "failed to create encrypted response event\n");
|
||||
nostr_nip46_free_response(&resp);
|
||||
nostr_nip46_free_request(&req);
|
||||
nostr_nip46_signer_session_destroy(&signer);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
char* response_event_json = cJSON_Print(response_event);
|
||||
if (response_event_json) {
|
||||
printf("\nEncrypted response event (publish this to relays):\n%s\n", response_event_json);
|
||||
free(response_event_json);
|
||||
}
|
||||
|
||||
cJSON_Delete(response_event);
|
||||
nostr_nip46_free_response(&resp);
|
||||
nostr_nip46_free_request(&req);
|
||||
nostr_nip46_signer_session_destroy(&signer);
|
||||
nostr_cleanup();
|
||||
|
||||
return 0;
|
||||
}
|
||||
+204
-7
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#define _DEFAULT_SOURCE
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -109,7 +110,7 @@ void* poll_thread_func(void* arg) {
|
||||
// Print menu
|
||||
void print_menu() {
|
||||
printf("\n=== NOSTR Relay Pool Test Menu ===\n");
|
||||
printf("1. Start Pool (wss://relay.laantungir.net)\n");
|
||||
printf("1. Start Pool (ws://localhost:7555)\n");
|
||||
printf("2. Stop Pool\n");
|
||||
printf("3. Add relay to pool\n");
|
||||
printf("4. Remove relay from pool\n");
|
||||
@@ -117,7 +118,8 @@ void print_menu() {
|
||||
printf("6. Remove subscription\n");
|
||||
printf("7. Show pool status\n");
|
||||
printf("8. Test reconnection (simulate disconnect)\n");
|
||||
printf("9. Exit\n");
|
||||
printf("9. Publish Event\n");
|
||||
printf("0. Exit\n");
|
||||
printf("Choice: ");
|
||||
}
|
||||
|
||||
@@ -405,11 +407,24 @@ void show_pool_status() {
|
||||
|
||||
printf("├── %s: %s\n", relay_urls[i], status_str);
|
||||
|
||||
// Show connection and publish error details
|
||||
const char* conn_error = nostr_relay_pool_get_relay_last_connection_error(pool, relay_urls[i]);
|
||||
const char* pub_error = nostr_relay_pool_get_relay_last_publish_error(pool, relay_urls[i]);
|
||||
|
||||
if (conn_error) {
|
||||
printf("│ ├── Connection error: %s\n", conn_error);
|
||||
}
|
||||
if (pub_error) {
|
||||
printf("│ ├── Last publish error: %s\n", pub_error);
|
||||
}
|
||||
|
||||
const nostr_relay_stats_t* stats = nostr_relay_pool_get_relay_stats(pool, relay_urls[i]);
|
||||
if (stats) {
|
||||
printf("│ ├── Events received: %d\n", stats->events_received);
|
||||
printf("│ ├── Connection attempts: %d\n", stats->connection_attempts);
|
||||
printf("│ ├── Connection failures: %d\n", stats->connection_failures);
|
||||
printf("│ ├── Events published: %d (OK: %d, Failed: %d)\n",
|
||||
stats->events_published, stats->events_published_ok, stats->events_published_failed);
|
||||
printf("│ ├── Ping latency: %.2f ms\n", stats->ping_latency_current);
|
||||
printf("│ └── Query latency: %.2f ms\n", stats->query_latency_avg);
|
||||
}
|
||||
@@ -422,6 +437,148 @@ void show_pool_status() {
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
|
||||
// Async publish callback context
|
||||
typedef struct {
|
||||
int total_relays;
|
||||
int responses_received;
|
||||
int success_count;
|
||||
time_t start_time;
|
||||
} async_publish_context_t;
|
||||
|
||||
// Async publish callback - called for each relay response
|
||||
void async_publish_callback(const char* relay_url, const char* event_id,
|
||||
int success, const char* message, void* user_data) {
|
||||
async_publish_context_t* ctx = (async_publish_context_t*)user_data;
|
||||
|
||||
ctx->responses_received++;
|
||||
if (success) {
|
||||
ctx->success_count++;
|
||||
}
|
||||
|
||||
// Calculate elapsed time
|
||||
time_t now = time(NULL);
|
||||
double elapsed = difftime(now, ctx->start_time);
|
||||
|
||||
// Log to file with real-time feedback
|
||||
char timestamp[26];
|
||||
ctime_r(&now, timestamp);
|
||||
timestamp[24] = '\0';
|
||||
|
||||
if (success) {
|
||||
printf("✅ %s: Published successfully (%.1fs)\n", relay_url, elapsed);
|
||||
dprintf(log_fd, "[%s] ✅ ASYNC: %s published successfully (%.1fs)\n",
|
||||
timestamp, relay_url, elapsed);
|
||||
} else {
|
||||
printf("❌ %s: Failed - %s (%.1fs)\n", relay_url, message ? message : "unknown error", elapsed);
|
||||
dprintf(log_fd, "[%s] ❌ ASYNC: %s failed - %s (%.1fs)\n",
|
||||
timestamp, relay_url, message ? message : "unknown error", elapsed);
|
||||
}
|
||||
|
||||
// Show progress
|
||||
printf(" Progress: %d/%d responses received\n", ctx->responses_received, ctx->total_relays);
|
||||
|
||||
if (ctx->responses_received >= ctx->total_relays) {
|
||||
printf("\n🎉 All relays responded! Final result: %d/%d successful\n",
|
||||
ctx->success_count, ctx->total_relays);
|
||||
dprintf(log_fd, "[%s] 🎉 ASYNC: All relays responded - %d/%d successful\n\n",
|
||||
timestamp, ctx->success_count, ctx->total_relays);
|
||||
}
|
||||
}
|
||||
|
||||
// Publish test event with async callbacks
|
||||
void publish_event() {
|
||||
if (!pool) {
|
||||
printf("❌ Pool not started\n");
|
||||
return;
|
||||
}
|
||||
|
||||
printf("\n--- Publish Test Event ---\n");
|
||||
|
||||
// Generate random keypair
|
||||
unsigned char private_key[32], public_key[32];
|
||||
if (nostr_generate_keypair(private_key, public_key) != NOSTR_SUCCESS) {
|
||||
printf("❌ Failed to generate keypair\n");
|
||||
return;
|
||||
}
|
||||
|
||||
// Get current timestamp
|
||||
time_t now = time(NULL);
|
||||
|
||||
// Format content with date/time
|
||||
char content[256];
|
||||
struct tm* tm_info = localtime(&now);
|
||||
strftime(content, sizeof(content), "Test post at %Y-%m-%d %H:%M:%S", tm_info);
|
||||
|
||||
// Create kind 1 event
|
||||
cJSON* event = nostr_create_and_sign_event(1, content, NULL, private_key, now);
|
||||
if (!event) {
|
||||
printf("❌ Failed to create event\n");
|
||||
return;
|
||||
}
|
||||
|
||||
// Get relay URLs from pool
|
||||
char** relay_urls = NULL;
|
||||
nostr_pool_relay_status_t* statuses = NULL;
|
||||
int relay_count = nostr_relay_pool_list_relays(pool, &relay_urls, &statuses);
|
||||
|
||||
if (relay_count <= 0) {
|
||||
printf("❌ No relays in pool\n");
|
||||
cJSON_Delete(event);
|
||||
return;
|
||||
}
|
||||
|
||||
printf("📤 Publishing event to %d relay(s)...\n", relay_count);
|
||||
printf("Watch for real-time responses below:\n\n");
|
||||
|
||||
// Setup callback context
|
||||
async_publish_context_t ctx = {0};
|
||||
ctx.total_relays = relay_count;
|
||||
ctx.start_time = time(NULL);
|
||||
|
||||
// Log the event
|
||||
char* event_json = cJSON_Print(event);
|
||||
char timestamp[26];
|
||||
ctime_r(&now, timestamp);
|
||||
timestamp[24] = '\0';
|
||||
dprintf(log_fd, "[%s] 📤 Publishing test event\n", timestamp);
|
||||
dprintf(log_fd, "Event: %s\n\n", event_json);
|
||||
free(event_json);
|
||||
|
||||
// Publish using async function
|
||||
int sent_count = nostr_relay_pool_publish_async(pool, (const char**)relay_urls,
|
||||
relay_count, event,
|
||||
async_publish_callback, &ctx);
|
||||
|
||||
if (sent_count > 0) {
|
||||
printf("📡 Event sent to %d/%d relays, waiting for responses...\n\n",
|
||||
sent_count, relay_count);
|
||||
|
||||
// Wait for all responses or timeout (10 seconds)
|
||||
time_t wait_start = time(NULL);
|
||||
while (ctx.responses_received < ctx.total_relays &&
|
||||
(time(NULL) - wait_start) < 10) {
|
||||
// Let the polling thread process messages
|
||||
usleep(100000); // 100ms
|
||||
}
|
||||
|
||||
if (ctx.responses_received < ctx.total_relays) {
|
||||
printf("\n⏰ Timeout reached - %d/%d relays responded\n",
|
||||
ctx.responses_received, ctx.total_relays);
|
||||
}
|
||||
} else {
|
||||
printf("❌ Failed to send event to any relays\n");
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
for (int i = 0; i < relay_count; i++) {
|
||||
free(relay_urls[i]);
|
||||
}
|
||||
free(relay_urls);
|
||||
free(statuses);
|
||||
cJSON_Delete(event);
|
||||
}
|
||||
|
||||
int main() {
|
||||
// Setup logging to file
|
||||
log_fd = open("pool.log", O_WRONLY | O_CREAT | O_TRUNC, 0644);
|
||||
@@ -489,14 +646,14 @@ int main() {
|
||||
break;
|
||||
}
|
||||
|
||||
if (nostr_relay_pool_add_relay(pool, "wss://relay.laantungir.net") != NOSTR_SUCCESS) {
|
||||
if (nostr_relay_pool_add_relay(pool, "ws://localhost:7555") != NOSTR_SUCCESS) {
|
||||
printf("❌ Failed to add default relay\n");
|
||||
nostr_relay_pool_destroy(pool);
|
||||
pool = NULL;
|
||||
break;
|
||||
}
|
||||
|
||||
printf("✅ Pool started with wss://relay.laantungir.net\n");
|
||||
printf("✅ Pool started with ws://localhost:7555\n");
|
||||
|
||||
now = time(NULL);
|
||||
ctime_r(&now, timestamp);
|
||||
@@ -544,13 +701,49 @@ int main() {
|
||||
if (url && strlen(url) > 0) {
|
||||
if (nostr_relay_pool_add_relay(pool, url) == NOSTR_SUCCESS) {
|
||||
printf("✅ Relay added: %s\n", url);
|
||||
printf("⏳ Attempting to connect...\n");
|
||||
|
||||
// Give it a moment to attempt connection
|
||||
sleep(2);
|
||||
|
||||
// Check connection status and show any errors
|
||||
nostr_pool_relay_status_t status = nostr_relay_pool_get_relay_status(pool, url);
|
||||
const char* error_msg = nostr_relay_pool_get_relay_last_connection_error(pool, url);
|
||||
|
||||
switch (status) {
|
||||
case NOSTR_POOL_RELAY_CONNECTED:
|
||||
printf("🟢 Successfully connected to %s\n", url);
|
||||
break;
|
||||
case NOSTR_POOL_RELAY_CONNECTING:
|
||||
printf("🟡 Still connecting to %s...\n", url);
|
||||
break;
|
||||
case NOSTR_POOL_RELAY_DISCONNECTED:
|
||||
printf("⚪ Disconnected from %s\n", url);
|
||||
if (error_msg) {
|
||||
printf(" Last error: %s\n", error_msg);
|
||||
}
|
||||
break;
|
||||
case NOSTR_POOL_RELAY_ERROR:
|
||||
printf("🔴 Connection error for %s\n", url);
|
||||
if (error_msg) {
|
||||
printf(" Error details: %s\n", error_msg);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
printf("❓ Unknown status for %s\n", url);
|
||||
break;
|
||||
}
|
||||
|
||||
now = time(NULL);
|
||||
ctime_r(&now, timestamp);
|
||||
timestamp[24] = '\0';
|
||||
dprintf(log_fd, "[%s] ➕ Relay added: %s\n\n", timestamp, url);
|
||||
dprintf(log_fd, "[%s] ➕ Relay added: %s (status: %d)\n", timestamp, url, status);
|
||||
if (error_msg) {
|
||||
dprintf(log_fd, " Connection error: %s\n", error_msg);
|
||||
}
|
||||
dprintf(log_fd, "\n");
|
||||
} else {
|
||||
printf("❌ Failed to add relay\n");
|
||||
printf("❌ Failed to add relay to pool\n");
|
||||
}
|
||||
}
|
||||
free(url);
|
||||
@@ -655,7 +848,11 @@ int main() {
|
||||
break;
|
||||
}
|
||||
|
||||
case '9': // Exit
|
||||
case '9': // Publish Event
|
||||
publish_event();
|
||||
break;
|
||||
|
||||
case '0': // Exit
|
||||
running = 0;
|
||||
break;
|
||||
|
||||
|
||||
+385
-59
@@ -26,8 +26,8 @@
|
||||
// cJSON for JSON handling
|
||||
#include "../cjson/cJSON.h"
|
||||
|
||||
|
||||
|
||||
// NIP-42 Authentication
|
||||
#include "nip042.h"
|
||||
|
||||
// =============================================================================
|
||||
// RELAY POOL MANAGEMENT
|
||||
@@ -41,6 +41,7 @@
|
||||
#define NOSTR_POOL_SUBSCRIPTION_ID_SIZE 32
|
||||
#define NOSTR_POOL_PING_INTERVAL 59 // 59 seconds - keeps connections alive
|
||||
#define NOSTR_POOL_MAX_PENDING_SUBSCRIPTIONS 8 // Max concurrent subscription timings per relay
|
||||
#define NOSTR_POOL_MAX_PENDING_PUBLISHES 32 // Max concurrent publish operations
|
||||
|
||||
// High-resolution timing helper
|
||||
static double get_current_time_ms(void) {
|
||||
@@ -60,6 +61,17 @@ typedef struct subscription_timing {
|
||||
int active;
|
||||
} subscription_timing_t;
|
||||
|
||||
// Publish operation tracking for async callbacks
|
||||
typedef struct publish_operation {
|
||||
char event_id[65]; // Event ID being published
|
||||
publish_response_callback_t callback; // User callback function
|
||||
void* user_data; // User data for callback
|
||||
time_t publish_time; // When publish was initiated
|
||||
int pending_relay_count; // Number of relays still pending response
|
||||
char** pending_relay_urls; // URLs of relays still pending
|
||||
int total_relay_count; // Total number of relays for this publish
|
||||
} publish_operation_t;
|
||||
|
||||
// Internal structures
|
||||
typedef struct relay_connection {
|
||||
char* url;
|
||||
@@ -93,6 +105,12 @@ typedef struct relay_connection {
|
||||
char last_connection_error[512]; // Last error message from relay connection
|
||||
time_t last_connection_error_time; // When the connection error occurred
|
||||
|
||||
// NIP-42 Authentication fields
|
||||
nostr_auth_state_t auth_state; // Current authentication state
|
||||
char auth_challenge[NOSTR_NIP42_MAX_CHALLENGE_LENGTH]; // Stored challenge
|
||||
time_t auth_challenge_time; // When challenge was received
|
||||
int nip42_enabled; // Whether NIP-42 is enabled for this relay
|
||||
|
||||
// Statistics
|
||||
nostr_relay_stats_t stats;
|
||||
} relay_connection_t;
|
||||
@@ -147,8 +165,17 @@ struct nostr_relay_pool {
|
||||
nostr_pool_subscription_t* subscriptions[NOSTR_POOL_MAX_SUBSCRIPTIONS];
|
||||
int subscription_count;
|
||||
|
||||
// Active publish operations for async callbacks
|
||||
publish_operation_t* publish_operations[NOSTR_POOL_MAX_PENDING_PUBLISHES];
|
||||
int publish_operation_count;
|
||||
|
||||
// Pool-wide settings
|
||||
int default_timeout_ms;
|
||||
|
||||
// NIP-42 Authentication configuration
|
||||
int nip42_enabled;
|
||||
unsigned char private_key[32];
|
||||
int has_private_key;
|
||||
};
|
||||
|
||||
// Helper function to generate unique subscription IDs
|
||||
@@ -217,6 +244,122 @@ static double remove_subscription_timing(relay_connection_t* relay, const char*
|
||||
return -1.0; // Not found
|
||||
}
|
||||
|
||||
// Helper functions for managing publish operations
|
||||
static int add_publish_operation(nostr_relay_pool_t* pool, const char* event_id,
|
||||
const char** relay_urls, int relay_count,
|
||||
publish_response_callback_t callback, void* user_data) {
|
||||
if (!pool || !event_id || !relay_urls || relay_count <= 0) return -1;
|
||||
|
||||
// Check if we have space for another operation
|
||||
if (pool->publish_operation_count >= NOSTR_POOL_MAX_PENDING_PUBLISHES) {
|
||||
return -1; // No space available
|
||||
}
|
||||
|
||||
// Create new publish operation
|
||||
publish_operation_t* op = calloc(1, sizeof(publish_operation_t));
|
||||
if (!op) return -1;
|
||||
|
||||
// Copy event ID
|
||||
strncpy(op->event_id, event_id, sizeof(op->event_id) - 1);
|
||||
op->event_id[sizeof(op->event_id) - 1] = '\0';
|
||||
|
||||
// Set callback and user data
|
||||
op->callback = callback;
|
||||
op->user_data = user_data;
|
||||
op->publish_time = time(NULL);
|
||||
op->total_relay_count = relay_count;
|
||||
op->pending_relay_count = relay_count;
|
||||
|
||||
// Copy relay URLs
|
||||
op->pending_relay_urls = malloc(relay_count * sizeof(char*));
|
||||
if (!op->pending_relay_urls) {
|
||||
free(op);
|
||||
return -1;
|
||||
}
|
||||
|
||||
for (int i = 0; i < relay_count; i++) {
|
||||
op->pending_relay_urls[i] = strdup(relay_urls[i]);
|
||||
if (!op->pending_relay_urls[i]) {
|
||||
// Cleanup on failure
|
||||
for (int j = 0; j < i; j++) {
|
||||
free(op->pending_relay_urls[j]);
|
||||
}
|
||||
free(op->pending_relay_urls);
|
||||
free(op);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// Add to pool
|
||||
pool->publish_operations[pool->publish_operation_count++] = op;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static publish_operation_t* find_publish_operation(nostr_relay_pool_t* pool, const char* event_id) {
|
||||
if (!pool || !event_id) return NULL;
|
||||
|
||||
for (int i = 0; i < pool->publish_operation_count; i++) {
|
||||
if (pool->publish_operations[i] &&
|
||||
strcmp(pool->publish_operations[i]->event_id, event_id) == 0) {
|
||||
return pool->publish_operations[i];
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void remove_publish_operation(nostr_relay_pool_t* pool, const char* event_id) {
|
||||
if (!pool || !event_id) return;
|
||||
|
||||
for (int i = 0; i < pool->publish_operation_count; i++) {
|
||||
if (pool->publish_operations[i] &&
|
||||
strcmp(pool->publish_operations[i]->event_id, event_id) == 0) {
|
||||
|
||||
publish_operation_t* op = pool->publish_operations[i];
|
||||
|
||||
// Free relay URLs (only non-NULL ones)
|
||||
if (op->pending_relay_urls) {
|
||||
for (int j = 0; j < op->total_relay_count; j++) {
|
||||
if (op->pending_relay_urls[j]) {
|
||||
free(op->pending_relay_urls[j]);
|
||||
op->pending_relay_urls[j] = NULL;
|
||||
}
|
||||
}
|
||||
free(op->pending_relay_urls);
|
||||
op->pending_relay_urls = NULL;
|
||||
}
|
||||
free(op);
|
||||
|
||||
// Shift remaining operations
|
||||
for (int j = i; j < pool->publish_operation_count - 1; j++) {
|
||||
pool->publish_operations[j] = pool->publish_operations[j + 1];
|
||||
}
|
||||
pool->publish_operations[--pool->publish_operation_count] = NULL;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int remove_relay_from_publish_operation(publish_operation_t* op, const char* relay_url) {
|
||||
if (!op || !relay_url) return -1;
|
||||
|
||||
for (int i = 0; i < op->pending_relay_count; i++) {
|
||||
if (op->pending_relay_urls[i] && strcmp(op->pending_relay_urls[i], relay_url) == 0) {
|
||||
// Free this relay URL
|
||||
free(op->pending_relay_urls[i]);
|
||||
op->pending_relay_urls[i] = NULL; // Mark as freed
|
||||
|
||||
// Shift remaining URLs
|
||||
for (int j = i; j < op->pending_relay_count - 1; j++) {
|
||||
op->pending_relay_urls[j] = op->pending_relay_urls[j + 1];
|
||||
}
|
||||
op->pending_relay_urls[op->pending_relay_count - 1] = NULL; // Clear the last slot
|
||||
op->pending_relay_count--;
|
||||
return op->pending_relay_count; // Return remaining count
|
||||
}
|
||||
}
|
||||
return -1; // Relay not found
|
||||
}
|
||||
|
||||
// Helper function to ensure relay connection
|
||||
static int ensure_relay_connection(relay_connection_t* relay) {
|
||||
if (!relay) {
|
||||
@@ -470,6 +613,38 @@ nostr_relay_pool_t* nostr_relay_pool_create_compat(void) {
|
||||
return nostr_relay_pool_create(NULL);
|
||||
}
|
||||
|
||||
int nostr_relay_pool_set_auth(nostr_relay_pool_t* pool,
|
||||
const unsigned char* private_key,
|
||||
int enable) {
|
||||
if (!pool) {
|
||||
return NOSTR_ERROR_INVALID_INPUT;
|
||||
}
|
||||
|
||||
pool->nip42_enabled = enable ? 1 : 0;
|
||||
|
||||
if (private_key) {
|
||||
memcpy(pool->private_key, private_key, sizeof(pool->private_key));
|
||||
pool->has_private_key = 1;
|
||||
} else {
|
||||
memset(pool->private_key, 0, sizeof(pool->private_key));
|
||||
pool->has_private_key = 0;
|
||||
}
|
||||
|
||||
// Propagate to existing relay connections
|
||||
for (int i = 0; i < pool->relay_count; i++) {
|
||||
if (pool->relays[i]) {
|
||||
pool->relays[i]->nip42_enabled = pool->nip42_enabled;
|
||||
if (!pool->nip42_enabled) {
|
||||
pool->relays[i]->auth_state = NOSTR_AUTH_STATE_NONE;
|
||||
memset(pool->relays[i]->auth_challenge, 0, sizeof(pool->relays[i]->auth_challenge));
|
||||
pool->relays[i]->auth_challenge_time = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
int nostr_relay_pool_add_relay(nostr_relay_pool_t* pool, const char* relay_url) {
|
||||
if (!pool || !relay_url || pool->relay_count >= NOSTR_POOL_MAX_RELAYS) {
|
||||
return NOSTR_ERROR_INVALID_INPUT;
|
||||
@@ -508,6 +683,12 @@ int nostr_relay_pool_add_relay(nostr_relay_pool_t* pool, const char* relay_url)
|
||||
relay->ping_pending = 0;
|
||||
relay->pending_ping_start_ms = 0.0;
|
||||
|
||||
// Initialize NIP-42 authentication fields
|
||||
relay->auth_state = NOSTR_AUTH_STATE_NONE;
|
||||
memset(relay->auth_challenge, 0, sizeof(relay->auth_challenge));
|
||||
relay->auth_challenge_time = 0;
|
||||
relay->nip42_enabled = pool->nip42_enabled;
|
||||
|
||||
// Initialize statistics
|
||||
memset(&relay->stats, 0, sizeof(relay->stats));
|
||||
relay->stats.connection_uptime_start = time(NULL);
|
||||
@@ -559,6 +740,20 @@ void nostr_relay_pool_destroy(nostr_relay_pool_t* pool) {
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up all pending publish operations
|
||||
for (int i = 0; i < pool->publish_operation_count; i++) {
|
||||
if (pool->publish_operations[i]) {
|
||||
publish_operation_t* op = pool->publish_operations[i];
|
||||
|
||||
// Free relay URLs
|
||||
for (int j = 0; j < op->total_relay_count; j++) {
|
||||
free(op->pending_relay_urls[j]);
|
||||
}
|
||||
free(op->pending_relay_urls);
|
||||
free(op);
|
||||
}
|
||||
}
|
||||
|
||||
// Close all relay connections
|
||||
for (int i = 0; i < pool->relay_count; i++) {
|
||||
if (pool->relays[i]) {
|
||||
@@ -570,6 +765,11 @@ void nostr_relay_pool_destroy(nostr_relay_pool_t* pool) {
|
||||
}
|
||||
}
|
||||
|
||||
if (pool->has_private_key) {
|
||||
memset(pool->private_key, 0, sizeof(pool->private_key));
|
||||
pool->has_private_key = 0;
|
||||
}
|
||||
|
||||
free(pool);
|
||||
}
|
||||
|
||||
@@ -902,26 +1102,122 @@ static void process_relay_message(nostr_relay_pool_t* pool, relay_connection_t*
|
||||
} else if (strcmp(msg_type, "OK") == 0) {
|
||||
// Handle OK response: ["OK", event_id, true/false, message]
|
||||
if (cJSON_IsArray(parsed) && cJSON_GetArraySize(parsed) >= 3) {
|
||||
cJSON* event_id_json = cJSON_GetArrayItem(parsed, 1);
|
||||
cJSON* success_flag = cJSON_GetArrayItem(parsed, 2);
|
||||
|
||||
if (cJSON_IsBool(success_flag)) {
|
||||
if (cJSON_IsTrue(success_flag)) {
|
||||
if (cJSON_IsString(event_id_json) && cJSON_IsBool(success_flag)) {
|
||||
const char* event_id = cJSON_GetStringValue(event_id_json);
|
||||
int success = cJSON_IsTrue(success_flag);
|
||||
const char* error_message = NULL;
|
||||
|
||||
// Extract error message if available
|
||||
if (!success && cJSON_GetArraySize(parsed) >= 4) {
|
||||
cJSON* error_msg = cJSON_GetArrayItem(parsed, 3);
|
||||
if (cJSON_IsString(error_msg)) {
|
||||
error_message = cJSON_GetStringValue(error_msg);
|
||||
}
|
||||
}
|
||||
|
||||
// Update relay statistics
|
||||
if (success) {
|
||||
relay->stats.events_published_ok++;
|
||||
if (relay->auth_state == NOSTR_AUTH_STATE_AUTHENTICATING) {
|
||||
relay->auth_state = NOSTR_AUTH_STATE_AUTHENTICATED;
|
||||
}
|
||||
} else {
|
||||
relay->stats.events_published_failed++;
|
||||
// Store error message if available
|
||||
if (cJSON_GetArraySize(parsed) >= 4) {
|
||||
cJSON* error_msg = cJSON_GetArrayItem(parsed, 3);
|
||||
if (cJSON_IsString(error_msg)) {
|
||||
const char* msg = cJSON_GetStringValue(error_msg);
|
||||
if (msg) {
|
||||
strncpy(relay->last_publish_error, msg,
|
||||
sizeof(relay->last_publish_error) - 1);
|
||||
relay->last_publish_error[sizeof(relay->last_publish_error) - 1] = '\0';
|
||||
relay->last_publish_error_time = time(NULL);
|
||||
|
||||
if (error_message && strstr(error_message, "auth-required") != NULL) {
|
||||
relay->auth_state = NOSTR_AUTH_STATE_REJECTED;
|
||||
|
||||
// If we already have a challenge, immediately attempt re-authentication
|
||||
if (relay->nip42_enabled && pool->has_private_key && relay->auth_challenge[0] != '\0') {
|
||||
cJSON* auth_event = nostr_nip42_create_auth_event(
|
||||
relay->auth_challenge,
|
||||
relay->url,
|
||||
pool->private_key,
|
||||
0
|
||||
);
|
||||
if (auth_event) {
|
||||
char* auth_message = nostr_nip42_create_auth_message(auth_event);
|
||||
if (auth_message) {
|
||||
if (nostr_ws_send_text(relay->ws_client, auth_message) >= 0) {
|
||||
relay->auth_state = NOSTR_AUTH_STATE_AUTHENTICATING;
|
||||
}
|
||||
free(auth_message);
|
||||
}
|
||||
cJSON_Delete(auth_event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Store error message for legacy API
|
||||
if (error_message) {
|
||||
strncpy(relay->last_publish_error, error_message,
|
||||
sizeof(relay->last_publish_error) - 1);
|
||||
relay->last_publish_error[sizeof(relay->last_publish_error) - 1] = '\0';
|
||||
relay->last_publish_error_time = time(NULL);
|
||||
}
|
||||
}
|
||||
|
||||
// Check for async publish operation callback
|
||||
publish_operation_t* op = find_publish_operation(pool, event_id);
|
||||
if (op && op->callback) {
|
||||
// Call the user's callback
|
||||
op->callback(relay->url, event_id, success, error_message, op->user_data);
|
||||
|
||||
// Remove this relay from the pending list
|
||||
int remaining = remove_relay_from_publish_operation(op, relay->url);
|
||||
|
||||
// If no more relays pending, remove the operation
|
||||
if (remaining == 0) {
|
||||
remove_publish_operation(pool, event_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (strcmp(msg_type, "AUTH") == 0) {
|
||||
// Handle AUTH challenge message: ["AUTH", <challenge-string>]
|
||||
if (relay->nip42_enabled && pool->has_private_key &&
|
||||
cJSON_IsArray(parsed) && cJSON_GetArraySize(parsed) >= 2) {
|
||||
cJSON* challenge_json = cJSON_GetArrayItem(parsed, 1);
|
||||
if (cJSON_IsString(challenge_json)) {
|
||||
const char* challenge = cJSON_GetStringValue(challenge_json);
|
||||
|
||||
strncpy(relay->auth_challenge, challenge, sizeof(relay->auth_challenge) - 1);
|
||||
relay->auth_challenge[sizeof(relay->auth_challenge) - 1] = '\0';
|
||||
relay->auth_challenge_time = time(NULL);
|
||||
relay->auth_state = NOSTR_AUTH_STATE_CHALLENGE_RECEIVED;
|
||||
|
||||
cJSON* auth_event = nostr_nip42_create_auth_event(
|
||||
challenge,
|
||||
relay->url,
|
||||
pool->private_key,
|
||||
0
|
||||
);
|
||||
if (auth_event) {
|
||||
char* auth_message = nostr_nip42_create_auth_message(auth_event);
|
||||
if (auth_message) {
|
||||
if (nostr_ws_send_text(relay->ws_client, auth_message) >= 0) {
|
||||
relay->auth_state = NOSTR_AUTH_STATE_AUTHENTICATING;
|
||||
}
|
||||
free(auth_message);
|
||||
}
|
||||
cJSON_Delete(auth_event);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (strcmp(msg_type, "NOTICE") == 0) {
|
||||
// Handle NOTICE message: ["NOTICE", <message>]
|
||||
if (cJSON_IsArray(parsed) && cJSON_GetArraySize(parsed) >= 2) {
|
||||
cJSON* notice_msg = cJSON_GetArrayItem(parsed, 1);
|
||||
if (cJSON_IsString(notice_msg)) {
|
||||
const char* notice = cJSON_GetStringValue(notice_msg);
|
||||
if (notice && strstr(notice, "auth-required") != NULL) {
|
||||
relay->auth_state = NOSTR_AUTH_STATE_REJECTED;
|
||||
strncpy(relay->last_publish_error, notice, sizeof(relay->last_publish_error) - 1);
|
||||
relay->last_publish_error[sizeof(relay->last_publish_error) - 1] = '\0';
|
||||
relay->last_publish_error_time = time(NULL);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1052,6 +1348,37 @@ cJSON** nostr_relay_pool_query_sync(
|
||||
eose_count++;
|
||||
}
|
||||
}
|
||||
} else if (msg_type && strcmp(msg_type, "AUTH") == 0) {
|
||||
// Handle AUTH challenge message: ["AUTH", <challenge-string>]
|
||||
if (relay->nip42_enabled && pool->has_private_key &&
|
||||
cJSON_IsArray(parsed) && cJSON_GetArraySize(parsed) >= 2) {
|
||||
cJSON* challenge_json = cJSON_GetArrayItem(parsed, 1);
|
||||
if (cJSON_IsString(challenge_json)) {
|
||||
const char* challenge = cJSON_GetStringValue(challenge_json);
|
||||
|
||||
strncpy(relay->auth_challenge, challenge, sizeof(relay->auth_challenge) - 1);
|
||||
relay->auth_challenge[sizeof(relay->auth_challenge) - 1] = '\0';
|
||||
relay->auth_challenge_time = time(NULL);
|
||||
relay->auth_state = NOSTR_AUTH_STATE_CHALLENGE_RECEIVED;
|
||||
|
||||
cJSON* auth_event = nostr_nip42_create_auth_event(
|
||||
challenge,
|
||||
relay->url,
|
||||
pool->private_key,
|
||||
0
|
||||
);
|
||||
if (auth_event) {
|
||||
char* auth_message = nostr_nip42_create_auth_message(auth_event);
|
||||
if (auth_message) {
|
||||
if (nostr_ws_send_text(relay->ws_client, auth_message) >= 0) {
|
||||
relay->auth_state = NOSTR_AUTH_STATE_AUTHENTICATING;
|
||||
}
|
||||
free(auth_message);
|
||||
}
|
||||
cJSON_Delete(auth_event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (msg_type) free(msg_type);
|
||||
if (parsed) cJSON_Delete(parsed);
|
||||
@@ -1113,16 +1440,35 @@ cJSON* nostr_relay_pool_get_event(
|
||||
return result;
|
||||
}
|
||||
|
||||
int nostr_relay_pool_publish(
|
||||
|
||||
int nostr_relay_pool_publish_async(
|
||||
nostr_relay_pool_t* pool,
|
||||
const char** relay_urls,
|
||||
int relay_count,
|
||||
cJSON* event) {
|
||||
cJSON* event,
|
||||
publish_response_callback_t callback,
|
||||
void* user_data) {
|
||||
|
||||
if (!pool || !relay_urls || relay_count <= 0 || !event) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Extract event ID for tracking
|
||||
cJSON* event_id_json = cJSON_GetObjectItem(event, "id");
|
||||
if (!event_id_json || !cJSON_IsString(event_id_json)) {
|
||||
return -1; // Event must have an ID
|
||||
}
|
||||
const char* event_id = cJSON_GetStringValue(event_id_json);
|
||||
|
||||
// Add publish operation for tracking (only if callback provided)
|
||||
publish_operation_t* op = NULL;
|
||||
if (callback) {
|
||||
if (add_publish_operation(pool, event_id, relay_urls, relay_count, callback, user_data) != 0) {
|
||||
return -1; // Failed to add operation
|
||||
}
|
||||
op = find_publish_operation(pool, event_id);
|
||||
}
|
||||
|
||||
int success_count = 0;
|
||||
|
||||
for (int i = 0; i < relay_count; i++) {
|
||||
@@ -1135,55 +1481,35 @@ int nostr_relay_pool_publish(
|
||||
}
|
||||
|
||||
if (relay && ensure_relay_connection(relay) == 0) {
|
||||
double start_time_ms = get_current_time_ms();
|
||||
|
||||
// Send EVENT message
|
||||
if (nostr_relay_send_event(relay->ws_client, event) >= 0) {
|
||||
relay->stats.events_published++;
|
||||
|
||||
// Wait for OK response
|
||||
char buffer[1024];
|
||||
time_t wait_start = time(NULL);
|
||||
int got_response = 0;
|
||||
|
||||
while (time(NULL) - wait_start < 5 && !got_response) { // 5 second timeout
|
||||
int len = nostr_ws_receive(relay->ws_client, buffer, sizeof(buffer) - 1, 1000);
|
||||
if (len > 0) {
|
||||
buffer[len] = '\0';
|
||||
|
||||
char* msg_type = NULL;
|
||||
cJSON* parsed = NULL;
|
||||
if (nostr_parse_relay_message(buffer, &msg_type, &parsed) == 0) {
|
||||
if (msg_type && strcmp(msg_type, "OK") == 0) {
|
||||
// Handle OK response
|
||||
if (cJSON_IsArray(parsed) && cJSON_GetArraySize(parsed) >= 3) {
|
||||
cJSON* success_flag = cJSON_GetArrayItem(parsed, 2);
|
||||
if (cJSON_IsBool(success_flag) && cJSON_IsTrue(success_flag)) {
|
||||
success_count++;
|
||||
relay->stats.events_published_ok++;
|
||||
|
||||
// Update publish latency statistics
|
||||
double latency_ms = get_current_time_ms() - start_time_ms;
|
||||
if (relay->stats.publish_samples == 0) {
|
||||
relay->stats.publish_latency_avg = latency_ms;
|
||||
} else {
|
||||
relay->stats.publish_latency_avg =
|
||||
(relay->stats.publish_latency_avg * relay->stats.publish_samples + latency_ms) /
|
||||
(relay->stats.publish_samples + 1);
|
||||
}
|
||||
relay->stats.publish_samples++;
|
||||
} else {
|
||||
relay->stats.events_published_failed++;
|
||||
}
|
||||
}
|
||||
got_response = 1;
|
||||
}
|
||||
if (msg_type) free(msg_type);
|
||||
if (parsed) cJSON_Delete(parsed);
|
||||
}
|
||||
success_count++;
|
||||
} else {
|
||||
// If send failed and we have a callback, notify immediately
|
||||
if (callback && op) {
|
||||
callback(relay_urls[i], event_id, 0, "Failed to send event to relay", user_data);
|
||||
|
||||
// Remove this relay from the pending operation
|
||||
int remaining = remove_relay_from_publish_operation(op, relay_urls[i]);
|
||||
if (remaining == 0) {
|
||||
remove_publish_operation(pool, event_id);
|
||||
op = NULL; // Mark as removed to prevent double-free
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Connection failed - notify callback immediately if provided
|
||||
if (callback && op) {
|
||||
callback(relay_urls[i], event_id, 0, "Failed to connect to relay", user_data);
|
||||
|
||||
// Remove this relay from the pending operation
|
||||
int remaining = remove_relay_from_publish_operation(op, relay_urls[i]);
|
||||
if (remaining == 0) {
|
||||
remove_publish_operation(pool, event_id);
|
||||
op = NULL; // Mark as removed to prevent double-free
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ extern "C" {
|
||||
#endif
|
||||
|
||||
// NIP-04 constants
|
||||
// #define NOSTR_NIP04_MAX_PLAINTEXT_SIZE 65535
|
||||
// #define NOSTR_NIP04_MAX_PLAINTEXT_SIZE 1048576 // 1MB
|
||||
// NIP-04 Constants
|
||||
// #define NOSTR_NIP04_MAX_PLAINTEXT_SIZE 16777216 // 16MB
|
||||
// #define NOSTR_NIP04_MAX_ENCRYPTED_SIZE 22369621 // ~21.3MB (accounts for base64 overhead + IV)
|
||||
|
||||
+10
-9
@@ -258,11 +258,12 @@ cJSON* nostr_nip17_create_relay_list_event(const char** relay_urls,
|
||||
* NIP-17: Send a direct message to recipients
|
||||
*/
|
||||
int nostr_nip17_send_dm(cJSON* dm_event,
|
||||
const char** recipient_pubkeys,
|
||||
int num_recipients,
|
||||
const unsigned char* sender_private_key,
|
||||
cJSON** gift_wraps_out,
|
||||
int max_gift_wraps) {
|
||||
const char** recipient_pubkeys,
|
||||
int num_recipients,
|
||||
const unsigned char* sender_private_key,
|
||||
cJSON** gift_wraps_out,
|
||||
int max_gift_wraps,
|
||||
long max_delay_sec) {
|
||||
if (!dm_event || !recipient_pubkeys || num_recipients <= 0 ||
|
||||
!sender_private_key || !gift_wraps_out || max_gift_wraps <= 0) {
|
||||
return -1;
|
||||
@@ -278,13 +279,13 @@ int nostr_nip17_send_dm(cJSON* dm_event,
|
||||
}
|
||||
|
||||
// Create seal for this recipient
|
||||
cJSON* seal = nostr_nip59_create_seal(dm_event, sender_private_key, recipient_public_key);
|
||||
cJSON* seal = nostr_nip59_create_seal(dm_event, sender_private_key, recipient_public_key, max_delay_sec);
|
||||
if (!seal) {
|
||||
continue; // Skip if sealing fails
|
||||
}
|
||||
|
||||
// Create gift wrap for this recipient
|
||||
cJSON* gift_wrap = nostr_nip59_create_gift_wrap(seal, recipient_pubkeys[i]);
|
||||
cJSON* gift_wrap = nostr_nip59_create_gift_wrap(seal, recipient_pubkeys[i], max_delay_sec);
|
||||
cJSON_Delete(seal); // Seal is now wrapped
|
||||
|
||||
if (!gift_wrap) {
|
||||
@@ -303,10 +304,10 @@ int nostr_nip17_send_dm(cJSON* dm_event,
|
||||
nostr_bytes_to_hex(sender_public_key, 32, sender_pubkey_hex);
|
||||
|
||||
// Create seal for sender
|
||||
cJSON* sender_seal = nostr_nip59_create_seal(dm_event, sender_private_key, sender_public_key);
|
||||
cJSON* sender_seal = nostr_nip59_create_seal(dm_event, sender_private_key, sender_public_key, max_delay_sec);
|
||||
if (sender_seal) {
|
||||
// Create gift wrap for sender
|
||||
cJSON* sender_gift_wrap = nostr_nip59_create_gift_wrap(sender_seal, sender_pubkey_hex);
|
||||
cJSON* sender_gift_wrap = nostr_nip59_create_gift_wrap(sender_seal, sender_pubkey_hex, max_delay_sec);
|
||||
cJSON_Delete(sender_seal);
|
||||
|
||||
if (sender_gift_wrap) {
|
||||
|
||||
+3
-1
@@ -97,6 +97,7 @@ cJSON* nostr_nip17_create_relay_list_event(const char** relay_urls,
|
||||
* @param sender_private_key 32-byte sender private key
|
||||
* @param gift_wraps_out Array to store resulting gift wrap events (caller must free)
|
||||
* @param max_gift_wraps Maximum number of gift wraps to create
|
||||
* @param max_delay_sec Maximum random timestamp delay in seconds (0 = no randomization)
|
||||
* @return Number of gift wrap events created, or -1 on error
|
||||
*/
|
||||
int nostr_nip17_send_dm(cJSON* dm_event,
|
||||
@@ -104,7 +105,8 @@ int nostr_nip17_send_dm(cJSON* dm_event,
|
||||
int num_recipients,
|
||||
const unsigned char* sender_private_key,
|
||||
cJSON** gift_wraps_out,
|
||||
int max_gift_wraps);
|
||||
int max_gift_wraps,
|
||||
long max_delay_sec);
|
||||
|
||||
/**
|
||||
* NIP-17: Receive and decrypt a direct message
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ extern "C" {
|
||||
#endif
|
||||
|
||||
// NIP-44 constants
|
||||
// #define NOSTR_NIP44_MAX_PLAINTEXT_SIZE 65535
|
||||
// #define NOSTR_NIP44_MAX_PLAINTEXT_SIZE 1048576
|
||||
|
||||
/**
|
||||
* NIP-44: Encrypt a message using ECDH + ChaCha20 + HMAC
|
||||
|
||||
@@ -0,0 +1,987 @@
|
||||
/*
|
||||
* NIP-46: Nostr Remote Signing Implementation
|
||||
* https://github.com/nostr-protocol/nips/blob/master/46.md
|
||||
*/
|
||||
|
||||
#define _GNU_SOURCE
|
||||
#include "nip046.h"
|
||||
#include "nip044.h"
|
||||
#include "nip004.h"
|
||||
#include "utils.h"
|
||||
#include "nostr_common.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ctype.h>
|
||||
#include <time.h>
|
||||
|
||||
// Forward declarations for crypto/private APIs
|
||||
int nostr_ec_public_key_from_private_key(const unsigned char* private_key, unsigned char* public_key);
|
||||
int nostr_secp256k1_get_random_bytes(unsigned char* buf, size_t len);
|
||||
|
||||
static char* nip46_strdup(const char* s) {
|
||||
if (!s) return NULL;
|
||||
size_t len = strlen(s);
|
||||
char* out = (char*)malloc(len + 1);
|
||||
if (!out) return NULL;
|
||||
memcpy(out, s, len + 1);
|
||||
return out;
|
||||
}
|
||||
|
||||
static void safe_copy(char* dst, size_t dst_size, const char* src) {
|
||||
if (!dst || dst_size == 0) return;
|
||||
if (!src) {
|
||||
dst[0] = '\0';
|
||||
return;
|
||||
}
|
||||
|
||||
size_t src_len = strlen(src);
|
||||
size_t copy_len = (src_len < (dst_size - 1U)) ? src_len : (dst_size - 1U);
|
||||
memcpy(dst, src, copy_len);
|
||||
dst[copy_len] = '\0';
|
||||
}
|
||||
|
||||
static int is_hex_64(const char* s) {
|
||||
if (!s || strlen(s) != 64) return 0;
|
||||
for (int i = 0; i < 64; i++) {
|
||||
if (!isxdigit((unsigned char)s[i])) return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int hex_val(char c) {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int url_decode(const char* in, char* out, size_t out_size) {
|
||||
if (!in || !out || out_size == 0) return NOSTR_ERROR_INVALID_INPUT;
|
||||
|
||||
size_t oi = 0;
|
||||
for (size_t i = 0; in[i] != '\0'; i++) {
|
||||
if (oi + 1 >= out_size) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
|
||||
if (in[i] == '%' && in[i + 1] && in[i + 2]) {
|
||||
int hi = hex_val(in[i + 1]);
|
||||
int lo = hex_val(in[i + 2]);
|
||||
if (hi < 0 || lo < 0) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
out[oi++] = (char)((hi << 4) | lo);
|
||||
i += 2;
|
||||
} else if (in[i] == '+') {
|
||||
out[oi++] = ' ';
|
||||
} else {
|
||||
out[oi++] = in[i];
|
||||
}
|
||||
}
|
||||
|
||||
out[oi] = '\0';
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
static int is_unreserved(char c) {
|
||||
return (isalnum((unsigned char)c) || c == '-' || c == '_' || c == '.' || c == '~');
|
||||
}
|
||||
|
||||
static int url_encode(const char* in, char* out, size_t out_size) {
|
||||
if (!in || !out || out_size == 0) return NOSTR_ERROR_INVALID_INPUT;
|
||||
|
||||
static const char* HEX = "0123456789ABCDEF";
|
||||
size_t oi = 0;
|
||||
for (size_t i = 0; in[i] != '\0'; i++) {
|
||||
unsigned char c = (unsigned char)in[i];
|
||||
if (is_unreserved((char)c)) {
|
||||
if (oi + 1 >= out_size) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
out[oi++] = (char)c;
|
||||
} else {
|
||||
if (oi + 3 >= out_size) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
out[oi++] = '%';
|
||||
out[oi++] = HEX[(c >> 4) & 0x0F];
|
||||
out[oi++] = HEX[c & 0x0F];
|
||||
}
|
||||
}
|
||||
out[oi] = '\0';
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
const char* nostr_nip46_method_to_string(nostr_nip46_method_t method) {
|
||||
switch (method) {
|
||||
case NOSTR_NIP46_METHOD_CONNECT: return "connect";
|
||||
case NOSTR_NIP46_METHOD_SIGN_EVENT: return "sign_event";
|
||||
case NOSTR_NIP46_METHOD_PING: return "ping";
|
||||
case NOSTR_NIP46_METHOD_GET_PUBLIC_KEY: return "get_public_key";
|
||||
case NOSTR_NIP46_METHOD_NIP04_ENCRYPT: return "nip04_encrypt";
|
||||
case NOSTR_NIP46_METHOD_NIP04_DECRYPT: return "nip04_decrypt";
|
||||
case NOSTR_NIP46_METHOD_NIP44_ENCRYPT: return "nip44_encrypt";
|
||||
case NOSTR_NIP46_METHOD_NIP44_DECRYPT: return "nip44_decrypt";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
nostr_nip46_method_t nostr_nip46_string_to_method(const char* method) {
|
||||
if (!method) return NOSTR_NIP46_METHOD_UNKNOWN;
|
||||
if (strcmp(method, "connect") == 0) return NOSTR_NIP46_METHOD_CONNECT;
|
||||
if (strcmp(method, "sign_event") == 0) return NOSTR_NIP46_METHOD_SIGN_EVENT;
|
||||
if (strcmp(method, "ping") == 0) return NOSTR_NIP46_METHOD_PING;
|
||||
if (strcmp(method, "get_public_key") == 0) return NOSTR_NIP46_METHOD_GET_PUBLIC_KEY;
|
||||
if (strcmp(method, "nip04_encrypt") == 0) return NOSTR_NIP46_METHOD_NIP04_ENCRYPT;
|
||||
if (strcmp(method, "nip04_decrypt") == 0) return NOSTR_NIP46_METHOD_NIP04_DECRYPT;
|
||||
if (strcmp(method, "nip44_encrypt") == 0) return NOSTR_NIP46_METHOD_NIP44_ENCRYPT;
|
||||
if (strcmp(method, "nip44_decrypt") == 0) return NOSTR_NIP46_METHOD_NIP44_DECRYPT;
|
||||
return NOSTR_NIP46_METHOD_UNKNOWN;
|
||||
}
|
||||
|
||||
int nostr_nip46_generate_request_id(char* output, size_t output_size) {
|
||||
if (!output || output_size < NOSTR_NIP46_MAX_REQUEST_ID_LEN) {
|
||||
return NOSTR_ERROR_INVALID_INPUT;
|
||||
}
|
||||
|
||||
unsigned char rnd[16];
|
||||
if (nostr_secp256k1_get_random_bytes(rnd, sizeof(rnd)) != 1) {
|
||||
return NOSTR_ERROR_CRYPTO_FAILED;
|
||||
}
|
||||
|
||||
nostr_bytes_to_hex(rnd, sizeof(rnd), output);
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
int nostr_nip46_create_request(const char* id,
|
||||
nostr_nip46_method_t method,
|
||||
const char** params,
|
||||
int param_count,
|
||||
nostr_nip46_request_t* out) {
|
||||
if (!id || !out || param_count < 0) return NOSTR_ERROR_INVALID_INPUT;
|
||||
if (strlen(id) >= sizeof(out->id)) return NOSTR_ERROR_NIP46_INVALID_REQUEST;
|
||||
|
||||
memset(out, 0, sizeof(*out));
|
||||
safe_copy(out->id, sizeof(out->id), id);
|
||||
out->method = method;
|
||||
safe_copy(out->method_str, sizeof(out->method_str), nostr_nip46_method_to_string(method));
|
||||
|
||||
out->param_count = param_count;
|
||||
if (param_count == 0) {
|
||||
out->params = NULL;
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
out->params = (char**)calloc((size_t)param_count, sizeof(char*));
|
||||
if (!out->params) return NOSTR_ERROR_MEMORY_FAILED;
|
||||
|
||||
for (int i = 0; i < param_count; i++) {
|
||||
const char* p = (params && params[i]) ? params[i] : "";
|
||||
out->params[i] = nip46_strdup(p);
|
||||
if (!out->params[i]) {
|
||||
for (int j = 0; j < i; j++) free(out->params[j]);
|
||||
free(out->params);
|
||||
out->params = NULL;
|
||||
out->param_count = 0;
|
||||
return NOSTR_ERROR_MEMORY_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
int nostr_nip46_create_response(const char* id,
|
||||
const char* result,
|
||||
const char* error,
|
||||
nostr_nip46_response_t* out) {
|
||||
if (!id || !out) return NOSTR_ERROR_INVALID_INPUT;
|
||||
if (strlen(id) >= sizeof(out->id)) return NOSTR_ERROR_NIP46_INVALID_RESPONSE;
|
||||
|
||||
memset(out, 0, sizeof(*out));
|
||||
safe_copy(out->id, sizeof(out->id), id);
|
||||
|
||||
if (result) {
|
||||
out->result = nip46_strdup(result);
|
||||
if (!out->result) return NOSTR_ERROR_MEMORY_FAILED;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
out->error = nip46_strdup(error);
|
||||
if (!out->error) {
|
||||
free(out->result);
|
||||
out->result = NULL;
|
||||
return NOSTR_ERROR_MEMORY_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
void nostr_nip46_free_request(nostr_nip46_request_t* request) {
|
||||
if (!request) return;
|
||||
if (request->params) {
|
||||
for (int i = 0; i < request->param_count; i++) {
|
||||
free(request->params[i]);
|
||||
}
|
||||
free(request->params);
|
||||
}
|
||||
memset(request, 0, sizeof(*request));
|
||||
}
|
||||
|
||||
void nostr_nip46_free_response(nostr_nip46_response_t* response) {
|
||||
if (!response) return;
|
||||
free(response->result);
|
||||
free(response->error);
|
||||
memset(response, 0, sizeof(*response));
|
||||
}
|
||||
|
||||
int nostr_nip46_request_to_json(const nostr_nip46_request_t* request, char** output_json) {
|
||||
if (!request || !output_json) return NOSTR_ERROR_INVALID_INPUT;
|
||||
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (!root) return NOSTR_ERROR_MEMORY_FAILED;
|
||||
|
||||
cJSON_AddStringToObject(root, "id", request->id);
|
||||
cJSON_AddStringToObject(root, "method", request->method_str);
|
||||
|
||||
cJSON* params = cJSON_CreateArray();
|
||||
if (!params) {
|
||||
cJSON_Delete(root);
|
||||
return NOSTR_ERROR_MEMORY_FAILED;
|
||||
}
|
||||
|
||||
for (int i = 0; i < request->param_count; i++) {
|
||||
cJSON_AddItemToArray(params, cJSON_CreateString(request->params[i] ? request->params[i] : ""));
|
||||
}
|
||||
cJSON_AddItemToObject(root, "params", params);
|
||||
|
||||
char* js = cJSON_PrintUnformatted(root);
|
||||
cJSON_Delete(root);
|
||||
if (!js) return NOSTR_ERROR_MEMORY_FAILED;
|
||||
|
||||
*output_json = js;
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
int nostr_nip46_response_to_json(const nostr_nip46_response_t* response, char** output_json) {
|
||||
if (!response || !output_json) return NOSTR_ERROR_INVALID_INPUT;
|
||||
|
||||
cJSON* root = cJSON_CreateObject();
|
||||
if (!root) return NOSTR_ERROR_MEMORY_FAILED;
|
||||
|
||||
cJSON_AddStringToObject(root, "id", response->id);
|
||||
cJSON_AddStringToObject(root, "result", response->result ? response->result : "");
|
||||
if (response->error) {
|
||||
cJSON_AddStringToObject(root, "error", response->error);
|
||||
}
|
||||
|
||||
char* js = cJSON_PrintUnformatted(root);
|
||||
cJSON_Delete(root);
|
||||
if (!js) return NOSTR_ERROR_MEMORY_FAILED;
|
||||
|
||||
*output_json = js;
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
int nostr_nip46_parse_request(const char* json_payload, nostr_nip46_request_t* out) {
|
||||
if (!json_payload || !out) return NOSTR_ERROR_INVALID_INPUT;
|
||||
memset(out, 0, sizeof(*out));
|
||||
|
||||
cJSON* root = cJSON_Parse(json_payload);
|
||||
if (!root) return NOSTR_ERROR_NIP46_INVALID_REQUEST;
|
||||
|
||||
cJSON* id = cJSON_GetObjectItem(root, "id");
|
||||
cJSON* method = cJSON_GetObjectItem(root, "method");
|
||||
cJSON* params = cJSON_GetObjectItem(root, "params");
|
||||
|
||||
if (!cJSON_IsString(id) || !cJSON_IsString(method) || !cJSON_IsArray(params)) {
|
||||
cJSON_Delete(root);
|
||||
return NOSTR_ERROR_NIP46_INVALID_REQUEST;
|
||||
}
|
||||
|
||||
safe_copy(out->id, sizeof(out->id), cJSON_GetStringValue(id));
|
||||
safe_copy(out->method_str, sizeof(out->method_str), cJSON_GetStringValue(method));
|
||||
out->method = nostr_nip46_string_to_method(out->method_str);
|
||||
|
||||
out->param_count = cJSON_GetArraySize(params);
|
||||
if (out->param_count > 0) {
|
||||
out->params = (char**)calloc((size_t)out->param_count, sizeof(char*));
|
||||
if (!out->params) {
|
||||
cJSON_Delete(root);
|
||||
return NOSTR_ERROR_MEMORY_FAILED;
|
||||
}
|
||||
|
||||
for (int i = 0; i < out->param_count; i++) {
|
||||
cJSON* p = cJSON_GetArrayItem(params, i);
|
||||
if (!cJSON_IsString(p)) {
|
||||
nostr_nip46_free_request(out);
|
||||
cJSON_Delete(root);
|
||||
return NOSTR_ERROR_NIP46_INVALID_REQUEST;
|
||||
}
|
||||
out->params[i] = nip46_strdup(cJSON_GetStringValue(p));
|
||||
if (!out->params[i]) {
|
||||
nostr_nip46_free_request(out);
|
||||
cJSON_Delete(root);
|
||||
return NOSTR_ERROR_MEMORY_FAILED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cJSON_Delete(root);
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
int nostr_nip46_parse_response(const char* json_payload, nostr_nip46_response_t* out) {
|
||||
if (!json_payload || !out) return NOSTR_ERROR_INVALID_INPUT;
|
||||
memset(out, 0, sizeof(*out));
|
||||
|
||||
cJSON* root = cJSON_Parse(json_payload);
|
||||
if (!root) return NOSTR_ERROR_NIP46_INVALID_RESPONSE;
|
||||
|
||||
cJSON* id = cJSON_GetObjectItem(root, "id");
|
||||
cJSON* result = cJSON_GetObjectItem(root, "result");
|
||||
cJSON* error = cJSON_GetObjectItem(root, "error");
|
||||
|
||||
if (!cJSON_IsString(id) || !cJSON_IsString(result)) {
|
||||
cJSON_Delete(root);
|
||||
return NOSTR_ERROR_NIP46_INVALID_RESPONSE;
|
||||
}
|
||||
|
||||
safe_copy(out->id, sizeof(out->id), cJSON_GetStringValue(id));
|
||||
out->result = nip46_strdup(cJSON_GetStringValue(result));
|
||||
if (!out->result) {
|
||||
cJSON_Delete(root);
|
||||
return NOSTR_ERROR_MEMORY_FAILED;
|
||||
}
|
||||
|
||||
if (error && cJSON_IsString(error)) {
|
||||
out->error = nip46_strdup(cJSON_GetStringValue(error));
|
||||
if (!out->error) {
|
||||
nostr_nip46_free_response(out);
|
||||
cJSON_Delete(root);
|
||||
return NOSTR_ERROR_MEMORY_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
cJSON_Delete(root);
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
static cJSON* create_nip46_event(int kind,
|
||||
const char* encrypted_content,
|
||||
const unsigned char* sender_private_key,
|
||||
const unsigned char* recipient_public_key,
|
||||
time_t timestamp) {
|
||||
if (!encrypted_content || !sender_private_key || !recipient_public_key) return NULL;
|
||||
|
||||
char recipient_hex[65];
|
||||
nostr_bytes_to_hex(recipient_public_key, 32, recipient_hex);
|
||||
|
||||
cJSON* tags = cJSON_CreateArray();
|
||||
if (!tags) return NULL;
|
||||
|
||||
cJSON* ptag = cJSON_CreateArray();
|
||||
if (!ptag) {
|
||||
cJSON_Delete(tags);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
cJSON_AddItemToArray(ptag, cJSON_CreateString("p"));
|
||||
cJSON_AddItemToArray(ptag, cJSON_CreateString(recipient_hex));
|
||||
cJSON_AddItemToArray(tags, ptag);
|
||||
|
||||
cJSON* evt = nostr_create_and_sign_event(kind, encrypted_content, tags, sender_private_key, timestamp);
|
||||
cJSON_Delete(tags);
|
||||
return evt;
|
||||
}
|
||||
|
||||
cJSON* nostr_nip46_create_request_event(const nostr_nip46_request_t* request,
|
||||
const unsigned char* sender_private_key,
|
||||
const unsigned char* recipient_public_key,
|
||||
time_t timestamp) {
|
||||
if (!request || !sender_private_key || !recipient_public_key) return NULL;
|
||||
|
||||
char* json_payload = NULL;
|
||||
if (nostr_nip46_request_to_json(request, &json_payload) != NOSTR_SUCCESS) return NULL;
|
||||
|
||||
char encrypted[NOSTR_NIP46_MAX_PAYLOAD_LEN];
|
||||
int rc = nostr_nip44_encrypt(sender_private_key, recipient_public_key, json_payload,
|
||||
encrypted, sizeof(encrypted));
|
||||
free(json_payload);
|
||||
if (rc != NOSTR_SUCCESS) return NULL;
|
||||
|
||||
return create_nip46_event(NOSTR_NIP46_EVENT_KIND, encrypted,
|
||||
sender_private_key, recipient_public_key, timestamp);
|
||||
}
|
||||
|
||||
cJSON* nostr_nip46_create_response_event(const nostr_nip46_response_t* response,
|
||||
const unsigned char* sender_private_key,
|
||||
const unsigned char* recipient_public_key,
|
||||
time_t timestamp) {
|
||||
if (!response || !sender_private_key || !recipient_public_key) return NULL;
|
||||
|
||||
char* json_payload = NULL;
|
||||
if (nostr_nip46_response_to_json(response, &json_payload) != NOSTR_SUCCESS) return NULL;
|
||||
|
||||
char encrypted[NOSTR_NIP46_MAX_PAYLOAD_LEN];
|
||||
int rc = nostr_nip44_encrypt(sender_private_key, recipient_public_key, json_payload,
|
||||
encrypted, sizeof(encrypted));
|
||||
free(json_payload);
|
||||
if (rc != NOSTR_SUCCESS) return NULL;
|
||||
|
||||
return create_nip46_event(NOSTR_NIP46_EVENT_KIND, encrypted,
|
||||
sender_private_key, recipient_public_key, timestamp);
|
||||
}
|
||||
|
||||
int nostr_nip46_decrypt_event(cJSON* event,
|
||||
const unsigned char* recipient_private_key,
|
||||
char* output,
|
||||
size_t output_size) {
|
||||
if (!event || !recipient_private_key || !output || output_size == 0) {
|
||||
return NOSTR_ERROR_INVALID_INPUT;
|
||||
}
|
||||
|
||||
cJSON* content = cJSON_GetObjectItem(event, "content");
|
||||
cJSON* pubkey = cJSON_GetObjectItem(event, "pubkey");
|
||||
cJSON* kind = cJSON_GetObjectItem(event, "kind");
|
||||
|
||||
if (!cJSON_IsString(content) || !cJSON_IsString(pubkey) || !cJSON_IsNumber(kind)) {
|
||||
return NOSTR_ERROR_NIP46_INVALID_REQUEST;
|
||||
}
|
||||
|
||||
if ((int)cJSON_GetNumberValue(kind) != NOSTR_NIP46_EVENT_KIND) {
|
||||
return NOSTR_ERROR_NIP46_INVALID_REQUEST;
|
||||
}
|
||||
|
||||
const char* sender_hex = cJSON_GetStringValue(pubkey);
|
||||
unsigned char sender_pubkey[32];
|
||||
if (nostr_hex_to_bytes(sender_hex, sender_pubkey, 32) != 0) {
|
||||
return NOSTR_ERROR_NIP46_DECRYPTION_FAILED;
|
||||
}
|
||||
|
||||
int rc = nostr_nip44_decrypt(recipient_private_key, sender_pubkey,
|
||||
cJSON_GetStringValue(content), output, output_size);
|
||||
if (rc != NOSTR_SUCCESS) return NOSTR_ERROR_NIP46_DECRYPTION_FAILED;
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
static int parse_query_pairs(const char* query,
|
||||
int (*cb)(const char* key, const char* val, void* ctx),
|
||||
void* ctx) {
|
||||
if (!query || !cb) return NOSTR_ERROR_INVALID_INPUT;
|
||||
|
||||
char* work = nip46_strdup(query);
|
||||
if (!work) return NOSTR_ERROR_MEMORY_FAILED;
|
||||
|
||||
char* saveptr = NULL;
|
||||
char* token = strtok_r(work, "&", &saveptr);
|
||||
while (token) {
|
||||
char* eq = strchr(token, '=');
|
||||
if (eq) {
|
||||
*eq = '\0';
|
||||
const char* key = token;
|
||||
const char* val = eq + 1;
|
||||
int rc = cb(key, val, ctx);
|
||||
if (rc != NOSTR_SUCCESS) {
|
||||
free(work);
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
token = strtok_r(NULL, "&", &saveptr);
|
||||
}
|
||||
|
||||
free(work);
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
nostr_nip46_bunker_url_t* out;
|
||||
} bunker_parse_ctx_t;
|
||||
|
||||
static int bunker_pair_cb(const char* key, const char* val, void* ctx) {
|
||||
bunker_parse_ctx_t* pctx = (bunker_parse_ctx_t*)ctx;
|
||||
char decoded[512];
|
||||
int rc = url_decode(val, decoded, sizeof(decoded));
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
|
||||
if (strcmp(key, "relay") == 0) {
|
||||
if (pctx->out->relay_count >= NOSTR_NIP46_MAX_RELAYS) return NOSTR_SUCCESS;
|
||||
safe_copy(pctx->out->relays[pctx->out->relay_count],
|
||||
sizeof(pctx->out->relays[pctx->out->relay_count]), decoded);
|
||||
pctx->out->relay_count++;
|
||||
} else if (strcmp(key, "secret") == 0) {
|
||||
safe_copy(pctx->out->secret, sizeof(pctx->out->secret), decoded);
|
||||
}
|
||||
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
int nostr_nip46_parse_bunker_url(const char* url, nostr_nip46_bunker_url_t* out) {
|
||||
if (!url || !out) return NOSTR_ERROR_INVALID_INPUT;
|
||||
memset(out, 0, sizeof(*out));
|
||||
|
||||
const char* prefix = "bunker://";
|
||||
size_t prefix_len = strlen(prefix);
|
||||
if (strncmp(url, prefix, prefix_len) != 0) {
|
||||
return NOSTR_ERROR_NIP46_INVALID_BUNKER_URL;
|
||||
}
|
||||
|
||||
const char* after = url + prefix_len;
|
||||
const char* q = strchr(after, '?');
|
||||
|
||||
char pubkey[65];
|
||||
if (!q) {
|
||||
safe_copy(pubkey, sizeof(pubkey), after);
|
||||
} else {
|
||||
size_t l = (size_t)(q - after);
|
||||
if (l >= sizeof(pubkey)) return NOSTR_ERROR_NIP46_INVALID_BUNKER_URL;
|
||||
memcpy(pubkey, after, l);
|
||||
pubkey[l] = '\0';
|
||||
}
|
||||
|
||||
if (!is_hex_64(pubkey)) return NOSTR_ERROR_NIP46_INVALID_BUNKER_URL;
|
||||
safe_copy(out->remote_signer_pubkey, sizeof(out->remote_signer_pubkey), pubkey);
|
||||
|
||||
if (q && *(q + 1)) {
|
||||
bunker_parse_ctx_t ctx = { out };
|
||||
int rc = parse_query_pairs(q + 1, bunker_pair_cb, &ctx);
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
}
|
||||
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
nostr_nip46_nostrconnect_url_t* out;
|
||||
} nostrconnect_parse_ctx_t;
|
||||
|
||||
static int nostrconnect_pair_cb(const char* key, const char* val, void* ctx) {
|
||||
nostrconnect_parse_ctx_t* pctx = (nostrconnect_parse_ctx_t*)ctx;
|
||||
char decoded[1024];
|
||||
int rc = url_decode(val, decoded, sizeof(decoded));
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
|
||||
if (strcmp(key, "relay") == 0) {
|
||||
if (pctx->out->relay_count >= NOSTR_NIP46_MAX_RELAYS) return NOSTR_SUCCESS;
|
||||
safe_copy(pctx->out->relays[pctx->out->relay_count],
|
||||
sizeof(pctx->out->relays[pctx->out->relay_count]), decoded);
|
||||
pctx->out->relay_count++;
|
||||
} else if (strcmp(key, "secret") == 0) {
|
||||
safe_copy(pctx->out->secret, sizeof(pctx->out->secret), decoded);
|
||||
} else if (strcmp(key, "perms") == 0) {
|
||||
safe_copy(pctx->out->perms, sizeof(pctx->out->perms), decoded);
|
||||
} else if (strcmp(key, "name") == 0) {
|
||||
safe_copy(pctx->out->name, sizeof(pctx->out->name), decoded);
|
||||
} else if (strcmp(key, "url") == 0) {
|
||||
safe_copy(pctx->out->url, sizeof(pctx->out->url), decoded);
|
||||
} else if (strcmp(key, "image") == 0) {
|
||||
safe_copy(pctx->out->image, sizeof(pctx->out->image), decoded);
|
||||
}
|
||||
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
int nostr_nip46_parse_nostrconnect_url(const char* url, nostr_nip46_nostrconnect_url_t* out) {
|
||||
if (!url || !out) return NOSTR_ERROR_INVALID_INPUT;
|
||||
memset(out, 0, sizeof(*out));
|
||||
|
||||
const char* prefix = "nostrconnect://";
|
||||
size_t prefix_len = strlen(prefix);
|
||||
if (strncmp(url, prefix, prefix_len) != 0) {
|
||||
return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
}
|
||||
|
||||
const char* after = url + prefix_len;
|
||||
const char* q = strchr(after, '?');
|
||||
|
||||
char pubkey[65];
|
||||
if (!q) {
|
||||
safe_copy(pubkey, sizeof(pubkey), after);
|
||||
} else {
|
||||
size_t l = (size_t)(q - after);
|
||||
if (l >= sizeof(pubkey)) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
memcpy(pubkey, after, l);
|
||||
pubkey[l] = '\0';
|
||||
}
|
||||
|
||||
if (!is_hex_64(pubkey)) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
safe_copy(out->client_pubkey, sizeof(out->client_pubkey), pubkey);
|
||||
|
||||
if (q && *(q + 1)) {
|
||||
nostrconnect_parse_ctx_t ctx = { out };
|
||||
int rc = parse_query_pairs(q + 1, nostrconnect_pair_cb, &ctx);
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
}
|
||||
|
||||
if (out->relay_count <= 0 || out->secret[0] == '\0') {
|
||||
return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
}
|
||||
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
int nostr_nip46_create_bunker_url(const nostr_nip46_bunker_url_t* in, char* output, size_t output_size) {
|
||||
if (!in || !output || output_size == 0) return NOSTR_ERROR_INVALID_INPUT;
|
||||
if (!is_hex_64(in->remote_signer_pubkey)) return NOSTR_ERROR_NIP46_INVALID_BUNKER_URL;
|
||||
|
||||
size_t used = (size_t)snprintf(output, output_size, "bunker://%s", in->remote_signer_pubkey);
|
||||
if (used >= output_size) return NOSTR_ERROR_NIP46_INVALID_BUNKER_URL;
|
||||
|
||||
int first = 1;
|
||||
for (int i = 0; i < in->relay_count; i++) {
|
||||
char enc[768];
|
||||
int rc = url_encode(in->relays[i], enc, sizeof(enc));
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
|
||||
int wrote = snprintf(output + used, output_size - used, "%crelay=%s", first ? '?' : '&', enc);
|
||||
if (wrote < 0 || (size_t)wrote >= output_size - used) return NOSTR_ERROR_NIP46_INVALID_BUNKER_URL;
|
||||
used += (size_t)wrote;
|
||||
first = 0;
|
||||
}
|
||||
|
||||
if (in->secret[0]) {
|
||||
char encs[512];
|
||||
int rc = url_encode(in->secret, encs, sizeof(encs));
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
|
||||
int wrote = snprintf(output + used, output_size - used, "%csecret=%s", first ? '?' : '&', encs);
|
||||
if (wrote < 0 || (size_t)wrote >= output_size - used) return NOSTR_ERROR_NIP46_INVALID_BUNKER_URL;
|
||||
}
|
||||
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
int nostr_nip46_create_nostrconnect_url(const nostr_nip46_nostrconnect_url_t* in,
|
||||
char* output,
|
||||
size_t output_size) {
|
||||
if (!in || !output || output_size == 0) return NOSTR_ERROR_INVALID_INPUT;
|
||||
if (!is_hex_64(in->client_pubkey)) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
if (in->relay_count <= 0 || in->secret[0] == '\0') return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
|
||||
size_t used = (size_t)snprintf(output, output_size, "nostrconnect://%s", in->client_pubkey);
|
||||
if (used >= output_size) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
|
||||
int first = 1;
|
||||
for (int i = 0; i < in->relay_count; i++) {
|
||||
char enc[768];
|
||||
int rc = url_encode(in->relays[i], enc, sizeof(enc));
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
|
||||
int wrote = snprintf(output + used, output_size - used, "%crelay=%s", first ? '?' : '&', enc);
|
||||
if (wrote < 0 || (size_t)wrote >= output_size - used) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
used += (size_t)wrote;
|
||||
first = 0;
|
||||
}
|
||||
|
||||
char enc_secret[512];
|
||||
int rc = url_encode(in->secret, enc_secret, sizeof(enc_secret));
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
|
||||
int wrote = snprintf(output + used, output_size - used, "%csecret=%s", first ? '?' : '&', enc_secret);
|
||||
if (wrote < 0 || (size_t)wrote >= output_size - used) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
used += (size_t)wrote;
|
||||
|
||||
if (in->perms[0]) {
|
||||
char enc[1024];
|
||||
rc = url_encode(in->perms, enc, sizeof(enc));
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
wrote = snprintf(output + used, output_size - used, "&perms=%s", enc);
|
||||
if (wrote < 0 || (size_t)wrote >= output_size - used) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
used += (size_t)wrote;
|
||||
}
|
||||
|
||||
if (in->name[0]) {
|
||||
char enc[512];
|
||||
rc = url_encode(in->name, enc, sizeof(enc));
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
wrote = snprintf(output + used, output_size - used, "&name=%s", enc);
|
||||
if (wrote < 0 || (size_t)wrote >= output_size - used) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
used += (size_t)wrote;
|
||||
}
|
||||
|
||||
if (in->url[0]) {
|
||||
char enc[768];
|
||||
rc = url_encode(in->url, enc, sizeof(enc));
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
wrote = snprintf(output + used, output_size - used, "&url=%s", enc);
|
||||
if (wrote < 0 || (size_t)wrote >= output_size - used) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
used += (size_t)wrote;
|
||||
}
|
||||
|
||||
if (in->image[0]) {
|
||||
char enc[768];
|
||||
rc = url_encode(in->image, enc, sizeof(enc));
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
wrote = snprintf(output + used, output_size - used, "&image=%s", enc);
|
||||
if (wrote < 0 || (size_t)wrote >= output_size - used) return NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT;
|
||||
}
|
||||
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
int nostr_nip46_client_session_init(nostr_nip46_client_session_t* session,
|
||||
const unsigned char* client_private_key,
|
||||
const char* bunker_url) {
|
||||
if (!session || !client_private_key || !bunker_url) return NOSTR_ERROR_INVALID_INPUT;
|
||||
|
||||
memset(session, 0, sizeof(*session));
|
||||
memcpy(session->client_private_key, client_private_key, 32);
|
||||
|
||||
unsigned char client_pub[32];
|
||||
if (nostr_ec_public_key_from_private_key(client_private_key, client_pub) != 0) {
|
||||
return NOSTR_ERROR_CRYPTO_FAILED;
|
||||
}
|
||||
nostr_bytes_to_hex(client_pub, 32, session->client_pubkey_hex);
|
||||
|
||||
nostr_nip46_bunker_url_t parsed;
|
||||
int rc = nostr_nip46_parse_bunker_url(bunker_url, &parsed);
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
|
||||
safe_copy(session->remote_signer_pubkey_hex, sizeof(session->remote_signer_pubkey_hex), parsed.remote_signer_pubkey);
|
||||
if (nostr_hex_to_bytes(parsed.remote_signer_pubkey, session->remote_signer_pubkey, 32) != 0) {
|
||||
return NOSTR_ERROR_NIP46_INVALID_BUNKER_URL;
|
||||
}
|
||||
|
||||
session->relay_count = parsed.relay_count;
|
||||
for (int i = 0; i < parsed.relay_count; i++) {
|
||||
safe_copy(session->relays[i], sizeof(session->relays[i]), parsed.relays[i]);
|
||||
}
|
||||
|
||||
session->connected = 0;
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
void nostr_nip46_client_session_destroy(nostr_nip46_client_session_t* session) {
|
||||
if (!session) return;
|
||||
memset(session, 0, sizeof(*session));
|
||||
}
|
||||
|
||||
static int client_make_request_event(nostr_nip46_client_session_t* session,
|
||||
nostr_nip46_method_t method,
|
||||
const char** params,
|
||||
int param_count,
|
||||
cJSON** request_event_out) {
|
||||
if (!session || !request_event_out) return NOSTR_ERROR_INVALID_INPUT;
|
||||
|
||||
char req_id[NOSTR_NIP46_MAX_REQUEST_ID_LEN];
|
||||
int rc = nostr_nip46_generate_request_id(req_id, sizeof(req_id));
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
|
||||
nostr_nip46_request_t req;
|
||||
rc = nostr_nip46_create_request(req_id, method, params, param_count, &req);
|
||||
if (rc != NOSTR_SUCCESS) return rc;
|
||||
|
||||
cJSON* evt = nostr_nip46_create_request_event(&req, session->client_private_key,
|
||||
session->remote_signer_pubkey, 0);
|
||||
nostr_nip46_free_request(&req);
|
||||
if (!evt) return NOSTR_ERROR_NIP46_ENCRYPTION_FAILED;
|
||||
|
||||
*request_event_out = evt;
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
int nostr_nip46_client_connect(nostr_nip46_client_session_t* session,
|
||||
const char* optional_secret,
|
||||
const char* optional_permissions,
|
||||
cJSON** request_event_out) {
|
||||
if (!session || !request_event_out) return NOSTR_ERROR_INVALID_INPUT;
|
||||
|
||||
const char* params[3];
|
||||
int count = 1;
|
||||
params[0] = session->remote_signer_pubkey_hex;
|
||||
|
||||
if (optional_secret && optional_secret[0]) {
|
||||
params[count++] = optional_secret;
|
||||
}
|
||||
if (optional_permissions && optional_permissions[0]) {
|
||||
params[count++] = optional_permissions;
|
||||
}
|
||||
|
||||
return client_make_request_event(session, NOSTR_NIP46_METHOD_CONNECT, params, count, request_event_out);
|
||||
}
|
||||
|
||||
int nostr_nip46_client_get_public_key(nostr_nip46_client_session_t* session,
|
||||
cJSON** request_event_out) {
|
||||
return client_make_request_event(session, NOSTR_NIP46_METHOD_GET_PUBLIC_KEY, NULL, 0, request_event_out);
|
||||
}
|
||||
|
||||
int nostr_nip46_client_ping(nostr_nip46_client_session_t* session,
|
||||
cJSON** request_event_out) {
|
||||
return client_make_request_event(session, NOSTR_NIP46_METHOD_PING, NULL, 0, request_event_out);
|
||||
}
|
||||
|
||||
int nostr_nip46_client_sign_event(nostr_nip46_client_session_t* session,
|
||||
cJSON* unsigned_event,
|
||||
cJSON** request_event_out) {
|
||||
if (!session || !unsigned_event || !request_event_out) return NOSTR_ERROR_INVALID_INPUT;
|
||||
|
||||
char* ev = cJSON_PrintUnformatted(unsigned_event);
|
||||
if (!ev) return NOSTR_ERROR_MEMORY_FAILED;
|
||||
|
||||
const char* params[1] = { ev };
|
||||
int rc = client_make_request_event(session, NOSTR_NIP46_METHOD_SIGN_EVENT, params, 1, request_event_out);
|
||||
free(ev);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int nostr_nip46_signer_session_init(nostr_nip46_signer_session_t* session,
|
||||
const unsigned char* signer_private_key,
|
||||
const unsigned char* user_private_key,
|
||||
const char** relays,
|
||||
int relay_count) {
|
||||
if (!session || !signer_private_key || !user_private_key) return NOSTR_ERROR_INVALID_INPUT;
|
||||
|
||||
memset(session, 0, sizeof(*session));
|
||||
memcpy(session->signer_private_key, signer_private_key, 32);
|
||||
memcpy(session->user_private_key, user_private_key, 32);
|
||||
|
||||
unsigned char signer_pub[32];
|
||||
unsigned char user_pub[32];
|
||||
|
||||
if (nostr_ec_public_key_from_private_key(signer_private_key, signer_pub) != 0) return NOSTR_ERROR_CRYPTO_FAILED;
|
||||
if (nostr_ec_public_key_from_private_key(user_private_key, user_pub) != 0) return NOSTR_ERROR_CRYPTO_FAILED;
|
||||
|
||||
nostr_bytes_to_hex(signer_pub, 32, session->signer_pubkey_hex);
|
||||
nostr_bytes_to_hex(user_pub, 32, session->user_pubkey_hex);
|
||||
|
||||
if (relay_count > NOSTR_NIP46_MAX_RELAYS) relay_count = NOSTR_NIP46_MAX_RELAYS;
|
||||
session->relay_count = relay_count;
|
||||
for (int i = 0; i < relay_count; i++) {
|
||||
safe_copy(session->relays[i], sizeof(session->relays[i]), relays[i]);
|
||||
}
|
||||
|
||||
session->connected = 0;
|
||||
return NOSTR_SUCCESS;
|
||||
}
|
||||
|
||||
void nostr_nip46_signer_session_destroy(nostr_nip46_signer_session_t* session) {
|
||||
if (!session) return;
|
||||
memset(session, 0, sizeof(*session));
|
||||
}
|
||||
|
||||
int nostr_nip46_signer_create_bunker_url(const nostr_nip46_signer_session_t* session,
|
||||
const char* optional_secret,
|
||||
char* output,
|
||||
size_t output_size) {
|
||||
if (!session || !output) return NOSTR_ERROR_INVALID_INPUT;
|
||||
|
||||
nostr_nip46_bunker_url_t b;
|
||||
memset(&b, 0, sizeof(b));
|
||||
safe_copy(b.remote_signer_pubkey, sizeof(b.remote_signer_pubkey), session->signer_pubkey_hex);
|
||||
b.relay_count = session->relay_count;
|
||||
for (int i = 0; i < session->relay_count; i++) {
|
||||
safe_copy(b.relays[i], sizeof(b.relays[i]), session->relays[i]);
|
||||
}
|
||||
if (optional_secret) {
|
||||
safe_copy(b.secret, sizeof(b.secret), optional_secret);
|
||||
}
|
||||
|
||||
return nostr_nip46_create_bunker_url(&b, output, output_size);
|
||||
}
|
||||
|
||||
static int signer_make_ok(const char* id, const char* result, nostr_nip46_response_t* out) {
|
||||
return nostr_nip46_create_response(id, result, NULL, out);
|
||||
}
|
||||
|
||||
static int signer_make_err(const char* id, const char* err, nostr_nip46_response_t* out) {
|
||||
return nostr_nip46_create_response(id, "", err, out);
|
||||
}
|
||||
|
||||
int nostr_nip46_signer_handle_request(nostr_nip46_signer_session_t* session,
|
||||
const nostr_nip46_request_t* request,
|
||||
nostr_nip46_response_t* response_out) {
|
||||
if (!session || !request || !response_out) return NOSTR_ERROR_INVALID_INPUT;
|
||||
|
||||
switch (request->method) {
|
||||
case NOSTR_NIP46_METHOD_CONNECT: {
|
||||
if (request->param_count >= 1 && request->params[0] && request->params[0][0]) {
|
||||
if (strcmp(request->params[0], session->signer_pubkey_hex) != 0) {
|
||||
return signer_make_err(request->id, "remote signer pubkey mismatch", response_out);
|
||||
}
|
||||
}
|
||||
session->connected = 1;
|
||||
if (request->param_count >= 2 && request->params[1] && request->params[1][0]) {
|
||||
return signer_make_ok(request->id, request->params[1], response_out);
|
||||
}
|
||||
return signer_make_ok(request->id, "ack", response_out);
|
||||
}
|
||||
|
||||
case NOSTR_NIP46_METHOD_PING:
|
||||
return signer_make_ok(request->id, "pong", response_out);
|
||||
|
||||
case NOSTR_NIP46_METHOD_GET_PUBLIC_KEY:
|
||||
return signer_make_ok(request->id, session->user_pubkey_hex, response_out);
|
||||
|
||||
case NOSTR_NIP46_METHOD_SIGN_EVENT: {
|
||||
if (request->param_count < 1 || !request->params[0]) {
|
||||
return signer_make_err(request->id, "missing sign_event payload", response_out);
|
||||
}
|
||||
|
||||
cJSON* in = cJSON_Parse(request->params[0]);
|
||||
if (!in) return signer_make_err(request->id, "invalid sign_event JSON", response_out);
|
||||
|
||||
cJSON* kind = cJSON_GetObjectItem(in, "kind");
|
||||
cJSON* content = cJSON_GetObjectItem(in, "content");
|
||||
cJSON* tags = cJSON_GetObjectItem(in, "tags");
|
||||
cJSON* created = cJSON_GetObjectItem(in, "created_at");
|
||||
|
||||
if (!cJSON_IsNumber(kind) || !cJSON_IsString(content)) {
|
||||
cJSON_Delete(in);
|
||||
return signer_make_err(request->id, "invalid sign_event fields", response_out);
|
||||
}
|
||||
|
||||
time_t ts = 0;
|
||||
if (created && cJSON_IsNumber(created)) {
|
||||
ts = (time_t)cJSON_GetNumberValue(created);
|
||||
}
|
||||
|
||||
cJSON* signed_evt = nostr_create_and_sign_event((int)cJSON_GetNumberValue(kind),
|
||||
cJSON_GetStringValue(content),
|
||||
cJSON_IsArray(tags) ? tags : NULL,
|
||||
session->user_private_key,
|
||||
ts);
|
||||
cJSON_Delete(in);
|
||||
if (!signed_evt) {
|
||||
return signer_make_err(request->id, "failed to sign event", response_out);
|
||||
}
|
||||
|
||||
char* signed_json = cJSON_PrintUnformatted(signed_evt);
|
||||
cJSON_Delete(signed_evt);
|
||||
if (!signed_json) {
|
||||
return signer_make_err(request->id, "failed to encode signed event", response_out);
|
||||
}
|
||||
|
||||
int rc = signer_make_ok(request->id, signed_json, response_out);
|
||||
free(signed_json);
|
||||
return rc;
|
||||
}
|
||||
|
||||
case NOSTR_NIP46_METHOD_NIP04_ENCRYPT:
|
||||
case NOSTR_NIP46_METHOD_NIP04_DECRYPT:
|
||||
case NOSTR_NIP46_METHOD_NIP44_ENCRYPT:
|
||||
case NOSTR_NIP46_METHOD_NIP44_DECRYPT: {
|
||||
if (request->param_count < 2 || !request->params[0] || !request->params[1]) {
|
||||
return signer_make_err(request->id, "missing crypto params", response_out);
|
||||
}
|
||||
|
||||
unsigned char peer_pub[32];
|
||||
if (nostr_hex_to_bytes(request->params[0], peer_pub, 32) != 0) {
|
||||
return signer_make_err(request->id, "invalid peer pubkey", response_out);
|
||||
}
|
||||
|
||||
char out_buf[NOSTR_NIP46_MAX_PAYLOAD_LEN];
|
||||
int rc;
|
||||
if (request->method == NOSTR_NIP46_METHOD_NIP04_ENCRYPT) {
|
||||
rc = nostr_nip04_encrypt(session->user_private_key, peer_pub, request->params[1], out_buf, sizeof(out_buf));
|
||||
} else if (request->method == NOSTR_NIP46_METHOD_NIP04_DECRYPT) {
|
||||
rc = nostr_nip04_decrypt(session->user_private_key, peer_pub, request->params[1], out_buf, sizeof(out_buf));
|
||||
} else if (request->method == NOSTR_NIP46_METHOD_NIP44_ENCRYPT) {
|
||||
rc = nostr_nip44_encrypt(session->user_private_key, peer_pub, request->params[1], out_buf, sizeof(out_buf));
|
||||
} else {
|
||||
rc = nostr_nip44_decrypt(session->user_private_key, peer_pub, request->params[1], out_buf, sizeof(out_buf));
|
||||
}
|
||||
|
||||
if (rc != NOSTR_SUCCESS) {
|
||||
return signer_make_err(request->id, nostr_strerror(rc), response_out);
|
||||
}
|
||||
|
||||
return signer_make_ok(request->id, out_buf, response_out);
|
||||
}
|
||||
|
||||
default:
|
||||
return signer_make_err(request->id, "unknown method", response_out);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
/*
|
||||
* NIP-46: Nostr Remote Signing
|
||||
* https://github.com/nostr-protocol/nips/blob/master/46.md
|
||||
*/
|
||||
|
||||
#ifndef NOSTR_NIP046_H
|
||||
#define NOSTR_NIP046_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <time.h>
|
||||
#include "nostr_common.h"
|
||||
#include "nip001.h"
|
||||
#include "../cjson/cJSON.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define NOSTR_NIP46_EVENT_KIND 24133
|
||||
#define NOSTR_NIP46_MAX_RELAYS 8
|
||||
#define NOSTR_NIP46_MAX_RELAY_URL_LEN 256
|
||||
#define NOSTR_NIP46_MAX_SECRET_LEN 128
|
||||
#define NOSTR_NIP46_MAX_REQUEST_ID_LEN 65
|
||||
#define NOSTR_NIP46_MAX_METHOD_LEN 32
|
||||
#define NOSTR_NIP46_MAX_URL_LEN 2048
|
||||
#define NOSTR_NIP46_MAX_PAYLOAD_LEN 65536
|
||||
|
||||
typedef enum {
|
||||
NOSTR_NIP46_CONN_BUNKER = 0,
|
||||
NOSTR_NIP46_CONN_NOSTRCONNECT = 1
|
||||
} nostr_nip46_connection_type_t;
|
||||
|
||||
typedef enum {
|
||||
NOSTR_NIP46_METHOD_CONNECT = 0,
|
||||
NOSTR_NIP46_METHOD_SIGN_EVENT,
|
||||
NOSTR_NIP46_METHOD_PING,
|
||||
NOSTR_NIP46_METHOD_GET_PUBLIC_KEY,
|
||||
NOSTR_NIP46_METHOD_NIP04_ENCRYPT,
|
||||
NOSTR_NIP46_METHOD_NIP04_DECRYPT,
|
||||
NOSTR_NIP46_METHOD_NIP44_ENCRYPT,
|
||||
NOSTR_NIP46_METHOD_NIP44_DECRYPT,
|
||||
NOSTR_NIP46_METHOD_UNKNOWN
|
||||
} nostr_nip46_method_t;
|
||||
|
||||
typedef struct {
|
||||
char remote_signer_pubkey[65];
|
||||
char relays[NOSTR_NIP46_MAX_RELAYS][NOSTR_NIP46_MAX_RELAY_URL_LEN];
|
||||
int relay_count;
|
||||
char secret[NOSTR_NIP46_MAX_SECRET_LEN];
|
||||
} nostr_nip46_bunker_url_t;
|
||||
|
||||
typedef struct {
|
||||
char client_pubkey[65];
|
||||
char relays[NOSTR_NIP46_MAX_RELAYS][NOSTR_NIP46_MAX_RELAY_URL_LEN];
|
||||
int relay_count;
|
||||
char secret[NOSTR_NIP46_MAX_SECRET_LEN];
|
||||
char perms[512];
|
||||
char name[128];
|
||||
char url[256];
|
||||
char image[256];
|
||||
} nostr_nip46_nostrconnect_url_t;
|
||||
|
||||
typedef struct {
|
||||
char id[NOSTR_NIP46_MAX_REQUEST_ID_LEN];
|
||||
nostr_nip46_method_t method;
|
||||
char method_str[NOSTR_NIP46_MAX_METHOD_LEN];
|
||||
char** params;
|
||||
int param_count;
|
||||
} nostr_nip46_request_t;
|
||||
|
||||
typedef struct {
|
||||
char id[NOSTR_NIP46_MAX_REQUEST_ID_LEN];
|
||||
char* result;
|
||||
char* error;
|
||||
} nostr_nip46_response_t;
|
||||
|
||||
typedef struct {
|
||||
unsigned char client_private_key[32];
|
||||
char client_pubkey_hex[65];
|
||||
char remote_signer_pubkey_hex[65];
|
||||
unsigned char remote_signer_pubkey[32];
|
||||
char user_pubkey_hex[65];
|
||||
char relays[NOSTR_NIP46_MAX_RELAYS][NOSTR_NIP46_MAX_RELAY_URL_LEN];
|
||||
int relay_count;
|
||||
int connected;
|
||||
} nostr_nip46_client_session_t;
|
||||
|
||||
typedef struct {
|
||||
unsigned char signer_private_key[32];
|
||||
char signer_pubkey_hex[65];
|
||||
unsigned char user_private_key[32];
|
||||
char user_pubkey_hex[65];
|
||||
char client_pubkey_hex[65];
|
||||
unsigned char client_pubkey[32];
|
||||
char relays[NOSTR_NIP46_MAX_RELAYS][NOSTR_NIP46_MAX_RELAY_URL_LEN];
|
||||
int relay_count;
|
||||
int connected;
|
||||
} nostr_nip46_signer_session_t;
|
||||
|
||||
/* URL parsing/creation */
|
||||
int nostr_nip46_parse_bunker_url(const char* url, nostr_nip46_bunker_url_t* out);
|
||||
int nostr_nip46_parse_nostrconnect_url(const char* url, nostr_nip46_nostrconnect_url_t* out);
|
||||
int nostr_nip46_create_bunker_url(const nostr_nip46_bunker_url_t* in, char* output, size_t output_size);
|
||||
int nostr_nip46_create_nostrconnect_url(const nostr_nip46_nostrconnect_url_t* in, char* output, size_t output_size);
|
||||
|
||||
/* Method conversion */
|
||||
const char* nostr_nip46_method_to_string(nostr_nip46_method_t method);
|
||||
nostr_nip46_method_t nostr_nip46_string_to_method(const char* method);
|
||||
|
||||
/* Request/response object utilities */
|
||||
int nostr_nip46_generate_request_id(char* output, size_t output_size);
|
||||
int nostr_nip46_create_request(const char* id,
|
||||
nostr_nip46_method_t method,
|
||||
const char** params,
|
||||
int param_count,
|
||||
nostr_nip46_request_t* out);
|
||||
int nostr_nip46_create_response(const char* id,
|
||||
const char* result,
|
||||
const char* error,
|
||||
nostr_nip46_response_t* out);
|
||||
int nostr_nip46_parse_request(const char* json_payload, nostr_nip46_request_t* out);
|
||||
int nostr_nip46_parse_response(const char* json_payload, nostr_nip46_response_t* out);
|
||||
void nostr_nip46_free_request(nostr_nip46_request_t* request);
|
||||
void nostr_nip46_free_response(nostr_nip46_response_t* response);
|
||||
|
||||
/* JSON payload serialization */
|
||||
int nostr_nip46_request_to_json(const nostr_nip46_request_t* request, char** output_json);
|
||||
int nostr_nip46_response_to_json(const nostr_nip46_response_t* response, char** output_json);
|
||||
|
||||
/* Event creation/decryption */
|
||||
cJSON* nostr_nip46_create_request_event(const nostr_nip46_request_t* request,
|
||||
const unsigned char* sender_private_key,
|
||||
const unsigned char* recipient_public_key,
|
||||
time_t timestamp);
|
||||
cJSON* nostr_nip46_create_response_event(const nostr_nip46_response_t* response,
|
||||
const unsigned char* sender_private_key,
|
||||
const unsigned char* recipient_public_key,
|
||||
time_t timestamp);
|
||||
int nostr_nip46_decrypt_event(cJSON* event,
|
||||
const unsigned char* recipient_private_key,
|
||||
char* output,
|
||||
size_t output_size);
|
||||
|
||||
/* Client session */
|
||||
int nostr_nip46_client_session_init(nostr_nip46_client_session_t* session,
|
||||
const unsigned char* client_private_key,
|
||||
const char* bunker_url);
|
||||
void nostr_nip46_client_session_destroy(nostr_nip46_client_session_t* session);
|
||||
|
||||
int nostr_nip46_client_connect(nostr_nip46_client_session_t* session,
|
||||
const char* optional_secret,
|
||||
const char* optional_permissions,
|
||||
cJSON** request_event_out);
|
||||
int nostr_nip46_client_get_public_key(nostr_nip46_client_session_t* session,
|
||||
cJSON** request_event_out);
|
||||
int nostr_nip46_client_ping(nostr_nip46_client_session_t* session,
|
||||
cJSON** request_event_out);
|
||||
int nostr_nip46_client_sign_event(nostr_nip46_client_session_t* session,
|
||||
cJSON* unsigned_event,
|
||||
cJSON** request_event_out);
|
||||
|
||||
/* Signer session */
|
||||
int nostr_nip46_signer_session_init(nostr_nip46_signer_session_t* session,
|
||||
const unsigned char* signer_private_key,
|
||||
const unsigned char* user_private_key,
|
||||
const char** relays,
|
||||
int relay_count);
|
||||
void nostr_nip46_signer_session_destroy(nostr_nip46_signer_session_t* session);
|
||||
int nostr_nip46_signer_handle_request(nostr_nip46_signer_session_t* session,
|
||||
const nostr_nip46_request_t* request,
|
||||
nostr_nip46_response_t* response_out);
|
||||
int nostr_nip46_signer_create_bunker_url(const nostr_nip46_signer_session_t* session,
|
||||
const char* optional_secret,
|
||||
char* output,
|
||||
size_t output_size);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* NOSTR_NIP046_H */
|
||||
+16
-10
@@ -26,12 +26,18 @@ static void memory_clear(const void *p, size_t len) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a random timestamp within 2 days in the past (as per NIP-59 spec)
|
||||
* Create a random timestamp within max_delay_sec in the past (configurable)
|
||||
*/
|
||||
static time_t random_past_timestamp(void) {
|
||||
static time_t random_past_timestamp(long max_delay_sec) {
|
||||
time_t now = time(NULL);
|
||||
// Random time up to 2 days (172800 seconds) in the past
|
||||
long random_offset = (long)(rand() % 172800);
|
||||
|
||||
// If max_delay_sec is 0, return current timestamp (no randomization)
|
||||
if (max_delay_sec == 0) {
|
||||
return now;
|
||||
}
|
||||
|
||||
// Random time up to max_delay_sec in the past
|
||||
long random_offset = (long)(rand() % max_delay_sec);
|
||||
return now - random_offset;
|
||||
}
|
||||
|
||||
@@ -104,8 +110,8 @@ cJSON* nostr_nip59_create_rumor(int kind, const char* content, cJSON* tags,
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Use provided timestamp or random past timestamp
|
||||
time_t event_time = (created_at == 0) ? random_past_timestamp() : created_at;
|
||||
// Use provided timestamp or random past timestamp (default to 0 for compatibility)
|
||||
time_t event_time = (created_at == 0) ? random_past_timestamp(0) : created_at;
|
||||
|
||||
// Create event structure (without id and sig - that's what makes it a rumor)
|
||||
cJSON* rumor = cJSON_CreateObject();
|
||||
@@ -142,7 +148,7 @@ cJSON* nostr_nip59_create_rumor(int kind, const char* content, cJSON* tags,
|
||||
* NIP-59: Create a seal (kind 13) wrapping a rumor
|
||||
*/
|
||||
cJSON* nostr_nip59_create_seal(cJSON* rumor, const unsigned char* sender_private_key,
|
||||
const unsigned char* recipient_public_key) {
|
||||
const unsigned char* recipient_public_key, long max_delay_sec) {
|
||||
if (!rumor || !sender_private_key || !recipient_public_key) {
|
||||
return NULL;
|
||||
}
|
||||
@@ -178,7 +184,7 @@ cJSON* nostr_nip59_create_seal(cJSON* rumor, const unsigned char* sender_private
|
||||
return NULL;
|
||||
}
|
||||
|
||||
time_t seal_time = random_past_timestamp();
|
||||
time_t seal_time = random_past_timestamp(max_delay_sec);
|
||||
|
||||
cJSON_AddStringToObject(seal, "pubkey", sender_pubkey_hex);
|
||||
cJSON_AddNumberToObject(seal, "created_at", (double)seal_time);
|
||||
@@ -217,7 +223,7 @@ cJSON* nostr_nip59_create_seal(cJSON* rumor, const unsigned char* sender_private
|
||||
/**
|
||||
* NIP-59: Create a gift wrap (kind 1059) wrapping a seal
|
||||
*/
|
||||
cJSON* nostr_nip59_create_gift_wrap(cJSON* seal, const char* recipient_public_key_hex) {
|
||||
cJSON* nostr_nip59_create_gift_wrap(cJSON* seal, const char* recipient_public_key_hex, long max_delay_sec) {
|
||||
if (!seal || !recipient_public_key_hex) {
|
||||
return NULL;
|
||||
}
|
||||
@@ -272,7 +278,7 @@ cJSON* nostr_nip59_create_gift_wrap(cJSON* seal, const char* recipient_public_ke
|
||||
return NULL;
|
||||
}
|
||||
|
||||
time_t wrap_time = random_past_timestamp();
|
||||
time_t wrap_time = random_past_timestamp(max_delay_sec);
|
||||
|
||||
cJSON_AddStringToObject(gift_wrap, "pubkey", random_pubkey_hex);
|
||||
cJSON_AddNumberToObject(gift_wrap, "created_at", (double)wrap_time);
|
||||
|
||||
+4
-2
@@ -33,19 +33,21 @@ cJSON* nostr_nip59_create_rumor(int kind, const char* content, cJSON* tags,
|
||||
* @param rumor The rumor event to seal (cJSON object)
|
||||
* @param sender_private_key 32-byte sender private key
|
||||
* @param recipient_public_key 32-byte recipient public key (x-only)
|
||||
* @param max_delay_sec Maximum random timestamp delay in seconds (0 = no randomization)
|
||||
* @return cJSON object representing the seal event, or NULL on error
|
||||
*/
|
||||
cJSON* nostr_nip59_create_seal(cJSON* rumor, const unsigned char* sender_private_key,
|
||||
const unsigned char* recipient_public_key);
|
||||
const unsigned char* recipient_public_key, long max_delay_sec);
|
||||
|
||||
/**
|
||||
* NIP-59: Create a gift wrap (kind 1059) wrapping a seal
|
||||
*
|
||||
* @param seal The seal event to wrap (cJSON object)
|
||||
* @param recipient_public_key_hex Recipient's public key in hex format
|
||||
* @param max_delay_sec Maximum random timestamp delay in seconds (0 = no randomization)
|
||||
* @return cJSON object representing the gift wrap event, or NULL on error
|
||||
*/
|
||||
cJSON* nostr_nip59_create_gift_wrap(cJSON* seal, const char* recipient_public_key_hex);
|
||||
cJSON* nostr_nip59_create_gift_wrap(cJSON* seal, const char* recipient_public_key_hex, long max_delay_sec);
|
||||
|
||||
/**
|
||||
* NIP-59: Unwrap a gift wrap to get the seal
|
||||
|
||||
@@ -52,6 +52,18 @@ const char* nostr_strerror(int error_code) {
|
||||
case NOSTR_ERROR_NIP42_INVALID_MESSAGE_FORMAT: return "NIP-42: Invalid message format";
|
||||
case NOSTR_ERROR_NIP42_CHALLENGE_TOO_SHORT: return "NIP-42: Challenge too short";
|
||||
case NOSTR_ERROR_NIP42_CHALLENGE_TOO_LONG: return "NIP-42: Challenge too long";
|
||||
case NOSTR_ERROR_NIP46_INVALID_BUNKER_URL: return "NIP-46: Invalid bunker URL";
|
||||
case NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT: return "NIP-46: Invalid nostrconnect URL";
|
||||
case NOSTR_ERROR_NIP46_INVALID_REQUEST: return "NIP-46: Invalid request payload";
|
||||
case NOSTR_ERROR_NIP46_INVALID_RESPONSE: return "NIP-46: Invalid response payload";
|
||||
case NOSTR_ERROR_NIP46_ENCRYPTION_FAILED: return "NIP-46: Encryption failed";
|
||||
case NOSTR_ERROR_NIP46_DECRYPTION_FAILED: return "NIP-46: Decryption failed";
|
||||
case NOSTR_ERROR_NIP46_CONNECTION_FAILED: return "NIP-46: Connection failed";
|
||||
case NOSTR_ERROR_NIP46_TIMEOUT: return "NIP-46: Timeout";
|
||||
case NOSTR_ERROR_NIP46_SECRET_MISMATCH: return "NIP-46: Secret mismatch";
|
||||
case NOSTR_ERROR_NIP46_UNKNOWN_METHOD: return "NIP-46: Unknown method";
|
||||
case NOSTR_ERROR_NIP46_AUTH_CHALLENGE: return "NIP-46: Auth challenge required";
|
||||
case NOSTR_ERROR_NIP46_NOT_CONNECTED: return "NIP-46: Not connected";
|
||||
default: return "Unknown error";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +62,20 @@
|
||||
#define NOSTR_ERROR_NIP42_CHALLENGE_TOO_SHORT -207
|
||||
#define NOSTR_ERROR_NIP42_CHALLENGE_TOO_LONG -208
|
||||
|
||||
// NIP-46 Remote Signing error codes
|
||||
#define NOSTR_ERROR_NIP46_INVALID_BUNKER_URL -300
|
||||
#define NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT -301
|
||||
#define NOSTR_ERROR_NIP46_INVALID_REQUEST -302
|
||||
#define NOSTR_ERROR_NIP46_INVALID_RESPONSE -303
|
||||
#define NOSTR_ERROR_NIP46_ENCRYPTION_FAILED -304
|
||||
#define NOSTR_ERROR_NIP46_DECRYPTION_FAILED -305
|
||||
#define NOSTR_ERROR_NIP46_CONNECTION_FAILED -306
|
||||
#define NOSTR_ERROR_NIP46_TIMEOUT -307
|
||||
#define NOSTR_ERROR_NIP46_SECRET_MISMATCH -308
|
||||
#define NOSTR_ERROR_NIP46_UNKNOWN_METHOD -309
|
||||
#define NOSTR_ERROR_NIP46_AUTH_CHALLENGE -310
|
||||
#define NOSTR_ERROR_NIP46_NOT_CONNECTED -311
|
||||
|
||||
// Constants
|
||||
#define NOSTR_PRIVATE_KEY_SIZE 32
|
||||
#define NOSTR_PUBLIC_KEY_SIZE 32
|
||||
@@ -72,11 +86,11 @@
|
||||
#define NIP05_DEFAULT_TIMEOUT 10
|
||||
|
||||
// NIP-04 Constants
|
||||
#define NOSTR_NIP04_MAX_PLAINTEXT_SIZE 16777216 // 16MB
|
||||
#define NOSTR_NIP04_MAX_PLAINTEXT_SIZE 1048576 // 1MB
|
||||
#define NOSTR_NIP04_MAX_ENCRYPTED_SIZE 22369621 // ~21.3MB (accounts for base64 overhead + IV)
|
||||
|
||||
// NIP-44 Constants
|
||||
#define NOSTR_NIP44_MAX_PLAINTEXT_SIZE 65536 // 64KB max plaintext (matches crypto header)
|
||||
// NIP-44 Constants
|
||||
#define NOSTR_NIP44_MAX_PLAINTEXT_SIZE 65535 // 64KB - 1 (NIP-44 spec compliant)
|
||||
|
||||
// Forward declaration for cJSON (to avoid requiring cJSON.h in header)
|
||||
struct cJSON;
|
||||
|
||||
+25
-4
@@ -2,10 +2,10 @@
|
||||
#define NOSTR_CORE_H
|
||||
|
||||
// Version information (auto-updated by increment_and_push.sh)
|
||||
#define VERSION "v0.4.5"
|
||||
#define VERSION "v0.4.10"
|
||||
#define VERSION_MAJOR 0
|
||||
#define VERSION_MINOR 4
|
||||
#define VERSION_PATCH 5
|
||||
#define VERSION_PATCH 10
|
||||
|
||||
/*
|
||||
* NOSTR Core Library - Complete API Reference
|
||||
@@ -49,6 +49,13 @@
|
||||
* - nostr_nip44_encrypt_with_nonce() -> Encrypt with specific nonce (testing)
|
||||
* - nostr_nip44_decrypt() -> Decrypt ChaCha20 + HMAC messages
|
||||
*
|
||||
* NIP-46 REMOTE SIGNING:
|
||||
* - nostr_nip46_parse_bunker_url() -> Parse bunker:// connection tokens
|
||||
* - nostr_nip46_parse_nostrconnect_url() -> Parse nostrconnect:// connection tokens
|
||||
* - nostr_nip46_create_request_event() -> Create encrypted kind 24133 request events
|
||||
* - nostr_nip46_create_response_event() -> Create encrypted kind 24133 response events
|
||||
* - nostr_nip46_signer_handle_request() -> Handle signer-side RPC requests
|
||||
*
|
||||
* NIP-59 GIFT WRAP:
|
||||
* - nostr_nip59_create_rumor() -> Create unsigned event (rumor)
|
||||
* - nostr_nip59_create_seal() -> Seal rumor with sender's key (kind 13)
|
||||
@@ -180,6 +187,7 @@ extern "C" {
|
||||
#include "nip021.h" // nostr: URI scheme
|
||||
#include "nip042.h" // Authentication of clients to relays
|
||||
#include "nip044.h" // Encryption (modern)
|
||||
#include "nip046.h" // Remote signing
|
||||
#include "nip059.h" // Gift Wrap
|
||||
|
||||
// Authentication and request validation system
|
||||
@@ -241,6 +249,7 @@ nostr_relay_pool_t* nostr_relay_pool_create(nostr_pool_reconnect_config_t* confi
|
||||
nostr_pool_reconnect_config_t* nostr_pool_reconnect_config_default(void);
|
||||
int nostr_relay_pool_add_relay(nostr_relay_pool_t* pool, const char* relay_url);
|
||||
int nostr_relay_pool_remove_relay(nostr_relay_pool_t* pool, const char* relay_url);
|
||||
int nostr_relay_pool_set_auth(nostr_relay_pool_t* pool, const unsigned char* private_key, int enable);
|
||||
void nostr_relay_pool_destroy(nostr_relay_pool_t* pool);
|
||||
|
||||
// Subscription management
|
||||
@@ -288,11 +297,23 @@ cJSON* nostr_relay_pool_get_event(
|
||||
int relay_count,
|
||||
cJSON* filter,
|
||||
int timeout_ms);
|
||||
int nostr_relay_pool_publish(
|
||||
// Async publish callback typedef
|
||||
typedef void (*publish_response_callback_t)(
|
||||
const char* relay_url,
|
||||
const char* event_id,
|
||||
int success, // 1 for OK, 0 for rejection
|
||||
const char* message, // Error message if rejected, NULL if success
|
||||
void* user_data
|
||||
);
|
||||
|
||||
// Async publish function (only async version available)
|
||||
int nostr_relay_pool_publish_async(
|
||||
nostr_relay_pool_t* pool,
|
||||
const char** relay_urls,
|
||||
int relay_count,
|
||||
cJSON* event);
|
||||
cJSON* event,
|
||||
publish_response_callback_t callback,
|
||||
void* user_data);
|
||||
|
||||
// Status and statistics functions
|
||||
nostr_pool_relay_status_t nostr_relay_pool_get_relay_status(
|
||||
|
||||
@@ -580,23 +580,30 @@ static int tls_recv(void* ctx, void* data, size_t len, int timeout_ms) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Check if SSL has pending data first
|
||||
if (SSL_pending(tls->ssl) == 0 && timeout_ms > 0) {
|
||||
// Only use select() if no data is pending in SSL buffers
|
||||
// Always use select() to ensure proper blocking behavior
|
||||
// If SSL has pending data, use zero timeout to return immediately
|
||||
// Otherwise use the full timeout to block until data arrives
|
||||
if (timeout_ms > 0) {
|
||||
fd_set readfds;
|
||||
struct timeval tv;
|
||||
|
||||
FD_ZERO(&readfds);
|
||||
FD_SET(tls->socket_fd, &readfds);
|
||||
|
||||
tv.tv_sec = timeout_ms / 1000;
|
||||
tv.tv_usec = (timeout_ms % 1000) * 1000;
|
||||
// If SSL has buffered data, use zero timeout; otherwise use full timeout
|
||||
if (SSL_pending(tls->ssl) > 0) {
|
||||
tv.tv_sec = 0;
|
||||
tv.tv_usec = 0;
|
||||
} else {
|
||||
tv.tv_sec = timeout_ms / 1000;
|
||||
tv.tv_usec = (timeout_ms % 1000) * 1000;
|
||||
}
|
||||
|
||||
int result = select(tls->socket_fd + 1, &readfds, NULL, NULL, &tv);
|
||||
if (result < 0) {
|
||||
return -1;
|
||||
} else if (result == 0) {
|
||||
return -1; // Timeout
|
||||
} else if (result == 0 && SSL_pending(tls->ssl) == 0) {
|
||||
return -1; // Timeout with no pending data
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
# NIP-42 Authentication Support for core_relay_pool.c
|
||||
|
||||
## Problem Statement
|
||||
|
||||
The relay pool ([`core_relay_pool.c`](nostr_core/core_relay_pool.c)) does not handle NIP-42 authentication. When a relay sends an `AUTH` challenge message, the pool silently ignores it, causing:
|
||||
|
||||
- Subscriptions to fail on auth-required relays (events never delivered)
|
||||
- Publishes to be rejected with `auth-required:` errors
|
||||
- No visibility into authentication state per relay
|
||||
|
||||
The synchronous relay functions in [`core_relays.c`](nostr_core/core_relays.c) already have full NIP-42 support (lines 58-63, 211-239, 595-624). The NIP-42 primitives in [`nip042.c`](nostr_core/nip042.c) / [`nip042.h`](nostr_core/nip042.h) are production-ready. This plan wires them into the pool.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[Relay sends AUTH challenge] --> B[process_relay_message parses AUTH]
|
||||
B --> C{pool has private_key?}
|
||||
C -->|No| D[Log warning, mark relay auth_state = CHALLENGE_RECEIVED]
|
||||
C -->|Yes| E[nostr_nip42_create_auth_event]
|
||||
E --> F[nostr_nip42_create_auth_message]
|
||||
F --> G[nostr_ws_send_text to relay]
|
||||
G --> H[Mark relay auth_state = AUTHENTICATING]
|
||||
H --> I[Relay sends OK for auth event]
|
||||
I --> J[Mark relay auth_state = AUTHENTICATED]
|
||||
|
||||
K[Relay sends OK with auth-required] --> L[process_relay_message detects prefix]
|
||||
L --> M{relay already authenticated?}
|
||||
M -->|No| N[Trigger auth flow if private_key available]
|
||||
M -->|Yes| O[Surface as publish failure]
|
||||
|
||||
P[Relay sends NOTICE] --> Q{Contains auth-required?}
|
||||
Q -->|Yes| R[Log auth-required notice]
|
||||
Q -->|No| S[Ignore or log]
|
||||
```
|
||||
|
||||
## Detailed Changes
|
||||
|
||||
### 1. Add NIP-42 include to core_relay_pool.c
|
||||
|
||||
Add `#include "nip042.h"` alongside the existing includes at the top of [`core_relay_pool.c`](nostr_core/core_relay_pool.c:27).
|
||||
|
||||
### 2. Add auth fields to `relay_connection_t` struct
|
||||
|
||||
Modeled after [`core_relays.c:58-63`](nostr_core/core_relays.c:58), add to the [`relay_connection_t`](nostr_core/core_relay_pool.c:76) struct:
|
||||
|
||||
```c
|
||||
// NIP-42 Authentication fields
|
||||
nostr_auth_state_t auth_state;
|
||||
char auth_challenge[NOSTR_NIP42_MAX_CHALLENGE_LENGTH];
|
||||
time_t auth_challenge_time;
|
||||
int nip42_enabled;
|
||||
```
|
||||
|
||||
These go after the existing `last_connection_error_time` field (around line 106).
|
||||
|
||||
### 3. Add private key and NIP-42 config to `nostr_relay_pool` struct
|
||||
|
||||
Add to the [`nostr_relay_pool`](nostr_core/core_relay_pool.c:146) struct:
|
||||
|
||||
```c
|
||||
// NIP-42 Authentication configuration
|
||||
int nip42_enabled;
|
||||
unsigned char private_key[32];
|
||||
int has_private_key;
|
||||
```
|
||||
|
||||
### 4. Add public API: `nostr_relay_pool_set_auth()`
|
||||
|
||||
Add to [`nostr_core.h`](nostr_core/nostr_core.h) after the existing pool management functions (around line 252):
|
||||
|
||||
```c
|
||||
// NIP-42 Authentication configuration for relay pool
|
||||
int nostr_relay_pool_set_auth(nostr_relay_pool_t* pool,
|
||||
const unsigned char* private_key,
|
||||
int enable);
|
||||
```
|
||||
|
||||
Implement in [`core_relay_pool.c`](nostr_core/core_relay_pool.c):
|
||||
- Copies the 32-byte private key into the pool struct
|
||||
- Sets `nip42_enabled` flag
|
||||
- Propagates `nip42_enabled` to all existing relay connections
|
||||
|
||||
### 5. Handle AUTH in `process_relay_message()`
|
||||
|
||||
Add an `AUTH` handler in [`process_relay_message()`](nostr_core/core_relay_pool.c:912) between the existing `OK` and `PONG` handlers (around line 1097). The logic mirrors [`core_relays.c:211-239`](nostr_core/core_relays.c:211):
|
||||
|
||||
```c
|
||||
} else if (strcmp(msg_type, "AUTH") == 0) {
|
||||
// Handle AUTH challenge: ["AUTH", <challenge-string>]
|
||||
if (pool->nip42_enabled && pool->has_private_key &&
|
||||
cJSON_IsArray(parsed) && cJSON_GetArraySize(parsed) >= 2) {
|
||||
cJSON* challenge_json = cJSON_GetArrayItem(parsed, 1);
|
||||
if (cJSON_IsString(challenge_json)) {
|
||||
const char* challenge = cJSON_GetStringValue(challenge_json);
|
||||
|
||||
// Store challenge
|
||||
strncpy(relay->auth_challenge, challenge,
|
||||
sizeof(relay->auth_challenge) - 1);
|
||||
relay->auth_challenge[sizeof(relay->auth_challenge) - 1] = '\0';
|
||||
relay->auth_challenge_time = time(NULL);
|
||||
relay->auth_state = NOSTR_AUTH_STATE_CHALLENGE_RECEIVED;
|
||||
|
||||
// Create and send auth event
|
||||
cJSON* auth_event = nostr_nip42_create_auth_event(
|
||||
challenge, relay->url, pool->private_key, 0);
|
||||
if (auth_event) {
|
||||
char* auth_message = nostr_nip42_create_auth_message(auth_event);
|
||||
if (auth_message) {
|
||||
if (nostr_ws_send_text(relay->ws_client, auth_message) >= 0) {
|
||||
relay->auth_state = NOSTR_AUTH_STATE_AUTHENTICATING;
|
||||
}
|
||||
free(auth_message);
|
||||
}
|
||||
cJSON_Delete(auth_event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 6. Handle AUTH in `nostr_relay_pool_query_sync()` inline loop
|
||||
|
||||
The [`nostr_relay_pool_query_sync()`](nostr_core/core_relay_pool.c:1107) function has its own inline message parsing loop (lines 1178-1227) that bypasses `process_relay_message()`. Add AUTH handling there too, similar to the pattern above.
|
||||
|
||||
### 7. Handle NOTICE messages
|
||||
|
||||
Add a `NOTICE` handler in [`process_relay_message()`](nostr_core/core_relay_pool.c:912):
|
||||
|
||||
```c
|
||||
} else if (strcmp(msg_type, "NOTICE") == 0) {
|
||||
// Handle NOTICE: ["NOTICE", <message>]
|
||||
if (cJSON_IsArray(parsed) && cJSON_GetArraySize(parsed) >= 2) {
|
||||
cJSON* notice_msg = cJSON_GetArrayItem(parsed, 1);
|
||||
if (cJSON_IsString(notice_msg)) {
|
||||
const char* notice = cJSON_GetStringValue(notice_msg);
|
||||
// Detect auth-required notices
|
||||
if (strstr(notice, "auth-required") != NULL) {
|
||||
relay->auth_state = NOSTR_AUTH_STATE_NONE; // Reset for re-auth
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 8. Handle OK auth-required rejections
|
||||
|
||||
Enhance the existing [`OK` handler](nostr_core/core_relay_pool.c:1048) to detect `auth-required:` prefix in error messages. When detected:
|
||||
- If the pool has a private key and the relay hasn't been authenticated yet, trigger the auth flow
|
||||
- Surface the rejection through the publish callback with the auth-required message
|
||||
|
||||
### 9. Initialize auth fields in `nostr_relay_pool_add_relay()`
|
||||
|
||||
In [`nostr_relay_pool_add_relay()`](nostr_core/core_relay_pool.c:605), initialize the new auth fields:
|
||||
|
||||
```c
|
||||
// Initialize NIP-42 authentication fields
|
||||
relay->auth_state = NOSTR_AUTH_STATE_NONE;
|
||||
memset(relay->auth_challenge, 0, sizeof(relay->auth_challenge));
|
||||
relay->auth_challenge_time = 0;
|
||||
relay->nip42_enabled = pool->nip42_enabled;
|
||||
```
|
||||
|
||||
### 10. Secure cleanup in `nostr_relay_pool_destroy()`
|
||||
|
||||
In [`nostr_relay_pool_destroy()`](nostr_core/core_relay_pool.c:684), zero the private key before freeing:
|
||||
|
||||
```c
|
||||
// Securely zero private key
|
||||
if (pool->has_private_key) {
|
||||
memset(pool->private_key, 0, sizeof(pool->private_key));
|
||||
pool->has_private_key = 0;
|
||||
}
|
||||
```
|
||||
|
||||
### 11. Test file
|
||||
|
||||
Create `tests/nip42_pool_test.c` that:
|
||||
- Creates a pool with auth configured
|
||||
- Verifies `nostr_relay_pool_set_auth()` stores the key
|
||||
- Simulates AUTH challenge parsing logic (unit-level, no live relay needed)
|
||||
- Verifies auth event creation with the pool's private key
|
||||
|
||||
### 12. Documentation updates
|
||||
|
||||
- Update [`POOL_API.md`](POOL_API.md) with `nostr_relay_pool_set_auth()` documentation
|
||||
- Update [`README.md`](README.md) with a relay pool NIP-42 usage example
|
||||
|
||||
## Files Modified
|
||||
|
||||
| File | Change Type | Description |
|
||||
|------|-------------|-------------|
|
||||
| [`nostr_core/core_relay_pool.c`](nostr_core/core_relay_pool.c) | Modified | Add auth fields, AUTH/NOTICE handlers, auth config API |
|
||||
| [`nostr_core/nostr_core.h`](nostr_core/nostr_core.h) | Modified | Add `nostr_relay_pool_set_auth()` declaration |
|
||||
| [`tests/nip42_pool_test.c`](tests/nip42_pool_test.c) | New | NIP-42 pool authentication tests |
|
||||
| [`POOL_API.md`](POOL_API.md) | Modified | Document new auth API |
|
||||
| [`README.md`](README.md) | Modified | Add pool auth usage example |
|
||||
|
||||
## Key Design Decisions
|
||||
|
||||
1. **Private key stored in pool, not per-relay**: A single identity authenticates to all relays in the pool. This matches the common use case and mirrors how `core_relays.c` accepts a single `private_key` parameter.
|
||||
|
||||
2. **Auth state tracked per-relay**: Each relay connection tracks its own `nostr_auth_state_t` since different relays may challenge at different times.
|
||||
|
||||
3. **Automatic re-auth on reconnect**: When a relay reconnects (via the existing reconnection logic), the auth state resets to `NOSTR_AUTH_STATE_NONE`, allowing the relay to re-challenge.
|
||||
|
||||
4. **No blocking on auth**: The AUTH response is sent asynchronously. If a relay requires auth before accepting subscriptions, the relay will re-send events after authentication succeeds. The pool does not block waiting for auth confirmation.
|
||||
|
||||
5. **Reuse existing NIP-42 primitives**: All crypto and message formatting uses [`nostr_nip42_create_auth_event()`](nostr_core/nip042.c:26) and [`nostr_nip42_create_auth_message()`](nostr_core/nip042.c:84) — no new crypto code needed.
|
||||
@@ -0,0 +1,350 @@
|
||||
# NIP-46 Remote Signing — Implementation Plan
|
||||
|
||||
## Overview
|
||||
|
||||
NIP-46 defines a protocol for **Nostr Remote Signing**, enabling 2-way communication between a client application and a remote signer (bunker) over Nostr relays. The remote signer holds the user's private keys and performs cryptographic operations on behalf of the client, reducing the attack surface by keeping keys off the client device.
|
||||
|
||||
This plan covers implementing **both sides** of the protocol:
|
||||
- **Client-side**: sends requests to a remote signer and processes responses
|
||||
- **Remote-signer-side**: receives requests and produces responses (for building bunker applications)
|
||||
|
||||
## Architecture
|
||||
|
||||
### Protocol Flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Client
|
||||
participant R as Relay
|
||||
participant S as Remote Signer
|
||||
|
||||
Note over C: Generate client-keypair
|
||||
C->>R: Subscribe to kind:24133 p-tagged to client-pubkey
|
||||
C->>R: Publish connect request, kind:24133, p-tag remote-signer-pubkey
|
||||
R->>S: Deliver connect request
|
||||
S->>R: Publish connect response, kind:24133, p-tag client-pubkey
|
||||
R->>C: Deliver connect response
|
||||
Note over C: Connection established
|
||||
|
||||
C->>R: Publish get_public_key request
|
||||
R->>S: Deliver request
|
||||
S->>R: Publish response with user-pubkey
|
||||
R->>C: Deliver response
|
||||
Note over C: Now knows user-pubkey
|
||||
|
||||
C->>R: Publish sign_event request
|
||||
R->>S: Deliver request
|
||||
S->>R: Publish signed event response
|
||||
R->>C: Deliver signed event
|
||||
```
|
||||
|
||||
### Connection Initiation
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[Connection Initiation] --> B{Who initiates?}
|
||||
B -->|Remote Signer| C[bunker:// URL]
|
||||
B -->|Client| D[nostrconnect:// URL]
|
||||
|
||||
C --> E[Client parses bunker URL]
|
||||
E --> F[Extract remote-signer-pubkey + relays + secret]
|
||||
F --> G[Client sends connect request to remote-signer]
|
||||
|
||||
D --> H[Remote signer parses nostrconnect URL]
|
||||
H --> I[Extract client-pubkey + relays + secret + perms]
|
||||
I --> J[Remote signer sends connect response to client]
|
||||
|
||||
G --> K[Connection Established]
|
||||
J --> K
|
||||
```
|
||||
|
||||
### Component Dependency Map
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
NIP46[nip046.c/h] --> NIP44[nip044 - NIP-44 Encryption]
|
||||
NIP46 --> NIP04[nip004 - NIP-04 Encryption]
|
||||
NIP46 --> NIP01[nip001 - Event Creation/Signing]
|
||||
NIP46 --> POOL[core_relay_pool - Relay Communication]
|
||||
NIP46 --> UTILS[utils - Hex/Bytes/Random]
|
||||
NIP46 --> CJSON[cJSON - JSON Handling]
|
||||
NIP46 --> COMMON[nostr_common - Error Codes/Constants]
|
||||
```
|
||||
|
||||
## Data Structures
|
||||
|
||||
### Core Types
|
||||
|
||||
```c
|
||||
// NIP-46 event kind
|
||||
#define NOSTR_NIP46_REQUEST_KIND 24133
|
||||
|
||||
// Connection types
|
||||
typedef enum {
|
||||
NOSTR_NIP46_CONN_BUNKER, // bunker:// initiated by remote-signer
|
||||
NOSTR_NIP46_CONN_NOSTRCONNECT // nostrconnect:// initiated by client
|
||||
} nostr_nip46_connection_type_t;
|
||||
|
||||
// RPC Method types
|
||||
typedef enum {
|
||||
NOSTR_NIP46_METHOD_CONNECT,
|
||||
NOSTR_NIP46_METHOD_SIGN_EVENT,
|
||||
NOSTR_NIP46_METHOD_PING,
|
||||
NOSTR_NIP46_METHOD_GET_PUBLIC_KEY,
|
||||
NOSTR_NIP46_METHOD_NIP04_ENCRYPT,
|
||||
NOSTR_NIP46_METHOD_NIP04_DECRYPT,
|
||||
NOSTR_NIP46_METHOD_NIP44_ENCRYPT,
|
||||
NOSTR_NIP46_METHOD_NIP44_DECRYPT
|
||||
} nostr_nip46_method_t;
|
||||
|
||||
// Parsed bunker:// URL
|
||||
typedef struct {
|
||||
char remote_signer_pubkey[65]; // hex pubkey
|
||||
char relays[8][256]; // up to 8 relay URLs
|
||||
int relay_count;
|
||||
char secret[128]; // optional secret
|
||||
} nostr_nip46_bunker_url_t;
|
||||
|
||||
// Parsed nostrconnect:// URL
|
||||
typedef struct {
|
||||
char client_pubkey[65]; // hex pubkey
|
||||
char relays[8][256]; // relay URLs
|
||||
int relay_count;
|
||||
char secret[128]; // required secret
|
||||
char perms[512]; // optional permissions
|
||||
char name[128]; // optional app name
|
||||
char url[256]; // optional app URL
|
||||
char image[256]; // optional app image
|
||||
} nostr_nip46_nostrconnect_url_t;
|
||||
|
||||
// JSON-RPC Request
|
||||
typedef struct {
|
||||
char id[65]; // random request ID
|
||||
nostr_nip46_method_t method;
|
||||
char method_str[32]; // string form of method
|
||||
char** params; // array of string params
|
||||
int param_count;
|
||||
} nostr_nip46_request_t;
|
||||
|
||||
// JSON-RPC Response
|
||||
typedef struct {
|
||||
char id[65]; // matching request ID
|
||||
char* result; // result string
|
||||
char* error; // error string, NULL if success
|
||||
} nostr_nip46_response_t;
|
||||
|
||||
// Client session state
|
||||
typedef struct {
|
||||
unsigned char client_private_key[32];
|
||||
char client_pubkey_hex[65];
|
||||
char remote_signer_pubkey_hex[65];
|
||||
unsigned char remote_signer_pubkey[32];
|
||||
char user_pubkey_hex[65]; // learned via get_public_key
|
||||
char relays[8][256];
|
||||
int relay_count;
|
||||
int connected;
|
||||
} nostr_nip46_client_session_t;
|
||||
|
||||
// Signer session state
|
||||
typedef struct {
|
||||
unsigned char signer_private_key[32];
|
||||
char signer_pubkey_hex[65];
|
||||
unsigned char user_private_key[32];
|
||||
char user_pubkey_hex[65];
|
||||
char client_pubkey_hex[65];
|
||||
unsigned char client_pubkey[32];
|
||||
char relays[8][256];
|
||||
int relay_count;
|
||||
int connected;
|
||||
} nostr_nip46_signer_session_t;
|
||||
```
|
||||
|
||||
## Public API Functions
|
||||
|
||||
### URL Parsing
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `nostr_nip46_parse_bunker_url()` | Parse `bunker://<pubkey>?relay=...&secret=...` |
|
||||
| `nostr_nip46_parse_nostrconnect_url()` | Parse `nostrconnect://<pubkey>?relay=...&secret=...&perms=...` |
|
||||
| `nostr_nip46_create_bunker_url()` | Generate a bunker:// connection token |
|
||||
| `nostr_nip46_create_nostrconnect_url()` | Generate a nostrconnect:// connection token |
|
||||
|
||||
### JSON-RPC Message Construction
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `nostr_nip46_create_request()` | Build a JSON-RPC request object |
|
||||
| `nostr_nip46_create_response()` | Build a JSON-RPC response object |
|
||||
| `nostr_nip46_parse_request()` | Parse decrypted JSON into request struct |
|
||||
| `nostr_nip46_parse_response()` | Parse decrypted JSON into response struct |
|
||||
| `nostr_nip46_free_request()` | Free request struct memory |
|
||||
| `nostr_nip46_free_response()` | Free response struct memory |
|
||||
|
||||
### Event Construction (kind: 24133)
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `nostr_nip46_create_request_event()` | Create NIP-44 encrypted kind:24133 request event |
|
||||
| `nostr_nip46_create_response_event()` | Create NIP-44 encrypted kind:24133 response event |
|
||||
| `nostr_nip46_decrypt_event()` | Decrypt a kind:24133 event content |
|
||||
|
||||
### Client-Side Operations
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `nostr_nip46_client_session_init()` | Initialize client session from bunker URL |
|
||||
| `nostr_nip46_client_session_destroy()` | Clean up client session |
|
||||
| `nostr_nip46_client_connect()` | Send connect request to remote signer |
|
||||
| `nostr_nip46_client_get_public_key()` | Request user pubkey from remote signer |
|
||||
| `nostr_nip46_client_sign_event()` | Request event signing from remote signer |
|
||||
| `nostr_nip46_client_ping()` | Send ping to remote signer |
|
||||
| `nostr_nip46_client_nip04_encrypt()` | Request NIP-04 encryption |
|
||||
| `nostr_nip46_client_nip04_decrypt()` | Request NIP-04 decryption |
|
||||
| `nostr_nip46_client_nip44_encrypt()` | Request NIP-44 encryption |
|
||||
| `nostr_nip46_client_nip44_decrypt()` | Request NIP-44 decryption |
|
||||
|
||||
### Remote-Signer-Side Operations
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `nostr_nip46_signer_session_init()` | Initialize signer session |
|
||||
| `nostr_nip46_signer_session_destroy()` | Clean up signer session |
|
||||
| `nostr_nip46_signer_handle_request()` | Process an incoming request and produce a response |
|
||||
| `nostr_nip46_signer_create_bunker_url()` | Generate bunker URL for distribution |
|
||||
|
||||
### Utility
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `nostr_nip46_generate_request_id()` | Generate random request ID string |
|
||||
| `nostr_nip46_method_to_string()` | Convert method enum to string |
|
||||
| `nostr_nip46_string_to_method()` | Convert string to method enum |
|
||||
|
||||
## Error Codes
|
||||
|
||||
New error codes to add to `nostr_common.h`:
|
||||
|
||||
```c
|
||||
// NIP-46 Remote Signing error codes
|
||||
#define NOSTR_ERROR_NIP46_INVALID_BUNKER_URL -300
|
||||
#define NOSTR_ERROR_NIP46_INVALID_NOSTRCONNECT -301
|
||||
#define NOSTR_ERROR_NIP46_INVALID_REQUEST -302
|
||||
#define NOSTR_ERROR_NIP46_INVALID_RESPONSE -303
|
||||
#define NOSTR_ERROR_NIP46_ENCRYPTION_FAILED -304
|
||||
#define NOSTR_ERROR_NIP46_DECRYPTION_FAILED -305
|
||||
#define NOSTR_ERROR_NIP46_CONNECTION_FAILED -306
|
||||
#define NOSTR_ERROR_NIP46_TIMEOUT -307
|
||||
#define NOSTR_ERROR_NIP46_SECRET_MISMATCH -308
|
||||
#define NOSTR_ERROR_NIP46_UNKNOWN_METHOD -309
|
||||
#define NOSTR_ERROR_NIP46_AUTH_CHALLENGE -310
|
||||
#define NOSTR_ERROR_NIP46_NOT_CONNECTED -311
|
||||
```
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
### New Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `nostr_core/nip046.h` | Header with all NIP-46 types, constants, and function declarations |
|
||||
| `nostr_core/nip046.c` | Implementation of all NIP-46 functions |
|
||||
| `tests/nip46_test.c` | Comprehensive test suite |
|
||||
| `examples/nip46_remote_signer.c` | Example showing both client and signer usage |
|
||||
|
||||
### Modified Files
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `nostr_core/nostr_core.h` | Add `#include "nip046.h"` and NIP-46 API docs in header comment |
|
||||
| `nostr_core/nostr_common.h` | Add NIP-46 error code defines |
|
||||
| `build.sh` | Add NIP-046 to auto-detection, `--nips=all` list, and description mapping |
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### URL Parsing Strategy
|
||||
|
||||
The `bunker://` and `nostrconnect://` URLs use standard URI format with query parameters. Implementation will:
|
||||
1. Validate the scheme prefix
|
||||
2. Extract the pubkey from the authority section
|
||||
3. Parse query parameters using simple string splitting — no external URL parsing library needed
|
||||
4. URL-decode relay values since they contain `://` characters
|
||||
|
||||
### NIP-44 Encryption Integration
|
||||
|
||||
All kind:24133 event content is NIP-44 encrypted. The implementation will use the existing `nostr_nip44_encrypt()` and `nostr_nip44_decrypt()` functions from `nip044.h`. The flow:
|
||||
1. Build JSON-RPC payload as a string
|
||||
2. Encrypt with `nostr_nip44_encrypt(client_privkey, remote_signer_pubkey, payload, ...)`
|
||||
3. Set as event content
|
||||
4. On receive: `nostr_nip44_decrypt(my_privkey, sender_pubkey, content, ...)`
|
||||
5. Parse decrypted JSON-RPC payload
|
||||
|
||||
### Relay Communication
|
||||
|
||||
For the initial implementation, the NIP-46 module will provide **event construction and parsing only** — it will not manage relay connections directly. Users will use the existing relay pool API to:
|
||||
1. Subscribe to kind:24133 events p-tagged to their pubkey
|
||||
2. Publish kind:24133 request/response events
|
||||
|
||||
This keeps the module focused and composable, matching the pattern used by NIP-59 and NIP-17.
|
||||
|
||||
A higher-level convenience layer could be added later that wraps the relay pool for a fully managed NIP-46 session.
|
||||
|
||||
### Auth Challenge Handling
|
||||
|
||||
When a response has `result: "auth_url"`, the error field contains a URL. The client-side API will return a specific error code `NOSTR_ERROR_NIP46_AUTH_CHALLENGE` and provide the URL in the response struct's error field, allowing the application to handle it appropriately.
|
||||
|
||||
## Test Plan
|
||||
|
||||
The test suite will cover:
|
||||
|
||||
1. **URL Parsing Tests**
|
||||
- Parse valid bunker:// URLs with single and multiple relays
|
||||
- Parse valid nostrconnect:// URLs with all optional fields
|
||||
- Reject malformed URLs
|
||||
- Handle URL-encoded relay values
|
||||
|
||||
2. **URL Generation Tests**
|
||||
- Generate bunker:// URLs and verify round-trip parsing
|
||||
- Generate nostrconnect:// URLs and verify round-trip parsing
|
||||
|
||||
3. **JSON-RPC Message Tests**
|
||||
- Create and parse each method type request
|
||||
- Create and parse success responses
|
||||
- Create and parse error responses
|
||||
- Verify request ID matching
|
||||
|
||||
4. **Event Construction Tests**
|
||||
- Create kind:24133 request events with proper encryption
|
||||
- Create kind:24133 response events with proper encryption
|
||||
- Decrypt events and verify content matches
|
||||
|
||||
5. **Method Enum Conversion Tests**
|
||||
- Round-trip all method enum values through string conversion
|
||||
|
||||
6. **Signer Request Handling Tests**
|
||||
- Handle connect request and produce ack response
|
||||
- Handle sign_event request and produce signed event response
|
||||
- Handle ping request and produce pong response
|
||||
- Handle get_public_key and return correct pubkey
|
||||
- Handle NIP-04/NIP-44 encrypt/decrypt requests
|
||||
|
||||
7. **End-to-End Flow Tests**
|
||||
- Client creates connect request → Signer handles → Client processes response
|
||||
- Client creates sign_event request → Signer signs → Client gets signed event
|
||||
- Full bunker:// connection flow
|
||||
- Secret validation on connect
|
||||
|
||||
## Implementation Order
|
||||
|
||||
1. Error codes in `nostr_common.h`
|
||||
2. Header file `nip046.h` with all declarations
|
||||
3. URL parsing functions
|
||||
4. JSON-RPC request/response construction and parsing
|
||||
5. Kind:24133 event creation and decryption
|
||||
6. Client session management
|
||||
7. Signer session and request handling
|
||||
8. Utility functions
|
||||
9. Build system updates
|
||||
10. Test suite
|
||||
11. Example program
|
||||
12. Documentation updates in `nostr_core.h`
|
||||
@@ -0,0 +1,93 @@
|
||||
#define _DEFAULT_SOURCE
|
||||
#include "../nostr_core/nostr_core.h"
|
||||
#include "../cjson/cJSON.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// Test callback function
|
||||
static int callback_count = 0;
|
||||
static int success_count = 0;
|
||||
|
||||
void test_callback(const char* relay_url, const char* event_id,
|
||||
int success, const char* message, void* user_data) {
|
||||
callback_count++;
|
||||
if (success) {
|
||||
success_count++;
|
||||
}
|
||||
|
||||
printf("📡 Callback %d: Relay %s, Event %s, Success: %s\n",
|
||||
callback_count, relay_url, event_id, success ? "YES" : "NO");
|
||||
if (message) {
|
||||
printf(" Message: %s\n", message);
|
||||
}
|
||||
|
||||
// Mark test as complete when we get the expected number of callbacks
|
||||
int* expected_callbacks = (int*)user_data;
|
||||
if (callback_count >= *expected_callbacks) {
|
||||
printf("✅ All callbacks received!\n");
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
printf("🧪 Testing Async Publish Functionality\n");
|
||||
printf("=====================================\n");
|
||||
|
||||
// Create pool
|
||||
nostr_relay_pool_t* pool = nostr_relay_pool_create(NULL);
|
||||
if (!pool) {
|
||||
printf("❌ Failed to create pool\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Create a test event
|
||||
cJSON* event = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(event, "id", "test_event_12345");
|
||||
cJSON_AddNumberToObject(event, "kind", 1);
|
||||
cJSON_AddStringToObject(event, "content", "Test async publish");
|
||||
cJSON_AddNumberToObject(event, "created_at", time(NULL));
|
||||
cJSON_AddStringToObject(event, "pubkey", "test_pubkey");
|
||||
cJSON_AddStringToObject(event, "sig", "test_signature");
|
||||
|
||||
// Test with non-existent relays (should trigger connection failure callbacks)
|
||||
const char* test_relays[] = {
|
||||
"ws://nonexistent1.example.com",
|
||||
"ws://nonexistent2.example.com"
|
||||
};
|
||||
int expected_callbacks = 2;
|
||||
|
||||
printf("🚀 Testing async publish with connection failure callbacks...\n");
|
||||
|
||||
// Call async publish
|
||||
int sent_count = nostr_relay_pool_publish_async(
|
||||
pool, test_relays, 2, event, test_callback, &expected_callbacks);
|
||||
|
||||
printf("📊 Sent to %d relays\n", sent_count);
|
||||
|
||||
// Wait a bit for callbacks (connection failures should be immediate)
|
||||
printf("⏳ Waiting for callbacks...\n");
|
||||
for (int i = 0; i < 10 && callback_count < expected_callbacks; i++) {
|
||||
nostr_relay_pool_poll(pool, 100);
|
||||
usleep(100000); // 100ms
|
||||
}
|
||||
|
||||
printf("\n📈 Results:\n");
|
||||
printf(" Callbacks received: %d/%d\n", callback_count, expected_callbacks);
|
||||
printf(" Successful publishes: %d\n", success_count);
|
||||
|
||||
// Test backward compatibility with synchronous version
|
||||
printf("\n🔄 Testing backward compatibility (sync version)...\n");
|
||||
int sync_result = nostr_relay_pool_publish_async(pool, test_relays, 2, event, NULL, NULL);
|
||||
printf(" Sync publish result: %d successful publishes\n", sync_result);
|
||||
|
||||
// Cleanup
|
||||
cJSON_Delete(event);
|
||||
nostr_relay_pool_destroy(pool);
|
||||
|
||||
printf("\n✅ Async publish test completed!\n");
|
||||
printf(" - Async callbacks: %s\n", callback_count >= expected_callbacks ? "PASS" : "FAIL");
|
||||
printf(" - Backward compatibility: %s\n", sync_result >= 0 ? "PASS" : "FAIL");
|
||||
|
||||
return (callback_count >= expected_callbacks && sync_result >= 0) ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#define _DEFAULT_SOURCE
|
||||
#include "../nostr_core/nostr_core.h"
|
||||
#include "../cjson/cJSON.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main() {
|
||||
printf("🧪 Backward Compatibility Test\n");
|
||||
printf("===============================\n");
|
||||
|
||||
// Create pool
|
||||
nostr_relay_pool_t* pool = nostr_relay_pool_create(NULL);
|
||||
if (!pool) {
|
||||
printf("❌ Failed to create pool\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Create a test event
|
||||
cJSON* event = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(event, "id", "test_event_sync");
|
||||
cJSON_AddNumberToObject(event, "kind", 1);
|
||||
cJSON_AddStringToObject(event, "content", "Test sync publish");
|
||||
cJSON_AddNumberToObject(event, "created_at", time(NULL));
|
||||
cJSON_AddStringToObject(event, "pubkey", "test_pubkey");
|
||||
cJSON_AddStringToObject(event, "sig", "test_signature");
|
||||
|
||||
// Test with non-existent relay (should return 0 successful publishes)
|
||||
const char* test_relays[] = {"ws://nonexistent.example.com"};
|
||||
|
||||
printf("🚀 Testing synchronous publish (backward compatibility)...\n");
|
||||
|
||||
// Call synchronous publish (old API)
|
||||
int result = nostr_relay_pool_publish_async(pool, test_relays, 1, event, NULL, NULL);
|
||||
|
||||
printf("📊 Synchronous publish result: %d successful publishes\n", result);
|
||||
|
||||
// Cleanup
|
||||
cJSON_Delete(event);
|
||||
nostr_relay_pool_destroy(pool);
|
||||
|
||||
printf("\n✅ Backward compatibility test completed!\n");
|
||||
printf(" Expected: 0 successful publishes (connection failure)\n");
|
||||
printf(" Actual: %d successful publishes\n", result);
|
||||
printf(" Result: %s\n", result == 0 ? "PASS" : "FAIL");
|
||||
|
||||
return result == 0 ? 0 : 1;
|
||||
}
|
||||
+3
-3
@@ -671,8 +671,8 @@ int test_vector_7_10kb_payload(void) {
|
||||
printf("Last 80 chars: \"...%.80s\"\n", encrypted + encrypted_len - 80);
|
||||
printf("\n");
|
||||
|
||||
// Test decryption with our ciphertext
|
||||
char* decrypted = malloc(NOSTR_NIP04_MAX_PLAINTEXT_SIZE);
|
||||
// Test decryption with our ciphertext - allocate larger buffer for safety
|
||||
char* decrypted = malloc(NOSTR_NIP04_MAX_PLAINTEXT_SIZE + 1024); // 1MB + 1KB extra
|
||||
if (!decrypted) {
|
||||
printf("❌ MEMORY ALLOCATION FAILED for decrypted buffer\n");
|
||||
free(large_plaintext);
|
||||
@@ -680,7 +680,7 @@ int test_vector_7_10kb_payload(void) {
|
||||
return 0;
|
||||
}
|
||||
printf("Testing decryption of 1MB ciphertext (Bob decrypts from Alice)...\n");
|
||||
result = nostr_nip04_decrypt(sk2, pk1, encrypted, decrypted, NOSTR_NIP04_MAX_PLAINTEXT_SIZE);
|
||||
result = nostr_nip04_decrypt(sk2, pk1, encrypted, decrypted, NOSTR_NIP04_MAX_PLAINTEXT_SIZE + 1024);
|
||||
|
||||
if (result != NOSTR_SUCCESS) {
|
||||
printf("❌ 1MB DECRYPTION FAILED: %s\n", nostr_strerror(result));
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
#define _DEFAULT_SOURCE
|
||||
#include "../nostr_core/nostr_core.h"
|
||||
#include "../cjson/cJSON.h"
|
||||
#include "../nostr_websocket/nostr_websocket_tls.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int g_callback_count = 0;
|
||||
static int g_publish_ok = 0;
|
||||
static int g_publish_fail = 0;
|
||||
static int g_auth_required_seen = 0;
|
||||
|
||||
static const char* relay_status_str(nostr_pool_relay_status_t status) {
|
||||
switch (status) {
|
||||
case NOSTR_POOL_RELAY_DISCONNECTED: return "DISCONNECTED";
|
||||
case NOSTR_POOL_RELAY_CONNECTING: return "CONNECTING";
|
||||
case NOSTR_POOL_RELAY_CONNECTED: return "CONNECTED";
|
||||
case NOSTR_POOL_RELAY_ERROR: return "ERROR";
|
||||
default: return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
static double now_ms(void) {
|
||||
struct timespec ts;
|
||||
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
|
||||
return (double)time(NULL) * 1000.0;
|
||||
}
|
||||
return ts.tv_sec * 1000.0 + ts.tv_nsec / 1000000.0;
|
||||
}
|
||||
|
||||
static void publish_callback(const char* relay_url,
|
||||
const char* event_id,
|
||||
int success,
|
||||
const char* message,
|
||||
void* user_data) {
|
||||
(void)user_data;
|
||||
|
||||
g_callback_count++;
|
||||
if (success) {
|
||||
g_publish_ok++;
|
||||
} else {
|
||||
g_publish_fail++;
|
||||
if (message && strstr(message, "auth-required") != NULL) {
|
||||
g_auth_required_seen++;
|
||||
}
|
||||
}
|
||||
|
||||
printf("[POOL CALLBACK %d] relay=%s event_id=%s success=%d", g_callback_count,
|
||||
relay_url ? relay_url : "(null)", event_id ? event_id : "(null)", success);
|
||||
if (message) {
|
||||
printf(" message=\"%s\"", message);
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
static cJSON* create_kind4_event(const unsigned char* private_key, int sequence) {
|
||||
if (!private_key) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
char content[256];
|
||||
snprintf(content, sizeof(content), "pool-auth-test message #%d at %ld", sequence, (long)time(NULL));
|
||||
|
||||
cJSON* tags = cJSON_CreateArray();
|
||||
if (!tags) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
cJSON* p_tag = cJSON_CreateArray();
|
||||
if (!p_tag) {
|
||||
cJSON_Delete(tags);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
cJSON_AddItemToArray(p_tag, cJSON_CreateString("p"));
|
||||
cJSON_AddItemToArray(p_tag, cJSON_CreateString("0000000000000000000000000000000000000000000000000000000000000000"));
|
||||
cJSON_AddItemToArray(tags, p_tag);
|
||||
|
||||
cJSON* event = nostr_create_and_sign_event(4, content, tags, private_key, 0);
|
||||
cJSON_Delete(tags);
|
||||
return event;
|
||||
}
|
||||
|
||||
static void run_relay_auth_probe(const char* relay_url) {
|
||||
printf("\n=== Relay AUTH Probe (raw responses) ===\n");
|
||||
|
||||
nostr_ws_client_t* probe = nostr_ws_connect(relay_url);
|
||||
if (!probe) {
|
||||
printf("[AUTH PROBE] connect failed for %s\n", relay_url);
|
||||
return;
|
||||
}
|
||||
|
||||
int auth_seen = 0;
|
||||
int ok_seen = 0;
|
||||
int notice_seen = 0;
|
||||
|
||||
double start = now_ms();
|
||||
while ((now_ms() - start) < 2500.0) {
|
||||
char buffer[8192];
|
||||
int len = nostr_ws_receive(probe, buffer, sizeof(buffer) - 1, 150);
|
||||
if (len <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
buffer[len] = '\0';
|
||||
printf("[AUTH PROBE RAW] %s\n", buffer);
|
||||
|
||||
char* msg_type = NULL;
|
||||
cJSON* parsed = NULL;
|
||||
if (nostr_parse_relay_message(buffer, &msg_type, &parsed) == 0) {
|
||||
if (msg_type) {
|
||||
printf("[AUTH PROBE PARSED] type=%s\n", msg_type);
|
||||
}
|
||||
|
||||
if (msg_type && strcmp(msg_type, "AUTH") == 0 && cJSON_IsArray(parsed) && cJSON_GetArraySize(parsed) >= 2) {
|
||||
cJSON* challenge_json = cJSON_GetArrayItem(parsed, 1);
|
||||
if (cJSON_IsString(challenge_json)) {
|
||||
printf("[AUTH PROBE] challenge=%s\n", cJSON_GetStringValue(challenge_json));
|
||||
}
|
||||
auth_seen++;
|
||||
} else if (msg_type && strcmp(msg_type, "OK") == 0) {
|
||||
ok_seen++;
|
||||
} else if (msg_type && strcmp(msg_type, "NOTICE") == 0) {
|
||||
notice_seen++;
|
||||
}
|
||||
}
|
||||
|
||||
if (msg_type) free(msg_type);
|
||||
if (parsed) cJSON_Delete(parsed);
|
||||
}
|
||||
|
||||
printf("[AUTH PROBE] summary: AUTH=%d OK=%d NOTICE=%d\n", auth_seen, ok_seen, notice_seen);
|
||||
nostr_ws_close(probe);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
printf("=== NIP-42 Relay Pool Publish Test (kind-4 over 5s) ===\n");
|
||||
|
||||
if (nostr_init() != NOSTR_SUCCESS) {
|
||||
printf("FAILED: nostr_init() failed\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char* relay_url = "ws://127.0.0.1:7777";
|
||||
const char* private_key_hex = "91ba716fa9e7ea2fcbad360cf4f8e0d312f73984da63d90f524ad61a6a1e7dbe";
|
||||
|
||||
unsigned char private_key[32];
|
||||
memset(private_key, 0, sizeof(private_key));
|
||||
if (nostr_hex_to_bytes(private_key_hex, private_key, sizeof(private_key)) != NOSTR_SUCCESS) {
|
||||
printf("FAILED: unable to decode private key hex\n");
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
unsigned char public_key[32];
|
||||
char pubkey_hex[65];
|
||||
if (nostr_ec_public_key_from_private_key(private_key, public_key) != NOSTR_SUCCESS) {
|
||||
printf("FAILED: unable to derive public key\n");
|
||||
memset(private_key, 0, sizeof(private_key));
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
nostr_bytes_to_hex(public_key, 32, pubkey_hex);
|
||||
printf("Using pubkey: %s\n", pubkey_hex);
|
||||
|
||||
nostr_relay_pool_t* pool = nostr_relay_pool_create(NULL);
|
||||
if (!pool) {
|
||||
printf("FAILED: unable to create relay pool\n");
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (nostr_relay_pool_set_auth(pool, private_key, 1) != NOSTR_SUCCESS) {
|
||||
printf("FAILED: unable to configure relay pool authentication\n");
|
||||
nostr_relay_pool_destroy(pool);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (nostr_relay_pool_add_relay(pool, relay_url) != NOSTR_SUCCESS) {
|
||||
printf("FAILED: unable to add relay %s\n", relay_url);
|
||||
nostr_relay_pool_destroy(pool);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
run_relay_auth_probe(relay_url);
|
||||
|
||||
const char* relays[] = { relay_url };
|
||||
int sent_attempts = 0;
|
||||
|
||||
const double test_duration_ms = 5000.0;
|
||||
const double publish_interval_ms = 650.0;
|
||||
double start = now_ms();
|
||||
double next_publish = start;
|
||||
int sequence = 1;
|
||||
|
||||
nostr_pool_relay_status_t last_status = NOSTR_POOL_RELAY_DISCONNECTED;
|
||||
char last_error_snapshot[512] = {0};
|
||||
|
||||
while ((now_ms() - start) < test_duration_ms) {
|
||||
nostr_relay_pool_poll(pool, 100);
|
||||
|
||||
nostr_pool_relay_status_t current_status = nostr_relay_pool_get_relay_status(pool, relay_url);
|
||||
if (current_status != last_status) {
|
||||
printf("[POOL STATUS] %s -> %s\n", relay_status_str(last_status), relay_status_str(current_status));
|
||||
last_status = current_status;
|
||||
}
|
||||
|
||||
const char* last_err_live = nostr_relay_pool_get_relay_last_publish_error(pool, relay_url);
|
||||
if (last_err_live && strcmp(last_err_live, last_error_snapshot) != 0) {
|
||||
strncpy(last_error_snapshot, last_err_live, sizeof(last_error_snapshot) - 1);
|
||||
last_error_snapshot[sizeof(last_error_snapshot) - 1] = '\0';
|
||||
printf("[POOL ERROR] %s\n", last_error_snapshot);
|
||||
}
|
||||
|
||||
double t = now_ms();
|
||||
if (t >= next_publish) {
|
||||
cJSON* event = create_kind4_event(private_key, sequence++);
|
||||
if (!event) {
|
||||
printf("WARN: failed to create signed event, skipping publish\n");
|
||||
next_publish += publish_interval_ms;
|
||||
usleep(100000);
|
||||
continue;
|
||||
}
|
||||
|
||||
int sent = nostr_relay_pool_publish_async(pool, relays, 1, event, publish_callback, NULL);
|
||||
if (sent > 0) {
|
||||
sent_attempts++;
|
||||
}
|
||||
|
||||
printf("[PUBLISH] attempt=%d sent=%d\n", sequence - 1, sent);
|
||||
|
||||
cJSON_Delete(event);
|
||||
next_publish += publish_interval_ms;
|
||||
}
|
||||
|
||||
usleep(100000);
|
||||
}
|
||||
|
||||
// Drain callbacks/messages a bit after last publish
|
||||
double drain_start = now_ms();
|
||||
while ((now_ms() - drain_start) < 1500.0) {
|
||||
nostr_relay_pool_poll(pool, 100);
|
||||
usleep(100000);
|
||||
}
|
||||
|
||||
const char* last_err = nostr_relay_pool_get_relay_last_publish_error(pool, relay_url);
|
||||
|
||||
cJSON* auth_filter = cJSON_CreateObject();
|
||||
cJSON* auth_kinds = cJSON_CreateArray();
|
||||
cJSON* auth_authors = cJSON_CreateArray();
|
||||
cJSON_AddItemToArray(auth_kinds, cJSON_CreateNumber(22242));
|
||||
cJSON_AddItemToArray(auth_authors, cJSON_CreateString(pubkey_hex));
|
||||
cJSON_AddItemToObject(auth_filter, "kinds", auth_kinds);
|
||||
cJSON_AddItemToObject(auth_filter, "authors", auth_authors);
|
||||
cJSON_AddItemToObject(auth_filter, "limit", cJSON_CreateNumber(20));
|
||||
|
||||
int auth_event_count = 0;
|
||||
cJSON** auth_events = nostr_relay_pool_query_sync(pool, relays, 1, auth_filter, &auth_event_count, 2500);
|
||||
cJSON_Delete(auth_filter);
|
||||
|
||||
printf("\n=== AUTH Events Seen On Relay (kind 22242) ===\n");
|
||||
printf("count=%d\n", auth_event_count);
|
||||
for (int i = 0; i < auth_event_count; i++) {
|
||||
cJSON* id = cJSON_GetObjectItem(auth_events[i], "id");
|
||||
cJSON* created_at = cJSON_GetObjectItem(auth_events[i], "created_at");
|
||||
printf("[AUTH EVENT %d] id=%s created_at=%lld\n",
|
||||
i + 1,
|
||||
(id && cJSON_IsString(id)) ? cJSON_GetStringValue(id) : "(no-id)",
|
||||
(long long)((created_at && cJSON_IsNumber(created_at)) ? cJSON_GetNumberValue(created_at) : 0));
|
||||
}
|
||||
|
||||
printf("\n=== Summary ===\n");
|
||||
printf("Relay: %s\n", relay_url);
|
||||
printf("Publish attempts sent: %d\n", sent_attempts);
|
||||
printf("Callbacks: %d\n", g_callback_count);
|
||||
printf("Accepted: %d\n", g_publish_ok);
|
||||
printf("Rejected/Failed: %d\n", g_publish_fail);
|
||||
printf("auth-required seen in callbacks: %d\n", g_auth_required_seen);
|
||||
printf("Last relay publish error: %s\n", last_err ? last_err : "(none)");
|
||||
|
||||
if (auth_events) {
|
||||
for (int i = 0; i < auth_event_count; i++) {
|
||||
if (auth_events[i]) {
|
||||
cJSON_Delete(auth_events[i]);
|
||||
}
|
||||
}
|
||||
free(auth_events);
|
||||
}
|
||||
|
||||
nostr_relay_pool_destroy(pool);
|
||||
memset(private_key, 0, sizeof(private_key));
|
||||
memset(public_key, 0, sizeof(public_key));
|
||||
nostr_cleanup();
|
||||
|
||||
// Test is considered successful if the loop executed and we attempted publishes.
|
||||
// Auth behavior is diagnosed by callback details and summary output.
|
||||
if (sent_attempts <= 0) {
|
||||
printf("RESULT: FAIL (no publish attempts were sent)\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("RESULT: PASS (publish attempts sent; inspect auth behavior in logs above)\n");
|
||||
return 0;
|
||||
}
|
||||
+183
-124
@@ -20,32 +20,7 @@ typedef struct {
|
||||
const char* expected_encrypted; // Optional - for known test vectors
|
||||
} nip44_test_vector_t;
|
||||
|
||||
// Known decryption-only test vectors from nostr-tools (for cross-compatibility testing)
|
||||
// Note: NIP-44 encryption is non-deterministic - ciphertext varies each time
|
||||
// These vectors test our ability to decrypt known good ciphertext from reference implementations
|
||||
static nip44_test_vector_t decryption_test_vectors[] = {
|
||||
{
|
||||
"Decryption test: single char 'a'",
|
||||
"0000000000000000000000000000000000000000000000000000000000000001", // sec1
|
||||
"0000000000000000000000000000000000000000000000000000000000000002", // sec2
|
||||
"a",
|
||||
"AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABee0G5VSK0/9YypIObAtDKfYEAjD35uVkHyB0F4DwrcNaCXlCWZKaArsGrY6M9wnuTMxWfp1RTN9Xga8no+kF5Vsb"
|
||||
},
|
||||
{
|
||||
"Decryption test: emoji",
|
||||
"0000000000000000000000000000000000000000000000000000000000000002", // sec1
|
||||
"0000000000000000000000000000000000000000000000000000000000000001", // sec2
|
||||
"🍕🫃",
|
||||
"AvAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAPSKSK6is9ngkX2+cSq85Th16oRTISAOfhStnixqZziKMDvB0QQzgFZdjLTPicCJaV8nDITO+QfaQ61+KbWQIOO2Yj"
|
||||
},
|
||||
{
|
||||
"Decryption test: wide unicode",
|
||||
"5c0c523f52a5b6fad39ed2403092df8cebc36318b39383bca6c00808626fab3a", // sec1
|
||||
"4b22aa260e4acb7021e32f38a6cdf4b673c6a277755bfce287e370c924dc936d", // sec2
|
||||
"表ポあA鷗ŒéB逍Üߪąñ丂㐀𠀀",
|
||||
"ArY1I2xC2yDwIbuNHN/1ynXdGgzHLqdCrXUPMwELJPc7s7JqlCMJBAIIjfkpHReBPXeoMCyuClwgbT419jUWU1PwaNl4FEQYKCDKVJz+97Mp3K+Q2YGa77B6gpxB/lr1QgoqpDf7wDVrDmOqGoiPjWDqy8KzLueKDcm9BVP8xeTJIxs="
|
||||
}
|
||||
};
|
||||
// Additional test vectors for edge cases (converted to round-trip tests with new 32-bit padding)
|
||||
|
||||
// Round-trip test vectors with proper key pairs
|
||||
static nip44_test_vector_t test_vectors[] = {
|
||||
@@ -69,6 +44,13 @@ static nip44_test_vector_t test_vectors[] = {
|
||||
"4444444444444444444444444444444444444444444444444444444444444444",
|
||||
"",
|
||||
NULL
|
||||
},
|
||||
{
|
||||
"64KB payload test",
|
||||
"91ba716fa9e7ea2fcbad360cf4f8e0d312f73984da63d90f524ad61a6a1e7dbe", // Same keys as basic test
|
||||
"96f6fa197aa07477ab88f6981118466ae3a982faab8ad5db9d5426870c73d220",
|
||||
NULL, // Will be generated dynamically
|
||||
NULL
|
||||
}
|
||||
};
|
||||
|
||||
@@ -86,76 +68,144 @@ static int hex_to_bytes(const char* hex, unsigned char* bytes, size_t len) {
|
||||
|
||||
static int test_nip44_round_trip(const nip44_test_vector_t* tv) {
|
||||
printf("Test: %s\n", tv->name);
|
||||
|
||||
|
||||
// Parse keys - both private keys
|
||||
unsigned char sender_private_key[32];
|
||||
unsigned char recipient_private_key[32];
|
||||
|
||||
|
||||
if (hex_to_bytes(tv->sender_private_key_hex, sender_private_key, 32) != 0) {
|
||||
printf(" FAIL: Failed to parse sender private key\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
if (hex_to_bytes(tv->recipient_private_key_hex, recipient_private_key, 32) != 0) {
|
||||
printf(" FAIL: Failed to parse recipient private key\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
// Generate the public keys from the private keys
|
||||
unsigned char sender_public_key[32];
|
||||
unsigned char recipient_public_key[32];
|
||||
|
||||
|
||||
if (nostr_ec_public_key_from_private_key(sender_private_key, sender_public_key) != 0) {
|
||||
printf(" FAIL: Failed to derive sender public key\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
if (nostr_ec_public_key_from_private_key(recipient_private_key, recipient_public_key) != 0) {
|
||||
printf(" FAIL: Failed to derive recipient public key\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Test encryption
|
||||
char encrypted[8192];
|
||||
int encrypt_result = nostr_nip44_encrypt(
|
||||
sender_private_key,
|
||||
recipient_public_key,
|
||||
tv->plaintext,
|
||||
encrypted,
|
||||
sizeof(encrypted)
|
||||
);
|
||||
|
||||
if (encrypt_result != NOSTR_SUCCESS) {
|
||||
printf(" FAIL: Encryption - Expected: %d, Actual: %d\n", NOSTR_SUCCESS, encrypt_result);
|
||||
|
||||
// Special handling for large payload tests
|
||||
char* test_plaintext;
|
||||
if (strcmp(tv->name, "64KB payload test") == 0) {
|
||||
// Generate exactly 64KB (65,535 bytes) of predictable content - max NIP-44 size
|
||||
const size_t payload_size = 65535;
|
||||
test_plaintext = malloc(payload_size + 1);
|
||||
if (!test_plaintext) {
|
||||
printf(" FAIL: Memory allocation failed for 64KB test payload\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Fill with a predictable pattern: "ABCDEFGH01234567" repeated
|
||||
const char* pattern = "ABCDEFGH01234567"; // 16 bytes
|
||||
const size_t pattern_len = 16;
|
||||
|
||||
for (size_t i = 0; i < payload_size; i += pattern_len) {
|
||||
size_t copy_len = (i + pattern_len <= payload_size) ? pattern_len : payload_size - i;
|
||||
memcpy(test_plaintext + i, pattern, copy_len);
|
||||
}
|
||||
test_plaintext[payload_size] = '\0';
|
||||
|
||||
printf(" Generated 64KB test payload (%zu bytes)\n", payload_size);
|
||||
printf(" Pattern: \"%s\" repeated\n", pattern);
|
||||
printf(" First 64 chars: \"%.64s...\"\n", test_plaintext);
|
||||
printf(" Last 64 chars: \"...%.64s\"\n", test_plaintext + payload_size - 64);
|
||||
} else {
|
||||
test_plaintext = (char*)tv->plaintext;
|
||||
}
|
||||
|
||||
// Debug: Check plaintext length
|
||||
size_t plaintext_len = strlen(test_plaintext);
|
||||
printf(" Plaintext length: %zu bytes\n", plaintext_len);
|
||||
printf(" Output buffer size: %zu bytes\n", (size_t)10485760);
|
||||
|
||||
// Test encryption - use larger buffer for 1MB+ payloads (10MB for NIP-44 overhead)
|
||||
char* encrypted = malloc(10485760); // 10MB buffer for large payloads
|
||||
if (!encrypted) {
|
||||
printf(" FAIL: Memory allocation failed for encrypted buffer\n");
|
||||
if (strcmp(tv->name, "0.5MB payload test") == 0) free(test_plaintext);
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
// For large payloads, use _with_nonce to avoid random generation issues
|
||||
unsigned char fixed_nonce[32] = {0};
|
||||
int encrypt_result = nostr_nip44_encrypt_with_nonce(
|
||||
sender_private_key,
|
||||
recipient_public_key,
|
||||
test_plaintext,
|
||||
fixed_nonce,
|
||||
encrypted,
|
||||
10485760
|
||||
);
|
||||
|
||||
if (encrypt_result != NOSTR_SUCCESS) {
|
||||
printf(" FAIL: Encryption - Expected: %d, Actual: %d\n", NOSTR_SUCCESS, encrypt_result);
|
||||
if (strcmp(tv->name, "1MB payload test") == 0) free(test_plaintext);
|
||||
free(encrypted);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Test decryption - use recipient private key + sender public key
|
||||
char decrypted[8192];
|
||||
char* decrypted = malloc(65536 + 1); // 64KB + 1 for null terminator
|
||||
if (!decrypted) {
|
||||
printf(" FAIL: Memory allocation failed for decrypted buffer\n");
|
||||
if (strcmp(tv->name, "64KB payload test") == 0) free(test_plaintext);
|
||||
free(encrypted);
|
||||
return -1;
|
||||
}
|
||||
int decrypt_result = nostr_nip44_decrypt(
|
||||
recipient_private_key,
|
||||
sender_public_key,
|
||||
encrypted,
|
||||
decrypted,
|
||||
sizeof(decrypted)
|
||||
65536 + 1
|
||||
);
|
||||
|
||||
|
||||
if (decrypt_result != NOSTR_SUCCESS) {
|
||||
printf(" FAIL: Decryption - Expected: %d, Actual: %d\n", NOSTR_SUCCESS, decrypt_result);
|
||||
if (strcmp(tv->name, "1MB payload test") == 0) free(test_plaintext);
|
||||
free(encrypted);
|
||||
free(decrypted);
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
// Verify round-trip
|
||||
if (strcmp(tv->plaintext, decrypted) != 0) {
|
||||
if (strcmp(test_plaintext, decrypted) != 0) {
|
||||
printf(" FAIL: Round-trip mismatch\n");
|
||||
printf(" Expected: \"%s\"\n", tv->plaintext);
|
||||
printf(" Expected: \"%s\"\n", test_plaintext);
|
||||
printf(" Actual: \"%s\"\n", decrypted);
|
||||
if (strcmp(tv->name, "1MB payload test") == 0) free(test_plaintext);
|
||||
free(encrypted);
|
||||
free(decrypted);
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf(" PASS: Expected: \"%s\", Actual: \"%s\"\n", tv->plaintext, decrypted);
|
||||
printf(" Encrypted output: %s\n", encrypted);
|
||||
|
||||
|
||||
if (strcmp(tv->name, "64KB payload test") == 0) {
|
||||
printf(" ✅ 64KB payload round-trip: PASS\n");
|
||||
printf(" ✅ Content verification: All %zu bytes match perfectly!\n", strlen(test_plaintext));
|
||||
printf(" Encrypted length: %zu bytes\n", strlen(encrypted));
|
||||
printf(" 🎉 64KB NIP-44 STRESS TEST COMPLETED SUCCESSFULLY! 🎉\n");
|
||||
} else {
|
||||
printf(" PASS: Expected: \"%s\", Actual: \"%s\"\n", test_plaintext, decrypted);
|
||||
printf(" Encrypted output: %s\n", encrypted);
|
||||
}
|
||||
|
||||
if (strcmp(tv->name, "64KB payload test") == 0) free(test_plaintext);
|
||||
free(encrypted);
|
||||
free(decrypted);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -215,59 +265,6 @@ static int test_nip44_error_conditions() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int test_nip44_decryption_vector(const nip44_test_vector_t* tv) {
|
||||
printf("Test: %s\n", tv->name);
|
||||
|
||||
// Parse keys
|
||||
unsigned char sender_private_key[32];
|
||||
unsigned char recipient_private_key[32];
|
||||
|
||||
if (hex_to_bytes(tv->sender_private_key_hex, sender_private_key, 32) != 0) {
|
||||
printf(" FAIL: Failed to parse sender private key\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (hex_to_bytes(tv->recipient_private_key_hex, recipient_private_key, 32) != 0) {
|
||||
printf(" FAIL: Failed to parse recipient private key\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Generate the public keys from the private keys
|
||||
unsigned char sender_public_key[32];
|
||||
|
||||
if (nostr_ec_public_key_from_private_key(sender_private_key, sender_public_key) != 0) {
|
||||
printf(" FAIL: Failed to derive sender public key\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Test decryption of known vector
|
||||
char decrypted[8192];
|
||||
int decrypt_result = nostr_nip44_decrypt(
|
||||
recipient_private_key,
|
||||
sender_public_key,
|
||||
tv->expected_encrypted,
|
||||
decrypted,
|
||||
sizeof(decrypted)
|
||||
);
|
||||
|
||||
if (decrypt_result != NOSTR_SUCCESS) {
|
||||
printf(" FAIL: Decryption - Expected: %d, Actual: %d\n", NOSTR_SUCCESS, decrypt_result);
|
||||
printf(" Input payload: %s\n", tv->expected_encrypted);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Verify decrypted plaintext matches expected
|
||||
if (strcmp(tv->plaintext, decrypted) != 0) {
|
||||
printf(" FAIL: Plaintext mismatch\n");
|
||||
printf(" Expected: \"%s\"\n", tv->plaintext);
|
||||
printf(" Actual: \"%s\"\n", decrypted);
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf(" PASS: Expected: \"%s\", Actual: \"%s\"\n", tv->plaintext, decrypted);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int test_nip44_encryption_variability() {
|
||||
printf("Test: NIP-44 encryption variability (non-deterministic)\n");
|
||||
@@ -287,11 +284,20 @@ static int test_nip44_encryption_variability() {
|
||||
}
|
||||
|
||||
// Encrypt the same message multiple times
|
||||
char encrypted1[8192], encrypted2[8192], encrypted3[8192];
|
||||
char* encrypted1 = malloc(2097152); // 2MB buffer
|
||||
char* encrypted2 = malloc(2097152);
|
||||
char* encrypted3 = malloc(2097152);
|
||||
if (!encrypted1 || !encrypted2 || !encrypted3) {
|
||||
printf(" FAIL: Memory allocation failed for encrypted buffers\n");
|
||||
free(encrypted1);
|
||||
free(encrypted2);
|
||||
free(encrypted3);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int result1 = nostr_nip44_encrypt(sender_key, recipient_pubkey, test_message, encrypted1, sizeof(encrypted1));
|
||||
int result2 = nostr_nip44_encrypt(sender_key, recipient_pubkey, test_message, encrypted2, sizeof(encrypted2));
|
||||
int result3 = nostr_nip44_encrypt(sender_key, recipient_pubkey, test_message, encrypted3, sizeof(encrypted3));
|
||||
int result1 = nostr_nip44_encrypt(sender_key, recipient_pubkey, test_message, encrypted1, 2097152);
|
||||
int result2 = nostr_nip44_encrypt(sender_key, recipient_pubkey, test_message, encrypted2, 2097152);
|
||||
int result3 = nostr_nip44_encrypt(sender_key, recipient_pubkey, test_message, encrypted3, 2097152);
|
||||
|
||||
if (result1 != NOSTR_SUCCESS || result2 != NOSTR_SUCCESS || result3 != NOSTR_SUCCESS) {
|
||||
printf(" FAIL: Encryption failed - Results: %d, %d, %d\n", result1, result2, result3);
|
||||
@@ -304,6 +310,9 @@ static int test_nip44_encryption_variability() {
|
||||
printf(" Encryption 1: %.50s...\n", encrypted1);
|
||||
printf(" Encryption 2: %.50s...\n", encrypted2);
|
||||
printf(" Encryption 3: %.50s...\n", encrypted3);
|
||||
free(encrypted1);
|
||||
free(encrypted2);
|
||||
free(encrypted3);
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -314,11 +323,23 @@ static int test_nip44_encryption_variability() {
|
||||
return -1;
|
||||
}
|
||||
|
||||
char decrypted1[8192], decrypted2[8192], decrypted3[8192];
|
||||
|
||||
int decrypt1 = nostr_nip44_decrypt(recipient_key, sender_pubkey, encrypted1, decrypted1, sizeof(decrypted1));
|
||||
int decrypt2 = nostr_nip44_decrypt(recipient_key, sender_pubkey, encrypted2, decrypted2, sizeof(decrypted2));
|
||||
int decrypt3 = nostr_nip44_decrypt(recipient_key, sender_pubkey, encrypted3, decrypted3, sizeof(decrypted3));
|
||||
char* decrypted1 = malloc(1048576 + 1);
|
||||
char* decrypted2 = malloc(1048576 + 1);
|
||||
char* decrypted3 = malloc(1048576 + 1);
|
||||
if (!decrypted1 || !decrypted2 || !decrypted3) {
|
||||
printf(" FAIL: Memory allocation failed for decrypted buffers\n");
|
||||
free(encrypted1);
|
||||
free(encrypted2);
|
||||
free(encrypted3);
|
||||
free(decrypted1);
|
||||
free(decrypted2);
|
||||
free(decrypted3);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int decrypt1 = nostr_nip44_decrypt(recipient_key, sender_pubkey, encrypted1, decrypted1, 1048576 + 1);
|
||||
int decrypt2 = nostr_nip44_decrypt(recipient_key, sender_pubkey, encrypted2, decrypted2, 1048576 + 1);
|
||||
int decrypt3 = nostr_nip44_decrypt(recipient_key, sender_pubkey, encrypted3, decrypted3, 1048576 + 1);
|
||||
|
||||
if (decrypt1 != NOSTR_SUCCESS || decrypt2 != NOSTR_SUCCESS || decrypt3 != NOSTR_SUCCESS) {
|
||||
printf(" FAIL: Decryption failed - Results: %d, %d, %d\n", decrypt1, decrypt2, decrypt3);
|
||||
@@ -331,12 +352,25 @@ static int test_nip44_encryption_variability() {
|
||||
printf(" Decrypted1: \"%s\"\n", decrypted1);
|
||||
printf(" Decrypted2: \"%s\"\n", decrypted2);
|
||||
printf(" Decrypted3: \"%s\"\n", decrypted3);
|
||||
free(encrypted1);
|
||||
free(encrypted2);
|
||||
free(encrypted3);
|
||||
free(decrypted1);
|
||||
free(decrypted2);
|
||||
free(decrypted3);
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
printf(" PASS: All encryptions different, all decrypt to: \"%s\"\n", test_message);
|
||||
printf(" Sample ciphertext lengths: %zu, %zu, %zu bytes\n", strlen(encrypted1), strlen(encrypted2), strlen(encrypted3));
|
||||
|
||||
|
||||
free(encrypted1);
|
||||
free(encrypted2);
|
||||
free(encrypted3);
|
||||
free(decrypted1);
|
||||
free(decrypted2);
|
||||
free(decrypted3);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -365,12 +399,37 @@ int main() {
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
// Test decryption vectors (cross-compatibility)
|
||||
size_t num_decryption_vectors = sizeof(decryption_test_vectors) / sizeof(decryption_test_vectors[0]);
|
||||
for (size_t i = 0; i < num_decryption_vectors; i++) {
|
||||
// Additional edge case tests (converted to round-trip tests with new 32-bit padding)
|
||||
// These test the same plaintexts as the old decryption vectors but with our new format
|
||||
static nip44_test_vector_t edge_case_test_vectors[] = {
|
||||
{
|
||||
"Edge case: single char 'a'",
|
||||
"0000000000000000000000000000000000000000000000000000000000000001", // sec1
|
||||
"0000000000000000000000000000000000000000000000000000000000000002", // sec2
|
||||
"a",
|
||||
NULL
|
||||
},
|
||||
{
|
||||
"Edge case: emoji",
|
||||
"0000000000000000000000000000000000000000000000000000000000000002", // sec1
|
||||
"0000000000000000000000000000000000000000000000000000000000000001", // sec2
|
||||
"🍕🫃",
|
||||
NULL
|
||||
},
|
||||
{
|
||||
"Edge case: wide unicode",
|
||||
"5c0c523f52a5b6fad39ed2403092df8cebc36318b39383bca6c00808626fab3a", // sec1
|
||||
"4b22aa260e4acb7021e32f38a6cdf4b673c6a277755bfce287e370c924dc936d", // sec2
|
||||
"表ポあA鷗ŒéB逍Üߪąñ丂㐀𠀀",
|
||||
NULL
|
||||
}
|
||||
};
|
||||
|
||||
size_t num_edge_case_vectors = sizeof(edge_case_test_vectors) / sizeof(edge_case_test_vectors[0]);
|
||||
for (size_t i = 0; i < num_edge_case_vectors; i++) {
|
||||
total_tests++;
|
||||
printf("Test #%d\n", total_tests);
|
||||
if (test_nip44_decryption_vector(&decryption_test_vectors[i]) == 0) {
|
||||
if (test_nip44_round_trip(&edge_case_test_vectors[i]) == 0) {
|
||||
passed_tests++;
|
||||
}
|
||||
printf("\n");
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
/*
|
||||
* NIP-46 Remote Signing Test Suite
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "../nostr_core/nostr_core.h"
|
||||
|
||||
static int tests_run = 0;
|
||||
static int tests_passed = 0;
|
||||
|
||||
static void expect_int(const char* name, int expected, int actual) {
|
||||
tests_run++;
|
||||
if (expected == actual) {
|
||||
tests_passed++;
|
||||
printf("✅ %s (expected=%d actual=%d)\n", name, expected, actual);
|
||||
} else {
|
||||
printf("❌ %s (expected=%d actual=%d)\n", name, expected, actual);
|
||||
}
|
||||
}
|
||||
|
||||
static void expect_true(const char* name, int cond) {
|
||||
tests_run++;
|
||||
if (cond) {
|
||||
tests_passed++;
|
||||
printf("✅ %s\n", name);
|
||||
} else {
|
||||
printf("❌ %s\n", name);
|
||||
}
|
||||
}
|
||||
|
||||
static int hex_to_bytes32(const char* hex, unsigned char out[32]) {
|
||||
return nostr_hex_to_bytes(hex, out, 32) == 0 ? 0 : -1;
|
||||
}
|
||||
|
||||
static void test_url_parsing_and_generation(void) {
|
||||
printf("\n=== test_url_parsing_and_generation ===\n");
|
||||
|
||||
const char* bunker = "bunker://fa984bd7dbb282f07e16e7ae87b26a2a7b9b90b7246a44771f0cf5ae58018f52?relay=wss%3A%2F%2Frelay1.example.com&relay=wss%3A%2F%2Frelay2.example.com&secret=s3cr3t";
|
||||
nostr_nip46_bunker_url_t bu;
|
||||
int rc = nostr_nip46_parse_bunker_url(bunker, &bu);
|
||||
expect_int("parse bunker url", NOSTR_SUCCESS, rc);
|
||||
expect_true("bunker pubkey parsed", strcmp(bu.remote_signer_pubkey, "fa984bd7dbb282f07e16e7ae87b26a2a7b9b90b7246a44771f0cf5ae58018f52") == 0);
|
||||
expect_int("bunker relay count", 2, bu.relay_count);
|
||||
expect_true("bunker relay[0] decoded", strcmp(bu.relays[0], "wss://relay1.example.com") == 0);
|
||||
expect_true("bunker secret parsed", strcmp(bu.secret, "s3cr3t") == 0);
|
||||
|
||||
char bunker_roundtrip[2048];
|
||||
rc = nostr_nip46_create_bunker_url(&bu, bunker_roundtrip, sizeof(bunker_roundtrip));
|
||||
expect_int("create bunker url", NOSTR_SUCCESS, rc);
|
||||
expect_true("bunker roundtrip has scheme", strstr(bunker_roundtrip, "bunker://") == bunker_roundtrip);
|
||||
|
||||
const char* nc = "nostrconnect://83f3b2ae6aa368e8275397b9c26cf550101d63ebaab900d19dd4a4429f5ad8f5?relay=wss%3A%2F%2Frelay1.example.com&secret=0s8j2djs&perms=nip44_encrypt%2Csign_event%3A1&name=My+Client&url=https%3A%2F%2Fclient.example.com";
|
||||
nostr_nip46_nostrconnect_url_t nu;
|
||||
rc = nostr_nip46_parse_nostrconnect_url(nc, &nu);
|
||||
expect_int("parse nostrconnect url", NOSTR_SUCCESS, rc);
|
||||
expect_int("nostrconnect relay count", 1, nu.relay_count);
|
||||
expect_true("nostrconnect secret parsed", strcmp(nu.secret, "0s8j2djs") == 0);
|
||||
expect_true("nostrconnect name decoded (+ to space)", strcmp(nu.name, "My Client") == 0);
|
||||
|
||||
char nc_roundtrip[2048];
|
||||
rc = nostr_nip46_create_nostrconnect_url(&nu, nc_roundtrip, sizeof(nc_roundtrip));
|
||||
expect_int("create nostrconnect url", NOSTR_SUCCESS, rc);
|
||||
expect_true("nostrconnect roundtrip has scheme", strstr(nc_roundtrip, "nostrconnect://") == nc_roundtrip);
|
||||
}
|
||||
|
||||
static void test_request_response_roundtrip(void) {
|
||||
printf("\n=== test_request_response_roundtrip ===\n");
|
||||
|
||||
char id[65];
|
||||
int rc = nostr_nip46_generate_request_id(id, sizeof(id));
|
||||
expect_int("generate request id", NOSTR_SUCCESS, rc);
|
||||
expect_true("request id hex length", strlen(id) == 32);
|
||||
|
||||
const char* params[] = {"abc", "def"};
|
||||
nostr_nip46_request_t req;
|
||||
rc = nostr_nip46_create_request(id, NOSTR_NIP46_METHOD_PING, params, 2, &req);
|
||||
expect_int("create request", NOSTR_SUCCESS, rc);
|
||||
|
||||
char* req_json = NULL;
|
||||
rc = nostr_nip46_request_to_json(&req, &req_json);
|
||||
expect_int("request to json", NOSTR_SUCCESS, rc);
|
||||
|
||||
nostr_nip46_request_t parsed_req;
|
||||
rc = nostr_nip46_parse_request(req_json, &parsed_req);
|
||||
expect_int("parse request", NOSTR_SUCCESS, rc);
|
||||
expect_true("parsed request id matches", strcmp(parsed_req.id, id) == 0);
|
||||
expect_true("parsed request method string", strcmp(parsed_req.method_str, "ping") == 0);
|
||||
expect_int("parsed request param count", 2, parsed_req.param_count);
|
||||
|
||||
free(req_json);
|
||||
nostr_nip46_free_request(&req);
|
||||
nostr_nip46_free_request(&parsed_req);
|
||||
|
||||
nostr_nip46_response_t resp;
|
||||
rc = nostr_nip46_create_response(id, "pong", NULL, &resp);
|
||||
expect_int("create response", NOSTR_SUCCESS, rc);
|
||||
|
||||
char* resp_json = NULL;
|
||||
rc = nostr_nip46_response_to_json(&resp, &resp_json);
|
||||
expect_int("response to json", NOSTR_SUCCESS, rc);
|
||||
|
||||
nostr_nip46_response_t parsed_resp;
|
||||
rc = nostr_nip46_parse_response(resp_json, &parsed_resp);
|
||||
expect_int("parse response", NOSTR_SUCCESS, rc);
|
||||
expect_true("parsed response id matches", strcmp(parsed_resp.id, id) == 0);
|
||||
expect_true("parsed response result matches", strcmp(parsed_resp.result, "pong") == 0);
|
||||
|
||||
free(resp_json);
|
||||
nostr_nip46_free_response(&resp);
|
||||
nostr_nip46_free_response(&parsed_resp);
|
||||
}
|
||||
|
||||
static void test_event_encryption_flow(void) {
|
||||
printf("\n=== test_event_encryption_flow ===\n");
|
||||
|
||||
const char* client_sk_hex = "91ba716fa9e7ea2fcbad360cf4f8e0d312f73984da63d90f524ad61a6a1e7dbe";
|
||||
const char* signer_sk_hex = "96f6fa197aa07477ab88f6981118466ae3a982faab8ad5db9d5426870c73d220";
|
||||
|
||||
unsigned char client_sk[32], signer_sk[32];
|
||||
unsigned char signer_pk[32];
|
||||
int rc = hex_to_bytes32(client_sk_hex, client_sk);
|
||||
expect_int("client sk parse", 0, rc);
|
||||
rc = hex_to_bytes32(signer_sk_hex, signer_sk);
|
||||
expect_int("signer sk parse", 0, rc);
|
||||
rc = nostr_ec_public_key_from_private_key(signer_sk, signer_pk);
|
||||
expect_int("derive signer public key", 0, rc);
|
||||
|
||||
const char* params[] = {"hello"};
|
||||
nostr_nip46_request_t req;
|
||||
rc = nostr_nip46_create_request("abc123", NOSTR_NIP46_METHOD_PING, params, 1, &req);
|
||||
expect_int("create ping request", NOSTR_SUCCESS, rc);
|
||||
|
||||
cJSON* evt = nostr_nip46_create_request_event(&req, client_sk, signer_pk, 0);
|
||||
expect_true("create encrypted request event", evt != NULL);
|
||||
|
||||
char decrypted[65536];
|
||||
rc = nostr_nip46_decrypt_event(evt, signer_sk, decrypted, sizeof(decrypted));
|
||||
expect_int("decrypt request event", NOSTR_SUCCESS, rc);
|
||||
expect_true("decrypted payload has method ping", strstr(decrypted, "\"method\":\"ping\"") != NULL);
|
||||
|
||||
cJSON_Delete(evt);
|
||||
nostr_nip46_free_request(&req);
|
||||
}
|
||||
|
||||
static void test_signer_handle_request(void) {
|
||||
printf("\n=== test_signer_handle_request ===\n");
|
||||
|
||||
const char* signer_sk_hex = "96f6fa197aa07477ab88f6981118466ae3a982faab8ad5db9d5426870c73d220";
|
||||
const char* user_sk_hex = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
unsigned char signer_sk[32], user_sk[32];
|
||||
|
||||
int rc = hex_to_bytes32(signer_sk_hex, signer_sk);
|
||||
expect_int("parse signer sk", 0, rc);
|
||||
rc = hex_to_bytes32(user_sk_hex, user_sk);
|
||||
expect_int("parse user sk", 0, rc);
|
||||
|
||||
const char* relays[] = {"wss://relay.example.com"};
|
||||
nostr_nip46_signer_session_t ss;
|
||||
rc = nostr_nip46_signer_session_init(&ss, signer_sk, user_sk, relays, 1);
|
||||
expect_int("signer session init", NOSTR_SUCCESS, rc);
|
||||
|
||||
const char* connect_params[] = { ss.signer_pubkey_hex, "secret123" };
|
||||
nostr_nip46_request_t connect_req;
|
||||
rc = nostr_nip46_create_request("req-connect", NOSTR_NIP46_METHOD_CONNECT, connect_params, 2, &connect_req);
|
||||
expect_int("build connect request", NOSTR_SUCCESS, rc);
|
||||
|
||||
nostr_nip46_response_t connect_resp;
|
||||
rc = nostr_nip46_signer_handle_request(&ss, &connect_req, &connect_resp);
|
||||
expect_int("handle connect request", NOSTR_SUCCESS, rc);
|
||||
expect_true("connect returns provided secret", connect_resp.result && strcmp(connect_resp.result, "secret123") == 0);
|
||||
nostr_nip46_free_request(&connect_req);
|
||||
nostr_nip46_free_response(&connect_resp);
|
||||
|
||||
nostr_nip46_request_t ping_req;
|
||||
rc = nostr_nip46_create_request("req-ping", NOSTR_NIP46_METHOD_PING, NULL, 0, &ping_req);
|
||||
expect_int("build ping request", NOSTR_SUCCESS, rc);
|
||||
|
||||
nostr_nip46_response_t ping_resp;
|
||||
rc = nostr_nip46_signer_handle_request(&ss, &ping_req, &ping_resp);
|
||||
expect_int("handle ping request", NOSTR_SUCCESS, rc);
|
||||
expect_true("ping response is pong", ping_resp.result && strcmp(ping_resp.result, "pong") == 0);
|
||||
nostr_nip46_free_request(&ping_req);
|
||||
nostr_nip46_free_response(&ping_resp);
|
||||
|
||||
nostr_nip46_request_t gpk_req;
|
||||
rc = nostr_nip46_create_request("req-gpk", NOSTR_NIP46_METHOD_GET_PUBLIC_KEY, NULL, 0, &gpk_req);
|
||||
expect_int("build get_public_key request", NOSTR_SUCCESS, rc);
|
||||
|
||||
nostr_nip46_response_t gpk_resp;
|
||||
rc = nostr_nip46_signer_handle_request(&ss, &gpk_req, &gpk_resp);
|
||||
expect_int("handle get_public_key request", NOSTR_SUCCESS, rc);
|
||||
expect_true("get_public_key returns hex", gpk_resp.result && strlen(gpk_resp.result) == 64);
|
||||
nostr_nip46_free_request(&gpk_req);
|
||||
nostr_nip46_free_response(&gpk_resp);
|
||||
|
||||
cJSON* tags = cJSON_CreateArray();
|
||||
cJSON* unsigned_event = cJSON_CreateObject();
|
||||
cJSON_AddNumberToObject(unsigned_event, "kind", 1);
|
||||
cJSON_AddStringToObject(unsigned_event, "content", "hello signer");
|
||||
cJSON_AddItemToObject(unsigned_event, "tags", tags);
|
||||
cJSON_AddNumberToObject(unsigned_event, "created_at", (double)time(NULL));
|
||||
|
||||
char* unsigned_event_json = cJSON_PrintUnformatted(unsigned_event);
|
||||
cJSON_Delete(unsigned_event);
|
||||
|
||||
const char* sign_params[] = { unsigned_event_json };
|
||||
nostr_nip46_request_t sign_req;
|
||||
rc = nostr_nip46_create_request("req-sign", NOSTR_NIP46_METHOD_SIGN_EVENT, sign_params, 1, &sign_req);
|
||||
expect_int("build sign_event request", NOSTR_SUCCESS, rc);
|
||||
|
||||
nostr_nip46_response_t sign_resp;
|
||||
rc = nostr_nip46_signer_handle_request(&ss, &sign_req, &sign_resp);
|
||||
expect_int("handle sign_event request", NOSTR_SUCCESS, rc);
|
||||
expect_true("sign_event response contains id field", sign_resp.result && strstr(sign_resp.result, "\"id\"") != NULL);
|
||||
expect_true("sign_event response contains sig field", sign_resp.result && strstr(sign_resp.result, "\"sig\"") != NULL);
|
||||
|
||||
nostr_nip46_free_request(&sign_req);
|
||||
nostr_nip46_free_response(&sign_resp);
|
||||
free(unsigned_event_json);
|
||||
|
||||
nostr_nip46_signer_session_destroy(&ss);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
printf("🧪 NIP-46 Test Suite\n");
|
||||
printf("===================\n");
|
||||
|
||||
int init_rc = nostr_init();
|
||||
if (init_rc != NOSTR_SUCCESS) {
|
||||
printf("❌ Failed to initialize nostr library: %s\n", nostr_strerror(init_rc));
|
||||
return 1;
|
||||
}
|
||||
|
||||
test_url_parsing_and_generation();
|
||||
test_request_response_roundtrip();
|
||||
test_event_encryption_flow();
|
||||
test_signer_handle_request();
|
||||
|
||||
nostr_cleanup();
|
||||
|
||||
printf("\n=== RESULT ===\n");
|
||||
printf("Passed %d / %d tests\n", tests_passed, tests_run);
|
||||
|
||||
return (tests_passed == tests_run) ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
#define _DEFAULT_SOURCE
|
||||
#include "../nostr_core/nostr_core.h"
|
||||
#include "../cjson/cJSON.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// Test callback function
|
||||
static int callback_count = 0;
|
||||
|
||||
void test_callback(const char* relay_url, const char* event_id,
|
||||
int success, const char* message, void* user_data) {
|
||||
(void)event_id; // Suppress unused parameter warning
|
||||
(void)user_data; // Suppress unused parameter warning
|
||||
|
||||
callback_count++;
|
||||
printf("📡 Callback %d: Relay %s, Success: %s\n",
|
||||
callback_count, relay_url, success ? "YES" : "NO");
|
||||
if (message) {
|
||||
printf(" Message: %s\n", message);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
printf("🧪 Simple Async Publish Test\n");
|
||||
printf("============================\n");
|
||||
|
||||
// Create pool
|
||||
nostr_relay_pool_t* pool = nostr_relay_pool_create(NULL);
|
||||
if (!pool) {
|
||||
printf("❌ Failed to create pool\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Create a test event
|
||||
cJSON* event = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(event, "id", "test_event_simple");
|
||||
cJSON_AddNumberToObject(event, "kind", 1);
|
||||
cJSON_AddStringToObject(event, "content", "Test async publish");
|
||||
cJSON_AddNumberToObject(event, "created_at", time(NULL));
|
||||
cJSON_AddStringToObject(event, "pubkey", "test_pubkey");
|
||||
cJSON_AddStringToObject(event, "sig", "test_signature");
|
||||
|
||||
// Test with non-existent relay (should trigger connection failure callback)
|
||||
const char* test_relays[] = {"ws://nonexistent.example.com"};
|
||||
|
||||
printf("🚀 Testing async publish...\n");
|
||||
|
||||
// Call async publish
|
||||
int sent_count = nostr_relay_pool_publish_async(
|
||||
pool, test_relays, 1, event, test_callback, NULL);
|
||||
|
||||
printf("📊 Sent to %d relays\n", sent_count);
|
||||
|
||||
// Wait a bit for callback
|
||||
printf("⏳ Waiting for callback...\n");
|
||||
for (int i = 0; i < 5 && callback_count == 0; i++) {
|
||||
nostr_relay_pool_poll(pool, 100);
|
||||
usleep(100000); // 100ms
|
||||
}
|
||||
|
||||
printf("\n📈 Results:\n");
|
||||
printf(" Callbacks received: %d\n", callback_count);
|
||||
|
||||
// Cleanup
|
||||
cJSON_Delete(event);
|
||||
nostr_relay_pool_destroy(pool);
|
||||
|
||||
printf("\n✅ Simple async test completed!\n");
|
||||
|
||||
return callback_count > 0 ? 0 : 1;
|
||||
}
|
||||
Reference in New Issue
Block a user