### Example: Whitelist Plugin (JavaScript) Source: https://github.com/hoytech/strfry/blob/master/docs/plugins.md A practical example of a JavaScript plugin that accepts only events from a predefined list of public keys. ```APIDOC ## Example: Whitelist Plugin (JavaScript) This example demonstrates a simple JavaScript plugin that maintains a whitelist of public keys and rejects any events not originating from those keys. ### Script (`whitelist.js`) ```javascript #!/usr/bin/env node const whiteList = { '003ba9b2c5bd8afeed41a4ce362a8b7fc3ab59c25b6a1359cae9093f296dac01': true, // Add more whitelisted pubkeys here }; const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout, terminal: false }); readline.on('line', (line) => { let req; try { req = JSON.parse(line); } catch (e) { console.error("Failed to parse JSON input:", e); // Log to strfry's stderr return; } if (req.type !== 'new') { console.error("Unexpected request type:", req.type); // Log to strfry's stderr return; } let res = { id: req.event.id }; // Must echo the event's id if (whiteList[req.event.pubkey]) { res.action = 'accept'; } else { res.action = 'reject'; res.msg = 'blocked: not on white-list'; } // Ensure output is stringified JSON followed by a newline console.log(JSON.stringify(res)); }); // Handle potential errors during input reading readline.on('error', (err) => { console.error('Error reading from stdin:', err); }); ``` ### Installation and Configuration 1. **Make the script executable**: ```bash chmod a+x whitelist.js ``` 2. **Configure Strfry**: Add the following line to your `strfry.conf` or a relevant router configuration file: ``` relay.writePolicy.plugin = "./whitelist.js" ``` (Ensure the path `./whitelist.js` is correct relative to where Strfry is run or is an absolute path.) * **Reloading**: The plugin will be reloaded automatically if its modification time changes. If the plugin command itself changes in the configuration file, Strfry will also reload the plugin. ``` -------------------------------- ### Minimal strfry Configuration Source: https://github.com/hoytech/strfry/blob/master/README.md A minimal configuration example for strfry requiring only the database path. ```text db = "/path/to/db/" ``` -------------------------------- ### strfry router configuration example Source: https://github.com/hoytech/strfry/blob/master/docs/router.md An example configuration file for strfry router, demonstrating top-level settings and stream definitions. It includes connection timeouts, verbosity, and multiple stream configurations with different directions, plugins, URLs, and filters. ```config connectionTimeout = 20 verbose = false streams { ## Stream down events from our friend relays friends { dir = "down" pluginDown = "/home/user/spam-filter.js" urls = [ "wss://nos.lol" "wss://relayable.org" ] } ## Bi-directional streaming within our cluster cluster { dir = "both" urls = [ "wss://eu.example.com" "wss://na.example.com" ] } ## Backup profiles and contact lists to our directory node directory { dir = "up" filter = { "kinds": [0, 3] } urls = [ "ws://internal-directory.example.com" ] } } ``` -------------------------------- ### Build and Install strfry from Source Source: https://github.com/hoytech/strfry/blob/master/docs/DEPLOYMENT.md Commands to update system dependencies, clone the repository, build the binary, and move it to the system path. ```bash sudo apt update git clone https://github.com/hoytech/strfry.git cd strfry sudo apt install -y git build-essential libyaml-perl libtemplate-perl libregexp-grammars-perl libssl-dev zlib1g-dev liblmdb-dev libflatbuffers-dev libsecp256k1-dev libzstd-dev ufw git submodule update --init make setup-golpe make -j2 sudo cp strfry /usr/local/bin ``` -------------------------------- ### Run Strfry Router Source: https://context7.com/hoytech/strfry/llms.txt Starts the Strfry router service with a specified configuration file. This is the primary command to get the relay operational. ```bash ./strfry router strfry-router.config ``` -------------------------------- ### Run strfry Relay Source: https://github.com/hoytech/strfry/blob/master/README.md Command to start the strfry relay process using the default configuration file. ```bash ./strfry relay ``` -------------------------------- ### strfry router command example Source: https://github.com/hoytech/strfry/blob/master/docs/router.md This command initiates the strfry router, specifying the path to its configuration file. The router will then parse the config and establish connections to the defined relays. ```bash strfry router strfry-router.config ``` -------------------------------- ### Configure strfry Relay Source: https://context7.com/hoytech/strfry/llms.txt Example configuration file structure for defining database paths, relay settings, and NIP-11 information. ```text db = "/var/lib/strfry/" dbParams { maxreaders = 256 mapsize = 10995116277760 noReadAhead = false } events { maxEventSize = 65536 rejectEventsNewerThanSeconds = 900 rejectEventsOlderThanSeconds = 94608000 maxNumTags = 2000 maxTagValSize = 1024 } relay { bind = "0.0.0.0" port = 7777 nofiles = 1000000 realIpHeader = "x-real-ip" auth { enabled = true serviceUrl = "wss://my-relay.com" } info { name = "My Relay" description = "A strfry nostr relay" pubkey = "003ba9b2c5bd8afeed41a4ce362a8b7fc3ab59c25b6a1359cae9093f296dac01" contact = "admin@example.com" } writePolicy { plugin = "/path/to/policy.js" timeoutSeconds = 10 } compression { enabled = true slidingWindow = true } negentropy { enabled = true maxSyncEvents = 1000000 } } ``` -------------------------------- ### Start strfry Relay Source: https://context7.com/hoytech/strfry/llms.txt Commands to initiate the strfry relay process using default or custom configuration files. ```bash # Start relay with default config (./strfry.conf) ./strfry relay # Start relay with custom config file ./strfry --config /etc/strfry.conf relay # Using environment variable for config STRFRY_CONFIG=/etc/strfry.conf ./strfry relay ``` -------------------------------- ### Compile strfry on FreeBSD Source: https://github.com/hoytech/strfry/blob/master/README.md Commands to install dependencies and build the strfry binary on FreeBSD systems using gmake. ```bash pkg install -y gcc gmake cmake git perl5 openssl lmdb flatbuffers libuv libinotify zstr secp256k1 zlib-ng git clone https://github.com/hoytech/strfry && cd strfry/ git submodule update --init gmake setup-golpe gmake -j4 ``` -------------------------------- ### Zero Downtime Restart using REUSE_PORT Source: https://context7.com/hoytech/strfry/llms.txt Demonstrates how to restart Strfry without disconnecting existing clients by leveraging the REUSE_PORT mechanism. This involves starting a new instance and then gracefully shutting down the old one. ```bash # Record current PID OLD_PID=$(pgrep -f "strfry relay") # Start new instance (both will accept connections) ./strfry relay & # Initiate graceful shutdown of old instance kill -USR1 $OLD_PID # Old instance stops accepting new connections # and exits after all existing connections close ``` -------------------------------- ### Compile strfry on Linux/Debian Source: https://github.com/hoytech/strfry/blob/master/README.md Commands to install dependencies and build the strfry binary on Debian or Ubuntu systems using make. ```bash sudo apt install -y git g++ make libssl-dev zlib1g-dev liblmdb-dev libflatbuffers-dev libsecp256k1-dev libzstd-dev git clone https://github.com/hoytech/strfry && cd strfry/ git submodule update --init make setup-golpe make -j4 ``` -------------------------------- ### Negentropy Protocol Message Examples (JSON) Source: https://context7.com/hoytech/strfry/llms.txt Examples of messages used in the Negentropy protocol for client-relay synchronization. These include initiating sync (NEG-OPEN), sending reconciliation data (NEG-MSG), error responses (NEG-ERR), and closing sessions (NEG-CLOSE). ```json // NEG-OPEN: Client initiates sync with filter ["NEG-OPEN", "sub1", {"kinds": [1]}, "616263646566..."] // NEG-MSG: Bidirectional reconciliation messages ["NEG-MSG", "sub1", "686970717273..."] // NEG-ERR: Error response from relay ["NEG-ERR", "sub1", "blocked: this query is too big"] // NEG-CLOSE: Client closes sync session ["NEG-CLOSE", "sub1"] ``` -------------------------------- ### Execute Event Writing Tests Source: https://github.com/hoytech/strfry/blob/master/test/README.md Runs the event writing test suite. This script requires the nostril utility to be installed and available in the system path. ```bash perl test/writeTest.pl ``` -------------------------------- ### Systemd Service for Strfry Source: https://context7.com/hoytech/strfry/llms.txt Defines a systemd service unit for running Strfry as a daemon. It includes configurations for user, restart behavior, and resource limits, along with commands to enable, start, and manage the service. ```ini # /etc/systemd/system/strfry.service [Unit] Description=strfry relay service After=network.target [Service] User=strfry ExecStart=/usr/local/bin/strfry relay Restart=on-failure RestartSec=5 ProtectHome=yes NoNewPrivileges=yes ProtectSystem=full LimitCORE=1000000000 LimitNOFILE=524288 [Install] WantedBy=multi-user.target ``` ```bash # Enable and start service sudo systemctl enable strfry.service sudo systemctl start strfry sudo systemctl status strfry # View logs journalctl -u strfry -f ``` -------------------------------- ### NGINX Reverse Proxy Configuration for Strfry Source: https://context7.com/hoytech/strfry/llms.txt Provides an NGINX configuration to act as a reverse proxy for Strfry, including SSL termination and WebSocket support. This setup allows Strfry to be accessed securely over HTTPS. ```nginx server { listen 443 ssl http2; server_name relay.yourdomain.com; ssl_certificate /etc/letsencrypt/live/relay.yourdomain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/relay.yourdomain.com/privkey.pem; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_pass http://127.0.0.1:7777; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 86400; } } ``` -------------------------------- ### Import Dataset for Fuzz Testing Source: https://github.com/hoytech/strfry/blob/master/test/README.md Imports a JSONL dataset into the strfry database to prepare for fuzz testing. It uses zstdcat to decompress the source file and pipes it into the strfry import command. ```bash zstdcat ../nostr-dumps/nostr-wellorder-early-500k-v1.jsonl.zst | ./strfry import ``` -------------------------------- ### Uploading and Downloading Events Source: https://github.com/hoytech/strfry/blob/master/README.md Instructions for uploading events to relays using `strfry upload` and downloading events from relays using `strfry download`. ```APIDOC ## Uploading Events with `strfry upload` ### Description Uploads Nostr events from standard input (minified JSONL) to a specified WebSocket relay. ### Method Command-line tool ### Endpoint `wss://relay.example.com` (WebSocket URL) ### Parameters #### Command Arguments - **relay_url** (string) - Required - The WebSocket URL of the relay to upload to. - **--pipeline** (integer) - Optional - The number of events to keep in flight (default: 50). ### Request Example ```bash cat my-events.jsonl | ./strfry upload wss://relay.example.com ``` ### Response Events are sent to the specified relay. The command exits after the input stream is fully processed. ## Downloading Events with `strfry download` ### Description Connects to a remote relay, retrieves events matching a filter, and prints them to standard output in JSONL format. ### Method Command-line tool ### Endpoint `wss://relay.example.com` (WebSocket URL) ### Parameters #### Command Arguments - **relay_url** (string) - Required - The WebSocket URL of the relay to download from. - **--filter** (string) - Optional - A JSON string representing the Nostr filter (NIP-01). Defaults to `{}` (all events). - **--range** (string) - Optional - Specifies a time range for the filter (e.g., `2h-`, `1Y-6M`). Units: s, m, h, d, w, M, Y. ### Request Example ```bash ./strfry download wss://relay.relay.com --filter '{"kinds":[0]}' > my-events.jsonl ``` ### Response Events matching the filter are printed to standard output in JSONL format. The command exits after retrieving all stored events from the relay. ``` -------------------------------- ### Importing and Exporting Data Source: https://github.com/hoytech/strfry/blob/master/README.md Details on how to import events from JSONL files using `strfry import` and export events to JSONL using `strfry export`. ```APIDOC ## Importing Data with `strfry import` ### Description Reads line-delimited JSON (JSONL) from standard input and imports valid Nostr events into the database in batches. ### Method Command-line tool ### Endpoint N/A (Local database operation) ### Parameters #### Command Arguments - **--no-verify** (flag) - Optional - Skips signature and field verification for faster imports if data is known to be valid. ### Request Example ```bash cat my-nostr-dump.jsonl | ./strfry import ``` ### Response Events are imported into the database. ## Exporting Data with `strfry export` ### Description Prints events from the database to standard output in JSONL format, ordered by `created_at`. ### Method Command-line tool ### Endpoint N/A (Local database operation) ### Parameters #### Command Arguments - **--since** (timestamp) - Optional - Exports events created after this timestamp. - **--until** (timestamp) - Optional - Exports events created before this timestamp. - **--reverse** (flag) - Optional - Reverses the order of events (newest first). - **--fried** (flag) - Optional - Outputs JSON lines with `fried` elements for faster re-import. ### Request Example ```bash ./strfry export --since 1678886400 --until 1678972800 ``` ### Response Events exported in JSONL format to standard output. ``` -------------------------------- ### Configure System Firewall Source: https://github.com/hoytech/strfry/blob/master/docs/DEPLOYMENT.md Commands to secure the server by setting default policies and allowing necessary traffic for SSH and NGINX. ```bash sudo ufw allow 'Nginx Full' sudo ufw default deny incoming sudo ufw default allow outgoing ufw allow 22/tcp sudo ufw enable ``` -------------------------------- ### Import Events to Database Source: https://context7.com/hoytech/strfry/llms.txt Import events from JSONL files into the strfry database, supporting various formats and verification options. ```bash cat my-nostr-dump.jsonl | ./strfry import cat my-nostr-dump.jsonl | ./strfry import --no-verify cat dbdump-fried.jsonl | ./strfry import --fried zcat events.jsonl.gz | ./strfry import ``` -------------------------------- ### Selecting and Deleting Events Source: https://github.com/hoytech/strfry/blob/master/README.md Learn how to select events using Nostr filters with `strfry scan` and delete events matching filters with `strfry delete`. ```APIDOC ## Selecting Events with `strfry scan` ### Description Scans the database for events matching a given Nostr filter and prints them to standard output in JSONL format. ### Method Command-line tool ### Endpoint N/A (Local database operation) ### Parameters #### Command Arguments - **filter** (string) - Required - A JSON string representing the Nostr filter (NIP-01). ### Request Example ```bash ./strfry scan '{"kinds":[0,1]}' ``` ### Response Events matching the filter, each on a new line in JSONL format. ## Deleting Events with `strfry delete` ### Description Deletes events from the database that match a specified Nostr filter. ### Method Command-line tool ### Endpoint N/A (Local database operation) ### Parameters #### Command Arguments - **--filter** (string) - Required - A JSON string representing the Nostr filter (NIP-01). ### Request Example ```bash ./strfry delete --filter '{"authors":["4c7a4fa1a6842266f3f8ca4f19516cf6aa8b5ff6063bc3ec5c995e61e5689c39"]}' ``` ### Response No explicit response, but events matching the filter are removed from the database. ``` -------------------------------- ### Scan Events via CLI Source: https://context7.com/hoytech/strfry/llms.txt Query the local database using nostr filters to retrieve specific events based on kinds, authors, tags, or time ranges. ```bash ./strfry scan '{"kinds":[0,1]}' ./strfry scan '{"authors":["003ba9b2c5bd8afeed41a4ce362a8b7fc3ab59c25b6a1359cae9093f296dac01"]}' ./strfry scan '{"#p":["003ba9b2c5bd8afeed41a4ce362a8b7fc3ab59c25b6a1359cae9093f296dac01"]}' ./strfry scan '{"since":1704067200,"until":1706745600}' ./strfry scan '{"kinds":[1],"authors":["003ba9b2c5bd8afeed41a4ce362a8b7fc3ab59c25b6a1359cae9093f296dac01"],"limit":100}' ``` -------------------------------- ### Define Systemd Service for strfry Source: https://github.com/hoytech/strfry/blob/master/docs/DEPLOYMENT.md Systemd unit file configuration to manage the strfry relay as a background service with appropriate security constraints. ```ini [Unit] Description=strfry relay service [Service] User=strfry ExecStart=/usr/local/bin/strfry relay Restart=on-failure RestartSec=5 ProtectHome=yes NoNewPrivileges=yes ProtectSystem=full LimitCORE=1000000000 [Install] WantedBy=multi-user.target ``` -------------------------------- ### Import and Export Event Data Source: https://github.com/hoytech/strfry/blob/master/README.md Import events from line-delimited JSON files into the database, or export existing events to stdout. Exporting supports time-based filtering and precomputed 'fried' data for faster re-imports. ```bash cat my-nostr-dump.jsonl | ./strfry import ./strfry export --since 1700000000 > output.jsonl ``` -------------------------------- ### Upload and Download Events via Relay Source: https://github.com/hoytech/strfry/blob/master/README.md Upload events from stdin to a remote relay or download events from a relay based on specific filters. These commands support piping and range-based time filtering. ```bash cat my-events.jsonl | ./strfry upload wss://relay.example.com ./strfry download wss://relay.example.com --filter '{"kinds":[0]}' > my-events.jsonl ``` -------------------------------- ### Select and Delete Events with Filters Source: https://github.com/hoytech/strfry/blob/master/README.md Use the scan command to retrieve events matching a specific Nostr filter, or the delete command to remove them from the database. Both commands accept JSON-formatted filters as arguments. ```bash ./strfry scan '{"kinds":[0,1]}' ./strfry delete --filter '{"authors":["4c7a4fa1a6842266f3f8ca4f19516cf6aa8b5ff6063bc3ec5c995e61e5689c39"]}' ``` -------------------------------- ### Run Fuzz Tests for Query and Monitor Engines Source: https://github.com/hoytech/strfry/blob/master/test/README.md Executes fuzz tests against the query and monitor engines using Perl scripts. These tests are deterministic and can be configured with a SEED environment variable. ```bash perl test/filterFuzzTest.pl scan-limit perl test/filterFuzzTest.pl scan perl test/filterFuzzTest.pl monitor ``` -------------------------------- ### Upgrade Strfry Database Source: https://github.com/hoytech/strfry/blob/master/README.md Upgrades the database format by exporting the current data to a JSONL file and re-importing it. This is required when the strfry binary version is incompatible with the existing database. ```bash ./strfry export --fried > dbdump.jsonl mv strfry-db/data.mdb data.mdb.bak ./strfry import --fried < dbdump.jsonl ``` -------------------------------- ### Strfry Router Configuration Source: https://context7.com/hoytech/strfry/llms.txt Configuration file for the strfry router, which manages streaming events between multiple relays. Defines connection timeouts, verbosity, and various streams with specific directions, filters, and target relay URLs. ```plaintext // strfry-router.config connectionTimeout = 20 verbose = false streams { // Stream down events from friend relays with spam filtering friends { dir = "down" pluginDown = "/home/user/spam-filter.js" urls = [ "wss://nos.lol" "wss://relayable.org" ] } // Bi-directional streaming within a cluster cluster { dir = "both" urls = [ "wss://eu.example.com" "wss://na.example.com" ] } // Backup profiles and contact lists to directory node directory { dir = "up" filter = { "kinds": [0, 3] } urls = [ "ws://internal-directory.example.com" ] } // Stream only text notes from specific authors curated { dir = "down" filter = { "kinds": [1], "authors": ["003ba9b2c5bd8afeed41a4ce362a8b7fc3ab59c25b6a1359cae9093f296dac01"] } urls = [ "wss://relay.damus.io" ] } } ``` -------------------------------- ### Sync Local DB with Remote Relay Source: https://context7.com/hoytech/strfry/llms.txt Synchronizes the local database with a remote relay using the negentropy protocol for efficient set reconciliation. Supports full sync, bidirectional sync, upload-only, and sync with specific filters or time ranges. ```bash # Full DB sync (download missing events from remote) ./strfry sync wss://relay.example.com # Bidirectional sync (exchange events both ways) ./strfry sync wss://relay.example.com --dir both # Upload only (send local events to remote) ./strfry sync wss://relay.example.com --dir up # Sync with specific filter ./strfry sync wss://relay.example.com --filter '{"authors":["003ba9b2c5bd8afeed41a4ce362a8b7fc3ab59c25b6a1359cae9093f296dac01"]}' # Sync with time range ./strfry sync wss://relay.example.com --range 1w- # Sync multiple filters (JSON array) ./strfry sync wss://relay.example.com --filter '[{"kinds":[0]},{"kinds":[3]}]' ``` -------------------------------- ### Manage Zstd Compression Dictionaries Source: https://context7.com/hoytech/strfry/llms.txt Utilizes zstd dictionaries to compress events stored on disk. This includes training a dictionary on specific event kinds, compressing events using the dictionary, viewing compression statistics, and decompressing events. ```bash # Train a dictionary on specific event kinds ./strfry dict train --filter '{"kinds":[1]}' --output dict-kind1.zstd # Compress events using the dictionary ./strfry dict compress --filter '{"kinds":[1]}' --dict dict-kind1.zstd # View compression statistics ./strfry dict stats # Decompress events back to original ./strfry dict decompress --filter '{"kinds":[1]}' ``` -------------------------------- ### Upload Events to Remote Relay Source: https://context7.com/hoytech/strfry/llms.txt Stream events from a local JSONL file to a remote nostr relay via websocket. ```bash cat my-events.jsonl | ./strfry upload wss://relay.example.com ``` -------------------------------- ### Upgrade LMDB Database Source: https://context7.com/hoytech/strfry/llms.txt Upgrades the database when strfry version changes introduce incompatible DB formats. This process involves exporting the current database, backing up the old one, and then importing into the new format. Finally, it verifies the import and cleans up temporary files. ```bash # Export with fried format for faster re-import ./strfry export --fried > dbdump.jsonl # Backup old database mv strfry-db/data.mdb data.mdb.bak # Import into new format ./strfry import --fried < dbdump.jsonl # Verify and clean up ./strfry scan '{}' | wc -l # Count events rm dbdump.jsonl data.mdb.bak ``` -------------------------------- ### Upload Events to Relay Source: https://context7.com/hoytech/strfry/llms.txt Uploads events from a local file or standard input to a specified relay. Supports pipeline depth for increased throughput and filtering of events before upload. ```bash cat my-events.jsonl | ./strfry upload wss://relay.example.com --pipeline 100 ./strfry scan '{"kinds":[0]}' | ./strfry upload wss://relay.example.com ./strfry scan '{"authors":["003ba9b2c5bd8afeed41a4ce362a8b7fc3ab59c25b6a1359cae9093f296dac01"]}' | ./strfry upload wss://relay.example.com ``` -------------------------------- ### Export Events from Database Source: https://context7.com/hoytech/strfry/llms.txt Export stored events to JSONL format with options for filtering, ordering, and compression. ```bash ./strfry export > all-events.jsonl ./strfry export --since 1704067200 --until 1706745600 > january-2024.jsonl ./strfry export --reverse > events-newest-first.jsonl ./strfry export --fried > dbdump-fried.jsonl ./strfry export | gzip > events.jsonl.gz ``` -------------------------------- ### Manage Negentropy BTrees Source: https://context7.com/hoytech/strfry/llms.txt Manages pre-computed BTree structures used for efficient negentropy sync operations. Allows listing, adding, building, and removing BTrees, each associated with a specific filter. ```bash # List all configured negentropy BTrees ./strfry negentropy list # Output: # tree 1 # filter: {} # size: 483057 # fingerprint: 9faaf0be1c25c1b4ee7e65f18cf4b352 # Add a new BTree for a specific filter ./strfry negentropy add '{"kinds":[0]}' # Output: created tree 2 # to populate, run: strfry negentropy build 2 # Build/populate a BTree ./strfry negentropy build 2 # Remove a BTree ./strfry negentropy remove 2 ``` -------------------------------- ### Configure NGINX Reverse Proxy Source: https://github.com/hoytech/strfry/blob/master/docs/DEPLOYMENT.md Sample configuration for NGINX to proxy WebSocket connections to the local strfry relay instance. ```nginx server{ server_name relay.yourdomain.com; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_pass http://127.0.0.1:7777; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } ``` -------------------------------- ### Synchronize Relay Database Source: https://github.com/hoytech/strfry/blob/master/README.md Performs set reconciliation between the local database and a remote relay using the negentropy protocol. Supports full database syncs or filtered syncs with configurable directions. ```bash ./strfry sync wss://relay.example.com ./strfry sync wss://relay.example.com --dir both ./strfry sync wss://relay.example.com --filter '{"authors":["..."]}' ``` -------------------------------- ### Compact Strfry Database Source: https://github.com/hoytech/strfry/blob/master/README.md Reclaims disk space by compacting the LMDB database file. It is recommended to stop the relay service before performing compaction to ensure data integrity. ```bash ./strfry compact - > strfry-db/data.mdb.compacted mv strfry-db/data.mdb.compacted strfry-db/data.mdb ``` -------------------------------- ### Prometheus Metrics Endpoint Configuration Source: https://context7.com/hoytech/strfry/llms.txt Configures Prometheus to scrape metrics from the built-in Strfry metrics endpoint. It shows how to set up the scrape job in Prometheus and how to fetch metrics directly using curl. ```yaml # prometheus.yml scrape_configs: - job_name: 'strfry' static_configs: - targets: ['localhost:7777'] metrics_path: '/metrics' ``` ```bash # Fetch metrics directly curl http://localhost:7777/metrics # Example output: # nostr_client_messages_total{verb="EVENT"} 12345 # nostr_client_messages_total{verb="REQ"} 67890 # nostr_relay_messages_total{verb="EVENT"} 54321 # nostr_relay_messages_total{verb="OK"} 12345 # nostr_events_total{kind="0"} 1000 # nostr_events_total{kind="1"} 50000 ``` -------------------------------- ### Download Events from Relay Source: https://context7.com/hoytech/strfry/llms.txt Downloads events from a remote relay using REQ requests. Supports downloading all events, events matching a specific filter, or events within a given time range. Can also pipe downloaded events directly for import. ```bash # Download all events (uses default {} filter) ./strfry download wss://relay.example.com > my-events.jsonl # Download with specific filter ./strfry download wss://relay.example.com --filter '{"kinds":[0]}' > profiles.jsonl # Download events from specific time range ./strfry download wss://relay.example.com --range 2h- > last-2-hours.jsonl ./strfry download wss://relay.example.com --range 1Y-6M > six-months-to-year-ago.jsonl # Download and import directly ./strfry download wss://relay.example.com --filter '{"kinds":[1]}' | ./strfry import ``` -------------------------------- ### JavaScript Whitelist Plugin for Strfry Source: https://github.com/hoytech/strfry/blob/master/docs/plugins.md A Node.js script that acts as a Strfry plugin to filter events based on a predefined whitelist of public keys. It reads event data from stdin, checks if the event's public key is in the whitelist, and outputs an 'accept' or 'reject' action to stdout. This plugin requires Node.js and the 'readline' module. ```javascript #!/usr/bin/env node const whiteList = { '003ba9b2c5bd8afeed41a4ce362a8b7fc3ab59c25b6a1359cae9093f296dac01': true, }; const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout, terminal: false }); rl.on('line', (line) => { let req = JSON.parse(line); if (req.type !== 'new') { console.error("unexpected request type"); // will appear in strfry logs return; } let res = { id: req.event.id }; // must echo the event's id if (whiteList[req.event.pubkey]) { res.action = 'accept'; } else { res.action = 'reject'; res.msg = 'blocked: not on white-list'; } console.log(JSON.stringify(res)); }); ``` -------------------------------- ### Event-sifter Plugin Interface Source: https://github.com/hoytech/strfry/blob/master/docs/plugins.md Details the input and output message formats for Strfry event-sifter plugins. ```APIDOC ## Event-sifter Plugin Interface Plugins in Strfry are responsible for implementing policy logic, allowing operators to control which events are stored by the relay. They communicate with Strfry by reading JSON objects from standard input and writing JSON objects to standard output. ### Input Messages Strfry sends the following JSON object to the plugin's stdin for each incoming event: #### Fields - **type** (string) - Currently always `"new"`. - **event** (object) - The event posted by the client, containing fields like `id`, `pubkey`, etc. - **receivedAt** (integer) - Unix timestamp of when the event was received by the relay. - **sourceType** (string) - The channel from which the event originated (e.g., `"IP4"`, `"IP6"`, `"Import"`, `"Stream"`, `"Sync"`, `"Stored"`). - **sourceInfo** (string) - Specific details about the event's source, typically an IP address. - **authed** (string) - Optional. Present if the connection has completed NIP-42 AUTH. Contains the authenticated public key in 32-byte hex format. ### Output Messages In response to a `"new"` event, the plugin must print a JSONL message (minified JSON followed by a newline) to its stdout. This message dictates the action to be taken on the event. #### Fields - **id** (string) - The event ID, which must match the `event.id` from the input message. - **action** (string) - The decision for the event. Must be one of `"accept"`, `"reject"`, or `"shadowReject"`. - **msg** (string) - Optional. A NIP-20 response message to be sent to the client. This is only used when the `action` is `"reject"`. ### Notes on Implementation * **Line Buffering**: Ensure that stdout is line buffered. For Perl, use `$|++`; for Python, use `print(response, flush=True)`. * **Error Handling**: If events are rejected with `error: internal error`, check Strfry logs for plugin misconfiguration or failures. * **Silencing Logs**: To prevent verbose logging when events are rejected, return an empty string for `msg` or omit it entirely. * **Acceptance Guarantee**: An `"accept"` action does not guarantee event acceptance. Strfry applies its own internal checks (e.g., expiration, deletion) after the plugin's decision. ```