Skip to content

Commit

Permalink
nip01: add support for filter prefix in authors and ids
Browse files Browse the repository at this point in the history
so clients can filter events by prefix in authors and ids as
described in nip-01, i.e. to subscribe to mined events starting
with zeroes or to add some privacy for clients that may not want
to disclose the exact filter.

see also scsibug/nostr-rs-relay#104
  • Loading branch information
offbyn authored and fiatjaf committed Apr 7, 2023
1 parent b0a58e2 commit 3bdb680
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
24 changes: 24 additions & 0 deletions filter.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ describe('Filter', () => {
expect(result).toEqual(false)
})

it('should return true when the event id starts with a prefix', () => {
const filter = {ids: ['22', '00']}

const event = {id: '001'}

const result = matchFilter(filter, event)

expect(result).toEqual(true)
})

it('should return false when the event kind is not in the filter', () => {
const filter = {kinds: [1, 2, 3]}

Expand Down Expand Up @@ -132,6 +142,20 @@ describe('Filter', () => {
expect(result).toEqual(true)
})

it('should return true when at least one prefix matches the event', () => {
const filters = [
{ids: ['1'], kinds: [1], authors: ['a']},
{ids: ['4'], kinds: [2], authors: ['d']},
{ids: ['9'], kinds: [3], authors: ['g']}
]

const event = {id: '987', 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},
Expand Down
13 changes: 10 additions & 3 deletions filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,17 @@ export function matchFilter(
filter: Filter,
event: Event
): boolean {
if (filter.ids && filter.ids.indexOf(event.id) === -1) return false
if (filter.ids && filter.ids.indexOf(event.id) === -1) {
if (!filter.ids.some(prefix => event.id.startsWith(prefix))) {
return false
}
}
if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) return false
if (filter.authors && filter.authors.indexOf(event.pubkey) === -1)
return false
if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {
if (!filter.authors.some(prefix => event.pubkey.startsWith(prefix))) {
return false
}
}

for (let f in filter) {
if (f[0] === '#') {
Expand Down

0 comments on commit 3bdb680

Please sign in to comment.