mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-08 16:28:49 +00:00
Compare commits
121 Commits
v1.0.0-rc1
...
v1.8.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce73b96565 | ||
|
|
8818e4f88a | ||
|
|
5a63c75f24 | ||
|
|
60e01a9006 | ||
|
|
687f387385 | ||
|
|
6d116a2f7f | ||
|
|
51c3aec788 | ||
|
|
613b2c177f | ||
|
|
24f5068fdb | ||
|
|
5733f9c4e4 | ||
|
|
6b73bbf8a3 | ||
|
|
d244b62c7a | ||
|
|
b00af9a30a | ||
|
|
be7c981c14 | ||
|
|
5539e5cf89 | ||
|
|
73decbc8e0 | ||
|
|
b3d95cecdd | ||
|
|
82228036ef | ||
|
|
01435ab9f5 | ||
|
|
63cbc4133a | ||
|
|
049f183d27 | ||
|
|
f9e3119ab4 | ||
|
|
f992c9c967 | ||
|
|
dbf625d6ac | ||
|
|
8622bd11dd | ||
|
|
0970eee70f | ||
|
|
086f8830e3 | ||
|
|
e48d722227 | ||
|
|
0d77013aab | ||
|
|
4c415280aa | ||
|
|
4188aaf7c8 | ||
|
|
673f4abab8 | ||
|
|
bcefaa0757 | ||
|
|
649af36a86 | ||
|
|
96a6f7af87 | ||
|
|
a4c713efcb | ||
|
|
9d345a8f01 | ||
|
|
c362212778 | ||
|
|
a8938a3a0f | ||
|
|
a21329da3f | ||
|
|
63f4a49a69 | ||
|
|
27749d91b8 | ||
|
|
9530849f0a | ||
|
|
b8aa75b6e1 | ||
|
|
344762820c | ||
|
|
f43d23d344 | ||
|
|
bf55ad6b5a | ||
|
|
04a46b815c | ||
|
|
165ff44dff | ||
|
|
7bfd23af3c | ||
|
|
3d93ec8446 | ||
|
|
0f841138cd | ||
|
|
336948b1d1 | ||
|
|
d46794c681 | ||
|
|
93cef5d886 | ||
|
|
2324f9548e | ||
|
|
f9748d9cc3 | ||
|
|
3a22dd3da6 | ||
|
|
d13039dc11 | ||
|
|
95b03902cc | ||
|
|
ab5ea8de36 | ||
|
|
a330b97590 | ||
|
|
24406b5679 | ||
|
|
6dbcc87d93 | ||
|
|
0ddcfdce68 | ||
|
|
87bf349ce8 | ||
|
|
54dfc7b972 | ||
|
|
32793146a4 | ||
|
|
c42cd925ce | ||
|
|
43ccb72476 | ||
|
|
b2b7999517 | ||
|
|
a568afc295 | ||
|
|
9bcaed6e60 | ||
|
|
5a9cbbb557 | ||
|
|
e9acc59809 | ||
|
|
18fe9637b9 | ||
|
|
ff3bf4a51c | ||
|
|
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 |
8
.github/workflows/npm-publish.yml
vendored
8
.github/workflows/npm-publish.yml
vendored
@@ -12,9 +12,11 @@ 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
|
||||||
|
- run: just emit-types
|
||||||
- uses: JS-DevTools/npm-publish@v1
|
- uses: JS-DevTools/npm-publish@v1
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.NPM_TOKEN }}
|
token: ${{ secrets.NPM_TOKEN }}
|
||||||
|
|||||||
10
.github/workflows/test.yml
vendored
10
.github/workflows/test.yml
vendored
@@ -3,15 +3,17 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
|
pull_request:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v3
|
||||||
- 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
|
||||||
|
|||||||
144
README.md
144
README.md
@@ -2,7 +2,13 @@
|
|||||||
|
|
||||||
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.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install nostr-tools # or yarn add nostr-tools
|
||||||
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
@@ -30,15 +36,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
|
||||||
@@ -53,8 +59,6 @@ import {
|
|||||||
} from 'nostr-tools'
|
} from 'nostr-tools'
|
||||||
|
|
||||||
const relay = relayInit('wss://relay.example.com')
|
const relay = relayInit('wss://relay.example.com')
|
||||||
await relay.connect()
|
|
||||||
|
|
||||||
relay.on('connect', () => {
|
relay.on('connect', () => {
|
||||||
console.log(`connected to ${relay.url}`)
|
console.log(`connected to ${relay.url}`)
|
||||||
})
|
})
|
||||||
@@ -62,6 +66,8 @@ relay.on('error', () => {
|
|||||||
console.log(`failed to connect to ${relay.url}`)
|
console.log(`failed to connect to ${relay.url}`)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await relay.connect()
|
||||||
|
|
||||||
// let's query for an event that exists
|
// let's query for an event that exists
|
||||||
let sub = relay.sub([
|
let sub = relay.sub([
|
||||||
{
|
{
|
||||||
@@ -98,20 +104,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', () => {
|
|
||||||
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}`)
|
||||||
})
|
})
|
||||||
|
|
||||||
await relay.close()
|
let events = await relay.list([{kinds: [0, 1]}])
|
||||||
|
let event = await relay.get({
|
||||||
|
ids: ['44e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245']
|
||||||
|
})
|
||||||
|
|
||||||
|
relay.close()
|
||||||
```
|
```
|
||||||
|
|
||||||
To use this on Node.js you first must install `websocket-polyfill` and import it:
|
To use this on Node.js you first must install `websocket-polyfill` and import it:
|
||||||
@@ -120,6 +128,68 @@ 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 {SimplePool} from 'nostr-tools'
|
||||||
|
|
||||||
|
const pool = new SimplePool()
|
||||||
|
|
||||||
|
let relays = ['wss://relay.example.com', 'wss://relay.example2.com']
|
||||||
|
|
||||||
|
let sub = pool.sub(
|
||||||
|
[...relays, 'wss://relay.example3.com'],
|
||||||
|
[
|
||||||
|
{
|
||||||
|
authors: [
|
||||||
|
'32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
sub.on('event', event => {
|
||||||
|
// this will only be called once the first time the event is received
|
||||||
|
// ...
|
||||||
|
})
|
||||||
|
|
||||||
|
let pubs = pool.publish(relays, newEvent)
|
||||||
|
pubs.on('ok', () => {
|
||||||
|
// this may be called multiple times, once for every relay that accepts the event
|
||||||
|
// ...
|
||||||
|
})
|
||||||
|
|
||||||
|
let events = await pool.list(relays, [{kinds: [0, 1]}])
|
||||||
|
let event = await pool.get(relays, {
|
||||||
|
ids: ['44e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245']
|
||||||
|
})
|
||||||
|
|
||||||
|
let relaysForEvent = pool.seenOn(
|
||||||
|
'44e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'
|
||||||
|
)
|
||||||
|
// relaysForEvent will be an array of URLs from relays a given event was seen on
|
||||||
|
```
|
||||||
|
|
||||||
|
### Parsing references (mentions) from a content using NIP-10 and NIP-27
|
||||||
|
|
||||||
|
```js
|
||||||
|
import {parseReferences} from 'nostr-tools'
|
||||||
|
|
||||||
|
let references = parseReferences(event)
|
||||||
|
let simpleAugmentedContent = event.content
|
||||||
|
for (let i = 0; i < references.length; i++) {
|
||||||
|
let {text, profile, event, address} = references[i]
|
||||||
|
let augmentedReference = profile
|
||||||
|
? `<strong>@${profilesCache[profile.pubkey].name}</strong>`
|
||||||
|
: event
|
||||||
|
? `<em>${eventsCache[event.id].content.slice(0, 5)}</em>`
|
||||||
|
: address
|
||||||
|
? `<a href="${text}">[link]</a>`
|
||||||
|
: text
|
||||||
|
simpleAugmentedContent.replaceAll(text, augmentedReference)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Querying profile data from a NIP-05 address
|
### Querying profile data from a NIP-05 address
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@@ -182,7 +252,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 +265,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)
|
||||||
@@ -213,6 +318,11 @@ Please consult the tests or [the source code](https://github.com/fiatjaf/nostr-t
|
|||||||
</script>
|
</script>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Plumbing
|
||||||
|
|
||||||
|
1. Install [`just`](https://just.systems/)
|
||||||
|
2. `just -l`
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
Public domain.
|
Public domain.
|
||||||
|
|||||||
10
build.js
10
build.js
@@ -1,5 +1,6 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
const fs = require('fs')
|
||||||
const esbuild = require('esbuild')
|
const esbuild = require('esbuild')
|
||||||
|
|
||||||
let common = {
|
let common = {
|
||||||
@@ -11,11 +12,16 @@ let common = {
|
|||||||
esbuild
|
esbuild
|
||||||
.build({
|
.build({
|
||||||
...common,
|
...common,
|
||||||
outfile: 'lib/nostr.esm.js',
|
outfile: 'lib/esm/nostr.mjs',
|
||||||
format: 'esm',
|
format: 'esm',
|
||||||
packages: 'external'
|
packages: 'external'
|
||||||
})
|
})
|
||||||
.then(() => console.log('esm build success.'))
|
.then(() => {
|
||||||
|
const packageJson = JSON.stringify({type: 'module'})
|
||||||
|
fs.writeFileSync(`${__dirname}/lib/esm/package.json`, packageJson, 'utf8')
|
||||||
|
|
||||||
|
console.log('esm build success.')
|
||||||
|
})
|
||||||
|
|
||||||
esbuild
|
esbuild
|
||||||
.build({
|
.build({
|
||||||
|
|||||||
369
event.test.js
369
event.test.js
@@ -1,49 +1,340 @@
|
|||||||
/* eslint-env jest */
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
|
getBlankEvent,
|
||||||
|
finishEvent,
|
||||||
|
serializeEvent,
|
||||||
|
getEventHash,
|
||||||
validateEvent,
|
validateEvent,
|
||||||
verifySignature,
|
verifySignature,
|
||||||
signEvent,
|
signEvent,
|
||||||
getEventHash,
|
getPublicKey,
|
||||||
getPublicKey
|
Kind
|
||||||
} = require('./lib/nostr.cjs')
|
} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
const event = {
|
describe('Event', () => {
|
||||||
id: 'd7dd5eb3ab747e16f8d0212d53032ea2a7cadef53837e5a6c66d42849fcb9027',
|
describe('getBlankEvent', () => {
|
||||||
kind: 1,
|
it('should return a blank event object', () => {
|
||||||
pubkey: '22a12a128a3be27cd7fb250cbe796e692896398dc1440ae3fa567812c8107c1c',
|
expect(getBlankEvent()).toEqual({
|
||||||
created_at: 1670869179,
|
kind: 255,
|
||||||
content:
|
content: '',
|
||||||
'NOSTR "WINE-ACCOUNT" WITH HARVEST DATE STAMPED\n\n\n"The older the wine, the greater its reputation"\n\n\n22a12a128a3be27cd7fb250cbe796e692896398dc1440ae3fa567812c8107c1c\n\n\nNWA 2022-12-12\nAA',
|
|
||||||
tags: [['client', 'astral']],
|
|
||||||
sig: 'f110e4fdf67835fb07abc72469933c40bdc7334615610cade9554bf00945a1cebf84f8d079ec325d26fefd76fe51cb589bdbe208ac9cdbd63351ddad24a57559'
|
|
||||||
}
|
|
||||||
|
|
||||||
const unsigned = {
|
|
||||||
created_at: 1671217411,
|
|
||||||
kind: 0,
|
|
||||||
tags: [],
|
tags: [],
|
||||||
content:
|
created_at: 0
|
||||||
'{"name":"fiatjaf","about":"buy my merch at fiatjaf store","picture":"https://fiatjaf.com/static/favicon.jpg","nip05":"_@fiatjaf.com"}'
|
})
|
||||||
}
|
})
|
||||||
|
})
|
||||||
|
|
||||||
const privateKey =
|
describe('finishEvent', () => {
|
||||||
'5c6c25b7ef18d8633e97512159954e1aa22809c6b763e94b9f91071836d00217'
|
it('should create a signed event from a template', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
test('validate event', () => {
|
const template = {
|
||||||
expect(validateEvent(event)).toBeTruthy()
|
kind: Kind.Text,
|
||||||
})
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
test('check signature', async () => {
|
created_at: 1617932115
|
||||||
expect(await verifySignature(event)).toBeTruthy()
|
}
|
||||||
})
|
|
||||||
|
const event = finishEvent(template, privateKey)
|
||||||
test('sign event', async () => {
|
|
||||||
let sig = await signEvent(unsigned, privateKey)
|
expect(event.kind).toEqual(template.kind)
|
||||||
let hash = getEventHash(unsigned)
|
expect(event.tags).toEqual(template.tags)
|
||||||
let pubkey = getPublicKey(privateKey)
|
expect(event.content).toEqual(template.content)
|
||||||
|
expect(event.created_at).toEqual(template.created_at)
|
||||||
let signed = {...unsigned, id: hash, sig, pubkey}
|
expect(event.pubkey).toEqual(publicKey)
|
||||||
|
expect(typeof event.id).toEqual('string')
|
||||||
expect(await verifySignature(signed)).toBeTruthy()
|
expect(typeof event.sig).toEqual('string')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('serializeEvent', () => {
|
||||||
|
it('should serialize a valid event object', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
pubkey: publicKey,
|
||||||
|
created_at: 1617932115,
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!'
|
||||||
|
}
|
||||||
|
|
||||||
|
const serializedEvent = serializeEvent(unsignedEvent)
|
||||||
|
|
||||||
|
expect(serializedEvent).toEqual(
|
||||||
|
JSON.stringify([
|
||||||
|
0,
|
||||||
|
publicKey,
|
||||||
|
unsignedEvent.created_at,
|
||||||
|
unsignedEvent.kind,
|
||||||
|
unsignedEvent.tags,
|
||||||
|
unsignedEvent.content
|
||||||
|
])
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should throw an error for an invalid event object', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const invalidEvent = {
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey // missing content
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
serializeEvent(invalidEvent)
|
||||||
|
}).toThrow("can't serialize event with wrong or missing properties")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('getEventHash', () => {
|
||||||
|
it('should return the correct event hash', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const eventHash = getEventHash(unsignedEvent)
|
||||||
|
|
||||||
|
expect(typeof eventHash).toEqual('string')
|
||||||
|
expect(eventHash.length).toEqual(64)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('validateEvent', () => {
|
||||||
|
it('should return true for a valid event object', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = validateEvent(unsignedEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for a non object event', () => {
|
||||||
|
const nonObjectEvent = ''
|
||||||
|
|
||||||
|
const isValid = validateEvent(nonObjectEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for an event object with missing properties', () => {
|
||||||
|
const invalidEvent = {
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
created_at: 1617932115 // missing content and pubkey
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = validateEvent(invalidEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for an empty object', () => {
|
||||||
|
const emptyObj = {}
|
||||||
|
|
||||||
|
const isValid = validateEvent(emptyObj)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for an object with invalid properties', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const invalidEvent = {
|
||||||
|
kind: 1,
|
||||||
|
tags: [],
|
||||||
|
created_at: '1617932115', // should be a number
|
||||||
|
pubkey: publicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = validateEvent(invalidEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for an object with an invalid public key', () => {
|
||||||
|
const invalidEvent = {
|
||||||
|
kind: 1,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: 'invalid_pubkey'
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = validateEvent(invalidEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for an object with invalid tags', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const invalidEvent = {
|
||||||
|
kind: 1,
|
||||||
|
tags: {}, // should be an array
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = validateEvent(invalidEvent)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('verifySignature', () => {
|
||||||
|
it('should return true for a valid event signature', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
|
||||||
|
const event = finishEvent(
|
||||||
|
{
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115
|
||||||
|
},
|
||||||
|
privateKey
|
||||||
|
)
|
||||||
|
|
||||||
|
const isValid = verifySignature(event)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false for an invalid event signature', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
|
||||||
|
const event = finishEvent(
|
||||||
|
{
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115
|
||||||
|
},
|
||||||
|
privateKey
|
||||||
|
)
|
||||||
|
|
||||||
|
// tamper with the signature
|
||||||
|
event.sig = event.sig.replace(/0/g, '1')
|
||||||
|
|
||||||
|
const isValid = verifySignature(event)
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when verifying an event with a different private key', () => {
|
||||||
|
const privateKey1 =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
|
||||||
|
const privateKey2 =
|
||||||
|
'5b4a34f4e4b23c63ad55a35e3f84a3b53d96dbf266edf521a8358f71d19cbf67'
|
||||||
|
const publicKey2 = getPublicKey(privateKey2)
|
||||||
|
|
||||||
|
const event = finishEvent(
|
||||||
|
{
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115
|
||||||
|
},
|
||||||
|
privateKey1
|
||||||
|
)
|
||||||
|
|
||||||
|
// verify with different private key
|
||||||
|
const isValid = verifySignature({
|
||||||
|
...event,
|
||||||
|
pubkey: publicKey2
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('signEvent', () => {
|
||||||
|
it('should sign an event object', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const sig = signEvent(unsignedEvent, privateKey)
|
||||||
|
|
||||||
|
// verify the signature
|
||||||
|
const isValid = verifySignature({
|
||||||
|
...unsignedEvent,
|
||||||
|
sig
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(typeof sig).toEqual('string')
|
||||||
|
expect(sig.length).toEqual(128)
|
||||||
|
expect(isValid).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should not sign an event with different private key', () => {
|
||||||
|
const privateKey =
|
||||||
|
'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
|
||||||
|
const publicKey = getPublicKey(privateKey)
|
||||||
|
|
||||||
|
const wrongPrivateKey =
|
||||||
|
'a91e2a9d9e0f70f0877bea0dbf034e8f95d7392a27a7f07da0d14b9e9d456be7'
|
||||||
|
|
||||||
|
const unsignedEvent = {
|
||||||
|
kind: Kind.Text,
|
||||||
|
tags: [],
|
||||||
|
content: 'Hello, world!',
|
||||||
|
created_at: 1617932115,
|
||||||
|
pubkey: publicKey
|
||||||
|
}
|
||||||
|
|
||||||
|
const sig = signEvent(unsignedEvent, wrongPrivateKey)
|
||||||
|
|
||||||
|
// verify the signature
|
||||||
|
const isValid = verifySignature({
|
||||||
|
...unsignedEvent,
|
||||||
|
sig
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(typeof sig).toEqual('string')
|
||||||
|
expect(sig.length).toEqual(128)
|
||||||
|
expect(isValid).toEqual(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
84
event.ts
84
event.ts
@@ -2,28 +2,67 @@ import * as secp256k1 from '@noble/secp256k1'
|
|||||||
import {sha256} from '@noble/hashes/sha256'
|
import {sha256} from '@noble/hashes/sha256'
|
||||||
|
|
||||||
import {utf8Encoder} from './utils'
|
import {utf8Encoder} from './utils'
|
||||||
|
import {getPublicKey} from './keys'
|
||||||
|
|
||||||
export type Event = {
|
/* eslint-disable no-unused-vars */
|
||||||
id?: string
|
export enum Kind {
|
||||||
sig?: string
|
Metadata = 0,
|
||||||
kind: number
|
Text = 1,
|
||||||
|
RecommendRelay = 2,
|
||||||
|
Contacts = 3,
|
||||||
|
EncryptedDirectMessage = 4,
|
||||||
|
EventDeletion = 5,
|
||||||
|
Reaction = 7,
|
||||||
|
ChannelCreation = 40,
|
||||||
|
ChannelMetadata = 41,
|
||||||
|
ChannelMessage = 42,
|
||||||
|
ChannelHideMessage = 43,
|
||||||
|
ChannelMuteUser = 44,
|
||||||
|
Report = 1984,
|
||||||
|
ZapRequest = 9734,
|
||||||
|
Zap = 9735,
|
||||||
|
RelayList = 10002,
|
||||||
|
ClientAuth = 22242,
|
||||||
|
Article = 30023
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EventTemplate = {
|
||||||
|
kind: Kind
|
||||||
tags: string[][]
|
tags: string[][]
|
||||||
pubkey: string
|
|
||||||
content: string
|
content: string
|
||||||
created_at: number
|
created_at: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getBlankEvent(): Event {
|
export type UnsignedEvent = EventTemplate & {
|
||||||
|
pubkey: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Event = UnsignedEvent & {
|
||||||
|
id: string
|
||||||
|
sig: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getBlankEvent(): EventTemplate {
|
||||||
return {
|
return {
|
||||||
kind: 255,
|
kind: 255,
|
||||||
pubkey: '',
|
|
||||||
content: '',
|
content: '',
|
||||||
tags: [],
|
tags: [],
|
||||||
created_at: 0
|
created_at: 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function serializeEvent(evt: Event): string {
|
export function finishEvent(t: EventTemplate, privateKey: string): Event {
|
||||||
|
let event = t as Event
|
||||||
|
event.pubkey = getPublicKey(privateKey)
|
||||||
|
event.id = getEventHash(event)
|
||||||
|
event.sig = signEvent(event, privateKey)
|
||||||
|
return event
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeEvent(evt: UnsignedEvent): 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,
|
||||||
@@ -34,15 +73,18 @@ export function serializeEvent(evt: Event): string {
|
|||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getEventHash(event: Event): string {
|
export function getEventHash(event: UnsignedEvent): string {
|
||||||
let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))
|
let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))
|
||||||
return secp256k1.utils.bytesToHex(eventHash)
|
return secp256k1.utils.bytesToHex(eventHash)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function validateEvent(event: Event): boolean {
|
export function validateEvent(event: UnsignedEvent): boolean {
|
||||||
if (event.id !== getEventHash(event)) return false
|
if (typeof event !== 'object') return false
|
||||||
|
if (typeof event.kind !== 'number') 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 +98,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: UnsignedEvent, 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')
|
||||||
|
}
|
||||||
200
filter.test.js
200
filter.test.js
@@ -1,42 +1,176 @@
|
|||||||
/* eslint-env jest */
|
/* eslint-env jest */
|
||||||
|
|
||||||
const {matchFilters} = require('./lib/nostr.cjs')
|
const {matchFilter, matchFilters} = require('./lib/nostr.cjs.js')
|
||||||
|
|
||||||
test('test if filters match', () => {
|
describe('Filter', () => {
|
||||||
;[
|
describe('matchFilter', () => {
|
||||||
{
|
it('should return true when all filter conditions are met', () => {
|
||||||
filters: [{ids: ['i']}],
|
const filter = {
|
||||||
good: [{id: 'i'}],
|
ids: ['123', '456'],
|
||||||
bad: [{id: 'j'}]
|
kinds: [1, 2, 3],
|
||||||
},
|
authors: ['abc'],
|
||||||
{
|
since: 100,
|
||||||
filters: [{authors: ['abc']}, {kinds: [1, 3]}],
|
until: 200,
|
||||||
good: [
|
'#tag': ['value']
|
||||||
{pubkey: 'xyz', kind: 3},
|
|
||||||
{pubkey: 'abc', kind: 12},
|
|
||||||
{pubkey: 'abc', kind: 1}
|
|
||||||
],
|
|
||||||
bad: [{pubkey: 'hhh', kind: 12}]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
filters: [{'#e': ['yyy'], since: 444}],
|
|
||||||
good: [
|
|
||||||
{
|
|
||||||
tags: [
|
|
||||||
['e', 'uuu'],
|
|
||||||
['e', 'yyy']
|
|
||||||
],
|
|
||||||
created_at: 555
|
|
||||||
}
|
}
|
||||||
],
|
|
||||||
bad: [{tags: [['e', 'uuu']], created_at: 111}]
|
const event = {
|
||||||
|
id: '123',
|
||||||
|
kind: 1,
|
||||||
|
pubkey: 'abc',
|
||||||
|
created_at: 150,
|
||||||
|
tags: [['tag', 'value']]
|
||||||
}
|
}
|
||||||
].forEach(({filters, good, bad}) => {
|
|
||||||
good.forEach(ev => {
|
const result = matchFilter(filter, event)
|
||||||
expect(matchFilters(filters, ev)).toBeTruthy()
|
|
||||||
|
expect(result).toEqual(true)
|
||||||
})
|
})
|
||||||
bad.forEach(ev => {
|
|
||||||
expect(matchFilters(filters, ev)).toBeFalsy()
|
it('should return false when the event id is not in the filter', () => {
|
||||||
|
const filter = {ids: ['123', '456']}
|
||||||
|
|
||||||
|
const event = {id: '789'}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when the event kind is not in the filter', () => {
|
||||||
|
const filter = {kinds: [1, 2, 3]}
|
||||||
|
|
||||||
|
const event = {kind: 4}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when the event author is not in the filter', () => {
|
||||||
|
const filter = {authors: ['abc', 'def']}
|
||||||
|
|
||||||
|
const event = {pubkey: 'ghi'}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when a tag is not present in the event', () => {
|
||||||
|
const filter = {'#tag': ['value1', 'value2']}
|
||||||
|
|
||||||
|
const event = {tags: [['not_tag', 'value1']]}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when a tag value is not present in the event', () => {
|
||||||
|
const filter = {'#tag': ['value1', 'value2']}
|
||||||
|
|
||||||
|
const event = {tags: [['tag', 'value3']]}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return true when filter has tags that is present in the event', () => {
|
||||||
|
const filter = {'#tag1': ['foo']}
|
||||||
|
|
||||||
|
const event = {
|
||||||
|
id: '123',
|
||||||
|
kind: 1,
|
||||||
|
pubkey: 'abc',
|
||||||
|
created_at: 150,
|
||||||
|
tags: [
|
||||||
|
['tag1', 'foo'],
|
||||||
|
['tag2', 'bar']
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when the event is before the filter since value', () => {
|
||||||
|
const filter = {since: 100}
|
||||||
|
|
||||||
|
const event = {created_at: 50}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when the event is after the filter until value', () => {
|
||||||
|
const filter = {until: 100}
|
||||||
|
|
||||||
|
const event = {created_at: 150}
|
||||||
|
|
||||||
|
const result = matchFilter(filter, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('matchFilters', () => {
|
||||||
|
it('should return true when at least one filter matches the event', () => {
|
||||||
|
const filters = [
|
||||||
|
{ids: ['123'], kinds: [1], authors: ['abc']},
|
||||||
|
{ids: ['456'], kinds: [2], authors: ['def']},
|
||||||
|
{ids: ['789'], kinds: [3], authors: ['ghi']}
|
||||||
|
]
|
||||||
|
|
||||||
|
const event = {id: '789', kind: 3, pubkey: 'ghi'}
|
||||||
|
|
||||||
|
const result = matchFilters(filters, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return true when event matches one or more filters and some have limit set', () => {
|
||||||
|
const filters = [
|
||||||
|
{ids: ['123'], limit: 1},
|
||||||
|
{kinds: [1], limit: 2},
|
||||||
|
{authors: ['abc'], limit: 3}
|
||||||
|
]
|
||||||
|
|
||||||
|
const event = {id: '123', kind: 1, pubkey: 'abc', created_at: 150}
|
||||||
|
|
||||||
|
const result = matchFilters(filters, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when no filters match the event', () => {
|
||||||
|
const filters = [
|
||||||
|
{ids: ['123'], kinds: [1], authors: ['abc']},
|
||||||
|
{ids: ['456'], kinds: [2], authors: ['def']},
|
||||||
|
{ids: ['789'], kinds: [3], authors: ['ghi']}
|
||||||
|
]
|
||||||
|
|
||||||
|
const event = {id: '100', kind: 4, pubkey: 'jkl'}
|
||||||
|
|
||||||
|
const result = matchFilters(filters, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return false when event matches none of the filters and some have limit set', () => {
|
||||||
|
const filters = [
|
||||||
|
{ids: ['123'], limit: 1},
|
||||||
|
{kinds: [1], limit: 2},
|
||||||
|
{authors: ['abc'], limit: 3}
|
||||||
|
]
|
||||||
|
const event = {id: '456', kind: 2, pubkey: 'def', created_at: 200}
|
||||||
|
|
||||||
|
const result = matchFilters(filters, event)
|
||||||
|
|
||||||
|
expect(result).toEqual(false)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ export type Filter = {
|
|||||||
authors?: string[]
|
authors?: string[]
|
||||||
since?: number
|
since?: number
|
||||||
until?: number
|
until?: number
|
||||||
|
limit?: number
|
||||||
|
search?: string
|
||||||
[key: `#${string}`]: string[]
|
[key: `#${string}`]: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
17
index.ts
17
index.ts
@@ -2,8 +2,25 @@ 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 * from './references'
|
||||||
|
|
||||||
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 nip39 from './nip39'
|
||||||
|
export * as nip57 from './nip57'
|
||||||
|
|
||||||
|
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))
|
||||||
|
|||||||
23
justfile
Normal file
23
justfile
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
export PATH := "./node_modules/.bin:" + env_var('PATH')
|
||||||
|
|
||||||
|
install-dependencies:
|
||||||
|
yarn --ignore-engines
|
||||||
|
|
||||||
|
build:
|
||||||
|
rm -rf lib
|
||||||
|
node build.js
|
||||||
|
|
||||||
|
test: build
|
||||||
|
jest
|
||||||
|
|
||||||
|
test-only file: build
|
||||||
|
jest {{file}}
|
||||||
|
|
||||||
|
emit-types:
|
||||||
|
tsc # see tsconfig.json
|
||||||
|
|
||||||
|
publish: build emit-types
|
||||||
|
npm publish
|
||||||
|
|
||||||
|
format:
|
||||||
|
prettier --plugin-search-dir . --write .
|
||||||
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},
|
||||||
|
|||||||
16
nip05.ts
16
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,9 +36,17 @@ export async function queryProfile(
|
|||||||
name = '_'
|
name = '_'
|
||||||
}
|
}
|
||||||
|
|
||||||
let res = await (
|
if (!name.match(/^[A-Za-z0-9-_]+$/)) return null
|
||||||
|
if (!domain.includes('.')) return null
|
||||||
|
|
||||||
|
let res
|
||||||
|
try {
|
||||||
|
res = await (
|
||||||
await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`)
|
await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`)
|
||||||
).json()
|
).json()
|
||||||
|
} catch (err) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
if (!res?.names?.[name]) return null
|
if (!res?.names?.[name]) return null
|
||||||
|
|
||||||
|
|||||||
19
nip06.test.js
Normal file
19
nip06.test.js
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
/* 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'
|
||||||
|
)
|
||||||
|
})
|
||||||
11
nip06.ts
11
nip06.ts
@@ -7,17 +7,16 @@ 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(
|
||||||
let root = HDKey.fromMasterSeed(secp256k1.utils.hexToBytes(seed))
|
mnemonic: string,
|
||||||
|
passphrase?: string
|
||||||
|
): string {
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,3 +34,69 @@ test('encode and decode nprofile', () => {
|
|||||||
expect(data.relays).toContain(relays[0])
|
expect(data.relays).toContain(relays[0])
|
||||||
expect(data.relays).toContain(relays[1])
|
expect(data.relays).toContain(relays[1])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('decode nprofile without relays', () => {
|
||||||
|
expect(
|
||||||
|
nip19.decode(
|
||||||
|
nip19.nprofileEncode({
|
||||||
|
pubkey:
|
||||||
|
'97c70a44366a6535c145b333f973ea86dfdc2d7a99da618c40c64705ad98e322',
|
||||||
|
relays: []
|
||||||
|
})
|
||||||
|
).data
|
||||||
|
).toHaveProperty(
|
||||||
|
'pubkey',
|
||||||
|
'97c70a44366a6535c145b333f973ea86dfdc2d7a99da618c40c64705ad98e322'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('encode and decode naddr', () => {
|
||||||
|
let pk = getPublicKey(generatePrivateKey())
|
||||||
|
let relays = [
|
||||||
|
'wss://relay.nostr.example.mydomain.example.com',
|
||||||
|
'wss://nostr.banana.com'
|
||||||
|
]
|
||||||
|
let naddr = nip19.naddrEncode({
|
||||||
|
pubkey: pk,
|
||||||
|
relays,
|
||||||
|
kind: 30023,
|
||||||
|
identifier: 'banana'
|
||||||
|
})
|
||||||
|
expect(naddr).toMatch(/naddr1\w+/)
|
||||||
|
let {type, data} = nip19.decode(naddr)
|
||||||
|
expect(type).toEqual('naddr')
|
||||||
|
expect(data.pubkey).toEqual(pk)
|
||||||
|
expect(data.relays).toContain(relays[0])
|
||||||
|
expect(data.relays).toContain(relays[1])
|
||||||
|
expect(data.kind).toEqual(30023)
|
||||||
|
expect(data.identifier).toEqual('banana')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('decode naddr from habla.news', () => {
|
||||||
|
let {type, data} = nip19.decode(
|
||||||
|
'naddr1qq98yetxv4ex2mnrv4esygrl54h466tz4v0re4pyuavvxqptsejl0vxcmnhfl60z3rth2xkpjspsgqqqw4rsf34vl5'
|
||||||
|
)
|
||||||
|
expect(type).toEqual('naddr')
|
||||||
|
expect(data.pubkey).toEqual(
|
||||||
|
'7fa56f5d6962ab1e3cd424e758c3002b8665f7b0d8dcee9fe9e288d7751ac194'
|
||||||
|
)
|
||||||
|
expect(data.kind).toEqual(30023)
|
||||||
|
expect(data.identifier).toEqual('references')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('decode naddr from go-nostr with different TLV ordering', () => {
|
||||||
|
let {type, data} = nip19.decode(
|
||||||
|
'naddr1qqrxyctwv9hxzq3q80cvv07tjdrrgpa0j7j7tmnyl2yr6yr7l8j4s3evf6u64th6gkwsxpqqqp65wqfwwaehxw309aex2mrp0yhxummnw3ezuetcv9khqmr99ekhjer0d4skjm3wv4uxzmtsd3jjucm0d5q3vamnwvaz7tmwdaehgu3wvfskuctwvyhxxmmd0zfmwx'
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(type).toEqual('naddr')
|
||||||
|
expect(data.pubkey).toEqual(
|
||||||
|
'3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d'
|
||||||
|
)
|
||||||
|
expect(data.relays).toContain(
|
||||||
|
'wss://relay.nostr.example.mydomain.example.com'
|
||||||
|
)
|
||||||
|
expect(data.relays).toContain('wss://nostr.banana.com')
|
||||||
|
expect(data.kind).toEqual(30023)
|
||||||
|
expect(data.identifier).toEqual('banana')
|
||||||
|
})
|
||||||
|
|||||||
80
nip19.ts
80
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[]
|
||||||
@@ -11,16 +13,25 @@ export type ProfilePointer = {
|
|||||||
export type EventPointer = {
|
export type EventPointer = {
|
||||||
id: string // hex
|
id: string // hex
|
||||||
relays?: string[]
|
relays?: string[]
|
||||||
|
author?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AddressPointer = {
|
||||||
|
identifier: string
|
||||||
|
pubkey: string
|
||||||
|
kind: number
|
||||||
|
relays?: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export function decode(nip19: string): {
|
export function decode(nip19: string): {
|
||||||
type: string
|
type: string
|
||||||
data: ProfilePointer | EventPointer | string
|
data: ProfilePointer | EventPointer | AddressPointer | 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') {
|
switch (prefix) {
|
||||||
|
case 'nprofile': {
|
||||||
let tlv = parseTLV(data)
|
let tlv = parseTLV(data)
|
||||||
if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')
|
if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nprofile')
|
||||||
if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')
|
if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')
|
||||||
@@ -29,30 +40,56 @@ export function decode(nip19: string): {
|
|||||||
type: 'nprofile',
|
type: 'nprofile',
|
||||||
data: {
|
data: {
|
||||||
pubkey: secp256k1.utils.bytesToHex(tlv[0][0]),
|
pubkey: secp256k1.utils.bytesToHex(tlv[0][0]),
|
||||||
relays: tlv[1].map(d => utf8Decoder.decode(d))
|
relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
case 'nevent': {
|
||||||
if (prefix === 'nevent') {
|
|
||||||
let tlv = parseTLV(data)
|
let tlv = parseTLV(data)
|
||||||
if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')
|
if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nevent')
|
||||||
if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')
|
if (tlv[0][0].length !== 32) throw new Error('TLV 0 should be 32 bytes')
|
||||||
|
if (tlv[2] && tlv[2][0].length !== 32)
|
||||||
|
throw new Error('TLV 2 should be 32 bytes')
|
||||||
|
|
||||||
return {
|
return {
|
||||||
type: 'nevent',
|
type: 'nevent',
|
||||||
data: {
|
data: {
|
||||||
id: secp256k1.utils.bytesToHex(tlv[0][0]),
|
id: secp256k1.utils.bytesToHex(tlv[0][0]),
|
||||||
relays: tlv[1].map(d => utf8Decoder.decode(d))
|
relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],
|
||||||
|
author: tlv[2]?.[0]
|
||||||
|
? secp256k1.utils.bytesToHex(tlv[2][0])
|
||||||
|
: undefined
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (prefix === 'nsec' || prefix === 'npub' || prefix === 'note') {
|
case 'naddr': {
|
||||||
|
let tlv = parseTLV(data)
|
||||||
|
if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for naddr')
|
||||||
|
if (!tlv[2]?.[0]) throw new Error('missing TLV 2 for naddr')
|
||||||
|
if (tlv[2][0].length !== 32) throw new Error('TLV 2 should be 32 bytes')
|
||||||
|
if (!tlv[3]?.[0]) throw new Error('missing TLV 3 for naddr')
|
||||||
|
if (tlv[3][0].length !== 4) throw new Error('TLV 3 should be 4 bytes')
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'naddr',
|
||||||
|
data: {
|
||||||
|
identifier: utf8Decoder.decode(tlv[0][0]),
|
||||||
|
pubkey: secp256k1.utils.bytesToHex(tlv[2][0]),
|
||||||
|
kind: parseInt(secp256k1.utils.bytesToHex(tlv[3][0]), 16),
|
||||||
|
relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'nsec':
|
||||||
|
case 'npub':
|
||||||
|
case 'note':
|
||||||
return {type: prefix, data: secp256k1.utils.bytesToHex(data)}
|
return {type: prefix, data: secp256k1.utils.bytesToHex(data)}
|
||||||
}
|
|
||||||
|
|
||||||
|
default:
|
||||||
throw new Error(`unknown prefix ${prefix}`)
|
throw new Error(`unknown prefix ${prefix}`)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type TLV = {[t: number]: Uint8Array[]}
|
type TLV = {[t: number]: Uint8Array[]}
|
||||||
@@ -87,7 +124,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,16 +133,31 @@ 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 {
|
||||||
let data = encodeTLV({
|
let data = encodeTLV({
|
||||||
0: [secp256k1.utils.hexToBytes(event.id)],
|
0: [secp256k1.utils.hexToBytes(event.id)],
|
||||||
1: (event.relays || []).map(url => utf8Encoder.encode(url))
|
1: (event.relays || []).map(url => utf8Encoder.encode(url)),
|
||||||
|
2: event.author ? [secp256k1.utils.hexToBytes(event.author)] : []
|
||||||
})
|
})
|
||||||
let words = bech32.toWords(data)
|
let words = bech32.toWords(data)
|
||||||
return bech32.encode('nevent', words, 1000)
|
return bech32.encode('nevent', words, Bech32MaxSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function naddrEncode(addr: AddressPointer): string {
|
||||||
|
let kind = new ArrayBuffer(4)
|
||||||
|
new DataView(kind).setUint32(0, addr.kind, false)
|
||||||
|
|
||||||
|
let data = encodeTLV({
|
||||||
|
0: [utf8Encoder.encode(addr.identifier)],
|
||||||
|
1: (addr.relays || []).map(url => utf8Encoder.encode(url)),
|
||||||
|
2: [secp256k1.utils.hexToBytes(addr.pubkey)],
|
||||||
|
3: [new Uint8Array(kind)]
|
||||||
|
})
|
||||||
|
let words = bech32.toWords(data)
|
||||||
|
return bech32.encode('naddr', 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
|
||||||
|
}
|
||||||
15
nip39.test.js
Normal file
15
nip39.test.js
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
|
||||||
|
const fetch = require('node-fetch')
|
||||||
|
const {nip39} = require('./lib/nostr.cjs.js')
|
||||||
|
|
||||||
|
test('validate github claim', async () => {
|
||||||
|
nip39.useFetchImplementation(fetch)
|
||||||
|
|
||||||
|
let result = await nip39.validateGithub(
|
||||||
|
'npub1gcxzte5zlkncx26j68ez60fzkvtkm9e0vrwdcvsjakxf9mu9qewqlfnj5z',
|
||||||
|
'vitorpamplona',
|
||||||
|
'cf19e2d1d7f8dac6348ad37b35ec8421'
|
||||||
|
)
|
||||||
|
expect(result).toBe(true)
|
||||||
|
})
|
||||||
27
nip39.ts
Normal file
27
nip39.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
var _fetch: any
|
||||||
|
|
||||||
|
try {
|
||||||
|
_fetch = fetch
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
export function useFetchImplementation(fetchImplementation: any) {
|
||||||
|
_fetch = fetchImplementation
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function validateGithub(
|
||||||
|
pubkey: string,
|
||||||
|
username: string,
|
||||||
|
proof: string
|
||||||
|
): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
let res = await (
|
||||||
|
await _fetch(`https://gist.github.com/${username}/${proof}/raw`)
|
||||||
|
).text()
|
||||||
|
return (
|
||||||
|
res ===
|
||||||
|
`Verifying that I control the following Nostr public key: ${pubkey}`
|
||||||
|
)
|
||||||
|
} catch (_) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
138
nip57.ts
Normal file
138
nip57.ts
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
import {bech32} from '@scure/base'
|
||||||
|
|
||||||
|
import {Event, EventTemplate, validateEvent, verifySignature} from './event'
|
||||||
|
import {utf8Decoder} from './utils'
|
||||||
|
|
||||||
|
var _fetch: any
|
||||||
|
|
||||||
|
try {
|
||||||
|
_fetch = fetch
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
export function useFetchImplementation(fetchImplementation: any) {
|
||||||
|
_fetch = fetchImplementation
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getZapEndpoint(metadata: Event): Promise<null | string> {
|
||||||
|
try {
|
||||||
|
let lnurl: string = ''
|
||||||
|
let {lud06, lud16} = JSON.parse(metadata.content)
|
||||||
|
if (lud06) {
|
||||||
|
let {words} = bech32.decode(lud06, 1000)
|
||||||
|
let data = bech32.fromWords(words)
|
||||||
|
lnurl = utf8Decoder.decode(data)
|
||||||
|
} else if (lud16) {
|
||||||
|
let [name, domain] = lud16.split('@')
|
||||||
|
lnurl = `https://${domain}/.well-known/lnurlp/${name}`
|
||||||
|
} else {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
let res = await _fetch(lnurl)
|
||||||
|
let body = await res.json()
|
||||||
|
|
||||||
|
if (body.allowsNostr && body.nostrPubkey) {
|
||||||
|
return body.callback
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
/*-*/
|
||||||
|
}
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makeZapRequest({
|
||||||
|
profile,
|
||||||
|
event,
|
||||||
|
amount,
|
||||||
|
relays,
|
||||||
|
comment = ''
|
||||||
|
}: {
|
||||||
|
profile: string
|
||||||
|
event: string | null
|
||||||
|
amount: number
|
||||||
|
comment: string
|
||||||
|
relays: string[]
|
||||||
|
}): EventTemplate {
|
||||||
|
if (!amount) throw new Error('amount not given')
|
||||||
|
if (!profile) throw new Error('profile not given')
|
||||||
|
|
||||||
|
let zr = {
|
||||||
|
kind: 9734,
|
||||||
|
created_at: Math.round(Date.now() / 1000),
|
||||||
|
content: comment,
|
||||||
|
tags: [
|
||||||
|
['p', profile],
|
||||||
|
['amount', amount.toString()],
|
||||||
|
['relays', ...relays]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event) {
|
||||||
|
zr.tags.push(['e', event])
|
||||||
|
}
|
||||||
|
|
||||||
|
return zr
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateZapRequest(zapRequestString: string): string | null {
|
||||||
|
let zapRequest: Event
|
||||||
|
|
||||||
|
try {
|
||||||
|
zapRequest = JSON.parse(zapRequestString)
|
||||||
|
} catch (err) {
|
||||||
|
return 'Invalid zap request JSON.'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!validateEvent(zapRequest))
|
||||||
|
return 'Zap request is not a valid Nostr event.'
|
||||||
|
if (!verifySignature(zapRequest)) return 'Invalid signature on zap request.'
|
||||||
|
|
||||||
|
let p = zapRequest.tags.find(([t, v]) => t === 'p' && v)
|
||||||
|
if (!p) return "Zap request doesn't have a 'p' tag."
|
||||||
|
if (!p[1].match(/^[a-f0-9]{64}$/))
|
||||||
|
return "Zap request 'p' tag is not valid hex."
|
||||||
|
|
||||||
|
let e = zapRequest.tags.find(([t, v]) => t === 'e' && v)
|
||||||
|
if (e && !e[1].match(/^[a-f0-9]{64}$/))
|
||||||
|
return "Zap request 'e' tag is not valid hex."
|
||||||
|
|
||||||
|
let relays = zapRequest.tags.find(([t, v]) => t === 'relays' && v)
|
||||||
|
if (!relays) return "Zap request doesn't have a 'relays' tag."
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makeZapReceipt({
|
||||||
|
zapRequest,
|
||||||
|
preimage,
|
||||||
|
bolt11,
|
||||||
|
paidAt
|
||||||
|
}: {
|
||||||
|
zapRequest: string
|
||||||
|
preimage: string | null
|
||||||
|
bolt11: string
|
||||||
|
paidAt: Date
|
||||||
|
}): EventTemplate {
|
||||||
|
let zr: Event = JSON.parse(zapRequest)
|
||||||
|
let tagsFromZapRequest = zr.tags.filter(
|
||||||
|
([t]) => t === 'e' || t === 'p' || t === 'a'
|
||||||
|
)
|
||||||
|
|
||||||
|
let zap = {
|
||||||
|
kind: 9735,
|
||||||
|
created_at: Math.round(paidAt.getTime() / 1000),
|
||||||
|
content: '',
|
||||||
|
tags: [
|
||||||
|
...tagsFromZapRequest,
|
||||||
|
['bolt11', bolt11],
|
||||||
|
['description', zapRequest]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preimage) {
|
||||||
|
zap.tags.push(['preimage', preimage])
|
||||||
|
}
|
||||||
|
|
||||||
|
return zap
|
||||||
|
}
|
||||||
50
package.json
50
package.json
@@ -1,20 +1,29 @@
|
|||||||
{
|
{
|
||||||
"name": "nostr-tools",
|
"name": "nostr-tools",
|
||||||
"version": "1.0.0-rc1",
|
"version": "1.8.0",
|
||||||
"description": "Tools for making a Nostr client.",
|
"description": "Tools for making a Nostr client.",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/fiatjaf/nostr-tools.git"
|
"url": "https://github.com/nbd-wtf/nostr-tools.git"
|
||||||
},
|
},
|
||||||
|
"files": [
|
||||||
|
"./lib/**/*"
|
||||||
|
],
|
||||||
|
"types": "./lib/index.d.ts",
|
||||||
"main": "lib/nostr.cjs.js",
|
"main": "lib/nostr.cjs.js",
|
||||||
"module": "lib/nostr.esm.js",
|
"module": "lib/esm/nostr.mjs",
|
||||||
|
"exports": {
|
||||||
|
"import": "./lib/esm/nostr.mjs",
|
||||||
|
"require": "./lib/nostr.cjs.js"
|
||||||
|
},
|
||||||
|
"license": "Public domain",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/hashes": "^0.5.7",
|
"@noble/hashes": "1.0.0",
|
||||||
"@noble/secp256k1": "^1.7.0",
|
"@noble/secp256k1": "^1.7.1",
|
||||||
"@scure/bip32": "^1.1.1",
|
"@scure/base": "^1.1.1",
|
||||||
"@scure/bip39": "^1.1.0",
|
"@scure/bip32": "^1.1.5",
|
||||||
"base64-arraybuffer": "^1.0.2",
|
"@scure/bip39": "^1.1.1",
|
||||||
"bech32": "^2.0.0"
|
"prettier": "^2.8.4"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"decentralization",
|
"decentralization",
|
||||||
@@ -24,25 +33,20 @@
|
|||||||
"nostr"
|
"nostr"
|
||||||
],
|
],
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^18.0.3",
|
"@types/node": "^18.13.0",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.46.1",
|
"@typescript-eslint/eslint-plugin": "^5.51.0",
|
||||||
"@typescript-eslint/parser": "^5.46.1",
|
"@typescript-eslint/parser": "^5.51.0",
|
||||||
"esbuild": "0.16.9",
|
"esbuild": "0.16.9",
|
||||||
"esbuild-plugin-alias": "^0.2.1",
|
"esbuild-plugin-alias": "^0.2.1",
|
||||||
"eslint": "^8.30.0",
|
"eslint": "^8.33.0",
|
||||||
"eslint-plugin-babel": "^5.3.1",
|
"eslint-plugin-babel": "^5.3.1",
|
||||||
"esm-loader-typescript": "^1.0.1",
|
"esm-loader-typescript": "^1.0.3",
|
||||||
"events": "^3.3.0",
|
"events": "^3.3.0",
|
||||||
"jest": "^29.3.1",
|
"jest": "^29.4.2",
|
||||||
"node-fetch": "2",
|
"node-fetch": "^2.6.9",
|
||||||
"ts-jest": "^29.0.3",
|
"ts-jest": "^29.0.5",
|
||||||
"tsd": "^0.22.0",
|
"tsd": "^0.22.0",
|
||||||
"typescript": "^4.9.4",
|
"typescript": "^4.9.5",
|
||||||
"websocket-polyfill": "^0.0.3"
|
"websocket-polyfill": "^0.0.3"
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"build": "node build.js",
|
|
||||||
"pretest": "node build.js",
|
|
||||||
"test": "jest"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
133
pool.test.js
Normal file
133
pool.test.js
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
|
||||||
|
require('websocket-polyfill')
|
||||||
|
const {
|
||||||
|
SimplePool,
|
||||||
|
generatePrivateKey,
|
||||||
|
getPublicKey,
|
||||||
|
getEventHash,
|
||||||
|
signEvent
|
||||||
|
} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
|
let pool = new SimplePool()
|
||||||
|
|
||||||
|
let relays = [
|
||||||
|
'wss://relay.damus.io/',
|
||||||
|
'wss://relay.nostr.bg/',
|
||||||
|
'wss://nostr.fmt.wiz.biz/',
|
||||||
|
'wss://relay.nostr.band/',
|
||||||
|
'wss://nos.lol/'
|
||||||
|
]
|
||||||
|
|
||||||
|
afterAll(() => {
|
||||||
|
pool.close([
|
||||||
|
...relays,
|
||||||
|
'wss://nostr.wine',
|
||||||
|
'wss://offchain.pub',
|
||||||
|
'wss://eden.nostr.land'
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('removing duplicates when querying', async () => {
|
||||||
|
let priv = generatePrivateKey()
|
||||||
|
let pub = getPublicKey(priv)
|
||||||
|
|
||||||
|
let sub = pool.sub(relays, [{authors: [pub]}])
|
||||||
|
let received = []
|
||||||
|
|
||||||
|
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('same with double querying', async () => {
|
||||||
|
let priv = generatePrivateKey()
|
||||||
|
let pub = getPublicKey(priv)
|
||||||
|
|
||||||
|
let sub1 = pool.sub(relays, [{authors: [pub]}])
|
||||||
|
let sub2 = pool.sub(relays, [{authors: [pub]}])
|
||||||
|
|
||||||
|
let received = []
|
||||||
|
|
||||||
|
sub1.on('event', event => {
|
||||||
|
received.push(event)
|
||||||
|
})
|
||||||
|
|
||||||
|
sub2.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)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('get()', async () => {
|
||||||
|
let event = await pool.get(relays, {
|
||||||
|
ids: ['d7dd5eb3ab747e16f8d0212d53032ea2a7cadef53837e5a6c66d42849fcb9027']
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(event).toHaveProperty(
|
||||||
|
'id',
|
||||||
|
'd7dd5eb3ab747e16f8d0212d53032ea2a7cadef53837e5a6c66d42849fcb9027'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('list()', async () => {
|
||||||
|
let events = await pool.list(
|
||||||
|
[...relays, 'wss://offchain.pub', 'wss://eden.nostr.land'],
|
||||||
|
[
|
||||||
|
{
|
||||||
|
authors: [
|
||||||
|
'3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d'
|
||||||
|
],
|
||||||
|
kinds: [1],
|
||||||
|
limit: 2
|
||||||
|
}
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
// the actual received number will be greater than 2, but there will be no duplicates
|
||||||
|
expect(events.length).toEqual(
|
||||||
|
events
|
||||||
|
.map(evt => evt.id)
|
||||||
|
.reduce((acc, n) => (acc.indexOf(n) !== -1 ? acc : [...acc, n]), [])
|
||||||
|
.length
|
||||||
|
)
|
||||||
|
|
||||||
|
let relaysForAllEvents = events
|
||||||
|
.map(event => pool.seenOn(event.id))
|
||||||
|
.reduce((acc, n) => acc.concat(n), [])
|
||||||
|
expect(relaysForAllEvents.length).toBeGreaterThanOrEqual(events.length)
|
||||||
|
})
|
||||||
191
pool.ts
Normal file
191
pool.ts
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
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}
|
||||||
|
private _seenOn: {[id: string]: Set<string>} = {} // a map of all events we've seen in each relay
|
||||||
|
|
||||||
|
private eoseSubTimeout: number
|
||||||
|
private getTimeout: number
|
||||||
|
|
||||||
|
constructor(options: {eoseSubTimeout?: number; getTimeout?: number} = {}) {
|
||||||
|
this._conn = {}
|
||||||
|
this.eoseSubTimeout = options.eoseSubTimeout || 3400
|
||||||
|
this.getTimeout = options.getTimeout || 3400
|
||||||
|
}
|
||||||
|
|
||||||
|
close(relays: string[]): void {
|
||||||
|
relays.forEach(url => {
|
||||||
|
let relay = this._conn[normalizeURL(url)]
|
||||||
|
if (relay) relay.close()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async ensureRelay(url: string): Promise<Relay> {
|
||||||
|
const nm = normalizeURL(url)
|
||||||
|
const existing = this._conn[nm]
|
||||||
|
if (existing && existing.status === 1) return existing
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
await existing.connect()
|
||||||
|
return existing
|
||||||
|
}
|
||||||
|
|
||||||
|
const relay = relayInit(nm, {
|
||||||
|
getTimeout: this.getTimeout * 0.9,
|
||||||
|
listTimeout: this.getTimeout * 0.9
|
||||||
|
})
|
||||||
|
this._conn[nm] = relay
|
||||||
|
|
||||||
|
await relay.connect()
|
||||||
|
|
||||||
|
return relay
|
||||||
|
}
|
||||||
|
|
||||||
|
sub(relays: string[], filters: Filter[], opts?: SubscriptionOptions): Sub {
|
||||||
|
let _knownIds: Set<string> = new Set()
|
||||||
|
let modifiedOpts = {...(opts || {})}
|
||||||
|
modifiedOpts.alreadyHaveEvent = (id, url) => {
|
||||||
|
if (opts?.alreadyHaveEvent?.(id, url)) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
let set = this._seenOn[id] || new Set()
|
||||||
|
set.add(url)
|
||||||
|
this._seenOn[id] = set
|
||||||
|
_knownIds.add(id)
|
||||||
|
return _knownIds.has(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
let subs: Sub[] = []
|
||||||
|
let eventListeners: Set<(event: Event) => void> = new Set()
|
||||||
|
let eoseListeners: Set<() => void> = new Set()
|
||||||
|
let eosesMissing = relays.length
|
||||||
|
|
||||||
|
let eoseSent = false
|
||||||
|
let eoseTimeout = setTimeout(() => {
|
||||||
|
eoseSent = true
|
||||||
|
for (let cb of eoseListeners.values()) cb()
|
||||||
|
}, this.eoseSubTimeout)
|
||||||
|
|
||||||
|
relays.forEach(async relay => {
|
||||||
|
let r
|
||||||
|
try {
|
||||||
|
r = await this.ensureRelay(relay)
|
||||||
|
} catch (err) {
|
||||||
|
handleEose()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!r) return
|
||||||
|
let s = r.sub(filters, modifiedOpts)
|
||||||
|
s.on('event', (event: Event) => {
|
||||||
|
for (let cb of eventListeners.values()) cb(event)
|
||||||
|
})
|
||||||
|
s.on('eose', () => {
|
||||||
|
if (eoseSent) return
|
||||||
|
handleEose()
|
||||||
|
})
|
||||||
|
subs.push(s)
|
||||||
|
|
||||||
|
function handleEose() {
|
||||||
|
eosesMissing--
|
||||||
|
if (eosesMissing === 0) {
|
||||||
|
clearTimeout(eoseTimeout)
|
||||||
|
for (let cb of eoseListeners.values()) cb()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
let greaterSub: Sub = {
|
||||||
|
sub(filters, opts) {
|
||||||
|
subs.forEach(sub => sub.sub(filters, opts))
|
||||||
|
return greaterSub
|
||||||
|
},
|
||||||
|
unsub() {
|
||||||
|
subs.forEach(sub => sub.unsub())
|
||||||
|
},
|
||||||
|
on(type, cb) {
|
||||||
|
if (type === 'event') {
|
||||||
|
eventListeners.add(cb)
|
||||||
|
} else if (type === 'eose') {
|
||||||
|
eoseListeners.add(cb as () => void | Promise<void>)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
off(type, cb) {
|
||||||
|
if (type === 'event') {
|
||||||
|
eventListeners.delete(cb)
|
||||||
|
} else if (type === 'eose')
|
||||||
|
eoseListeners.delete(cb as () => void | Promise<void>)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return greaterSub
|
||||||
|
}
|
||||||
|
|
||||||
|
get(
|
||||||
|
relays: string[],
|
||||||
|
filter: Filter,
|
||||||
|
opts?: SubscriptionOptions
|
||||||
|
): Promise<Event | null> {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
let sub = this.sub(relays, [filter], opts)
|
||||||
|
let timeout = setTimeout(() => {
|
||||||
|
sub.unsub()
|
||||||
|
resolve(null)
|
||||||
|
}, this.getTimeout)
|
||||||
|
sub.on('event', (event: Event) => {
|
||||||
|
resolve(event)
|
||||||
|
clearTimeout(timeout)
|
||||||
|
sub.unsub()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
list(
|
||||||
|
relays: string[],
|
||||||
|
filters: Filter[],
|
||||||
|
opts?: SubscriptionOptions
|
||||||
|
): Promise<Event[]> {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
let events: Event[] = []
|
||||||
|
let sub = this.sub(relays, filters, opts)
|
||||||
|
|
||||||
|
sub.on('event', (event: Event) => {
|
||||||
|
events.push(event)
|
||||||
|
})
|
||||||
|
|
||||||
|
// we can rely on an eose being emitted here because pool.sub() will fake one
|
||||||
|
sub.on('eose', () => {
|
||||||
|
sub.unsub()
|
||||||
|
resolve(events)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
publish(relays: string[], event: Event): Pub {
|
||||||
|
const pubs: Pub[] = []
|
||||||
|
relays.forEach(async relay => {
|
||||||
|
let r
|
||||||
|
try {
|
||||||
|
r = await this.ensureRelay(relay)
|
||||||
|
pubs.push(r.publish(event))
|
||||||
|
} catch (_) {}
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
on(type, cb) {
|
||||||
|
pubs.forEach((pub, i) => {
|
||||||
|
pub.on(type, () => cb(relays[i]))
|
||||||
|
})
|
||||||
|
},
|
||||||
|
off() {
|
||||||
|
// do nothing here, FIXME
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
seenOn(id: string): string[] {
|
||||||
|
return Array.from(this._seenOn[id]?.values?.() || [])
|
||||||
|
}
|
||||||
|
}
|
||||||
62
references.test.js
Normal file
62
references.test.js
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
/* eslint-env jest */
|
||||||
|
|
||||||
|
const {parseReferences} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
|
test('parse mentions', () => {
|
||||||
|
let evt = {
|
||||||
|
tags: [
|
||||||
|
[
|
||||||
|
'p',
|
||||||
|
'c9d556c6d3978d112d30616d0d20aaa81410e3653911dd67787b5aaf9b36ade8',
|
||||||
|
'wss://nostr.com'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'a84c5de86efc2ec2cff7bad077c4171e09146b633b7ad117fffe088d9579ac33',
|
||||||
|
'wss://other.com',
|
||||||
|
'reply'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'e',
|
||||||
|
'31d7c2875b5fc8e6f9c8f9dc1f84de1b6b91d1947ea4c59225e55c325d330fa8',
|
||||||
|
''
|
||||||
|
]
|
||||||
|
],
|
||||||
|
content:
|
||||||
|
'hello #[0], have you seen #[2]? it was made by nostr:nprofile1qqsvc6ulagpn7kwrcwdqgp797xl7usumqa6s3kgcelwq6m75x8fe8yc5usxdg on nostr:nevent1qqsvc6ulagpn7kwrcwdqgp797xl7usumqa6s3kgcelwq6m75x8fe8ychxp5v4! broken #[3]'
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(parseReferences(evt)).toEqual([
|
||||||
|
{
|
||||||
|
text: '#[0]',
|
||||||
|
profile: {
|
||||||
|
pubkey:
|
||||||
|
'c9d556c6d3978d112d30616d0d20aaa81410e3653911dd67787b5aaf9b36ade8',
|
||||||
|
relays: ['wss://nostr.com']
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: '#[2]',
|
||||||
|
event: {
|
||||||
|
id: '31d7c2875b5fc8e6f9c8f9dc1f84de1b6b91d1947ea4c59225e55c325d330fa8',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: 'nostr:nprofile1qqsvc6ulagpn7kwrcwdqgp797xl7usumqa6s3kgcelwq6m75x8fe8yc5usxdg',
|
||||||
|
profile: {
|
||||||
|
pubkey:
|
||||||
|
'cc6b9fea033f59c3c39a0407c5f1bfee439b077508d918cfdc0d6fd431d39393',
|
||||||
|
relays: []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
text: 'nostr:nevent1qqsvc6ulagpn7kwrcwdqgp797xl7usumqa6s3kgcelwq6m75x8fe8ychxp5v4',
|
||||||
|
event: {
|
||||||
|
id: 'cc6b9fea033f59c3c39a0407c5f1bfee439b077508d918cfdc0d6fd431d39393',
|
||||||
|
relays: [],
|
||||||
|
author: undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
])
|
||||||
|
})
|
||||||
104
references.ts
Normal file
104
references.ts
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
import {Event} from './event'
|
||||||
|
import {decode, AddressPointer, ProfilePointer, EventPointer} from './nip19'
|
||||||
|
|
||||||
|
type Reference = {
|
||||||
|
text: string
|
||||||
|
profile?: ProfilePointer
|
||||||
|
event?: EventPointer
|
||||||
|
address?: AddressPointer
|
||||||
|
}
|
||||||
|
|
||||||
|
const mentionRegex =
|
||||||
|
/\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]/g
|
||||||
|
|
||||||
|
export function parseReferences(evt: Event): Reference[] {
|
||||||
|
let references: Reference[] = []
|
||||||
|
for (let ref of evt.content.matchAll(mentionRegex)) {
|
||||||
|
if (ref[2]) {
|
||||||
|
// it's a NIP-27 mention
|
||||||
|
try {
|
||||||
|
let {type, data} = decode(ref[1])
|
||||||
|
switch (type) {
|
||||||
|
case 'npub': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
profile: {pubkey: data as string, relays: []}
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'nprofile': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
profile: data as ProfilePointer
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'note': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
event: {id: data as string, relays: []}
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'nevent': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
event: data as EventPointer
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'naddr': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
address: data as AddressPointer
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
/***/
|
||||||
|
}
|
||||||
|
} else if (ref[3]) {
|
||||||
|
// it's a NIP-10 mention
|
||||||
|
let idx = parseInt(ref[3], 10)
|
||||||
|
let tag = evt.tags[idx]
|
||||||
|
if (!tag) continue
|
||||||
|
|
||||||
|
switch (tag[0]) {
|
||||||
|
case 'p': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
profile: {pubkey: tag[1], relays: tag[2] ? [tag[2]] : []}
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'e': {
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
event: {id: tag[1], relays: tag[2] ? [tag[2]] : []}
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case 'a': {
|
||||||
|
try {
|
||||||
|
let [kind, pubkey, identifier] = ref[1].split(':')
|
||||||
|
references.push({
|
||||||
|
text: ref[0],
|
||||||
|
address: {
|
||||||
|
identifier,
|
||||||
|
pubkey,
|
||||||
|
kind: parseInt(kind, 10),
|
||||||
|
relays: tag[2] ? [tag[2]] : []
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
/***/
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return references
|
||||||
|
}
|
||||||
@@ -9,14 +9,14 @@ const {
|
|||||||
signEvent
|
signEvent
|
||||||
} = require('./lib/nostr.cjs')
|
} = require('./lib/nostr.cjs')
|
||||||
|
|
||||||
let relay = relayInit('wss://nostr-pub.semisol.dev/')
|
let relay = relayInit('wss://relay.damus.io/')
|
||||||
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
relay.connect()
|
relay.connect()
|
||||||
})
|
})
|
||||||
|
|
||||||
afterAll(async () => {
|
afterAll(() => {
|
||||||
await relay.close()
|
relay.close()
|
||||||
})
|
})
|
||||||
|
|
||||||
test('connectivity', () => {
|
test('connectivity', () => {
|
||||||
@@ -32,7 +32,7 @@ test('connectivity', () => {
|
|||||||
).resolves.toBe(true)
|
).resolves.toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('querying', () => {
|
test('querying', async () => {
|
||||||
var resolve1
|
var resolve1
|
||||||
var resolve2
|
var resolve2
|
||||||
|
|
||||||
@@ -52,8 +52,7 @@ test('querying', () => {
|
|||||||
resolve2(true)
|
resolve2(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
return expect(
|
let [t1, t2] = await Promise.all([
|
||||||
Promise.all([
|
|
||||||
new Promise(resolve => {
|
new Promise(resolve => {
|
||||||
resolve1 = resolve
|
resolve1 = resolve
|
||||||
}),
|
}),
|
||||||
@@ -61,7 +60,34 @@ test('querying', () => {
|
|||||||
resolve2 = resolve
|
resolve2 = resolve
|
||||||
})
|
})
|
||||||
])
|
])
|
||||||
).resolves.toEqual([true, true])
|
|
||||||
|
expect(t1).toEqual(true)
|
||||||
|
expect(t2).toEqual(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('get()', async () => {
|
||||||
|
let event = await relay.get({
|
||||||
|
ids: ['d7dd5eb3ab747e16f8d0212d53032ea2a7cadef53837e5a6c66d42849fcb9027']
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(event).toHaveProperty(
|
||||||
|
'id',
|
||||||
|
'd7dd5eb3ab747e16f8d0212d53032ea2a7cadef53837e5a6c66d42849fcb9027'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('list()', async () => {
|
||||||
|
let events = await relay.list([
|
||||||
|
{
|
||||||
|
authors: [
|
||||||
|
'3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d'
|
||||||
|
],
|
||||||
|
kinds: [1],
|
||||||
|
limit: 2
|
||||||
|
}
|
||||||
|
])
|
||||||
|
|
||||||
|
expect(events.length).toEqual(2)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('listening (twice) and publishing', async () => {
|
test('listening (twice) and publishing', async () => {
|
||||||
@@ -98,7 +124,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(
|
||||||
|
|||||||
278
relay.ts
278
relay.ts
@@ -2,54 +2,78 @@
|
|||||||
|
|
||||||
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: () => void | Promise<void>
|
||||||
|
disconnect: () => void | Promise<void>
|
||||||
|
error: () => void | Promise<void>
|
||||||
|
notice: (msg: string) => void | Promise<void>
|
||||||
|
}
|
||||||
|
type SubEvent = {
|
||||||
|
event: (event: Event) => void | Promise<void>
|
||||||
|
eose: () => void | Promise<void>
|
||||||
|
}
|
||||||
export type Relay = {
|
export type Relay = {
|
||||||
url: string
|
url: string
|
||||||
status: number
|
status: number
|
||||||
connect: () => void
|
connect: () => Promise<void>
|
||||||
close: () => void
|
close: () => 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
|
off: <T extends keyof RelayEvent, U extends RelayEvent[T]>(
|
||||||
off: (type: 'connect' | 'disconnect' | 'notice', cb: any) => void
|
event: T,
|
||||||
|
listener: U
|
||||||
|
) => void
|
||||||
|
on: <T extends keyof RelayEvent, U extends RelayEvent[T]>(
|
||||||
|
event: T,
|
||||||
|
listener: U
|
||||||
|
) => void
|
||||||
}
|
}
|
||||||
export type Pub = {
|
export type Pub = {
|
||||||
on: (type: 'ok' | 'seen' | 'failed', cb: any) => void
|
on: (type: 'ok' | 'failed', cb: any) => void
|
||||||
off: (type: 'ok' | 'seen' | 'failed', cb: any) => void
|
off: (type: 'ok' | 'failed', cb: any) => void
|
||||||
}
|
}
|
||||||
export type Sub = {
|
export type Sub = {
|
||||||
sub: (filters: Filter[], opts: SubscriptionOptions) => Sub
|
sub: (filters: Filter[], opts: SubscriptionOptions) => Sub
|
||||||
unsub: () => void
|
unsub: () => void
|
||||||
on: (type: 'event' | 'eose', cb: any) => void
|
on: <T extends keyof SubEvent, U extends SubEvent[T]>(
|
||||||
off: (type: 'event' | 'eose', cb: any) => void
|
event: T,
|
||||||
|
listener: U
|
||||||
|
) => void
|
||||||
|
off: <T extends keyof SubEvent, U extends SubEvent[T]>(
|
||||||
|
event: T,
|
||||||
|
listener: U
|
||||||
|
) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
type SubscriptionOptions = {
|
export type SubscriptionOptions = {
|
||||||
skipVerification?: boolean
|
|
||||||
id?: string
|
id?: string
|
||||||
|
skipVerification?: boolean
|
||||||
|
alreadyHaveEvent?: null | ((id: string, relay: string) => boolean)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function relayInit(url: string): Relay {
|
export function relayInit(
|
||||||
|
url: string,
|
||||||
|
options: {
|
||||||
|
getTimeout?: number
|
||||||
|
listTimeout?: number
|
||||||
|
} = {}
|
||||||
|
): Relay {
|
||||||
|
let {listTimeout = 3000, getTimeout = 3000} = options
|
||||||
|
|
||||||
var ws: WebSocket
|
var ws: WebSocket
|
||||||
var resolveClose: () => void
|
|
||||||
var untilOpen: Promise<void>
|
|
||||||
var openSubs: {[id: string]: {filters: Filter[]} & SubscriptionOptions} = {}
|
var openSubs: {[id: string]: {filters: Filter[]} & SubscriptionOptions} = {}
|
||||||
var listeners: {
|
var listeners: {[TK in keyof RelayEvent]: RelayEvent[TK][]} = {
|
||||||
connect: Array<() => void>
|
|
||||||
disconnect: Array<() => void>
|
|
||||||
error: Array<() => void>
|
|
||||||
notice: Array<(msg: string) => void>
|
|
||||||
} = {
|
|
||||||
connect: [],
|
connect: [],
|
||||||
disconnect: [],
|
disconnect: [],
|
||||||
error: [],
|
error: [],
|
||||||
notice: []
|
notice: []
|
||||||
}
|
}
|
||||||
var subListeners: {
|
var subListeners: {
|
||||||
[subid: string]: {
|
[subid: string]: {[TK in keyof SubEvent]: SubEvent[TK][]}
|
||||||
event: Array<(event: Event) => void>
|
|
||||||
eose: Array<() => void>
|
|
||||||
}
|
|
||||||
} = {}
|
} = {}
|
||||||
var pubListeners: {
|
var pubListeners: {
|
||||||
[eventid: string]: {
|
[eventid: string]: {
|
||||||
@@ -61,7 +85,11 @@ export function relayInit(url: string): Relay {
|
|||||||
|
|
||||||
async function connectRelay(): Promise<void> {
|
async function connectRelay(): Promise<void> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
|
try {
|
||||||
ws = new WebSocket(url)
|
ws = new WebSocket(url)
|
||||||
|
} catch (err) {
|
||||||
|
reject(err)
|
||||||
|
}
|
||||||
|
|
||||||
ws.onopen = () => {
|
ws.onopen = () => {
|
||||||
listeners.connect.forEach(cb => cb())
|
listeners.connect.forEach(cb => cb())
|
||||||
@@ -73,22 +101,48 @@ export function relayInit(url: string): Relay {
|
|||||||
}
|
}
|
||||||
ws.onclose = async () => {
|
ws.onclose = async () => {
|
||||||
listeners.disconnect.forEach(cb => cb())
|
listeners.disconnect.forEach(cb => cb())
|
||||||
resolveClose()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ws.onmessage = async e => {
|
let incomingMessageQueue: string[] = []
|
||||||
var data
|
let handleNextInterval: any
|
||||||
|
|
||||||
|
ws.onmessage = e => {
|
||||||
|
incomingMessageQueue.push(e.data)
|
||||||
|
if (!handleNextInterval) {
|
||||||
|
handleNextInterval = setInterval(handleNext, 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleNext() {
|
||||||
|
if (incomingMessageQueue.length === 0) {
|
||||||
|
clearInterval(handleNextInterval)
|
||||||
|
handleNextInterval = null
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var json = incomingMessageQueue.shift()
|
||||||
|
if (!json) return
|
||||||
|
|
||||||
|
let subid = getSubscriptionId(json)
|
||||||
|
if (subid) {
|
||||||
|
let so = openSubs[subid]
|
||||||
|
if (
|
||||||
|
so &&
|
||||||
|
so.alreadyHaveEvent &&
|
||||||
|
so.alreadyHaveEvent(getHex64(json, 'id'), url)
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
data = JSON.parse(e.data)
|
let data = JSON.parse(json)
|
||||||
} catch (err) {
|
|
||||||
data = e.data
|
// 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
|
||||||
|
|
||||||
if (data.length >= 1) {
|
|
||||||
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,51 +152,70 @@ 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())
|
if (id in subListeners) {
|
||||||
|
subListeners[id].eose.forEach(cb => cb())
|
||||||
|
subListeners[id].eose = [] // 'eose' only happens once per sub, so stop listeners here
|
||||||
|
}
|
||||||
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] || ''
|
||||||
if (ok) pubListeners[id]?.ok.forEach(cb => cb())
|
if (id in pubListeners) {
|
||||||
else pubListeners[id]?.failed.forEach(cb => cb(reason))
|
if (ok) pubListeners[id].ok.forEach(cb => cb())
|
||||||
|
else pubListeners[id].failed.forEach(cb => cb(reason))
|
||||||
|
pubListeners[id].ok = [] // 'ok' only happens once per pub, so stop listeners here
|
||||||
|
pubListeners[id].failed = []
|
||||||
|
}
|
||||||
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function connected() {
|
||||||
|
return ws?.readyState === 1
|
||||||
|
}
|
||||||
|
|
||||||
async function connect(): Promise<void> {
|
async function connect(): Promise<void> {
|
||||||
if (ws?.readyState && ws.readyState === 1) return // ws already open
|
if (connected()) return // ws already open
|
||||||
await connectRelay()
|
await connectRelay()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function trySend(params: [string, ...any]) {
|
async function trySend(params: [string, ...any]) {
|
||||||
let msg = JSON.stringify(params)
|
let msg = JSON.stringify(params)
|
||||||
|
if (!connected()) {
|
||||||
await untilOpen
|
await new Promise(resolve => setTimeout(resolve, 1000))
|
||||||
|
if (!connected()) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
ws.send(msg)
|
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 +224,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 +233,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: () => {
|
||||||
@@ -166,16 +241,23 @@ export function relayInit(url: string): Relay {
|
|||||||
delete subListeners[subid]
|
delete subListeners[subid]
|
||||||
trySend(['CLOSE', subid])
|
trySend(['CLOSE', subid])
|
||||||
},
|
},
|
||||||
on: (type: 'event' | 'eose', cb: any): void => {
|
on: <T extends keyof SubEvent, U extends SubEvent[T]>(
|
||||||
|
type: T,
|
||||||
|
cb: U
|
||||||
|
): void => {
|
||||||
subListeners[subid] = subListeners[subid] || {
|
subListeners[subid] = subListeners[subid] || {
|
||||||
event: [],
|
event: [],
|
||||||
eose: []
|
eose: []
|
||||||
}
|
}
|
||||||
subListeners[subid][type].push(cb)
|
subListeners[subid][type].push(cb)
|
||||||
},
|
},
|
||||||
off: (type: 'event' | 'eose', cb: any): void => {
|
off: <T extends keyof SubEvent, U extends SubEvent[T]>(
|
||||||
let idx = subListeners[subid][type].indexOf(cb)
|
type: T,
|
||||||
if (idx >= 0) subListeners[subid][type].splice(idx, 1)
|
cb: U
|
||||||
|
): void => {
|
||||||
|
let listeners = subListeners[subid]
|
||||||
|
let idx = listeners[type].indexOf(cb)
|
||||||
|
if (idx >= 0) listeners[type].splice(idx, 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -183,81 +265,83 @@ export function relayInit(url: string): Relay {
|
|||||||
return {
|
return {
|
||||||
url,
|
url,
|
||||||
sub,
|
sub,
|
||||||
on: (
|
on: <T extends keyof RelayEvent, U extends RelayEvent[T]>(
|
||||||
type: 'connect' | 'disconnect' | 'error' | 'notice',
|
type: T,
|
||||||
cb: any
|
cb: U
|
||||||
): void => {
|
): void => {
|
||||||
listeners[type].push(cb)
|
listeners[type].push(cb)
|
||||||
if (type === 'connect' && ws?.readyState === 1) {
|
if (type === 'connect' && ws?.readyState === 1) {
|
||||||
cb()
|
// i would love to know why we need this
|
||||||
|
;(cb as () => void)()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
off: (
|
off: <T extends keyof RelayEvent, U extends RelayEvent[T]>(
|
||||||
type: 'connect' | 'disconnect' | 'error' | 'notice',
|
type: T,
|
||||||
cb: any
|
cb: U
|
||||||
): void => {
|
): 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)
|
||||||
|
}, listTimeout)
|
||||||
|
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)
|
||||||
|
}, getTimeout)
|
||||||
|
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
|
||||||
|
|
||||||
var sent = false
|
|
||||||
var mustMonitor = false
|
|
||||||
|
|
||||||
trySend(['EVENT', event])
|
trySend(['EVENT', event])
|
||||||
.then(() => {
|
|
||||||
sent = true
|
|
||||||
if (mustMonitor) {
|
|
||||||
startMonitoring()
|
|
||||||
mustMonitor = false
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(() => {})
|
|
||||||
|
|
||||||
const startMonitoring = () => {
|
|
||||||
let monitor = sub([{ids: [id]}], {
|
|
||||||
id: `monitor-${id.slice(0, 5)}`
|
|
||||||
})
|
|
||||||
let willUnsub = setTimeout(() => {
|
|
||||||
pubListeners[id].failed.forEach(cb =>
|
|
||||||
cb('event not seen after 5 seconds')
|
|
||||||
)
|
|
||||||
monitor.unsub()
|
|
||||||
}, 5000)
|
|
||||||
monitor.on('event', () => {
|
|
||||||
clearTimeout(willUnsub)
|
|
||||||
pubListeners[id].seen.forEach(cb => cb())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
on: (type: 'ok' | 'seen' | 'failed', cb: any) => {
|
on: (type: 'ok' | 'failed', cb: any) => {
|
||||||
pubListeners[id] = pubListeners[id] || {
|
pubListeners[id] = pubListeners[id] || {
|
||||||
ok: [],
|
ok: [],
|
||||||
seen: [],
|
|
||||||
failed: []
|
failed: []
|
||||||
}
|
}
|
||||||
pubListeners[id][type].push(cb)
|
pubListeners[id][type].push(cb)
|
||||||
|
|
||||||
if (type === 'seen') {
|
|
||||||
if (sent) startMonitoring()
|
|
||||||
else mustMonitor = true
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
off: (type: 'ok' | 'seen' | 'failed', cb: any) => {
|
off: (type: 'ok' | '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(): void {
|
||||||
ws.close()
|
listeners = {connect: [], disconnect: [], error: [], notice: []}
|
||||||
return new Promise(resolve => {
|
subListeners = {}
|
||||||
resolveClose = resolve
|
pubListeners = {}
|
||||||
})
|
if (ws.readyState === WebSocket.OPEN) {
|
||||||
|
ws?.close()
|
||||||
|
}
|
||||||
},
|
},
|
||||||
get status() {
|
get status() {
|
||||||
return ws?.readyState ?? 3
|
return ws?.readyState ?? 3
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"emitDeclarationOnly": true,
|
"emitDeclarationOnly": true,
|
||||||
"outDir": "dist",
|
"outDir": "lib",
|
||||||
"rootDir": "."
|
"rootDir": "."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
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