mirror of
https://github.com/PR0M3TH3AN/bitvid.git
synced 2026-10-27 16:02:26 +00:00
Merge pull request #1798 from PR0M3TH3AN/ai/interop-tests-20250226-10619676065325825636
Add Nostr protocol interop test script
This commit is contained in:
1 file changed
+107
-165
+107
-165
@@ -1,196 +1,138 @@
|
||||
|
||||
import WebSocket from 'ws';
|
||||
import crypto from 'node:crypto';
|
||||
import './setup-test-env.js';
|
||||
import { NostrClient } from '../../js/nostr/client.js';
|
||||
import {
|
||||
buildVideoPostEvent,
|
||||
buildViewEvent
|
||||
} from '../../js/nostrEventSchemas.js';
|
||||
import * as NostrTools from 'nostr-tools';
|
||||
import { bytesToHex } from '../../vendor/crypto-helpers.bundle.min.js';
|
||||
|
||||
// Polyfills
|
||||
global.WebSocket = WebSocket;
|
||||
// Node 19+ has global.crypto. If not, polyfill it.
|
||||
if (!global.crypto) {
|
||||
global.crypto = crypto;
|
||||
}
|
||||
global.window = {
|
||||
crypto: global.crypto,
|
||||
localStorage: {
|
||||
_store: new Map(),
|
||||
getItem: (key) => global.window.localStorage._store.get(String(key)) || null,
|
||||
setItem: (key, value) => global.window.localStorage._store.set(String(key), String(value)),
|
||||
removeItem: (key) => global.window.localStorage._store.delete(String(key)),
|
||||
clear: () => global.window.localStorage._store.clear(),
|
||||
},
|
||||
location: { href: 'http://localhost' },
|
||||
};
|
||||
global.self = global.window;
|
||||
global.localStorage = global.window.localStorage;
|
||||
globalThis.localStorage = global.window.localStorage; // Ensure globalThis has it
|
||||
// Setup global NostrTools for toolkit.js fallback
|
||||
global.NostrTools = NostrTools;
|
||||
|
||||
// Helpers
|
||||
const bytesToHex = (bytes) => {
|
||||
return Array.from(bytes)
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
};
|
||||
async function waitForEvent(pool, relays, id, timeoutMs = 10000) {
|
||||
const start = Date.now();
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
const event = await pool.get(relays, { ids: [id] });
|
||||
if (event) return event;
|
||||
await new Promise(r => setTimeout(r, 1000));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function runTests() {
|
||||
console.log('Starting Protocol & Interop Tests...');
|
||||
|
||||
// Import application modules after polyfills are set
|
||||
const { NostrClient } = await import('../../js/nostr/client.js');
|
||||
const { buildVideoPostEvent, buildViewEvent } = await import('../../js/nostrEventSchemas.js');
|
||||
async function run() {
|
||||
console.log("Starting Interop Test...");
|
||||
|
||||
// 1. Setup Client
|
||||
const client = new NostrClient();
|
||||
|
||||
// Use test relays
|
||||
const TEST_RELAYS = [
|
||||
'wss://relay.damus.io',
|
||||
'wss://nos.lol',
|
||||
];
|
||||
client.relays = TEST_RELAYS;
|
||||
client.readRelays = TEST_RELAYS;
|
||||
client.writeRelays = TEST_RELAYS;
|
||||
// Test relays - using reputable public relays
|
||||
const TEST_RELAYS = ["wss://relay.damus.io", "wss://nos.lol"];
|
||||
client.relays = [...TEST_RELAYS];
|
||||
|
||||
console.log('Client initialized with relays:', TEST_RELAYS);
|
||||
|
||||
// 2. Generate Ephemeral Keys
|
||||
const sk = NostrTools.generateSecretKey();
|
||||
const skHex = bytesToHex(sk);
|
||||
const pk = NostrTools.getPublicKey(sk);
|
||||
console.log('Generated ephemeral identity:', pk);
|
||||
|
||||
// 3. Register Signer
|
||||
await client.registerPrivateKeySigner({
|
||||
privateKey: skHex,
|
||||
pubkey: pk,
|
||||
});
|
||||
console.log('Signer registered.');
|
||||
|
||||
// 4. Initialize Network
|
||||
await client.init();
|
||||
console.log('Client connected.');
|
||||
console.log(`Using relays: ${TEST_RELAYS.join(', ')}`);
|
||||
|
||||
try {
|
||||
// --- Test A: Video Post ---
|
||||
console.log('\n--- Test A: Video Post ---');
|
||||
// 2. Init (connects to relays)
|
||||
await client.init();
|
||||
|
||||
// Explicitly use schema builder
|
||||
const dTagValue = 'interop-test-' + Date.now();
|
||||
const contentPayload = {
|
||||
version: 3,
|
||||
title: 'Interop Test Video ' + Date.now(),
|
||||
description: 'This is an automated interoperability test event.',
|
||||
url: 'https://example.com/video.mp4',
|
||||
magnet: 'magnet:?xt=urn:btih:c9e15763f722f23e98cb6d93612d78af6e827cba&dn=test',
|
||||
thumbnail: 'https://example.com/thumb.jpg',
|
||||
mode: 'dev',
|
||||
videoRootId: dTagValue, // Simple root ID for testing
|
||||
deleted: false,
|
||||
isPrivate: false,
|
||||
isNsfw: false,
|
||||
isForKids: false,
|
||||
enableComments: true,
|
||||
};
|
||||
// 3. Generate Ephemeral Keys
|
||||
console.log("Generating ephemeral keys...");
|
||||
const sk = NostrTools.generateSecretKey();
|
||||
const skHex = bytesToHex(sk);
|
||||
const pk = NostrTools.getPublicKey(sk);
|
||||
console.log(`Ephemeral Pubkey: ${pk}`);
|
||||
|
||||
// 4. Register Signer
|
||||
await client.registerPrivateKeySigner({ privateKey: skHex, pubkey: pk });
|
||||
console.log("Signer registered.");
|
||||
|
||||
// 5. Test A: Video Post
|
||||
console.log("\n[Test A] Publishing VIDEO_POST...");
|
||||
const rootId = `test-root-${Date.now()}`;
|
||||
const videoEvent = buildVideoPostEvent({
|
||||
pubkey: pk,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
dTagValue: dTagValue,
|
||||
content: contentPayload,
|
||||
pubkey: pk,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
dTagValue: `interop-test-${Date.now()}`,
|
||||
content: {
|
||||
version: 3,
|
||||
title: "Interop Test Video",
|
||||
description: "Automated interop test video from Bitvid agent",
|
||||
videoRootId: rootId,
|
||||
url: "https://example.com/video.mp4",
|
||||
mimeType: "video/mp4",
|
||||
mode: "live",
|
||||
deleted: false
|
||||
},
|
||||
// 's' tag is required by schema (storage pointer)
|
||||
additionalTags: [['s', `url:https://example.com/video.mp4`]]
|
||||
});
|
||||
|
||||
console.log('Publishing video event built from schema...');
|
||||
// Use signAndPublishEvent directly
|
||||
const { signedEvent } = await client.signAndPublishEvent(videoEvent);
|
||||
console.log('Published event ID:', signedEvent.id);
|
||||
const publishResult = await client.signAndPublishEvent(videoEvent);
|
||||
const publishedEvent = publishResult.signedEvent;
|
||||
|
||||
if (!publishedEvent || !publishedEvent.id) {
|
||||
throw new Error("Publishing failed, no event returned");
|
||||
}
|
||||
|
||||
console.log(`Published Video Event ID: ${publishedEvent.id}`);
|
||||
|
||||
// Verify
|
||||
console.log('Fetching event back...');
|
||||
const fetchedEvent = await client.getEventById(signedEvent.id);
|
||||
if (fetchedEvent && fetchedEvent.id === signedEvent.id) {
|
||||
console.log('✅ Video event fetched and verified.');
|
||||
if (fetchedEvent.title === contentPayload.title) {
|
||||
console.log('✅ Content matches.');
|
||||
} else {
|
||||
console.error('❌ Content mismatch:', fetchedEvent.title, 'vs', contentPayload.title);
|
||||
}
|
||||
} else {
|
||||
console.error('❌ Failed to fetch video event.');
|
||||
}
|
||||
console.log("Verifying Video Post...");
|
||||
const rawRelayEvent = await waitForEvent(client.pool, TEST_RELAYS, publishedEvent.id);
|
||||
|
||||
// --- Test B: View Event ---
|
||||
console.log('\n--- Test B: View Event ---');
|
||||
// Explicitly use schema builder
|
||||
if (!rawRelayEvent) throw new Error("Failed to fetch published video event from relays");
|
||||
if (rawRelayEvent.id !== publishedEvent.id) throw new Error("Fetched event ID mismatch");
|
||||
console.log("Video Post Verified (Roundtrip).");
|
||||
|
||||
// 6. Test B: View Event
|
||||
console.log("\n[Test B] Publishing VIEW_EVENT...");
|
||||
const viewEvent = buildViewEvent({
|
||||
pubkey: pk,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
pointerTag: ['e', signedEvent.id],
|
||||
content: 'test-view-interop'
|
||||
pubkey: pk,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
pointerValue: publishedEvent.id,
|
||||
pointerTag: ['e', publishedEvent.id],
|
||||
content: "Interop test view"
|
||||
});
|
||||
|
||||
console.log('Publishing view event built from schema...');
|
||||
try {
|
||||
const { signedEvent: signedView } = await client.signAndPublishEvent(viewEvent);
|
||||
console.log('✅ View event published.', signedView.id);
|
||||
} catch (err) {
|
||||
console.error('❌ View event publish failed:', err);
|
||||
const viewPublishResult = await client.signAndPublishEvent(viewEvent);
|
||||
console.log(`Published View Event ID: ${viewPublishResult.signedEvent.id}`);
|
||||
|
||||
// Ensure it is visible to subscriber clients (simulate).
|
||||
const rawViewEvent = await waitForEvent(client.pool, TEST_RELAYS, viewPublishResult.signedEvent.id);
|
||||
if (!rawViewEvent) throw new Error("Failed to fetch published view event");
|
||||
console.log("View Event Verified.");
|
||||
|
||||
// 7. Test C: Direct Message
|
||||
console.log("\n[Test C] Testing Direct Message...");
|
||||
const msg = `Test DM ${Date.now()}`;
|
||||
const npub = NostrTools.nip19.npubEncode(pk);
|
||||
|
||||
console.log(`Sending DM to self (${npub})...`);
|
||||
const dmResult = await client.sendDirectMessage(npub, msg);
|
||||
|
||||
if (!dmResult.ok) throw new Error(`DM Send failed: ${dmResult.error}`);
|
||||
console.log("DM Sent.");
|
||||
|
||||
// Verify decryption using the appropriate decryptor helper
|
||||
console.log("Verifying DM (waiting 2s)...");
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
const dms = await client.listDirectMessages(pk, { limit: 10 });
|
||||
const found = dms.find(d => d.plaintext === msg);
|
||||
|
||||
if (!found) {
|
||||
console.log("Fetched DMs:", dms.map(d => d.plaintext));
|
||||
throw new Error("Failed to find sent DM");
|
||||
}
|
||||
console.log("DM Verified.");
|
||||
|
||||
// --- Test C: Direct Message ---
|
||||
console.log('\n--- Test C: Direct Message ---');
|
||||
const recipientSk = NostrTools.generateSecretKey();
|
||||
const recipientPk = NostrTools.getPublicKey(recipientSk);
|
||||
const recipientNpub = NostrTools.nip19.npubEncode(recipientPk);
|
||||
console.log('Generated recipient:', recipientPk);
|
||||
|
||||
const dmMessage = 'Hello from Interop Test ' + Date.now();
|
||||
console.log('Sending DM to recipient...');
|
||||
|
||||
// We use client.sendDirectMessage as it encapsulates encryption logic (NIP-04/17)
|
||||
// which is part of the protocol verification we want to test.
|
||||
const dmResult = await client.sendDirectMessage(recipientNpub, dmMessage);
|
||||
|
||||
if (dmResult.ok) {
|
||||
console.log('✅ DM sent successfully.');
|
||||
} else {
|
||||
console.error('❌ DM send failed:', dmResult);
|
||||
}
|
||||
|
||||
// Verification - list messages
|
||||
console.log('Listing DMs...');
|
||||
// Allow some time for propagation
|
||||
await new Promise(r => setTimeout(r, 2000));
|
||||
|
||||
const messages = await client.listDirectMessages();
|
||||
const found = messages.find(m => m.plaintext === dmMessage);
|
||||
|
||||
if (found) {
|
||||
console.log('✅ DM found and decrypted.');
|
||||
} else {
|
||||
console.error('❌ DM not found in list or decryption failed.');
|
||||
console.log('Messages found:', messages.length);
|
||||
if (messages.length > 0) {
|
||||
console.log('First message plain:', messages[0].plaintext);
|
||||
}
|
||||
}
|
||||
console.log("\nAll Interop Tests Passed!");
|
||||
process.exit(0);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Test failed with error:', error);
|
||||
console.error("\nTest Failed:", error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
// Cleanup
|
||||
console.log('\nCleaning up...');
|
||||
if (client.pool) {
|
||||
try {
|
||||
if (typeof client.pool.close === 'function') {
|
||||
client.pool.close(client.relays);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Error closing pool:', e);
|
||||
}
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
runTests();
|
||||
run();
|
||||
Reference in new issue
Block a user