2024-02-28 16:49:44 +00:00
|
|
|
import {
|
|
|
|
Filter,
|
|
|
|
SimplePool,
|
|
|
|
VerifiedEvent,
|
|
|
|
kinds,
|
|
|
|
validateEvent,
|
2024-03-01 10:16:35 +00:00
|
|
|
verifyEvent,
|
2024-05-10 10:16:28 +00:00
|
|
|
Event,
|
2024-05-10 10:57:04 +00:00
|
|
|
EventTemplate,
|
|
|
|
nip19
|
2024-02-28 16:49:44 +00:00
|
|
|
} from 'nostr-tools'
|
2024-05-10 10:57:04 +00:00
|
|
|
import { NostrJoiningBlock, ProfileMetadata, RelaySet } from '../types'
|
2024-03-01 10:16:35 +00:00
|
|
|
import { NostrController } from '.'
|
|
|
|
import { toast } from 'react-toastify'
|
2024-05-10 10:16:28 +00:00
|
|
|
import { queryNip05 } from '../utils'
|
|
|
|
import NDK, { NDKEvent, NDKSubscription } from '@nostr-dev-kit/ndk'
|
2024-05-30 17:28:40 +00:00
|
|
|
import { EventEmitter } from 'tseep'
|
|
|
|
import { localCache } from '../services'
|
2024-08-07 12:52:14 +00:00
|
|
|
import {
|
|
|
|
findRelayListAndUpdateCache,
|
|
|
|
findRelayListInCache,
|
|
|
|
getDefaultRelaySet,
|
|
|
|
getUserRelaySet
|
|
|
|
} from '../utils/relays.ts'
|
2024-02-28 16:49:44 +00:00
|
|
|
|
2024-05-30 17:28:40 +00:00
|
|
|
export class MetadataController extends EventEmitter {
|
2024-03-01 10:16:35 +00:00
|
|
|
private nostrController: NostrController
|
|
|
|
private specialMetadataRelay = 'wss://purplepag.es'
|
|
|
|
|
|
|
|
constructor() {
|
2024-05-30 17:28:40 +00:00
|
|
|
super()
|
2024-03-01 10:16:35 +00:00
|
|
|
this.nostrController = NostrController.getInstance()
|
|
|
|
}
|
2024-02-28 16:49:44 +00:00
|
|
|
|
2024-05-30 17:28:40 +00:00
|
|
|
/**
|
|
|
|
* Asynchronously checks for more recent metadata events authored by a specific key.
|
|
|
|
* If a more recent metadata event is found, it is handled and returned.
|
|
|
|
* If no more recent event is found, the current event is returned.
|
|
|
|
* @param hexKey The hexadecimal key of the author to filter metadata events.
|
|
|
|
* @param currentEvent The current metadata event, if any, to compare with newer events.
|
|
|
|
* @returns A promise resolving to the most recent metadata event found, or null if none is found.
|
|
|
|
*/
|
|
|
|
private async checkForMoreRecentMetadata(
|
|
|
|
hexKey: string,
|
|
|
|
currentEvent: Event | null
|
|
|
|
): Promise<Event | null> {
|
|
|
|
// Define the event filter to only include metadata events authored by the given key
|
2024-02-28 16:49:44 +00:00
|
|
|
const eventFilter: Filter = {
|
2024-05-30 17:28:40 +00:00
|
|
|
kinds: [kinds.Metadata], // Only metadata events
|
|
|
|
authors: [hexKey] // Authored by the specified key
|
2024-02-28 16:49:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const pool = new SimplePool()
|
|
|
|
|
2024-05-30 17:28:40 +00:00
|
|
|
// Try to get the metadata event from a special relay (wss://purplepag.es)
|
2024-03-19 09:23:34 +00:00
|
|
|
const metadataEvent = await pool
|
|
|
|
.get([this.specialMetadataRelay], eventFilter)
|
|
|
|
.catch((err) => {
|
2024-05-30 17:28:40 +00:00
|
|
|
console.error(err) // Log any errors
|
|
|
|
return null // Return null if an error occurs
|
2024-03-19 09:23:34 +00:00
|
|
|
})
|
|
|
|
|
2024-05-30 17:28:40 +00:00
|
|
|
// If a valid metadata event is found from the special relay
|
2024-03-19 09:23:34 +00:00
|
|
|
if (
|
|
|
|
metadataEvent &&
|
2024-05-30 17:28:40 +00:00
|
|
|
validateEvent(metadataEvent) && // Validate the event
|
|
|
|
verifyEvent(metadataEvent) // Verify the event's authenticity
|
2024-03-19 09:23:34 +00:00
|
|
|
) {
|
2024-05-30 17:28:40 +00:00
|
|
|
// If there's no current event or the new metadata event is more recent
|
2024-07-05 08:38:04 +00:00
|
|
|
if (
|
|
|
|
!currentEvent ||
|
|
|
|
metadataEvent.created_at >= currentEvent.created_at
|
|
|
|
) {
|
2024-05-30 17:28:40 +00:00
|
|
|
// Handle the new metadata event
|
|
|
|
this.handleNewMetadataEvent(metadataEvent)
|
|
|
|
}
|
2024-07-05 08:38:04 +00:00
|
|
|
|
|
|
|
return metadataEvent
|
2024-03-19 09:23:34 +00:00
|
|
|
}
|
|
|
|
|
2024-05-30 17:28:40 +00:00
|
|
|
// If no valid metadata event is found from the special relay, get the most popular relays
|
2024-05-28 09:22:31 +00:00
|
|
|
const mostPopularRelays = await this.nostrController.getMostPopularRelays()
|
2024-03-19 09:23:34 +00:00
|
|
|
|
2024-05-30 17:28:40 +00:00
|
|
|
// Query the most popular relays for metadata events
|
2024-05-28 09:22:31 +00:00
|
|
|
const events = await pool
|
|
|
|
.querySync(mostPopularRelays, eventFilter)
|
|
|
|
.catch((err) => {
|
2024-05-30 17:28:40 +00:00
|
|
|
console.error(err) // Log any errors
|
|
|
|
return null // Return null if an error occurs
|
2024-05-28 09:22:31 +00:00
|
|
|
})
|
2024-02-28 16:49:44 +00:00
|
|
|
|
2024-05-30 17:28:40 +00:00
|
|
|
// If events are found from the popular relays
|
2024-02-28 16:49:44 +00:00
|
|
|
if (events && events.length) {
|
2024-05-30 17:28:40 +00:00
|
|
|
events.sort((a, b) => b.created_at - a.created_at) // Sort events by creation date (descending)
|
2024-02-28 16:49:44 +00:00
|
|
|
|
2024-05-30 17:28:40 +00:00
|
|
|
// Iterate through the events
|
2024-02-28 16:49:44 +00:00
|
|
|
for (const event of events) {
|
2024-05-30 17:28:40 +00:00
|
|
|
// If the event is valid, authentic, and more recent than the current event
|
|
|
|
if (
|
|
|
|
validateEvent(event) &&
|
|
|
|
verifyEvent(event) &&
|
|
|
|
(!currentEvent || event.created_at > currentEvent.created_at)
|
|
|
|
) {
|
|
|
|
// Handle the new metadata event
|
|
|
|
this.handleNewMetadataEvent(event)
|
2024-02-28 16:49:44 +00:00
|
|
|
return event
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-30 17:28:40 +00:00
|
|
|
return currentEvent // Return the current event if no newer event is found
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handle new metadata events and emit them to subscribers
|
|
|
|
*/
|
|
|
|
private async handleNewMetadataEvent(event: VerifiedEvent) {
|
|
|
|
// update the event in local cache
|
|
|
|
localCache.addUserMetadata(event)
|
|
|
|
// Emit the event to subscribers.
|
|
|
|
this.emit(event.pubkey, event.kind, event)
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Finds metadata for a given hexadecimal key.
|
|
|
|
*
|
|
|
|
* @param hexKey - The hexadecimal key to search for metadata.
|
|
|
|
* @returns A promise that resolves to the metadata event.
|
|
|
|
*/
|
|
|
|
public findMetadata = async (hexKey: string): Promise<Event | null> => {
|
|
|
|
// Attempt to retrieve the metadata event from the local cache
|
|
|
|
const cachedMetadataEvent = await localCache.getUserMetadata(hexKey)
|
|
|
|
|
|
|
|
// If cached metadata is found, check its validity
|
|
|
|
if (cachedMetadataEvent) {
|
2024-07-05 08:38:04 +00:00
|
|
|
const oneWeekInMS = 7 * 24 * 60 * 60 * 1000 // Number of milliseconds in one week
|
2024-05-30 17:28:40 +00:00
|
|
|
|
2024-07-05 08:38:04 +00:00
|
|
|
// Check if the cached metadata is older than one week
|
|
|
|
if (Date.now() - cachedMetadataEvent.cachedAt > oneWeekInMS) {
|
|
|
|
// If older than one week, find the metadata from relays in background
|
2024-05-30 17:28:40 +00:00
|
|
|
|
|
|
|
this.checkForMoreRecentMetadata(hexKey, cachedMetadataEvent.event)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Return the cached metadata event
|
|
|
|
return cachedMetadataEvent.event
|
|
|
|
}
|
|
|
|
|
|
|
|
// If no cached metadata is found, retrieve it from relays
|
|
|
|
return this.checkForMoreRecentMetadata(hexKey, null)
|
2024-02-28 16:49:44 +00:00
|
|
|
}
|
|
|
|
|
2024-08-07 12:52:14 +00:00
|
|
|
/**
|
|
|
|
* Based on the hexKey of the current user, this method attempts to retrieve a relay set.
|
|
|
|
* @func findRelayListInCache first checks if there is already an up-to-date
|
|
|
|
* relay list available in cache; if not -
|
|
|
|
* @func findRelayListAndUpdateCache checks if the relevant relay event is available from
|
|
|
|
* the purple pages relay;
|
|
|
|
* @func findRelayListAndUpdateCache will run again if the previous two calls return null and
|
|
|
|
* check if the relevant relay event can be obtained from 'most popular relays'
|
|
|
|
* If relay event is found, it will be saved in cache for future use
|
|
|
|
* @param hexKey of the current user
|
|
|
|
* @return RelaySet which will contain either relays extracted from the user Relay Event
|
|
|
|
* or a fallback RelaySet with Sigit's Relay
|
|
|
|
*/
|
|
|
|
public findRelayListMetadata = async (hexKey: string): Promise<RelaySet> => {
|
2024-08-07 14:49:13 +00:00
|
|
|
const relayEvent =
|
|
|
|
(await findRelayListInCache(hexKey)) ||
|
|
|
|
(await findRelayListAndUpdateCache(
|
|
|
|
[this.specialMetadataRelay],
|
|
|
|
hexKey
|
|
|
|
)) ||
|
|
|
|
(await findRelayListAndUpdateCache(
|
|
|
|
await this.nostrController.getMostPopularRelays(),
|
|
|
|
hexKey
|
|
|
|
))
|
|
|
|
|
|
|
|
return relayEvent ? getUserRelaySet(relayEvent.tags) : getDefaultRelaySet()
|
2024-04-16 06:12:29 +00:00
|
|
|
}
|
|
|
|
|
2024-05-30 17:28:40 +00:00
|
|
|
public extractProfileMetadataContent = (event: Event) => {
|
2024-02-28 16:49:44 +00:00
|
|
|
try {
|
2024-05-17 11:33:01 +00:00
|
|
|
if (!event.content) return {}
|
2024-03-01 10:16:35 +00:00
|
|
|
return JSON.parse(event.content) as ProfileMetadata
|
2024-02-28 16:49:44 +00:00
|
|
|
} catch (error) {
|
|
|
|
console.log('error in parsing metadata event content :>> ', error)
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
}
|
2024-03-01 10:16:35 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Function will not sign provided event if the SIG exists
|
|
|
|
*/
|
|
|
|
public publishMetadataEvent = async (event: Event) => {
|
|
|
|
let signedMetadataEvent = event
|
|
|
|
|
|
|
|
if (event.sig.length < 1) {
|
|
|
|
const timestamp = Math.floor(Date.now() / 1000)
|
|
|
|
|
2024-03-19 09:23:34 +00:00
|
|
|
// Metadata event to publish to the wss://purplepag.es relay
|
2024-03-01 10:16:35 +00:00
|
|
|
const newMetadataEvent: Event = {
|
|
|
|
...event,
|
|
|
|
created_at: timestamp
|
|
|
|
}
|
|
|
|
|
2024-05-15 08:50:21 +00:00
|
|
|
signedMetadataEvent =
|
|
|
|
await this.nostrController.signEvent(newMetadataEvent)
|
2024-03-01 10:16:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
await this.nostrController
|
2024-04-16 06:12:29 +00:00
|
|
|
.publishEvent(signedMetadataEvent, [this.specialMetadataRelay])
|
|
|
|
.then((relays) => {
|
|
|
|
toast.success(`Metadata event published on: ${relays.join('\n')}`)
|
2024-05-30 17:28:40 +00:00
|
|
|
this.handleNewMetadataEvent(signedMetadataEvent as VerifiedEvent)
|
2024-03-01 10:16:35 +00:00
|
|
|
})
|
|
|
|
.catch((err) => {
|
|
|
|
toast.error(err.message)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-05-10 10:57:04 +00:00
|
|
|
public getNostrJoiningBlockNumber = async (
|
|
|
|
hexKey: string
|
|
|
|
): Promise<NostrJoiningBlock | null> => {
|
2024-05-10 10:16:28 +00:00
|
|
|
const relaySet = await this.findRelayListMetadata(hexKey)
|
|
|
|
|
2024-05-10 10:57:04 +00:00
|
|
|
const userRelays: string[] = []
|
2024-05-10 10:16:28 +00:00
|
|
|
|
2024-05-10 10:27:34 +00:00
|
|
|
// find user's relays
|
2024-05-10 10:16:28 +00:00
|
|
|
if (relaySet.write.length > 0) {
|
2024-05-10 10:57:04 +00:00
|
|
|
userRelays.push(...relaySet.write)
|
2024-05-10 10:16:28 +00:00
|
|
|
} else {
|
|
|
|
const metadata = await this.findMetadata(hexKey)
|
2024-05-30 17:28:40 +00:00
|
|
|
if (!metadata) return null
|
|
|
|
|
2024-05-10 10:16:28 +00:00
|
|
|
const metadataContent = this.extractProfileMetadataContent(metadata)
|
|
|
|
|
|
|
|
if (metadataContent?.nip05) {
|
|
|
|
const nip05Profile = await queryNip05(metadataContent.nip05)
|
|
|
|
|
|
|
|
if (nip05Profile && nip05Profile.pubkey === hexKey) {
|
2024-05-10 10:57:04 +00:00
|
|
|
userRelays.push(...nip05Profile.relays)
|
2024-05-10 10:16:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-10 10:57:04 +00:00
|
|
|
if (userRelays.length === 0) return null
|
2024-05-10 10:16:28 +00:00
|
|
|
|
2024-05-27 10:57:40 +00:00
|
|
|
// filter for finding user's first kind 0 event
|
2024-05-10 10:16:28 +00:00
|
|
|
const eventFilter: Filter = {
|
2024-05-27 10:57:40 +00:00
|
|
|
kinds: [kinds.Metadata],
|
2024-05-10 10:16:28 +00:00
|
|
|
authors: [hexKey]
|
|
|
|
}
|
|
|
|
|
|
|
|
const pool = new SimplePool()
|
2024-05-10 10:27:34 +00:00
|
|
|
|
2024-05-27 10:57:40 +00:00
|
|
|
// find user's kind 0 events published on user's relays
|
2024-05-10 10:57:04 +00:00
|
|
|
const events = await pool.querySync(userRelays, eventFilter)
|
2024-05-10 10:16:28 +00:00
|
|
|
if (events && events.length) {
|
2024-05-10 10:27:34 +00:00
|
|
|
// sort events by created_at time in ascending order
|
2024-05-10 10:16:28 +00:00
|
|
|
events.sort((a, b) => a.created_at - b.created_at)
|
|
|
|
|
2024-05-10 10:27:34 +00:00
|
|
|
// get first ever event published on user's relays
|
2024-05-10 10:16:28 +00:00
|
|
|
const event = events[0]
|
|
|
|
const { created_at } = event
|
|
|
|
|
2024-05-10 10:27:34 +00:00
|
|
|
// initialize job request
|
2024-05-10 10:16:28 +00:00
|
|
|
const jobEventTemplate: EventTemplate = {
|
|
|
|
content: '',
|
|
|
|
created_at: Math.round(Date.now() / 1000),
|
|
|
|
kind: 68001,
|
|
|
|
tags: [
|
|
|
|
['i', `${created_at * 1000}`],
|
|
|
|
['j', 'blockChain-block-number']
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
2024-05-10 10:27:34 +00:00
|
|
|
// sign job request event
|
2024-05-15 08:50:21 +00:00
|
|
|
const jobSignedEvent =
|
|
|
|
await this.nostrController.signEvent(jobEventTemplate)
|
2024-05-10 10:16:28 +00:00
|
|
|
|
|
|
|
const relays = [
|
|
|
|
'wss://relay.damus.io',
|
|
|
|
'wss://relay.primal.net',
|
|
|
|
'wss://relayable.org'
|
|
|
|
]
|
|
|
|
|
2024-05-10 10:27:34 +00:00
|
|
|
// publish job request
|
2024-05-10 10:16:28 +00:00
|
|
|
await this.nostrController.publishEvent(jobSignedEvent, relays)
|
|
|
|
|
|
|
|
console.log('jobSignedEvent :>> ', jobSignedEvent)
|
|
|
|
|
|
|
|
const subscribeWithTimeout = (
|
|
|
|
subscription: NDKSubscription,
|
|
|
|
timeoutMs: number
|
|
|
|
): Promise<string> => {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const eventHandler = (event: NDKEvent) => {
|
|
|
|
subscription.stop()
|
|
|
|
resolve(event.content)
|
|
|
|
}
|
|
|
|
|
|
|
|
subscription.on('event', eventHandler)
|
|
|
|
|
|
|
|
// Set up a timeout to stop the subscription after a specified time
|
|
|
|
const timeout = setTimeout(() => {
|
|
|
|
subscription.stop() // Stop the subscription
|
|
|
|
reject(new Error('Subscription timed out')) // Reject the promise with a timeout error
|
|
|
|
}, timeoutMs)
|
|
|
|
|
|
|
|
// Handle subscription close event
|
|
|
|
subscription.on('close', () => clearTimeout(timeout))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const dvmNDK = new NDK({
|
|
|
|
explicitRelayUrls: relays
|
|
|
|
})
|
|
|
|
|
|
|
|
await dvmNDK.connect(2000)
|
|
|
|
|
2024-05-10 10:27:34 +00:00
|
|
|
// filter for getting DVM job's result
|
2024-05-10 10:16:28 +00:00
|
|
|
const sub = dvmNDK.subscribe({
|
|
|
|
kinds: [68002 as number],
|
|
|
|
'#e': [jobSignedEvent.id],
|
|
|
|
'#p': [jobSignedEvent.pubkey]
|
|
|
|
})
|
|
|
|
|
2024-05-10 10:57:04 +00:00
|
|
|
// asynchronously get block number from dvm job with 20 seconds timeout
|
|
|
|
const dvmJobResult = await subscribeWithTimeout(sub, 20000)
|
2024-05-10 10:16:28 +00:00
|
|
|
|
2024-05-10 10:57:04 +00:00
|
|
|
const encodedEventPointer = nip19.neventEncode({
|
|
|
|
id: event.id,
|
|
|
|
relays: userRelays,
|
|
|
|
author: event.pubkey,
|
|
|
|
kind: event.kind
|
|
|
|
})
|
|
|
|
|
|
|
|
return {
|
|
|
|
block: parseInt(dvmJobResult),
|
|
|
|
encodedEventPointer
|
|
|
|
}
|
2024-05-10 10:16:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
|
2024-03-01 10:16:35 +00:00
|
|
|
public validate = (event: Event) => validateEvent(event) && verifyEvent(event)
|
2024-05-30 17:28:40 +00:00
|
|
|
|
|
|
|
public getEmptyMetadataEvent = (): Event => {
|
|
|
|
return {
|
|
|
|
content: '',
|
|
|
|
created_at: new Date().valueOf(),
|
|
|
|
id: '',
|
|
|
|
kind: 0,
|
|
|
|
pubkey: '',
|
|
|
|
sig: '',
|
|
|
|
tags: []
|
|
|
|
}
|
|
|
|
}
|
2024-02-28 16:49:44 +00:00
|
|
|
}
|