From 74b7e1fe143af72da9a0c21733505b69f5b47f42 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Fri, 7 Jul 2017 21:45:28 -0400 Subject: [PATCH 01/19] updated buffers to Node API 8.1.3 --- lib/algoProperties.js | 4 +- lib/util.js | 105 +++++++++++++++++------------------------- package-lock.json | 25 ++++++++++ package.json | 6 +-- 4 files changed, 71 insertions(+), 69 deletions(-) create mode 100644 package-lock.json diff --git a/lib/algoProperties.js b/lib/algoProperties.js index 7725ee62..cb3658e6 100644 --- a/lib/algoProperties.js +++ b/lib/algoProperties.js @@ -39,7 +39,7 @@ var algos = module.exports = global.algos = { } } }, - 'scrypt-jane': { + /*'scrypt-jane': { multiplier: Math.pow(2, 16), hash: function(coinConfig){ var nTimestamp = coinConfig.chainStartTime || 1367991200; @@ -49,7 +49,7 @@ var algos = module.exports = global.algos = { return multiHashing.scryptjane(data, nTime, nTimestamp, nMin, nMax); } } - }, + },*/ 'scrypt-n': { multiplier: Math.pow(2, 16), hash: function(coinConfig){ diff --git a/lib/util.js b/lib/util.js index 394d0599..6f93b2d4 100644 --- a/lib/util.js +++ b/lib/util.js @@ -7,7 +7,7 @@ var bignum = require('bignum'); exports.addressFromEx = function(exAddress, ripdm160Key){ try { var versionByte = exports.getVersionByte(exAddress); - var addrBase = Buffer.concat([versionByte, new Buffer(ripdm160Key, 'hex')]); + var addrBase = Buffer.concat([versionByte, Buffer.from(ripdm160Key, 'hex')]); var checksum = exports.sha256d(addrBase).slice(0, 4); var address = Buffer.concat([addrBase, checksum]); return base58.encode(address); @@ -34,14 +34,14 @@ exports.sha256d = function(buffer){ }; exports.reverseBuffer = function(buff){ - var reversed = new Buffer(buff.length); + var reversed = Buffer.alloc(buff.length); for (var i = buff.length - 1; i >= 0; i--) reversed[buff.length - i - 1] = buff[i]; return reversed; }; exports.reverseHex = function(hex){ - return exports.reverseBuffer(new Buffer(hex, 'hex')).toString('hex'); + return exports.reverseBuffer(Buffer.from(hex, 'hex')).toString('hex'); }; exports.reverseByteOrder = function(buff){ @@ -51,13 +51,13 @@ exports.reverseByteOrder = function(buff){ exports.uint256BufferFromHash = function(hex){ - var fromHex = new Buffer(hex, 'hex'); + var fromHex; - if (fromHex.length != 32){ - var empty = new Buffer(32); - empty.fill(0); - fromHex.copy(empty); - fromHex = empty; + if (hex != 0) { + fromHex = Buffer.from(hex, 'hex'); + } else { + fromHex = Buffer.alloc(32); + fromHex.fill(0); } return exports.reverseBuffer(fromHex); @@ -74,21 +74,21 @@ Defined in bitcoin protocol here: */ exports.varIntBuffer = function(n){ if (n < 0xfd) - return new Buffer([n]); + return Buffer.from([n]); else if (n <= 0xffff){ - var buff = new Buffer(3); + var buff = Buffer.alloc(3); buff[0] = 0xfd; buff.writeUInt16LE(n, 1); return buff; } else if (n <= 0xffffffff){ - var buff = new Buffer(5); + var buff = Buffer.alloc(5); buff[0] = 0xfe; buff.writeUInt32LE(n, 1); return buff; } else{ - var buff = new Buffer(9); + var buff = Buffer.alloc(9); buff[0] = 0xff; exports.packUInt16LE(n).copy(buff, 1); return buff; @@ -96,7 +96,7 @@ exports.varIntBuffer = function(n){ }; exports.varStringBuffer = function(string){ - var strBuff = new Buffer(string); + var strBuff = Buffer.from(string); return Buffer.concat([exports.varIntBuffer(strBuff.length), strBuff]); }; @@ -108,33 +108,10 @@ Used to format height and date when putting into script signature: */ exports.serializeNumber = function(n){ - /* Old version that is bugged - if (n < 0xfd){ - var buff = new Buffer(2); - buff[0] = 0x1; - buff.writeUInt8(n, 1); - return buff; - } - else if (n <= 0xffff){ - var buff = new Buffer(4); - buff[0] = 0x3; - buff.writeUInt16LE(n, 1); - return buff; - } - else if (n <= 0xffffffff){ - var buff = new Buffer(5); - buff[0] = 0x4; - buff.writeUInt32LE(n, 1); - return buff; - } - else{ - return Buffer.concat([new Buffer([0x9]), binpack.packUInt64(n, 'little')]); - }*/ - - //New version from TheSeven - if (n >= 1 && n <= 16) return new Buffer([0x50 + n]); + //Version from TheSeven + if (n >= 1 && n <= 16) return Buffer.from([0x50 + n]); var l = 1; - var buff = new Buffer(9); + var buff = Buffer.alloc(9); while (n > 0x7f) { buff.writeUInt8(n & 0xff, l++); @@ -154,58 +131,58 @@ exports.serializeString = function(s){ if (s.length < 253) return Buffer.concat([ - new Buffer([s.length]), - new Buffer(s) + Buffer.from([s.length]), + Buffer.from(s) ]); else if (s.length < 0x10000) return Buffer.concat([ - new Buffer([253]), + Buffer.from([253]), exports.packUInt16LE(s.length), - new Buffer(s) + Buffer.from(s) ]); else if (s.length < 0x100000000) return Buffer.concat([ - new Buffer([254]), + Buffer.from([254]), exports.packUInt32LE(s.length), - new Buffer(s) + Buffer.from(s) ]); else return Buffer.concat([ - new Buffer([255]), + Buffer.from([255]), exports.packUInt16LE(s.length), - new Buffer(s) + Buffer.from(s) ]); }; exports.packUInt16LE = function(num){ - var buff = new Buffer(2); + var buff = Buffer.alloc(2); buff.writeUInt16LE(num, 0); return buff; }; exports.packInt32LE = function(num){ - var buff = new Buffer(4); + var buff = Buffer.alloc(4); buff.writeInt32LE(num, 0); return buff; }; exports.packInt32BE = function(num){ - var buff = new Buffer(4); + var buff = Buffer.alloc(4); buff.writeInt32BE(num, 0); return buff; }; exports.packUInt32LE = function(num){ - var buff = new Buffer(4); + var buff = Buffer.alloc(4); buff.writeUInt32LE(num, 0); return buff; }; exports.packUInt32BE = function(num){ - var buff = new Buffer(4); + var buff = Buffer.alloc(4); buff.writeUInt32BE(num, 0); return buff; }; exports.packInt64LE = function(num){ - var buff = new Buffer(8); + var buff = Buffer.alloc(8); buff.writeUInt32LE(num % Math.pow(2, 32), 0); buff.writeUInt32LE(Math.floor(num / Math.pow(2, 32)), 4); return buff; @@ -245,17 +222,17 @@ exports.pubkeyToScript = function(key){ console.error('Invalid pubkey: ' + key); throw new Error(); } - var pubkey = new Buffer(35); + var pubkey = Buffer.alloc(35); pubkey[0] = 0x21; pubkey[34] = 0xac; - new Buffer(key, 'hex').copy(pubkey, 1); + Buffer.from(key, 'hex').copy(pubkey, 1); return pubkey; }; exports.miningKeyToScript = function(key){ - var keyBuffer = new Buffer(key, 'hex'); - return Buffer.concat([new Buffer([0x76, 0xa9, 0x14]), keyBuffer, new Buffer([0x88, 0xac])]); + var keyBuffer = Buffer.from(key, 'hex'); + return Buffer.concat([Buffer.from([0x76, 0xa9, 0x14]), keyBuffer, Buffer.from([0x88, 0xac])]); }; /* @@ -277,7 +254,7 @@ exports.addressToScript = function(addr){ var pubkey = decoded.slice(1,-4); - return Buffer.concat([new Buffer([0x76, 0xa9, 0x14]), pubkey, new Buffer([0x88, 0xac])]); + return Buffer.concat([Buffer.from([0x76, 0xa9, 0x14]), pubkey, Buffer.from([0x88, 0xac])]); }; @@ -324,7 +301,7 @@ exports.shiftMax256Right = function(shiftRight){ } - return new Buffer(octets); + return Buffer.from(octets); }; @@ -332,9 +309,9 @@ exports.bufferToCompactBits = function(startingBuff){ var bigNum = bignum.fromBuffer(startingBuff); var buff = bigNum.toBuffer(); - buff = buff.readUInt8(0) > 0x7f ? Buffer.concat([new Buffer([0x00]), buff]) : buff; + buff = buff.readUInt8(0) > 0x7f ? Buffer.concat([Buffer.from([0x00]), buff]) : buff; - buff = Buffer.concat([new Buffer([buff.length]), buff]); + buff = Buffer.concat([Buffer.from([buff.length]), buff]); var compact = buff.slice(0, 4); return compact; }; @@ -358,14 +335,14 @@ exports.bignumFromBitsBuffer = function(bitsBuff){ }; exports.bignumFromBitsHex = function(bitsString){ - var bitsBuff = new Buffer(bitsString, 'hex'); + var bitsBuff = Buffer.from(bitsString, 'hex'); return exports.bignumFromBitsBuffer(bitsBuff); }; exports.convertBitsToBuff = function(bitsBuff){ var target = exports.bignumFromBitsBuffer(bitsBuff); var resultBuff = target.toBuffer(); - var buff256 = new Buffer(32); + var buff256 = Buffer.alloc(32); buff256.fill(0); resultBuff.copy(buff256, buff256.length - resultBuff.length); return buff256; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..f9b16327 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,25 @@ +{ + "name": "stratum-pool", + "version": "0.1.9", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "bindings": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.2.1.tgz", + "integrity": "sha1-FK1hE4EtLTfXLme0ystLtyZQXxE=" + }, + "multi-hashing": { + "version": "git+https://github.com/krisklosterman/node-multi-hashing.git#58de58a2977b87a8b48292fdf2feae06c81b085f", + "requires": { + "bindings": "1.2.1", + "nan": "2.6.2" + } + }, + "nan": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.6.2.tgz", + "integrity": "sha1-5P805slf37WuzAjeZZb0NgWn20U=" + } + } +} diff --git a/package.json b/package.json index 4bc8904e..ff78b192 100644 --- a/package.json +++ b/package.json @@ -28,10 +28,10 @@ "url": "https://github.com/zone117x/node-stratum-pool.git" }, "dependencies": { - "multi-hashing": "git://github.com/zone117x/node-multi-hashing.git", - "bignum": "*", + "async": "*", "base58-native": "*", - "async": "*" + "bignum": "*", + "multi-hashing": "git+https://github.com/krisklosterman/node-multi-hashing.git" }, "engines": { "node": ">=0.10" From 3c4542f294f9e98f15e9fd046bfd92bb840ca68a Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Sun, 9 Jul 2017 22:13:41 -0400 Subject: [PATCH 02/19] pushing to test on different platoform --- lib/blockTemplate.js | 12 ++--- lib/jobManager.js | 6 +-- lib/peer.js | 18 +++---- lib/transactions.js | 126 ++----------------------------------------- package-lock.json | 25 --------- package.json | 2 +- 6 files changed, 24 insertions(+), 165 deletions(-) delete mode 100644 package-lock.json diff --git a/lib/blockTemplate.js b/lib/blockTemplate.js index 723e0cfa..89a3079c 100644 --- a/lib/blockTemplate.js +++ b/lib/blockTemplate.js @@ -32,12 +32,12 @@ var BlockTemplate = module.exports = function BlockTemplate(jobId, rpcData, pool } function getVoteData(){ - if (!rpcData.masternode_payments) return new Buffer([]); + if (!rpcData.masternode_payments) return Buffer.from([]); return Buffer.concat( [util.varIntBuffer(rpcData.votes.length)].concat( rpcData.votes.map(function (vt) { - return new Buffer(vt, 'hex'); + return Buffer.from(vt, 'hex'); }) ) ); @@ -59,9 +59,9 @@ var BlockTemplate = module.exports = function BlockTemplate(jobId, rpcData, pool - this.prevHashReversed = util.reverseByteOrder(new Buffer(rpcData.previousblockhash, 'hex')).toString('hex'); + this.prevHashReversed = util.reverseByteOrder(Buffer.from(rpcData.previousblockhash, 'hex')).toString('hex'); this.transactionData = Buffer.concat(rpcData.transactions.map(function(tx){ - return new Buffer(tx.data, 'hex'); + return Buffer.from(tx.data, 'hex'); })); this.merkleTree = new merkleTree(getTransactionBuffers(rpcData.transactions)); this.merkleBranch = getMerkleHashes(this.merkleTree.steps); @@ -87,7 +87,7 @@ var BlockTemplate = module.exports = function BlockTemplate(jobId, rpcData, pool //https://en.bitcoin.it/wiki/Protocol_specification#Block_Headers this.serializeHeader = function(merkleRoot, nTime, nonce){ - var header = new Buffer(80); + var header = Buffer.alloc(80); var position = 0; header.write(nonce, position, 4, 'hex'); header.write(rpcData.bits, position += 4, 4, 'hex'); @@ -110,7 +110,7 @@ var BlockTemplate = module.exports = function BlockTemplate(jobId, rpcData, pool getVoteData(), //POS coins require a zero byte appended to block which the daemon replaces with the signature - new Buffer(reward === 'POS' ? [0] : []) + Buffer.from(reward === 'POS' ? [0] : []) ]); }; diff --git a/lib/jobManager.js b/lib/jobManager.js index cbcfc48e..10275e9f 100644 --- a/lib/jobManager.js +++ b/lib/jobManager.js @@ -58,7 +58,7 @@ var JobManager = module.exports = function JobManager(options){ //public members this.extraNonceCounter = new ExtraNonceCounter(options.instanceId); - this.extraNoncePlaceholder = new Buffer('f000000ff111111f', 'hex'); + this.extraNoncePlaceholder = Buffer.from('f000000ff111111f', 'hex'); this.extraNonce2Size = this.extraNoncePlaceholder.length - this.extraNonceCounter.size; this.currentJob; @@ -213,8 +213,8 @@ var JobManager = module.exports = function JobManager(options){ } - var extraNonce1Buffer = new Buffer(extraNonce1, 'hex'); - var extraNonce2Buffer = new Buffer(extraNonce2, 'hex'); + var extraNonce1Buffer = Buffer.from(extraNonce1, 'hex'); + var extraNonce2Buffer = Buffer.from(extraNonce2, 'hex'); var coinbaseBuffer = job.serializeCoinbase(extraNonce1Buffer, extraNonce2Buffer); var coinbaseHash = coinbaseHasher(coinbaseBuffer); diff --git a/lib/peer.js b/lib/peer.js index 5435c3b9..7ce61e0e 100644 --- a/lib/peer.js +++ b/lib/peer.js @@ -9,7 +9,7 @@ var util = require('./util.js'); var fixedLenStringBuffer = function(s, len) { - var buff = new Buffer(len); + var buff = Buffer.alloc(len); buff.fill(0); buff.write(s); return buff; @@ -26,7 +26,7 @@ var commandStringBuffer = function (s) { - callback returns 1) data buffer and 2) lopped/over-read data */ var readFlowingBytes = function (stream, amount, preRead, callback) { - var buff = preRead ? preRead : new Buffer([]); + var buff = preRead ? preRead : Buffer.from([]); var readData = function (data) { buff = Buffer.concat([buff, data]); @@ -39,14 +39,14 @@ var readFlowingBytes = function (stream, amount, preRead, callback) { stream.once('data', readData); }; - readData(new Buffer([])); + readData(Buffer.from([])); }; var Peer = module.exports = function (options) { var _this = this; var client; - var magic = new Buffer(options.testnet ? options.coin.peerMagicTestnet : options.coin.peerMagic, 'hex'); + var magic = Buffer.from(options.testnet ? options.coin.peerMagicTestnet : options.coin.peerMagic, 'hex'); var magicInt = magic.readUInt32LE(0); var verack = false; var validConnectionConfig = true; @@ -58,14 +58,14 @@ var Peer = module.exports = function (options) { block: 2 }; - var networkServices = new Buffer('0100000000000000', 'hex'); //NODE_NETWORK services (value 1 packed as uint64) - var emptyNetAddress = new Buffer('010000000000000000000000000000000000ffff000000000000', 'hex'); + var networkServices = Buffer.from('0100000000000000', 'hex'); //NODE_NETWORK services (value 1 packed as uint64) + var emptyNetAddress = Buffer.from('010000000000000000000000000000000000ffff000000000000', 'hex'); var userAgent = util.varStringBuffer('/node-stratum/'); - var blockStartHeight = new Buffer('00000000', 'hex'); //block start_height, can be empty + var blockStartHeight = Buffer.from('00000000', 'hex'); //block start_height, can be empty //If protocol version is new enough, add do not relay transactions flag byte, outlined in BIP37 //https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki#extensions-to-existing-messages - var relayTransactions = options.p2p.disableTransactions === true ? new Buffer([false]) : new Buffer([]); + var relayTransactions = options.p2p.disableTransactions === true ? Buffer.from([false]) : Buffer.from([]); var commands = { version: commandStringBuffer('version'), @@ -127,7 +127,7 @@ var Peer = module.exports = function (options) { if (header.readUInt32LE(0) === magicInt) { beginReadingMessage(header); } else { - beginReadingMessage(new Buffer([])); + beginReadingMessage(Buffer.from([])); } return; } diff --git a/lib/transactions.js b/lib/transactions.js index 76cc1e8c..dcd9daa5 100644 --- a/lib/transactions.js +++ b/lib/transactions.js @@ -1,121 +1,5 @@ var util = require('./util.js'); - -/* -function Transaction(params){ - - var version = params.version || 1, - inputs = params.inputs || [], - outputs = params.outputs || [], - lockTime = params.lockTime || 0; - - - this.toBuffer = function(){ - return Buffer.concat([ - binpack.packUInt32(version, 'little'), - util.varIntBuffer(inputs.length), - Buffer.concat(inputs.map(function(i){ return i.toBuffer() })), - util.varIntBuffer(outputs.length), - Buffer.concat(outputs.map(function(o){ return o.toBuffer() })), - binpack.packUInt32(lockTime, 'little') - ]); - }; - - this.inputs = inputs; - this.outputs = outputs; - -} - -function TransactionInput(params){ - - var prevOutHash = params.prevOutHash || 0, - prevOutIndex = params.prevOutIndex, - sigScript = params.sigScript, - sequence = params.sequence || 0; - - - this.toBuffer = function(){ - sigScriptBuffer = sigScript.toBuffer(); - console.log('scriptSig length ' + sigScriptBuffer.length); - return Buffer.concat([ - util.uint256BufferFromHash(prevOutHash), - binpack.packUInt32(prevOutIndex, 'little'), - util.varIntBuffer(sigScriptBuffer.length), - sigScriptBuffer, - binpack.packUInt32(sequence) - ]); - }; -} - -function TransactionOutput(params){ - - var value = params.value, - pkScriptBuffer = params.pkScriptBuffer; - - this.toBuffer = function(){ - return Buffer.concat([ - binpack.packInt64(value, 'little'), - util.varIntBuffer(pkScriptBuffer.length), - pkScriptBuffer - ]); - }; -} - -function ScriptSig(params){ - - var height = params.height, - flags = params.flags, - extraNoncePlaceholder = params.extraNoncePlaceholder; - - this.toBuffer = function(){ - - return Buffer.concat([ - util.serializeNumber(height), - new Buffer(flags, 'hex'), - util.serializeNumber(Date.now() / 1000 | 0), - new Buffer([extraNoncePlaceholder.length]), - extraNoncePlaceholder, - util.serializeString('/nodeStratum/') - ]); - } -}; - - -var Generation = exports.Generation = function Generation(rpcData, publicKey, extraNoncePlaceholder){ - - var tx = new Transaction({ - inputs: [new TransactionInput({ - prevOutIndex : Math.pow(2, 32) - 1, - sigScript : new ScriptSig({ - height : rpcData.height, - flags : rpcData.coinbaseaux.flags, - extraNoncePlaceholder : extraNoncePlaceholder - }) - })], - outputs: [new TransactionOutput({ - value : rpcData.coinbasevalue, - pkScriptBuffer : publicKey - })] - }); - - var txBuffer = tx.toBuffer(); - var epIndex = buffertools.indexOf(txBuffer, extraNoncePlaceholder); - var p1 = txBuffer.slice(0, epIndex); - var p2 = txBuffer.slice(epIndex + extraNoncePlaceholder.length); - - this.transaction = tx; - this.coinbase = [p1, p2]; - -}; -*/ - - -/* - ^^^^ The above code was a bit slow. The below code is uglier but optimized. - */ - - - /* This function creates the generation transaction that accepts the reward for successfully mining a new block. @@ -167,7 +51,7 @@ var generateOutputTransactions = function(poolRecipient, recipients, rpcData){ ])); if (rpcData.default_witness_commitment !== undefined){ - witness_commitment = new Buffer(rpcData.default_witness_commitment, 'hex'); + witness_commitment = Buffer.from(rpcData.default_witness_commitment, 'hex'); txOutputBuffers.unshift(Buffer.concat([ util.packInt64LE(0), util.varIntBuffer(witness_commitment.length), @@ -196,19 +80,19 @@ exports.CreateGeneration = function(rpcData, publicKey, extraNoncePlaceholder, r //Only required for POS coins var txTimestamp = reward === 'POS' ? - util.packUInt32LE(rpcData.curtime) : new Buffer([]); + util.packUInt32LE(rpcData.curtime) : Buffer.from([]); //For coins that support/require transaction comments var txComment = txMessages === true ? util.serializeString('https://github.com/zone117x/node-stratum') : - new Buffer([]); + Buffer.from([]); var scriptSigPart1 = Buffer.concat([ util.serializeNumber(rpcData.height), - new Buffer(rpcData.coinbaseaux.flags, 'hex'), + Buffer.from(rpcData.coinbaseaux.flags, 'hex'), util.serializeNumber(Date.now() / 1000 | 0), - new Buffer([extraNoncePlaceholder.length]) + Buffer.from([extraNoncePlaceholder.length]) ]); var scriptSigPart2 = util.serializeString('/nodeStratum/'); diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index f9b16327..00000000 --- a/package-lock.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "stratum-pool", - "version": "0.1.9", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "bindings": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.2.1.tgz", - "integrity": "sha1-FK1hE4EtLTfXLme0ystLtyZQXxE=" - }, - "multi-hashing": { - "version": "git+https://github.com/krisklosterman/node-multi-hashing.git#58de58a2977b87a8b48292fdf2feae06c81b085f", - "requires": { - "bindings": "1.2.1", - "nan": "2.6.2" - } - }, - "nan": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/nan/-/nan-2.6.2.tgz", - "integrity": "sha1-5P805slf37WuzAjeZZb0NgWn20U=" - } - } -} diff --git a/package.json b/package.json index ff78b192..af307d16 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "async": "*", "base58-native": "*", "bignum": "*", - "multi-hashing": "git+https://github.com/krisklosterman/node-multi-hashing.git" + "multi-hashing": "git://github.com/krisklosterman/node-multi-hashing.git" }, "engines": { "node": ">=0.10" From 2ef76aa7932837d136a507b119742bedd07c2ee4 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Mon, 10 Jul 2017 10:04:29 -0400 Subject: [PATCH 03/19] added some loggin for debuging --- .gitignore | 3 ++- lib/jobManager.js | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index d35bbf75..1b18ef57 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ node_modules/ -.idea/ \ No newline at end of file +.idea/ +.vscode/ \ No newline at end of file diff --git a/lib/jobManager.js b/lib/jobManager.js index 10275e9f..66413daf 100644 --- a/lib/jobManager.js +++ b/lib/jobManager.js @@ -212,6 +212,7 @@ var JobManager = module.exports = function JobManager(options){ return shareError([22, 'duplicate share']); } + console.log(jobId + " | " + previousDifficulty + " | " + difficulty + " | " + extraNonce1 + " | " + extraNonce2 + " | " + nTime + " | " + nonce + " | " + ipAddress + " | " + port + " | " + workerName); var extraNonce1Buffer = Buffer.from(extraNonce1, 'hex'); var extraNonce2Buffer = Buffer.from(extraNonce2, 'hex'); @@ -233,10 +234,23 @@ var JobManager = module.exports = function JobManager(options){ var blockDiffAdjusted = job.difficulty * shareMultiplier; + console.log(extraNonce1Buffer); + console.log(extraNonce2Buffer); + console.log(coinbaseBuffer); + console.log(coinbaseHash); + console.log(merkleRoot); + console.log(headerBuffer); + console.log(headerHash); + console.log(headerBigNum); + console.log(shareDiff); + console.log(blockDiffAdjusted); + //Check if share is a block candidate (matched network difficulty) if (job.target.ge(headerBigNum)){ blockHex = job.serializeBlock(headerBuffer, coinbaseBuffer).toString('hex'); blockHash = blockHasher(headerBuffer, nTime).toString('hex'); + console.log(blockHex); + console.log(blockHash); } else { if (options.emitInvalidBlockHashes) From 3053926905c07535bacf9e27ece95140644cbff9 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Mon, 10 Jul 2017 15:09:13 -0400 Subject: [PATCH 04/19] testing --- lib/jobManager.js | 1 + lib/pool.js | 4 +++- package.json | 6 +++--- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/lib/jobManager.js b/lib/jobManager.js index 66413daf..685fbd4c 100644 --- a/lib/jobManager.js +++ b/lib/jobManager.js @@ -246,6 +246,7 @@ var JobManager = module.exports = function JobManager(options){ console.log(blockDiffAdjusted); //Check if share is a block candidate (matched network difficulty) + console.log("Job Target: " + job.target); if (job.target.ge(headerBigNum)){ blockHex = job.serializeBlock(headerBuffer, coinbaseBuffer).toString('hex'); blockHash = blockHasher(headerBuffer, nTime).toString('hex'); diff --git a/lib/pool.js b/lib/pool.js index 2b6ad4df..af02f697 100644 --- a/lib/pool.js +++ b/lib/pool.js @@ -627,6 +627,7 @@ var pool = module.exports = function pool(options, authorizeFn){ Object.keys(origStratumClients).forEach(function (subId) { stratumClients.push({subId: subId, client: origStratumClients[subId]}); }); + //TODO: Think of a way to use API 8's async/await and promises to replace async lib async.filter( stratumClients, filterFn, @@ -646,7 +647,8 @@ var pool = module.exports = function pool(options, authorizeFn){ ); }); } - ) + ); + }; diff --git a/package.json b/package.json index af307d16..d1e3f589 100644 --- a/package.json +++ b/package.json @@ -28,9 +28,9 @@ "url": "https://github.com/zone117x/node-stratum-pool.git" }, "dependencies": { - "async": "*", - "base58-native": "*", - "bignum": "*", + "async": "^2.5.0", + "base58-native": "^0.1.4", + "bignum": "^0.12.5", "multi-hashing": "git://github.com/krisklosterman/node-multi-hashing.git" }, "engines": { From 85fed70736dcecd298f9f7fb61e0da70d83c0c6a Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Mon, 10 Jul 2017 17:30:31 -0400 Subject: [PATCH 05/19] testing --- lib/util.js | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/util.js b/lib/util.js index 6f93b2d4..79df1af6 100644 --- a/lib/util.js +++ b/lib/util.js @@ -24,6 +24,7 @@ exports.getVersionByte = function(addr){ }; exports.sha256 = function(buffer){ + console.log('RUNNING NSP sha256 method'); var hash1 = crypto.createHash('sha256'); hash1.update(buffer); return hash1.digest(); From f5f8422592cc026cea18839934a22cf79120c845 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Tue, 11 Jul 2017 08:52:38 -0400 Subject: [PATCH 06/19] adding logging for testing --- lib/pool.js | 10 ++++++++++ lib/util.js | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/pool.js b/lib/pool.js index af02f697..a7cf1354 100644 --- a/lib/pool.js +++ b/lib/pool.js @@ -224,6 +224,8 @@ var pool = module.exports = function pool(options, authorizeFn){ */ function SubmitBlock(blockHex, callback){ + console.log("SUBMIT BLOCK: BlockHex: " + blockHex) + var rpcCommand, rpcArgs; if (options.hasSubmitMethod){ rpcCommand = 'submitblock'; @@ -249,6 +251,8 @@ var pool = module.exports = function pool(options, authorizeFn){ } else if (result.response === 'rejected') { emitErrorLog('Daemon instance ' + result.instance.index + ' rejected a supposedly valid block'); + console.log("NSP: SubmitBlock: Rejected"); + console.log(result); return; } } @@ -315,6 +319,9 @@ var pool = module.exports = function pool(options, authorizeFn){ before we emit the share, lets submit the block, then check if it was accepted using RPC getblock */ + console.log("NSP: OnShare: sharedata and blockhex following this"); + console.log(shareData); + console.log(blockHex); if (!isValidBlock) emitShare(); else{ @@ -329,6 +336,9 @@ var pool = module.exports = function pool(options, authorizeFn){ emitLog('Block notification via RPC after block submission'); }); + console.log("NSP: CheckBlockAccepted called: "); + console.log(isAccepted); + }); }); } diff --git a/lib/util.js b/lib/util.js index 79df1af6..e9f77690 100644 --- a/lib/util.js +++ b/lib/util.js @@ -24,9 +24,9 @@ exports.getVersionByte = function(addr){ }; exports.sha256 = function(buffer){ - console.log('RUNNING NSP sha256 method'); var hash1 = crypto.createHash('sha256'); hash1.update(buffer); + console.log("Running sha256 on nsp: " + hash1); return hash1.digest(); }; From ebc30bb11d6568b4013346f001260b910d8a1025 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Wed, 12 Jul 2017 12:05:41 -0400 Subject: [PATCH 07/19] removed all the testing comments --- lib/jobManager.js | 16 ---------------- lib/pool.js | 10 ---------- lib/util.js | 1 - 3 files changed, 27 deletions(-) diff --git a/lib/jobManager.js b/lib/jobManager.js index 685fbd4c..bb6d9cd8 100644 --- a/lib/jobManager.js +++ b/lib/jobManager.js @@ -212,8 +212,6 @@ var JobManager = module.exports = function JobManager(options){ return shareError([22, 'duplicate share']); } - console.log(jobId + " | " + previousDifficulty + " | " + difficulty + " | " + extraNonce1 + " | " + extraNonce2 + " | " + nTime + " | " + nonce + " | " + ipAddress + " | " + port + " | " + workerName); - var extraNonce1Buffer = Buffer.from(extraNonce1, 'hex'); var extraNonce2Buffer = Buffer.from(extraNonce2, 'hex'); @@ -234,24 +232,10 @@ var JobManager = module.exports = function JobManager(options){ var blockDiffAdjusted = job.difficulty * shareMultiplier; - console.log(extraNonce1Buffer); - console.log(extraNonce2Buffer); - console.log(coinbaseBuffer); - console.log(coinbaseHash); - console.log(merkleRoot); - console.log(headerBuffer); - console.log(headerHash); - console.log(headerBigNum); - console.log(shareDiff); - console.log(blockDiffAdjusted); - //Check if share is a block candidate (matched network difficulty) - console.log("Job Target: " + job.target); if (job.target.ge(headerBigNum)){ blockHex = job.serializeBlock(headerBuffer, coinbaseBuffer).toString('hex'); blockHash = blockHasher(headerBuffer, nTime).toString('hex'); - console.log(blockHex); - console.log(blockHash); } else { if (options.emitInvalidBlockHashes) diff --git a/lib/pool.js b/lib/pool.js index a7cf1354..af02f697 100644 --- a/lib/pool.js +++ b/lib/pool.js @@ -224,8 +224,6 @@ var pool = module.exports = function pool(options, authorizeFn){ */ function SubmitBlock(blockHex, callback){ - console.log("SUBMIT BLOCK: BlockHex: " + blockHex) - var rpcCommand, rpcArgs; if (options.hasSubmitMethod){ rpcCommand = 'submitblock'; @@ -251,8 +249,6 @@ var pool = module.exports = function pool(options, authorizeFn){ } else if (result.response === 'rejected') { emitErrorLog('Daemon instance ' + result.instance.index + ' rejected a supposedly valid block'); - console.log("NSP: SubmitBlock: Rejected"); - console.log(result); return; } } @@ -319,9 +315,6 @@ var pool = module.exports = function pool(options, authorizeFn){ before we emit the share, lets submit the block, then check if it was accepted using RPC getblock */ - console.log("NSP: OnShare: sharedata and blockhex following this"); - console.log(shareData); - console.log(blockHex); if (!isValidBlock) emitShare(); else{ @@ -336,9 +329,6 @@ var pool = module.exports = function pool(options, authorizeFn){ emitLog('Block notification via RPC after block submission'); }); - console.log("NSP: CheckBlockAccepted called: "); - console.log(isAccepted); - }); }); } diff --git a/lib/util.js b/lib/util.js index e9f77690..6f93b2d4 100644 --- a/lib/util.js +++ b/lib/util.js @@ -26,7 +26,6 @@ exports.getVersionByte = function(addr){ exports.sha256 = function(buffer){ var hash1 = crypto.createHash('sha256'); hash1.update(buffer); - console.log("Running sha256 on nsp: " + hash1); return hash1.digest(); }; From 239db54abbe19a7c8bec50e1e6aca80c990b1b69 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Wed, 12 Jul 2017 13:30:05 -0400 Subject: [PATCH 08/19] More error testing... --- lib/pool.js | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/pool.js b/lib/pool.js index af02f697..92f5d8ef 100644 --- a/lib/pool.js +++ b/lib/pool.js @@ -568,6 +568,7 @@ var pool = module.exports = function pool(options, authorizeFn){ _this.daemon.cmd('getblocktemplate', [{"capabilities": [ "coinbasetxn", "workid", "coinbase/append" ], "rules": [ "segwit" ]}], function(result){ + console.log(result); if (result.error){ emitErrorLog('getblocktemplate call failed for daemon instance ' + result.instance.index + ' with error ' + JSON.stringify(result.error)); From b3b4cd1a33a06f2a7eb2665c27f44afd3d7d7b66 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Wed, 12 Jul 2017 13:33:05 -0400 Subject: [PATCH 09/19] logging in the wrong place --- lib/pool.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pool.js b/lib/pool.js index 92f5d8ef..0375721a 100644 --- a/lib/pool.js +++ b/lib/pool.js @@ -568,8 +568,8 @@ var pool = module.exports = function pool(options, authorizeFn){ _this.daemon.cmd('getblocktemplate', [{"capabilities": [ "coinbasetxn", "workid", "coinbase/append" ], "rules": [ "segwit" ]}], function(result){ - console.log(result); if (result.error){ + console.log(result); emitErrorLog('getblocktemplate call failed for daemon instance ' + result.instance.index + ' with error ' + JSON.stringify(result.error)); callback(result.error); From 4ff88f70d0c38cd08893cc8ce74b223f7856a363 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Mon, 17 Jul 2017 10:54:59 -0400 Subject: [PATCH 10/19] testing updates --- lib/pool.js | 4 ++-- lib/stratum.js | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/pool.js b/lib/pool.js index 0375721a..c12075a3 100644 --- a/lib/pool.js +++ b/lib/pool.js @@ -231,7 +231,7 @@ var pool = module.exports = function pool(options, authorizeFn){ } else{ rpcCommand = 'getblocktemplate'; - rpcArgs = [{'mode': 'submit', 'data': blockHex}]; + rpcArgs = [{'mode': 'submit', 'data': blockHex}]; // TODO: is mode submit even correct? } @@ -569,7 +569,7 @@ var pool = module.exports = function pool(options, authorizeFn){ [{"capabilities": [ "coinbasetxn", "workid", "coinbase/append" ], "rules": [ "segwit" ]}], function(result){ if (result.error){ - console.log(result); + console.log("GetBlockTemplate()", result); emitErrorLog('getblocktemplate call failed for daemon instance ' + result.instance.index + ' with error ' + JSON.stringify(result.error)); callback(result.error); diff --git a/lib/stratum.js b/lib/stratum.js index 02f2728e..1bed2e42 100644 --- a/lib/stratum.js +++ b/lib/stratum.js @@ -60,7 +60,9 @@ var StratumClient = function(options){ }; function handleMessage(message){ + //added mining.extranonce.subscribe TODO:: why does scryptn client send it this way? switch(message.method){ + //case 'mining.extranonce.subscribe': case 'mining.subscribe': handleSubscribe(message); break; From 8484c5af1ef093431241303b4905c8344c607ec5 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Wed, 19 Jul 2017 15:16:56 -0400 Subject: [PATCH 11/19] Added debuging for failed block submits --- lib/jobManager.js | 33 +++++++++++++++++++++++++++++++++ lib/util.js | 2 +- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/lib/jobManager.js b/lib/jobManager.js index bb6d9cd8..d0878666 100644 --- a/lib/jobManager.js +++ b/lib/jobManager.js @@ -183,6 +183,18 @@ var JobManager = module.exports = function JobManager(options){ }); return {error: error, result: null}; }; + console.log("processShare - Stuff passed in", { + "jobId": jobId, + "previousDifficulty": previousDifficulty, + "difficulty": difficulty, + "extraNonce1": extraNonce1, + "extraNonce2": extraNonce2, + "nTime": nTime, + "nonce": nonce, + "ipAddress": ipAddress, + "port": port, + "workerName": workerName + }); var submitTime = Date.now() / 1000 | 0; @@ -232,10 +244,31 @@ var JobManager = module.exports = function JobManager(options){ var blockDiffAdjusted = job.difficulty * shareMultiplier; + console.log("processShare - Stuff calculated", { + "extraNonce1Buffer": extraNonce1Buffer, + "extraNonce2Buffer": extraNonce2Buffer, + "coinbaseBuffer": coinbaseBuffer, + "coinbaseHash": coinbaseHash, + "merkleRoot": merkleRoot, + "headerBuffer": headerBuffer, + "headerHash": headerHash, + "headerBigNum": headerBigNum, + "shareDiff": shareDiff, + "blockDiffAdjusted": blockDiffAdjusted + }); + + console.log("processShare - Globals", { + "job.target": job.target + }); + //Check if share is a block candidate (matched network difficulty) if (job.target.ge(headerBigNum)){ blockHex = job.serializeBlock(headerBuffer, coinbaseBuffer).toString('hex'); blockHash = blockHasher(headerBuffer, nTime).toString('hex'); + console.log("processShare - Block Candidate", { + "blockHex": blockHex, + "blockHash": blockHash + }); } else { if (options.emitInvalidBlockHashes) diff --git a/lib/util.js b/lib/util.js index 6f93b2d4..f233b480 100644 --- a/lib/util.js +++ b/lib/util.js @@ -57,7 +57,7 @@ exports.uint256BufferFromHash = function(hex){ fromHex = Buffer.from(hex, 'hex'); } else { fromHex = Buffer.alloc(32); - fromHex.fill(0); + //fromHex.fill(0); This is not needed because it happens by default with .alloc } return exports.reverseBuffer(fromHex); From ac43b48e31fe06d81460a4068f6b38828eec2f49 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Mon, 7 Aug 2017 07:51:31 -0400 Subject: [PATCH 12/19] Removed Logging --- lib/jobManager.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/jobManager.js b/lib/jobManager.js index d0878666..07087e0f 100644 --- a/lib/jobManager.js +++ b/lib/jobManager.js @@ -183,7 +183,7 @@ var JobManager = module.exports = function JobManager(options){ }); return {error: error, result: null}; }; - console.log("processShare - Stuff passed in", { + /*console.log("processShare - Stuff passed in", { "jobId": jobId, "previousDifficulty": previousDifficulty, "difficulty": difficulty, @@ -194,7 +194,7 @@ var JobManager = module.exports = function JobManager(options){ "ipAddress": ipAddress, "port": port, "workerName": workerName - }); + });*/ var submitTime = Date.now() / 1000 | 0; @@ -244,7 +244,7 @@ var JobManager = module.exports = function JobManager(options){ var blockDiffAdjusted = job.difficulty * shareMultiplier; - console.log("processShare - Stuff calculated", { + /*console.log("processShare - Stuff calculated", { "extraNonce1Buffer": extraNonce1Buffer, "extraNonce2Buffer": extraNonce2Buffer, "coinbaseBuffer": coinbaseBuffer, @@ -255,20 +255,20 @@ var JobManager = module.exports = function JobManager(options){ "headerBigNum": headerBigNum, "shareDiff": shareDiff, "blockDiffAdjusted": blockDiffAdjusted - }); + });*/ - console.log("processShare - Globals", { + /*console.log("processShare - Globals", { "job.target": job.target - }); + });*/ //Check if share is a block candidate (matched network difficulty) if (job.target.ge(headerBigNum)){ blockHex = job.serializeBlock(headerBuffer, coinbaseBuffer).toString('hex'); blockHash = blockHasher(headerBuffer, nTime).toString('hex'); - console.log("processShare - Block Candidate", { + /*console.log("processShare - Block Candidate", { "blockHex": blockHex, "blockHash": blockHash - }); + });*/ } else { if (options.emitInvalidBlockHashes) From a01db6ef4a5297100ec38e7bc483f92c10fa7fb5 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Tue, 15 Aug 2017 10:40:49 -0400 Subject: [PATCH 13/19] Added some more information around mining.extranounce.subscribe, testing first time --- lib/stratum.js | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/lib/stratum.js b/lib/stratum.js index 1bed2e42..10641a2c 100644 --- a/lib/stratum.js +++ b/lib/stratum.js @@ -60,11 +60,12 @@ var StratumClient = function(options){ }; function handleMessage(message){ - //added mining.extranonce.subscribe TODO:: why does scryptn client send it this way? switch(message.method){ - //case 'mining.extranonce.subscribe': + case 'mining.extranonce.subscribe': + handleExtraNounceSubscribe(message); case 'mining.subscribe': handleSubscribe(message); + console.log(message); break; case 'mining.authorize': handleAuthorize(message, true /*reply to socket*/); @@ -86,6 +87,23 @@ var StratumClient = function(options){ } } + function handleExtraNounceSubscribe(message) { + // Support for mining.extranonce.subscribe is currently not written. The client sends this to let the server know + // its supported, not handeling it is ok. The client first sends mining.subscribe, then send the extranounce command. + // It expects a return of the extranounce value and size if supported. + _this.emit('unknownStratumMethod', "Currently " + message + " is not supported, sending not support back to client."); + sendJson({ + id: message.id, + result: false, + "error": [20, "Not supported.", null] + }); + console.log({ + id: message.id, + result: false, + "error": [20, "Not supported.", null] + }); + } + function handleSubscribe(message){ if (! _this._authorized ) { _this.requestedSubscriptionBeforeAuth = true; From dcd68b3bbb43ffcdbded90871023e35d04d91e6e Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Tue, 15 Aug 2017 10:55:42 -0400 Subject: [PATCH 14/19] Removed some buggy code, from last commit --- lib/stratum.js | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/lib/stratum.js b/lib/stratum.js index 10641a2c..9377e5ea 100644 --- a/lib/stratum.js +++ b/lib/stratum.js @@ -61,11 +61,10 @@ var StratumClient = function(options){ function handleMessage(message){ switch(message.method){ - case 'mining.extranonce.subscribe': - handleExtraNounceSubscribe(message); + //case 'mining.extranonce.subscribe': + // handleExtraNounceSubscribe(message); case 'mining.subscribe': handleSubscribe(message); - console.log(message); break; case 'mining.authorize': handleAuthorize(message, true /*reply to socket*/); @@ -88,20 +87,17 @@ var StratumClient = function(options){ } function handleExtraNounceSubscribe(message) { + // TODO: Apparently even trying to catch this message causes low difficulty shares to be submitted by client, more investigation needed + // Support for mining.extranonce.subscribe is currently not written. The client sends this to let the server know // its supported, not handeling it is ok. The client first sends mining.subscribe, then send the extranounce command. // It expects a return of the extranounce value and size if supported. - _this.emit('unknownStratumMethod', "Currently " + message + " is not supported, sending not support back to client."); + //_this.emit('unknownStratumMethod', { method: "Currently " + message.method + " is not supported, sending not supported back to client." }); sendJson({ id: message.id, result: false, "error": [20, "Not supported.", null] }); - console.log({ - id: message.id, - result: false, - "error": [20, "Not supported.", null] - }); } function handleSubscribe(message){ From bef7181e5045055c282e20c73228553288321f2e Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Wed, 16 Aug 2017 08:20:33 -0400 Subject: [PATCH 15/19] Added Scrypt Jane back in --- lib/algoProperties.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/algoProperties.js b/lib/algoProperties.js index cb3658e6..7725ee62 100644 --- a/lib/algoProperties.js +++ b/lib/algoProperties.js @@ -39,7 +39,7 @@ var algos = module.exports = global.algos = { } } }, - /*'scrypt-jane': { + 'scrypt-jane': { multiplier: Math.pow(2, 16), hash: function(coinConfig){ var nTimestamp = coinConfig.chainStartTime || 1367991200; @@ -49,7 +49,7 @@ var algos = module.exports = global.algos = { return multiHashing.scryptjane(data, nTime, nTimestamp, nMin, nMax); } } - },*/ + }, 'scrypt-n': { multiplier: Math.pow(2, 16), hash: function(coinConfig){ From 7d128693e08acb1cb1d179cf0354d33c08a23a97 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Thu, 2 Nov 2017 14:05:04 -0400 Subject: [PATCH 16/19] testing equihash --- lib/algoProperties.js | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/algoProperties.js b/lib/algoProperties.js index 7725ee62..5f559fce 100644 --- a/lib/algoProperties.js +++ b/lib/algoProperties.js @@ -14,6 +14,15 @@ var algos = module.exports = global.algos = { } } }, + 'equihash': { + multiplier: 1, + diff: parseInt('0x0007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'), + hash: function(){ + return function(){ + return multiHashing.equihash(this, arguments); + } + } + }, 'scrypt': { //Uncomment diff if you want to use hardcoded truncated diff //diff: '0000ffff00000000000000000000000000000000000000000000000000000000', From cacb284d6a120d69dfeeeffc6e7bcd93ad935e5f Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Thu, 2 Nov 2017 15:31:48 -0400 Subject: [PATCH 17/19] more changes for equihash --- lib/jobManager.js | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/lib/jobManager.js b/lib/jobManager.js index 07087e0f..1fc31b23 100644 --- a/lib/jobManager.js +++ b/lib/jobManager.js @@ -82,33 +82,37 @@ var JobManager = module.exports = function JobManager(options){ })(); - var blockHasher = (function () { + var blockHasher = (() => { switch (options.coin.algorithm) { case 'scrypt': if (options.coin.reward === 'POS') { - return function (d) { + return (d) => { return util.reverseBuffer(hashDigest.apply(this, arguments)); }; } case 'scrypt-og': if (options.coin.reward === 'POS') { - return function (d) { + return (d) => { return util.reverseBuffer(hashDigest.apply(this, arguments)); }; } case 'scrypt-jane': if (options.coin.reward === 'POS') { - return function (d) { + return (d) => { return util.reverseBuffer(hashDigest.apply(this, arguments)); }; } case 'scrypt-n': case 'sha1': - return function (d) { + return (d) => { return util.reverseBuffer(util.sha256d(d)); }; + case 'equihash': + return (d) => { + return util.reverseBuffer(util.sha256(d)); + }; default: - return function () { + return () => { return util.reverseBuffer(hashDigest.apply(this, arguments)); }; } From c2ec449ef99ed0dc6080bec09fb0ffbf18a04b39 Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Sat, 10 Oct 2020 10:20:56 -0400 Subject: [PATCH 18/19] Added some changes to support veriums new version --- lib/jobManager.js | 16 +- lib/pool.js | 378 +++++++++++++++++++++++++--------------------- package.json | 6 +- 3 files changed, 213 insertions(+), 187 deletions(-) diff --git a/lib/jobManager.js b/lib/jobManager.js index 1fc31b23..6929a3f6 100644 --- a/lib/jobManager.js +++ b/lib/jobManager.js @@ -25,7 +25,7 @@ var ExtraNonceCounter = function(configInstanceId){ }; //Unique job per new block template -var JobCounter = function(){ +var JobCounter = () => { var counter = 0; this.next = function(){ @@ -187,19 +187,7 @@ var JobManager = module.exports = function JobManager(options){ }); return {error: error, result: null}; }; - /*console.log("processShare - Stuff passed in", { - "jobId": jobId, - "previousDifficulty": previousDifficulty, - "difficulty": difficulty, - "extraNonce1": extraNonce1, - "extraNonce2": extraNonce2, - "nTime": nTime, - "nonce": nonce, - "ipAddress": ipAddress, - "port": port, - "workerName": workerName - });*/ - + var submitTime = Date.now() / 1000 | 0; if (extraNonce2.length / 2 !== _this.extraNonce2Size) diff --git a/lib/pool.js b/lib/pool.js index c12075a3..57064ee0 100644 --- a/lib/pool.js +++ b/lib/pool.js @@ -13,7 +13,7 @@ var util = require('./util.js'); throw err; });*/ -var pool = module.exports = function pool(options, authorizeFn){ +var pool = module.exports = function pool(options, authorizeFn) { this.options = options; @@ -21,32 +21,40 @@ var pool = module.exports = function pool(options, authorizeFn){ var blockPollingIntervalId; - var emitLog = function(text) { _this.emit('log', 'debug' , text); }; - var emitWarningLog = function(text) { _this.emit('log', 'warning', text); }; - var emitErrorLog = function(text) { _this.emit('log', 'error' , text); }; - var emitSpecialLog = function(text) { _this.emit('log', 'special', text); }; + var emitLog = function (text) { + _this.emit('log', 'debug', text); + }; + var emitWarningLog = function (text) { + _this.emit('log', 'warning', text); + }; + var emitErrorLog = function (text) { + _this.emit('log', 'error', text); + }; + var emitSpecialLog = function (text) { + _this.emit('log', 'special', text); + }; - if (!(options.coin.algorithm in algos)){ + if (!(options.coin.algorithm in algos)) { emitErrorLog('The ' + options.coin.algorithm + ' hashing algorithm is not supported.'); throw new Error(); } - this.start = function(){ + this.start = function () { SetupVarDiff(); SetupApi(); - SetupDaemonInterface(function(){ - DetectCoinData(function(){ + SetupDaemonInterface(function () { + DetectCoinData(function () { SetupRecipients(); SetupJobManager(); - OnBlockchainSynced(function(){ - GetFirstJob(function(){ + OnBlockchainSynced(function () { + GetFirstJob(function () { SetupBlockPolling(); SetupPeer(); - StartStratumServer(function(){ + StartStratumServer(function () { OutputPoolInfo(); _this.emit('started'); }); @@ -58,9 +66,9 @@ var pool = module.exports = function pool(options, authorizeFn){ - function GetFirstJob(finishedCallback){ + function GetFirstJob(finishedCallback) { - GetBlockTemplate(function(error, result){ + GetBlockTemplate(function (error, result) { if (error) { emitErrorLog('Error with getblocktemplate on creating first job, server cannot start'); return; @@ -70,7 +78,7 @@ var pool = module.exports = function pool(options, authorizeFn){ var networkDiffAdjusted = options.initStats.difficulty; - Object.keys(options.ports).forEach(function(port){ + Object.keys(options.ports).forEach(function (port) { var portDiff = options.ports[port].diff; if (networkDiffAdjusted < portDiff) portWarnings.push('port ' + port + ' w/ diff ' + portDiff); @@ -78,8 +86,8 @@ var pool = module.exports = function pool(options, authorizeFn){ //Only let the first fork show synced status or the log wil look flooded with it if (portWarnings.length > 0 && (!process.env.forkId || process.env.forkId === '0')) { - var warnMessage = 'Network diff of ' + networkDiffAdjusted + ' is lower than ' - + portWarnings.join(' and '); + var warnMessage = 'Network diff of ' + networkDiffAdjusted + ' is lower than ' + + portWarnings.join(' and '); emitWarningLog(warnMessage); } @@ -89,24 +97,24 @@ var pool = module.exports = function pool(options, authorizeFn){ } - function OutputPoolInfo(){ + function OutputPoolInfo() { var startMessage = 'Stratum Pool Server Started for ' + options.coin.name + ' [' + options.coin.symbol.toUpperCase() + '] {' + options.coin.algorithm + '}'; - if (process.env.forkId && process.env.forkId !== '0'){ + if (process.env.forkId && process.env.forkId !== '0') { emitLog(startMessage); return; } var infoLines = [startMessage, - 'Network Connected:\t' + (options.testnet ? 'Testnet' : 'Mainnet'), - 'Detected Reward Type:\t' + options.coin.reward, - 'Current Block Height:\t' + _this.jobManager.currentJob.rpcData.height, - 'Current Connect Peers:\t' + options.initStats.connections, - 'Current Block Diff:\t' + _this.jobManager.currentJob.difficulty * algos[options.coin.algorithm].multiplier, - 'Network Difficulty:\t' + options.initStats.difficulty, - 'Network Hash Rate:\t' + util.getReadableHashRateString(options.initStats.networkHashRate), - 'Stratum Port(s):\t' + _this.options.initStats.stratumPorts.join(', '), - 'Pool Fee Percent:\t' + _this.options.feePercent + '%' + 'Network Connected:\t' + (options.testnet ? 'Testnet' : 'Mainnet'), + 'Detected Reward Type:\t' + options.coin.reward, + 'Current Block Height:\t' + _this.jobManager.currentJob.rpcData.height, + 'Current Connect Peers:\t' + options.initStats.connections, + 'Current Block Diff:\t' + _this.jobManager.currentJob.difficulty * algos[options.coin.algorithm].multiplier, + 'Network Difficulty:\t' + options.initStats.difficulty, + 'Network Hash Rate:\t' + util.getReadableHashRateString(options.initStats.networkHashRate), + 'Stratum Port(s):\t' + _this.options.initStats.stratumPorts.join(', '), + 'Pool Fee Percent:\t' + _this.options.feePercent + '%' ]; if (typeof options.blockRefreshInterval === "number" && options.blockRefreshInterval > 0) @@ -116,17 +124,19 @@ var pool = module.exports = function pool(options, authorizeFn){ } - function OnBlockchainSynced(syncedCallback){ + function OnBlockchainSynced(syncedCallback) { - var checkSynced = function(displayNotSynced){ - _this.daemon.cmd('getblocktemplate', [{"capabilities": [ "coinbasetxn", "workid", "coinbase/append" ], "rules": [ "segwit" ]}], function(results){ - var synced = results.every(function(r){ + var checkSynced = function (displayNotSynced) { + _this.daemon.cmd('getblocktemplate', [{ + "capabilities": ["coinbasetxn", "workid", "coinbase/append"], + "rules": ["segwit"] + }], function (results) { + var synced = results.every(function (r) { return !r.error || r.error.code !== -10; }); - if (synced){ + if (synced) { syncedCallback(); - } - else{ + } else { if (displayNotSynced) displayNotSynced(); setTimeout(checkSynced, 5000); @@ -137,25 +147,26 @@ var pool = module.exports = function pool(options, authorizeFn){ }); }; - checkSynced(function(){ + checkSynced(function () { //Only let the first fork show synced status or the log wil look flooded with it if (!process.env.forkId || process.env.forkId === '0') emitErrorLog('Daemon is still syncing with network (download blockchain) - server will be started once synced'); }); - var generateProgress = function(){ + var generateProgress = function () { - _this.daemon.cmd('getinfo', [], function(results) { + var cmd = options.coin.hasGetInfo ? 'getinfo' : 'getblockchaininfo'; + _this.daemon.cmd(cmd, [], function (results) { var blockCount = results.sort(function (a, b) { return b.response.blocks - a.response.blocks; })[0].response.blocks; //get list of peers and their highest block height to compare to ours - _this.daemon.cmd('getpeerinfo', [], function(results){ + _this.daemon.cmd('getpeerinfo', [], function (results) { var peers = results[0].response; - var totalBlocks = peers.sort(function(a, b){ + var totalBlocks = peers.sort(function (a, b) { return b.startingheight - a.startingheight; })[0].startingheight; @@ -170,7 +181,7 @@ var pool = module.exports = function pool(options, authorizeFn){ function SetupApi() { - if (typeof(options.api) !== 'object' || typeof(options.api.start) !== 'function') { + if (typeof (options.api) !== 'object' || typeof (options.api.start) !== 'function') { return; } else { options.api.start(_this); @@ -178,41 +189,40 @@ var pool = module.exports = function pool(options, authorizeFn){ } - function SetupPeer(){ + function SetupPeer() { if (!options.p2p || !options.p2p.enabled) return; - if (options.testnet && !options.coin.peerMagicTestnet){ + if (options.testnet && !options.coin.peerMagicTestnet) { emitErrorLog('p2p cannot be enabled in testnet without peerMagicTestnet set in coin configuration'); return; - } - else if (!options.coin.peerMagic){ + } else if (!options.coin.peerMagic) { emitErrorLog('p2p cannot be enabled without peerMagic set in coin configuration'); return; } _this.peer = new peer(options); - _this.peer.on('connected', function() { + _this.peer.on('connected', function () { emitLog('p2p connection successful'); - }).on('connectionRejected', function(){ + }).on('connectionRejected', function () { emitErrorLog('p2p connection failed - likely incorrect p2p magic value'); - }).on('disconnected', function(){ + }).on('disconnected', function () { emitWarningLog('p2p peer node disconnected - attempting reconnection...'); - }).on('connectionFailed', function(e){ + }).on('connectionFailed', function (e) { emitErrorLog('p2p connection failed - likely incorrect host or port'); - }).on('socketError', function(e){ + }).on('socketError', function (e) { emitErrorLog('p2p had a socket error ' + JSON.stringify(e)); - }).on('error', function(msg){ + }).on('error', function (msg) { emitWarningLog('p2p had an error ' + msg); - }).on('blockFound', function(hash){ + }).on('blockFound', function (hash) { _this.processBlockNotify(hash, 'p2p'); }); } - function SetupVarDiff(){ + function SetupVarDiff() { _this.varDiff = {}; - Object.keys(options.ports).forEach(function(port) { + Object.keys(options.ports).forEach(function (port) { if (options.ports[port].varDiff) _this.setVarDiff(port, options.ports[port].varDiff); }); @@ -222,32 +232,33 @@ var pool = module.exports = function pool(options, authorizeFn){ /* Coin daemons either use submitblock or getblocktemplate for submitting new blocks */ - function SubmitBlock(blockHex, callback){ + function SubmitBlock(blockHex, callback) { var rpcCommand, rpcArgs; - if (options.hasSubmitMethod){ + if (options.hasSubmitMethod) { rpcCommand = 'submitblock'; rpcArgs = [blockHex]; - } - else{ + } else { rpcCommand = 'getblocktemplate'; - rpcArgs = [{'mode': 'submit', 'data': blockHex}]; // TODO: is mode submit even correct? + rpcArgs = [{ + 'mode': 'submit', + 'data': blockHex + }]; } _this.daemon.cmd(rpcCommand, rpcArgs, - function(results){ - for (var i = 0; i < results.length; i++){ + function (results) { + for (var i = 0; i < results.length; i++) { var result = results[i]; if (result.error) { emitErrorLog('rpc error with daemon instance ' + - result.instance.index + ' when submitting block with ' + rpcCommand + ' ' + - JSON.stringify(result.error) + result.instance.index + ' when submitting block with ' + rpcCommand + ' ' + + JSON.stringify(result.error) ); return; - } - else if (result.response === 'rejected') { + } else if (result.response === 'rejected') { emitErrorLog('Daemon instance ' + result.instance.index + ' rejected a supposedly valid block'); return; } @@ -260,11 +271,11 @@ var pool = module.exports = function pool(options, authorizeFn){ } - function SetupRecipients(){ + function SetupRecipients() { var recipients = []; options.feePercent = 0; options.rewardRecipients = options.rewardRecipients || {}; - for (var r in options.rewardRecipients){ + for (var r in options.rewardRecipients) { var percent = options.rewardRecipients[r]; var rObj = { percent: percent / 100 @@ -276,37 +287,36 @@ var pool = module.exports = function pool(options, authorizeFn){ rObj.script = util.addressToScript(r); recipients.push(rObj); options.feePercent += percent; - } - catch(e){ + } catch (e) { emitErrorLog('Error generating transaction output script for ' + r + ' in rewardRecipients'); } } - if (recipients.length === 0){ + if (recipients.length === 0) { emitErrorLog('No rewardRecipients have been setup which means no fees will be taken'); } options.recipients = recipients; } - function SetupJobManager(){ + function SetupJobManager() { _this.jobManager = new jobManager(options); - _this.jobManager.on('newBlock', function(blockTemplate){ + _this.jobManager.on('newBlock', function (blockTemplate) { //Check if stratumServer has been initialized yet if (_this.stratumServer) { _this.stratumServer.broadcastMiningJobs(blockTemplate.getJobParams()); } - }).on('updatedBlock', function(blockTemplate){ + }).on('updatedBlock', function (blockTemplate) { //Check if stratumServer has been initialized yet if (_this.stratumServer) { var job = blockTemplate.getJobParams(); job[8] = false; _this.stratumServer.broadcastMiningJobs(job); } - }).on('share', function(shareData, blockHex){ + }).on('share', function (shareData, blockHex) { var isValidShare = !shareData.error; var isValidBlock = !!blockHex; - var emitShare = function(){ + var emitShare = function () { _this.emit('share', isValidShare, isValidBlock, shareData); }; @@ -317,14 +327,14 @@ var pool = module.exports = function pool(options, authorizeFn){ */ if (!isValidBlock) emitShare(); - else{ - SubmitBlock(blockHex, function(){ - CheckBlockAccepted(shareData.blockHash, function(isAccepted, tx){ + else { + SubmitBlock(blockHex, function () { + CheckBlockAccepted(shareData.blockHash, function (isAccepted, tx) { isValidBlock = isAccepted; shareData.txHash = tx; emitShare(); - GetBlockTemplate(function(error, result, foundNewBlock){ + GetBlockTemplate(function (error, result, foundNewBlock) { if (foundNewBlock) emitLog('Block notification via RPC after block submission'); }); @@ -332,30 +342,30 @@ var pool = module.exports = function pool(options, authorizeFn){ }); }); } - }).on('log', function(severity, message){ + }).on('log', function (severity, message) { _this.emit('log', severity, message); }); } - function SetupDaemonInterface(finishedCallback){ + function SetupDaemonInterface(finishedCallback) { - if (!Array.isArray(options.daemons) || options.daemons.length < 1){ + if (!Array.isArray(options.daemons) || options.daemons.length < 1) { emitErrorLog('No daemons have been configured - pool cannot start'); return; } - _this.daemon = new daemon.interface(options.daemons, function(severity, message){ - _this.emit('log', severity , message); + _this.daemon = new daemon.interface(options.daemons, function (severity, message) { + _this.emit('log', severity, message); }); - _this.daemon.once('online', function(){ + _this.daemon.once('online', function () { finishedCallback(); - }).on('connectionFailed', function(error){ + }).on('connectionFailed', function (error) { emitErrorLog('Failed to connect daemon(s): ' + JSON.stringify(error)); - }).on('error', function(message){ + }).on('error', function (message) { emitErrorLog(message); }); @@ -364,36 +374,41 @@ var pool = module.exports = function pool(options, authorizeFn){ } - function DetectCoinData(finishedCallback){ + function DetectCoinData(finishedCallback) { var batchRpcCalls = [ ['validateaddress', [options.address]], ['getdifficulty', []], - ['getinfo', []], ['getmininginfo', []], ['submitblock', []] ]; - _this.daemon.batchCmd(batchRpcCalls, function(error, results){ - if (error || !results){ + if (options.coin.hasGetInfo) { + batchRpcCalls.push(['getinfo', []]); + } else { + batchRpcCalls.push(['getblockchaininfo', []], ['getnetworkinfo', []], ['getaddressinfo', [options.address]]); + } + + _this.daemon.batchCmd(batchRpcCalls, function (error, results) { + if (error || !results) { emitErrorLog('Could not start pool, error with init batch RPC call: ' + JSON.stringify(error)); return; } var rpcResults = {}; - for (var i = 0; i < results.length; i++){ + for (var i = 0; i < results.length; i++) { var rpcCall = batchRpcCalls[i][0]; var r = results[i]; rpcResults[rpcCall] = r.result || r.error; - if (rpcCall !== 'submitblock' && (r.error || !r.result)){ + if (rpcCall !== 'submitblock' && (r.error || !r.result)) { emitErrorLog('Could not start pool, error with init RPC ' + rpcCall + ' - ' + JSON.stringify(r.error)); return; } } - if (!rpcResults.validateaddress.isvalid){ + if (!rpcResults.validateaddress.isvalid) { emitErrorLog('Daemon reports address is not valid'); return; } @@ -408,37 +423,55 @@ var pool = module.exports = function pool(options, authorizeFn){ /* POS coins must use the pubkey in coinbase transaction, and pubkey is only given if address is owned by wallet.*/ - if (options.coin.reward === 'POS' && typeof(rpcResults.validateaddress.pubkey) == 'undefined') { + if (options.coin.reward === 'POS' && typeof (rpcResults.validateaddress.pubkey) == 'undefined' && typeof (rpcResults.getaddressinfo.pubkey) == 'undefined') { emitErrorLog('The address provided is not from the daemon wallet - this is required for POS coins.'); return; } - options.poolAddressScript = (function(){ - switch(options.coin.reward){ + options.poolAddressScript = (function () { + switch (options.coin.reward) { case 'POS': - return util.pubkeyToScript(rpcResults.validateaddress.pubkey); - case 'POW': - return util.addressToScript(rpcResults.validateaddress.address); + if (typeof (rpcResults.validateaddress.pubkey) == 'undefined') { + return util.pubkeyToScript(rpcResults.getaddressinfo.pubkey); + } else { + return util.pubkeyToScript(rpcResults.validateaddress.pubkey); + } + case 'POW': + return util.addressToScript(rpcResults.validateaddress.address); } })(); - options.testnet = rpcResults.getinfo.testnet; - options.protocolVersion = rpcResults.getinfo.protocolversion; + var difficulty; + var connections; + + if (options.coin.hasGetInfo) { + options.testnet = rpcResults.getinfo.testnet; + options.protocolVersion = rpcResults.getinfo.protocolversion; + difficulty = rpcResults.getinfo.difficulty; + connections = rpcResults.getinfo.connections; + } else { + options.testnet = (rpcResults.getblockchaininfo.chain === 'test') ? true : false + options.protocolVersion = rpcResults.getnetworkinfo.protocolversion; + difficulty = rpcResults.getblockchaininfo.difficulty; + connections = rpcResults.getnetworkinfo.connections; + } + + if (typeof (difficulty) == 'object') { + difficulty = difficulty['proof-of-work']; + } options.initStats = { - connections: rpcResults.getinfo.connections, - difficulty: rpcResults.getinfo.difficulty * algos[options.coin.algorithm].multiplier, + connections: connections, + difficulty: difficulty * algos[options.coin.algorithm].multiplier, networkHashRate: rpcResults.getmininginfo.networkhashps }; - if (rpcResults.submitblock.message === 'Method not found'){ + if (rpcResults.submitblock.message === 'Method not found') { options.hasSubmitMethod = false; - } - else if (rpcResults.submitblock.code === -1){ + } else if (rpcResults.submitblock.code === -1) { options.hasSubmitMethod = true; - } - else { + } else { emitErrorLog('Could not detect block submission RPC method, ' + JSON.stringify(results)); return; } @@ -450,31 +483,31 @@ var pool = module.exports = function pool(options, authorizeFn){ - function StartStratumServer(finishedCallback){ + function StartStratumServer(finishedCallback) { _this.stratumServer = new stratum.Server(options, authorizeFn); - _this.stratumServer.on('started', function(){ + _this.stratumServer.on('started', function () { options.initStats.stratumPorts = Object.keys(options.ports); _this.stratumServer.broadcastMiningJobs(_this.jobManager.currentJob.getJobParams()); finishedCallback(); - }).on('broadcastTimeout', function(){ + }).on('broadcastTimeout', function () { emitLog('No new blocks for ' + options.jobRebroadcastTimeout + ' seconds - updating transactions & rebroadcasting work'); - GetBlockTemplate(function(error, rpcData, processedBlock){ + GetBlockTemplate(function (error, rpcData, processedBlock) { if (error || processedBlock) return; _this.jobManager.updateCurrentJob(rpcData); }); - }).on('client.connected', function(client){ - if (typeof(_this.varDiff[client.socket.localPort]) !== 'undefined') { + }).on('client.connected', function (client) { + if (typeof (_this.varDiff[client.socket.localPort]) !== 'undefined') { _this.varDiff[client.socket.localPort].manageClient(client); } - client.on('difficultyChanged', function(diff){ + client.on('difficultyChanged', function (diff) { _this.emit('difficultyUpdate', client.workerName, diff); - }).on('subscription', function(params, resultCallback){ + }).on('subscription', function (params, resultCallback) { var extraNonce = _this.jobManager.extraNonceCounter.next(); var extraNonce2Size = _this.jobManager.extraNonce2Size; @@ -483,16 +516,16 @@ var pool = module.exports = function pool(options, authorizeFn){ extraNonce2Size ); - if (typeof(options.ports[client.socket.localPort]) !== 'undefined' && options.ports[client.socket.localPort].diff) { + if (typeof (options.ports[client.socket.localPort]) !== 'undefined' && options.ports[client.socket.localPort].diff) { this.sendDifficulty(options.ports[client.socket.localPort].diff); } else { this.sendDifficulty(8); } - + this.sendMiningJob(_this.jobManager.currentJob.getJobParams()); - - }).on('submit', function(params, resultCallback){ - var result =_this.jobManager.processShare( + + }).on('submit', function (params, resultCallback) { + var result = _this.jobManager.processShare( params.jobId, client.previousDifficulty, client.difficulty, @@ -510,34 +543,34 @@ var pool = module.exports = function pool(options, authorizeFn){ }).on('malformedMessage', function (message) { emitWarningLog('Malformed message from ' + client.getLabel() + ': ' + message); - }).on('socketError', function(err) { + }).on('socketError', function (err) { emitWarningLog('Socket error from ' + client.getLabel() + ': ' + JSON.stringify(err)); - }).on('socketTimeout', function(reason){ + }).on('socketTimeout', function (reason) { emitWarningLog('Connected timed out for ' + client.getLabel() + ': ' + reason) - }).on('socketDisconnect', function() { + }).on('socketDisconnect', function () { //emitLog('Socket disconnected from ' + client.getLabel()); - }).on('kickedBannedIP', function(remainingBanTime){ + }).on('kickedBannedIP', function (remainingBanTime) { emitLog('Rejected incoming connection from ' + client.remoteAddress + ' banned for ' + remainingBanTime + ' more seconds'); - }).on('forgaveBannedIP', function(){ + }).on('forgaveBannedIP', function () { emitLog('Forgave banned IP ' + client.remoteAddress); - }).on('unknownStratumMethod', function(fullMessage) { + }).on('unknownStratumMethod', function (fullMessage) { emitLog('Unknown stratum method from ' + client.getLabel() + ': ' + fullMessage.method); - }).on('socketFlooded', function() { + }).on('socketFlooded', function () { emitWarningLog('Detected socket flooding from ' + client.getLabel()); - }).on('tcpProxyError', function(data) { + }).on('tcpProxyError', function (data) { emitErrorLog('Client IP detection failed, tcpProxyProtocol is enabled yet did not receive proxy protocol message, instead got data: ' + data); - }).on('bootedBannedWorker', function(){ + }).on('bootedBannedWorker', function () { emitWarningLog('Booted worker ' + client.getLabel() + ' who was connected from an IP address that was just banned'); - }).on('triggerBan', function(reason){ + }).on('triggerBan', function (reason) { emitWarningLog('Banned triggered for ' + client.getLabel() + ': ' + reason); _this.emit('banIP', client.remoteAddress, client.workerName); }); @@ -546,8 +579,8 @@ var pool = module.exports = function pool(options, authorizeFn){ - function SetupBlockPolling(){ - if (typeof options.blockRefreshInterval !== "number" || options.blockRefreshInterval <= 0){ + function SetupBlockPolling() { + if (typeof options.blockRefreshInterval !== "number" || options.blockRefreshInterval <= 0) { emitLog('Block template polling has been disabled'); return; } @@ -555,7 +588,7 @@ var pool = module.exports = function pool(options, authorizeFn){ var pollingInterval = options.blockRefreshInterval; blockPollingIntervalId = setInterval(function () { - GetBlockTemplate(function(error, result, foundNewBlock){ + GetBlockTemplate(function (error, result, foundNewBlock) { if (foundNewBlock) emitLog('Block notification via RPC polling'); }); @@ -564,11 +597,14 @@ var pool = module.exports = function pool(options, authorizeFn){ - function GetBlockTemplate(callback){ + function GetBlockTemplate(callback) { _this.daemon.cmd('getblocktemplate', - [{"capabilities": [ "coinbasetxn", "workid", "coinbase/append" ], "rules": [ "segwit" ]}], - function(result){ - if (result.error){ + [{ + "capabilities": ["coinbasetxn", "workid", "coinbase/append"], + "rules": ["segwit"] + }], + function (result) { + if (result.error) { console.log("GetBlockTemplate()", result); emitErrorLog('getblocktemplate call failed for daemon instance ' + result.instance.index + ' with error ' + JSON.stringify(result.error)); @@ -576,7 +612,7 @@ var pool = module.exports = function pool(options, authorizeFn){ } else { var processedNewBlock = _this.jobManager.processTemplate(result.response); callback(null, result.response, processedNewBlock); - callback = function(){}; + callback = function () {}; } }, true ); @@ -584,23 +620,22 @@ var pool = module.exports = function pool(options, authorizeFn){ - function CheckBlockAccepted(blockHash, callback){ + function CheckBlockAccepted(blockHash, callback) { //setTimeout(function(){ - _this.daemon.cmd('getblock', - [blockHash], - function(results){ - var validResults = results.filter(function(result){ - return result.response && (result.response.hash === blockHash) - }); + _this.daemon.cmd('getblock', + [blockHash], + function (results) { + var validResults = results.filter(function (result) { + return result.response && (result.response.hash === blockHash) + }); - if (validResults.length >= 1){ - callback(true, validResults[0].response.tx[0]); - } - else{ - callback(false); - } + if (validResults.length >= 1) { + callback(true, validResults[0].response.tx[0]); + } else { + callback(false); } - ); + } + ); //}, 500); } @@ -609,11 +644,11 @@ var pool = module.exports = function pool(options, authorizeFn){ /** * This method is being called from the blockNotify so that when a new block is discovered by the daemon * We can inform our miners about the newly found block - **/ - this.processBlockNotify = function(blockHash, sourceTrigger) { + **/ + this.processBlockNotify = function (blockHash, sourceTrigger) { emitLog('Block notification via ' + sourceTrigger); - if (typeof(_this.jobManager.currentJob) !== 'undefined' && blockHash !== _this.jobManager.currentJob.rpcData.previousblockhash){ - GetBlockTemplate(function(error, result){ + if (typeof (_this.jobManager.currentJob) !== 'undefined' && blockHash !== _this.jobManager.currentJob.rpcData.previousblockhash) { + GetBlockTemplate(function (error, result) { if (error) emitErrorLog('Block notify error getting block template for ' + options.coin.name); }) @@ -621,23 +656,26 @@ var pool = module.exports = function pool(options, authorizeFn){ }; - this.relinquishMiners = function(filterFn, resultCback) { + this.relinquishMiners = function (filterFn, resultCback) { var origStratumClients = this.stratumServer.getStratumClients(); var stratumClients = []; Object.keys(origStratumClients).forEach(function (subId) { - stratumClients.push({subId: subId, client: origStratumClients[subId]}); + stratumClients.push({ + subId: subId, + client: origStratumClients[subId] + }); }); //TODO: Think of a way to use API 8's async/await and promises to replace async lib async.filter( stratumClients, filterFn, function (clientsToRelinquish) { - clientsToRelinquish.forEach(function(cObj) { + clientsToRelinquish.forEach(function (cObj) { cObj.client.removeAllListeners(); _this.stratumServer.removeStratumClientBySubId(cObj.subId); }); - + process.nextTick(function () { resultCback( clientsToRelinquish.map( @@ -645,15 +683,15 @@ var pool = module.exports = function pool(options, authorizeFn){ return item.client; } ) - ); + ); }); } ); - + }; - this.attachMiners = function(miners) { + this.attachMiners = function (miners) { miners.forEach(function (clientObj) { _this.stratumServer.manuallyAddStratumClient(clientObj); }); @@ -662,18 +700,18 @@ var pool = module.exports = function pool(options, authorizeFn){ }; - this.getStratumServer = function() { + this.getStratumServer = function () { return _this.stratumServer; }; - this.setVarDiff = function(port, varDiffConfig) { - if (typeof(_this.varDiff[port]) != 'undefined' ) { + this.setVarDiff = function (port, varDiffConfig) { + if (typeof (_this.varDiff[port]) != 'undefined') { _this.varDiff[port].removeAllListeners(); } var varDiffInstance = new varDiff(port, varDiffConfig); _this.varDiff[port] = varDiffInstance; - _this.varDiff[port].on('newDifficulty', function(client, newDiff) { + _this.varDiff[port].on('newDifficulty', function (client, newDiff) { /* We request to set the newDiff @ the next difficulty retarget (which should happen when a new job comes in - AKA BLOCK) */ @@ -693,4 +731,4 @@ var pool = module.exports = function pool(options, authorizeFn){ }; }; -pool.prototype.__proto__ = events.EventEmitter.prototype; +pool.prototype.__proto__ = events.EventEmitter.prototype; \ No newline at end of file diff --git a/package.json b/package.json index d1e3f589..3fba1aa7 100644 --- a/package.json +++ b/package.json @@ -12,9 +12,9 @@ "litecoin", "scrypt" ], - "homepage": "https://github.com/zone117x/node-stratum-pool", + "homepage": "https://github.com/krisklosterman/node-stratum-pool", "bugs": { - "url": "https://github.com/zone117x/node-stratum-pool/issues" + "url": "https://github.com/krisklosterman/node-stratum-pool/issues" }, "license": "GPL-2.0", "author": "Matthew Little", @@ -25,7 +25,7 @@ "main": "lib/index.js", "repository": { "type": "git", - "url": "https://github.com/zone117x/node-stratum-pool.git" + "url": "https://github.com/krisklosterman/node-stratum-pool.git" }, "dependencies": { "async": "^2.5.0", From 5030388ff77c754dca48a67a8129acaa7971060d Mon Sep 17 00:00:00 2001 From: Kristopher Klosterman Date: Mon, 19 Oct 2020 10:02:02 -0400 Subject: [PATCH 19/19] updated deps --- package.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 3fba1aa7..c56ec805 100644 --- a/package.json +++ b/package.json @@ -28,9 +28,9 @@ "url": "https://github.com/krisklosterman/node-stratum-pool.git" }, "dependencies": { - "async": "^2.5.0", - "base58-native": "^0.1.4", - "bignum": "^0.12.5", + "async": "*", + "base58-native": "*", + "bignum": "0.12.5", "multi-hashing": "git://github.com/krisklosterman/node-multi-hashing.git" }, "engines": {