Created
February 6, 2023 00:41
-
-
Save mikehw/c2226fcff952f61e41ec69acb693ee3a to your computer and use it in GitHub Desktop.
DID Message Verify Worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as dotenv from "dotenv"; | |
dotenv.config(); | |
import { createClient } from "@supabase/supabase-js"; | |
import { z } from "zod"; | |
import { relayInit, Event, Filter } from "nostr-tools"; | |
import { message_schema_compat, verify } from "chia-signing-tools"; | |
import { createHash } from "crypto"; | |
Object.assign(global, { WebSocket: require('ws') }); | |
const supabaseClient = createClient( | |
"https://umwdejvagxgtebmvyqvi.supabase.co", | |
process.env.SUPABASE_KEY ?? "" | |
); | |
const reputation_schema = z.discriminatedUnion("type", [ | |
z.object({ | |
type: z.literal("did_trust"), | |
ts: z.string().datetime(), | |
data: z.object({ | |
did: z.string().startsWith("did:chia:"), | |
}), | |
}), | |
]); | |
const relay = relayInit("wss://nostr.p2sh.co"); | |
relay.on("connect", () => { | |
console.log(`connected to ${relay!.url}`); | |
}); | |
relay.on("error" as any, () => { | |
console.log(`failed to connect to ${relay!.url}`); | |
}); | |
relay.on("disconnect" as any, () => { | |
console.log(`disconnect from ${relay!.url}`); | |
relay?.connect(); | |
}); | |
relay.on("notice" as any, () => { | |
console.log(`notice from ${relay!.url}`); | |
}); | |
function subscribeToEvents(filter: Filter, callback: any) { | |
if (!relay) { | |
throw new Error("Relay not initialized"); | |
} | |
const sub = relay.sub([filter]); | |
sub.on("event", async (event: Event) => { | |
try { | |
console.log("event", event); | |
const message = message_schema_compat.parse(JSON.parse(event.content)); | |
// TODO Confirm the local wallet node is synced | |
const result = await isValid(event.content); | |
if (result === true || result === false) { | |
const hash = await sha256(event.content); | |
const { data, error } = await supabaseClient | |
.from("checked_messages") | |
.upsert([{ hash, valid: result, checked: new Date() }]); | |
console.log(data, error); | |
} | |
} catch (e) { | |
console.error(e); | |
// Ignore | |
} | |
}); | |
return sub; | |
} | |
subscribeToEvents( | |
{ | |
kinds: [8444], | |
}, | |
(event: Event) => { | |
console.log(event); | |
} | |
); | |
relay.connect(); | |
async function isValid(message: string) { | |
try { | |
const result = await verify(message); | |
return result.isValid; | |
} catch (e) { | |
// Benefit of the doubt for now | |
return undefined; | |
} | |
} | |
async function sha256(str: string) { | |
return createHash('sha256').update(str).digest('hex') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment