I am getting the error:
events.js:291
throw er; // Unhandled 'error' event
^
Error: Cannot find module '/usr/local/lib/node_modules/jest/node_modules/jest-runtime/build/get-block-at-difficulty.worker.ts'
Require stack:
- /Users/robertotomas/Public/Github/learning-chain/node_modules/ts-worker/dist/register.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
at Function.Module._load (internal/modules/cjs/loader.js:725:27)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (/Users/robertotomas/Public/Github/learning-chain/node_modules/ts-worker/dist/register.js:4:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
Emitted 'error' event on process instance at:
at emitUnhandledRejectionOrErr (internal/event_target.js:542:11)
at MessagePort.[nodejs.internal.kHybridDispatch] (internal/event_target.js:357:9)
at MessagePort.exports.emitMessage (internal/per_context/messageport.js:18:26) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/Users/robertotomas/Public/Github/learning-chain/node_modules/ts-worker/dist/register.js'
]
}
The directory structure I am working in is like:
src/blockchain/
- utilities.ts
- utilities.spec.ts
- get-block-at-difficulty.worker.ts
so, the worker is in the same directory as the utilities library where it is being referenced.
I have the worker:
get-block-at-difficulty.worker.ts
import { parentPort, workerData } from 'worker_threads'
import { getBlockAtDifficulty } from './utilities'
const block = workerData.args[0]
const difficulty = workerData.args[1]
const index = workerData.args[2]
const step = workerData.args[3]
parentPort!.postMessage(getBlockAtDifficulty(block, difficulty, index, step))
and it is relying on utilities.ts where it is also being called. see this excerpt:
utilities.ts
export function detect(hash: string, difficulty: number) {
let i, b
for (i = 0, b = hash.length; i < b; i++) {
if (hash[i] !== '0') {
break;
}
}
return i === difficulty;
}
export function getBlockAtDifficulty(block: Partial<Block>, difficulty: number, index = 0, step = 1) {
let result: Block
let nonce = index
do {
result = new Block({ ...block, nonce: String(nonce) })
nonce += step
} while (!detect(Hash.encode(String(result)), difficulty))
return result
}
export interface MultiServiceThreadpoolResolution { [threadpool: string]: any }
export class MultiService {
private static resolver = new Subject<MultiServiceThreadpoolResolution>()
static resolver$: Observable<MultiServiceThreadpoolResolution>
static initialize() {
MultiService.resolver$ = MultiService.resolver.asObservable()
}
static resolve(pr: Promise<any>, threadpool: string) {
pr
.then(v => MultiService.resolver.next({ [threadpool]: v }))
.catch(e => console.error(e))
}
}
MultiService.initialize()
/**
* spawns threads to resolve hash at difficulty, publishing result in
* MultiService
* @param block Block to resolve hash of
* @param difficulty Difficulty of hash to resolve
* @returns uuid of multiservice to subscribe to
* usage:
* const multiService = new MultiService()
* const task = getBlockAtDifficultyMultiThreaded(myBlock, someDifficulty)
* multiService.resolve$
* .pipe(first(resolution => resolution.hasOwnProperty(task)))
* .subscribe(resolution => onSuccess(resolution[task]))
*/
export function getBlockAtDifficultyMultiThreaded(block: Partial<Block>, difficulty: number): UUID {
const uuid = uuidV4() // our task identifier
const workers: Array<Worker> = []
const threads = os.cpus()
threads.forEach((_, i) => {
const args = [block, difficulty, i, threads]
const worker: Worker = TSWorker('get-block-at-difficulty.worker.ts', {
workerData: { args }
});
workers.push(worker)
worker.on('message', (result: Block) => {
MultiService.resolve(new Promise(res => res(result)), uuid)
workers.forEach(w => w.terminate())
})
})
return uuid
}
I have a jest test for this:
utilties.spec.ts
describe('getBlockAtDifficultyMultithreaded', () => {
it('should produce a hash multithreaded', done => {
const chain: Array<Block> = []
const data = ['Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.']
chain.push(Block.factoryGenesisBlock())
const task = getBlockAtDifficultyMultiThreaded(factoryNextBlock({ data }, chain), 8)
MultiService.resolver$.pipe(first(resolution => resolution.hasOwnProperty(task))).subscribe(resolution => {
chain.push(resolution[task])
console.log(Hash.encode(String(chain[1])))
expect(difficulty(Hash.encode(String(chain[1])))).toEqual(8)
done()
})
})
})
I thought to try specifying the absolute path:
const worker: Worker = TSWorker([__dirname, 'get-block-at-difficulty.worker.ts'].join('/'), {
workerData: { args }
});
but this produces basically the same error:
Error: Cannot find module '/usr/local/lib/node_modules/jest/node_modules/jest-runtime/build/Users/robertotomas/Public/Github/learning-chain/src/blockchain/get-block-at-difficulty.worker.ts'