mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-08 16:28:49 +00:00
Compare commits
44 Commits
v1.0.0-rc1
...
v1.3.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ff97b5488 | ||
|
|
df169ea42b | ||
|
|
341f2bcb8d | ||
|
|
b2d1dd2110 | ||
|
|
75d7be5a54 | ||
|
|
b5c8255b2f | ||
|
|
4485c8ed5e | ||
|
|
3710866430 | ||
|
|
da59e3ce90 | ||
|
|
cc8e34163d | ||
|
|
9082953ede | ||
|
|
61f397463d | ||
|
|
312b6fd035 | ||
|
|
7f1bd4f4a8 | ||
|
|
26089ef958 | ||
|
|
2e305b7cd4 | ||
|
|
51c1a54ddf | ||
|
|
cb05ee188f | ||
|
|
fa9e169c46 | ||
|
|
bb1e3f2fa6 | ||
|
|
160987472f | ||
|
|
8b18341ebb | ||
|
|
901445dea1 | ||
|
|
91b67cd0d5 | ||
|
|
1e696e0f3b | ||
|
|
4b36848b2d | ||
|
|
3cb351a5f4 | ||
|
|
5db1934fa4 | ||
|
|
50c3f24b25 | ||
|
|
39ea47660d | ||
|
|
8071e2f4fa | ||
|
|
cc2250da1f | ||
|
|
c37d10bb9d | ||
|
|
97e28fdf9a | ||
|
|
87c0f0d061 | ||
|
|
83c397b839 | ||
|
|
cd7d1cec48 | ||
|
|
613a843838 | ||
|
|
74a0d5454a | ||
|
|
c0d1e41424 | ||
|
|
f7e510e1c8 | ||
|
|
c08bdac7a7 | ||
|
|
c5b64404f6 | ||
|
|
c7b26fdba2 |
7
.github/workflows/npm-publish.yml
vendored
7
.github/workflows/npm-publish.yml
vendored
@@ -12,9 +12,10 @@ jobs:
|
|||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
node-version: 18
|
node-version: 18
|
||||||
- run: yarn --ignore-engines
|
- uses: extractions/setup-just@v1
|
||||||
- run: node build.js
|
- run: just install-dependencies
|
||||||
- run: yarn test
|
- run: just build
|
||||||
|
- run: just test
|
||||||
- uses: JS-DevTools/npm-publish@v1
|
- uses: JS-DevTools/npm-publish@v1
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.NPM_TOKEN }}
|
token: ${{ secrets.NPM_TOKEN }}
|
||||||
|
|||||||
12
.github/workflows/test.yml
vendored
12
.github/workflows/test.yml
vendored
@@ -1,8 +1,7 @@
|
|||||||
name: test every commit
|
name: test every commit
|
||||||
on:
|
on:
|
||||||
push:
|
- push
|
||||||
branches:
|
- pull_request
|
||||||
- master
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
@@ -12,6 +11,7 @@ jobs:
|
|||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
node-version: 18
|
node-version: 18
|
||||||
- run: yarn --ignore-engines
|
- uses: extractions/setup-just@v1
|
||||||
- run: node build.js
|
- run: just install-dependencies
|
||||||
- run: yarn test
|
- run: just build
|
||||||
|
- run: just test
|
||||||
|
|||||||
104
README.md
104
README.md
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Tools for developing [Nostr](https://github.com/fiatjaf/nostr) clients.
|
Tools for developing [Nostr](https://github.com/fiatjaf/nostr) clients.
|
||||||
|
|
||||||
Very lean on dependencies.
|
Only depends on _@scure_ and _@noble_ packages.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
@@ -30,15 +30,15 @@ let event = {
|
|||||||
kind: 1,
|
kind: 1,
|
||||||
created_at: Math.floor(Date.now() / 1000),
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
tags: [],
|
tags: [],
|
||||||
content: 'hello'
|
content: 'hello',
|
||||||
|
pubkey: getPublicKey(privateKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
event.id = getEventHash(event)
|
event.id = getEventHash(event)
|
||||||
event.pubkey = getPublicKey(privateKey)
|
event.sig = signEvent(event, privateKey)
|
||||||
event.sig = await signEvent(event, privateKey)
|
|
||||||
|
|
||||||
let ok = validateEvent(event)
|
let ok = validateEvent(event)
|
||||||
let veryOk = await verifySignature(event)
|
let veryOk = verifySignature(event)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Interacting with a relay
|
### Interacting with a relay
|
||||||
@@ -98,17 +98,22 @@ let event = {
|
|||||||
content: 'hello world'
|
content: 'hello world'
|
||||||
}
|
}
|
||||||
event.id = getEventHash(event)
|
event.id = getEventHash(event)
|
||||||
event.sig = await signEvent(event, sk)
|
event.sig = signEvent(event, sk)
|
||||||
|
|
||||||
let pub = relay.publish(event)
|
let pub = relay.publish(event)
|
||||||
pub.on('ok', () => {
|
pub.on('ok', () => {
|
||||||
console.log(`{relay.url} has accepted our event`)
|
console.log(`${relay.url} has accepted our event`)
|
||||||
})
|
})
|
||||||
pub.on('seen', () => {
|
pub.on('seen', () => {
|
||||||
console.log(`we saw the event on {relay.url}`)
|
console.log(`we saw the event on ${relay.url}`)
|
||||||
})
|
})
|
||||||
pub.on('failed', reason => {
|
pub.on('failed', reason => {
|
||||||
console.log(`failed to publish to {relay.url}: ${reason}`)
|
console.log(`failed to publish to ${relay.url}: ${reason}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
let events = await relay.list([{kinds: [0, 1]}])
|
||||||
|
let event = await relay.get({
|
||||||
|
ids: ['44e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245']
|
||||||
})
|
})
|
||||||
|
|
||||||
await relay.close()
|
await relay.close()
|
||||||
@@ -120,6 +125,46 @@ To use this on Node.js you first must install `websocket-polyfill` and import it
|
|||||||
import 'websocket-polyfill'
|
import 'websocket-polyfill'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Interacting with multiple relays
|
||||||
|
|
||||||
|
```js
|
||||||
|
import {pool} from 'nostr-tools'
|
||||||
|
|
||||||
|
const pool = new SimplePool()
|
||||||
|
|
||||||
|
let relays = ['wss://relay.example.com', 'wss://relay.example2.com']
|
||||||
|
|
||||||
|
relays.forEach(async url => {
|
||||||
|
let relay = pool.ensureRelay(url)
|
||||||
|
await relay.connect()
|
||||||
|
})
|
||||||
|
|
||||||
|
let relay = pool.ensureRelay('wss://relay.example3.com')
|
||||||
|
|
||||||
|
let subs = pool.sub([...relays, relay], {
|
||||||
|
authors: ['32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245']
|
||||||
|
})
|
||||||
|
|
||||||
|
subs.forEach(sub =>
|
||||||
|
sub.on('event', event => {
|
||||||
|
// this will only be called once the first time the event is received
|
||||||
|
// ...
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
let pubs = pool.publish(relays, newEvent)
|
||||||
|
pubs.forEach(pub =>
|
||||||
|
pub.on('ok', () => {
|
||||||
|
// ...
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
let events = await pool.list(relays, [{kinds: [0, 1]}])
|
||||||
|
let event = await pool.get(relays, {
|
||||||
|
ids: ['44e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245']
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
### Querying profile data from a NIP-05 address
|
### Querying profile data from a NIP-05 address
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@@ -182,7 +227,7 @@ let pk2 = getPublicKey(sk2)
|
|||||||
|
|
||||||
// on the sender side
|
// on the sender side
|
||||||
let message = 'hello'
|
let message = 'hello'
|
||||||
let ciphertext = await nip04.encrypt(sk1, pk2, 'hello')
|
let ciphertext = await nip04.encrypt(sk1, pk2, message)
|
||||||
|
|
||||||
let event = {
|
let event = {
|
||||||
kind: 4,
|
kind: 4,
|
||||||
@@ -195,13 +240,48 @@ let event = {
|
|||||||
sendEvent(event)
|
sendEvent(event)
|
||||||
|
|
||||||
// on the receiver side
|
// on the receiver side
|
||||||
sub.on('event', (event) => {
|
sub.on('event', event => {
|
||||||
let sender = event.tags.find(([k, v]) => k === 'p' && && v && v !== '')[1]
|
let sender = event.tags.find(([k, v]) => k === 'p' && v && v !== '')[1]
|
||||||
pk1 === sender
|
pk1 === sender
|
||||||
let plaintext = await nip04.decrypt(sk2, pk1, event.content)
|
let plaintext = await nip04.decrypt(sk2, pk1, event.content)
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Performing and checking for delegation
|
||||||
|
|
||||||
|
```js
|
||||||
|
import {nip26, getPublicKey, generatePrivateKey} from 'nostr-tools'
|
||||||
|
|
||||||
|
// delegator
|
||||||
|
let sk1 = generatePrivateKey()
|
||||||
|
let pk1 = getPublicKey(sk1)
|
||||||
|
|
||||||
|
// delegatee
|
||||||
|
let sk2 = generatePrivateKey()
|
||||||
|
let pk2 = getPublicKey(sk2)
|
||||||
|
|
||||||
|
// generate delegation
|
||||||
|
let delegation = nip26.createDelegation(sk1, {
|
||||||
|
pubkey: pk2,
|
||||||
|
kind: 1,
|
||||||
|
since: Math.round(Date.now() / 1000),
|
||||||
|
until: Math.round(Date.now() / 1000) + 60 * 60 * 24 * 30 /* 30 days */
|
||||||
|
})
|
||||||
|
|
||||||
|
// the delegatee uses the delegation when building an event
|
||||||
|
let event = {
|
||||||
|
pubkey: pk2,
|
||||||
|
kind: 1,
|
||||||
|
created_at: Math.round(Date.now() / 1000),
|
||||||
|
content: 'hello from a delegated key',
|
||||||
|
tags: [['delegation', delegation.from, delegation.cond, delegation.sig]]
|
||||||
|
}
|
||||||
|
|
||||||
|
// finally any receiver of this event can check for the presence of a valid delegation tag
|
||||||
|
let delegator = nip26.getDelegator(event)
|
||||||
|
assert(delegator === pk1) // will be null if there is no delegation tag or if it is invalid
|
||||||
|
```
|
||||||
|
|
||||||
Please consult the tests or [the source code](https://github.com/fiatjaf/nostr-tools) for more information that isn't available here.
|
Please consult the tests or [the source code](https://github.com/fiatjaf/nostr-tools) for more information that isn't available here.
|
||||||
|
|
||||||
### Using from the browser (if you don't want to use a bundler)
|
### Using from the browser (if you don't want to use a bundler)
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ const {
|
|||||||
validateEvent,
|
validateEvent,
|
||||||
verifySignature,
|
verifySignature,
|
||||||
signEvent,
|
signEvent,
|
||||||
getEventHash,
|
|
||||||
getPublicKey
|
getPublicKey
|
||||||
} = require('./lib/nostr.cjs')
|
} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
@@ -35,15 +34,15 @@ test('validate event', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test('check signature', async () => {
|
test('check signature', async () => {
|
||||||
expect(await verifySignature(event)).toBeTruthy()
|
expect(verifySignature(event)).toBeTruthy()
|
||||||
})
|
})
|
||||||
|
|
||||||
test('sign event', async () => {
|
test('sign event', async () => {
|
||||||
let sig = await signEvent(unsigned, privateKey)
|
|
||||||
let hash = getEventHash(unsigned)
|
|
||||||
let pubkey = getPublicKey(privateKey)
|
let pubkey = getPublicKey(privateKey)
|
||||||
|
let authored = {...unsigned, pubkey}
|
||||||
|
|
||||||
let signed = {...unsigned, id: hash, sig, pubkey}
|
let sig = signEvent(authored, privateKey)
|
||||||
|
let signed = {...authored, sig}
|
||||||
|
|
||||||
expect(await verifySignature(signed)).toBeTruthy()
|
expect(verifySignature(signed)).toBeTruthy()
|
||||||
})
|
})
|
||||||
|
|||||||
44
event.ts
44
event.ts
@@ -3,10 +3,26 @@ import {sha256} from '@noble/hashes/sha256'
|
|||||||
|
|
||||||
import {utf8Encoder} from './utils'
|
import {utf8Encoder} from './utils'
|
||||||
|
|
||||||
|
/* eslint-disable no-unused-vars */
|
||||||
|
export enum Kind {
|
||||||
|
Metadata = 0,
|
||||||
|
Text = 1,
|
||||||
|
RecommendRelay = 2,
|
||||||
|
Contacts = 3,
|
||||||
|
EncryptedDirectMessage = 4,
|
||||||
|
EventDeletion = 5,
|
||||||
|
Reaction = 7,
|
||||||
|
ChannelCreation = 40,
|
||||||
|
ChannelMetadata = 41,
|
||||||
|
ChannelMessage = 42,
|
||||||
|
ChannelHideMessage = 43,
|
||||||
|
ChannelMuteUser = 44
|
||||||
|
}
|
||||||
|
|
||||||
export type Event = {
|
export type Event = {
|
||||||
id?: string
|
id?: string
|
||||||
sig?: string
|
sig?: string
|
||||||
kind: number
|
kind: Kind
|
||||||
tags: string[][]
|
tags: string[][]
|
||||||
pubkey: string
|
pubkey: string
|
||||||
content: string
|
content: string
|
||||||
@@ -24,6 +40,9 @@ export function getBlankEvent(): Event {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function serializeEvent(evt: Event): string {
|
export function serializeEvent(evt: Event): string {
|
||||||
|
if (!validateEvent(evt))
|
||||||
|
throw new Error("can't serialize event with wrong or missing properties")
|
||||||
|
|
||||||
return JSON.stringify([
|
return JSON.stringify([
|
||||||
0,
|
0,
|
||||||
evt.pubkey,
|
evt.pubkey,
|
||||||
@@ -40,9 +59,10 @@ export function getEventHash(event: Event): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function validateEvent(event: Event): boolean {
|
export function validateEvent(event: Event): boolean {
|
||||||
if (event.id !== getEventHash(event)) return false
|
|
||||||
if (typeof event.content !== 'string') return false
|
if (typeof event.content !== 'string') return false
|
||||||
if (typeof event.created_at !== 'number') return false
|
if (typeof event.created_at !== 'number') return false
|
||||||
|
if (typeof event.pubkey !== 'string') return false
|
||||||
|
if (!event.pubkey.match(/^[a-f0-9]{64}$/)) return false
|
||||||
|
|
||||||
if (!Array.isArray(event.tags)) return false
|
if (!Array.isArray(event.tags)) return false
|
||||||
for (let i = 0; i < event.tags.length; i++) {
|
for (let i = 0; i < event.tags.length; i++) {
|
||||||
@@ -56,14 +76,16 @@ export function validateEvent(event: Event): boolean {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
export function verifySignature(
|
export function verifySignature(event: Event & {sig: string}): boolean {
|
||||||
event: Event & {id: string; sig: string}
|
return secp256k1.schnorr.verifySync(
|
||||||
): Promise<boolean> {
|
event.sig,
|
||||||
return secp256k1.schnorr.verify(event.sig, event.id, event.pubkey)
|
getEventHash(event),
|
||||||
}
|
event.pubkey
|
||||||
|
)
|
||||||
export async function signEvent(event: Event, key: string): Promise<string> {
|
}
|
||||||
return secp256k1.utils.bytesToHex(
|
|
||||||
await secp256k1.schnorr.sign(event.id || getEventHash(event), key)
|
export function signEvent(event: Event, key: string): string {
|
||||||
|
return secp256k1.utils.bytesToHex(
|
||||||
|
secp256k1.schnorr.signSync(getEventHash(event), key)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
49
fakejson.test.js
Normal file
49
fakejson.test.js
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
|
||||||
|
const {fj} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
|
test('match id', () => {
|
||||||
|
expect(
|
||||||
|
fj.matchEventId(
|
||||||
|
`["EVENT","nostril-query",{"tags":[],"content":"so did we cut all corners and p2p stuff in order to make a decentralized social network that was fast and worked, but in the end what we got was a lot of very slow clients that can't handle the traffic of one jack dorsey tweet?","sig":"ca62629d189edebb8f0811cfa0ac53015013df5f305dcba3f411ba15cfc4074d8c2d517ee7d9e81c9eb72a7328bfbe31c9122156397565ac55e740404e2b1fe7","id":"fef2a50f7d9d3d5a5f38ee761bc087ec16198d3f0140df6d1e8193abf7c2b146","kind":1,"pubkey":"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d","created_at":1671150419}]`,
|
||||||
|
'fef2a50f7d9d3d5a5f38ee761bc087ec16198d3f0140df6d1e8193abf7c2b146'
|
||||||
|
)
|
||||||
|
).toBeTruthy()
|
||||||
|
|
||||||
|
expect(
|
||||||
|
fj.matchEventId(
|
||||||
|
`["EVENT","nostril-query",{"content":"a bunch of mfs interacted with my post using what I assume were \"likes\": https://nostr.build/i/964.png","created_at":1672506879,"id":"f40bdd0905137ad60482537e260890ab50b0863bf16e67cf9383f203bd26c96f","kind":1,"pubkey":"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d","sig":"8b825d2d4096f0643b18ca39da59ec07a682cd8a3e717f119c845037573d98099f5bea94ec7ddedd5600c8020144a255ed52882a911f7f7ada6d6abb3c0a1eb4","tags":[]}]`,
|
||||||
|
'fef2a50f7d9d3d5a5f38ee761bc087ec16198d3f0140df6d1e8193abf7c2b146'
|
||||||
|
)
|
||||||
|
).toBeFalsy()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('match kind', () => {
|
||||||
|
expect(
|
||||||
|
fj.matchEventKind(
|
||||||
|
`["EVENT","nostril-query",{"tags":[],"content":"so did we cut all corners and p2p stuff in order to make a decentralized social network that was fast and worked, but in the end what we got was a lot of very slow clients that can't handle the traffic of one jack dorsey tweet?","sig":"ca62629d189edebb8f0811cfa0ac53015013df5f305dcba3f411ba15cfc4074d8c2d517ee7d9e81c9eb72a7328bfbe31c9122156397565ac55e740404e2b1fe7","id":"fef2a50f7d9d3d5a5f38ee761bc087ec16198d3f0140df6d1e8193abf7c2b146","kind":1,"pubkey":"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d","created_at":1671150419}]`,
|
||||||
|
1
|
||||||
|
)
|
||||||
|
).toBeTruthy()
|
||||||
|
|
||||||
|
expect(
|
||||||
|
fj.matchEventKind(
|
||||||
|
`["EVENT","nostril-query",{"content":"{\"name\":\"fiatjaf\",\"about\":\"buy my merch at fiatjaf store\",\"picture\":\"https://fiatjaf.com/static/favicon.jpg\",\"nip05\":\"_@fiatjaf.com\"}","created_at":1671217411,"id":"b52f93f6dfecf9d81f59062827cd941412a0e8398dda60baf960b17499b88900","kind":12720,"pubkey":"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d","sig":"fc1ea5d45fa5ed0526faed06e8fc7a558e60d1b213e9714f440828584ee999b93407092f9b04deea7e504fa034fc0428f31f7f0f95417b3280ebe6004b80b470","tags":[]}]`,
|
||||||
|
12720
|
||||||
|
)
|
||||||
|
).toBeTruthy()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('match subscription id', () => {
|
||||||
|
expect(fj.getSubscriptionId('["EVENT","",{}]')).toEqual('')
|
||||||
|
expect(fj.getSubscriptionId('["EVENT","_",{}]')).toEqual('_')
|
||||||
|
expect(fj.getSubscriptionId('["EVENT","subname",{}]')).toEqual('subname')
|
||||||
|
expect(fj.getSubscriptionId('["EVENT", "kasjbdjkav", {}]')).toEqual(
|
||||||
|
'kasjbdjkav'
|
||||||
|
)
|
||||||
|
expect(
|
||||||
|
fj.getSubscriptionId(
|
||||||
|
' [ \n\n "EVENT" , \n\n "y4d5ow45gfwoiudfÇA VSADLKAN KLDASB[12312535]SFMZSNJKLH" , {}]'
|
||||||
|
)
|
||||||
|
).toEqual('y4d5ow45gfwoiudfÇA VSADLKAN KLDASB[12312535]SFMZSNJKLH')
|
||||||
|
})
|
||||||
41
fakejson.ts
Normal file
41
fakejson.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
export function getHex64(json: string, field: string): string {
|
||||||
|
let len = field.length + 3
|
||||||
|
let idx = json.indexOf(`"${field}":`) + len
|
||||||
|
let s = json.slice(idx).indexOf(`"`) + idx + 1
|
||||||
|
return json.slice(s, s + 64)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getInt(json: string, field: string): number {
|
||||||
|
let len = field.length
|
||||||
|
let idx = json.indexOf(`"${field}":`) + len + 3
|
||||||
|
let sliced = json.slice(idx)
|
||||||
|
let end = Math.min(sliced.indexOf(','), sliced.indexOf('}'))
|
||||||
|
return parseInt(sliced.slice(0, end), 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSubscriptionId(json: string): string | null {
|
||||||
|
let idx = json.slice(0, 22).indexOf(`"EVENT"`)
|
||||||
|
if (idx === -1) return null
|
||||||
|
|
||||||
|
let pstart = json.slice(idx + 7 + 1).indexOf(`"`)
|
||||||
|
if (pstart === -1) return null
|
||||||
|
let start = idx + 7 + 1 + pstart
|
||||||
|
|
||||||
|
let pend = json.slice(start + 1, 80).indexOf(`"`)
|
||||||
|
if (pend === -1) return null
|
||||||
|
let end = start + 1 + pend
|
||||||
|
|
||||||
|
return json.slice(start + 1, end)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function matchEventId(json: string, id: string): boolean {
|
||||||
|
return id === getHex64(json, 'id')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function matchEventPubkey(json: string, pubkey: string): boolean {
|
||||||
|
return pubkey === getHex64(json, 'pubkey')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function matchEventKind(json: string, kind: number): boolean {
|
||||||
|
return kind === getInt(json, 'kind')
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ export type Filter = {
|
|||||||
authors?: string[]
|
authors?: string[]
|
||||||
since?: number
|
since?: number
|
||||||
until?: number
|
until?: number
|
||||||
|
limit?: number
|
||||||
[key: `#${string}`]: string[]
|
[key: `#${string}`]: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
14
index.ts
14
index.ts
@@ -2,8 +2,22 @@ export * from './keys'
|
|||||||
export * from './relay'
|
export * from './relay'
|
||||||
export * from './event'
|
export * from './event'
|
||||||
export * from './filter'
|
export * from './filter'
|
||||||
|
export * from './pool'
|
||||||
|
|
||||||
export * as nip04 from './nip04'
|
export * as nip04 from './nip04'
|
||||||
export * as nip05 from './nip05'
|
export * as nip05 from './nip05'
|
||||||
export * as nip06 from './nip06'
|
export * as nip06 from './nip06'
|
||||||
export * as nip19 from './nip19'
|
export * as nip19 from './nip19'
|
||||||
|
export * as nip26 from './nip26'
|
||||||
|
|
||||||
|
export * as fj from './fakejson'
|
||||||
|
export * as utils from './utils'
|
||||||
|
|
||||||
|
// monkey patch secp256k1
|
||||||
|
import * as secp256k1 from '@noble/secp256k1'
|
||||||
|
import {hmac} from '@noble/hashes/hmac'
|
||||||
|
import {sha256} from '@noble/hashes/sha256'
|
||||||
|
secp256k1.utils.hmacSha256Sync = (key, ...msgs) =>
|
||||||
|
hmac(sha256, key, secp256k1.utils.concatBytes(...msgs))
|
||||||
|
secp256k1.utils.sha256Sync = (...msgs) =>
|
||||||
|
sha256(secp256k1.utils.concatBytes(...msgs))
|
||||||
|
|||||||
13
justfile
Normal file
13
justfile
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
export PATH := "./node_modules/.bin:" + env_var('PATH')
|
||||||
|
|
||||||
|
install-dependencies:
|
||||||
|
yarn --ignore-engines
|
||||||
|
|
||||||
|
build:
|
||||||
|
node build.js
|
||||||
|
|
||||||
|
test: build
|
||||||
|
jest
|
||||||
|
|
||||||
|
testOnly file: build
|
||||||
|
jest {{file}}
|
||||||
10
nip04.ts
10
nip04.ts
@@ -1,6 +1,6 @@
|
|||||||
import {randomBytes} from '@noble/hashes/utils'
|
import {randomBytes} from '@noble/hashes/utils'
|
||||||
import * as secp256k1 from '@noble/secp256k1'
|
import * as secp256k1 from '@noble/secp256k1'
|
||||||
import {encode as b64encode, decode as b64decode} from 'base64-arraybuffer'
|
import {base64} from '@scure/base'
|
||||||
|
|
||||||
import {utf8Decoder, utf8Encoder} from './utils'
|
import {utf8Decoder, utf8Encoder} from './utils'
|
||||||
|
|
||||||
@@ -26,8 +26,8 @@ export async function encrypt(
|
|||||||
cryptoKey,
|
cryptoKey,
|
||||||
plaintext
|
plaintext
|
||||||
)
|
)
|
||||||
let ctb64 = b64encode(ciphertext)
|
let ctb64 = base64.encode(new Uint8Array(ciphertext))
|
||||||
let ivb64 = b64encode(iv.buffer)
|
let ivb64 = base64.encode(new Uint8Array(iv.buffer))
|
||||||
|
|
||||||
return `${ctb64}?iv=${ivb64}`
|
return `${ctb64}?iv=${ivb64}`
|
||||||
}
|
}
|
||||||
@@ -48,8 +48,8 @@ export async function decrypt(
|
|||||||
false,
|
false,
|
||||||
['decrypt']
|
['decrypt']
|
||||||
)
|
)
|
||||||
let ciphertext = b64decode(ctb64)
|
let ciphertext = base64.decode(ctb64)
|
||||||
let iv = b64decode(ivb64)
|
let iv = base64.decode(ivb64)
|
||||||
|
|
||||||
let plaintext = await crypto.subtle.decrypt(
|
let plaintext = await crypto.subtle.decrypt(
|
||||||
{name: 'AES-CBC', iv},
|
{name: 'AES-CBC', iv},
|
||||||
|
|||||||
8
nip05.ts
8
nip05.ts
@@ -1,6 +1,10 @@
|
|||||||
import {ProfilePointer} from './nip19'
|
import {ProfilePointer} from './nip19'
|
||||||
|
|
||||||
var _fetch = fetch
|
var _fetch: any
|
||||||
|
|
||||||
|
try {
|
||||||
|
_fetch = fetch
|
||||||
|
} catch {}
|
||||||
|
|
||||||
export function useFetchImplementation(fetchImplementation: any) {
|
export function useFetchImplementation(fetchImplementation: any) {
|
||||||
_fetch = fetchImplementation
|
_fetch = fetchImplementation
|
||||||
@@ -32,6 +36,8 @@ export async function queryProfile(
|
|||||||
name = '_'
|
name = '_'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!name.match(/^[A-Za-z0-9-_]+$/)) return null
|
||||||
|
|
||||||
let res = await (
|
let res = await (
|
||||||
await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`)
|
await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`)
|
||||||
).json()
|
).json()
|
||||||
|
|||||||
15
nip06.test.js
Normal file
15
nip06.test.js
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
const {nip06} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
|
test('generate private key from a mnemonic', async () => {
|
||||||
|
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
||||||
|
const privateKey = nip06.privateKeyFromSeedWords(mnemonic)
|
||||||
|
expect(privateKey).toEqual('c26cf31d8ba425b555ca27d00ca71b5008004f2f662470f8c8131822ec129fe2')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('generate private key from a mnemonic and passphrase', async () => {
|
||||||
|
const mnemonic = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
|
||||||
|
const passphrase = '123'
|
||||||
|
const privateKey = nip06.privateKeyFromSeedWords(mnemonic, passphrase)
|
||||||
|
expect(privateKey).toEqual('55a22b8203273d0aaf24c22c8fbe99608e70c524b17265641074281c8b978ae4')
|
||||||
|
})
|
||||||
8
nip06.ts
8
nip06.ts
@@ -7,17 +7,13 @@ import {
|
|||||||
} from '@scure/bip39'
|
} from '@scure/bip39'
|
||||||
import {HDKey} from '@scure/bip32'
|
import {HDKey} from '@scure/bip32'
|
||||||
|
|
||||||
export function privateKeyFromSeed(seed: string): string {
|
export function privateKeyFromSeedWords(mnemonic: string, passphrase?: string): string {
|
||||||
let root = HDKey.fromMasterSeed(secp256k1.utils.hexToBytes(seed))
|
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
|
||||||
let privateKey = root.derive(`m/44'/1237'/0'/0/0`).privateKey
|
let privateKey = root.derive(`m/44'/1237'/0'/0/0`).privateKey
|
||||||
if (!privateKey) throw new Error('could not derive private key')
|
if (!privateKey) throw new Error('could not derive private key')
|
||||||
return secp256k1.utils.bytesToHex(privateKey)
|
return secp256k1.utils.bytesToHex(privateKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function seedFromWords(mnemonic: string): string {
|
|
||||||
return secp256k1.utils.bytesToHex(mnemonicToSeedSync(mnemonic))
|
|
||||||
}
|
|
||||||
|
|
||||||
export function generateSeedWords(): string {
|
export function generateSeedWords(): string {
|
||||||
return generateMnemonic(wordlist)
|
return generateMnemonic(wordlist)
|
||||||
}
|
}
|
||||||
|
|||||||
12
nip19.ts
12
nip19.ts
@@ -1,8 +1,10 @@
|
|||||||
import * as secp256k1 from '@noble/secp256k1'
|
import * as secp256k1 from '@noble/secp256k1'
|
||||||
import {bech32} from 'bech32'
|
import {bech32} from '@scure/base'
|
||||||
|
|
||||||
import {utf8Decoder, utf8Encoder} from './utils'
|
import {utf8Decoder, utf8Encoder} from './utils'
|
||||||
|
|
||||||
|
const Bech32MaxSize = 5000
|
||||||
|
|
||||||
export type ProfilePointer = {
|
export type ProfilePointer = {
|
||||||
pubkey: string // hex
|
pubkey: string // hex
|
||||||
relays?: string[]
|
relays?: string[]
|
||||||
@@ -17,7 +19,7 @@ export function decode(nip19: string): {
|
|||||||
type: string
|
type: string
|
||||||
data: ProfilePointer | EventPointer | string
|
data: ProfilePointer | EventPointer | string
|
||||||
} {
|
} {
|
||||||
let {prefix, words} = bech32.decode(nip19, 1000)
|
let {prefix, words} = bech32.decode(nip19, Bech32MaxSize)
|
||||||
let data = new Uint8Array(bech32.fromWords(words))
|
let data = new Uint8Array(bech32.fromWords(words))
|
||||||
|
|
||||||
if (prefix === 'nprofile') {
|
if (prefix === 'nprofile') {
|
||||||
@@ -87,7 +89,7 @@ export function noteEncode(hex: string): string {
|
|||||||
function encodeBytes(prefix: string, hex: string): string {
|
function encodeBytes(prefix: string, hex: string): string {
|
||||||
let data = secp256k1.utils.hexToBytes(hex)
|
let data = secp256k1.utils.hexToBytes(hex)
|
||||||
let words = bech32.toWords(data)
|
let words = bech32.toWords(data)
|
||||||
return bech32.encode(prefix, words, 1000)
|
return bech32.encode(prefix, words, Bech32MaxSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function nprofileEncode(profile: ProfilePointer): string {
|
export function nprofileEncode(profile: ProfilePointer): string {
|
||||||
@@ -96,7 +98,7 @@ export function nprofileEncode(profile: ProfilePointer): string {
|
|||||||
1: (profile.relays || []).map(url => utf8Encoder.encode(url))
|
1: (profile.relays || []).map(url => utf8Encoder.encode(url))
|
||||||
})
|
})
|
||||||
let words = bech32.toWords(data)
|
let words = bech32.toWords(data)
|
||||||
return bech32.encode('nprofile', words, 1000)
|
return bech32.encode('nprofile', words, Bech32MaxSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function neventEncode(event: EventPointer): string {
|
export function neventEncode(event: EventPointer): string {
|
||||||
@@ -105,7 +107,7 @@ export function neventEncode(event: EventPointer): string {
|
|||||||
1: (event.relays || []).map(url => utf8Encoder.encode(url))
|
1: (event.relays || []).map(url => utf8Encoder.encode(url))
|
||||||
})
|
})
|
||||||
let words = bech32.toWords(data)
|
let words = bech32.toWords(data)
|
||||||
return bech32.encode('nevent', words, 1000)
|
return bech32.encode('nevent', words, Bech32MaxSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
function encodeTLV(tlv: TLV): Uint8Array {
|
function encodeTLV(tlv: TLV): Uint8Array {
|
||||||
|
|||||||
105
nip26.test.js
Normal file
105
nip26.test.js
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
|
||||||
|
const {nip26, getPublicKey, generatePrivateKey} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
|
test('parse good delegation from NIP', async () => {
|
||||||
|
expect(
|
||||||
|
nip26.getDelegator({
|
||||||
|
id: 'a080fd288b60ac2225ff2e2d815291bd730911e583e177302cc949a15dc2b2dc',
|
||||||
|
pubkey:
|
||||||
|
'62903b1ff41559daf9ee98ef1ae67cc52f301bb5ce26d14baba3052f649c3f49',
|
||||||
|
created_at: 1660896109,
|
||||||
|
kind: 1,
|
||||||
|
tags: [
|
||||||
|
[
|
||||||
|
'delegation',
|
||||||
|
'86f0689bd48dcd19c67a19d994f938ee34f251d8c39976290955ff585f2db42e',
|
||||||
|
'kind=1&created_at>1640995200',
|
||||||
|
'c33c88ba78ec3c760e49db591ac5f7b129e3887c8af7729795e85a0588007e5ac89b46549232d8f918eefd73e726cb450135314bfda419c030d0b6affe401ec1'
|
||||||
|
]
|
||||||
|
],
|
||||||
|
content: 'Hello world',
|
||||||
|
sig: 'cd4a3cd20dc61dcbc98324de561a07fd23b3d9702115920c0814b5fb822cc5b7c5bcdaf3fa326d24ed50c5b9c8214d66c75bae34e3a84c25e4d122afccb66eb6'
|
||||||
|
})
|
||||||
|
).toEqual('86f0689bd48dcd19c67a19d994f938ee34f251d8c39976290955ff585f2db42e')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('parse bad delegations', async () => {
|
||||||
|
expect(
|
||||||
|
nip26.getDelegator({
|
||||||
|
id: 'a080fd288b60ac2225ff2e2d815291bd730911e583e177302cc949a15dc2b2dc',
|
||||||
|
pubkey:
|
||||||
|
'62903b1ff41559daf9ee98ef1ae67cc52f301bb5ce26d14baba3052f649c3f49',
|
||||||
|
created_at: 1660896109,
|
||||||
|
kind: 1,
|
||||||
|
tags: [
|
||||||
|
[
|
||||||
|
'delegation',
|
||||||
|
'86f0689bd48dcd19c67a19d994f938ee34f251d8c39976290955ff585f2db42f',
|
||||||
|
'kind=1&created_at>1640995200',
|
||||||
|
'c33c88ba78ec3c760e49db591ac5f7b129e3887c8af7729795e85a0588007e5ac89b46549232d8f918eefd73e726cb450135314bfda419c030d0b6affe401ec1'
|
||||||
|
]
|
||||||
|
],
|
||||||
|
content: 'Hello world',
|
||||||
|
sig: 'cd4a3cd20dc61dcbc98324de561a07fd23b3d9702115920c0814b5fb822cc5b7c5bcdaf3fa326d24ed50c5b9c8214d66c75bae34e3a84c25e4d122afccb66eb6'
|
||||||
|
})
|
||||||
|
).toEqual(null)
|
||||||
|
|
||||||
|
expect(
|
||||||
|
nip26.getDelegator({
|
||||||
|
id: 'a080fd288b60ac2225ff2e2d815291bd730911e583e177302cc949a15dc2b2dc',
|
||||||
|
pubkey:
|
||||||
|
'62903b1ff41559daf9ee98ef1ae67cc52f301bb5ce26d14baba3052f649c3f49',
|
||||||
|
created_at: 1660896109,
|
||||||
|
kind: 1,
|
||||||
|
tags: [
|
||||||
|
[
|
||||||
|
'delegation',
|
||||||
|
'86f0689bd48dcd19c67a19d994f938ee34f251d8c39976290955ff585f2db42e',
|
||||||
|
'kind=1&created_at>1740995200',
|
||||||
|
'c33c88ba78ec3c760e49db591ac5f7b129e3887c8af7729795e85a0588007e5ac89b46549232d8f918eefd73e726cb450135314bfda419c030d0b6affe401ec1'
|
||||||
|
]
|
||||||
|
],
|
||||||
|
content: 'Hello world',
|
||||||
|
sig: 'cd4a3cd20dc61dcbc98324de561a07fd23b3d9702115920c0814b5fb822cc5b7c5bcdaf3fa326d24ed50c5b9c8214d66c75bae34e3a84c25e4d122afccb66eb6'
|
||||||
|
})
|
||||||
|
).toEqual(null)
|
||||||
|
|
||||||
|
expect(
|
||||||
|
nip26.getDelegator({
|
||||||
|
id: 'a080fd288b60ac2225ff2e2d815291bd730911e583e177302cc949a15dc2b2dc',
|
||||||
|
pubkey:
|
||||||
|
'62903b1ff41559daf9ee98ef1ae67c152f301bb5ce26d14baba3052f649c3f49',
|
||||||
|
created_at: 1660896109,
|
||||||
|
kind: 1,
|
||||||
|
tags: [
|
||||||
|
[
|
||||||
|
'delegation',
|
||||||
|
'86f0689bd48dcd19c67a19d994f938ee34f251d8c39976290955ff585f2db42e',
|
||||||
|
'kind=1&created_at>1640995200',
|
||||||
|
'c33c88ba78ec3c760e49db591ac5f7b129e3887c8af7729795e85a0588007e5ac89b46549232d8f918eefd73e726cb450135314bfda419c030d0b6affe401ec1'
|
||||||
|
]
|
||||||
|
],
|
||||||
|
content: 'Hello world',
|
||||||
|
sig: 'cd4a3cd20dc61dcbc98324de561a07fd23b3d9702115920c0814b5fb822cc5b7c5bcdaf3fa326d24ed50c5b9c8214d66c75bae34e3a84c25e4d122afccb66eb6'
|
||||||
|
})
|
||||||
|
).toEqual(null)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('create and verify delegation', async () => {
|
||||||
|
let sk1 = generatePrivateKey()
|
||||||
|
let pk1 = getPublicKey(sk1)
|
||||||
|
let sk2 = generatePrivateKey()
|
||||||
|
let pk2 = getPublicKey(sk2)
|
||||||
|
let delegation = nip26.createDelegation(sk1, {pubkey: pk2, kind: 1})
|
||||||
|
expect(delegation).toHaveProperty('from', pk1)
|
||||||
|
expect(delegation).toHaveProperty('to', pk2)
|
||||||
|
expect(delegation).toHaveProperty('cond', 'kind=1')
|
||||||
|
|
||||||
|
let event = {
|
||||||
|
kind: 1,
|
||||||
|
tags: [['delegation', delegation.from, delegation.cond, delegation.sig]],
|
||||||
|
pubkey: pk2
|
||||||
|
}
|
||||||
|
expect(nip26.getDelegator(event)).toEqual(pk1)
|
||||||
|
})
|
||||||
90
nip26.ts
Normal file
90
nip26.ts
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
import * as secp256k1 from '@noble/secp256k1'
|
||||||
|
import {sha256} from '@noble/hashes/sha256'
|
||||||
|
|
||||||
|
import {Event} from './event'
|
||||||
|
import {utf8Encoder} from './utils'
|
||||||
|
import {getPublicKey} from './keys'
|
||||||
|
|
||||||
|
export type Parameters = {
|
||||||
|
pubkey: string // the key to whom the delegation will be given
|
||||||
|
kind: number | undefined
|
||||||
|
until: number | undefined // delegation will only be valid until this date
|
||||||
|
since: number | undefined // delegation will be valid from this date on
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Delegation = {
|
||||||
|
from: string // the pubkey who signed the delegation
|
||||||
|
to: string // the pubkey that is allowed to use the delegation
|
||||||
|
cond: string // the string of conditions as they should be included in the event tag
|
||||||
|
sig: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createDelegation(
|
||||||
|
privateKey: string,
|
||||||
|
parameters: Parameters
|
||||||
|
): Delegation {
|
||||||
|
let conditions = []
|
||||||
|
if ((parameters.kind || -1) >= 0) conditions.push(`kind=${parameters.kind}`)
|
||||||
|
if (parameters.until) conditions.push(`created_at<${parameters.until}`)
|
||||||
|
if (parameters.since) conditions.push(`created_at>${parameters.since}`)
|
||||||
|
let cond = conditions.join('&')
|
||||||
|
|
||||||
|
if (cond === '')
|
||||||
|
throw new Error('refusing to create a delegation without any conditions')
|
||||||
|
|
||||||
|
let sighash = sha256(
|
||||||
|
utf8Encoder.encode(`nostr:delegation:${parameters.pubkey}:${cond}`)
|
||||||
|
)
|
||||||
|
|
||||||
|
let sig = secp256k1.utils.bytesToHex(
|
||||||
|
secp256k1.schnorr.signSync(sighash, privateKey)
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
from: getPublicKey(privateKey),
|
||||||
|
to: parameters.pubkey,
|
||||||
|
cond,
|
||||||
|
sig
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDelegator(event: Event): string | null {
|
||||||
|
// find delegation tag
|
||||||
|
let tag = event.tags.find(tag => tag[0] === 'delegation' && tag.length >= 4)
|
||||||
|
if (!tag) return null
|
||||||
|
|
||||||
|
let pubkey = tag[1]
|
||||||
|
let cond = tag[2]
|
||||||
|
let sig = tag[3]
|
||||||
|
|
||||||
|
// check conditions
|
||||||
|
let conditions = cond.split('&')
|
||||||
|
for (let i = 0; i < conditions.length; i++) {
|
||||||
|
let [key, operator, value] = conditions[i].split(/\b/)
|
||||||
|
|
||||||
|
// the supported conditions are just 'kind' and 'created_at' for now
|
||||||
|
if (key === 'kind' && operator === '=' && event.kind === parseInt(value))
|
||||||
|
continue
|
||||||
|
else if (
|
||||||
|
key === 'created_at' &&
|
||||||
|
operator === '<' &&
|
||||||
|
event.created_at < parseInt(value)
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
else if (
|
||||||
|
key === 'created_at' &&
|
||||||
|
operator === '>' &&
|
||||||
|
event.created_at > parseInt(value)
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
else return null // invalid condition
|
||||||
|
}
|
||||||
|
|
||||||
|
// check signature
|
||||||
|
let sighash = sha256(
|
||||||
|
utf8Encoder.encode(`nostr:delegation:${event.pubkey}:${cond}`)
|
||||||
|
)
|
||||||
|
if (!secp256k1.schnorr.verifySync(sig, sighash, pubkey)) return null
|
||||||
|
|
||||||
|
return pubkey
|
||||||
|
}
|
||||||
12
package.json
12
package.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "nostr-tools",
|
"name": "nostr-tools",
|
||||||
"version": "1.0.0-rc1",
|
"version": "1.3.0",
|
||||||
"description": "Tools for making a Nostr client.",
|
"description": "Tools for making a Nostr client.",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
@@ -11,10 +11,9 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/hashes": "^0.5.7",
|
"@noble/hashes": "^0.5.7",
|
||||||
"@noble/secp256k1": "^1.7.0",
|
"@noble/secp256k1": "^1.7.0",
|
||||||
|
"@scure/base": "^1.1.1",
|
||||||
"@scure/bip32": "^1.1.1",
|
"@scure/bip32": "^1.1.1",
|
||||||
"@scure/bip39": "^1.1.0",
|
"@scure/bip39": "^1.1.0"
|
||||||
"base64-arraybuffer": "^1.0.2",
|
|
||||||
"bech32": "^2.0.0"
|
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"decentralization",
|
"decentralization",
|
||||||
@@ -39,10 +38,5 @@
|
|||||||
"tsd": "^0.22.0",
|
"tsd": "^0.22.0",
|
||||||
"typescript": "^4.9.4",
|
"typescript": "^4.9.4",
|
||||||
"websocket-polyfill": "^0.0.3"
|
"websocket-polyfill": "^0.0.3"
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"build": "node build.js",
|
|
||||||
"pretest": "node build.js",
|
|
||||||
"test": "jest"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
119
pool.test.js
Normal file
119
pool.test.js
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
|
||||||
|
require('websocket-polyfill')
|
||||||
|
const {
|
||||||
|
SimplePool,
|
||||||
|
generatePrivateKey,
|
||||||
|
getPublicKey,
|
||||||
|
getEventHash,
|
||||||
|
signEvent
|
||||||
|
} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
|
let pool = new SimplePool()
|
||||||
|
|
||||||
|
let relays = [
|
||||||
|
'wss://nostr-dev.wellorder.net/',
|
||||||
|
'wss://relay.nostr.bg/',
|
||||||
|
'wss://nostr.fmt.wiz.biz/',
|
||||||
|
'wss://relay.nostr.band/',
|
||||||
|
'wss://nostr.zebedee.cloud/'
|
||||||
|
]
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
Promise.all(
|
||||||
|
relays.map(relay => {
|
||||||
|
try {
|
||||||
|
let r = pool.ensureRelay(relay)
|
||||||
|
return r.connect()
|
||||||
|
} catch (err) {
|
||||||
|
/***/
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
relays.forEach(relay => {
|
||||||
|
try {
|
||||||
|
let r = pool.ensureRelay(relay)
|
||||||
|
r.close()
|
||||||
|
} catch (err) {
|
||||||
|
/***/
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('removing duplicates when querying', async () => {
|
||||||
|
let priv = generatePrivateKey()
|
||||||
|
let pub = getPublicKey(priv)
|
||||||
|
|
||||||
|
let subs = pool.sub(relays, [
|
||||||
|
{
|
||||||
|
authors: [pub]
|
||||||
|
}
|
||||||
|
])
|
||||||
|
|
||||||
|
let received = []
|
||||||
|
|
||||||
|
subs.forEach(sub =>
|
||||||
|
sub.on('event', event => {
|
||||||
|
// this should be called only once even though we're listening
|
||||||
|
// to multiple relays because the events will be catched and
|
||||||
|
// deduplicated efficiently (without even being parsed)
|
||||||
|
received.push(event)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
let event = {
|
||||||
|
pubkey: pub,
|
||||||
|
created_at: Math.round(Date.now() / 1000),
|
||||||
|
content: 'test',
|
||||||
|
kind: 22345,
|
||||||
|
tags: []
|
||||||
|
}
|
||||||
|
event.id = getEventHash(event)
|
||||||
|
event.sig = signEvent(event, priv)
|
||||||
|
|
||||||
|
pool.publish(relays, event)
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 1500))
|
||||||
|
|
||||||
|
expect(received).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('removing duplicates correctly when double querying', async () => {
|
||||||
|
let priv = generatePrivateKey()
|
||||||
|
let pub = getPublicKey(priv)
|
||||||
|
|
||||||
|
let subs1 = pool.sub(relays, [{authors: [pub]}])
|
||||||
|
let subs2 = pool.sub(relays, [{authors: [pub]}])
|
||||||
|
|
||||||
|
let received = []
|
||||||
|
|
||||||
|
subs1.forEach(sub =>
|
||||||
|
sub.on('event', event => {
|
||||||
|
received.push(event)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
subs2.forEach(sub =>
|
||||||
|
sub.on('event', event => {
|
||||||
|
received.push(event)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
let event = {
|
||||||
|
pubkey: pub,
|
||||||
|
created_at: Math.round(Date.now() / 1000),
|
||||||
|
content: 'test2',
|
||||||
|
kind: 22346,
|
||||||
|
tags: []
|
||||||
|
}
|
||||||
|
event.id = getEventHash(event)
|
||||||
|
event.sig = signEvent(event, priv)
|
||||||
|
|
||||||
|
pool.publish(relays, event)
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 1500))
|
||||||
|
|
||||||
|
expect(received).toHaveLength(2)
|
||||||
|
})
|
||||||
130
pool.ts
Normal file
130
pool.ts
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
import {Relay, relayInit} from './relay'
|
||||||
|
import {normalizeURL} from './utils'
|
||||||
|
import {Filter} from './filter'
|
||||||
|
import {Event} from './event'
|
||||||
|
import {SubscriptionOptions, Sub, Pub} from './relay'
|
||||||
|
|
||||||
|
export class SimplePool {
|
||||||
|
private _conn: {[url: string]: Relay}
|
||||||
|
|
||||||
|
constructor(defaultRelays: string[] = []) {
|
||||||
|
this._conn = {}
|
||||||
|
defaultRelays.forEach(this.ensureRelay)
|
||||||
|
}
|
||||||
|
|
||||||
|
ensureRelay(url: string): Relay {
|
||||||
|
const nm = normalizeURL(url)
|
||||||
|
const existing = this._conn[nm]
|
||||||
|
if (existing) return existing
|
||||||
|
|
||||||
|
const relay = relayInit(nm)
|
||||||
|
this._conn[nm] = relay
|
||||||
|
|
||||||
|
return relay
|
||||||
|
}
|
||||||
|
|
||||||
|
sub(relays: string[], filters: Filter[], opts?: SubscriptionOptions): Sub[] {
|
||||||
|
let _knownIds: Set<string> = new Set()
|
||||||
|
let modifiedOpts = opts || {}
|
||||||
|
modifiedOpts.alreadyHaveEvent = id => _knownIds.has(id)
|
||||||
|
|
||||||
|
return relays.map(relay => {
|
||||||
|
let r = this._conn[relay]
|
||||||
|
if (!r) return badSub()
|
||||||
|
let s = r.sub(filters, modifiedOpts)
|
||||||
|
s.on('event', (event: Event) => _knownIds.add(event.id as string))
|
||||||
|
return s
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
get(
|
||||||
|
relays: string[],
|
||||||
|
filter: Filter,
|
||||||
|
opts?: SubscriptionOptions
|
||||||
|
): Promise<Event | null> {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
let subs = this.sub(relays, [filter], opts)
|
||||||
|
let timeout = setTimeout(() => {
|
||||||
|
subs.forEach(sub => sub.unsub(), 1500)
|
||||||
|
resolve(null)
|
||||||
|
})
|
||||||
|
subs.forEach(sub => {
|
||||||
|
sub.on('event', (event: Event) => {
|
||||||
|
resolve(event)
|
||||||
|
clearTimeout(timeout)
|
||||||
|
subs.forEach(sub => {
|
||||||
|
sub.unsub()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
list(
|
||||||
|
relays: string[],
|
||||||
|
filters: Filter[],
|
||||||
|
opts?: SubscriptionOptions
|
||||||
|
): Promise<Event[]> {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
let _knownIds: Set<string> = new Set()
|
||||||
|
let modifiedOpts = opts || {}
|
||||||
|
modifiedOpts.alreadyHaveEvent = id => _knownIds.has(id)
|
||||||
|
|
||||||
|
let events: Event[] = []
|
||||||
|
|
||||||
|
let subs = this.sub(relays, filters, modifiedOpts)
|
||||||
|
let timeout = setTimeout(() => {
|
||||||
|
subs.forEach(sub => sub.unsub(), 1500)
|
||||||
|
resolve(events)
|
||||||
|
})
|
||||||
|
|
||||||
|
let pendingEoses = relays.length
|
||||||
|
|
||||||
|
subs.forEach(sub => {
|
||||||
|
sub.on('event', (event: Event) => {
|
||||||
|
events.push(event)
|
||||||
|
})
|
||||||
|
|
||||||
|
sub.on('eose', () => {
|
||||||
|
pendingEoses--
|
||||||
|
if (pendingEoses === 0) {
|
||||||
|
resolve(events)
|
||||||
|
clearTimeout(timeout)
|
||||||
|
subs.forEach(sub => {
|
||||||
|
sub.unsub()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
publish(relays: string[], event: Event): Pub[] {
|
||||||
|
return relays.map(relay => {
|
||||||
|
let r = this._conn[relay]
|
||||||
|
if (!r) return badPub(relay)
|
||||||
|
let s = r.publish(event)
|
||||||
|
return s
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function badSub(): Sub {
|
||||||
|
return {
|
||||||
|
on() {},
|
||||||
|
off() {},
|
||||||
|
sub(): Sub {
|
||||||
|
return badSub()
|
||||||
|
},
|
||||||
|
unsub() {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function badPub(relay: string): Pub {
|
||||||
|
return {
|
||||||
|
on(typ, cb) {
|
||||||
|
if (typ === 'failed') cb(`relay ${relay} not connected`)
|
||||||
|
},
|
||||||
|
off() {}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@ const {
|
|||||||
signEvent
|
signEvent
|
||||||
} = require('./lib/nostr.cjs')
|
} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
let relay = relayInit('wss://nostr-pub.semisol.dev/')
|
let relay = relayInit('wss://nostr-dev.wellorder.net/')
|
||||||
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
relay.connect()
|
relay.connect()
|
||||||
@@ -98,7 +98,7 @@ test('listening (twice) and publishing', async () => {
|
|||||||
content: 'nostr-tools test suite'
|
content: 'nostr-tools test suite'
|
||||||
}
|
}
|
||||||
event.id = getEventHash(event)
|
event.id = getEventHash(event)
|
||||||
event.sig = await signEvent(event, sk)
|
event.sig = signEvent(event, sk)
|
||||||
|
|
||||||
relay.publish(event)
|
relay.publish(event)
|
||||||
return expect(
|
return expect(
|
||||||
|
|||||||
144
relay.ts
144
relay.ts
@@ -2,16 +2,21 @@
|
|||||||
|
|
||||||
import {Event, verifySignature, validateEvent} from './event'
|
import {Event, verifySignature, validateEvent} from './event'
|
||||||
import {Filter, matchFilters} from './filter'
|
import {Filter, matchFilters} from './filter'
|
||||||
|
import {getHex64, getSubscriptionId} from './fakejson'
|
||||||
|
|
||||||
|
type RelayEvent = 'connect' | 'disconnect' | 'error' | 'notice'
|
||||||
|
|
||||||
export type Relay = {
|
export type Relay = {
|
||||||
url: string
|
url: string
|
||||||
status: number
|
status: number
|
||||||
connect: () => void
|
connect: () => Promise<void>
|
||||||
close: () => void
|
close: () => Promise<void>
|
||||||
sub: (filters: Filter[], opts: SubscriptionOptions) => Sub
|
sub: (filters: Filter[], opts?: SubscriptionOptions) => Sub
|
||||||
|
list: (filters: Filter[], opts?: SubscriptionOptions) => Promise<Event[]>
|
||||||
|
get: (filter: Filter, opts?: SubscriptionOptions) => Promise<Event | null>
|
||||||
publish: (event: Event) => Pub
|
publish: (event: Event) => Pub
|
||||||
on: (type: 'connect' | 'disconnect' | 'notice', cb: any) => void
|
on: (type: RelayEvent, cb: any) => void
|
||||||
off: (type: 'connect' | 'disconnect' | 'notice', cb: any) => void
|
off: (type: RelayEvent, cb: any) => void
|
||||||
}
|
}
|
||||||
export type Pub = {
|
export type Pub = {
|
||||||
on: (type: 'ok' | 'seen' | 'failed', cb: any) => void
|
on: (type: 'ok' | 'seen' | 'failed', cb: any) => void
|
||||||
@@ -24,15 +29,19 @@ export type Sub = {
|
|||||||
off: (type: 'event' | 'eose', cb: any) => void
|
off: (type: 'event' | 'eose', cb: any) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
type SubscriptionOptions = {
|
export type SubscriptionOptions = {
|
||||||
skipVerification?: boolean
|
skipVerification?: boolean
|
||||||
|
alreadyHaveEvent?: null | ((id: string) => boolean)
|
||||||
id?: string
|
id?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export function relayInit(url: string): Relay {
|
export function relayInit(url: string): Relay {
|
||||||
var ws: WebSocket
|
var ws: WebSocket
|
||||||
var resolveClose: () => void
|
var resolveClose: () => void
|
||||||
var untilOpen: Promise<void>
|
var setOpen: (value: PromiseLike<void> | void) => void
|
||||||
|
var untilOpen = new Promise<void>(resolve => {
|
||||||
|
setOpen = resolve
|
||||||
|
})
|
||||||
var openSubs: {[id: string]: {filters: Filter[]} & SubscriptionOptions} = {}
|
var openSubs: {[id: string]: {filters: Filter[]} & SubscriptionOptions} = {}
|
||||||
var listeners: {
|
var listeners: {
|
||||||
connect: Array<() => void>
|
connect: Array<() => void>
|
||||||
@@ -65,6 +74,7 @@ export function relayInit(url: string): Relay {
|
|||||||
|
|
||||||
ws.onopen = () => {
|
ws.onopen = () => {
|
||||||
listeners.connect.forEach(cb => cb())
|
listeners.connect.forEach(cb => cb())
|
||||||
|
setOpen()
|
||||||
resolve()
|
resolve()
|
||||||
}
|
}
|
||||||
ws.onerror = () => {
|
ws.onerror = () => {
|
||||||
@@ -73,22 +83,45 @@ export function relayInit(url: string): Relay {
|
|||||||
}
|
}
|
||||||
ws.onclose = async () => {
|
ws.onclose = async () => {
|
||||||
listeners.disconnect.forEach(cb => cb())
|
listeners.disconnect.forEach(cb => cb())
|
||||||
resolveClose()
|
resolveClose && resolveClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
ws.onmessage = async e => {
|
let incomingMessageQueue: string[] = []
|
||||||
var data
|
let handleNextInterval: any
|
||||||
try {
|
|
||||||
data = JSON.parse(e.data)
|
ws.onmessage = e => {
|
||||||
} catch (err) {
|
incomingMessageQueue.push(e.data)
|
||||||
data = e.data
|
if (!handleNextInterval) {
|
||||||
|
handleNextInterval = setInterval(handleNext, 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleNext() {
|
||||||
|
if (incomingMessageQueue.length === 0) {
|
||||||
|
clearInterval(handleNextInterval)
|
||||||
|
handleNextInterval = null
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.length >= 1) {
|
var json = incomingMessageQueue.shift()
|
||||||
|
if (!json) return
|
||||||
|
|
||||||
|
let subid = getSubscriptionId(json)
|
||||||
|
if (subid) {
|
||||||
|
let {alreadyHaveEvent} = openSubs[subid]
|
||||||
|
if (alreadyHaveEvent && alreadyHaveEvent(getHex64(json, 'id'))) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
let data = JSON.parse(json)
|
||||||
|
|
||||||
|
// we won't do any checks against the data since all failures (i.e. invalid messages from relays)
|
||||||
|
// will naturally be caught by the encompassing try..catch block
|
||||||
|
|
||||||
switch (data[0]) {
|
switch (data[0]) {
|
||||||
case 'EVENT':
|
case 'EVENT':
|
||||||
if (data.length !== 3) return // ignore empty or malformed EVENT
|
|
||||||
|
|
||||||
let id = data[1]
|
let id = data[1]
|
||||||
let event = data[2]
|
let event = data[2]
|
||||||
if (
|
if (
|
||||||
@@ -98,17 +131,15 @@ export function relayInit(url: string): Relay {
|
|||||||
matchFilters(openSubs[id].filters, event)
|
matchFilters(openSubs[id].filters, event)
|
||||||
) {
|
) {
|
||||||
openSubs[id]
|
openSubs[id]
|
||||||
subListeners[id]?.event.forEach(cb => cb(event))
|
;(subListeners[id]?.event || []).forEach(cb => cb(event))
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
case 'EOSE': {
|
case 'EOSE': {
|
||||||
if (data.length !== 2) return // ignore empty or malformed EOSE
|
|
||||||
let id = data[1]
|
let id = data[1]
|
||||||
subListeners[id]?.eose.forEach(cb => cb())
|
;(subListeners[id]?.eose || []).forEach(cb => cb())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
case 'OK': {
|
case 'OK': {
|
||||||
if (data.length < 3) return // ignore empty or malformed OK
|
|
||||||
let id: string = data[1]
|
let id: string = data[1]
|
||||||
let ok: boolean = data[2]
|
let ok: boolean = data[2]
|
||||||
let reason: string = data[3] || ''
|
let reason: string = data[3] || ''
|
||||||
@@ -117,11 +148,12 @@ export function relayInit(url: string): Relay {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
case 'NOTICE':
|
case 'NOTICE':
|
||||||
if (data.length !== 2) return // ignore empty or malformed NOTICE
|
|
||||||
let notice = data[1]
|
let notice = data[1]
|
||||||
listeners.notice.forEach(cb => cb(notice))
|
listeners.notice.forEach(cb => cb(notice))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
} catch (err) {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -136,13 +168,18 @@ export function relayInit(url: string): Relay {
|
|||||||
let msg = JSON.stringify(params)
|
let msg = JSON.stringify(params)
|
||||||
|
|
||||||
await untilOpen
|
await untilOpen
|
||||||
ws.send(msg)
|
try {
|
||||||
|
ws.send(msg)
|
||||||
|
} catch (err) {
|
||||||
|
console.log(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const sub = (
|
const sub = (
|
||||||
filters: Filter[],
|
filters: Filter[],
|
||||||
{
|
{
|
||||||
skipVerification = false,
|
skipVerification = false,
|
||||||
|
alreadyHaveEvent = null,
|
||||||
id = Math.random().toString().slice(2)
|
id = Math.random().toString().slice(2)
|
||||||
}: SubscriptionOptions = {}
|
}: SubscriptionOptions = {}
|
||||||
): Sub => {
|
): Sub => {
|
||||||
@@ -151,7 +188,8 @@ export function relayInit(url: string): Relay {
|
|||||||
openSubs[subid] = {
|
openSubs[subid] = {
|
||||||
id: subid,
|
id: subid,
|
||||||
filters,
|
filters,
|
||||||
skipVerification
|
skipVerification,
|
||||||
|
alreadyHaveEvent
|
||||||
}
|
}
|
||||||
trySend(['REQ', subid, ...filters])
|
trySend(['REQ', subid, ...filters])
|
||||||
|
|
||||||
@@ -159,6 +197,7 @@ export function relayInit(url: string): Relay {
|
|||||||
sub: (newFilters, newOpts = {}) =>
|
sub: (newFilters, newOpts = {}) =>
|
||||||
sub(newFilters || filters, {
|
sub(newFilters || filters, {
|
||||||
skipVerification: newOpts.skipVerification || skipVerification,
|
skipVerification: newOpts.skipVerification || skipVerification,
|
||||||
|
alreadyHaveEvent: newOpts.alreadyHaveEvent || alreadyHaveEvent,
|
||||||
id: subid
|
id: subid
|
||||||
}),
|
}),
|
||||||
unsub: () => {
|
unsub: () => {
|
||||||
@@ -174,8 +213,9 @@ export function relayInit(url: string): Relay {
|
|||||||
subListeners[subid][type].push(cb)
|
subListeners[subid][type].push(cb)
|
||||||
},
|
},
|
||||||
off: (type: 'event' | 'eose', cb: any): void => {
|
off: (type: 'event' | 'eose', cb: any): void => {
|
||||||
let idx = subListeners[subid][type].indexOf(cb)
|
let listeners = subListeners[subid]
|
||||||
if (idx >= 0) subListeners[subid][type].splice(idx, 1)
|
let idx = listeners[type].indexOf(cb)
|
||||||
|
if (idx >= 0) listeners[type].splice(idx, 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -183,22 +223,46 @@ export function relayInit(url: string): Relay {
|
|||||||
return {
|
return {
|
||||||
url,
|
url,
|
||||||
sub,
|
sub,
|
||||||
on: (
|
on: (type: RelayEvent, cb: any): void => {
|
||||||
type: 'connect' | 'disconnect' | 'error' | 'notice',
|
|
||||||
cb: any
|
|
||||||
): void => {
|
|
||||||
listeners[type].push(cb)
|
listeners[type].push(cb)
|
||||||
if (type === 'connect' && ws?.readyState === 1) {
|
if (type === 'connect' && ws?.readyState === 1) {
|
||||||
cb()
|
cb()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
off: (
|
off: (type: RelayEvent, cb: any): void => {
|
||||||
type: 'connect' | 'disconnect' | 'error' | 'notice',
|
|
||||||
cb: any
|
|
||||||
): void => {
|
|
||||||
let index = listeners[type].indexOf(cb)
|
let index = listeners[type].indexOf(cb)
|
||||||
if (index !== -1) listeners[type].splice(index, 1)
|
if (index !== -1) listeners[type].splice(index, 1)
|
||||||
},
|
},
|
||||||
|
list: (filters: Filter[], opts?: SubscriptionOptions): Promise<Event[]> =>
|
||||||
|
new Promise(resolve => {
|
||||||
|
let s = sub(filters, opts)
|
||||||
|
let events: Event[] = []
|
||||||
|
let timeout = setTimeout(() => {
|
||||||
|
s.unsub()
|
||||||
|
resolve(events)
|
||||||
|
}, 1500)
|
||||||
|
s.on('eose', () => {
|
||||||
|
s.unsub()
|
||||||
|
clearTimeout(timeout)
|
||||||
|
resolve(events)
|
||||||
|
})
|
||||||
|
s.on('event', (event: Event) => {
|
||||||
|
events.push(event)
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
get: (filter: Filter, opts?: SubscriptionOptions): Promise<Event | null> =>
|
||||||
|
new Promise(resolve => {
|
||||||
|
let s = sub([filter], opts)
|
||||||
|
let timeout = setTimeout(() => {
|
||||||
|
s.unsub()
|
||||||
|
resolve(null)
|
||||||
|
}, 1500)
|
||||||
|
s.on('event', (event: Event) => {
|
||||||
|
s.unsub()
|
||||||
|
clearTimeout(timeout)
|
||||||
|
resolve(event)
|
||||||
|
})
|
||||||
|
}),
|
||||||
publish(event: Event): Pub {
|
publish(event: Event): Pub {
|
||||||
if (!event.id) throw new Error(`event ${event} has no id`)
|
if (!event.id) throw new Error(`event ${event} has no id`)
|
||||||
let id = event.id
|
let id = event.id
|
||||||
@@ -221,14 +285,14 @@ export function relayInit(url: string): Relay {
|
|||||||
id: `monitor-${id.slice(0, 5)}`
|
id: `monitor-${id.slice(0, 5)}`
|
||||||
})
|
})
|
||||||
let willUnsub = setTimeout(() => {
|
let willUnsub = setTimeout(() => {
|
||||||
pubListeners[id].failed.forEach(cb =>
|
;(pubListeners[id]?.failed || []).forEach(cb =>
|
||||||
cb('event not seen after 5 seconds')
|
cb('event not seen after 5 seconds')
|
||||||
)
|
)
|
||||||
monitor.unsub()
|
monitor.unsub()
|
||||||
}, 5000)
|
}, 5000)
|
||||||
monitor.on('event', () => {
|
monitor.on('event', () => {
|
||||||
clearTimeout(willUnsub)
|
clearTimeout(willUnsub)
|
||||||
pubListeners[id].seen.forEach(cb => cb())
|
;(pubListeners[id]?.seen || []).forEach(cb => cb())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -247,15 +311,17 @@ export function relayInit(url: string): Relay {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
off: (type: 'ok' | 'seen' | 'failed', cb: any) => {
|
off: (type: 'ok' | 'seen' | 'failed', cb: any) => {
|
||||||
let idx = pubListeners[id][type].indexOf(cb)
|
let listeners = pubListeners[id]
|
||||||
if (idx >= 0) pubListeners[id][type].splice(idx, 1)
|
if (!listeners) return
|
||||||
|
let idx = listeners[type].indexOf(cb)
|
||||||
|
if (idx >= 0) listeners[type].splice(idx, 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
connect,
|
connect,
|
||||||
close(): Promise<void> {
|
close(): Promise<void> {
|
||||||
ws.close()
|
ws.close()
|
||||||
return new Promise(resolve => {
|
return new Promise<void>(resolve => {
|
||||||
resolveClose = resolve
|
resolveClose = resolve
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|||||||
183
utils.test.js
Normal file
183
utils.test.js
Normal file
@@ -0,0 +1,183 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
|
||||||
|
const {utils} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
|
const {insertEventIntoAscendingList, insertEventIntoDescendingList} = utils
|
||||||
|
|
||||||
|
describe('inserting into a desc sorted list of events', () => {
|
||||||
|
test('insert into an empty list', async () => {
|
||||||
|
const list0 = []
|
||||||
|
expect(
|
||||||
|
insertEventIntoDescendingList(list0, {id: 'abc', created_at: 10})
|
||||||
|
).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('insert in the beginning of a list', async () => {
|
||||||
|
const list0 = [{created_at: 20}, {created_at: 10}]
|
||||||
|
const list1 = insertEventIntoDescendingList(list0, {
|
||||||
|
id: 'abc',
|
||||||
|
created_at: 30
|
||||||
|
})
|
||||||
|
expect(list1).toHaveLength(3)
|
||||||
|
expect(list1[0].id).toBe('abc')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('insert in the beginning of a list with same created_at', async () => {
|
||||||
|
const list0 = [{created_at: 30}, {created_at: 20}, {created_at: 10}]
|
||||||
|
const list1 = insertEventIntoDescendingList(list0, {
|
||||||
|
id: 'abc',
|
||||||
|
created_at: 30
|
||||||
|
})
|
||||||
|
expect(list1).toHaveLength(4)
|
||||||
|
expect(list1[0].id).toBe('abc')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('insert in the middle of a list', async () => {
|
||||||
|
const list0 = [
|
||||||
|
{created_at: 30},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 10},
|
||||||
|
{created_at: 1}
|
||||||
|
]
|
||||||
|
const list1 = insertEventIntoDescendingList(list0, {
|
||||||
|
id: 'abc',
|
||||||
|
created_at: 15
|
||||||
|
})
|
||||||
|
expect(list1).toHaveLength(5)
|
||||||
|
expect(list1[2].id).toBe('abc')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('insert in the end of a list', async () => {
|
||||||
|
const list0 = [
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 10}
|
||||||
|
]
|
||||||
|
const list1 = insertEventIntoDescendingList(list0, {
|
||||||
|
id: 'abc',
|
||||||
|
created_at: 5
|
||||||
|
})
|
||||||
|
expect(list1).toHaveLength(6)
|
||||||
|
expect(list1.slice(-1)[0].id).toBe('abc')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('insert in the last-to-end of a list with same created_at', async () => {
|
||||||
|
const list0 = [
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 10}
|
||||||
|
]
|
||||||
|
const list1 = insertEventIntoDescendingList(list0, {
|
||||||
|
id: 'abc',
|
||||||
|
created_at: 10
|
||||||
|
})
|
||||||
|
expect(list1).toHaveLength(6)
|
||||||
|
expect(list1.slice(-2)[0].id).toBe('abc')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('do not insert duplicates', async () => {
|
||||||
|
const list0 = [
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 10, id: 'abc'}
|
||||||
|
]
|
||||||
|
const list1 = insertEventIntoDescendingList(list0, {
|
||||||
|
id: 'abc',
|
||||||
|
created_at: 10
|
||||||
|
})
|
||||||
|
expect(list1).toHaveLength(3)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('inserting into a asc sorted list of events', () => {
|
||||||
|
test('insert into an empty list', async () => {
|
||||||
|
const list0 = []
|
||||||
|
expect(
|
||||||
|
insertEventIntoAscendingList(list0, {id: 'abc', created_at: 10})
|
||||||
|
).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('insert in the beginning of a list', async () => {
|
||||||
|
const list0 = [{created_at: 10}, {created_at: 20}]
|
||||||
|
const list1 = insertEventIntoAscendingList(list0, {
|
||||||
|
id: 'abc',
|
||||||
|
created_at: 1
|
||||||
|
})
|
||||||
|
expect(list1).toHaveLength(3)
|
||||||
|
expect(list1[0].id).toBe('abc')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('insert in the beginning of a list with same created_at', async () => {
|
||||||
|
const list0 = [{created_at: 10}, {created_at: 20}, {created_at: 30}]
|
||||||
|
const list1 = insertEventIntoAscendingList(list0, {
|
||||||
|
id: 'abc',
|
||||||
|
created_at: 10
|
||||||
|
})
|
||||||
|
expect(list1).toHaveLength(4)
|
||||||
|
expect(list1[0].id).toBe('abc')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('insert in the middle of a list', async () => {
|
||||||
|
const list0 = [
|
||||||
|
{created_at: 10},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 30},
|
||||||
|
{created_at: 40}
|
||||||
|
]
|
||||||
|
const list1 = insertEventIntoAscendingList(list0, {
|
||||||
|
id: 'abc',
|
||||||
|
created_at: 25
|
||||||
|
})
|
||||||
|
expect(list1).toHaveLength(5)
|
||||||
|
expect(list1[2].id).toBe('abc')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('insert in the end of a list', async () => {
|
||||||
|
const list0 = [
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 40}
|
||||||
|
]
|
||||||
|
const list1 = insertEventIntoAscendingList(list0, {
|
||||||
|
id: 'abc',
|
||||||
|
created_at: 50
|
||||||
|
})
|
||||||
|
expect(list1).toHaveLength(6)
|
||||||
|
expect(list1.slice(-1)[0].id).toBe('abc')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('insert in the last-to-end of a list with same created_at', async () => {
|
||||||
|
const list0 = [
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 30}
|
||||||
|
]
|
||||||
|
const list1 = insertEventIntoAscendingList(list0, {
|
||||||
|
id: 'abc',
|
||||||
|
created_at: 30
|
||||||
|
})
|
||||||
|
expect(list1).toHaveLength(6)
|
||||||
|
expect(list1.slice(-2)[0].id).toBe('abc')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('do not insert duplicates', async () => {
|
||||||
|
const list0 = [
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 20},
|
||||||
|
{created_at: 30, id: 'abc'}
|
||||||
|
]
|
||||||
|
const list1 = insertEventIntoAscendingList(list0, {
|
||||||
|
id: 'abc',
|
||||||
|
created_at: 30
|
||||||
|
})
|
||||||
|
expect(list1).toHaveLength(3)
|
||||||
|
})
|
||||||
|
})
|
||||||
109
utils.ts
109
utils.ts
@@ -1,2 +1,111 @@
|
|||||||
|
import {Event} from './event'
|
||||||
|
|
||||||
export const utf8Decoder = new TextDecoder('utf-8')
|
export const utf8Decoder = new TextDecoder('utf-8')
|
||||||
export const utf8Encoder = new TextEncoder()
|
export const utf8Encoder = new TextEncoder()
|
||||||
|
|
||||||
|
export function normalizeURL(url: string): string {
|
||||||
|
let p = new URL(url)
|
||||||
|
p.pathname = p.pathname.replace(/\/+/g, '/')
|
||||||
|
if (p.pathname.endsWith('/')) p.pathname = p.pathname.slice(0, -1)
|
||||||
|
if (
|
||||||
|
(p.port === '80' && p.protocol === 'ws:') ||
|
||||||
|
(p.port === '443' && p.protocol === 'wss:')
|
||||||
|
)
|
||||||
|
p.port = ''
|
||||||
|
p.searchParams.sort()
|
||||||
|
p.hash = ''
|
||||||
|
return p.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// fast insert-into-sorted-array functions adapted from https://github.com/terrymorse58/fast-sorted-array
|
||||||
|
//
|
||||||
|
export function insertEventIntoDescendingList(
|
||||||
|
sortedArray: Event[],
|
||||||
|
event: Event
|
||||||
|
) {
|
||||||
|
let start = 0
|
||||||
|
let end = sortedArray.length - 1
|
||||||
|
let midPoint
|
||||||
|
let position = start
|
||||||
|
|
||||||
|
if (end < 0) {
|
||||||
|
position = 0
|
||||||
|
} else if (event.created_at < sortedArray[end].created_at) {
|
||||||
|
position = end + 1
|
||||||
|
} else if (event.created_at >= sortedArray[start].created_at) {
|
||||||
|
position = start
|
||||||
|
} else
|
||||||
|
while (true) {
|
||||||
|
if (end <= start + 1) {
|
||||||
|
position = end
|
||||||
|
break
|
||||||
|
}
|
||||||
|
midPoint = Math.floor(start + (end - start) / 2)
|
||||||
|
if (sortedArray[midPoint].created_at > event.created_at) {
|
||||||
|
start = midPoint
|
||||||
|
} else if (sortedArray[midPoint].created_at < event.created_at) {
|
||||||
|
end = midPoint
|
||||||
|
} else {
|
||||||
|
// aMidPoint === num
|
||||||
|
position = midPoint
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// insert when num is NOT already in (no duplicates)
|
||||||
|
if (sortedArray[position]?.id !== event.id) {
|
||||||
|
return [
|
||||||
|
...sortedArray.slice(0, position),
|
||||||
|
event,
|
||||||
|
...sortedArray.slice(position)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
return sortedArray
|
||||||
|
}
|
||||||
|
|
||||||
|
export function insertEventIntoAscendingList(
|
||||||
|
sortedArray: Event[],
|
||||||
|
event: Event
|
||||||
|
) {
|
||||||
|
let start = 0
|
||||||
|
let end = sortedArray.length - 1
|
||||||
|
let midPoint
|
||||||
|
let position = start
|
||||||
|
|
||||||
|
if (end < 0) {
|
||||||
|
position = 0
|
||||||
|
} else if (event.created_at > sortedArray[end].created_at) {
|
||||||
|
position = end + 1
|
||||||
|
} else if (event.created_at <= sortedArray[start].created_at) {
|
||||||
|
position = start
|
||||||
|
} else
|
||||||
|
while (true) {
|
||||||
|
if (end <= start + 1) {
|
||||||
|
position = end
|
||||||
|
break
|
||||||
|
}
|
||||||
|
midPoint = Math.floor(start + (end - start) / 2)
|
||||||
|
if (sortedArray[midPoint].created_at < event.created_at) {
|
||||||
|
start = midPoint
|
||||||
|
} else if (sortedArray[midPoint].created_at > event.created_at) {
|
||||||
|
end = midPoint
|
||||||
|
} else {
|
||||||
|
// aMidPoint === num
|
||||||
|
position = midPoint
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// insert when num is NOT already in (no duplicates)
|
||||||
|
if (sortedArray[position]?.id !== event.id) {
|
||||||
|
return [
|
||||||
|
...sortedArray.slice(0, position),
|
||||||
|
event,
|
||||||
|
...sortedArray.slice(position)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
return sortedArray
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user