Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

key: use nip19 identifiers everywhere #383

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 103 additions & 29 deletions src/js/lib/nostr-tools/nip19.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,48 +13,99 @@ export type ProfilePointer = {
export type EventPointer = {
id: string // hex
relays?: string[]
author?: string
}

export function decode(nip19: string): {
type: string
data: ProfilePointer | EventPointer | string
} {
export type AddressPointer = {
identifier: string
pubkey: string
kind: number
relays?: string[]
}

export type DecodeResult =
| {type: 'nprofile'; data: ProfilePointer}
| {type: 'nrelay'; data: string}
| {type: 'nevent'; data: EventPointer}
| {type: 'naddr'; data: AddressPointer}
| {type: 'nsec'; data: string}
| {type: 'npub'; data: string}
| {type: 'note'; data: string}

export function decode(nip19: string): DecodeResult {
let {prefix, words} = bech32.decode(nip19, Bech32MaxSize)
let data = new Uint8Array(bech32.fromWords(words))

if (prefix === 'nprofile') {
let tlv = parseTLV(data)
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')
switch (prefix) {
case 'nprofile': {
let tlv = parseTLV(data)
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')

return {
type: 'nprofile',
data: {
pubkey: secp256k1.utils.bytesToHex(tlv[0][0]),
relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : []
}
}
}
case 'nevent': {
let tlv = parseTLV(data)
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[2] && tlv[2][0].length !== 32)
throw new Error('TLV 2 should be 32 bytes')

return {
type: 'nevent',
data: {
id: secp256k1.utils.bytesToHex(tlv[0][0]),
relays: tlv[1] ? tlv[1].map(d => utf8Decoder.decode(d)) : [],
author: tlv[2]?.[0]
? secp256k1.utils.bytesToHex(tlv[2][0])
: undefined
}
}
}

return {
type: 'nprofile',
data: {
pubkey: secp256k1.utils.bytesToHex(tlv[0][0]),
relays: tlv[1].map(d => utf8Decoder.decode(d))
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)) : []
}
}
}
}

if (prefix === 'nevent') {
let tlv = parseTLV(data)
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')
case 'nrelay': {
let tlv = parseTLV(data)
if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nrelay')

return {
type: 'nevent',
data: {
id: secp256k1.utils.bytesToHex(tlv[0][0]),
relays: tlv[1].map(d => utf8Decoder.decode(d))
return {
type: 'nrelay',
data: utf8Decoder.decode(tlv[0][0])
}
}
}

if (prefix === 'nsec' || prefix === 'npub' || prefix === 'note') {
return {type: prefix, data: secp256k1.utils.bytesToHex(data)}
}
case 'nsec':
case 'npub':
case 'note':
return {type: prefix, data: secp256k1.utils.bytesToHex(data)}

throw new Error(`unknown prefix ${prefix}`)
default:
throw new Error(`unknown prefix ${prefix}`)
}
}

type TLV = {[t: number]: Uint8Array[]}
Expand Down Expand Up @@ -104,12 +155,35 @@ export function nprofileEncode(profile: ProfilePointer): string {
export function neventEncode(event: EventPointer): string {
let data = encodeTLV({
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)
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)
}

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[] = []

Expand Down
9 changes: 9 additions & 0 deletions src/js/nostr/EventsMeta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ class EventMetaStore {
return this;
}

upsertRelays(id: string, relays: string[] = []) {
if (relays.length === 0) {
return;
}
this.upsert(id, {
relays: new Set(relays),
});
}

get(id: string): undefined | EventMetadata {
if (!id) return;
return this._data.get(id);
Expand Down
90 changes: 73 additions & 17 deletions src/js/nostr/Key.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { Event, generatePrivateKey, getPublicKey, nip04, signEvent } from '../lib/nostr-tools';

import Events from './Events';
const bech32 = require('bech32-buffer'); /* eslint-disable-line @typescript-eslint/no-var-requires */
import { route } from 'preact-router';

import Helpers from '../Helpers';
import {
Event,
generatePrivateKey,
getPublicKey,
nip04,
nip19,
signEvent,
} from '../lib/nostr-tools';
import localState from '../LocalState';

import Events from './Events';

declare global {
interface Window {
nostr: any; // possible nostr browser extension
Expand Down Expand Up @@ -204,6 +209,44 @@ export default {
return false;
}
},
// Encodes npub/note into nprofile/nevent, if necessary.
_addRelays(address: string) {
const { data, type } = nip19.decode(address);
switch (type) {
case 'npub':
return nip19.nprofileEncode({
pubkey: data,
relays: Events.eventsMetaDb.getRelays(data).slice(0, 5),
});
case 'note':
return nip19.neventEncode({
id: data,
relays: Events.eventsMetaDb.getRelays(data).slice(0, 5),
});
// These already contain relay data, so keep it.
case 'nprofile':
case 'nevent':
case 'naddr':
return address;
}
},
// Encodes into nprofile/nevent, adding relays we know of.
_encodeWithRelays(hexAddress: string, prefix: string) {
switch (prefix) {
case 'npub':
case 'nprofile':
return nip19.nprofileEncode({
pubkey: hexAddress,
relays: Events.eventsMetaDb.getRelays(hexAddress).slice(0, 5),
});
case 'nevent':
case 'note':
return nip19.neventEncode({
id: hexAddress,
relays: Events.eventsMetaDb.getRelays(hexAddress).slice(0, 5),
});
}
},
toNostrBech32Address: function (address: string, prefix: string) {
if (!address) {
return;
Expand All @@ -212,18 +255,17 @@ export default {
throw new Error('prefix is required');
}
try {
const decoded = bech32.decode(address);
if (prefix !== decoded.prefix) {
return null;
const addr = this._addRelays(address);
if (addr) {
return addr;
}
return bech32.encode(prefix, decoded.data);
} catch (e) {
// not a bech32 address
// nop
}

if (address.match(/^[0-9a-fA-F]{64}$/)) {
const words = Buffer.from(address, 'hex');
return bech32.encode(prefix, words);
try {
return this._encodeWithRelays(address, prefix);
} catch {
// nop
}
return null;
},
Expand All @@ -232,9 +274,23 @@ export default {
return str;
}
try {
const { data } = bech32.decode(str);
const addr = Helpers.arrayToHex(data);
return addr;
const { data, type } = nip19.decode(str);
switch (type) {
case 'nprofile':
Events.eventsMetaDb.upsertRelays(data.pubkey, data.relays);
return data.pubkey;
case 'nevent':
Events.eventsMetaDb.upsertRelays(data.id, data.relays);
return data.id;
case 'naddr':
Events.eventsMetaDb.upsertRelays(data.identifier, data.relays);
return data.identifier;
case 'note':
case 'npub':
case 'nrelay':
case 'nsec':
return data;
}
} catch (e) {
// not a bech32 address
}
Expand Down