nostr-dev-kit / ndk

Nostr Development Kit with outbox-model support
https://nostr-dev-kit.github.io/ndk/
MIT License
366 stars 99 forks source link

adding web worker-based POW to NDK #194

Closed arkin0x closed 7 months ago

arkin0x commented 8 months ago

I've developed a web-worker based proof-of-work for ONOSENDAI and wanted to contribute it to NDK.

This allows you to call ndkevent.pow(5) to get 5 leading zeroes on your event id.

There are a few little technical problems I could use help with that are unrelated to the actual functionality. TypeScript throws when trying to build because of the pow.worker.js. I haven't yet figured out how to get this working properly.

When using Vite, you add "?worker" to your worker import and Vite does something magical to make it work fine. But NDK uses a different build process so I'm not sure how to fix this. The Turbo docs didn't mention anything about importing workers.

I haven't yet had a chance to try and implement the advice in this stack overflow answer but it may help, although I was nervous about editing the tsconfig: https://stackoverflow.com/questions/56356655/structuring-a-typescript-project-with-workers

If I could kindly get some assistance with this worker issue, then we'll have slick POW built into NDK! 🚀

arkin0x commented 7 months ago

I've added pow.worker.ts which will definitely provide more clarity. It was .gitignored as a .js file and I didn't realize it.

The mining works by serializing the event, finding the byte indices of the nonce, and then converting it to binary to send to the worker. The worker hashes and updates the nonce in the binary range, which alleviates the memory leaks caused by invoking TextEncoder() for every hash inside a web worker.