mirror of
https://github.com/smolgrrr/TAO.git
synced 2024-09-20 09:21:25 +00:00
Merge pull request #1 from smolgrrr/webworkertests
implement web workers for PoW note gen
This commit is contained in:
commit
1f00204ab6
@ -5,6 +5,7 @@ import Settings from './components/Settings';
|
|||||||
import SwipeableViews from 'react-swipeable-views';
|
import SwipeableViews from 'react-swipeable-views';
|
||||||
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
|
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
|
||||||
import Thread from './components/Thread/Thread';
|
import Thread from './components/Thread/Thread';
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const [index, setIndex] = React.useState(1);
|
const [index, setIndex] = React.useState(1);
|
||||||
|
@ -17,11 +17,11 @@ const ContentPreview = ({ key, comment }: { key: string, comment: string }) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const findUrl = comment.match(/\bhttps?:\/\/\S+/gi);
|
// const findUrl = comment.match(/\bhttps?:\/\/\S+/gi);
|
||||||
if (findUrl && findUrl.length > 0) {
|
// if (findUrl && findUrl.length > 0) {
|
||||||
setUrl(findUrl[0])
|
// setUrl(findUrl[0])
|
||||||
setFinalComment(finalComment.replace(findUrl[0], '').trim())
|
// setFinalComment(finalComment.replace(findUrl[0], '').trim())
|
||||||
}
|
// }
|
||||||
|
|
||||||
const match = comment.match(/\bnostr:([a-z0-9]+)/i);
|
const match = comment.match(/\bnostr:([a-z0-9]+)/i);
|
||||||
const nostrQuoteID = match && match[1];
|
const nostrQuoteID = match && match[1];
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import CardContainer from './CardContainer';
|
import CardContainer from './CardContainer';
|
||||||
import { ArrowUpTrayIcon, CpuChipIcon } from '@heroicons/react/24/outline';
|
import { ArrowUpTrayIcon, CpuChipIcon } from '@heroicons/react/24/outline';
|
||||||
import { useState } from 'react';
|
import { useState, useEffect, useMemo } from 'react';
|
||||||
import { generatePrivateKey, getPublicKey, finishEvent } from 'nostr-tools';
|
import { generatePrivateKey, getPublicKey, finishEvent } from 'nostr-tools';
|
||||||
import { minePow } from '../../utils/mine';
|
import { minePow } from '../../utils/mine';
|
||||||
import { publish } from '../../utils/relays';
|
import { publish } from '../../utils/relays';
|
||||||
@ -11,30 +11,51 @@ const difficulty = 20
|
|||||||
const NewThreadCard: React.FC = () => {
|
const NewThreadCard: React.FC = () => {
|
||||||
const [comment, setComment] = useState("");
|
const [comment, setComment] = useState("");
|
||||||
const [file, setFile] = useState("");
|
const [file, setFile] = useState("");
|
||||||
|
const [sk, setSk] = useState(generatePrivateKey());
|
||||||
|
|
||||||
|
const [messageFromWorker, setMessageFromWorker] = useState(null);
|
||||||
|
// Initialize the worker outside of any effects
|
||||||
|
const worker = useMemo(() => new Worker(new URL('../../powWorker', import.meta.url)), []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
worker.onmessage = (event) => {
|
||||||
|
setMessageFromWorker(event.data);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
let sk = generatePrivateKey();
|
worker.postMessage({
|
||||||
|
unsigned: {
|
||||||
try {
|
|
||||||
const event = minePow({
|
|
||||||
kind: 1,
|
kind: 1,
|
||||||
tags: [],
|
tags: [],
|
||||||
content: comment + " " + file,
|
content: comment + " " + file,
|
||||||
created_at: Math.floor(Date.now() / 1000),
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
pubkey: getPublicKey(sk),
|
pubkey: getPublicKey(sk),
|
||||||
}, difficulty);
|
},
|
||||||
|
difficulty
|
||||||
const signedEvent = finishEvent(event, sk);
|
});
|
||||||
await publish(signedEvent);
|
|
||||||
|
|
||||||
setComment("")
|
|
||||||
setFile("")
|
|
||||||
} catch (error) {
|
|
||||||
setComment(comment + " " + error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (messageFromWorker) {
|
||||||
|
try {
|
||||||
|
const signedEvent = finishEvent(messageFromWorker, sk);
|
||||||
|
publish(signedEvent);
|
||||||
|
|
||||||
|
setComment("");
|
||||||
|
setFile("");
|
||||||
|
setSk(generatePrivateKey())
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
worker.terminate();
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
setComment(error + ' ' + comment);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [messageFromWorker]);
|
||||||
|
|
||||||
async function attachFile(file_input: File | null) {
|
async function attachFile(file_input: File | null) {
|
||||||
try {
|
try {
|
||||||
if (file_input) {
|
if (file_input) {
|
||||||
@ -55,6 +76,7 @@ const NewThreadCard: React.FC = () => {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<CardContainer>
|
<CardContainer>
|
||||||
|
{/* <p>Message from worker: {messageFromWorker}</p> */}
|
||||||
<form
|
<form
|
||||||
name="post"
|
name="post"
|
||||||
method="post"
|
method="post"
|
||||||
|
15
client/src/custom.d.ts
vendored
Normal file
15
client/src/custom.d.ts
vendored
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
// Make TypeScript treat *.worker.ts as a module
|
||||||
|
declare module 'worker-loader!*' {
|
||||||
|
class WebpackWorker extends Worker {
|
||||||
|
constructor();
|
||||||
|
}
|
||||||
|
|
||||||
|
export = WebpackWorker;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extend the default Worker type with the properties used in the worker
|
||||||
|
interface Worker {
|
||||||
|
new (stringUrl: string, options?: WorkerOptions): Worker;
|
||||||
|
postMessage: (message: any) => void;
|
||||||
|
}
|
||||||
|
|
74
client/src/powWorker.ts
Normal file
74
client/src/powWorker.ts
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
import { type UnsignedEvent, type Event, getEventHash } from 'nostr-tools'
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-restricted-globals
|
||||||
|
const ctx: Worker = self as any;
|
||||||
|
|
||||||
|
// Respond to message from parent thread
|
||||||
|
ctx.addEventListener('message', (event) => {
|
||||||
|
console.log("Received message in worker:", event.data);
|
||||||
|
|
||||||
|
const { unsigned, difficulty } = event.data;
|
||||||
|
|
||||||
|
const result = minePow(unsigned, difficulty);
|
||||||
|
console.log("Mining result:", result);
|
||||||
|
|
||||||
|
// Post the mined event back to the main thread
|
||||||
|
ctx.postMessage(result);
|
||||||
|
});
|
||||||
|
|
||||||
|
ctx.onerror = function(e) {
|
||||||
|
console.error("Worker error:", e);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Get POW difficulty from a Nostr hex ID. */
|
||||||
|
export function getPow(hex: string): number {
|
||||||
|
let count = 0
|
||||||
|
|
||||||
|
for (let i = 0; i < hex.length; i++) {
|
||||||
|
const nibble = parseInt(hex[i], 16)
|
||||||
|
if (nibble === 0) {
|
||||||
|
count += 4
|
||||||
|
} else {
|
||||||
|
count += Math.clz32(nibble) - 28
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mine an event with the desired POW. This function mutates the event.
|
||||||
|
* Note that this operation is synchronous and should be run in a worker context to avoid blocking the main thread.
|
||||||
|
*
|
||||||
|
* Adapted from Snort: https://git.v0l.io/Kieran/snort/src/commit/4df6c19248184218c4c03728d61e94dae5f2d90c/packages/system/src/pow-util.ts#L14-L36
|
||||||
|
*/
|
||||||
|
export function minePow<K extends number>(unsigned: UnsignedEvent<K>, difficulty: number): Omit<Event<K>, 'sig'> {
|
||||||
|
let count = 0
|
||||||
|
|
||||||
|
const event = unsigned as Omit<Event<K>, 'sig'>
|
||||||
|
const tag = ['nonce', count.toString(), difficulty.toString()]
|
||||||
|
|
||||||
|
event.tags.push(tag)
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const now = Math.floor(new Date().getTime() / 1000)
|
||||||
|
|
||||||
|
if (now !== event.created_at) {
|
||||||
|
count = 0
|
||||||
|
event.created_at = now
|
||||||
|
}
|
||||||
|
|
||||||
|
tag[1] = (++count).toString()
|
||||||
|
|
||||||
|
event.id = getEventHash(event)
|
||||||
|
|
||||||
|
if (getPow(event.id) >= difficulty) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return event
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ctx;
|
@ -4,7 +4,8 @@
|
|||||||
"lib": [
|
"lib": [
|
||||||
"dom",
|
"dom",
|
||||||
"dom.iterable",
|
"dom.iterable",
|
||||||
"esnext"
|
"esnext",
|
||||||
|
"webworker"
|
||||||
],
|
],
|
||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
|
Loading…
Reference in New Issue
Block a user