Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- importScripts("cn.js"); // imports the "glue" interface generated by emscripten
- // Webassembly cryptonight hash_cn function wrapper.
- // First arg is the name of the function, the second arg is the return type
- // Third arg is an array with the type of each parameter of the function
- const hash_cn = Module.cwrap("hash_cn", "string", [
- "string",
- "number",
- "number",
- "number",
- ]);
- function zeroPad(num, places) {
- var zero = places - num.toString().length + 1;
- return Array(+(zero > 0 && zero)).join("0") + num;
- }
- function hex2int(s) {
- return parseInt(
- s
- .match(/[a-fA-F0-9]{2}/g)
- .reverse()
- .join(""),
- 16
- );
- }
- function int2hex(i) {
- return zeroPad(i.toString(16), 8)
- .match(/[a-fA-F0-9]{2}/g)
- .reverse()
- .join("");
- }
- function getRandomInt(min, max) {
- return Math.floor(Math.random() * (max - min + 1)) + min;
- }
- onmessage = ({ data }) => {
- var jbthrt = data;
- var job = jbthrt.job;
- var throttlePercent = jbthrt.throttle;
- var bsuccess = false;
- var hash = "";
- var hexnonce = 0;
- var calcHash = function () {
- if (job !== null) {
- var target = hex2int(job.target);
- var inonce = getRandomInt(0, 0xffffffff);
- hexnonce = int2hex(inonce);
- var blob =
- job.blob.substring(0, 78) +
- hexnonce +
- job.blob.substring(86, job.blob.length);
- try {
- if (job.algo === "cn") hash = hash_cn(blob, 0, job.variant, job.height);
- else if (job.algo === "cn-lite")
- hash = hash_cn(blob, 1, job.variant, job.height);
- else if (job.algo === "cn-pico")
- hash = hash_cn(blob, 2, job.variant, job.height);
- else if (job.algo === "cn-half")
- hash = hash_cn(blob, 3, job.variant, job.height);
- else if (job.algo === "cn-rwz")
- hash = hash_cn(blob, 4, job.variant, job.height);
- else throw "algorithm not supported!";
- var hashval = hex2int(hash.substring(56, 64));
- bsuccess = hashval < target;
- } catch (err) {
- console.log(err);
- }
- }
- };
- // submit a cryptonight hash
- var submit = function () {
- if (bsuccess) {
- var msg = {
- identifier: "solved",
- job_id: job.job_id,
- nonce: hexnonce,
- result: hash,
- };
- postMessage(JSON.stringify(msg));
- } else {
- postMessage("nothing");
- }
- };
- if (throttlePercent === 0) {
- calcHash();
- submit();
- } else {
- const t0 = performance.now();
- calcHash();
- const dt = performance.now() - t0;
- const sleepTime = Math.round(
- (throttlePercent / (100 - throttlePercent + 10)) * dt
- );
- setTimeout(submit, sleepTime);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement