Compare commits

...

15 Commits

Author SHA1 Message Date
fiatjaf
ac212cb5c8 tag v1.9.0 using @noble/curves. 2023-04-14 17:09:28 -03:00
Paul Miller
204ae0eff1 Switch from noble-secp256k1 to noble-curves 2023-04-14 16:45:01 -03:00
Alejandro Gomez
f17ab41d72 NIP-19: Add nrelay encoding and decoding 2023-04-14 13:26:31 -03:00
fiatjaf
f6f5ee8223 tag v1.8.4 2023-04-11 18:23:04 -03:00
Alex Gleason
a05506468d Add NIP-13 (proof-of-work) module 2023-04-11 18:21:40 -03:00
Agustin Kassis
674ff66b6f added badge events
Added the following badge kinds according to NIP 58
  BadgeDefinition: 30008,
  BadgeAward: 8,
  ProfileBadge: 30009,
2023-04-11 17:39:13 -03:00
channelninja
731705047a fix(nip05): allow dot in name 2023-04-09 19:32:58 -03:00
Alex Gleason
94b382a49f Fix validateEvent type checking 2023-04-08 17:53:31 -03:00
fiatjaf
199411a971 yarn.lock with deduped packages. 2023-04-08 15:44:37 -03:00
fiatjaf
a1dc6f41b9 fix conflict in noble dependencies. 2023-04-08 15:43:47 -03:00
Alex Gleason
5b59b93d86 validateEvent: use assertion function 2023-04-08 15:07:25 -03:00
OFF0
12acd7bdca scripts: add npm build, format and test scripts
in addition to the just tasks, this commit adds npm scripts back,
for convenience.

example taks:
- npm test
- npm test filter.test.js
- npm run build
- npm run format

in yarn it should just work without 'run' i.e. 'yarn build'.
2023-04-08 09:05:23 -03:00
OFF0
3bdb68020d nip01: add support for filter prefix in authors and ids
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 https://github.com/scsibug/nostr-rs-relay/issues/104
2023-04-07 08:29:00 -03:00
Susumu OTA
b0a58e2ca4 fix: Event type has id and sig field. 2023-04-06 06:15:07 -03:00
Susumu OTA
b063be76ae fix: must be tag not ref. 2023-04-06 06:14:40 -03:00
17 changed files with 4163 additions and 54 deletions

View File

@@ -1,5 +1,6 @@
import * as secp256k1 from '@noble/secp256k1'
import {schnorr} from '@noble/curves/secp256k1'
import {sha256} from '@noble/hashes/sha256'
import {bytesToHex} from '@noble/hashes/utils'
import {utf8Encoder} from './utils'
import {getPublicKey} from './keys'
@@ -13,6 +14,7 @@ export enum Kind {
EncryptedDirectMessage = 4,
EventDeletion = 5,
Reaction = 7,
BadgeAward = 8,
ChannelCreation = 40,
ChannelMetadata = 41,
ChannelMessage = 42,
@@ -23,6 +25,8 @@ export enum Kind {
Zap = 9735,
RelayList = 10002,
ClientAuth = 22242,
BadgeDefinition = 30008,
ProfileBadge = 30009,
Article = 30023
}
@@ -75,11 +79,13 @@ export function serializeEvent(evt: UnsignedEvent): string {
export function getEventHash(event: UnsignedEvent): string {
let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)))
return secp256k1.utils.bytesToHex(eventHash)
return bytesToHex(eventHash)
}
export function validateEvent(event: UnsignedEvent): boolean {
if (typeof event !== 'object') return false
const isRecord = (obj: unknown): obj is Record<string, unknown> => obj instanceof Object
export function validateEvent<T>(event: T): event is T & UnsignedEvent {
if (!isRecord(event)) return false
if (typeof event.kind !== 'number') return false
if (typeof event.content !== 'string') return false
if (typeof event.created_at !== 'number') return false
@@ -98,8 +104,8 @@ export function validateEvent(event: UnsignedEvent): boolean {
return true
}
export function verifySignature(event: Event & {sig: string}): boolean {
return secp256k1.schnorr.verifySync(
export function verifySignature(event: Event): boolean {
return schnorr.verify(
event.sig,
getEventHash(event),
event.pubkey
@@ -107,7 +113,7 @@ export function verifySignature(event: Event & {sig: string}): boolean {
}
export function signEvent(event: UnsignedEvent, key: string): string {
return secp256k1.utils.bytesToHex(
secp256k1.schnorr.signSync(getEventHash(event), key)
return bytesToHex(
schnorr.sign(getEventHash(event), key)
)
}

View File

@@ -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]}
@@ -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},

View File

@@ -13,12 +13,19 @@ export type Filter = {
export function matchFilter(
filter: Filter,
event: Event & {id: string}
event: Event
): boolean {
if (filter.ids && filter.ids.indexOf(event.id) === -1) return false
if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) return false
if (filter.authors && filter.authors.indexOf(event.pubkey) === -1)
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) {
if (!filter.authors.some(prefix => event.pubkey.startsWith(prefix))) {
return false
}
}
for (let f in filter) {
if (f[0] === '#') {
@@ -42,7 +49,7 @@ export function matchFilter(
export function matchFilters(
filters: Filter[],
event: Event & {id: string}
event: Event
): boolean {
for (let i = 0; i < filters.length; i++) {
if (matchFilter(filters[i], event)) return true

View File

@@ -9,6 +9,7 @@ export * as nip04 from './nip04'
export * as nip05 from './nip05'
export * as nip06 from './nip06'
export * as nip10 from './nip10'
export * as nip13 from './nip13'
export * as nip19 from './nip19'
export * as nip26 from './nip26'
export * as nip39 from './nip39'
@@ -16,12 +17,3 @@ 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))

View File

@@ -1,9 +1,10 @@
import * as secp256k1 from '@noble/secp256k1'
import {schnorr} from '@noble/curves/secp256k1'
import {bytesToHex} from '@noble/hashes/utils'
export function generatePrivateKey(): string {
return secp256k1.utils.bytesToHex(secp256k1.utils.randomPrivateKey())
return bytesToHex(schnorr.utils.randomPrivateKey())
}
export function getPublicKey(privateKey: string): string {
return secp256k1.utils.bytesToHex(secp256k1.schnorr.getPublicKey(privateKey))
return bytesToHex(schnorr.getPublicKey(privateKey))
}

View File

@@ -1,5 +1,5 @@
import {randomBytes} from '@noble/hashes/utils'
import * as secp256k1 from '@noble/secp256k1'
import {secp256k1} from '@noble/curves/secp256k1'
import {base64} from '@scure/base'
import {utf8Decoder, utf8Encoder} from './utils'

View File

@@ -17,4 +17,9 @@ test('fetch nip05 profiles', async () => {
'32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'
)
expect(p2.relays).toEqual(['wss://relay.damus.io'])
let p3 = await nip05.queryProfile('channel.ninja@channel.ninja')
expect(p3.pubkey).toEqual(
'36e65b503eba8a6b698e724a59137603101166a1cddb45ddc704247fc8aa0fce'
)
})

View File

@@ -36,7 +36,7 @@ export async function queryProfile(
name = '_'
}
if (!name.match(/^[A-Za-z0-9-_]+$/)) return null
if (!name.match(/^[A-Za-z0-9-_.]+$/)) return null
if (!domain.includes('.')) return null
let res

View File

@@ -1,4 +1,4 @@
import * as secp256k1 from '@noble/secp256k1'
import {bytesToHex} from '@noble/hashes/utils'
import {wordlist} from '@scure/bip39/wordlists/english.js'
import {
generateMnemonic,
@@ -14,7 +14,7 @@ export function privateKeyFromSeedWords(
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase))
let privateKey = root.derive(`m/44'/1237'/0'/0/0`).privateKey
if (!privateKey) throw new Error('could not derive private key')
return secp256k1.utils.bytesToHex(privateKey)
return bytesToHex(privateKey)
}
export function generateSeedWords(): string {

8
nip13.test.js Normal file
View File

@@ -0,0 +1,8 @@
/* eslint-env jest */
const {nip13} = require('./lib/nostr.cjs')
test('identifies proof-of-work difficulty', async () => {
const id = '000006d8c378af1779d2feebc7603a125d99eca0ccf1085959b307f64e5dd358'
const difficulty = nip13.getPow(id)
expect(difficulty).toEqual(21)
})

42
nip13.ts Normal file
View File

@@ -0,0 +1,42 @@
import {hexToBytes} from '@noble/hashes/utils'
/** Get POW difficulty from a Nostr hex ID. */
export function getPow(id: string): number {
return getLeadingZeroBits(hexToBytes(id))
}
/**
* Get number of leading 0 bits. Adapted from nostream.
* https://github.com/Cameri/nostream/blob/fb6948fd83ca87ce552f39f9b5eb780ea07e272e/src/utils/proof-of-work.ts
*/
function getLeadingZeroBits(hash: Uint8Array): number {
let total: number, i: number, bits: number
for (i = 0, total = 0; i < hash.length; i++) {
bits = msb(hash[i])
total += bits
if (bits !== 8) {
break
}
}
return total
}
/**
* Adapted from nostream.
* https://github.com/Cameri/nostream/blob/fb6948fd83ca87ce552f39f9b5eb780ea07e272e/src/utils/proof-of-work.ts
*/
function msb(b: number) {
let n = 0
if (b === 0) {
return 8
}
// eslint-disable-next-line no-cond-assign
while (b >>= 1) {
n++
}
return 7 - n
}

View File

@@ -100,3 +100,12 @@ test('decode naddr from go-nostr with different TLV ordering', () => {
expect(data.kind).toEqual(30023)
expect(data.identifier).toEqual('banana')
})
test('encode and decode nrelay', () => {
let url = "wss://relay.nostr.example"
let nrelay = nip19.nrelayEncode(url)
expect(nrelay).toMatch(/nrelay1\w+/)
let {type, data} = nip19.decode(nrelay)
expect(type).toEqual('nrelay')
expect(data).toEqual(url)
})

View File

@@ -1,4 +1,4 @@
import * as secp256k1 from '@noble/secp256k1'
import {bytesToHex, concatBytes, hexToBytes} from '@noble/hashes/utils'
import {bech32} from '@scure/base'
import {utf8Decoder, utf8Encoder} from './utils'
@@ -39,7 +39,7 @@ export function decode(nip19: string): {
return {
type: 'nprofile',
data: {
pubkey: secp256k1.utils.bytesToHex(tlv[0][0]),
pubkey: bytesToHex(tlv[0][0]),
relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : []
}
}
@@ -54,10 +54,10 @@ export function decode(nip19: string): {
return {
type: 'nevent',
data: {
id: secp256k1.utils.bytesToHex(tlv[0][0]),
id: bytesToHex(tlv[0][0]),
relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],
author: tlv[2]?.[0]
? secp256k1.utils.bytesToHex(tlv[2][0])
? bytesToHex(tlv[2][0])
: undefined
}
}
@@ -75,17 +75,27 @@ export function decode(nip19: string): {
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),
pubkey: bytesToHex(tlv[2][0]),
kind: parseInt(bytesToHex(tlv[3][0]), 16),
relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : []
}
}
}
case 'nrelay': {
let tlv = parseTLV(data)
if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nrelay')
return {
type: 'nrelay',
data: utf8Decoder.decode(tlv[0][0])
}
}
case 'nsec':
case 'npub':
case 'note':
return {type: prefix, data: secp256k1.utils.bytesToHex(data)}
return {type: prefix, data: bytesToHex(data)}
default:
throw new Error(`unknown prefix ${prefix}`)
@@ -122,14 +132,14 @@ export function noteEncode(hex: string): string {
}
function encodeBytes(prefix: string, hex: string): string {
let data = secp256k1.utils.hexToBytes(hex)
let data = hexToBytes(hex)
let words = bech32.toWords(data)
return bech32.encode(prefix, words, Bech32MaxSize)
}
export function nprofileEncode(profile: ProfilePointer): string {
let data = encodeTLV({
0: [secp256k1.utils.hexToBytes(profile.pubkey)],
0: [hexToBytes(profile.pubkey)],
1: (profile.relays || []).map(url => utf8Encoder.encode(url))
})
let words = bech32.toWords(data)
@@ -138,9 +148,9 @@ export function nprofileEncode(profile: ProfilePointer): string {
export function neventEncode(event: EventPointer): string {
let data = encodeTLV({
0: [secp256k1.utils.hexToBytes(event.id)],
0: [hexToBytes(event.id)],
1: (event.relays || []).map(url => utf8Encoder.encode(url)),
2: event.author ? [secp256k1.utils.hexToBytes(event.author)] : []
2: event.author ? [hexToBytes(event.author)] : []
})
let words = bech32.toWords(data)
return bech32.encode('nevent', words, Bech32MaxSize)
@@ -153,13 +163,21 @@ export function naddrEncode(addr: AddressPointer): string {
let data = encodeTLV({
0: [utf8Encoder.encode(addr.identifier)],
1: (addr.relays || []).map(url => utf8Encoder.encode(url)),
2: [secp256k1.utils.hexToBytes(addr.pubkey)],
2: [hexToBytes(addr.pubkey)],
3: [new Uint8Array(kind)]
})
let words = bech32.toWords(data)
return bech32.encode('naddr', words, Bech32MaxSize)
}
export function nrelayEncode(url: string): string {
let data = encodeTLV({
0: [utf8Encoder.encode(url)]
})
let words = bech32.toWords(data)
return bech32.encode('nrelay', words, Bech32MaxSize)
}
function encodeTLV(tlv: TLV): Uint8Array {
let entries: Uint8Array[] = []
@@ -173,5 +191,5 @@ function encodeTLV(tlv: TLV): Uint8Array {
})
})
return secp256k1.utils.concatBytes(...entries)
return concatBytes(...entries)
}

View File

@@ -1,4 +1,5 @@
import * as secp256k1 from '@noble/secp256k1'
import {schnorr} from '@noble/curves/secp256k1'
import {bytesToHex} from '@noble/hashes/utils'
import {sha256} from '@noble/hashes/sha256'
import {Event} from './event'
@@ -36,8 +37,8 @@ export function createDelegation(
utf8Encoder.encode(`nostr:delegation:${parameters.pubkey}:${cond}`)
)
let sig = secp256k1.utils.bytesToHex(
secp256k1.schnorr.signSync(sighash, privateKey)
let sig = bytesToHex(
schnorr.sign(sighash, privateKey)
)
return {
@@ -84,7 +85,7 @@ export function getDelegator(event: Event): string | null {
let sighash = sha256(
utf8Encoder.encode(`nostr:delegation:${event.pubkey}:${cond}`)
)
if (!secp256k1.schnorr.verifySync(sig, sighash, pubkey)) return null
if (!schnorr.verify(sig, sighash, pubkey)) return null
return pubkey
}

View File

@@ -1,6 +1,6 @@
{
"name": "nostr-tools",
"version": "1.8.2",
"version": "1.9.0",
"description": "Tools for making a Nostr client.",
"repository": {
"type": "git",
@@ -18,12 +18,11 @@
},
"license": "Public domain",
"dependencies": {
"@noble/hashes": "1.0.0",
"@noble/secp256k1": "^1.7.1",
"@scure/base": "^1.1.1",
"@scure/bip32": "^1.1.5",
"@scure/bip39": "^1.1.1",
"prettier": "^2.8.4"
"@noble/curves": "1.0.0",
"@noble/hashes": "1.3.0",
"@scure/base": "1.1.1",
"@scure/bip32": "1.3.0",
"@scure/bip39": "1.2.0"
},
"keywords": [
"decentralization",
@@ -32,6 +31,11 @@
"client",
"nostr"
],
"scripts": {
"build": "node build",
"format": "prettier --plugin-search-dir . --write .",
"test": "node build && jest"
},
"devDependencies": {
"@types/node": "^18.13.0",
"@typescript-eslint/eslint-plugin": "^5.51.0",
@@ -44,6 +48,7 @@
"events": "^3.3.0",
"jest": "^29.4.2",
"node-fetch": "^2.6.9",
"prettier": "^2.8.4",
"ts-jest": "^29.0.5",
"tsd": "^0.22.0",
"typescript": "^4.9.5",

View File

@@ -81,7 +81,7 @@ export function parseReferences(evt: Event): Reference[] {
}
case 'a': {
try {
let [kind, pubkey, identifier] = ref[1].split(':')
let [kind, pubkey, identifier] = tag[1].split(':')
references.push({
text: ref[0],
address: {

3991
yarn.lock Normal file

File diff suppressed because it is too large Load Diff