NIP-19: Add nrelay encoding and decoding

This commit is contained in:
Alejandro Gomez
2023-04-14 17:46:06 +02:00
committed by fiatjaf_
parent f6f5ee8223
commit f17ab41d72
2 changed files with 27 additions and 0 deletions

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

@@ -82,6 +82,16 @@ export function decode(nip19: string): {
}
}
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':
@@ -160,6 +170,14 @@ export function naddrEncode(addr: AddressPointer): string {
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[] = []