From 781d864c8bd2ca8d95eac1b98a881d8b6cf9a45e Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Thu, 25 Jul 2019 14:50:40 -0300 Subject: [PATCH 01/25] Install new tooling --- .gitignore | 1 + .prettierignore | 5 +++++ package.json | 9 ++++++++- prettier.config.js | 1 + tsconfig.json | 7 +++++++ tsconfig.prod.json | 7 +++++++ tslint.json | 3 +++ 7 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 .prettierignore create mode 100644 prettier.config.js create mode 100644 tsconfig.json create mode 100644 tsconfig.prod.json create mode 100644 tslint.json diff --git a/.gitignore b/.gitignore index 31289d6..67d3750 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +.idea # Created by https://www.gitignore.io/api/osx,node diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..03abf45 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,5 @@ +node_modules +.vscode +package.json +dist +.nyc_output \ No newline at end of file diff --git a/package.json b/package.json index 5138305..0c33e05 100644 --- a/package.json +++ b/package.json @@ -42,6 +42,9 @@ "merkle-patricia-tree": "^2.1.2" }, "devDependencies": { + "@ethereumjs/config-prettier": "^1.1.1", + "@ethereumjs/config-tsc": "^1.1.1", + "@ethereumjs/config-tslint": "^1.1.1", "babel-preset-env": "^1.6.1", "babelify": "^8.0.0", "browserify": "^15.0.0", @@ -56,7 +59,11 @@ "karma-env-preprocessor": "^0.1.1", "karma-firefox-launcher": "^1.1.0", "karma-tap": "^4.0.0", + "prettier": "^1.18.2", "standard": "^8.4.0", - "tape": "^4.2.0" + "tape": "^4.2.0", + "ts-node": "^8.3.0", + "tslint": "^5.18.0", + "typescript": "^3.5.3" } } diff --git a/prettier.config.js b/prettier.config.js new file mode 100644 index 0000000..0f2e5b7 --- /dev/null +++ b/prettier.config.js @@ -0,0 +1 @@ +module.exports = require('@ethereumjs/config-prettier') diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..16b64ff --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "@ethereumjs/config-tsc", + "include": ["src/**/*.ts", "test/**/*.ts"], + "compilerOptions": { + "outDir": "test-build" + } +} diff --git a/tsconfig.prod.json b/tsconfig.prod.json new file mode 100644 index 0000000..184d95b --- /dev/null +++ b/tsconfig.prod.json @@ -0,0 +1,7 @@ +{ + "extends": "@ethereumjs/config-tsc", + "compilerOptions": { + "outDir": "./dist" + }, + "include": ["src/**/*.ts"] +} diff --git a/tslint.json b/tslint.json new file mode 100644 index 0000000..2ba21c4 --- /dev/null +++ b/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "@ethereumjs/config-tslint" +} From 4346a6ef2c9b23f2dafbc1d76cb92bbffba52b2f Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Thu, 25 Jul 2019 14:51:28 -0300 Subject: [PATCH 02/25] Reformat everything with prettier --- from-rpc.js | 22 ++-- header-from-rpc.js | 6 +- header.js | 221 ++++++++++++++++++++--------------- index.js | 158 +++++++++++++------------ karma.conf.js | 30 +++-- tests/block.js | 78 ++++++++----- tests/difficulty.js | 28 ++--- tests/from-rpc.js | 4 +- tests/genesishashestest.json | 2 +- tests/header.js | 48 +++++--- tests/testdata-from-rpc.json | 156 +++++++++++++------------ tests/testdata2.json | 115 +++++++++--------- 12 files changed, 487 insertions(+), 381 deletions(-) diff --git a/from-rpc.js b/from-rpc.js index aa65197..201cf70 100644 --- a/from-rpc.js +++ b/from-rpc.js @@ -11,39 +11,43 @@ module.exports = blockFromRpc * @param {Object} blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) * @param {Array.} Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) */ -function blockFromRpc (blockParams, uncles) { +function blockFromRpc(blockParams, uncles) { uncles = uncles || [] const block = new Block({ transactions: [], - uncleHeaders: [] + uncleHeaders: [], }) block.header = blockHeaderFromRpc(blockParams) - block.transactions = (blockParams.transactions || []).map(function (_txParams) { + block.transactions = (blockParams.transactions || []).map(function(_txParams) { const txParams = normalizeTxParams(_txParams) // override from address const fromAddress = ethUtil.toBuffer(txParams.from) delete txParams.from const tx = new Transaction(txParams) tx._from = fromAddress - tx.getSenderAddress = function () { return fromAddress } + tx.getSenderAddress = function() { + return fromAddress + } // override hash const txHash = ethUtil.toBuffer(txParams.hash) - tx.hash = function () { return txHash } + tx.hash = function() { + return txHash + } return tx }) - block.uncleHeaders = uncles.map(function (uncleParams) { + block.uncleHeaders = uncles.map(function(uncleParams) { return blockHeaderFromRpc(uncleParams) }) return block } -function normalizeTxParams (_txParams) { +function normalizeTxParams(_txParams) { const txParams = Object.assign({}, _txParams) // hot fix for https://github.com/ethereumjs/ethereumjs-util/issues/40 - txParams.gasLimit = (txParams.gasLimit === undefined) ? txParams.gas : txParams.gasLimit - txParams.data = (txParams.data === undefined) ? txParams.input : txParams.data + txParams.gasLimit = txParams.gasLimit === undefined ? txParams.gas : txParams.gasLimit + txParams.data = txParams.data === undefined ? txParams.input : txParams.data // strict byte length checking txParams.to = txParams.to ? ethUtil.setLengthLeft(ethUtil.toBuffer(txParams.to), 20) : null // v as raw signature value {0,1} diff --git a/header-from-rpc.js b/header-from-rpc.js index 21c7b38..48437bd 100644 --- a/header-from-rpc.js +++ b/header-from-rpc.js @@ -8,7 +8,7 @@ module.exports = blockHeaderFromRpc * Creates a new block header object from Ethereum JSON RPC. * @param {Object} blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) */ -function blockHeaderFromRpc (blockParams) { +function blockHeaderFromRpc(blockParams) { const blockHeader = new BlockHeader({ parentHash: blockParams.parentHash, uncleHash: blockParams.sha3Uncles, @@ -24,11 +24,11 @@ function blockHeaderFromRpc (blockParams) { timestamp: blockParams.timestamp, extraData: blockParams.extraData, mixHash: blockParams.mixHash, - nonce: blockParams.nonce + nonce: blockParams.nonce, }) // override hash incase something was missing - blockHeader.hash = function () { + blockHeader.hash = function() { return ethUtil.toBuffer(blockParams.hash) } diff --git a/header.js b/header.js index ed21c47..f700ca0 100644 --- a/header.js +++ b/header.js @@ -1,30 +1,30 @@ const Common = require('ethereumjs-common').default const utils = require('ethereumjs-util') const BN = utils.BN - /** - * An object that repersents the block header - * @constructor - * @param {Array} data raw data, deserialized - * @param {Array} opts Options - * @param {String|Number} opts.chain The chain for the block header [default: 'mainnet'] - * @param {String} opts.hardfork Hardfork for the block header [default: null, block number-based behaviour] - * @param {Object} opts.common Alternatively pass a Common instance instead of setting chain/hardfork directly - * @prop {Buffer} parentHash the blocks' parent's hash - * @prop {Buffer} uncleHash sha3(rlp_encode(uncle_list)) - * @prop {Buffer} coinbase the miner address - * @prop {Buffer} stateRoot The root of a Merkle Patricia tree - * @prop {Buffer} transactionTrie the root of a Trie containing the transactions - * @prop {Buffer} receiptTrie the root of a Trie containing the transaction Reciept - * @prop {Buffer} bloom - * @prop {Buffer} difficulty - * @prop {Buffer} number the block's height - * @prop {Buffer} gasLimit - * @prop {Buffer} gasUsed - * @prop {Buffer} timestamp - * @prop {Buffer} extraData - * @prop {Array.} raw an array of buffers containing the raw blocks. - */ -var BlockHeader = module.exports = function (data, opts) { +/** + * An object that repersents the block header + * @constructor + * @param {Array} data raw data, deserialized + * @param {Array} opts Options + * @param {String|Number} opts.chain The chain for the block header [default: 'mainnet'] + * @param {String} opts.hardfork Hardfork for the block header [default: null, block number-based behaviour] + * @param {Object} opts.common Alternatively pass a Common instance instead of setting chain/hardfork directly + * @prop {Buffer} parentHash the blocks' parent's hash + * @prop {Buffer} uncleHash sha3(rlp_encode(uncle_list)) + * @prop {Buffer} coinbase the miner address + * @prop {Buffer} stateRoot The root of a Merkle Patricia tree + * @prop {Buffer} transactionTrie the root of a Trie containing the transactions + * @prop {Buffer} receiptTrie the root of a Trie containing the transaction Reciept + * @prop {Buffer} bloom + * @prop {Buffer} difficulty + * @prop {Buffer} number the block's height + * @prop {Buffer} gasLimit + * @prop {Buffer} gasUsed + * @prop {Buffer} timestamp + * @prop {Buffer} extraData + * @prop {Array.} raw an array of buffers containing the raw blocks. + */ +var BlockHeader = (module.exports = function(data, opts) { opts = opts || {} if (opts.common) { @@ -38,64 +38,80 @@ var BlockHeader = module.exports = function (data, opts) { this._common = new Common(chain, hardfork) } - var fields = [{ - name: 'parentHash', - length: 32, - default: utils.zeros(32) - }, { - name: 'uncleHash', - default: utils.SHA3_RLP_ARRAY - }, { - name: 'coinbase', - length: 20, - default: utils.zeros(20) - }, { - name: 'stateRoot', - length: 32, - default: utils.zeros(32) - }, { - name: 'transactionsTrie', - length: 32, - default: utils.SHA3_RLP - }, { - name: 'receiptTrie', - length: 32, - default: utils.SHA3_RLP - }, { - name: 'bloom', - default: utils.zeros(256) - }, { - name: 'difficulty', - default: Buffer.from([]) - }, { - name: 'number', - // TODO: params.homeSteadForkNumber.v left for legacy reasons, replace on future release - default: utils.intToBuffer(1150000) - }, { - name: 'gasLimit', - default: Buffer.from('ffffffffffffff', 'hex') - }, { - name: 'gasUsed', - empty: true, - default: Buffer.from([]) - }, { - name: 'timestamp', - default: Buffer.from([]) - }, { - name: 'extraData', - allowZero: true, - empty: true, - default: Buffer.from([]) - }, { - name: 'mixHash', - default: utils.zeros(32) + var fields = [ + { + name: 'parentHash', + length: 32, + default: utils.zeros(32), + }, + { + name: 'uncleHash', + default: utils.SHA3_RLP_ARRAY, + }, + { + name: 'coinbase', + length: 20, + default: utils.zeros(20), + }, + { + name: 'stateRoot', + length: 32, + default: utils.zeros(32), + }, + { + name: 'transactionsTrie', + length: 32, + default: utils.SHA3_RLP, + }, + { + name: 'receiptTrie', + length: 32, + default: utils.SHA3_RLP, + }, + { + name: 'bloom', + default: utils.zeros(256), + }, + { + name: 'difficulty', + default: Buffer.from([]), + }, + { + name: 'number', + // TODO: params.homeSteadForkNumber.v left for legacy reasons, replace on future release + default: utils.intToBuffer(1150000), + }, + { + name: 'gasLimit', + default: Buffer.from('ffffffffffffff', 'hex'), + }, + { + name: 'gasUsed', + empty: true, + default: Buffer.from([]), + }, + { + name: 'timestamp', + default: Buffer.from([]), + }, + { + name: 'extraData', + allowZero: true, + empty: true, + default: Buffer.from([]), + }, + { + name: 'mixHash', + default: utils.zeros(32), // length: 32 - }, { - name: 'nonce', - default: utils.zeros(8) // sha3(42) - }] + }, + { + name: 'nonce', + default: utils.zeros(8), // sha3(42) + }, + ] utils.defineProperties(this, fields, data) -} +}) /** * Returns the canoncical difficulty of the block @@ -103,8 +119,9 @@ var BlockHeader = module.exports = function (data, opts) { * @param {Block} parentBlock the parent `Block` of the this header * @return {BN} */ -BlockHeader.prototype.canonicalDifficulty = function (parentBlock) { - const hardfork = this._common.hardfork() || this._common.activeHardfork(utils.bufferToInt(this.number)) +BlockHeader.prototype.canonicalDifficulty = function(parentBlock) { + const hardfork = + this._common.hardfork() || this._common.activeHardfork(utils.bufferToInt(this.number)) const blockTs = new BN(this.timestamp) const parentTs = new BN(parentBlock.header.timestamp) const parentDif = new BN(parentBlock.header.difficulty) @@ -118,7 +135,11 @@ BlockHeader.prototype.canonicalDifficulty = function (parentBlock) { if (this._common.hardforkGteHardfork(hardfork, 'byzantium')) { // max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99) (EIP100) var uncleAddend = parentBlock.header.uncleHash.equals(utils.SHA3_RLP_ARRAY) ? 1 : 2 - a = blockTs.sub(parentTs).idivn(9).ineg().iaddn(uncleAddend) + a = blockTs + .sub(parentTs) + .idivn(9) + .ineg() + .iaddn(uncleAddend) cutoff = new BN(-99) // MAX(cutoff, a) if (cutoff.cmp(a) === 1) { @@ -141,7 +162,11 @@ BlockHeader.prototype.canonicalDifficulty = function (parentBlock) { } } else if (this._common.hardforkGteHardfork(hardfork, 'homestead')) { // 1 - (block_timestamp - parent_timestamp) // 10 - a = blockTs.sub(parentTs).idivn(10).ineg().iaddn(1) + a = blockTs + .sub(parentTs) + .idivn(10) + .ineg() + .iaddn(1) cutoff = new BN(-99) // MAX(cutoff, a) if (cutoff.cmp(a) === 1) { @@ -175,7 +200,7 @@ BlockHeader.prototype.canonicalDifficulty = function (parentBlock) { * @param {Block} parentBlock this block's parent * @return {Boolean} */ -BlockHeader.prototype.validateDifficulty = function (parentBlock) { +BlockHeader.prototype.validateDifficulty = function(parentBlock) { const dif = this.canonicalDifficulty(parentBlock) return dif.cmp(new BN(this.difficulty)) === 0 } @@ -186,15 +211,21 @@ BlockHeader.prototype.validateDifficulty = function (parentBlock) { * @param {Block} parentBlock this block's parent * @returns {Boolean} */ -BlockHeader.prototype.validateGasLimit = function (parentBlock) { +BlockHeader.prototype.validateGasLimit = function(parentBlock) { const pGasLimit = new BN(parentBlock.header.gasLimit) const gasLimit = new BN(this.gasLimit) - const hardfork = this._common.hardfork() ? this._common.hardfork() : this._common.activeHardfork(this.number) + const hardfork = this._common.hardfork() + ? this._common.hardfork() + : this._common.activeHardfork(this.number) const a = pGasLimit.div(new BN(this._common.param('gasConfig', 'gasLimitBoundDivisor', hardfork))) const maxGasLimit = pGasLimit.add(a) const minGasLimit = pGasLimit.sub(a) - return gasLimit.lt(maxGasLimit) && gasLimit.gt(minGasLimit) && gasLimit.gte(this._common.param('gasConfig', 'minGasLimit', hardfork)) + return ( + gasLimit.lt(maxGasLimit) && + gasLimit.gt(minGasLimit) && + gasLimit.gte(this._common.param('gasConfig', 'minGasLimit', hardfork)) + ) } /** @@ -204,7 +235,7 @@ BlockHeader.prototype.validateGasLimit = function (parentBlock) { * @param {Bignum} [height] if this is an uncle header, this is the height of the block that is including it * @param {Function} cb the callback function. The callback is given an `error` if the block is invalid */ -BlockHeader.prototype.validate = function (blockchain, height, cb) { +BlockHeader.prototype.validate = function(blockchain, height, cb) { var self = this if (arguments.length === 2) { cb = height @@ -216,7 +247,7 @@ BlockHeader.prototype.validate = function (blockchain, height, cb) { } // find the blocks parent - blockchain.getBlock(self.parentHash, function (err, parentBlock) { + blockchain.getBlock(self.parentHash, function(err, parentBlock) { if (err) { return cb('could not find parent block') } @@ -251,7 +282,9 @@ BlockHeader.prototype.validate = function (blockchain, height, cb) { return cb('invalid timestamp') } - const hardfork = self._common.hardfork() ? self._common.hardfork() : self._common.activeHardfork(height) + const hardfork = self._common.hardfork() + ? self._common.hardfork() + : self._common.activeHardfork(height) if (self.extraData.length > self._common.param('vm', 'maxExtraDataSize', hardfork)) { return cb('invalid amount of extra data') } @@ -265,7 +298,7 @@ BlockHeader.prototype.validate = function (blockchain, height, cb) { * @method hash * @return {Buffer} */ -BlockHeader.prototype.hash = function () { +BlockHeader.prototype.hash = function() { return utils.rlphash(this.raw) } @@ -274,7 +307,7 @@ BlockHeader.prototype.hash = function () { * @method isGenesis * @return {Boolean} */ -BlockHeader.prototype.isGenesis = function () { +BlockHeader.prototype.isGenesis = function() { return this.number.toString('hex') === '' } @@ -282,7 +315,7 @@ BlockHeader.prototype.isGenesis = function () { * turns the header into the canonical genesis block header * @method setGenesisParams */ -BlockHeader.prototype.setGenesisParams = function () { +BlockHeader.prototype.setGenesisParams = function() { this.timestamp = this._common.genesis().timestamp this.gasLimit = this._common.genesis().gasLimit this.difficulty = this._common.genesis().difficulty diff --git a/index.js b/index.js index 32404f5..fd9ef21 100644 --- a/index.js +++ b/index.js @@ -19,7 +19,7 @@ const BlockHeader = require('./header') * @prop {Array.
} uncleList an array of uncle headers * @prop {Array.} raw an array of buffers containing the raw blocks. */ -var Block = module.exports = function (data, opts) { +var Block = (module.exports = function(data, opts) { opts = opts || {} if (opts.common) { @@ -39,9 +39,9 @@ var Block = module.exports = function (data, opts) { this.txTrie = new Trie() Object.defineProperty(this, 'raw', { - get: function () { + get: function() { return this.serialize(false) - } + }, }) var rawTransactions, rawUncleHeaders @@ -76,7 +76,7 @@ var Block = module.exports = function (data, opts) { tx._homestead = true this.transactions.push(tx) } -} +}) Block.Header = BlockHeader @@ -84,7 +84,7 @@ Block.Header = BlockHeader * Produces a hash the RLP of the block * @method hash */ -Block.prototype.hash = function () { +Block.prototype.hash = function() { return this.header.hash() } @@ -93,7 +93,7 @@ Block.prototype.hash = function () { * @method isGenisis * @return Boolean */ -Block.prototype.isGenesis = function () { +Block.prototype.isGenesis = function() { return this.header.isGenesis() } @@ -101,7 +101,7 @@ Block.prototype.isGenesis = function () { * turns the block into the canonical genesis block * @method setGenesisParams */ -Block.prototype.setGenesisParams = function () { +Block.prototype.setGenesisParams = function() { this.header.setGenesisParams() } @@ -110,21 +110,19 @@ Block.prototype.setGenesisParams = function () { * @method serialize * @param {Boolean} rlpEncode whether to rlp encode the block or not */ -Block.prototype.serialize = function (rlpEncode) { - var raw = [this.header.raw, [], - [] - ] +Block.prototype.serialize = function(rlpEncode) { + var raw = [this.header.raw, [], []] // rlpEnode defaults to true if (typeof rlpEncode === 'undefined') { rlpEncode = true } - this.transactions.forEach(function (tx) { + this.transactions.forEach(function(tx) { raw[1].push(tx.raw) }) - this.uncleHeaders.forEach(function (uncle) { + this.uncleHeaders.forEach(function(uncle) { raw[2].push(uncle.raw) }) @@ -137,14 +135,18 @@ Block.prototype.serialize = function (rlpEncode) { * @method genTxTrie * @param {Function} cb the callback */ -Block.prototype.genTxTrie = function (cb) { +Block.prototype.genTxTrie = function(cb) { var i = 0 var self = this - async.eachSeries(this.transactions, function (tx, done) { - self.txTrie.put(rlp.encode(i), tx.serialize(), done) - i++ - }, cb) + async.eachSeries( + this.transactions, + function(tx, done) { + self.txTrie.put(rlp.encode(i), tx.serialize(), done) + i++ + }, + cb, + ) } /** @@ -152,7 +154,7 @@ Block.prototype.genTxTrie = function (cb) { * @method validateTransactionTrie * @return {Boolean} */ -Block.prototype.validateTransactionsTrie = function () { +Block.prototype.validateTransactionsTrie = function() { var txT = this.header.transactionsTrie.toString('hex') if (this.transactions.length) { return txT === this.txTrie.root.toString('hex') @@ -167,10 +169,10 @@ Block.prototype.validateTransactionsTrie = function () { * @param {Boolean} [stringError=false] whether to return a string with a dscription of why the validation failed or return a Bloolean * @return {Boolean} */ -Block.prototype.validateTransactions = function (stringError) { +Block.prototype.validateTransactions = function(stringError) { var errors = [] - this.transactions.forEach(function (tx, i) { + this.transactions.forEach(function(tx, i) { var error = tx.validate(true) if (error) { errors.push(error + ' at tx ' + i) @@ -190,37 +192,40 @@ Block.prototype.validateTransactions = function (stringError) { * @param {BlockChain} blockChain the blockchain that this block wants to be part of * @param {Function} cb the callback which is given a `String` if the block is not valid */ -Block.prototype.validate = function (blockChain, cb) { +Block.prototype.validate = function(blockChain, cb) { var self = this var errors = [] - async.parallel([ - // validate uncles - self.validateUncles.bind(self, blockChain), - // validate block - self.header.validate.bind(self.header, blockChain), - // generate the transaction trie - self.genTxTrie.bind(self) - ], function (err) { - if (err) { - errors.push(err) - } + async.parallel( + [ + // validate uncles + self.validateUncles.bind(self, blockChain), + // validate block + self.header.validate.bind(self.header, blockChain), + // generate the transaction trie + self.genTxTrie.bind(self), + ], + function(err) { + if (err) { + errors.push(err) + } - if (!self.validateTransactionsTrie()) { - errors.push('invalid transaction trie') - } + if (!self.validateTransactionsTrie()) { + errors.push('invalid transaction trie') + } - var txErrors = self.validateTransactions(true) - if (txErrors !== '') { - errors.push(txErrors) - } + var txErrors = self.validateTransactions(true) + if (txErrors !== '') { + errors.push(txErrors) + } - if (!self.validateUnclesHash()) { - errors.push('invalid uncle hash') - } + if (!self.validateUnclesHash()) { + errors.push('invalid uncle hash') + } - cb(arrayToString(errors)) - }) + cb(arrayToString(errors)) + }, + ) } /** @@ -228,9 +233,9 @@ Block.prototype.validate = function (blockChain, cb) { * @method validateUncleHash * @return {Boolean} */ -Block.prototype.validateUnclesHash = function () { +Block.prototype.validateUnclesHash = function() { var raw = [] - this.uncleHeaders.forEach(function (uncle) { + this.uncleHeaders.forEach(function(uncle) { raw.push(uncle.raw) }) @@ -244,7 +249,7 @@ Block.prototype.validateUnclesHash = function () { * @param {Blockchain} blockChaina an instance of the Blockchain * @param {Function} cb the callback */ -Block.prototype.validateUncles = function (blockChain, cb) { +Block.prototype.validateUncles = function(blockChain, cb) { if (this.isGenesis()) { return cb() } @@ -255,31 +260,38 @@ Block.prototype.validateUncles = function (blockChain, cb) { return cb('too many uncle headers') } - var uncleHashes = self.uncleHeaders.map(function (header) { + var uncleHashes = self.uncleHeaders.map(function(header) { return header.hash().toString('hex') }) - if (!((new Set(uncleHashes)).size === uncleHashes.length)) { + if (!(new Set(uncleHashes).size === uncleHashes.length)) { return cb('duplicate uncles') } - async.each(self.uncleHeaders, function (uncle, cb2) { - var height = new BN(self.header.number) - async.parallel([ - uncle.validate.bind(uncle, blockChain, height), - // check to make sure the uncle is not already in the blockchain - function (cb3) { - blockChain.getDetails(uncle.hash(), function (err, blockInfo) { - // TODO: remove uncles from BC - if (blockInfo && blockInfo.isUncle) { - cb3(err || 'uncle already included') - } else { - cb3() - } - }) - } - ], cb2) - }, cb) + async.each( + self.uncleHeaders, + function(uncle, cb2) { + var height = new BN(self.header.number) + async.parallel( + [ + uncle.validate.bind(uncle, blockChain, height), + // check to make sure the uncle is not already in the blockchain + function(cb3) { + blockChain.getDetails(uncle.hash(), function(err, blockInfo) { + // TODO: remove uncles from BC + if (blockInfo && blockInfo.isUncle) { + cb3(err || 'uncle already included') + } else { + cb3() + } + }) + }, + ], + cb2, + ) + }, + cb, + ) } /** @@ -288,19 +300,19 @@ Block.prototype.validateUncles = function (blockChain, cb) { * @param {Bool} labeled whether to create an labeled object or an array * @return {Object} */ -Block.prototype.toJSON = function (labeled) { +Block.prototype.toJSON = function(labeled) { if (labeled) { var obj = { header: this.header.toJSON(true), transactions: [], - uncleHeaders: [] + uncleHeaders: [], } - this.transactions.forEach(function (tx) { + this.transactions.forEach(function(tx) { obj.transactions.push(tx.toJSON(labeled)) }) - this.uncleHeaders.forEach(function (uh) { + this.uncleHeaders.forEach(function(uh) { obj.uncleHeaders.push(uh.toJSON()) }) return obj @@ -309,9 +321,9 @@ Block.prototype.toJSON = function (labeled) { } } -function arrayToString (array) { +function arrayToString(array) { try { - return array.reduce(function (str, err) { + return array.reduce(function(str, err) { if (str) { str += ' ' } diff --git a/karma.conf.js b/karma.conf.js index 75eae96..9445846 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -1,14 +1,12 @@ process.env.ethTest = 'BasicTests' -module.exports = function (config) { +module.exports = function(config) { config.set({ browserNoActivityTimeout: 60000, frameworks: ['browserify', 'detectBrowsers', 'tap'], - files: [ - './tests/difficulty.js' - ], + files: ['./tests/difficulty.js'], preprocessors: { - 'tests/*.js': ['browserify', 'env'] + 'tests/*.js': ['browserify', 'env'], }, singleRun: true, plugins: [ @@ -17,33 +15,31 @@ module.exports = function (config) { 'karma-env-preprocessor', 'karma-tap', 'karma-firefox-launcher', - 'karma-detect-browsers' + 'karma-detect-browsers', ], browserify: { - 'transform': [ + transform: [ [ 'babelify', { - 'presets': [ - 'env' - ] - } - ] - ] + presets: ['env'], + }, + ], + ], }, detectBrowsers: { enabled: true, usePhantomJS: false, - postDetection: function (availableBrowser) { + postDetection: function(availableBrowser) { if (process.env.TRAVIS) { return ['Firefox'] } var browsers = ['Chrome', 'Firefox'] - return browsers.filter(function (browser) { + return browsers.filter(function(browser) { return availableBrowser.indexOf(browser) !== -1 }) - } - } + }, + }, }) } diff --git a/tests/block.js b/tests/block.js index 8806f2f..5e1062c 100644 --- a/tests/block.js +++ b/tests/block.js @@ -3,50 +3,60 @@ const Common = require('ethereumjs-common').default const rlp = require('ethereumjs-util').rlp const Block = require('../index.js') -tape('[Block]: block functions', function (t) { - t.test('should test block initialization', function (st) { - const block1 = new Block(null, { 'chain': 'ropsten' }) +tape('[Block]: block functions', function(t) { + t.test('should test block initialization', function(st) { + const block1 = new Block(null, { chain: 'ropsten' }) const common = new Common('ropsten') - const block2 = new Block(null, { 'common': common }) + const block2 = new Block(null, { common: common }) block1.setGenesisParams() block2.setGenesisParams() - st.strictEqual(block1.hash().toString('hex'), block2.hash().toString('hex'), 'block hashes match') + st.strictEqual( + block1.hash().toString('hex'), + block2.hash().toString('hex'), + 'block hashes match', + ) - st.throws(function () { new Block(null, { 'chain': 'ropsten', 'common': common }) }, /not allowed!$/, 'should throw on initialization with chain and common parameter') // eslint-disable-line + st.throws( + function() { + new Block(null, { chain: 'ropsten', common: common }) + }, + /not allowed!$/, + 'should throw on initialization with chain and common parameter', + ) // eslint-disable-line st.end() }) const testData = require('./testdata.json') - function testTransactionValidation (st, block) { + function testTransactionValidation(st, block) { st.equal(block.validateTransactions(), true) - block.genTxTrie(function () { + block.genTxTrie(function() { st.equal(block.validateTransactionsTrie(), true) st.end() }) } - t.test('should test transaction validation', function (st) { + t.test('should test transaction validation', function(st) { var block = new Block(rlp.decode(testData.blocks[0].rlp)) st.plan(2) testTransactionValidation(st, block) }) - t.test('should test transaction validation with empty transaction list', function (st) { + t.test('should test transaction validation with empty transaction list', function(st) { var block = new Block() st.plan(2) testTransactionValidation(st, block) }) const testData2 = require('./testdata2.json') - t.test('should test uncles hash validation', function (st) { + t.test('should test uncles hash validation', function(st) { var block = new Block(rlp.decode(testData2.blocks[2].rlp)) st.equal(block.validateUnclesHash(), true) st.end() }) - t.test('should test isGenesis (mainnet default)', function (st) { + t.test('should test isGenesis (mainnet default)', function(st) { var block = new Block() st.notEqual(block.isGenesis(), true) block.header.number = Buffer.from([]) @@ -54,8 +64,8 @@ tape('[Block]: block functions', function (t) { st.end() }) - t.test('should test isGenesis (ropsten)', function (st) { - var block = new Block(null, { 'chain': 'ropsten' }) + t.test('should test isGenesis (ropsten)', function(st) { + var block = new Block(null, { chain: 'ropsten' }) st.notEqual(block.isGenesis(), true) block.header.number = Buffer.from([]) st.equal(block.isGenesis(), true) @@ -63,43 +73,59 @@ tape('[Block]: block functions', function (t) { }) const testDataGenesis = require('./genesishashestest.json').test - t.test('should test genesis hashes (mainnet default)', function (st) { + t.test('should test genesis hashes (mainnet default)', function(st) { var genesisBlock = new Block() genesisBlock.setGenesisParams() var rlp = genesisBlock.serialize() st.strictEqual(rlp.toString('hex'), testDataGenesis.genesis_rlp_hex, 'rlp hex match') - st.strictEqual(genesisBlock.hash().toString('hex'), testDataGenesis.genesis_hash, 'genesis hash match') + st.strictEqual( + genesisBlock.hash().toString('hex'), + testDataGenesis.genesis_hash, + 'genesis hash match', + ) st.end() }) - t.test('should test genesis hashes (ropsten)', function (st) { + t.test('should test genesis hashes (ropsten)', function(st) { var common = new Common('ropsten') var genesisBlock = new Block(null, { common: common }) genesisBlock.setGenesisParams() - st.strictEqual(genesisBlock.hash().toString('hex'), common.genesis().hash.slice(2), 'genesis hash match') + st.strictEqual( + genesisBlock.hash().toString('hex'), + common.genesis().hash.slice(2), + 'genesis hash match', + ) st.end() }) - t.test('should test genesis hashes (rinkeby)', function (st) { + t.test('should test genesis hashes (rinkeby)', function(st) { var common = new Common('rinkeby') var genesisBlock = new Block(null, { common: common }) genesisBlock.setGenesisParams() - st.strictEqual(genesisBlock.hash().toString('hex'), common.genesis().hash.slice(2), 'genesis hash match') + st.strictEqual( + genesisBlock.hash().toString('hex'), + common.genesis().hash.slice(2), + 'genesis hash match', + ) st.end() }) - t.test('should test genesis parameters (ropsten)', function (st) { - var genesisBlock = new Block(null, { 'chain': 'ropsten' }) + t.test('should test genesis parameters (ropsten)', function(st) { + var genesisBlock = new Block(null, { chain: 'ropsten' }) genesisBlock.setGenesisParams() let ropstenStateRoot = '217b0bbcfb72e2d57e28f33cb361b9983513177755dc3f33ce3e7022ed62b77b' - st.strictEqual(genesisBlock.header.stateRoot.toString('hex'), ropstenStateRoot, 'genesis stateRoot match') + st.strictEqual( + genesisBlock.header.stateRoot.toString('hex'), + ropstenStateRoot, + 'genesis stateRoot match', + ) st.end() }) - t.test('should test toJSON', function (st) { + t.test('should test toJSON', function(st) { var block = new Block(rlp.decode(testData2.blocks[2].rlp)) - st.equal(typeof (block.toJSON()), 'object') - st.equal(typeof (block.toJSON(true)), 'object') + st.equal(typeof block.toJSON(), 'object') + st.equal(typeof block.toJSON(true), 'object') st.end() }) }) diff --git a/tests/difficulty.js b/tests/difficulty.js index b7ec1b3..feedc2b 100644 --- a/tests/difficulty.js +++ b/tests/difficulty.js @@ -3,16 +3,16 @@ const tape = require('tape') const Block = require('../') const BN = utils.BN -function normalize (data) { - Object.keys(data).map(function (i) { - if (i !== 'homestead' && typeof (data[i]) === 'string') { +function normalize(data) { + Object.keys(data).map(function(i) { + if (i !== 'homestead' && typeof data[i] === 'string') { data[i] = utils.isHexPrefixed(data[i]) ? new BN(utils.toBuffer(data[i])) : new BN(data[i]) } }) } tape('[Header]: difficulty tests', t => { - function runDifficultyTests (test, parentBlock, block, msg) { + function runDifficultyTests(test, parentBlock, block, msg) { normalize(test) var dif = block.header.canonicalDifficulty(parentBlock) @@ -21,21 +21,21 @@ tape('[Header]: difficulty tests', t => { } const hardforkTestData = { - 'chainstart': require('./difficultyFrontier.json').tests, - 'homestead': require('./difficultyHomestead.json').tests, - 'byzantium': require('./difficultyByzantium.json').tests, - 'constantinople': require('./difficultyConstantinople.json').tests + chainstart: require('./difficultyFrontier.json').tests, + homestead: require('./difficultyHomestead.json').tests, + byzantium: require('./difficultyByzantium.json').tests, + constantinople: require('./difficultyConstantinople.json').tests, } for (let hardfork in hardforkTestData) { const testData = hardforkTestData[hardfork] for (let testName in testData) { let test = testData[testName] - let parentBlock = new Block(null, { 'chain': 'mainnet', 'hardfork': hardfork }) + let parentBlock = new Block(null, { chain: 'mainnet', hardfork: hardfork }) parentBlock.header.timestamp = test.parentTimestamp parentBlock.header.difficulty = test.parentDifficulty parentBlock.header.uncleHash = test.parentUncles - let block = new Block(null, { 'chain': 'mainnet', 'hardfork': hardfork }) + let block = new Block(null, { chain: 'mainnet', hardfork: hardfork }) block.header.timestamp = test.currentTimestamp block.header.difficulty = test.currentDifficulty block.header.number = test.currentBlockNumber @@ -45,19 +45,19 @@ tape('[Header]: difficulty tests', t => { } const chainTestData = { - 'mainnet': require('./difficultyMainNetwork.json').tests, - 'ropsten': require('./difficultyRopstenConstantinople.json').tests + mainnet: require('./difficultyMainNetwork.json').tests, + ropsten: require('./difficultyRopstenConstantinople.json').tests, } for (let chain in chainTestData) { const testData = chainTestData[chain] for (let testName in testData) { let test = testData[testName] - let parentBlock = new Block(null, { 'chain': chain }) + let parentBlock = new Block(null, { chain: chain }) parentBlock.header.timestamp = test.parentTimestamp parentBlock.header.difficulty = test.parentDifficulty parentBlock.header.uncleHash = test.parentUncles - let block = new Block(null, { 'chain': chain }) + let block = new Block(null, { chain: chain }) block.header.timestamp = test.currentTimestamp block.header.difficulty = test.currentDifficulty block.header.number = test.currentBlockNumber diff --git a/tests/from-rpc.js b/tests/from-rpc.js index a16de3d..814394b 100644 --- a/tests/from-rpc.js +++ b/tests/from-rpc.js @@ -3,8 +3,8 @@ const tape = require('tape') const blockFromRpc = require('../from-rpc.js') const blockData = require('./testdata-from-rpc.json') -tape('[fromRPC]: block #2924874', function (t) { - t.test('should create a block with transactions with valid signatures', function (st) { +tape('[fromRPC]: block #2924874', function(t) { + t.test('should create a block with transactions with valid signatures', function(st) { let block = blockFromRpc(blockData) let allValid = block.transactions.every(tx => tx.verifySignature()) st.equal(allValid, true, 'all transaction signatures are valid') diff --git a/tests/genesishashestest.json b/tests/genesishashestest.json index c0b03f1..a2b0a5a 100644 --- a/tests/genesishashestest.json +++ b/tests/genesishashestest.json @@ -6,5 +6,5 @@ "genesis_rlp_hex": "f90219f90214a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000850400000000808213888080a011bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82faa00000000000000000000000000000000000000000000000000000000000000000880000000000000042c0c0", "genesis_state_root": "d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544", "genesis_hash": "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" - } + } } diff --git a/tests/header.js b/tests/header.js index 6a74e65..49ca9df 100644 --- a/tests/header.js +++ b/tests/header.js @@ -5,9 +5,9 @@ const rlp = utils.rlp const Header = require('../header.js') const Block = require('../index.js') -tape('[Block]: Header functions', function (t) { - t.test('should create with default constructor', function (st) { - function compareDefaultHeader (st, header) { +tape('[Block]: Header functions', function(t) { + t.test('should create with default constructor', function(st) { + function compareDefaultHeader(st, header) { st.deepEqual(header.parentHash, utils.zeros(32)) st.equal(header.uncleHash.toString('hex'), utils.SHA3_RLP_ARRAY_S) st.deepEqual(header.coinbase, utils.zeros(20)) @@ -35,19 +35,29 @@ tape('[Block]: Header functions', function (t) { st.end() }) - t.test('should test header initialization', function (st) { - const header1 = new Header(null, { 'chain': 'ropsten' }) + t.test('should test header initialization', function(st) { + const header1 = new Header(null, { chain: 'ropsten' }) const common = new Common('ropsten') - const header2 = new Header(null, { 'common': common }) + const header2 = new Header(null, { common: common }) header1.setGenesisParams() header2.setGenesisParams() - st.strictEqual(header1.hash().toString('hex'), header2.hash().toString('hex'), 'header hashes match') + st.strictEqual( + header1.hash().toString('hex'), + header2.hash().toString('hex'), + 'header hashes match', + ) - st.throws(function () { new Header(null, { 'chain': 'ropsten', 'common': common }) }, /not allowed!$/, 'should throw on initialization with chain and common parameter') // eslint-disable-line + st.throws( + function() { + new Header(null, { chain: 'ropsten', common: common }) + }, + /not allowed!$/, + 'should throw on initialization with chain and common parameter', + ) // eslint-disable-line st.end() }) - t.test('should test validateGasLimit', function (st) { + t.test('should test validateGasLimit', function(st) { const testData = require('./bcBlockGasLimitTest.json').tests const bcBlockGasLimigTestData = testData.BlockGasLimit2p63m1 @@ -60,7 +70,7 @@ tape('[Block]: Header functions', function (t) { st.end() }) - t.test('should test isGenesis', function (st) { + t.test('should test isGenesis', function(st) { var header = new Header() st.equal(header.isGenesis(), false) header.number = Buffer.from([]) @@ -69,18 +79,26 @@ tape('[Block]: Header functions', function (t) { }) const testDataGenesis = require('./genesishashestest.json').test - t.test('should test genesis hashes (mainnet default)', function (st) { + t.test('should test genesis hashes (mainnet default)', function(st) { var header = new Header() header.setGenesisParams() - st.strictEqual(header.hash().toString('hex'), testDataGenesis.genesis_hash, 'genesis hash match') + st.strictEqual( + header.hash().toString('hex'), + testDataGenesis.genesis_hash, + 'genesis hash match', + ) st.end() }) - t.test('should test genesis parameters (ropsten)', function (st) { - var genesisHeader = new Header(null, { 'chain': 'ropsten' }) + t.test('should test genesis parameters (ropsten)', function(st) { + var genesisHeader = new Header(null, { chain: 'ropsten' }) genesisHeader.setGenesisParams() let ropstenStateRoot = '217b0bbcfb72e2d57e28f33cb361b9983513177755dc3f33ce3e7022ed62b77b' - st.strictEqual(genesisHeader.stateRoot.toString('hex'), ropstenStateRoot, 'genesis stateRoot match') + st.strictEqual( + genesisHeader.stateRoot.toString('hex'), + ropstenStateRoot, + 'genesis stateRoot match', + ) st.end() }) }) diff --git a/tests/testdata-from-rpc.json b/tests/testdata-from-rpc.json index 0dafd6e..f79920a 100644 --- a/tests/testdata-from-rpc.json +++ b/tests/testdata-from-rpc.json @@ -12,85 +12,93 @@ "number": "0x2ca14a", "parentHash": "0x24f155bdf17217767531f464636fe4b84b87a38c53127541f952b3052adbac95", "receiptsRoot": "0x0eb6a50257911130ea2fa2e500e71e55e2dfc38eb97f64ca9cfca6faeabd693e", - "sealFields": ["0xcb3723ab82e84594d0ec9ed5a45fd976d5aba09903826e5ed5e06ae893011eaa", "0xa76a9a500301e044"], + "sealFields": [ + "0xcb3723ab82e84594d0ec9ed5a45fd976d5aba09903826e5ed5e06ae893011eaa", + "0xa76a9a500301e044" + ], "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "size": "0x3d7", "stateRoot": "0xdf97474b1b492cb6491cff267ca53c33aa42b611ba15239b4027a77275afeffc", "timestamp": "0x586afa54", "totalDifficulty": "0x61decf2ca7d9bbbf8", - "transactions": [{ - "blockHash": "0xc596cb892b649b4917da8c6b78611346d55daf7bcf4375da86a2d98810888e84", - "blockNumber": "0x2ca14a", - "creates": null, - "from": "0x41959417325160f8952bc933ae8317b4e5140dda", - "gas": "0x5e1b", - "gasPrice": "0x98bca5a00", - "hash": "0x542e06b2b8beb71305bf1bfd4d2088da9848d8795971d93d5f7893ecceef095b", - "input": "0x", - "nonce": "0x0", - "publicKey": "0x0ddc5f895f174466d0278ed91297d18346632fbcd98d902b4f36c1e3ac0fc2b14e3024c25280415a37ef1dccdb8118ea2232305485c0a87e17417637a972c7bd", - "r": "0x7150d00a9dcd8a8287ad220010c52ff2608906b746de23c993999768091ff210", - "raw": "0xf86c8085098bca5a00825e1b940c7c0b72004a7a66ffa780637427fed0c4faac478844004c09e76a00008025a07150d00a9dcd8a8287ad220010c52ff2608906b746de23c993999768091ff210a05585fabcd1dc415e1668d4cbc2d419cf0381bf9707480ad2f86d0800732f6d7e", - "s": "0x5585fabcd1dc415e1668d4cbc2d419cf0381bf9707480ad2f86d0800732f6d7e", - "to": "0x0c7c0b72004a7a66ffa780637427fed0c4faac47", - "transactionIndex": "0x0", - "v": 0, - "value": "0x44004c09e76a0000" - }, { - "blockHash": "0xc596cb892b649b4917da8c6b78611346d55daf7bcf4375da86a2d98810888e84", - "blockNumber": "0x2ca14a", - "creates": null, - "from": "0x56ce1399be2831f8a3f918a0408c05bbad658ef3", - "gas": "0x5208", - "gasPrice": "0x4e3b29200", - "hash": "0xe9e15dd4f1070ec30ca4bfbe70738e78b0bb7d126a512e7dc9b22df5b64af791", - "input": "0x", - "nonce": "0x9d", - "publicKey": "0x82a51957d31375120093359ab7beefe9d7d68579d6e40b99d85bff1283a687f8a88c0f3c0a1160f68df814a3bfe7f649a4c16f9b6dbdaf289e6dec93bf083287", - "r": "0x5d92c10b5789801d4ce0fc558eedc6e6cccbaf0105a7c1f909feabcedfe56cd9", - "raw": "0xf86d819d8504e3b2920082520894f4702bb51b8270729db362b0d4f82a56bdd66c6588120a871cc0020000801ba05d92c10b5789801d4ce0fc558eedc6e6cccbaf0105a7c1f909feabcedfe56cd9a072cc370fa5fd3b43c2ba4e9e70fea1b5e950b4261ab4274982d8ae15a3403a33", - "s": "0x72cc370fa5fd3b43c2ba4e9e70fea1b5e950b4261ab4274982d8ae15a3403a33", - "to": "0xf4702bb51b8270729db362b0d4f82a56bdd66c65", - "transactionIndex": "0x1", - "v": 0, - "value": "0x120a871cc0020000" - }, { - "blockHash": "0xc596cb892b649b4917da8c6b78611346d55daf7bcf4375da86a2d98810888e84", - "blockNumber": "0x2ca14a", - "creates": null, - "from": "0x1e9939daaad6924ad004c2560e90804164900341", - "gas": "0x9858", - "gasPrice": "0x4a817c800", - "hash": "0x3078eeb8227d104338666de260aac59c141a08f519856fd8b7253398d9347f51", - "input": "0x", - "nonce": "0x22f5d", - "publicKey": "0x9fd89da696721cb906af81fe5d8bc3d0a4a7368be52db98d9e3a2d7c5f7aef545e8e578c2a158236d6221512c5df892b23bbe1087966f134799d6e36d3097973", - "r": "0x7ee15b226f6c767ccace78a4b5b4cbf0be6ec20a899e058d3c95977bacd0cbd5", - "raw": "0xf86f83022f5d8504a817c80082985894b8201140a49b0d5b65a23b4b2fa8a6efff87c576880de4ea09ac8f1e888025a07ee15b226f6c767ccace78a4b5b4cbf0be6ec20a899e058d3c95977bacd0cbd5a027e75bcd3bfd199e8c3e3f0c90b0d39f01b773b3da64060e06c0d568ae5c7523", - "s": "0x27e75bcd3bfd199e8c3e3f0c90b0d39f01b773b3da64060e06c0d568ae5c7523", - "to": "0xb8201140a49b0d5b65a23b4b2fa8a6efff87c576", - "transactionIndex": "0x2", - "v": 0, - "value": "0xde4ea09ac8f1e88" - }, { - "blockHash": "0xc596cb892b649b4917da8c6b78611346d55daf7bcf4375da86a2d98810888e84", - "blockNumber": "0x2ca14a", - "creates": null, - "from": "0xea674fdde714fd979de3edf0f56aa9716b898ec8", - "gas": "0x15f90", - "gasPrice": "0x4a817c800", - "hash": "0x9de43b061e5286ab1ad7494f50fac1ec9b541998800f9388ae6e7119f312c5cd", - "input": "0x", - "nonce": "0xfc02d", - "publicKey": "0x5d8af02c52b1fb40e45d6e04ae2351d443d1f7327e9b6dbb5ae1d918414899c625690c4c236889e23d9705f9db88876542b959d947a3497a30d0d922ee30015f", - "r": "0x059934eeace580cc2bdc292415976692c751f0bcb025930bd40fcc31e91208f3", - "raw": "0xf870830fc02d8504a817c80083015f9094c4f381af25c41786110242623373cc9c7647f3f1880e139507cd50c0188026a0059934eeace580cc2bdc292415976692c751f0bcb025930bd40fcc31e91208f3a077ff34a10a3de0d906a0363b4bdbc0e9a06cb4378476d96dfd446225d8d9949c", - "s": "0x77ff34a10a3de0d906a0363b4bdbc0e9a06cb4378476d96dfd446225d8d9949c", - "to": "0xc4f381af25c41786110242623373cc9c7647f3f1", - "transactionIndex": "0x3", - "v": 1, - "value": "0xe139507cd50c018" - }], + "transactions": [ + { + "blockHash": "0xc596cb892b649b4917da8c6b78611346d55daf7bcf4375da86a2d98810888e84", + "blockNumber": "0x2ca14a", + "creates": null, + "from": "0x41959417325160f8952bc933ae8317b4e5140dda", + "gas": "0x5e1b", + "gasPrice": "0x98bca5a00", + "hash": "0x542e06b2b8beb71305bf1bfd4d2088da9848d8795971d93d5f7893ecceef095b", + "input": "0x", + "nonce": "0x0", + "publicKey": "0x0ddc5f895f174466d0278ed91297d18346632fbcd98d902b4f36c1e3ac0fc2b14e3024c25280415a37ef1dccdb8118ea2232305485c0a87e17417637a972c7bd", + "r": "0x7150d00a9dcd8a8287ad220010c52ff2608906b746de23c993999768091ff210", + "raw": "0xf86c8085098bca5a00825e1b940c7c0b72004a7a66ffa780637427fed0c4faac478844004c09e76a00008025a07150d00a9dcd8a8287ad220010c52ff2608906b746de23c993999768091ff210a05585fabcd1dc415e1668d4cbc2d419cf0381bf9707480ad2f86d0800732f6d7e", + "s": "0x5585fabcd1dc415e1668d4cbc2d419cf0381bf9707480ad2f86d0800732f6d7e", + "to": "0x0c7c0b72004a7a66ffa780637427fed0c4faac47", + "transactionIndex": "0x0", + "v": 0, + "value": "0x44004c09e76a0000" + }, + { + "blockHash": "0xc596cb892b649b4917da8c6b78611346d55daf7bcf4375da86a2d98810888e84", + "blockNumber": "0x2ca14a", + "creates": null, + "from": "0x56ce1399be2831f8a3f918a0408c05bbad658ef3", + "gas": "0x5208", + "gasPrice": "0x4e3b29200", + "hash": "0xe9e15dd4f1070ec30ca4bfbe70738e78b0bb7d126a512e7dc9b22df5b64af791", + "input": "0x", + "nonce": "0x9d", + "publicKey": "0x82a51957d31375120093359ab7beefe9d7d68579d6e40b99d85bff1283a687f8a88c0f3c0a1160f68df814a3bfe7f649a4c16f9b6dbdaf289e6dec93bf083287", + "r": "0x5d92c10b5789801d4ce0fc558eedc6e6cccbaf0105a7c1f909feabcedfe56cd9", + "raw": "0xf86d819d8504e3b2920082520894f4702bb51b8270729db362b0d4f82a56bdd66c6588120a871cc0020000801ba05d92c10b5789801d4ce0fc558eedc6e6cccbaf0105a7c1f909feabcedfe56cd9a072cc370fa5fd3b43c2ba4e9e70fea1b5e950b4261ab4274982d8ae15a3403a33", + "s": "0x72cc370fa5fd3b43c2ba4e9e70fea1b5e950b4261ab4274982d8ae15a3403a33", + "to": "0xf4702bb51b8270729db362b0d4f82a56bdd66c65", + "transactionIndex": "0x1", + "v": 0, + "value": "0x120a871cc0020000" + }, + { + "blockHash": "0xc596cb892b649b4917da8c6b78611346d55daf7bcf4375da86a2d98810888e84", + "blockNumber": "0x2ca14a", + "creates": null, + "from": "0x1e9939daaad6924ad004c2560e90804164900341", + "gas": "0x9858", + "gasPrice": "0x4a817c800", + "hash": "0x3078eeb8227d104338666de260aac59c141a08f519856fd8b7253398d9347f51", + "input": "0x", + "nonce": "0x22f5d", + "publicKey": "0x9fd89da696721cb906af81fe5d8bc3d0a4a7368be52db98d9e3a2d7c5f7aef545e8e578c2a158236d6221512c5df892b23bbe1087966f134799d6e36d3097973", + "r": "0x7ee15b226f6c767ccace78a4b5b4cbf0be6ec20a899e058d3c95977bacd0cbd5", + "raw": "0xf86f83022f5d8504a817c80082985894b8201140a49b0d5b65a23b4b2fa8a6efff87c576880de4ea09ac8f1e888025a07ee15b226f6c767ccace78a4b5b4cbf0be6ec20a899e058d3c95977bacd0cbd5a027e75bcd3bfd199e8c3e3f0c90b0d39f01b773b3da64060e06c0d568ae5c7523", + "s": "0x27e75bcd3bfd199e8c3e3f0c90b0d39f01b773b3da64060e06c0d568ae5c7523", + "to": "0xb8201140a49b0d5b65a23b4b2fa8a6efff87c576", + "transactionIndex": "0x2", + "v": 0, + "value": "0xde4ea09ac8f1e88" + }, + { + "blockHash": "0xc596cb892b649b4917da8c6b78611346d55daf7bcf4375da86a2d98810888e84", + "blockNumber": "0x2ca14a", + "creates": null, + "from": "0xea674fdde714fd979de3edf0f56aa9716b898ec8", + "gas": "0x15f90", + "gasPrice": "0x4a817c800", + "hash": "0x9de43b061e5286ab1ad7494f50fac1ec9b541998800f9388ae6e7119f312c5cd", + "input": "0x", + "nonce": "0xfc02d", + "publicKey": "0x5d8af02c52b1fb40e45d6e04ae2351d443d1f7327e9b6dbb5ae1d918414899c625690c4c236889e23d9705f9db88876542b959d947a3497a30d0d922ee30015f", + "r": "0x059934eeace580cc2bdc292415976692c751f0bcb025930bd40fcc31e91208f3", + "raw": "0xf870830fc02d8504a817c80083015f9094c4f381af25c41786110242623373cc9c7647f3f1880e139507cd50c0188026a0059934eeace580cc2bdc292415976692c751f0bcb025930bd40fcc31e91208f3a077ff34a10a3de0d906a0363b4bdbc0e9a06cb4378476d96dfd446225d8d9949c", + "s": "0x77ff34a10a3de0d906a0363b4bdbc0e9a06cb4378476d96dfd446225d8d9949c", + "to": "0xc4f381af25c41786110242623373cc9c7647f3f1", + "transactionIndex": "0x3", + "v": 1, + "value": "0xe139507cd50c018" + } + ], "transactionsRoot": "0xe307e6d0e13f41ed336e09d71deb59a354eee4121449f0286cfb076e767fd45b", "uncles": [] } diff --git a/tests/testdata2.json b/tests/testdata2.json index f1eb464..14e7432 100644 --- a/tests/testdata2.json +++ b/tests/testdata2.json @@ -4,7 +4,8 @@ "filledwith": "cpp-1.3.0+commit.26123543.Linux.g++", "source": "/src/BlockchainTestsFiller/bcUncleHeaderValiditiy/correctFiller.json" }, - "blocks": [{ + "blocks": [ + { "blockHeader": { "bloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "coinbase": "0x8888f1f195afa192cfee860698584c030f4c9db1", @@ -24,17 +25,19 @@ "uncleHash": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" }, "rlp": "0xf90261f901f9a05a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5aea01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0cb52de543653d86ccd13ba3ddf8b052525b04231c6884a4db3188a184681d878a05c9151c2413d1cd25c51ffb4ac38948acc1359bf08c6b49f283660e9bcf0f516a0e9244cf7503b79c03d3a099e07a80d2dbc77bb0b502d8a89d51ac0d68dd31313b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000001832fefba825208845982d2cb80a0c62911f4c54474a95c8f49044e4cf77aa7bb4c6534887d80ddc1a1ccdad9d3e8884e379cdf33222ddff862f86080018304cb2f94095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba077c7cd36820c71821c1aed59de46e70e701c4a8dd89c9ba508ab722210f60da8a03f29825d40c7c3f7bff3ca69267e0f3fb74b2d18b8c2c4e3c135b5d3b06e288dc0", - "transactions": [{ - "data": "", - "gasLimit": "0x04cb2f", - "gasPrice": "0x01", - "nonce": "0x00", - "r": "0x77c7cd36820c71821c1aed59de46e70e701c4a8dd89c9ba508ab722210f60da8", - "s": "0x3f29825d40c7c3f7bff3ca69267e0f3fb74b2d18b8c2c4e3c135b5d3b06e288d", - "to": "0x095e7baea6a6c7c4c2dfeb977efac326af552d87", - "v": "0x1b", - "value": "0x0a" - }], + "transactions": [ + { + "data": "", + "gasLimit": "0x04cb2f", + "gasPrice": "0x01", + "nonce": "0x00", + "r": "0x77c7cd36820c71821c1aed59de46e70e701c4a8dd89c9ba508ab722210f60da8", + "s": "0x3f29825d40c7c3f7bff3ca69267e0f3fb74b2d18b8c2c4e3c135b5d3b06e288d", + "to": "0x095e7baea6a6c7c4c2dfeb977efac326af552d87", + "v": "0x1b", + "value": "0x0a" + } + ], "uncleHeaders": [] }, { @@ -57,17 +60,19 @@ "uncleHash": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" }, "rlp": "0xf90260f901f9a0ca028b1318795714d130a99d8023bd7463cf8084f31d2f95f1a2d9eb342e9caca01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0e7e4760f75476ec7f51869d8bdce5c693058fd5a95c77ea9c0bf7ced1e50d70ea0c673e076264c4669a5c2e479f1757b78e42511efe33b5fd2c0a23b929c7f87f5a05ea1a8b24652fed0ecab4738edd9211891eb8c4353c345973b78a02cc0f32f6bb90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302004002832fefba825208845982d2cd80a06695294f40e94ba1641fad8c4827dfa8929c8b5b6df64bf79dae8067ae5809ca88b4fca9b7d3af4eccf861f85f01018304cb2f94095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba033c86e64d708c97c6b135cadff79dbf45985aa0b53694789e90d15f756765f239f1d0f8caa2a16405148c9d85581be5814960010f3cba938b5501590cea1f7cfc0", - "transactions": [{ - "data": "", - "gasLimit": "0x04cb2f", - "gasPrice": "0x01", - "nonce": "0x01", - "r": "0x33c86e64d708c97c6b135cadff79dbf45985aa0b53694789e90d15f756765f23", - "s": "0x1d0f8caa2a16405148c9d85581be5814960010f3cba938b5501590cea1f7cf", - "to": "0x095e7baea6a6c7c4c2dfeb977efac326af552d87", - "v": "0x1b", - "value": "0x0a" - }], + "transactions": [ + { + "data": "", + "gasLimit": "0x04cb2f", + "gasPrice": "0x01", + "nonce": "0x01", + "r": "0x33c86e64d708c97c6b135cadff79dbf45985aa0b53694789e90d15f756765f23", + "s": "0x1d0f8caa2a16405148c9d85581be5814960010f3cba938b5501590cea1f7cf", + "to": "0x095e7baea6a6c7c4c2dfeb977efac326af552d87", + "v": "0x1b", + "value": "0x0a" + } + ], "uncleHeaders": [] }, { @@ -90,35 +95,39 @@ "uncleHash": "0xbeb175854a56183e630cd77e1c6dcd50a8bab221f81f2376919c649b33c500e0" }, "rlp": "0xf9045df901f9a02b530c31b2556d8ad5e12311658f0ec47e35a4ceffecd83d06e7cd918d3a85f1a0beb175854a56183e630cd77e1c6dcd50a8bab221f81f2376919c649b33c500e0948888f1f195afa192cfee860698584c030f4c9db1a077f96f4c766c10cd0207e2672b1b747c741ed75bc94e7be7abacb71cdca3c8fba01722b8a91bfc4f5614ce36ee77c7cce6620ab4af36d3c54baa66d7dbeb7bce1aa04ede0225773c7a517b91994aca65ade45124e7ef4b8be1e6097c9773a11920afb90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302008003832fefba825208845982d2d180a016bd3db367a3b218565e6744de193fb601587af40ba093e8e3cf9b29f0aa4ff188f5c0d237b1a07faaf862f86002018304cb2f94095e7baea6a6c7c4c2dfeb977efac326af552d870a801ca015eb1cc916728b9799e55c489857727669afb2986433d5f54cde11faaed9f0eea05d36f6d06c34aae8d0a2a5895c8ba4a17ad46a5fa59f361cb3e7e01a23030e38f901faf901f7a0ca028b1318795714d130a99d8023bd7463cf8084f31d2f95f1a2d9eb342e9caca01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0cb52de543653d86ccd13ba3ddf8b052525b04231c6884a4db3188a184681d878a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302004002832fefba80845982d2cf80a0b5488407bc8b147a9b3c4811864ebfc5bdb568fc8f91dcf9232ed6b7429c52f8882b9b47250942c14e", - "transactions": [{ - "data": "", - "gasLimit": "0x04cb2f", - "gasPrice": "0x01", - "nonce": "0x02", - "r": "0x15eb1cc916728b9799e55c489857727669afb2986433d5f54cde11faaed9f0ee", - "s": "0x5d36f6d06c34aae8d0a2a5895c8ba4a17ad46a5fa59f361cb3e7e01a23030e38", - "to": "0x095e7baea6a6c7c4c2dfeb977efac326af552d87", - "v": "0x1c", - "value": "0x0a" - }], - "uncleHeaders": [{ - "bloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "coinbase": "0x0000000000000000000000000000000000000000", - "difficulty": "0x020040", - "extraData": "", - "gasLimit": "0x2fefba", - "gasUsed": "0x00", - "hash": "0xcac5903348d2b4ca370227f7bd24bc3101b327a05172a3d7d3106a11d2019c16", - "mixHash": "0xb5488407bc8b147a9b3c4811864ebfc5bdb568fc8f91dcf9232ed6b7429c52f8", - "nonce": "0x2b9b47250942c14e", - "number": "0x02", - "parentHash": "0xca028b1318795714d130a99d8023bd7463cf8084f31d2f95f1a2d9eb342e9cac", - "receiptTrie": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", - "stateRoot": "0xcb52de543653d86ccd13ba3ddf8b052525b04231c6884a4db3188a184681d878", - "timestamp": "0x5982d2cf", - "transactionsTrie": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", - "uncleHash": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" - }] + "transactions": [ + { + "data": "", + "gasLimit": "0x04cb2f", + "gasPrice": "0x01", + "nonce": "0x02", + "r": "0x15eb1cc916728b9799e55c489857727669afb2986433d5f54cde11faaed9f0ee", + "s": "0x5d36f6d06c34aae8d0a2a5895c8ba4a17ad46a5fa59f361cb3e7e01a23030e38", + "to": "0x095e7baea6a6c7c4c2dfeb977efac326af552d87", + "v": "0x1c", + "value": "0x0a" + } + ], + "uncleHeaders": [ + { + "bloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "difficulty": "0x020040", + "extraData": "", + "gasLimit": "0x2fefba", + "gasUsed": "0x00", + "hash": "0xcac5903348d2b4ca370227f7bd24bc3101b327a05172a3d7d3106a11d2019c16", + "mixHash": "0xb5488407bc8b147a9b3c4811864ebfc5bdb568fc8f91dcf9232ed6b7429c52f8", + "nonce": "0x2b9b47250942c14e", + "number": "0x02", + "parentHash": "0xca028b1318795714d130a99d8023bd7463cf8084f31d2f95f1a2d9eb342e9cac", + "receiptTrie": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "stateRoot": "0xcb52de543653d86ccd13ba3ddf8b052525b04231c6884a4db3188a184681d878", + "timestamp": "0x5982d2cf", + "transactionsTrie": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + "uncleHash": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" + } + ] } ], "genesisBlockHeader": { @@ -176,4 +185,4 @@ "storage": {} } } -} \ No newline at end of file +} From a8a9ee9e10493afd47f6d633fee17f802f4339a8 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Thu, 25 Jul 2019 14:52:56 -0300 Subject: [PATCH 03/25] Move sources to /src --- from-rpc.js => src/from-rpc.js | 0 header-from-rpc.js => src/header-from-rpc.js | 0 header.js => src/header.js | 0 index.js => src/index.js | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename from-rpc.js => src/from-rpc.js (100%) rename header-from-rpc.js => src/header-from-rpc.js (100%) rename header.js => src/header.js (100%) rename index.js => src/index.js (100%) diff --git a/from-rpc.js b/src/from-rpc.js similarity index 100% rename from from-rpc.js rename to src/from-rpc.js diff --git a/header-from-rpc.js b/src/header-from-rpc.js similarity index 100% rename from header-from-rpc.js rename to src/header-from-rpc.js diff --git a/header.js b/src/header.js similarity index 100% rename from header.js rename to src/header.js diff --git a/index.js b/src/index.js similarity index 100% rename from index.js rename to src/index.js From f230334a06b81c2e5cc347803ee652c337dcec4b Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Thu, 25 Jul 2019 14:53:07 -0300 Subject: [PATCH 04/25] Move tests to test/ --- {tests => test}/bcBlockGasLimitTest.json | 0 {tests => test}/block.js | 0 {tests => test}/difficulty.js | 0 {tests => test}/difficultyByzantium.json | 0 {tests => test}/difficultyConstantinople.json | 0 {tests => test}/difficultyFrontier.json | 0 {tests => test}/difficultyHomestead.json | 0 {tests => test}/difficultyMainNetwork.json | 0 {tests => test}/difficultyRopstenByzantium.json | 0 {tests => test}/difficultyRopstenConstantinople.json | 0 {tests => test}/from-rpc.js | 0 {tests => test}/genesishashestest.json | 0 {tests => test}/header.js | 0 {tests => test}/index.js | 0 {tests => test}/testdata-from-rpc.json | 0 {tests => test}/testdata.json | 0 {tests => test}/testdata2.json | 0 17 files changed, 0 insertions(+), 0 deletions(-) rename {tests => test}/bcBlockGasLimitTest.json (100%) rename {tests => test}/block.js (100%) rename {tests => test}/difficulty.js (100%) rename {tests => test}/difficultyByzantium.json (100%) rename {tests => test}/difficultyConstantinople.json (100%) rename {tests => test}/difficultyFrontier.json (100%) rename {tests => test}/difficultyHomestead.json (100%) rename {tests => test}/difficultyMainNetwork.json (100%) rename {tests => test}/difficultyRopstenByzantium.json (100%) rename {tests => test}/difficultyRopstenConstantinople.json (100%) rename {tests => test}/from-rpc.js (100%) rename {tests => test}/genesishashestest.json (100%) rename {tests => test}/header.js (100%) rename {tests => test}/index.js (100%) rename {tests => test}/testdata-from-rpc.json (100%) rename {tests => test}/testdata.json (100%) rename {tests => test}/testdata2.json (100%) diff --git a/tests/bcBlockGasLimitTest.json b/test/bcBlockGasLimitTest.json similarity index 100% rename from tests/bcBlockGasLimitTest.json rename to test/bcBlockGasLimitTest.json diff --git a/tests/block.js b/test/block.js similarity index 100% rename from tests/block.js rename to test/block.js diff --git a/tests/difficulty.js b/test/difficulty.js similarity index 100% rename from tests/difficulty.js rename to test/difficulty.js diff --git a/tests/difficultyByzantium.json b/test/difficultyByzantium.json similarity index 100% rename from tests/difficultyByzantium.json rename to test/difficultyByzantium.json diff --git a/tests/difficultyConstantinople.json b/test/difficultyConstantinople.json similarity index 100% rename from tests/difficultyConstantinople.json rename to test/difficultyConstantinople.json diff --git a/tests/difficultyFrontier.json b/test/difficultyFrontier.json similarity index 100% rename from tests/difficultyFrontier.json rename to test/difficultyFrontier.json diff --git a/tests/difficultyHomestead.json b/test/difficultyHomestead.json similarity index 100% rename from tests/difficultyHomestead.json rename to test/difficultyHomestead.json diff --git a/tests/difficultyMainNetwork.json b/test/difficultyMainNetwork.json similarity index 100% rename from tests/difficultyMainNetwork.json rename to test/difficultyMainNetwork.json diff --git a/tests/difficultyRopstenByzantium.json b/test/difficultyRopstenByzantium.json similarity index 100% rename from tests/difficultyRopstenByzantium.json rename to test/difficultyRopstenByzantium.json diff --git a/tests/difficultyRopstenConstantinople.json b/test/difficultyRopstenConstantinople.json similarity index 100% rename from tests/difficultyRopstenConstantinople.json rename to test/difficultyRopstenConstantinople.json diff --git a/tests/from-rpc.js b/test/from-rpc.js similarity index 100% rename from tests/from-rpc.js rename to test/from-rpc.js diff --git a/tests/genesishashestest.json b/test/genesishashestest.json similarity index 100% rename from tests/genesishashestest.json rename to test/genesishashestest.json diff --git a/tests/header.js b/test/header.js similarity index 100% rename from tests/header.js rename to test/header.js diff --git a/tests/index.js b/test/index.js similarity index 100% rename from tests/index.js rename to test/index.js diff --git a/tests/testdata-from-rpc.json b/test/testdata-from-rpc.json similarity index 100% rename from tests/testdata-from-rpc.json rename to test/testdata-from-rpc.json diff --git a/tests/testdata.json b/test/testdata.json similarity index 100% rename from tests/testdata.json rename to test/testdata.json diff --git a/tests/testdata2.json b/test/testdata2.json similarity index 100% rename from tests/testdata2.json rename to test/testdata2.json From f87ab987fe02ff841174de6fa607dcf84f9fde76 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Thu, 25 Jul 2019 14:54:05 -0300 Subject: [PATCH 05/25] Rename sources to .ts --- src/{from-rpc.js => from-rpc.ts} | 0 src/{header-from-rpc.js => header-from-rpc.ts} | 0 src/{header.js => header.ts} | 0 src/{index.js => index.ts} | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename src/{from-rpc.js => from-rpc.ts} (100%) rename src/{header-from-rpc.js => header-from-rpc.ts} (100%) rename src/{header.js => header.ts} (100%) rename src/{index.js => index.ts} (100%) diff --git a/src/from-rpc.js b/src/from-rpc.ts similarity index 100% rename from src/from-rpc.js rename to src/from-rpc.ts diff --git a/src/header-from-rpc.js b/src/header-from-rpc.ts similarity index 100% rename from src/header-from-rpc.js rename to src/header-from-rpc.ts diff --git a/src/header.js b/src/header.ts similarity index 100% rename from src/header.js rename to src/header.ts diff --git a/src/index.js b/src/index.ts similarity index 100% rename from src/index.js rename to src/index.ts From 1727cf621ec220fa8854ca0dfc064aabdf6c1577 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Thu, 25 Jul 2019 18:18:35 -0300 Subject: [PATCH 06/25] Initial migration --- .gitignore | 47 +- .travis.yml | 19 +- CHANGELOG.md | 56 ++- README.md | 24 +- docs/fromRpc.md | 6 +- docs/index.md | 104 ++--- karma.conf.js | 37 +- package.json | 75 ++-- src/block.ts | 303 +++++++++++++ src/callbackify.ts | 77 ++++ src/from-rpc.ts | 112 ++--- src/header-from-rpc.ts | 72 +-- src/header.ts | 603 ++++++++++++++------------ src/index.ts | 338 +-------------- src/types.ts | 77 ++++ test/{block.js => block.ts} | 45 +- test/{difficulty.js => difficulty.ts} | 46 +- test/from-rpc.js | 13 - test/from-rpc.ts | 13 + test/{header.js => header.ts} | 44 +- test/index.js | 4 - test/index.ts | 4 + tsconfig.json | 3 +- tsconfig.prod.json | 3 +- tslint.json | 5 +- 25 files changed, 1173 insertions(+), 957 deletions(-) create mode 100644 src/block.ts create mode 100644 src/callbackify.ts create mode 100644 src/types.ts rename test/{block.js => block.ts} (71%) rename test/{difficulty.js => difficulty.ts} (65%) delete mode 100644 test/from-rpc.js create mode 100644 test/from-rpc.ts rename test/{header.js => header.ts} (65%) delete mode 100644 test/index.js create mode 100644 test/index.ts diff --git a/.gitignore b/.gitignore index 67d3750..42b42f8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,30 +1,33 @@ .idea +package-lock.json +test-build +dist # Created by https://www.gitignore.io/api/osx,node ### OSX ### -*.DS_Store -.AppleDouble -.LSOverride - -# Icon must end with two \r -Icon -# Thumbnails -._* -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns -.com.apple.timemachine.donotpresent -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon +# Thumbnails +._* +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk ### Node ### diff --git a/.travis.yml b/.travis.yml index fdd5946..8c67ccd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,9 @@ language: node_js node_js: - - "7" - "8" -env: - - CXX=g++-4.8 + - "10" + - "11" + - "12" addons: firefox: latest apt: @@ -14,6 +14,7 @@ addons: before_install: - sh -e /etc/init.d/xvfb start env: + - CXX=g++-4.8 global: - DISPLAY=:99.0 matrix: @@ -28,9 +29,19 @@ matrix: node_js: "8" env: CXX=g++-4.8 TEST_SUITE=lint - os: linux - node_js: "7" + node_js: "8" env: CXX=g++-4.8 TEST_SUITE=test:node - os: linux node_js: "8" env: CXX=g++-4.8 TEST_SUITE=test:node + - os: linux + node_js: "10" + env: CXX=g++-4.8 TEST_SUITE=test:node + - os: linux + node_js: "11" + env: CXX=g++-4.8 TEST_SUITE=test:node + - os: linux + node_js: "12" + env: CXX=g++-4.8 TEST_SUITE=test:node + script: npm run $TEST_SUITE diff --git a/CHANGELOG.md b/CHANGELOG.md index 7456e19..83d90c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,19 +1,21 @@ # Changelog + All notable changes to this project will be documented in this file. -The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) -(modification: no type change headlines) and this project adheres to +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +(modification: no type change headlines) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). - ## [2.2.0] - 2019-02-06 -**Petersburg** (aka `constantinopleFix`) as well as **Goerli** -support/readiness by updating to a supporting `ethereumjs-common` version -[v1.1.0](https://github.com/ethereumjs/ethereumjs-common/releases/tag/v1.1.0), + +**Petersburg** (aka `constantinopleFix`) as well as **Goerli** +support/readiness by updating to a supporting `ethereumjs-common` version +[v1.1.0](https://github.com/ethereumjs/ethereumjs-common/releases/tag/v1.1.0), PR [#64](https://github.com/ethereumjs/ethereumjs-block/pull/64) **Other Changes:** -- Fixed package size issue by excluding tests and docs from being included in + +- Fixed package size issue by excluding tests and docs from being included in the package, PR [#66](https://github.com/ethereumjs/ethereumjs-block/pull/66) - Error message fixes in `index.js`, PR [#62](https://github.com/ethereumjs/ethereumjs-block/pull/62) @@ -25,58 +27,66 @@ PR [#64](https://github.com/ethereumjs/ethereumjs-block/pull/64) [2.2.0]: https://github.com/ethereumjs/ethereumjs-vm/compare/v2.1.0...v2.2.0 ## [2.1.0] - 2018-10-19 + - **Constantinople** support, added difficulty bomb delay (EIP-1234), PR [#54](https://github.com/ethereumjs/ethereumjs-block/pull/54) - Updated test data, added Constantinople tests, PR [#56](https://github.com/ethereumjs/ethereumjs-block/pull/56), [#57](https://github.com/ethereumjs/ethereumjs-block/pull/57) -- Added ``timestamp`` field to ``setGenesisParams()``, PR [#52](https://github.com/ethereumjs/ethereumjs-block/pull/52) +- Added `timestamp` field to `setGenesisParams()`, PR [#52](https://github.com/ethereumjs/ethereumjs-block/pull/52) [2.1.0]: https://github.com/ethereumjs/ethereumjs-vm/compare/v2.0.1...v2.1.0 ## [2.0.1] - 2018-08-08 -- Fixes ``BlockHeader.prototype.validate()`` bug, see PR [#49](https://github.com/ethereumjs/ethereumjs-block/pull/49) + +- Fixes `BlockHeader.prototype.validate()` bug, see PR [#49](https://github.com/ethereumjs/ethereumjs-block/pull/49) [2.0.1]: https://github.com/ethereumjs/ethereumjs-vm/compare/v2.0.0...v2.0.1 ## [2.0.0] - 2018-06-25 -This release introduces both support for different ``chains`` (``mainnet``, ``ropsten``, ...) -and ``hardforks`` up to the latest applied HF (``byzantium``). Parameters and genesis values + +This release introduces both support for different `chains` (`mainnet`, `ropsten`, ...) +and `hardforks` up to the latest applied HF (`byzantium`). Parameters and genesis values are provided by the new [ethereumjs-common](https://github.com/ethereumjs/ethereumjs-common) library which also defines the set of supported chains and forks. Changes in detail: -- New initialization parameters ``opts.chain`` (default: ``mainnet``) and ``opts.hardfork`` - (default: ``null``, block number-based behaviour), PR [#44](https://github.com/ethereumjs/ethereumjs-block/pull/44) -- Alternatively a ``Common`` class object can be provided directly with the ``opts.common`` parameter, + +- New initialization parameters `opts.chain` (default: `mainnet`) and `opts.hardfork` + (default: `null`, block number-based behaviour), PR [#44](https://github.com/ethereumjs/ethereumjs-block/pull/44) +- Alternatively a `Common` class object can be provided directly with the `opts.common` parameter, see [API](https://github.com/ethereumjs/ethereumjs-block/blob/master/docs/index.md) docs -- Correct block validation for all know hardforks, PR +- Correct block validation for all know hardforks, PR [#47](https://github.com/ethereumjs/ethereumjs-block/pull/47), if no hardfork is set validation logic - is determined by block number in combination with the ``chain`` set -- Genesis block initialization depending on the ``chain`` set (see ``ethereumjs-common`` for supported chains) + is determined by block number in combination with the `chain` set +- Genesis block initialization depending on the `chain` set (see `ethereumjs-common` for supported chains) - Extensive test additions to cover the newly introduced capabilities and changes -- Fix default value for ``nonce`` (empty buffer -> ````), PR [#42](https://github.com/ethereumjs/ethereumjs-block/pull/42) +- Fix default value for `nonce` (empty buffer -> ``), PR [#42](https://github.com/ethereumjs/ethereumjs-block/pull/42) [2.0.0]: https://github.com/ethereumjs/ethereumjs-vm/compare/v1.7.1...v2.0.0 ## [1.7.1] - 2018-02-15 -- Fix ``browserify`` issue blocking updates for packages depending on ``ethereumjs-block`` + +- Fix `browserify` issue blocking updates for packages depending on `ethereumjs-block` library, PR [#40](https://github.com/ethereumjs/ethereumjs-block/pull/40) -- Updated ``ethereumjs/common`` dependency, PR [#38](https://github.com/ethereumjs/ethereumjs-block/pull/38) +- Updated `ethereumjs/common` dependency, PR [#38](https://github.com/ethereumjs/ethereumjs-block/pull/38) [1.7.1]: https://github.com/ethereumjs/ethereumjs-vm/compare/v1.7.0...v1.7.1 ## [1.7.0] - 2017-10-11 -- ``Metro-Byzantium`` compatible + +- `Metro-Byzantium` compatible - New difficulty formula (EIP 100) - Difficulty bomb delay (EIP 649) -- Removed ``isHomestead``, ``isHomesteadReprice`` from API methods +- Removed `isHomestead`, `isHomesteadReprice` from API methods [1.7.0]: https://github.com/ethereumjs/ethereumjs-vm/compare/v1.6.0...v1.7.0 ## [1.6.0] - 2017-07-12 + - Breakout header-from-rpc as separate module [1.6.0]: https://github.com/ethereumjs/ethereumjs-block/compare/v1.5.1...v1.6.0 ## [1.5.1] - 2017-06-04 + - Dev dependency updates - BN for gas limit @@ -88,5 +98,3 @@ Changes in detail: - [1.4.0](https://github.com/ethereumjs/ethereumjs-block/compare/v1.3.1...v1.4.0) - 2016-12-15 - [1.3.1](https://github.com/ethereumjs/ethereumjs-block/compare/v1.3.0...v1.3.1) - 2016-10-14 - [1.3.0](https://github.com/ethereumjs/ethereumjs-block/compare/v1.2.2...v1.3.0) - 2017-10-11 - - diff --git a/README.md b/README.md index f345aca..80756a0 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,33 @@ -# SYNOPSIS +# SYNOPSIS + [![NPM Package](https://img.shields.io/npm/v/ethereumjs-block.svg?style=flat-square)](https://www.npmjs.org/package/ethereumjs-block) [![Build Status](https://img.shields.io/travis/ethereumjs/ethereumjs-block.svg?branch=master&style=flat-square)](https://travis-ci.org/ethereumjs/ethereumjs-block) [![Coverage Status](https://img.shields.io/coveralls/ethereumjs/ethereumjs-block.svg?style=flat-square)](https://coveralls.io/r/ethereumjs/ethereumjs-block) -[![Gitter](https://img.shields.io/gitter/room/ethereum/ethereumjs-lib.svg?style=flat-square)]() or #ethereumjs on freenode - -[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) +[![Gitter](https://img.shields.io/gitter/room/ethereum/ethereumjs-lib.svg?style=flat-square)]() or #ethereumjs on freenode +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) -Implements schema and functions related to Ethereum's block. +Implements schema and functions related to Ethereum's block. # INSTALL + `npm install ethereumjs-block` -# BROWSER +# BROWSER + This module work with `browserify`. # API + [./docs](./docs/index.md) # TESTING -Tests in the ``tests`` directory are partly outdated and testing is primarily done by running the ``BlockchainTests`` from within the [ethereumjs-vm](https://github.com/ethereumjs/ethereumjs-vm) repository. + +Tests in the `tests` directory are partly outdated and testing is primarily done by running the `BlockchainTests` from within the [ethereumjs-vm](https://github.com/ethereumjs/ethereumjs-vm) repository. Relevant test folders: -- ``bcTotalDifficultyTest`` + +- `bcTotalDifficultyTest` - TODO # EthereumJS @@ -32,4 +37,5 @@ See our organizational [documentation](https://ethereumjs.readthedocs.io) for an If you want to join for work or do improvements on the libraries have a look at our [contribution guidelines](https://ethereumjs.readthedocs.io/en/latest/contributing.html). # LICENSE -[MPL-2.0](https://tldrlegal.com/license/mozilla-public-license-2.0-(mpl-2)) + +[MPL-2.0]() diff --git a/docs/fromRpc.md b/docs/fromRpc.md index 52b1167..8c58320 100644 --- a/docs/fromRpc.md +++ b/docs/fromRpc.md @@ -6,6 +6,6 @@ Creates a new block object from Ethereum JSON RPC. **Parameters** -- `blockParams` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Ethereum JSON RPC of block (eth_getBlockByNumber) -- `Optional` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)>** list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) -- `uncles` +- `blockParams` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Ethereum JSON RPC of block (eth_getBlockByNumber) +- `Optional` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)>** list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) +- `uncles` diff --git a/docs/index.md b/docs/index.md index 1a38b58..ff40076 100644 --- a/docs/index.md +++ b/docs/index.md @@ -6,17 +6,17 @@ Creates a new block object **Parameters** -- `data` **([Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) \| [Buffer](https://nodejs.org/api/buffer.html) \| [Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object))** -- `opts` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)** Options - - `opts.chain` **([String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number))** The chain for the block [default: 'mainnet'] - - `opts.hardfork` **[String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Hardfork for the block [default: null, block number-based behaviour] - - `opts.common` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Alternatively pass a Common instance (ethereumjs-common) instead of setting chain/hardfork directly +- `data` **([Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) \| [Buffer](https://nodejs.org/api/buffer.html) \| [Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object))** +- `opts` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)** Options + - `opts.chain` **([String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number))** The chain for the block [default: 'mainnet'] + - `opts.hardfork` **[String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Hardfork for the block [default: null, block number-based behaviour] + - `opts.common` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Alternatively pass a Common instance (ethereumjs-common) instead of setting chain/hardfork directly **Properties** -- `header` **Header** the block's header -- `uncleList` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<Header>** an array of uncle headers -- `raw` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Buffer](https://nodejs.org/api/buffer.html)>** an array of buffers containing the raw blocks. +- `header` **Header** the block's header +- `uncleList` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<Header>** an array of uncle headers +- `raw` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Buffer](https://nodejs.org/api/buffer.html)>** an array of buffers containing the raw blocks. ## hash @@ -38,7 +38,7 @@ Produces a serialization of the block. **Parameters** -- `rlpEncode` **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** whether to rlp encode the block or not +- `rlpEncode` **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** whether to rlp encode the block or not ## genTxTrie @@ -47,13 +47,13 @@ be validated with `validateTransactionTrie` **Parameters** -- `cb` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback +- `cb` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback ## validateTransactionTrie Validates the transaction trie -Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** +Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** ## validateTransactions @@ -61,9 +61,9 @@ Validates the transactions **Parameters** -- `stringError` **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?** whether to return a string with a dscription of why the validation failed or return a Bloolean (optional, default `false`) +- `stringError` **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?** whether to return a string with a dscription of why the validation failed or return a Bloolean (optional, default `false`) -Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** +Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** ## validate @@ -71,14 +71,14 @@ Validates the entire block. Returns a string to the callback if block is invalid **Parameters** -- `blockChain` **BlockChain** the blockchain that this block wants to be part of -- `cb` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback which is given a `String` if the block is not valid +- `blockChain` **BlockChain** the blockchain that this block wants to be part of +- `cb` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback which is given a `String` if the block is not valid ## validateUncleHash Validates the uncle's hash -Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** +Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** ## validateUncles @@ -86,9 +86,9 @@ Validates the uncles that are in the block if any. Returns a string to the callb **Parameters** -- `blockChaina` **Blockchain** an instance of the Blockchain -- `cb` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback -- `blockChain` +- `blockChaina` **Blockchain** an instance of the Blockchain +- `cb` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback +- `blockChain` ## toJSON @@ -96,9 +96,9 @@ Converts the block toJSON **Parameters** -- `labeled` **Bool** whether to create an labeled object or an array +- `labeled` **Bool** whether to create an labeled object or an array -Returns **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** +Returns **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** # BlockHeader @@ -106,28 +106,28 @@ An object that repersents the block header **Parameters** -- `data` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)** raw data, deserialized -- `opts` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)** Options - - `opts.chain` **([String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number))** The chain for the block header [default: 'mainnet'] - - `opts.hardfork` **[String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Hardfork for the block header [default: null, block number-based behaviour] - - `opts.common` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Alternatively pass a Common instance instead of setting chain/hardfork directly +- `data` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)** raw data, deserialized +- `opts` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)** Options + - `opts.chain` **([String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number))** The chain for the block header [default: 'mainnet'] + - `opts.hardfork` **[String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Hardfork for the block header [default: null, block number-based behaviour] + - `opts.common` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Alternatively pass a Common instance instead of setting chain/hardfork directly **Properties** -- `parentHash` **[Buffer](https://nodejs.org/api/buffer.html)** the blocks' parent's hash -- `uncleHash` **[Buffer](https://nodejs.org/api/buffer.html)** sha3(rlp_encode(uncle_list)) -- `coinbase` **[Buffer](https://nodejs.org/api/buffer.html)** the miner address -- `stateRoot` **[Buffer](https://nodejs.org/api/buffer.html)** The root of a Merkle Patricia tree -- `transactionTrie` **[Buffer](https://nodejs.org/api/buffer.html)** the root of a Trie containing the transactions -- `receiptTrie` **[Buffer](https://nodejs.org/api/buffer.html)** the root of a Trie containing the transaction Reciept -- `bloom` **[Buffer](https://nodejs.org/api/buffer.html)** -- `difficulty` **[Buffer](https://nodejs.org/api/buffer.html)** -- `number` **[Buffer](https://nodejs.org/api/buffer.html)** the block's height -- `gasLimit` **[Buffer](https://nodejs.org/api/buffer.html)** -- `gasUsed` **[Buffer](https://nodejs.org/api/buffer.html)** -- `timestamp` **[Buffer](https://nodejs.org/api/buffer.html)** -- `extraData` **[Buffer](https://nodejs.org/api/buffer.html)** -- `raw` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Buffer](https://nodejs.org/api/buffer.html)>** an array of buffers containing the raw blocks. +- `parentHash` **[Buffer](https://nodejs.org/api/buffer.html)** the blocks' parent's hash +- `uncleHash` **[Buffer](https://nodejs.org/api/buffer.html)** sha3(rlp_encode(uncle_list)) +- `coinbase` **[Buffer](https://nodejs.org/api/buffer.html)** the miner address +- `stateRoot` **[Buffer](https://nodejs.org/api/buffer.html)** The root of a Merkle Patricia tree +- `transactionTrie` **[Buffer](https://nodejs.org/api/buffer.html)** the root of a Trie containing the transactions +- `receiptTrie` **[Buffer](https://nodejs.org/api/buffer.html)** the root of a Trie containing the transaction Reciept +- `bloom` **[Buffer](https://nodejs.org/api/buffer.html)** +- `difficulty` **[Buffer](https://nodejs.org/api/buffer.html)** +- `number` **[Buffer](https://nodejs.org/api/buffer.html)** the block's height +- `gasLimit` **[Buffer](https://nodejs.org/api/buffer.html)** +- `gasUsed` **[Buffer](https://nodejs.org/api/buffer.html)** +- `timestamp` **[Buffer](https://nodejs.org/api/buffer.html)** +- `extraData` **[Buffer](https://nodejs.org/api/buffer.html)** +- `raw` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Buffer](https://nodejs.org/api/buffer.html)>** an array of buffers containing the raw blocks. ## canonicalDifficulty @@ -135,9 +135,9 @@ Returns the canoncical difficulty of the block **Parameters** -- `parentBlock` **[Block](#block)** the parent `Block` of the this header +- `parentBlock` **[Block](#block)** the parent `Block` of the this header -Returns **BN** +Returns **BN** ## validateDifficulty @@ -145,9 +145,9 @@ checks that the block's `difficuly` matches the canonical difficulty **Parameters** -- `parentBlock` **[Block](#block)** this block's parent +- `parentBlock` **[Block](#block)** this block's parent -Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** +Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** ## validateGasLimit @@ -155,9 +155,9 @@ Validates the gasLimit **Parameters** -- `parentBlock` **[Block](#block)** this block's parent +- `parentBlock` **[Block](#block)** this block's parent -Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** +Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** ## validate @@ -165,22 +165,22 @@ Validates the entire block header **Parameters** -- `blockChain` **Blockchain** the blockchain that this block is validating against -- `height` **Bignum?** if this is an uncle header, this is the height of the block that is including it -- `cb` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback function. The callback is given an `error` if the block is invalid -- `blockchain` +- `blockChain` **Blockchain** the blockchain that this block is validating against +- `height` **Bignum?** if this is an uncle header, this is the height of the block that is including it +- `cb` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback function. The callback is given an `error` if the block is invalid +- `blockchain` ## hash Returns the sha3 hash of the blockheader -Returns **[Buffer](https://nodejs.org/api/buffer.html)** +Returns **[Buffer](https://nodejs.org/api/buffer.html)** ## isGenesis checks if the blockheader is a genesis header -Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** +Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** ## setGenesisParams diff --git a/karma.conf.js b/karma.conf.js index 9445846..45c591e 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -1,45 +1,18 @@ -process.env.ethTest = 'BasicTests' - module.exports = function(config) { config.set({ browserNoActivityTimeout: 60000, frameworks: ['browserify', 'detectBrowsers', 'tap'], - files: ['./tests/difficulty.js'], + files: ['./test-build/test/index.js'], preprocessors: { - 'tests/*.js': ['browserify', 'env'], + './test-build/**/*.js': ['browserify'] }, singleRun: true, - plugins: [ - 'karma-browserify', - 'karma-chrome-launcher', - 'karma-env-preprocessor', - 'karma-tap', - 'karma-firefox-launcher', - 'karma-detect-browsers', - ], - browserify: { - transform: [ - [ - 'babelify', - { - presets: ['env'], - }, - ], - ], - }, detectBrowsers: { enabled: true, usePhantomJS: false, - postDetection: function(availableBrowser) { - if (process.env.TRAVIS) { - return ['Firefox'] - } - - var browsers = ['Chrome', 'Firefox'] - return browsers.filter(function(browser) { - return availableBrowser.indexOf(browser) !== -1 - }) + postDetection: function(availableBrowsers) { + return ['Firefox'] }, - }, + } }) } diff --git a/package.json b/package.json index 0c33e05..4815b21 100644 --- a/package.json +++ b/package.json @@ -1,19 +1,29 @@ { "name": "ethereumjs-block", - "version": "2.2.0", + "version": "3.0.0", "description": "Provides Block serialization and help functions", - "main": "index.js", + "main": "dist/index.js", + "types": "dist/index.d.ts", "files": [ - "*.js" + "dist" ], "scripts": { - "coverage": "istanbul cover ./tests/index.js", - "coveralls": "npm run coverage && coveralls < coverage/lcov.info", - "lint": "standard", - "test": "npm run test:node && npm run test:browser", - "test:browser": "karma start karma.conf.js", - "test:node": "node tests/index.js", - "build:docs": "documentation build ./index.js ./header.js --format md --shallow > ./docs/index.md && documentation build ./from-rpc.js --format md --shallow > ./docs/fromRpc.md" + "build": "ethereumjs-config-build", + "prepublishOnly": "npm run test && npm run build", + "coverage": "ethereumjs-config-coverage", + "coveralls": "ethereumjs-config-coveralls", + "docs:build": "typedoc --out docs --mode file --readme none --theme markdown --mdEngine github --excludeNotExported src", + "format": "ethereumjs-config-format", + "format:fix": "ethereumjs-config-format-fix", + "tslint": "ethereumjs-config-tslint", + "tslint:fix": "ethereumjs-config-tslint-fix", + "tsc": "ethereumjs-config-tsc", + "lint": "ethereumjs-config-lint", + "lint:fix": "ethereumjs-config-lint-fix", + "test": "npm run test:node", + "test:node": "ts-node node_modules/tape/bin/tape ./test/index.ts", + "test:browser:build": "tsc && cp ./test/*.json test-build/test/", + "test:browser": "npm run test:browser:build && karma start karma.conf.js" }, "husky": { "hooks": { @@ -35,35 +45,36 @@ }, "homepage": "https://github.com/ethereumjs/ethereumjs-block#readme", "dependencies": { - "async": "^2.0.1", - "ethereumjs-common": "^1.1.0", - "ethereumjs-tx": "^1.2.2", - "ethereumjs-util": "^5.0.0", + "@types/bn.js": "^4.11.5", + "ethereumjs-common": "^1.3.0", + "ethereumjs-tx": "^2.1.0", + "ethereumjs-util": "^6.1.0", "merkle-patricia-tree": "^2.1.2" }, "devDependencies": { + "@ethereumjs/config-nyc": "^1.1.1", "@ethereumjs/config-prettier": "^1.1.1", "@ethereumjs/config-tsc": "^1.1.1", "@ethereumjs/config-tslint": "^1.1.1", - "babel-preset-env": "^1.6.1", - "babelify": "^8.0.0", - "browserify": "^15.0.0", - "coveralls": "^2.11.6", - "documentation": "4.0.0-beta16", + "@types/node": "^11.13.4", + "@types/tape": "^4.2.33", + "browserify": "^16.2.3", + "coveralls": "^2.11.4", "husky": "^2.1.0", - "istanbul": "^0.4.2", - "karma": "^2.0.0", - "karma-browserify": "^5.1.0", - "karma-chrome-launcher": "^2.2.0", - "karma-detect-browsers": "^2.2.5", - "karma-env-preprocessor": "^0.1.1", + "istanbul": "^0.4.1", + "karma": "^4.1.0", + "karma-browserify": "^6.0.0", + "karma-detect-browsers": "^2.3.3", "karma-firefox-launcher": "^1.1.0", - "karma-tap": "^4.0.0", - "prettier": "^1.18.2", - "standard": "^8.4.0", - "tape": "^4.2.0", - "ts-node": "^8.3.0", - "tslint": "^5.18.0", - "typescript": "^3.5.3" + "karma-tap": "^4.1.4", + "nyc": "^14.0.0", + "prettier": "^1.17.0", + "tape": "^4.0.3", + "ts-node": "^8.0.3", + "tslint": "^5.15.0", + "typedoc": "^0.14.2", + "typedoc-plugin-markdown": "^1.2.0", + "typescript": "^3.4.3", + "typestrict": "^1.0.2" } } diff --git a/src/block.ts b/src/block.ts new file mode 100644 index 0000000..767a447 --- /dev/null +++ b/src/block.ts @@ -0,0 +1,303 @@ +import Common from 'ethereumjs-common' +import * as ethUtil from 'ethereumjs-util' +import { BN, rlp } from 'ethereumjs-util' +import { Transaction } from 'ethereumjs-tx' + +import { BlockHeader } from './header' +import { Blockchain, BlockData, NetworkOptions, NoReturnValueCallback } from './types' +import { callbackify } from './callbackify' + +const Trie = require('merkle-patricia-tree') + +/** + * Creates a new block object + * @constructor the raw serialized or the deserialized block. + * @param {Array|Buffer|Object} data + * @param {Array} opts Options + * @param {String|Number} opts.chain The chain for the block [default: 'mainnet'] + * @param {String} opts.hardfork Hardfork for the block [default: null, block number-based behaviour] + * @param {Object} opts.common Alternatively pass a Common instance (ethereumjs-common) instead of setting chain/hardfork directly + * @prop {Header} header the block's header + * @prop {Array.
} uncleList an array of uncle headers + * @prop {Array.} raw an array of buffers containing the raw blocks. + */ +export class Block { + public readonly header: BlockHeader + public readonly transactions: Transaction[] = [] + public readonly uncleHeaders: BlockHeader[] = [] + public readonly txTrie = new Trie() + + private readonly _common: Common + + constructor( + data: Buffer | [Buffer[], Buffer[], Buffer[]] | BlockData = {}, + opts: NetworkOptions = {}, + ) { + if (opts.common) { + if (opts.chain !== undefined || opts.hardfork !== undefined) { + throw new Error( + 'Instantiation with both opts.common and opts.chain / opts.hardfork parameter not allowed!', + ) + } + + this._common = opts.common + } else { + const chain = opts.chain ? opts.chain : 'mainnet' + const hardfork = opts.hardfork ? opts.hardfork : null + this._common = new Common(chain, hardfork) + } + + let rawTransactions + let rawUncleHeaders + + if (Buffer.isBuffer(data)) { + // We do this to silence a TS error. We know that after this statement, data is + // a [Buffer[], Buffer[], Buffer[]] + const dataAsAny = rlp.decode(data) as any + data = dataAsAny as [Buffer[], Buffer[], Buffer[]] + } + + if (Array.isArray(data)) { + // TODO: Pass the common object + this.header = new BlockHeader(data[0], opts) + rawTransactions = data[1] + rawUncleHeaders = data[2] + } else { + // TODO: Pass the common object + this.header = new BlockHeader(data.header, opts) + rawTransactions = data.transactions || [] + rawUncleHeaders = data.uncleHeaders || [] + } + + // parse uncle headers + for (let i = 0; i < rawUncleHeaders.length; i++) { + this.uncleHeaders.push(new BlockHeader(rawUncleHeaders[i], opts)) + } + + // parse transactions + for (let i = 0; i < rawTransactions.length; i++) { + const tx = new Transaction(rawTransactions[i], opts) + this.transactions.push(tx) + } + } + + get raw() { + return this.serialize(false) + } + + /** + * Produces a hash the RLP of the block + * @method hash + */ + hash() { + return this.header.hash() + } + + /** + * Determines if a given block is the genesis block + * @method isGenisis + * @return Boolean + */ + isGenesis() { + return this.header.isGenesis() + } + + /** + * turns the block into the canonical genesis block + * @method setGenesisParams + */ + setGenesisParams() { + this.header.setGenesisParams() + } + + /** + * Produces a serialization of the block. + */ + serialize(): Buffer + serialize(rlpEncode: true): Buffer + serialize(rlpEncode: false): [Buffer[], Buffer[], Buffer[]] + serialize(rlpEncode = true) { + const raw = [ + this.header.raw, + this.transactions.map(tx => tx.raw), + this.uncleHeaders.map(uh => uh.raw), + ] + + return rlpEncode ? rlp.encode(raw) : raw + } + + /** + * Generate transaction trie. The tx trie must be generated before the transaction trie can + * be validated with `validateTransactionTrie` + */ + genTxTrie(cb: NoReturnValueCallback) { + callbackify(this._getTxTrie.bind(this))(cb) + } + + private async _getTxTrie() { + for (let i = 0; i < this.transactions.length; i++) { + const tx = this.transactions[i] + await this._putTxInTrie(i, tx) + } + } + + private async _putTxInTrie(txIndex: number, tx: Transaction) { + await new Promise((resolve, reject) => { + this.txTrie.put(rlp.encode(txIndex), tx.serialize(), (err: any) => { + if (err) { + reject(err) + } else { + resolve() + } + }) + }) + } + + /** + * Validates the transaction trie + * @method validateTransactionTrie + * @return {Boolean} + */ + validateTransactionsTrie(): boolean { + const txT = this.header.transactionsTrie.toString('hex') + if (this.transactions.length) { + return txT === this.txTrie.root.toString('hex') + } else { + return txT === ethUtil.KECCAK256_RLP.toString('hex') + } + } + + /** + * Validates the transactions + */ + validateTransactions(): boolean + validateTransactions(stringError: false): boolean + validateTransactions(stringError: true): string + validateTransactions(stringError = false) { + const errors: string[] = [] + + this.transactions.forEach(function(tx, i) { + const error = tx.validate(true) + if (error) { + errors.push(error + ' at tx ' + i) + } + }) + + if (!stringError) { + return errors.length === 0 + } + + return errors.join(' ') + } + + /** + * Validates the entire block. Returns a string to the callback if block is invalid + * @method validate + * @param {BlockChain} blockChain the blockchain that this block wants to be part of + * @param {Function} cb the callback which is given a `String` if the block is not valid + */ + validate(blockChain: Blockchain, cb: NoReturnValueCallback) { + callbackify(this._validate.bind(this, blockChain))(cb) + } + + private async _validate(blockChain: Blockchain) { + await Promise.all([ + this._validateUncles(blockChain), + this._getTxTrie(), + this._validateHeader(this.header, blockChain), + ]) + + if (!this.validateTransactionsTrie()) { + throw new Error('invalid transaction trie') + } + + const txErrors = this.validateTransactions(true) + if (txErrors !== '') { + throw new Error(txErrors) + } + + if (!this.validateUnclesHash()) { + throw new Error('invalid uncle hash') + } + } + + /** + * Validates the uncle's hash + */ + validateUnclesHash(): boolean { + const raw = rlp.encode(this.uncleHeaders.map(uh => uh.raw)) + + return ethUtil.keccak256(raw).toString('hex') === this.header.uncleHash.toString('hex') + } + + /** + * Validates the uncles that are in the block if any. Returns a string to the callback if uncles are invalid + * @method validateUncles + * @param {Blockchain} blockChain an instance of the Blockchain + * @param {Function} cb the callback + */ + validateUncles(blockChain: Blockchain, cb: NoReturnValueCallback) { + callbackify(this._validateUncles.bind(this, blockChain))(cb) + } + + private async _validateUncles(blockchain: Blockchain) { + if (this.isGenesis()) { + return + } + + if (this.uncleHeaders.length > 2) { + throw new Error('too many uncle headers') + } + + const uncleHashes = this.uncleHeaders.map(header => header.hash().toString('hex')) + + if (!(new Set(uncleHashes).size === uncleHashes.length)) { + throw new Error('duplicate uncles') + } + + return Promise.all( + this.uncleHeaders.map(async uh => { + const height = new BN(this.header.number) + return this._validateHeader(uh, blockchain, height) + }), + ) + } + + /** + * Returns the block in JSON format + * @see {@link https://github.com/ethereumjs/ethereumjs-util/blob/master/docs/index.md#defineproperties|ethereumjs-util} + */ + toJSON(labeled: boolean = false) { + if (labeled) { + return { + header: this.header.toJSON(true), + transactions: this.transactions.map(tx => tx.toJSON(true)), + uncleHeaders: this.uncleHeaders.forEach(uh => uh.toJSON(true)), + } + } else { + return ethUtil.baToJSON(this.raw) + } + } + + private _validateHeader(header: BlockHeader, blockchain: Blockchain, height?: BN) { + return new Promise((resolve, reject) => { + if (height !== undefined) { + header.validate(blockchain, height, err => { + if (err) { + reject(err) + } + + resolve() + }) + } else { + header.validate(blockchain, err => { + if (err) { + reject(err) + } + + resolve() + }) + } + }) + } +} diff --git a/src/callbackify.ts b/src/callbackify.ts new file mode 100644 index 0000000..5d3fbc9 --- /dev/null +++ b/src/callbackify.ts @@ -0,0 +1,77 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function callbackifyOnRejected(reason: any, cb: any) { + // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). + // Because `null` is a special error value in callbacks which means "no error + // occurred", we error-wrap so the callback consumer can distinguish between + // "the promise rejected with null" or "the promise fulfilled with undefined". + if (!reason) { + const newReason = new Error('Promise was rejected with a falsy value') as any + newReason.reason = reason + reason = newReason + } + return cb(reason) +} + +export function callbackify(original: any): any { + if (typeof original !== 'function') { + throw new TypeError('The "original" argument must be of type Function') + } + + // We DO NOT return the promise as it gives the user a false sense that + // the promise is actually somehow related to the callback's execution + // and that the callback throwing will reject the promise. + function callbackified(this: any) { + const args = [] + for (let i = 0; i < arguments.length; i++) { + args.push(arguments[i]) + } + + const maybeCb = args.pop() + if (typeof maybeCb !== 'function') { + throw new TypeError('The last argument must be of type Function') + } + + //tslint:disable-next-line no-invalid-this + const self = this + const cb = function() { + return maybeCb.apply(self, arguments) + } + + // In true node style we process the callback on `nextTick` with all the + // implications (stack, `uncaughtException`, `async_hooks`) + //tslint:disable-next-line no-invalid-this + original.apply(this, args).then( + function(ret: any) { + process.nextTick(cb.bind(null, null, ret)) + }, + function(rej: any) { + process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) + }, + ) + } + + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)) + Object.defineProperties(callbackified, Object.getOwnPropertyDescriptors(original)) + + return callbackified +} diff --git a/src/from-rpc.ts b/src/from-rpc.ts index 201cf70..f73cd03 100644 --- a/src/from-rpc.ts +++ b/src/from-rpc.ts @@ -1,56 +1,56 @@ -'use strict' -const Transaction = require('ethereumjs-tx') -const ethUtil = require('ethereumjs-util') -const Block = require('./') -const blockHeaderFromRpc = require('./header-from-rpc') - -module.exports = blockFromRpc - -/** - * Creates a new block object from Ethereum JSON RPC. - * @param {Object} blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) - * @param {Array.} Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) - */ -function blockFromRpc(blockParams, uncles) { - uncles = uncles || [] - const block = new Block({ - transactions: [], - uncleHeaders: [], - }) - block.header = blockHeaderFromRpc(blockParams) - - block.transactions = (blockParams.transactions || []).map(function(_txParams) { - const txParams = normalizeTxParams(_txParams) - // override from address - const fromAddress = ethUtil.toBuffer(txParams.from) - delete txParams.from - const tx = new Transaction(txParams) - tx._from = fromAddress - tx.getSenderAddress = function() { - return fromAddress - } - // override hash - const txHash = ethUtil.toBuffer(txParams.hash) - tx.hash = function() { - return txHash - } - return tx - }) - block.uncleHeaders = uncles.map(function(uncleParams) { - return blockHeaderFromRpc(uncleParams) - }) - - return block -} - -function normalizeTxParams(_txParams) { - const txParams = Object.assign({}, _txParams) - // hot fix for https://github.com/ethereumjs/ethereumjs-util/issues/40 - txParams.gasLimit = txParams.gasLimit === undefined ? txParams.gas : txParams.gasLimit - txParams.data = txParams.data === undefined ? txParams.input : txParams.data - // strict byte length checking - txParams.to = txParams.to ? ethUtil.setLengthLeft(ethUtil.toBuffer(txParams.to), 20) : null - // v as raw signature value {0,1} - txParams.v = txParams.v < 27 ? txParams.v + 27 : txParams.v - return txParams -} +// import { Transaction } from 'ethereumjs-tx' +// import * as ethUtil from 'ethereumjs-util' +// import { Block } from './index' +// +// const blockHeaderFromRpc = require('./header-from-rpc') +// +// module.exports = blockFromRpc +// +// /** +// * Creates a new block object from Ethereum JSON RPC. +// * @param {Object} blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) +// * @param {Array.} Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) +// */ +// function blockFromRpc(blockParams, uncles) { +// uncles = uncles || [] +// const block = new Block({ +// transactions: [], +// uncleHeaders: [], +// }) +// block.header = blockHeaderFromRpc(blockParams) +// +// block.transactions = (blockParams.transactions || []).map(function(_txParams) { +// const txParams = normalizeTxParams(_txParams) +// // override from address +// const fromAddress = ethUtil.toBuffer(txParams.from) +// delete txParams.from +// const tx = new Transaction(txParams) +// tx._from = fromAddress +// tx.getSenderAddress = function() { +// return fromAddress +// } +// // override hash +// const txHash = ethUtil.toBuffer(txParams.hash) +// tx.hash = function() { +// return txHash +// } +// return tx +// }) +// block.uncleHeaders = uncles.map(function(uncleParams) { +// return blockHeaderFromRpc(uncleParams) +// }) +// +// return block +// } +// +// function normalizeTxParams(_txParams) { +// const txParams = Object.assign({}, _txParams) +// // hot fix for https://github.com/ethereumjs/ethereumjs-util/issues/40 +// txParams.gasLimit = txParams.gasLimit === undefined ? txParams.gas : txParams.gasLimit +// txParams.data = txParams.data === undefined ? txParams.input : txParams.data +// // strict byte length checking +// txParams.to = txParams.to ? ethUtil.setLengthLeft(ethUtil.toBuffer(txParams.to), 20) : null +// // v as raw signature value {0,1} +// txParams.v = txParams.v < 27 ? txParams.v + 27 : txParams.v +// return txParams +// } diff --git a/src/header-from-rpc.ts b/src/header-from-rpc.ts index 48437bd..4367e17 100644 --- a/src/header-from-rpc.ts +++ b/src/header-from-rpc.ts @@ -1,36 +1,36 @@ -'use strict' -const BlockHeader = require('./header') -const ethUtil = require('ethereumjs-util') - -module.exports = blockHeaderFromRpc - -/** - * Creates a new block header object from Ethereum JSON RPC. - * @param {Object} blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) - */ -function blockHeaderFromRpc(blockParams) { - const blockHeader = new BlockHeader({ - parentHash: blockParams.parentHash, - uncleHash: blockParams.sha3Uncles, - coinbase: blockParams.miner, - stateRoot: blockParams.stateRoot, - transactionsTrie: blockParams.transactionsRoot, - receiptTrie: blockParams.receiptRoot || blockParams.receiptsRoot || ethUtil.SHA3_NULL, - bloom: blockParams.logsBloom, - difficulty: blockParams.difficulty, - number: blockParams.number, - gasLimit: blockParams.gasLimit, - gasUsed: blockParams.gasUsed, - timestamp: blockParams.timestamp, - extraData: blockParams.extraData, - mixHash: blockParams.mixHash, - nonce: blockParams.nonce, - }) - - // override hash incase something was missing - blockHeader.hash = function() { - return ethUtil.toBuffer(blockParams.hash) - } - - return blockHeader -} +// 'use strict' +// const BlockHeader = require('./header') +// const ethUtil = require('ethereumjs-util') +// +// module.exports = blockHeaderFromRpc +// +// /** +// * Creates a new block header object from Ethereum JSON RPC. +// * @param {Object} blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) +// */ +// function blockHeaderFromRpc(blockParams) { +// const blockHeader = new BlockHeader({ +// parentHash: blockParams.parentHash, +// uncleHash: blockParams.sha3Uncles, +// coinbase: blockParams.miner, +// stateRoot: blockParams.stateRoot, +// transactionsTrie: blockParams.transactionsRoot, +// receiptTrie: blockParams.receiptRoot || blockParams.receiptsRoot || ethUtil.SHA3_NULL, +// bloom: blockParams.logsBloom, +// difficulty: blockParams.difficulty, +// number: blockParams.number, +// gasLimit: blockParams.gasLimit, +// gasUsed: blockParams.gasUsed, +// timestamp: blockParams.timestamp, +// extraData: blockParams.extraData, +// mixHash: blockParams.mixHash, +// nonce: blockParams.nonce, +// }) +// +// // override hash incase something was missing +// blockHeader.hash = function() { +// return ethUtil.toBuffer(blockParams.hash) +// } +// +// return blockHeader +// } diff --git a/src/header.ts b/src/header.ts index f700ca0..2c0a12b 100644 --- a/src/header.ts +++ b/src/header.ts @@ -1,6 +1,17 @@ -const Common = require('ethereumjs-common').default -const utils = require('ethereumjs-util') -const BN = utils.BN +import Common from 'ethereumjs-common' +import * as utils from 'ethereumjs-util' +import { BN } from 'ethereumjs-util' +import { + Blockchain, + BlockHeaderData, + BufferLike, + NetworkOptions, + NoReturnValueCallback, + PrefixedHexString, +} from './types' +import { Buffer } from 'buffer' +import { Block } from './block' + /** * An object that repersents the block header * @constructor @@ -24,303 +35,361 @@ const BN = utils.BN * @prop {Buffer} extraData * @prop {Array.} raw an array of buffers containing the raw blocks. */ -var BlockHeader = (module.exports = function(data, opts) { - opts = opts || {} +export class BlockHeader { + public raw!: Buffer[] + public parentHash!: Buffer + public uncleHash!: Buffer + public coinbase!: Buffer + public stateRoot!: Buffer + public transactionsTrie!: Buffer + public receiptTrie!: Buffer + public bloom!: Buffer + public difficulty!: Buffer + public number!: Buffer + public gasLimit!: Buffer + public gasUsed!: Buffer + public timestamp!: Buffer + public extraData!: Buffer + public mixHash!: Buffer + public nonce!: Buffer - if (opts.common) { - if (opts.chain) { - throw new Error('Instantiation with both opts.common and opts.chain parameter not allowed!') - } - this._common = opts.common - } else { - let chain = opts.chain ? opts.chain : 'mainnet' - let hardfork = opts.hardfork ? opts.hardfork : null - this._common = new Common(chain, hardfork) - } + private readonly _common: Common - var fields = [ - { - name: 'parentHash', - length: 32, - default: utils.zeros(32), - }, - { - name: 'uncleHash', - default: utils.SHA3_RLP_ARRAY, - }, - { - name: 'coinbase', - length: 20, - default: utils.zeros(20), - }, - { - name: 'stateRoot', - length: 32, - default: utils.zeros(32), - }, - { - name: 'transactionsTrie', - length: 32, - default: utils.SHA3_RLP, - }, - { - name: 'receiptTrie', - length: 32, - default: utils.SHA3_RLP, - }, - { - name: 'bloom', - default: utils.zeros(256), - }, - { - name: 'difficulty', - default: Buffer.from([]), - }, - { - name: 'number', - // TODO: params.homeSteadForkNumber.v left for legacy reasons, replace on future release - default: utils.intToBuffer(1150000), - }, - { - name: 'gasLimit', - default: Buffer.from('ffffffffffffff', 'hex'), - }, - { - name: 'gasUsed', - empty: true, - default: Buffer.from([]), - }, - { - name: 'timestamp', - default: Buffer.from([]), - }, - { - name: 'extraData', - allowZero: true, - empty: true, - default: Buffer.from([]), - }, - { - name: 'mixHash', - default: utils.zeros(32), - // length: 32 - }, - { - name: 'nonce', - default: utils.zeros(8), // sha3(42) - }, - ] - utils.defineProperties(this, fields, data) -}) + constructor( + data: Buffer | PrefixedHexString | BufferLike[] | BlockHeaderData = {}, + opts: NetworkOptions = {}, + ) { + if (opts.common !== undefined) { + if (opts.chain !== undefined || opts.hardfork !== undefined) { + throw new Error( + 'Instantiation with both opts.common and opts.chain / opts.hardfork parameter not allowed!', + ) + } -/** - * Returns the canoncical difficulty of the block - * @method canonicalDifficulty - * @param {Block} parentBlock the parent `Block` of the this header - * @return {BN} - */ -BlockHeader.prototype.canonicalDifficulty = function(parentBlock) { - const hardfork = - this._common.hardfork() || this._common.activeHardfork(utils.bufferToInt(this.number)) - const blockTs = new BN(this.timestamp) - const parentTs = new BN(parentBlock.header.timestamp) - const parentDif = new BN(parentBlock.header.difficulty) - const minimumDifficulty = new BN(this._common.param('pow', 'minimumDifficulty', hardfork)) - var offset = parentDif.div(new BN(this._common.param('pow', 'difficultyBoundDivisor', hardfork))) - var num = new BN(this.number) - var a - var cutoff - var dif - - if (this._common.hardforkGteHardfork(hardfork, 'byzantium')) { - // max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99) (EIP100) - var uncleAddend = parentBlock.header.uncleHash.equals(utils.SHA3_RLP_ARRAY) ? 1 : 2 - a = blockTs - .sub(parentTs) - .idivn(9) - .ineg() - .iaddn(uncleAddend) - cutoff = new BN(-99) - // MAX(cutoff, a) - if (cutoff.cmp(a) === 1) { - a = cutoff + this._common = opts.common + } else { + const chain = opts.chain ? opts.chain : 'mainnet' + const hardfork = opts.hardfork ? opts.hardfork : null + this._common = new Common(chain, hardfork) } - dif = parentDif.add(offset.mul(a)) + + const fields = [ + { + name: 'parentHash', + length: 32, + default: utils.zeros(32), + }, + { + name: 'uncleHash', + default: utils.KECCAK256_RLP_ARRAY, + }, + { + name: 'coinbase', + length: 20, + default: utils.zeros(20), + }, + { + name: 'stateRoot', + length: 32, + default: utils.zeros(32), + }, + { + name: 'transactionsTrie', + length: 32, + default: utils.KECCAK256_RLP, + }, + { + name: 'receiptTrie', + length: 32, + default: utils.KECCAK256_RLP, + }, + { + name: 'bloom', + default: utils.zeros(256), + }, + { + name: 'difficulty', + default: Buffer.from([]), + }, + { + name: 'number', + // TODO: params.homeSteadForkNumber.v left for legacy reasons, replace on future release + default: utils.toBuffer(1150000), + }, + { + name: 'gasLimit', + default: Buffer.from('ffffffffffffff', 'hex'), + }, + { + name: 'gasUsed', + empty: true, + default: Buffer.from([]), + }, + { + name: 'timestamp', + default: Buffer.from([]), + }, + { + name: 'extraData', + allowZero: true, + empty: true, + default: Buffer.from([]), + }, + { + name: 'mixHash', + default: utils.zeros(32), + // length: 32 + }, + { + name: 'nonce', + default: utils.zeros(8), // sha3(42) + }, + ] + utils.defineProperties(this, fields, data) } - if (this._common.hardforkGteHardfork(hardfork, 'constantinople')) { - // Constantinople difficulty bomb delay (EIP1234) - num.isubn(5000000) - if (num.ltn(0)) { - num = new BN(0) + /** + * Returns the canoncical difficulty of the block + * @method canonicalDifficulty + * @param {Block} parentBlock the parent `Block` of the this header + * @return {BN} + */ + canonicalDifficulty(parentBlock: Block): BN { + const hardfork = this._getHardfork() + const blockTs = new BN(this.timestamp) + const parentTs = new BN(parentBlock.header.timestamp) + const parentDif = new BN(parentBlock.header.difficulty) + const minimumDifficulty = new BN(this._common.param('pow', 'minimumDifficulty', hardfork)) + const offset = parentDif.div( + new BN(this._common.param('pow', 'difficultyBoundDivisor', hardfork)), + ) + let num = new BN(this.number) + + // We use a ! here as TS can follow this hardforks-dependent logic, but it always gets assigned + let dif!: BN + + if (this._common.hardforkGteHardfork(hardfork, 'byzantium')) { + // max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99) (EIP100) + const uncleAddend = parentBlock.header.uncleHash.equals(utils.KECCAK256_RLP_ARRAY) ? 1 : 2 + let a = blockTs + .sub(parentTs) + .idivn(9) + .ineg() + .iaddn(uncleAddend) + const cutoff = new BN(-99) + // MAX(cutoff, a) + if (cutoff.cmp(a) === 1) { + a = cutoff + } + dif = parentDif.add(offset.mul(a)) } - } else if (this._common.hardforkGteHardfork(hardfork, 'byzantium')) { - // Byzantium difficulty bomb delay (EIP649) - num.isubn(3000000) - if (num.ltn(0)) { - num = new BN(0) + + if (this._common.hardforkGteHardfork(hardfork, 'constantinople')) { + // Constantinople difficulty bomb delay (EIP1234) + num.isubn(5000000) + if (num.ltn(0)) { + num = new BN(0) + } + } else if (this._common.hardforkGteHardfork(hardfork, 'byzantium')) { + // Byzantium difficulty bomb delay (EIP649) + num.isubn(3000000) + if (num.ltn(0)) { + num = new BN(0) + } + } else if (this._common.hardforkGteHardfork(hardfork, 'homestead')) { + // 1 - (block_timestamp - parent_timestamp) // 10 + let a = blockTs + .sub(parentTs) + .idivn(10) + .ineg() + .iaddn(1) + const cutoff = new BN(-99) + // MAX(cutoff, a) + if (cutoff.cmp(a) === 1) { + a = cutoff + } + dif = parentDif.add(offset.mul(a)) + } else { + // pre-homestead + if (parentTs.addn(this._common.param('pow', 'durationLimit', hardfork)).cmp(blockTs) === 1) { + dif = offset.add(parentDif) + } else { + dif = parentDif.sub(offset) + } } - } else if (this._common.hardforkGteHardfork(hardfork, 'homestead')) { - // 1 - (block_timestamp - parent_timestamp) // 10 - a = blockTs - .sub(parentTs) - .idivn(10) - .ineg() - .iaddn(1) - cutoff = new BN(-99) - // MAX(cutoff, a) - if (cutoff.cmp(a) === 1) { - a = cutoff + + const exp = num.idivn(100000).isubn(2) + if (!exp.isNeg()) { + dif.iadd(new BN(2).pow(exp)) } - dif = parentDif.add(offset.mul(a)) - } else { - // pre-homestead - if (parentTs.addn(this._common.param('pow', 'durationLimit', hardfork)).cmp(blockTs) === 1) { - dif = offset.add(parentDif) - } else { - dif = parentDif.sub(offset) + + if (dif.cmp(minimumDifficulty) === -1) { + dif = minimumDifficulty } - } - var exp = num.idivn(100000).isubn(2) - if (!exp.isNeg()) { - dif.iadd(new BN(2).pow(exp)) + return dif } - if (dif.cmp(minimumDifficulty) === -1) { - dif = minimumDifficulty + /** + * checks that the block's `difficuly` matches the canonical difficulty + * @method validateDifficulty + * @param {Block} parentBlock this block's parent + * @return {Boolean} + */ + validateDifficulty(parentBlock: Block): boolean { + const dif = this.canonicalDifficulty(parentBlock) + return dif.cmp(new BN(this.difficulty)) === 0 } - return dif -} + /** + * Validates the gasLimit + * @method validateGasLimit + * @param {Block} parentBlock this block's parent + * @returns {Boolean} + */ + validateGasLimit(parentBlock: Block): boolean { + const pGasLimit = new BN(parentBlock.header.gasLimit) + const gasLimit = new BN(this.gasLimit) + const hardfork = this._getHardfork() -/** - * checks that the block's `difficuly` matches the canonical difficulty - * @method validateDifficulty - * @param {Block} parentBlock this block's parent - * @return {Boolean} - */ -BlockHeader.prototype.validateDifficulty = function(parentBlock) { - const dif = this.canonicalDifficulty(parentBlock) - return dif.cmp(new BN(this.difficulty)) === 0 -} + const a = pGasLimit.div( + new BN(this._common.param('gasConfig', 'gasLimitBoundDivisor', hardfork)), + ) + const maxGasLimit = pGasLimit.add(a) + const minGasLimit = pGasLimit.sub(a) -/** - * Validates the gasLimit - * @method validateGasLimit - * @param {Block} parentBlock this block's parent - * @returns {Boolean} - */ -BlockHeader.prototype.validateGasLimit = function(parentBlock) { - const pGasLimit = new BN(parentBlock.header.gasLimit) - const gasLimit = new BN(this.gasLimit) - const hardfork = this._common.hardfork() - ? this._common.hardfork() - : this._common.activeHardfork(this.number) - const a = pGasLimit.div(new BN(this._common.param('gasConfig', 'gasLimitBoundDivisor', hardfork))) - const maxGasLimit = pGasLimit.add(a) - const minGasLimit = pGasLimit.sub(a) - - return ( - gasLimit.lt(maxGasLimit) && - gasLimit.gt(minGasLimit) && - gasLimit.gte(this._common.param('gasConfig', 'minGasLimit', hardfork)) - ) -} - -/** - * Validates the entire block header - * @method validate - * @param {Blockchain} blockChain the blockchain that this block is validating against - * @param {Bignum} [height] if this is an uncle header, this is the height of the block that is including it - * @param {Function} cb the callback function. The callback is given an `error` if the block is invalid - */ -BlockHeader.prototype.validate = function(blockchain, height, cb) { - var self = this - if (arguments.length === 2) { - cb = height - height = false + return ( + gasLimit.lt(maxGasLimit) && + gasLimit.gt(minGasLimit) && + gasLimit.gte(this._common.param('gasConfig', 'minGasLimit', hardfork)) + ) } - if (this.isGenesis()) { - return cb() - } + /** + * Validates the entire block header + * @method validate + * @param {Blockchain} blockChain the blockchain that this block is validating against + * @param {Bignum} [height] if this is an uncle header, this is the height of the block that is including it + * @param {Function} cb the callback function. The callback is given an `error` if the block is invalid + */ + validate(blockchain: Blockchain, cb: NoReturnValueCallback): void + validate(blockchain: Blockchain, height: BN, cb: NoReturnValueCallback): void + validate( + blockchain: Blockchain, + heightOrCb: BN | NoReturnValueCallback, + cb?: NoReturnValueCallback, + ): void { + if (heightOrCb instanceof Function) { + cb = heightOrCb + } - // find the blocks parent - blockchain.getBlock(self.parentHash, function(err, parentBlock) { - if (err) { - return cb('could not find parent block') + if (cb === undefined) { + throw new Error('No callback provided') } - self.parentBlock = parentBlock + const callback = cb - var number = new BN(self.number) - if (number.cmp(new BN(parentBlock.header.number).iaddn(1)) !== 0) { - return cb('invalid number') + if (this.isGenesis()) { + return callback(null) } - if (height) { - var dif = height.sub(new BN(parentBlock.header.number)) - if (!(dif.cmpn(8) === -1 && dif.cmpn(1) === 1)) { - return cb('uncle block has a parent that is too old or to young') + // find the blocks parent + blockchain.getBlock(this.parentHash, (err, parentBlock) => { + if (err || parentBlock === undefined) { + return callback(new Error('could not find parent block')) } - } - if (!self.validateDifficulty(parentBlock)) { - return cb('invalid Difficulty') - } + const number = new BN(this.number) + if (number.cmp(new BN(parentBlock.header.number).iaddn(1)) !== 0) { + return callback(new Error('invalid number')) + } - if (!self.validateGasLimit(parentBlock)) { - return cb('invalid gas limit') - } + if (BN.isBN(heightOrCb)) { + const dif = heightOrCb.sub(new BN(parentBlock.header.number)) + if (!(dif.cmpn(8) === -1 && dif.cmpn(1) === 1)) { + return callback(new Error('uncle block has a parent that is too old or to young')) + } + } - if (utils.bufferToInt(parentBlock.header.number) + 1 !== utils.bufferToInt(self.number)) { - return cb('invalid heigth') - } + if (!this.validateDifficulty(parentBlock)) { + return callback(new Error('invalid Difficulty')) + } - if (utils.bufferToInt(self.timestamp) <= utils.bufferToInt(parentBlock.header.timestamp)) { - return cb('invalid timestamp') - } + if (!this.validateGasLimit(parentBlock)) { + return callback(new Error('invalid gas limit')) + } - const hardfork = self._common.hardfork() - ? self._common.hardfork() - : self._common.activeHardfork(height) - if (self.extraData.length > self._common.param('vm', 'maxExtraDataSize', hardfork)) { - return cb('invalid amount of extra data') - } + if (utils.bufferToInt(parentBlock.header.number) + 1 !== utils.bufferToInt(this.number)) { + return callback(new Error('invalid heigth')) + } - cb() - }) -} + if (utils.bufferToInt(this.timestamp) <= utils.bufferToInt(parentBlock.header.timestamp)) { + return callback(new Error('invalid timestamp')) + } -/** - * Returns the sha3 hash of the blockheader - * @method hash - * @return {Buffer} - */ -BlockHeader.prototype.hash = function() { - return utils.rlphash(this.raw) -} + const hardfork = this._getHardfork() + if (this.extraData.length > this._common.param('vm', 'maxExtraDataSize', hardfork)) { + return callback(new Error('invalid amount of extra data')) + } -/** - * checks if the blockheader is a genesis header - * @method isGenesis - * @return {Boolean} - */ -BlockHeader.prototype.isGenesis = function() { - return this.number.toString('hex') === '' -} + callback(null) + }) + } -/** - * turns the header into the canonical genesis block header - * @method setGenesisParams - */ -BlockHeader.prototype.setGenesisParams = function() { - this.timestamp = this._common.genesis().timestamp - this.gasLimit = this._common.genesis().gasLimit - this.difficulty = this._common.genesis().difficulty - this.extraData = this._common.genesis().extraData - this.nonce = this._common.genesis().nonce - this.stateRoot = this._common.genesis().stateRoot - this.number = Buffer.from([]) + /** + * Returns the sha3 hash of the blockheader + * @method hash + * @return {Buffer} + */ + hash(): Buffer { + return utils.rlphash(this.raw) + } + + /** + * checks if the blockheader is a genesis header + * @method isGenesis + * @return {Boolean} + */ + isGenesis(): boolean { + return this.number.length === 0 + } + + /** + * turns the header into the canonical genesis block header + * @method setGenesisParams + */ + setGenesisParams(): void { + this.timestamp = this._common.genesis().timestamp + this.gasLimit = this._common.genesis().gasLimit + this.difficulty = this._common.genesis().difficulty + this.extraData = this._common.genesis().extraData + this.nonce = this._common.genesis().nonce + this.stateRoot = this._common.genesis().stateRoot + this.number = Buffer.from([]) + } + + /** + * Returns the rlp encoding of the block header + */ + serialize(): Buffer { + // Note: This never gets executed, defineProperties overwrites it. + return Buffer.from([]) + } + + /** + * Returns the block header in JSON format + * @see {@link https://github.com/ethereumjs/ethereumjs-util/blob/master/docs/index.md#defineproperties|ethereumjs-util} + */ + toJSON(_labels: boolean = false): { [key: string]: string } | string[] { + // Note: This never gets executed, defineProperties overwrites it. + return {} + } + + private _getHardfork(): string { + const commonHardFork = this._common.hardfork() + + return commonHardFork !== null + ? commonHardFork + : this._common.activeHardfork(utils.bufferToInt(this.number)) + } } diff --git a/src/index.ts b/src/index.ts index fd9ef21..6273a83 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,335 +1,3 @@ -const Common = require('ethereumjs-common').default -const ethUtil = require('ethereumjs-util') -const Tx = require('ethereumjs-tx') -const Trie = require('merkle-patricia-tree') -const BN = ethUtil.BN -const rlp = ethUtil.rlp -const async = require('async') -const BlockHeader = require('./header') - -/** - * Creates a new block object - * @constructor the raw serialized or the deserialized block. - * @param {Array|Buffer|Object} data - * @param {Array} opts Options - * @param {String|Number} opts.chain The chain for the block [default: 'mainnet'] - * @param {String} opts.hardfork Hardfork for the block [default: null, block number-based behaviour] - * @param {Object} opts.common Alternatively pass a Common instance (ethereumjs-common) instead of setting chain/hardfork directly - * @prop {Header} header the block's header - * @prop {Array.
} uncleList an array of uncle headers - * @prop {Array.} raw an array of buffers containing the raw blocks. - */ -var Block = (module.exports = function(data, opts) { - opts = opts || {} - - if (opts.common) { - if (opts.chain) { - throw new Error('Instantiation with both opts.common and opts.chain parameter not allowed!') - } - this._common = opts.common - } else { - let chain = opts.chain ? opts.chain : 'mainnet' - let hardfork = opts.hardfork ? opts.hardfork : null - this._common = new Common(chain, hardfork) - } - - this.transactions = [] - this.uncleHeaders = [] - this._inBlockChain = false - this.txTrie = new Trie() - - Object.defineProperty(this, 'raw', { - get: function() { - return this.serialize(false) - }, - }) - - var rawTransactions, rawUncleHeaders - - // defaults - if (!data) { - data = [[], [], []] - } - - if (Buffer.isBuffer(data)) { - data = rlp.decode(data) - } - - if (Array.isArray(data)) { - this.header = new BlockHeader(data[0], opts) - rawTransactions = data[1] - rawUncleHeaders = data[2] - } else { - this.header = new BlockHeader(data.header, opts) - rawTransactions = data.transactions || [] - rawUncleHeaders = data.uncleHeaders || [] - } - - // parse uncle headers - for (var i = 0; i < rawUncleHeaders.length; i++) { - this.uncleHeaders.push(new BlockHeader(rawUncleHeaders[i], opts)) - } - - // parse transactions - for (i = 0; i < rawTransactions.length; i++) { - var tx = new Tx(rawTransactions[i]) - tx._homestead = true - this.transactions.push(tx) - } -}) - -Block.Header = BlockHeader - -/** - * Produces a hash the RLP of the block - * @method hash - */ -Block.prototype.hash = function() { - return this.header.hash() -} - -/** - * Determines if a given block is the genesis block - * @method isGenisis - * @return Boolean - */ -Block.prototype.isGenesis = function() { - return this.header.isGenesis() -} - -/** - * turns the block into the canonical genesis block - * @method setGenesisParams - */ -Block.prototype.setGenesisParams = function() { - this.header.setGenesisParams() -} - -/** - * Produces a serialization of the block. - * @method serialize - * @param {Boolean} rlpEncode whether to rlp encode the block or not - */ -Block.prototype.serialize = function(rlpEncode) { - var raw = [this.header.raw, [], []] - - // rlpEnode defaults to true - if (typeof rlpEncode === 'undefined') { - rlpEncode = true - } - - this.transactions.forEach(function(tx) { - raw[1].push(tx.raw) - }) - - this.uncleHeaders.forEach(function(uncle) { - raw[2].push(uncle.raw) - }) - - return rlpEncode ? rlp.encode(raw) : raw -} - -/** - * Generate transaction trie. The tx trie must be generated before the transaction trie can - * be validated with `validateTransactionTrie` - * @method genTxTrie - * @param {Function} cb the callback - */ -Block.prototype.genTxTrie = function(cb) { - var i = 0 - var self = this - - async.eachSeries( - this.transactions, - function(tx, done) { - self.txTrie.put(rlp.encode(i), tx.serialize(), done) - i++ - }, - cb, - ) -} - -/** - * Validates the transaction trie - * @method validateTransactionTrie - * @return {Boolean} - */ -Block.prototype.validateTransactionsTrie = function() { - var txT = this.header.transactionsTrie.toString('hex') - if (this.transactions.length) { - return txT === this.txTrie.root.toString('hex') - } else { - return txT === ethUtil.SHA3_RLP.toString('hex') - } -} - -/** - * Validates the transactions - * @method validateTransactions - * @param {Boolean} [stringError=false] whether to return a string with a dscription of why the validation failed or return a Bloolean - * @return {Boolean} - */ -Block.prototype.validateTransactions = function(stringError) { - var errors = [] - - this.transactions.forEach(function(tx, i) { - var error = tx.validate(true) - if (error) { - errors.push(error + ' at tx ' + i) - } - }) - - if (stringError === undefined || stringError === false) { - return errors.length === 0 - } else { - return arrayToString(errors) - } -} - -/** - * Validates the entire block. Returns a string to the callback if block is invalid - * @method validate - * @param {BlockChain} blockChain the blockchain that this block wants to be part of - * @param {Function} cb the callback which is given a `String` if the block is not valid - */ -Block.prototype.validate = function(blockChain, cb) { - var self = this - var errors = [] - - async.parallel( - [ - // validate uncles - self.validateUncles.bind(self, blockChain), - // validate block - self.header.validate.bind(self.header, blockChain), - // generate the transaction trie - self.genTxTrie.bind(self), - ], - function(err) { - if (err) { - errors.push(err) - } - - if (!self.validateTransactionsTrie()) { - errors.push('invalid transaction trie') - } - - var txErrors = self.validateTransactions(true) - if (txErrors !== '') { - errors.push(txErrors) - } - - if (!self.validateUnclesHash()) { - errors.push('invalid uncle hash') - } - - cb(arrayToString(errors)) - }, - ) -} - -/** - * Validates the uncle's hash - * @method validateUncleHash - * @return {Boolean} - */ -Block.prototype.validateUnclesHash = function() { - var raw = [] - this.uncleHeaders.forEach(function(uncle) { - raw.push(uncle.raw) - }) - - raw = rlp.encode(raw) - return ethUtil.sha3(raw).toString('hex') === this.header.uncleHash.toString('hex') -} - -/** - * Validates the uncles that are in the block if any. Returns a string to the callback if uncles are invalid - * @method validateUncles - * @param {Blockchain} blockChaina an instance of the Blockchain - * @param {Function} cb the callback - */ -Block.prototype.validateUncles = function(blockChain, cb) { - if (this.isGenesis()) { - return cb() - } - - var self = this - - if (self.uncleHeaders.length > 2) { - return cb('too many uncle headers') - } - - var uncleHashes = self.uncleHeaders.map(function(header) { - return header.hash().toString('hex') - }) - - if (!(new Set(uncleHashes).size === uncleHashes.length)) { - return cb('duplicate uncles') - } - - async.each( - self.uncleHeaders, - function(uncle, cb2) { - var height = new BN(self.header.number) - async.parallel( - [ - uncle.validate.bind(uncle, blockChain, height), - // check to make sure the uncle is not already in the blockchain - function(cb3) { - blockChain.getDetails(uncle.hash(), function(err, blockInfo) { - // TODO: remove uncles from BC - if (blockInfo && blockInfo.isUncle) { - cb3(err || 'uncle already included') - } else { - cb3() - } - }) - }, - ], - cb2, - ) - }, - cb, - ) -} - -/** - * Converts the block toJSON - * @method toJSON - * @param {Bool} labeled whether to create an labeled object or an array - * @return {Object} - */ -Block.prototype.toJSON = function(labeled) { - if (labeled) { - var obj = { - header: this.header.toJSON(true), - transactions: [], - uncleHeaders: [], - } - - this.transactions.forEach(function(tx) { - obj.transactions.push(tx.toJSON(labeled)) - }) - - this.uncleHeaders.forEach(function(uh) { - obj.uncleHeaders.push(uh.toJSON()) - }) - return obj - } else { - return ethUtil.baToJSON(this.raw) - } -} - -function arrayToString(array) { - try { - return array.reduce(function(str, err) { - if (str) { - str += ' ' - } - return str + err - }) - } catch (e) { - return '' - } -} +export { Block } from './block' +export { BlockHeader } from './header' +export * from './types' diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..6dea7a5 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,77 @@ +import Common from 'ethereumjs-common' +import { TxData } from 'ethereumjs-tx' +import { Block } from './block' + +/** + * An object to set which network blocks and their headers belong to. This could be specified using + * a Common object, or `chain` and `hardfork`. Defaults to mainnet. + */ +export interface NetworkOptions { + /** + * A Common object defining the chain and the hardfork a block/block header belongs to. + */ + common?: Common + + /** + * The chain of the block/block header, default: 'mainnet' + */ + chain?: number | string + + /** + * The hardfork of the block/block header, default: 'petersburg' + */ + hardfork?: string +} + +/** + * Any object that can be transformed into a `Buffer` + */ +export interface TransformableToBuffer { + toBuffer(): Buffer +} + +/** + * A hex string prefixed with `0x`. + */ +export type PrefixedHexString = string + +/** + * A Buffer, hex string prefixed with `0x`, Number, or an object with a toBuffer method such as BN. + */ +export type BufferLike = Buffer | TransformableToBuffer | PrefixedHexString | number + +/** + * A block header's data. + */ +export interface BlockHeaderData { + parentHash?: BufferLike + uncleHash?: BufferLike + coinbase?: BufferLike + stateRoot?: BufferLike + transactionsTrie?: BufferLike + receiptTrie?: BufferLike + bloom?: BufferLike + difficulty?: BufferLike + number?: BufferLike + gasLimit?: BufferLike + gasUsed?: BufferLike + timestamp?: BufferLike + extraData?: BufferLike + mixHash?: BufferLike + nonce?: BufferLike +} + +/** + * A block's data. + */ +export interface BlockData { + header?: Buffer | PrefixedHexString | BufferLike[] | BlockHeaderData + transactions?: Array + uncleHeaders?: Array +} + +export interface Blockchain { + getBlock(hash: Buffer, callback: (err: Error | null, block?: Block) => void): void +} + +export type NoReturnValueCallback = (err: Error | null) => void diff --git a/test/block.js b/test/block.ts similarity index 71% rename from test/block.js rename to test/block.ts index 5e1062c..413f75b 100644 --- a/test/block.js +++ b/test/block.ts @@ -1,13 +1,14 @@ -const tape = require('tape') -const Common = require('ethereumjs-common').default -const rlp = require('ethereumjs-util').rlp -const Block = require('../index.js') +import Common from 'ethereumjs-common' +import tape = require('tape') +import { rlp } from 'ethereumjs-util' + +import { Block } from '../src/block' tape('[Block]: block functions', function(t) { t.test('should test block initialization', function(st) { - const block1 = new Block(null, { chain: 'ropsten' }) + const block1 = new Block(undefined, { chain: 'ropsten' }) const common = new Common('ropsten') - const block2 = new Block(null, { common: common }) + const block2 = new Block(undefined, { common: common }) block1.setGenesisParams() block2.setGenesisParams() st.strictEqual( @@ -18,7 +19,7 @@ tape('[Block]: block functions', function(t) { st.throws( function() { - new Block(null, { chain: 'ropsten', common: common }) + new Block(undefined, { chain: 'ropsten', common: common }) }, /not allowed!$/, 'should throw on initialization with chain and common parameter', @@ -28,7 +29,7 @@ tape('[Block]: block functions', function(t) { const testData = require('./testdata.json') - function testTransactionValidation(st, block) { + function testTransactionValidation(st: tape.Test, block: Block) { st.equal(block.validateTransactions(), true) block.genTxTrie(function() { @@ -38,26 +39,26 @@ tape('[Block]: block functions', function(t) { } t.test('should test transaction validation', function(st) { - var block = new Block(rlp.decode(testData.blocks[0].rlp)) + const block = new Block(rlp.decode(testData.blocks[0].rlp)) st.plan(2) testTransactionValidation(st, block) }) t.test('should test transaction validation with empty transaction list', function(st) { - var block = new Block() + const block = new Block() st.plan(2) testTransactionValidation(st, block) }) const testData2 = require('./testdata2.json') t.test('should test uncles hash validation', function(st) { - var block = new Block(rlp.decode(testData2.blocks[2].rlp)) + const block = new Block(rlp.decode(testData2.blocks[2].rlp)) st.equal(block.validateUnclesHash(), true) st.end() }) t.test('should test isGenesis (mainnet default)', function(st) { - var block = new Block() + const block = new Block() st.notEqual(block.isGenesis(), true) block.header.number = Buffer.from([]) st.equal(block.isGenesis(), true) @@ -65,7 +66,7 @@ tape('[Block]: block functions', function(t) { }) t.test('should test isGenesis (ropsten)', function(st) { - var block = new Block(null, { chain: 'ropsten' }) + const block = new Block(undefined, { chain: 'ropsten' }) st.notEqual(block.isGenesis(), true) block.header.number = Buffer.from([]) st.equal(block.isGenesis(), true) @@ -74,9 +75,9 @@ tape('[Block]: block functions', function(t) { const testDataGenesis = require('./genesishashestest.json').test t.test('should test genesis hashes (mainnet default)', function(st) { - var genesisBlock = new Block() + const genesisBlock = new Block() genesisBlock.setGenesisParams() - var rlp = genesisBlock.serialize() + const rlp = genesisBlock.serialize() st.strictEqual(rlp.toString('hex'), testDataGenesis.genesis_rlp_hex, 'rlp hex match') st.strictEqual( genesisBlock.hash().toString('hex'), @@ -87,8 +88,8 @@ tape('[Block]: block functions', function(t) { }) t.test('should test genesis hashes (ropsten)', function(st) { - var common = new Common('ropsten') - var genesisBlock = new Block(null, { common: common }) + const common = new Common('ropsten') + const genesisBlock = new Block(undefined, { common: common }) genesisBlock.setGenesisParams() st.strictEqual( genesisBlock.hash().toString('hex'), @@ -99,8 +100,8 @@ tape('[Block]: block functions', function(t) { }) t.test('should test genesis hashes (rinkeby)', function(st) { - var common = new Common('rinkeby') - var genesisBlock = new Block(null, { common: common }) + const common = new Common('rinkeby') + const genesisBlock = new Block(undefined, { common: common }) genesisBlock.setGenesisParams() st.strictEqual( genesisBlock.hash().toString('hex'), @@ -111,9 +112,9 @@ tape('[Block]: block functions', function(t) { }) t.test('should test genesis parameters (ropsten)', function(st) { - var genesisBlock = new Block(null, { chain: 'ropsten' }) + const genesisBlock = new Block(undefined, { chain: 'ropsten' }) genesisBlock.setGenesisParams() - let ropstenStateRoot = '217b0bbcfb72e2d57e28f33cb361b9983513177755dc3f33ce3e7022ed62b77b' + const ropstenStateRoot = '217b0bbcfb72e2d57e28f33cb361b9983513177755dc3f33ce3e7022ed62b77b' st.strictEqual( genesisBlock.header.stateRoot.toString('hex'), ropstenStateRoot, @@ -123,7 +124,7 @@ tape('[Block]: block functions', function(t) { }) t.test('should test toJSON', function(st) { - var block = new Block(rlp.decode(testData2.blocks[2].rlp)) + const block = new Block(rlp.decode(testData2.blocks[2].rlp)) st.equal(typeof block.toJSON(), 'object') st.equal(typeof block.toJSON(true), 'object') st.end() diff --git a/test/difficulty.js b/test/difficulty.ts similarity index 65% rename from test/difficulty.js rename to test/difficulty.ts index feedc2b..2321a1d 100644 --- a/test/difficulty.js +++ b/test/difficulty.ts @@ -1,41 +1,45 @@ -const utils = require('ethereumjs-util') -const tape = require('tape') -const Block = require('../') -const BN = utils.BN +import * as utils from 'ethereumjs-util' +import { BN } from 'ethereumjs-util' +import { Block } from '../src/block' +import tape = require('tape') -function normalize(data) { - Object.keys(data).map(function(i) { +function isHexPrefixed(str: string) { + return str.toLowerCase().startsWith('0x') +} + +function normalize(data: any) { + Object.keys(data).forEach(function(i) { if (i !== 'homestead' && typeof data[i] === 'string') { - data[i] = utils.isHexPrefixed(data[i]) ? new BN(utils.toBuffer(data[i])) : new BN(data[i]) + data[i] = isHexPrefixed(data[i]) ? new BN(utils.toBuffer(data[i])) : new BN(data[i]) } }) } tape('[Header]: difficulty tests', t => { - function runDifficultyTests(test, parentBlock, block, msg) { + function runDifficultyTests(test: any, parentBlock: Block, block: Block, msg: string) { normalize(test) - var dif = block.header.canonicalDifficulty(parentBlock) + const dif = block.header.canonicalDifficulty(parentBlock) t.equal(dif.toString(), test.currentDifficulty.toString(), `test canonicalDifficulty (${msg})`) t.assert(block.header.validateDifficulty(parentBlock), `test validateDifficulty (${msg})`) } - const hardforkTestData = { + const hardforkTestData: any = { chainstart: require('./difficultyFrontier.json').tests, homestead: require('./difficultyHomestead.json').tests, byzantium: require('./difficultyByzantium.json').tests, constantinople: require('./difficultyConstantinople.json').tests, } - for (let hardfork in hardforkTestData) { + for (const hardfork in hardforkTestData) { const testData = hardforkTestData[hardfork] - for (let testName in testData) { - let test = testData[testName] - let parentBlock = new Block(null, { chain: 'mainnet', hardfork: hardfork }) + for (const testName in testData) { + const test = testData[testName] + const parentBlock = new Block(undefined, { chain: 'mainnet', hardfork: hardfork }) parentBlock.header.timestamp = test.parentTimestamp parentBlock.header.difficulty = test.parentDifficulty parentBlock.header.uncleHash = test.parentUncles - let block = new Block(null, { chain: 'mainnet', hardfork: hardfork }) + const block = new Block(undefined, { chain: 'mainnet', hardfork: hardfork }) block.header.timestamp = test.currentTimestamp block.header.difficulty = test.currentDifficulty block.header.number = test.currentBlockNumber @@ -44,20 +48,20 @@ tape('[Header]: difficulty tests', t => { } } - const chainTestData = { + const chainTestData: any = { mainnet: require('./difficultyMainNetwork.json').tests, ropsten: require('./difficultyRopstenConstantinople.json').tests, } - for (let chain in chainTestData) { + for (const chain in chainTestData) { const testData = chainTestData[chain] - for (let testName in testData) { - let test = testData[testName] - let parentBlock = new Block(null, { chain: chain }) + for (const testName in testData) { + const test = testData[testName] + const parentBlock = new Block(undefined, { chain: chain }) parentBlock.header.timestamp = test.parentTimestamp parentBlock.header.difficulty = test.parentDifficulty parentBlock.header.uncleHash = test.parentUncles - let block = new Block(null, { chain: chain }) + const block = new Block(undefined, { chain: chain }) block.header.timestamp = test.currentTimestamp block.header.difficulty = test.currentDifficulty block.header.number = test.currentBlockNumber diff --git a/test/from-rpc.js b/test/from-rpc.js deleted file mode 100644 index 814394b..0000000 --- a/test/from-rpc.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict' -const tape = require('tape') -const blockFromRpc = require('../from-rpc.js') -const blockData = require('./testdata-from-rpc.json') - -tape('[fromRPC]: block #2924874', function(t) { - t.test('should create a block with transactions with valid signatures', function(st) { - let block = blockFromRpc(blockData) - let allValid = block.transactions.every(tx => tx.verifySignature()) - st.equal(allValid, true, 'all transaction signatures are valid') - st.end() - }) -}) diff --git a/test/from-rpc.ts b/test/from-rpc.ts new file mode 100644 index 0000000..f8b6c4c --- /dev/null +++ b/test/from-rpc.ts @@ -0,0 +1,13 @@ +// 'use strict' +// const tape = require('tape') +// const blockFromRpc = require('../from-rpc.js') +// const blockData = require('./testdata-from-rpc.json') +// +// tape('[fromRPC]: block #2924874', function(t) { +// t.test('should create a block with transactions with valid signatures', function(st) { +// let block = blockFromRpc(blockData) +// let allValid = block.transactions.every(tx => tx.verifySignature()) +// st.equal(allValid, true, 'all transaction signatures are valid') +// st.end() +// }) +// }) diff --git a/test/header.js b/test/header.ts similarity index 65% rename from test/header.js rename to test/header.ts index 49ca9df..05f92ec 100644 --- a/test/header.js +++ b/test/header.ts @@ -1,22 +1,22 @@ -const tape = require('tape') -const Common = require('ethereumjs-common').default -const utils = require('ethereumjs-util') -const rlp = utils.rlp -const Header = require('../header.js') -const Block = require('../index.js') +import tape = require('tape') +import Common from 'ethereumjs-common' +import * as utils from 'ethereumjs-util' +import { rlp } from 'ethereumjs-util' +import { BlockHeader } from '../src/header' +import { Block } from '../src/block' tape('[Block]: Header functions', function(t) { t.test('should create with default constructor', function(st) { - function compareDefaultHeader(st, header) { + function compareDefaultHeader(st: tape.Test, header: BlockHeader) { st.deepEqual(header.parentHash, utils.zeros(32)) - st.equal(header.uncleHash.toString('hex'), utils.SHA3_RLP_ARRAY_S) + st.equal(header.uncleHash.toString('hex'), utils.KECCAK256_RLP_ARRAY_S) st.deepEqual(header.coinbase, utils.zeros(20)) st.deepEqual(header.stateRoot, utils.zeros(32)) - st.equal(header.transactionsTrie.toString('hex'), utils.SHA3_RLP_S) - st.equal(header.receiptTrie.toString('hex'), utils.SHA3_RLP_S) + st.equal(header.transactionsTrie.toString('hex'), utils.KECCAK256_RLP_S) + st.equal(header.receiptTrie.toString('hex'), utils.KECCAK256_RLP_S) st.deepEqual(header.bloom, utils.zeros(256)) st.deepEqual(header.difficulty, Buffer.from([])) - st.deepEqual(header.number, utils.intToBuffer(1150000)) + st.deepEqual(header.number, utils.toBuffer(1150000)) st.deepEqual(header.gasLimit, Buffer.from('ffffffffffffff', 'hex')) st.deepEqual(header.gasUsed, Buffer.from([])) st.deepEqual(header.timestamp, Buffer.from([])) @@ -25,10 +25,10 @@ tape('[Block]: Header functions', function(t) { st.deepEqual(header.nonce, utils.zeros(8)) } - var header = new Header() + let header = new BlockHeader() compareDefaultHeader(st, header) - var block = new Block() + const block = new Block() header = block.header compareDefaultHeader(st, header) @@ -36,9 +36,9 @@ tape('[Block]: Header functions', function(t) { }) t.test('should test header initialization', function(st) { - const header1 = new Header(null, { chain: 'ropsten' }) + const header1 = new BlockHeader(undefined, { chain: 'ropsten' }) const common = new Common('ropsten') - const header2 = new Header(null, { common: common }) + const header2 = new BlockHeader(undefined, { common: common }) header1.setGenesisParams() header2.setGenesisParams() st.strictEqual( @@ -49,7 +49,7 @@ tape('[Block]: Header functions', function(t) { st.throws( function() { - new Header(null, { chain: 'ropsten', common: common }) + new BlockHeader(undefined, { chain: 'ropsten', common: common }) }, /not allowed!$/, 'should throw on initialization with chain and common parameter', @@ -62,8 +62,8 @@ tape('[Block]: Header functions', function(t) { const bcBlockGasLimigTestData = testData.BlockGasLimit2p63m1 Object.keys(bcBlockGasLimigTestData).forEach(key => { - var parentBlock = new Block(rlp.decode(bcBlockGasLimigTestData[key].genesisRLP)) - var block = new Block(rlp.decode(bcBlockGasLimigTestData[key].blocks[0].rlp)) + const parentBlock = new Block(rlp.decode(bcBlockGasLimigTestData[key].genesisRLP)) + const block = new Block(rlp.decode(bcBlockGasLimigTestData[key].blocks[0].rlp)) st.equal(block.header.validateGasLimit(parentBlock), true) }) @@ -71,7 +71,7 @@ tape('[Block]: Header functions', function(t) { }) t.test('should test isGenesis', function(st) { - var header = new Header() + const header = new BlockHeader() st.equal(header.isGenesis(), false) header.number = Buffer.from([]) st.equal(header.isGenesis(), true) @@ -80,7 +80,7 @@ tape('[Block]: Header functions', function(t) { const testDataGenesis = require('./genesishashestest.json').test t.test('should test genesis hashes (mainnet default)', function(st) { - var header = new Header() + const header = new BlockHeader() header.setGenesisParams() st.strictEqual( header.hash().toString('hex'), @@ -91,9 +91,9 @@ tape('[Block]: Header functions', function(t) { }) t.test('should test genesis parameters (ropsten)', function(st) { - var genesisHeader = new Header(null, { chain: 'ropsten' }) + const genesisHeader = new BlockHeader(undefined, { chain: 'ropsten' }) genesisHeader.setGenesisParams() - let ropstenStateRoot = '217b0bbcfb72e2d57e28f33cb361b9983513177755dc3f33ce3e7022ed62b77b' + const ropstenStateRoot = '217b0bbcfb72e2d57e28f33cb361b9983513177755dc3f33ce3e7022ed62b77b' st.strictEqual( genesisHeader.stateRoot.toString('hex'), ropstenStateRoot, diff --git a/test/index.js b/test/index.js deleted file mode 100644 index f0db526..0000000 --- a/test/index.js +++ /dev/null @@ -1,4 +0,0 @@ -require('./header.js') -require('./block.js') -require('./difficulty.js') -require('./from-rpc.js') diff --git a/test/index.ts b/test/index.ts new file mode 100644 index 0000000..ad57656 --- /dev/null +++ b/test/index.ts @@ -0,0 +1,4 @@ +import './header' +import './block' +import './difficulty' +import './from-rpc' diff --git a/tsconfig.json b/tsconfig.json index 16b64ff..c1249c3 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,6 +2,7 @@ "extends": "@ethereumjs/config-tsc", "include": ["src/**/*.ts", "test/**/*.ts"], "compilerOptions": { - "outDir": "test-build" + "outDir": "test-build", + "esModuleInterop": true } } diff --git a/tsconfig.prod.json b/tsconfig.prod.json index 184d95b..48aa0d4 100644 --- a/tsconfig.prod.json +++ b/tsconfig.prod.json @@ -1,7 +1,8 @@ { "extends": "@ethereumjs/config-tsc", "compilerOptions": { - "outDir": "./dist" + "outDir": "./dist", + "esModuleInterop": true }, "include": ["src/**/*.ts"] } diff --git a/tslint.json b/tslint.json index 2ba21c4..d0507fe 100644 --- a/tslint.json +++ b/tslint.json @@ -1,3 +1,6 @@ { - "extends": "@ethereumjs/config-tslint" + "extends": "@ethereumjs/config-tslint", + "rules": { + "prefer-const": true + } } From c08fcba9baa244eea7022d9a5ab0c9d19cbd1bd4 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Thu, 25 Jul 2019 20:17:00 -0300 Subject: [PATCH 07/25] Update .prettierignore --- .prettierignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.prettierignore b/.prettierignore index 03abf45..3cad7b1 100644 --- a/.prettierignore +++ b/.prettierignore @@ -2,4 +2,5 @@ node_modules .vscode package.json dist +test-build .nyc_output \ No newline at end of file From 58413c18ca6585143de00a5a5c89c03a2f10b964 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Mon, 29 Jul 2019 14:34:25 -0300 Subject: [PATCH 08/25] Fix travis config --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 8c67ccd..c506d2e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,7 +38,7 @@ matrix: node_js: "10" env: CXX=g++-4.8 TEST_SUITE=test:node - os: linux - node_js: "11" + node_js: "11" env: CXX=g++-4.8 TEST_SUITE=test:node - os: linux node_js: "12" From dab891ab38972322765209f32d54b138e87f45e8 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Mon, 29 Jul 2019 14:54:03 -0300 Subject: [PATCH 09/25] Remove callbacks in favor of async await --- src/block.ts | 56 +++++------------------- src/callbackify.ts | 77 --------------------------------- src/header.ts | 104 ++++++++++++++++++++------------------------- src/types.ts | 2 - test/block.ts | 18 ++++---- 5 files changed, 64 insertions(+), 193 deletions(-) delete mode 100644 src/callbackify.ts diff --git a/src/block.ts b/src/block.ts index 767a447..d691db8 100644 --- a/src/block.ts +++ b/src/block.ts @@ -4,8 +4,7 @@ import { BN, rlp } from 'ethereumjs-util' import { Transaction } from 'ethereumjs-tx' import { BlockHeader } from './header' -import { Blockchain, BlockData, NetworkOptions, NoReturnValueCallback } from './types' -import { callbackify } from './callbackify' +import { Blockchain, BlockData, NetworkOptions } from './types' const Trie = require('merkle-patricia-tree') @@ -130,11 +129,7 @@ export class Block { * Generate transaction trie. The tx trie must be generated before the transaction trie can * be validated with `validateTransactionTrie` */ - genTxTrie(cb: NoReturnValueCallback) { - callbackify(this._getTxTrie.bind(this))(cb) - } - - private async _getTxTrie() { + async genTxTrie() { for (let i = 0; i < this.transactions.length; i++) { const tx = this.transactions[i] await this._putTxInTrie(i, tx) @@ -179,7 +174,7 @@ export class Block { this.transactions.forEach(function(tx, i) { const error = tx.validate(true) if (error) { - errors.push(error + ' at tx ' + i) + errors.push(`${error} at tx ${i}`) } }) @@ -193,18 +188,13 @@ export class Block { /** * Validates the entire block. Returns a string to the callback if block is invalid * @method validate - * @param {BlockChain} blockChain the blockchain that this block wants to be part of - * @param {Function} cb the callback which is given a `String` if the block is not valid + * @param blockChain the blockchain that this block wants to be part of */ - validate(blockChain: Blockchain, cb: NoReturnValueCallback) { - callbackify(this._validate.bind(this, blockChain))(cb) - } - - private async _validate(blockChain: Blockchain) { + async validate(blockChain: Blockchain) { await Promise.all([ - this._validateUncles(blockChain), - this._getTxTrie(), - this._validateHeader(this.header, blockChain), + this.validateUncles(blockChain), + this.genTxTrie(), + this.header.validate(blockChain), ]) if (!this.validateTransactionsTrie()) { @@ -236,11 +226,7 @@ export class Block { * @param {Blockchain} blockChain an instance of the Blockchain * @param {Function} cb the callback */ - validateUncles(blockChain: Blockchain, cb: NoReturnValueCallback) { - callbackify(this._validateUncles.bind(this, blockChain))(cb) - } - - private async _validateUncles(blockchain: Blockchain) { + async validateUncles(blockchain: Blockchain) { if (this.isGenesis()) { return } @@ -258,7 +244,7 @@ export class Block { return Promise.all( this.uncleHeaders.map(async uh => { const height = new BN(this.header.number) - return this._validateHeader(uh, blockchain, height) + return uh.validate(blockchain, height) }), ) } @@ -278,26 +264,4 @@ export class Block { return ethUtil.baToJSON(this.raw) } } - - private _validateHeader(header: BlockHeader, blockchain: Blockchain, height?: BN) { - return new Promise((resolve, reject) => { - if (height !== undefined) { - header.validate(blockchain, height, err => { - if (err) { - reject(err) - } - - resolve() - }) - } else { - header.validate(blockchain, err => { - if (err) { - reject(err) - } - - resolve() - }) - } - }) - } } diff --git a/src/callbackify.ts b/src/callbackify.ts deleted file mode 100644 index 5d3fbc9..0000000 --- a/src/callbackify.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -function callbackifyOnRejected(reason: any, cb: any) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - const newReason = new Error('Promise was rejected with a falsy value') as any - newReason.reason = reason - reason = newReason - } - return cb(reason) -} - -export function callbackify(original: any): any { - if (typeof original !== 'function') { - throw new TypeError('The "original" argument must be of type Function') - } - - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified(this: any) { - const args = [] - for (let i = 0; i < arguments.length; i++) { - args.push(arguments[i]) - } - - const maybeCb = args.pop() - if (typeof maybeCb !== 'function') { - throw new TypeError('The last argument must be of type Function') - } - - //tslint:disable-next-line no-invalid-this - const self = this - const cb = function() { - return maybeCb.apply(self, arguments) - } - - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - //tslint:disable-next-line no-invalid-this - original.apply(this, args).then( - function(ret: any) { - process.nextTick(cb.bind(null, null, ret)) - }, - function(rej: any) { - process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) - }, - ) - } - - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)) - Object.defineProperties(callbackified, Object.getOwnPropertyDescriptors(original)) - - return callbackified -} diff --git a/src/header.ts b/src/header.ts index 2c0a12b..0100a32 100644 --- a/src/header.ts +++ b/src/header.ts @@ -1,14 +1,7 @@ import Common from 'ethereumjs-common' import * as utils from 'ethereumjs-util' import { BN } from 'ethereumjs-util' -import { - Blockchain, - BlockHeaderData, - BufferLike, - NetworkOptions, - NoReturnValueCallback, - PrefixedHexString, -} from './types' +import { Blockchain, BlockHeaderData, BufferLike, NetworkOptions, PrefixedHexString } from './types' import { Buffer } from 'buffer' import { Block } from './block' @@ -270,70 +263,50 @@ export class BlockHeader { * @method validate * @param {Blockchain} blockChain the blockchain that this block is validating against * @param {Bignum} [height] if this is an uncle header, this is the height of the block that is including it - * @param {Function} cb the callback function. The callback is given an `error` if the block is invalid */ - validate(blockchain: Blockchain, cb: NoReturnValueCallback): void - validate(blockchain: Blockchain, height: BN, cb: NoReturnValueCallback): void - validate( - blockchain: Blockchain, - heightOrCb: BN | NoReturnValueCallback, - cb?: NoReturnValueCallback, - ): void { - if (heightOrCb instanceof Function) { - cb = heightOrCb - } - - if (cb === undefined) { - throw new Error('No callback provided') - } - - const callback = cb - + async validate(blockchain: Blockchain, height?: BN): Promise { if (this.isGenesis()) { - return callback(null) + return } - // find the blocks parent - blockchain.getBlock(this.parentHash, (err, parentBlock) => { - if (err || parentBlock === undefined) { - return callback(new Error('could not find parent block')) - } + const parentBlock = await this._getBlockByHash(blockchain, this.parentHash) - const number = new BN(this.number) - if (number.cmp(new BN(parentBlock.header.number).iaddn(1)) !== 0) { - return callback(new Error('invalid number')) - } + if (parentBlock === undefined) { + throw new Error('could not find parent block') + } - if (BN.isBN(heightOrCb)) { - const dif = heightOrCb.sub(new BN(parentBlock.header.number)) - if (!(dif.cmpn(8) === -1 && dif.cmpn(1) === 1)) { - return callback(new Error('uncle block has a parent that is too old or to young')) - } - } + const number = new BN(this.number) + if (number.cmp(new BN(parentBlock.header.number).iaddn(1)) !== 0) { + throw new Error('invalid number') + } - if (!this.validateDifficulty(parentBlock)) { - return callback(new Error('invalid Difficulty')) + if (height !== undefined && BN.isBN(height)) { + const dif = height.sub(new BN(parentBlock.header.number)) + if (!(dif.cmpn(8) === -1 && dif.cmpn(1) === 1)) { + throw new Error('uncle block has a parent that is too old or to young') } + } - if (!this.validateGasLimit(parentBlock)) { - return callback(new Error('invalid gas limit')) - } + if (!this.validateDifficulty(parentBlock)) { + throw new Error('invalid Difficulty') + } - if (utils.bufferToInt(parentBlock.header.number) + 1 !== utils.bufferToInt(this.number)) { - return callback(new Error('invalid heigth')) - } + if (!this.validateGasLimit(parentBlock)) { + throw new Error('invalid gas limit') + } - if (utils.bufferToInt(this.timestamp) <= utils.bufferToInt(parentBlock.header.timestamp)) { - return callback(new Error('invalid timestamp')) - } + if (utils.bufferToInt(parentBlock.header.number) + 1 !== utils.bufferToInt(this.number)) { + throw new Error('invalid heigth') + } - const hardfork = this._getHardfork() - if (this.extraData.length > this._common.param('vm', 'maxExtraDataSize', hardfork)) { - return callback(new Error('invalid amount of extra data')) - } + if (utils.bufferToInt(this.timestamp) <= utils.bufferToInt(parentBlock.header.timestamp)) { + throw new Error('invalid timestamp') + } - callback(null) - }) + const hardfork = this._getHardfork() + if (this.extraData.length > this._common.param('vm', 'maxExtraDataSize', hardfork)) { + throw new Error('invalid amount of extra data') + } } /** @@ -392,4 +365,17 @@ export class BlockHeader { ? commonHardFork : this._common.activeHardfork(utils.bufferToInt(this.number)) } + + private async _getBlockByHash(blockchain: Blockchain, hash: Buffer): Promise { + return new Promise((resolve, reject) => { + blockchain.getBlock(hash, (err, block) => { + if (err) { + reject(err) + return + } + + resolve(block) + }) + }) + } } diff --git a/src/types.ts b/src/types.ts index 6dea7a5..724909a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -73,5 +73,3 @@ export interface BlockData { export interface Blockchain { getBlock(hash: Buffer, callback: (err: Error | null, block?: Block) => void): void } - -export type NoReturnValueCallback = (err: Error | null) => void diff --git a/test/block.ts b/test/block.ts index 413f75b..e619aa2 100644 --- a/test/block.ts +++ b/test/block.ts @@ -29,25 +29,25 @@ tape('[Block]: block functions', function(t) { const testData = require('./testdata.json') - function testTransactionValidation(st: tape.Test, block: Block) { + async function testTransactionValidation(st: tape.Test, block: Block) { st.equal(block.validateTransactions(), true) - block.genTxTrie(function() { - st.equal(block.validateTransactionsTrie(), true) - st.end() - }) + await block.genTxTrie() + + st.equal(block.validateTransactionsTrie(), true) + st.end() } - t.test('should test transaction validation', function(st) { + t.test('should test transaction validation', async function(st) { const block = new Block(rlp.decode(testData.blocks[0].rlp)) st.plan(2) - testTransactionValidation(st, block) + await testTransactionValidation(st, block) }) - t.test('should test transaction validation with empty transaction list', function(st) { + t.test('should test transaction validation with empty transaction list', async function(st) { const block = new Block() st.plan(2) - testTransactionValidation(st, block) + await testTransactionValidation(st, block) }) const testData2 = require('./testdata2.json') From 66ea2d66379a3ac390ddeee97bd8225de4bf630d Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Mon, 29 Jul 2019 15:03:57 -0300 Subject: [PATCH 10/25] Fix .travis.yml --- .travis.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index c506d2e..025e381 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,14 +8,14 @@ addons: firefox: latest apt: sources: - - ubuntu-toolchain-r-test + - ubuntu-toolchain-r-test packages: - - g++-4.8 + - g++-4.8 before_install: - sh -e /etc/init.d/xvfb start env: - - CXX=g++-4.8 global: + - CXX=g++-4.8 - DISPLAY=:99.0 matrix: - CXX=g++-4.8 TEST_SUITE=test:node From 5acf16e189db87a07877fb475a285ead8900e6aa Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Mon, 29 Jul 2019 15:20:20 -0300 Subject: [PATCH 11/25] Document missing uncle validation --- src/block.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/block.ts b/src/block.ts index d691db8..510c261 100644 --- a/src/block.ts +++ b/src/block.ts @@ -241,12 +241,7 @@ export class Block { throw new Error('duplicate uncles') } - return Promise.all( - this.uncleHeaders.map(async uh => { - const height = new BN(this.header.number) - return uh.validate(blockchain, height) - }), - ) + return Promise.all(this.uncleHeaders.map(async uh => this._validateUncleHeader(uh, blockchain))) } /** @@ -264,4 +259,13 @@ export class Block { return ethUtil.baToJSON(this.raw) } } + + private _validateUncleHeader(uncleHeader: BlockHeader, blockchain: Blockchain) { + // TODO: Validate that the uncle header hasn't been included in the blockchain yet. + // This is not possible in ethereumjs-blockchain since this PR was merged: + // https://github.com/ethereumjs/ethereumjs-blockchain/pull/47 + + const height = new BN(this.header.number) + return uncleHeader.validate(blockchain, height) + } } From 4769f90900238b33f058b808c715dca721434afd Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Mon, 29 Jul 2019 15:32:22 -0300 Subject: [PATCH 12/25] Migrate RPC related functions --- src/from-rpc.ts | 121 ++++++++++++++++++++++------------------- src/header-from-rpc.ts | 74 +++++++++++++------------ test/from-rpc.ts | 25 ++++----- 3 files changed, 115 insertions(+), 105 deletions(-) diff --git a/src/from-rpc.ts b/src/from-rpc.ts index f73cd03..ee1146b 100644 --- a/src/from-rpc.ts +++ b/src/from-rpc.ts @@ -1,56 +1,65 @@ -// import { Transaction } from 'ethereumjs-tx' -// import * as ethUtil from 'ethereumjs-util' -// import { Block } from './index' -// -// const blockHeaderFromRpc = require('./header-from-rpc') -// -// module.exports = blockFromRpc -// -// /** -// * Creates a new block object from Ethereum JSON RPC. -// * @param {Object} blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) -// * @param {Array.} Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) -// */ -// function blockFromRpc(blockParams, uncles) { -// uncles = uncles || [] -// const block = new Block({ -// transactions: [], -// uncleHeaders: [], -// }) -// block.header = blockHeaderFromRpc(blockParams) -// -// block.transactions = (blockParams.transactions || []).map(function(_txParams) { -// const txParams = normalizeTxParams(_txParams) -// // override from address -// const fromAddress = ethUtil.toBuffer(txParams.from) -// delete txParams.from -// const tx = new Transaction(txParams) -// tx._from = fromAddress -// tx.getSenderAddress = function() { -// return fromAddress -// } -// // override hash -// const txHash = ethUtil.toBuffer(txParams.hash) -// tx.hash = function() { -// return txHash -// } -// return tx -// }) -// block.uncleHeaders = uncles.map(function(uncleParams) { -// return blockHeaderFromRpc(uncleParams) -// }) -// -// return block -// } -// -// function normalizeTxParams(_txParams) { -// const txParams = Object.assign({}, _txParams) -// // hot fix for https://github.com/ethereumjs/ethereumjs-util/issues/40 -// txParams.gasLimit = txParams.gasLimit === undefined ? txParams.gas : txParams.gasLimit -// txParams.data = txParams.data === undefined ? txParams.input : txParams.data -// // strict byte length checking -// txParams.to = txParams.to ? ethUtil.setLengthLeft(ethUtil.toBuffer(txParams.to), 20) : null -// // v as raw signature value {0,1} -// txParams.v = txParams.v < 27 ? txParams.v + 27 : txParams.v -// return txParams -// } +import { FakeTransaction } from 'ethereumjs-tx' +import * as ethUtil from 'ethereumjs-util' +import { Block, NetworkOptions } from './index' + +import blockHeaderFromRpc from './header-from-rpc' + +/** + * Creates a new block object from Ethereum JSON RPC. + * @param blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) + * @param uncles - Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) + * @param networkOptions - An object describing the network + */ +export default function blockFromRpc( + blockParams: any, + uncles?: any[], + networkOptions?: NetworkOptions, +) { + uncles = uncles || [] + + const header = blockHeaderFromRpc(blockParams, networkOptions) + + const block = new Block( + { + header: header.toJSON(true), + transactions: [], + uncleHeaders: uncles.map(uh => blockHeaderFromRpc(uh, networkOptions).toJSON(true)), + }, + networkOptions, + ) + + if (blockParams.transactions) { + for (const _txParams of blockParams.transactions) { + const txParams = normalizeTxParams(_txParams) + // override from address + const fromAddress = ethUtil.toBuffer(txParams.from) + delete txParams.from + const tx = new FakeTransaction(txParams, networkOptions) + tx.from = fromAddress + tx.getSenderAddress = function() { + return fromAddress + } + // override hash + const txHash = ethUtil.toBuffer(txParams.hash) + tx.hash = function() { + return txHash + } + + block.transactions.push(tx) + } + } + + return block +} + +function normalizeTxParams(_txParams: any) { + const txParams = Object.assign({}, _txParams) + // hot fix for https://github.com/ethereumjs/ethereumjs-util/issues/40 + txParams.gasLimit = txParams.gasLimit === undefined ? txParams.gas : txParams.gasLimit + txParams.data = txParams.data === undefined ? txParams.input : txParams.data + // strict byte length checking + txParams.to = txParams.to ? ethUtil.setLengthLeft(ethUtil.toBuffer(txParams.to), 20) : null + // v as raw signature value {0,1} + txParams.v = txParams.v < 27 ? txParams.v + 27 : txParams.v + return txParams +} diff --git a/src/header-from-rpc.ts b/src/header-from-rpc.ts index 4367e17..6923307 100644 --- a/src/header-from-rpc.ts +++ b/src/header-from-rpc.ts @@ -1,36 +1,38 @@ -// 'use strict' -// const BlockHeader = require('./header') -// const ethUtil = require('ethereumjs-util') -// -// module.exports = blockHeaderFromRpc -// -// /** -// * Creates a new block header object from Ethereum JSON RPC. -// * @param {Object} blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) -// */ -// function blockHeaderFromRpc(blockParams) { -// const blockHeader = new BlockHeader({ -// parentHash: blockParams.parentHash, -// uncleHash: blockParams.sha3Uncles, -// coinbase: blockParams.miner, -// stateRoot: blockParams.stateRoot, -// transactionsTrie: blockParams.transactionsRoot, -// receiptTrie: blockParams.receiptRoot || blockParams.receiptsRoot || ethUtil.SHA3_NULL, -// bloom: blockParams.logsBloom, -// difficulty: blockParams.difficulty, -// number: blockParams.number, -// gasLimit: blockParams.gasLimit, -// gasUsed: blockParams.gasUsed, -// timestamp: blockParams.timestamp, -// extraData: blockParams.extraData, -// mixHash: blockParams.mixHash, -// nonce: blockParams.nonce, -// }) -// -// // override hash incase something was missing -// blockHeader.hash = function() { -// return ethUtil.toBuffer(blockParams.hash) -// } -// -// return blockHeader -// } +import { BlockHeader } from './header' +import * as ethUtil from 'ethereumjs-util' +import { NetworkOptions } from './types' + +/** + * Creates a new block header object from Ethereum JSON RPC. + * @param blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) + * @param networkOptions - An object describing the network + */ +export default function blockHeaderFromRpc(blockParams: any, networkOptions?: NetworkOptions) { + const blockHeader = new BlockHeader( + { + parentHash: blockParams.parentHash, + uncleHash: blockParams.sha3Uncles, + coinbase: blockParams.miner, + stateRoot: blockParams.stateRoot, + transactionsTrie: blockParams.transactionsRoot, + receiptTrie: blockParams.receiptRoot || blockParams.receiptsRoot || ethUtil.KECCAK256_NULL, + bloom: blockParams.logsBloom, + difficulty: blockParams.difficulty, + number: blockParams.number, + gasLimit: blockParams.gasLimit, + gasUsed: blockParams.gasUsed, + timestamp: blockParams.timestamp, + extraData: blockParams.extraData, + mixHash: blockParams.mixHash, + nonce: blockParams.nonce, + }, + networkOptions, + ) + + // override hash in case something was missing + blockHeader.hash = function() { + return ethUtil.toBuffer(blockParams.hash) + } + + return blockHeader +} diff --git a/test/from-rpc.ts b/test/from-rpc.ts index f8b6c4c..c6e71da 100644 --- a/test/from-rpc.ts +++ b/test/from-rpc.ts @@ -1,13 +1,12 @@ -// 'use strict' -// const tape = require('tape') -// const blockFromRpc = require('../from-rpc.js') -// const blockData = require('./testdata-from-rpc.json') -// -// tape('[fromRPC]: block #2924874', function(t) { -// t.test('should create a block with transactions with valid signatures', function(st) { -// let block = blockFromRpc(blockData) -// let allValid = block.transactions.every(tx => tx.verifySignature()) -// st.equal(allValid, true, 'all transaction signatures are valid') -// st.end() -// }) -// }) +import tape = require('tape') +import blockFromRpc from '../src/from-rpc' +import * as blockData from './testdata-from-rpc.json' + +tape('[fromRPC]: block #2924874', function(t) { + t.test('should create a block with transactions with valid signatures', function(st) { + let block = blockFromRpc(blockData) + let allValid = block.transactions.every(tx => tx.verifySignature()) + st.equal(allValid, true, 'all transaction signatures are valid') + st.end() + }) +}) From 1cf52dec0a914380233d3ed968c0807294426e4f Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Mon, 29 Jul 2019 15:53:43 -0300 Subject: [PATCH 13/25] Update docs --- README.md | 7 - docs/README.md | 99 +++++ docs/classes/block.md | 396 ++++++++++++++++++++ docs/classes/blockheader.md | 438 +++++++++++++++++++++++ docs/fromRpc.md | 11 - docs/index.md | 187 ---------- docs/interfaces/blockchain.md | 36 ++ docs/interfaces/blockdata.md | 51 +++ docs/interfaces/blockheaderdata.md | 183 ++++++++++ docs/interfaces/networkoptions.md | 57 +++ docs/interfaces/transformabletobuffer.md | 31 ++ src/block.ts | 84 +++-- src/from-rpc.ts | 1 + src/header-from-rpc.ts | 1 + src/header.ts | 68 ++-- src/types.ts | 4 +- 16 files changed, 1359 insertions(+), 295 deletions(-) create mode 100644 docs/README.md create mode 100644 docs/classes/block.md create mode 100644 docs/classes/blockheader.md delete mode 100644 docs/fromRpc.md delete mode 100644 docs/index.md create mode 100644 docs/interfaces/blockchain.md create mode 100644 docs/interfaces/blockdata.md create mode 100644 docs/interfaces/blockheaderdata.md create mode 100644 docs/interfaces/networkoptions.md create mode 100644 docs/interfaces/transformabletobuffer.md diff --git a/README.md b/README.md index 80756a0..16254bb 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,6 @@ [![Coverage Status](https://img.shields.io/coveralls/ethereumjs/ethereumjs-block.svg?style=flat-square)](https://coveralls.io/r/ethereumjs/ethereumjs-block) [![Gitter](https://img.shields.io/gitter/room/ethereum/ethereumjs-lib.svg?style=flat-square)]() or #ethereumjs on freenode -[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) - Implements schema and functions related to Ethereum's block. # INSTALL @@ -25,11 +23,6 @@ This module work with `browserify`. Tests in the `tests` directory are partly outdated and testing is primarily done by running the `BlockchainTests` from within the [ethereumjs-vm](https://github.com/ethereumjs/ethereumjs-vm) repository. -Relevant test folders: - -- `bcTotalDifficultyTest` -- TODO - # EthereumJS See our organizational [documentation](https://ethereumjs.readthedocs.io) for an introduction to `EthereumJS` as well as information on current standards and best practices. diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..7db8c6e --- /dev/null +++ b/docs/README.md @@ -0,0 +1,99 @@ +# ethereumjs-block + +## Index + +### Classes + +- [Block](classes/block.md) +- [BlockHeader](classes/blockheader.md) + +### Interfaces + +- [BlockData](interfaces/blockdata.md) +- [BlockHeaderData](interfaces/blockheaderdata.md) +- [Blockchain](interfaces/blockchain.md) +- [NetworkOptions](interfaces/networkoptions.md) +- [TransformableToBuffer](interfaces/transformabletobuffer.md) + +### Type aliases + +- [BufferLike](#bufferlike) +- [PrefixedHexString](#prefixedhexstring) + +### Functions + +- [blockFromRpc](#blockfromrpc) +- [blockHeaderFromRpc](#blockheaderfromrpc) + +--- + +## Type aliases + + + +### BufferLike + +**Ƭ BufferLike**: _`Buffer` \| [TransformableToBuffer](interfaces/transformabletobuffer.md) \| [PrefixedHexString](#prefixedhexstring) \| `number`_ + +_Defined in [types.ts:41](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L41)_ + +A Buffer, hex string prefixed with `0x`, Number, or an object with a toBuffer method such as BN. + +--- + + + +### PrefixedHexString + +**Ƭ PrefixedHexString**: _`string`_ + +_Defined in [types.ts:36](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L36)_ + +A hex string prefixed with `0x`. + +--- + +## Functions + + + +### blockFromRpc + +▸ **blockFromRpc**(blockParams: _`any`_, uncles?: _`any`[]_, networkOptions?: _[NetworkOptions](interfaces/networkoptions.md)_): [Block](classes/block.md) + +_Defined in [from-rpc.ts:14](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/from-rpc.ts#L14)_ + +Creates a new block object from Ethereum JSON RPC. + +**Parameters:** + +| Name | Type | Description | +| ------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------ | +| blockParams | `any` | Ethereum JSON RPC of block (eth_getBlockByNumber) | +| `Optional` uncles | `any`[] | Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) | +| `Optional` networkOptions | [NetworkOptions](interfaces/networkoptions.md) | An object describing the network | + +**Returns:** [Block](classes/block.md) + +--- + + + +### blockHeaderFromRpc + +▸ **blockHeaderFromRpc**(blockParams: _`any`_, networkOptions?: _[NetworkOptions](interfaces/networkoptions.md)_): [BlockHeader](classes/blockheader.md) + +_Defined in [header-from-rpc.ts:11](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header-from-rpc.ts#L11)_ + +Creates a new block header object from Ethereum JSON RPC. + +**Parameters:** + +| Name | Type | Description | +| ------------------------- | ---------------------------------------------- | ------------------------------------------------- | +| blockParams | `any` | Ethereum JSON RPC of block (eth_getBlockByNumber) | +| `Optional` networkOptions | [NetworkOptions](interfaces/networkoptions.md) | An object describing the network | + +**Returns:** [BlockHeader](classes/blockheader.md) + +--- diff --git a/docs/classes/block.md b/docs/classes/block.md new file mode 100644 index 0000000..7aeaa03 --- /dev/null +++ b/docs/classes/block.md @@ -0,0 +1,396 @@ +[ethereumjs-block](../README.md) > [Block](../classes/block.md) + +# Class: Block + +An object that represents the block + +## Hierarchy + +**Block** + +## Index + +### Constructors + +- [constructor](block.md#constructor) + +### Properties + +- [\_common](block.md#_common) +- [header](block.md#header) +- [transactions](block.md#transactions) +- [txTrie](block.md#txtrie) +- [uncleHeaders](block.md#uncleheaders) + +### Accessors + +- [raw](block.md#raw) + +### Methods + +- [\_putTxInTrie](block.md#_puttxintrie) +- [\_validateUncleHeader](block.md#_validateuncleheader) +- [genTxTrie](block.md#gentxtrie) +- [hash](block.md#hash) +- [isGenesis](block.md#isgenesis) +- [serialize](block.md#serialize) +- [setGenesisParams](block.md#setgenesisparams) +- [toJSON](block.md#tojson) +- [validate](block.md#validate) +- [validateTransactions](block.md#validatetransactions) +- [validateTransactionsTrie](block.md#validatetransactionstrie) +- [validateUncles](block.md#validateuncles) +- [validateUnclesHash](block.md#validateuncleshash) + +--- + +## Constructors + + + +### constructor + +⊕ **new Block**(data?: _`Buffer` \| [`Buffer`[], `Buffer`[], `Buffer`[]] \| [BlockData](../interfaces/blockdata.md)_, opts?: _[NetworkOptions](../interfaces/networkoptions.md)_): [Block](block.md) + +_Defined in [block.ts:20](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L20)_ + +Creates a new block object + +**Parameters:** + +| Name | Type | Default value | Description | +| -------------------- | ------------------------------------------------------------------------------------------- | ------------- | -------------------------------------------------------------------------- | +| `Default value` data | `Buffer` \| [`Buffer`[], `Buffer`[], `Buffer`[]] \| [BlockData](../interfaces/blockdata.md) | {} | The block's data. | +| `Default value` opts | [NetworkOptions](../interfaces/networkoptions.md) | {} | The network options for this block, and its header, uncle headers and txs. | + +**Returns:** [Block](block.md) + +--- + +## Properties + + + +### `` \_common + +**● \_common**: _`Common`_ + +_Defined in [block.ts:20](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L20)_ + +--- + + + +### header + +**● header**: _[BlockHeader](blockheader.md)_ + +_Defined in [block.ts:15](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L15)_ + +--- + + + +### transactions + +**● transactions**: _`Transaction`[]_ = [] + +_Defined in [block.ts:16](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L16)_ + +--- + + + +### txTrie + +**● txTrie**: _`any`_ = new Trie() + +_Defined in [block.ts:18](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L18)_ + +--- + + + +### uncleHeaders + +**● uncleHeaders**: _[BlockHeader](blockheader.md)[]_ = [] + +_Defined in [block.ts:17](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L17)_ + +--- + +## Accessors + + + +### raw + +**get raw**(): [`Buffer`[], `Buffer`[], `Buffer`[]] + +_Defined in [block.ts:81](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L81)_ + +**Returns:** [`Buffer`[], `Buffer`[], `Buffer`[]] + +--- + +## Methods + + + +### `` \_putTxInTrie + +▸ **\_putTxInTrie**(txIndex: _`number`_, tx: _`Transaction`_): `Promise`<`void`> + +_Defined in [block.ts:249](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L249)_ + +**Parameters:** + +| Name | Type | +| ------- | ------------- | +| txIndex | `number` | +| tx | `Transaction` | + +**Returns:** `Promise`<`void`> + +--- + + + +### `` \_validateUncleHeader + +▸ **\_validateUncleHeader**(uncleHeader: _[BlockHeader](blockheader.md)_, blockchain: _[Blockchain](../interfaces/blockchain.md)_): `Promise`<`void`> + +_Defined in [block.ts:261](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L261)_ + +**Parameters:** + +| Name | Type | +| ----------- | ----------------------------------------- | +| uncleHeader | [BlockHeader](blockheader.md) | +| blockchain | [Blockchain](../interfaces/blockchain.md) | + +**Returns:** `Promise`<`void`> + +--- + + + +### genTxTrie + +▸ **genTxTrie**(): `Promise`<`void`> + +_Defined in [block.ts:130](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L130)_ + +Generate transaction trie. The tx trie must be generated before the transaction trie can be validated with `validateTransactionTrie` + +**Returns:** `Promise`<`void`> + +--- + + + +### hash + +▸ **hash**(): `Buffer` + +_Defined in [block.ts:88](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L88)_ + +Produces a hash the RLP of the block + +**Returns:** `Buffer` + +--- + + + +### isGenesis + +▸ **isGenesis**(): `boolean` + +_Defined in [block.ts:95](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L95)_ + +Determines if this block is the genesis block + +**Returns:** `boolean` + +--- + + + +### serialize + +▸ **serialize**(): `Buffer` + +▸ **serialize**(rlpEncode: _`true`_): `Buffer` + +▸ **serialize**(rlpEncode: _`false`_): [`Buffer`[], `Buffer`[], `Buffer`[]] + +_Defined in [block.ts:113](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L113)_ + +Produces a serialization of the block. + +**Returns:** `Buffer` + +_Defined in [block.ts:114](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L114)_ + +**Parameters:** + +| Name | Type | +| --------- | ------ | +| rlpEncode | `true` | + +**Returns:** `Buffer` + +_Defined in [block.ts:115](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L115)_ + +**Parameters:** + +| Name | Type | +| --------- | ------- | +| rlpEncode | `false` | + +**Returns:** [`Buffer`[], `Buffer`[], `Buffer`[]] + +--- + + + +### setGenesisParams + +▸ **setGenesisParams**(): `void` + +_Defined in [block.ts:102](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L102)_ + +Turns the block into the canonical genesis block + +**Returns:** `void` + +--- + + + +### toJSON + +▸ **toJSON**(labeled?: _`boolean`_): `undefined` \| `string` \| `any`[] \| `object` + +_Defined in [block.ts:237](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L237)_ + +Returns the block in JSON format + +_**see**_: [ethereumjs-util](https://github.com/ethereumjs/ethereumjs-util/blob/master/docs/index.md#defineproperties) + +**Parameters:** + +| Name | Type | Default value | +| ----------------------- | --------- | ------------- | +| `Default value` labeled | `boolean` | false | + +**Returns:** `undefined` \| `string` \| `any`[] \| `object` + +--- + + + +### validate + +▸ **validate**(blockChain: _[Blockchain](../interfaces/blockchain.md)_): `Promise`<`void`> + +_Defined in [block.ts:179](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L179)_ + +Validates the entire block, throwing if invalid. + +**Parameters:** + +| Name | Type | Description | +| ---------- | ----------------------------------------- | -------------------------------------------------- | +| blockChain | [Blockchain](../interfaces/blockchain.md) | the blockchain that this block wants to be part of | + +**Returns:** `Promise`<`void`> + +--- + + + +### validateTransactions + +▸ **validateTransactions**(): `boolean` + +▸ **validateTransactions**(stringError: _`false`_): `boolean` + +▸ **validateTransactions**(stringError: _`true`_): `string` + +_Defined in [block.ts:154](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L154)_ + +Validates the transactions + +**Returns:** `boolean` + +_Defined in [block.ts:155](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L155)_ + +**Parameters:** + +| Name | Type | +| ----------- | ------- | +| stringError | `false` | + +**Returns:** `boolean` + +_Defined in [block.ts:156](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L156)_ + +**Parameters:** + +| Name | Type | +| ----------- | ------ | +| stringError | `true` | + +**Returns:** `string` + +--- + + + +### validateTransactionsTrie + +▸ **validateTransactionsTrie**(): `boolean` + +_Defined in [block.ts:140](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L140)_ + +Validates the transaction trie + +**Returns:** `boolean` + +--- + + + +### validateUncles + +▸ **validateUncles**(blockchain: _[Blockchain](../interfaces/blockchain.md)_): `Promise`<`undefined` \| `void`[]> + +_Defined in [block.ts:214](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L214)_ + +Validates the uncles that are in the block, if any. This method throws if they are invalid. + +**Parameters:** + +| Name | Type | +| ---------- | ----------------------------------------- | +| blockchain | [Blockchain](../interfaces/blockchain.md) | + +**Returns:** `Promise`<`undefined` \| `void`[]> + +--- + + + +### validateUnclesHash + +▸ **validateUnclesHash**(): `boolean` + +_Defined in [block.ts:203](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L203)_ + +Validates the uncle's hash + +**Returns:** `boolean` + +--- diff --git a/docs/classes/blockheader.md b/docs/classes/blockheader.md new file mode 100644 index 0000000..e498641 --- /dev/null +++ b/docs/classes/blockheader.md @@ -0,0 +1,438 @@ +[ethereumjs-block](../README.md) > [BlockHeader](../classes/blockheader.md) + +# Class: BlockHeader + +An object that represents the block header + +## Hierarchy + +**BlockHeader** + +## Index + +### Constructors + +- [constructor](blockheader.md#constructor) + +### Properties + +- [\_common](blockheader.md#_common) +- [bloom](blockheader.md#bloom) +- [coinbase](blockheader.md#coinbase) +- [difficulty](blockheader.md#difficulty) +- [extraData](blockheader.md#extradata) +- [gasLimit](blockheader.md#gaslimit) +- [gasUsed](blockheader.md#gasused) +- [mixHash](blockheader.md#mixhash) +- [nonce](blockheader.md#nonce) +- [number](blockheader.md#number) +- [parentHash](blockheader.md#parenthash) +- [raw](blockheader.md#raw) +- [receiptTrie](blockheader.md#receipttrie) +- [stateRoot](blockheader.md#stateroot) +- [timestamp](blockheader.md#timestamp) +- [transactionsTrie](blockheader.md#transactionstrie) +- [uncleHash](blockheader.md#unclehash) + +### Methods + +- [\_getBlockByHash](blockheader.md#_getblockbyhash) +- [\_getHardfork](blockheader.md#_gethardfork) +- [canonicalDifficulty](blockheader.md#canonicaldifficulty) +- [hash](blockheader.md#hash) +- [isGenesis](blockheader.md#isgenesis) +- [serialize](blockheader.md#serialize) +- [setGenesisParams](blockheader.md#setgenesisparams) +- [toJSON](blockheader.md#tojson) +- [validate](blockheader.md#validate) +- [validateDifficulty](blockheader.md#validatedifficulty) +- [validateGasLimit](blockheader.md#validategaslimit) + +--- + +## Constructors + + + +### constructor + +⊕ **new BlockHeader**(data?: _`Buffer` \| [PrefixedHexString](../#prefixedhexstring) \| [BufferLike](../#bufferlike)[] \| [BlockHeaderData](../interfaces/blockheaderdata.md)_, opts?: _[NetworkOptions](../interfaces/networkoptions.md)_): [BlockHeader](blockheader.md) + +_Defined in [header.ts:29](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L29)_ + +Creates a new block header. + +**Parameters:** + +| Name | Type | Default value | Description | +| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------------------------------------------------------------------------- | +| `Default value` data | `Buffer` \| [PrefixedHexString](../#prefixedhexstring) \| [BufferLike](../#bufferlike)[] \| [BlockHeaderData](../interfaces/blockheaderdata.md) | {} | The data of the block header. | +| `Default value` opts | [NetworkOptions](../interfaces/networkoptions.md) | {} | The network options for this block, and its header, uncle headers and txs. | + +**Returns:** [BlockHeader](blockheader.md) + +--- + +## Properties + + + +### `` \_common + +**● \_common**: _`Common`_ + +_Defined in [header.ts:29](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L29)_ + +--- + + + +### bloom + +**● bloom**: _`Buffer`_ + +_Defined in [header.ts:19](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L19)_ + +--- + + + +### coinbase + +**● coinbase**: _`Buffer`_ + +_Defined in [header.ts:15](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L15)_ + +--- + + + +### difficulty + +**● difficulty**: _`Buffer`_ + +_Defined in [header.ts:20](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L20)_ + +--- + + + +### extraData + +**● extraData**: _`Buffer`_ + +_Defined in [header.ts:25](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L25)_ + +--- + + + +### gasLimit + +**● gasLimit**: _`Buffer`_ + +_Defined in [header.ts:22](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L22)_ + +--- + + + +### gasUsed + +**● gasUsed**: _`Buffer`_ + +_Defined in [header.ts:23](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L23)_ + +--- + + + +### mixHash + +**● mixHash**: _`Buffer`_ + +_Defined in [header.ts:26](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L26)_ + +--- + + + +### nonce + +**● nonce**: _`Buffer`_ + +_Defined in [header.ts:27](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L27)_ + +--- + + + +### number + +**● number**: _`Buffer`_ + +_Defined in [header.ts:21](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L21)_ + +--- + + + +### parentHash + +**● parentHash**: _`Buffer`_ + +_Defined in [header.ts:13](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L13)_ + +--- + + + +### raw + +**● raw**: _`Buffer`[]_ + +_Defined in [header.ts:12](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L12)_ + +--- + + + +### receiptTrie + +**● receiptTrie**: _`Buffer`_ + +_Defined in [header.ts:18](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L18)_ + +--- + + + +### stateRoot + +**● stateRoot**: _`Buffer`_ + +_Defined in [header.ts:16](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L16)_ + +--- + + + +### timestamp + +**● timestamp**: _`Buffer`_ + +_Defined in [header.ts:24](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L24)_ + +--- + + + +### transactionsTrie + +**● transactionsTrie**: _`Buffer`_ + +_Defined in [header.ts:17](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L17)_ + +--- + + + +### uncleHash + +**● uncleHash**: _`Buffer`_ + +_Defined in [header.ts:14](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L14)_ + +--- + +## Methods + + + +### `` \_getBlockByHash + +▸ **\_getBlockByHash**(blockchain: _[Blockchain](../interfaces/blockchain.md)_, hash: _`Buffer`_): `Promise`<[Block](block.md) \| `undefined`> + +_Defined in [header.ts:347](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L347)_ + +**Parameters:** + +| Name | Type | +| ---------- | ----------------------------------------- | +| blockchain | [Blockchain](../interfaces/blockchain.md) | +| hash | `Buffer` | + +**Returns:** `Promise`<[Block](block.md) \| `undefined`> + +--- + + + +### `` \_getHardfork + +▸ **\_getHardfork**(): `string` + +_Defined in [header.ts:339](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L339)_ + +**Returns:** `string` + +--- + + + +### canonicalDifficulty + +▸ **canonicalDifficulty**(parentBlock: _[Block](block.md)_): `BN` + +_Defined in [header.ts:134](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L134)_ + +Returns the canonical difficulty for this block. + +**Parameters:** + +| Name | Type | Description | +| ----------- | ----------------- | --------------------------------------- | +| parentBlock | [Block](block.md) | the parent \`Block\` of the this header | + +**Returns:** `BN` + +--- + + + +### hash + +▸ **hash**(): `Buffer` + +_Defined in [header.ts:297](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L297)_ + +Returns the hash of the block header. + +**Returns:** `Buffer` + +--- + + + +### isGenesis + +▸ **isGenesis**(): `boolean` + +_Defined in [header.ts:304](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L304)_ + +Checks if the block header is a genesis header. + +**Returns:** `boolean` + +--- + + + +### serialize + +▸ **serialize**(): `Buffer` + +_Defined in [header.ts:324](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L324)_ + +Returns the rlp encoding of the block header + +**Returns:** `Buffer` + +--- + + + +### setGenesisParams + +▸ **setGenesisParams**(): `void` + +_Defined in [header.ts:311](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L311)_ + +Turns the header into the canonical genesis block header. + +**Returns:** `void` + +--- + + + +### toJSON + +▸ **toJSON**(\_labels?: _`boolean`_): `object` \| `string`[] + +_Defined in [header.ts:334](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L334)_ + +Returns the block header in JSON format + +_**see**_: [ethereumjs-util](https://github.com/ethereumjs/ethereumjs-util/blob/master/docs/index.md#defineproperties) + +**Parameters:** + +| Name | Type | Default value | +| ------------------------ | --------- | ------------- | +| `Default value` \_labels | `boolean` | false | + +**Returns:** `object` \| `string`[] + +--- + + + +### validate + +▸ **validate**(blockchain: _[Blockchain](../interfaces/blockchain.md)_, height?: _`BN`_): `Promise`<`void`> + +_Defined in [header.ts:249](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L249)_ + +Validates the entire block header, throwing if invalid. + +**Parameters:** + +| Name | Type | Description | +| ----------------- | ----------------------------------------- | -------------------------------------------------------------------------------- | +| blockchain | [Blockchain](../interfaces/blockchain.md) | the blockchain that this block is validating against | +| `Optional` height | `BN` | If this is an uncle header, this is the height of the block that is including it | + +**Returns:** `Promise`<`void`> + +--- + + + +### validateDifficulty + +▸ **validateDifficulty**(parentBlock: _[Block](block.md)_): `boolean` + +_Defined in [header.ts:215](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L215)_ + +Checks that the block's `difficulty` matches the canonical difficulty. + +**Parameters:** + +| Name | Type | Description | +| ----------- | ----------------- | ------------------- | +| parentBlock | [Block](block.md) | this block's parent | + +**Returns:** `boolean` + +--- + + + +### validateGasLimit + +▸ **validateGasLimit**(parentBlock: _[Block](block.md)_): `boolean` + +_Defined in [header.ts:225](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L225)_ + +Validates the gasLimit. + +**Parameters:** + +| Name | Type | Description | +| ----------- | ----------------- | ------------------- | +| parentBlock | [Block](block.md) | this block's parent | + +**Returns:** `boolean` + +--- diff --git a/docs/fromRpc.md b/docs/fromRpc.md deleted file mode 100644 index 8c58320..0000000 --- a/docs/fromRpc.md +++ /dev/null @@ -1,11 +0,0 @@ - - -# blockFromRpc - -Creates a new block object from Ethereum JSON RPC. - -**Parameters** - -- `blockParams` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Ethereum JSON RPC of block (eth_getBlockByNumber) -- `Optional` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)>** list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) -- `uncles` diff --git a/docs/index.md b/docs/index.md deleted file mode 100644 index ff40076..0000000 --- a/docs/index.md +++ /dev/null @@ -1,187 +0,0 @@ - - -# Block - -Creates a new block object - -**Parameters** - -- `data` **([Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) \| [Buffer](https://nodejs.org/api/buffer.html) \| [Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object))** -- `opts` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)** Options - - `opts.chain` **([String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number))** The chain for the block [default: 'mainnet'] - - `opts.hardfork` **[String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Hardfork for the block [default: null, block number-based behaviour] - - `opts.common` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Alternatively pass a Common instance (ethereumjs-common) instead of setting chain/hardfork directly - -**Properties** - -- `header` **Header** the block's header -- `uncleList` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<Header>** an array of uncle headers -- `raw` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Buffer](https://nodejs.org/api/buffer.html)>** an array of buffers containing the raw blocks. - -## hash - -Produces a hash the RLP of the block - -## isGenisis - -Determines if a given block is the genesis block - -Returns **any** Boolean - -## setGenesisParams - -turns the block into the canonical genesis block - -## serialize - -Produces a serialization of the block. - -**Parameters** - -- `rlpEncode` **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** whether to rlp encode the block or not - -## genTxTrie - -Generate transaction trie. The tx trie must be generated before the transaction trie can -be validated with `validateTransactionTrie` - -**Parameters** - -- `cb` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback - -## validateTransactionTrie - -Validates the transaction trie - -Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** - -## validateTransactions - -Validates the transactions - -**Parameters** - -- `stringError` **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)?** whether to return a string with a dscription of why the validation failed or return a Bloolean (optional, default `false`) - -Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** - -## validate - -Validates the entire block. Returns a string to the callback if block is invalid - -**Parameters** - -- `blockChain` **BlockChain** the blockchain that this block wants to be part of -- `cb` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback which is given a `String` if the block is not valid - -## validateUncleHash - -Validates the uncle's hash - -Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** - -## validateUncles - -Validates the uncles that are in the block if any. Returns a string to the callback if uncles are invalid - -**Parameters** - -- `blockChaina` **Blockchain** an instance of the Blockchain -- `cb` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback -- `blockChain` - -## toJSON - -Converts the block toJSON - -**Parameters** - -- `labeled` **Bool** whether to create an labeled object or an array - -Returns **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** - -# BlockHeader - -An object that repersents the block header - -**Parameters** - -- `data` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)** raw data, deserialized -- `opts` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)** Options - - `opts.chain` **([String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number))** The chain for the block header [default: 'mainnet'] - - `opts.hardfork` **[String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** Hardfork for the block header [default: null, block number-based behaviour] - - `opts.common` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** Alternatively pass a Common instance instead of setting chain/hardfork directly - -**Properties** - -- `parentHash` **[Buffer](https://nodejs.org/api/buffer.html)** the blocks' parent's hash -- `uncleHash` **[Buffer](https://nodejs.org/api/buffer.html)** sha3(rlp_encode(uncle_list)) -- `coinbase` **[Buffer](https://nodejs.org/api/buffer.html)** the miner address -- `stateRoot` **[Buffer](https://nodejs.org/api/buffer.html)** The root of a Merkle Patricia tree -- `transactionTrie` **[Buffer](https://nodejs.org/api/buffer.html)** the root of a Trie containing the transactions -- `receiptTrie` **[Buffer](https://nodejs.org/api/buffer.html)** the root of a Trie containing the transaction Reciept -- `bloom` **[Buffer](https://nodejs.org/api/buffer.html)** -- `difficulty` **[Buffer](https://nodejs.org/api/buffer.html)** -- `number` **[Buffer](https://nodejs.org/api/buffer.html)** the block's height -- `gasLimit` **[Buffer](https://nodejs.org/api/buffer.html)** -- `gasUsed` **[Buffer](https://nodejs.org/api/buffer.html)** -- `timestamp` **[Buffer](https://nodejs.org/api/buffer.html)** -- `extraData` **[Buffer](https://nodejs.org/api/buffer.html)** -- `raw` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Buffer](https://nodejs.org/api/buffer.html)>** an array of buffers containing the raw blocks. - -## canonicalDifficulty - -Returns the canoncical difficulty of the block - -**Parameters** - -- `parentBlock` **[Block](#block)** the parent `Block` of the this header - -Returns **BN** - -## validateDifficulty - -checks that the block's `difficuly` matches the canonical difficulty - -**Parameters** - -- `parentBlock` **[Block](#block)** this block's parent - -Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** - -## validateGasLimit - -Validates the gasLimit - -**Parameters** - -- `parentBlock` **[Block](#block)** this block's parent - -Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** - -## validate - -Validates the entire block header - -**Parameters** - -- `blockChain` **Blockchain** the blockchain that this block is validating against -- `height` **Bignum?** if this is an uncle header, this is the height of the block that is including it -- `cb` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** the callback function. The callback is given an `error` if the block is invalid -- `blockchain` - -## hash - -Returns the sha3 hash of the blockheader - -Returns **[Buffer](https://nodejs.org/api/buffer.html)** - -## isGenesis - -checks if the blockheader is a genesis header - -Returns **[Boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** - -## setGenesisParams - -turns the header into the canonical genesis block header diff --git a/docs/interfaces/blockchain.md b/docs/interfaces/blockchain.md new file mode 100644 index 0000000..a2332a9 --- /dev/null +++ b/docs/interfaces/blockchain.md @@ -0,0 +1,36 @@ +[ethereumjs-block](../README.md) > [Blockchain](../interfaces/blockchain.md) + +# Interface: Blockchain + +## Hierarchy + +**Blockchain** + +## Index + +### Methods + +- [getBlock](blockchain.md#getblock) + +--- + +## Methods + + + +### getBlock + +▸ **getBlock**(hash: _`Buffer`_, callback: _`function`_): `void` + +_Defined in [types.ts:74](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L74)_ + +**Parameters:** + +| Name | Type | +| -------- | ---------- | +| hash | `Buffer` | +| callback | `function` | + +**Returns:** `void` + +--- diff --git a/docs/interfaces/blockdata.md b/docs/interfaces/blockdata.md new file mode 100644 index 0000000..a0830e4 --- /dev/null +++ b/docs/interfaces/blockdata.md @@ -0,0 +1,51 @@ +[ethereumjs-block](../README.md) > [BlockData](../interfaces/blockdata.md) + +# Interface: BlockData + +A block's data. + +## Hierarchy + +**BlockData** + +## Index + +### Properties + +- [header](blockdata.md#header) +- [transactions](blockdata.md#transactions) +- [uncleHeaders](blockdata.md#uncleheaders) + +--- + +## Properties + + + +### `` header + +**● header**: _`Buffer` \| [PrefixedHexString](../#prefixedhexstring) \| [BufferLike](../#bufferlike)[] \| [BlockHeaderData](blockheaderdata.md)_ + +_Defined in [types.ts:68](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L68)_ + +--- + + + +### `` transactions + +**● transactions**: _`Array`<`Buffer` \| [PrefixedHexString](../#prefixedhexstring) \| [BufferLike](../#bufferlike)[] \| `TxData`>_ + +_Defined in [types.ts:69](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L69)_ + +--- + + + +### `` uncleHeaders + +**● uncleHeaders**: _`Array`<`Buffer` \| [PrefixedHexString](../#prefixedhexstring) \| [BufferLike](../#bufferlike)[] \| [BlockHeaderData](blockheaderdata.md)>_ + +_Defined in [types.ts:70](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L70)_ + +--- diff --git a/docs/interfaces/blockheaderdata.md b/docs/interfaces/blockheaderdata.md new file mode 100644 index 0000000..623a485 --- /dev/null +++ b/docs/interfaces/blockheaderdata.md @@ -0,0 +1,183 @@ +[ethereumjs-block](../README.md) > [BlockHeaderData](../interfaces/blockheaderdata.md) + +# Interface: BlockHeaderData + +A block header's data. + +## Hierarchy + +**BlockHeaderData** + +## Index + +### Properties + +- [bloom](blockheaderdata.md#bloom) +- [coinbase](blockheaderdata.md#coinbase) +- [difficulty](blockheaderdata.md#difficulty) +- [extraData](blockheaderdata.md#extradata) +- [gasLimit](blockheaderdata.md#gaslimit) +- [gasUsed](blockheaderdata.md#gasused) +- [mixHash](blockheaderdata.md#mixhash) +- [nonce](blockheaderdata.md#nonce) +- [number](blockheaderdata.md#number) +- [parentHash](blockheaderdata.md#parenthash) +- [receiptTrie](blockheaderdata.md#receipttrie) +- [stateRoot](blockheaderdata.md#stateroot) +- [timestamp](blockheaderdata.md#timestamp) +- [transactionsTrie](blockheaderdata.md#transactionstrie) +- [uncleHash](blockheaderdata.md#unclehash) + +--- + +## Properties + + + +### `` bloom + +**● bloom**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:53](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L53)_ + +--- + + + +### `` coinbase + +**● coinbase**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:49](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L49)_ + +--- + + + +### `` difficulty + +**● difficulty**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:54](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L54)_ + +--- + + + +### `` extraData + +**● extraData**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:59](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L59)_ + +--- + + + +### `` gasLimit + +**● gasLimit**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:56](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L56)_ + +--- + + + +### `` gasUsed + +**● gasUsed**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:57](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L57)_ + +--- + + + +### `` mixHash + +**● mixHash**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:60](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L60)_ + +--- + + + +### `` nonce + +**● nonce**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:61](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L61)_ + +--- + + + +### `` number + +**● number**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:55](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L55)_ + +--- + + + +### `` parentHash + +**● parentHash**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:47](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L47)_ + +--- + + + +### `` receiptTrie + +**● receiptTrie**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:52](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L52)_ + +--- + + + +### `` stateRoot + +**● stateRoot**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:50](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L50)_ + +--- + + + +### `` timestamp + +**● timestamp**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:58](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L58)_ + +--- + + + +### `` transactionsTrie + +**● transactionsTrie**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:51](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L51)_ + +--- + + + +### `` uncleHash + +**● uncleHash**: _[BufferLike](../#bufferlike)_ + +_Defined in [types.ts:48](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L48)_ + +--- diff --git a/docs/interfaces/networkoptions.md b/docs/interfaces/networkoptions.md new file mode 100644 index 0000000..d690212 --- /dev/null +++ b/docs/interfaces/networkoptions.md @@ -0,0 +1,57 @@ +[ethereumjs-block](../README.md) > [NetworkOptions](../interfaces/networkoptions.md) + +# Interface: NetworkOptions + +An object to set to which network blocks and their headers belong. This could be specified using a Common object, or `chain` and `hardfork`. Defaults to mainnet without specifying a hardfork. + +## Hierarchy + +**NetworkOptions** + +## Index + +### Properties + +- [chain](networkoptions.md#chain) +- [common](networkoptions.md#common) +- [hardfork](networkoptions.md#hardfork) + +--- + +## Properties + + + +### `` chain + +**● chain**: _`number` \| `string`_ + +_Defined in [types.ts:18](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L18)_ + +The chain of the block/block header, default: 'mainnet' + +--- + + + +### `` common + +**● common**: _`Common`_ + +_Defined in [types.ts:13](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L13)_ + +A Common object defining the chain and the hardfork a block/block header belongs to. + +--- + + + +### `` hardfork + +**● hardfork**: _`undefined` \| `string`_ + +_Defined in [types.ts:23](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L23)_ + +The hardfork of the block/block header, default: 'petersburg' + +--- diff --git a/docs/interfaces/transformabletobuffer.md b/docs/interfaces/transformabletobuffer.md new file mode 100644 index 0000000..1075351 --- /dev/null +++ b/docs/interfaces/transformabletobuffer.md @@ -0,0 +1,31 @@ +[ethereumjs-block](../README.md) > [TransformableToBuffer](../interfaces/transformabletobuffer.md) + +# Interface: TransformableToBuffer + +Any object that can be transformed into a `Buffer` + +## Hierarchy + +**TransformableToBuffer** + +## Index + +### Methods + +- [toBuffer](transformabletobuffer.md#tobuffer) + +--- + +## Methods + + + +### toBuffer + +▸ **toBuffer**(): `Buffer` + +_Defined in [types.ts:30](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L30)_ + +**Returns:** `Buffer` + +--- diff --git a/src/block.ts b/src/block.ts index 510c261..7ebd923 100644 --- a/src/block.ts +++ b/src/block.ts @@ -9,16 +9,7 @@ import { Blockchain, BlockData, NetworkOptions } from './types' const Trie = require('merkle-patricia-tree') /** - * Creates a new block object - * @constructor the raw serialized or the deserialized block. - * @param {Array|Buffer|Object} data - * @param {Array} opts Options - * @param {String|Number} opts.chain The chain for the block [default: 'mainnet'] - * @param {String} opts.hardfork Hardfork for the block [default: null, block number-based behaviour] - * @param {Object} opts.common Alternatively pass a Common instance (ethereumjs-common) instead of setting chain/hardfork directly - * @prop {Header} header the block's header - * @prop {Array.
} uncleList an array of uncle headers - * @prop {Array.} raw an array of buffers containing the raw blocks. + * An object that represents the block */ export class Block { public readonly header: BlockHeader @@ -28,6 +19,13 @@ export class Block { private readonly _common: Common + /** + * Creates a new block object + * + * + * @param data - The block's data. + * @param opts - The network options for this block, and its header, uncle headers and txs. + */ constructor( data: Buffer | [Buffer[], Buffer[], Buffer[]] | BlockData = {}, opts: NetworkOptions = {}, @@ -80,37 +78,37 @@ export class Block { } } - get raw() { + get raw(): [Buffer[], Buffer[], Buffer[]] { return this.serialize(false) } /** * Produces a hash the RLP of the block - * @method hash */ - hash() { + hash(): Buffer { return this.header.hash() } /** - * Determines if a given block is the genesis block - * @method isGenisis - * @return Boolean + * Determines if this block is the genesis block */ - isGenesis() { + isGenesis(): boolean { return this.header.isGenesis() } /** - * turns the block into the canonical genesis block - * @method setGenesisParams + * Turns the block into the canonical genesis block */ - setGenesisParams() { + setGenesisParams(): void { this.header.setGenesisParams() } /** * Produces a serialization of the block. + * + * @param rlpEncode - If `true`, the returned object is the RLP encoded data as seen by the + * Ethereum wire protocol. If `true`, a tuple with the raw data of the header, the txs and the + * uncle headers is returned. */ serialize(): Buffer serialize(rlpEncode: true): Buffer @@ -129,29 +127,15 @@ export class Block { * Generate transaction trie. The tx trie must be generated before the transaction trie can * be validated with `validateTransactionTrie` */ - async genTxTrie() { + async genTxTrie(): Promise { for (let i = 0; i < this.transactions.length; i++) { const tx = this.transactions[i] await this._putTxInTrie(i, tx) } } - private async _putTxInTrie(txIndex: number, tx: Transaction) { - await new Promise((resolve, reject) => { - this.txTrie.put(rlp.encode(txIndex), tx.serialize(), (err: any) => { - if (err) { - reject(err) - } else { - resolve() - } - }) - }) - } - /** * Validates the transaction trie - * @method validateTransactionTrie - * @return {Boolean} */ validateTransactionsTrie(): boolean { const txT = this.header.transactionsTrie.toString('hex') @@ -164,6 +148,8 @@ export class Block { /** * Validates the transactions + * + * @param stringError - If `true`, a string with the indices of the invalid txs is returned. */ validateTransactions(): boolean validateTransactions(stringError: false): boolean @@ -186,11 +172,11 @@ export class Block { } /** - * Validates the entire block. Returns a string to the callback if block is invalid - * @method validate - * @param blockChain the blockchain that this block wants to be part of + * Validates the entire block, throwing if invalid. + * + * @param blockChain - the blockchain that this block wants to be part of */ - async validate(blockChain: Blockchain) { + async validate(blockChain: Blockchain): Promise { await Promise.all([ this.validateUncles(blockChain), this.genTxTrie(), @@ -221,10 +207,9 @@ export class Block { } /** - * Validates the uncles that are in the block if any. Returns a string to the callback if uncles are invalid - * @method validateUncles - * @param {Blockchain} blockChain an instance of the Blockchain - * @param {Function} cb the callback + * Validates the uncles that are in the block, if any. This method throws if they are invalid. + * + * @param blockChain - the blockchain that this block wants to be part of */ async validateUncles(blockchain: Blockchain) { if (this.isGenesis()) { @@ -246,6 +231,7 @@ export class Block { /** * Returns the block in JSON format + * * @see {@link https://github.com/ethereumjs/ethereumjs-util/blob/master/docs/index.md#defineproperties|ethereumjs-util} */ toJSON(labeled: boolean = false) { @@ -260,6 +246,18 @@ export class Block { } } + private async _putTxInTrie(txIndex: number, tx: Transaction) { + await new Promise((resolve, reject) => { + this.txTrie.put(rlp.encode(txIndex), tx.serialize(), (err: any) => { + if (err) { + reject(err) + } else { + resolve() + } + }) + }) + } + private _validateUncleHeader(uncleHeader: BlockHeader, blockchain: Blockchain) { // TODO: Validate that the uncle header hasn't been included in the blockchain yet. // This is not possible in ethereumjs-blockchain since this PR was merged: diff --git a/src/from-rpc.ts b/src/from-rpc.ts index ee1146b..5b6eba4 100644 --- a/src/from-rpc.ts +++ b/src/from-rpc.ts @@ -6,6 +6,7 @@ import blockHeaderFromRpc from './header-from-rpc' /** * Creates a new block object from Ethereum JSON RPC. + * * @param blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) * @param uncles - Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) * @param networkOptions - An object describing the network diff --git a/src/header-from-rpc.ts b/src/header-from-rpc.ts index 6923307..4433172 100644 --- a/src/header-from-rpc.ts +++ b/src/header-from-rpc.ts @@ -4,6 +4,7 @@ import { NetworkOptions } from './types' /** * Creates a new block header object from Ethereum JSON RPC. + * * @param blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) * @param networkOptions - An object describing the network */ diff --git a/src/header.ts b/src/header.ts index 0100a32..057f4f6 100644 --- a/src/header.ts +++ b/src/header.ts @@ -6,27 +6,7 @@ import { Buffer } from 'buffer' import { Block } from './block' /** - * An object that repersents the block header - * @constructor - * @param {Array} data raw data, deserialized - * @param {Array} opts Options - * @param {String|Number} opts.chain The chain for the block header [default: 'mainnet'] - * @param {String} opts.hardfork Hardfork for the block header [default: null, block number-based behaviour] - * @param {Object} opts.common Alternatively pass a Common instance instead of setting chain/hardfork directly - * @prop {Buffer} parentHash the blocks' parent's hash - * @prop {Buffer} uncleHash sha3(rlp_encode(uncle_list)) - * @prop {Buffer} coinbase the miner address - * @prop {Buffer} stateRoot The root of a Merkle Patricia tree - * @prop {Buffer} transactionTrie the root of a Trie containing the transactions - * @prop {Buffer} receiptTrie the root of a Trie containing the transaction Reciept - * @prop {Buffer} bloom - * @prop {Buffer} difficulty - * @prop {Buffer} number the block's height - * @prop {Buffer} gasLimit - * @prop {Buffer} gasUsed - * @prop {Buffer} timestamp - * @prop {Buffer} extraData - * @prop {Array.} raw an array of buffers containing the raw blocks. + * An object that represents the block header */ export class BlockHeader { public raw!: Buffer[] @@ -48,6 +28,11 @@ export class BlockHeader { private readonly _common: Common + /** + * Creates a new block header. + * @param data - The data of the block header. + * @param opts - The network options for this block, and its header, uncle headers and txs. + */ constructor( data: Buffer | PrefixedHexString | BufferLike[] | BlockHeaderData = {}, opts: NetworkOptions = {}, @@ -142,10 +127,9 @@ export class BlockHeader { } /** - * Returns the canoncical difficulty of the block - * @method canonicalDifficulty - * @param {Block} parentBlock the parent `Block` of the this header - * @return {BN} + * Returns the canonical difficulty for this block. + * + * @param parentBlock - the parent `Block` of the this header */ canonicalDifficulty(parentBlock: Block): BN { const hardfork = this._getHardfork() @@ -224,10 +208,9 @@ export class BlockHeader { } /** - * checks that the block's `difficuly` matches the canonical difficulty - * @method validateDifficulty - * @param {Block} parentBlock this block's parent - * @return {Boolean} + * Checks that the block's `difficulty` matches the canonical difficulty. + * + * @param parentBlock - this block's parent */ validateDifficulty(parentBlock: Block): boolean { const dif = this.canonicalDifficulty(parentBlock) @@ -235,10 +218,9 @@ export class BlockHeader { } /** - * Validates the gasLimit - * @method validateGasLimit - * @param {Block} parentBlock this block's parent - * @returns {Boolean} + * Validates the gasLimit. + * + * @param parentBlock - this block's parent */ validateGasLimit(parentBlock: Block): boolean { const pGasLimit = new BN(parentBlock.header.gasLimit) @@ -259,10 +241,10 @@ export class BlockHeader { } /** - * Validates the entire block header - * @method validate - * @param {Blockchain} blockChain the blockchain that this block is validating against - * @param {Bignum} [height] if this is an uncle header, this is the height of the block that is including it + * Validates the entire block header, throwing if invalid. + * + * @param blockchain - the blockchain that this block is validating against + * @param height - If this is an uncle header, this is the height of the block that is including it */ async validate(blockchain: Blockchain, height?: BN): Promise { if (this.isGenesis()) { @@ -310,26 +292,21 @@ export class BlockHeader { } /** - * Returns the sha3 hash of the blockheader - * @method hash - * @return {Buffer} + * Returns the hash of the block header. */ hash(): Buffer { return utils.rlphash(this.raw) } /** - * checks if the blockheader is a genesis header - * @method isGenesis - * @return {Boolean} + * Checks if the block header is a genesis header. */ isGenesis(): boolean { return this.number.length === 0 } /** - * turns the header into the canonical genesis block header - * @method setGenesisParams + * Turns the header into the canonical genesis block header. */ setGenesisParams(): void { this.timestamp = this._common.genesis().timestamp @@ -351,6 +328,7 @@ export class BlockHeader { /** * Returns the block header in JSON format + * * @see {@link https://github.com/ethereumjs/ethereumjs-util/blob/master/docs/index.md#defineproperties|ethereumjs-util} */ toJSON(_labels: boolean = false): { [key: string]: string } | string[] { diff --git a/src/types.ts b/src/types.ts index 724909a..7856f62 100644 --- a/src/types.ts +++ b/src/types.ts @@ -3,8 +3,8 @@ import { TxData } from 'ethereumjs-tx' import { Block } from './block' /** - * An object to set which network blocks and their headers belong to. This could be specified using - * a Common object, or `chain` and `hardfork`. Defaults to mainnet. + * An object to set to which network blocks and their headers belong. This could be specified using + * a Common object, or `chain` and `hardfork`. Defaults to mainnet without specifying a hardfork. */ export interface NetworkOptions { /** From 8bcfdd72d2ccdd73bb014644c3bab957a16bc072 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Wed, 31 Jul 2019 15:34:32 -0300 Subject: [PATCH 14/25] Remove node 11 from travis config --- .travis.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 025e381..3169e69 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,7 +2,6 @@ language: node_js node_js: - "8" - "10" - - "11" - "12" addons: firefox: latest @@ -37,9 +36,6 @@ matrix: - os: linux node_js: "10" env: CXX=g++-4.8 TEST_SUITE=test:node - - os: linux - node_js: "11" - env: CXX=g++-4.8 TEST_SUITE=test:node - os: linux node_js: "12" env: CXX=g++-4.8 TEST_SUITE=test:node From 8e898fd872ecd8489470b1a0bc04ad3504b28f3c Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Wed, 31 Jul 2019 15:34:49 -0300 Subject: [PATCH 15/25] Update xvfb config in .travis.yml --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 3169e69..fca2cd5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,8 +10,8 @@ addons: - ubuntu-toolchain-r-test packages: - g++-4.8 -before_install: - - sh -e /etc/init.d/xvfb start +services: + - xvfb env: global: - CXX=g++-4.8 From e75f9eb7c952e8204f82cb979d0d85ba1f101d90 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Wed, 31 Jul 2019 15:37:33 -0300 Subject: [PATCH 16/25] Rollback version bump --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 4815b21..dc039e5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ethereumjs-block", - "version": "3.0.0", + "version": "2.2.0", "description": "Provides Block serialization and help functions", "main": "dist/index.js", "types": "dist/index.d.ts", From ae5157129e346f3810836a03d1c0648c145c2606 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Wed, 31 Jul 2019 15:38:09 -0300 Subject: [PATCH 17/25] Run browser tests on travis --- .travis.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.travis.yml b/.travis.yml index fca2cd5..9383018 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,6 +27,9 @@ matrix: - os: linux node_js: "8" env: CXX=g++-4.8 TEST_SUITE=lint + - os: linux + node_js: "8" + env: CXX=g++-4.8 TEST_SUITE=test:browser - os: linux node_js: "8" env: CXX=g++-4.8 TEST_SUITE=test:node From 58f8ada511453bbe912610819a285e9d4267b302 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Wed, 31 Jul 2019 15:38:42 -0300 Subject: [PATCH 18/25] Remove blank line --- src/block.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/block.ts b/src/block.ts index 7ebd923..666eed4 100644 --- a/src/block.ts +++ b/src/block.ts @@ -22,7 +22,6 @@ export class Block { /** * Creates a new block object * - * * @param data - The block's data. * @param opts - The network options for this block, and its header, uncle headers and txs. */ From db76a6a5045ac3e5ed2b09f29d9cdc0c48346dfa Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Wed, 31 Jul 2019 15:49:56 -0300 Subject: [PATCH 19/25] Small doc fix --- src/block.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/block.ts b/src/block.ts index 666eed4..98e820e 100644 --- a/src/block.ts +++ b/src/block.ts @@ -106,7 +106,7 @@ export class Block { * Produces a serialization of the block. * * @param rlpEncode - If `true`, the returned object is the RLP encoded data as seen by the - * Ethereum wire protocol. If `true`, a tuple with the raw data of the header, the txs and the + * Ethereum wire protocol. If `false`, a tuple with the raw data of the header, the txs and the * uncle headers is returned. */ serialize(): Buffer From b3ccd5b5486adb00ab0de897d03563aa61e2866f Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Wed, 31 Jul 2019 15:50:22 -0300 Subject: [PATCH 20/25] Specify and simplify a return type --- src/block.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/block.ts b/src/block.ts index 98e820e..1b69a93 100644 --- a/src/block.ts +++ b/src/block.ts @@ -210,7 +210,7 @@ export class Block { * * @param blockChain - the blockchain that this block wants to be part of */ - async validateUncles(blockchain: Blockchain) { + async validateUncles(blockchain: Blockchain): Promise { if (this.isGenesis()) { return } @@ -225,7 +225,7 @@ export class Block { throw new Error('duplicate uncles') } - return Promise.all(this.uncleHeaders.map(async uh => this._validateUncleHeader(uh, blockchain))) + await Promise.all(this.uncleHeaders.map(async uh => this._validateUncleHeader(uh, blockchain))) } /** From eb1cdc878c852d6f6e2f8d7f5579aea515ba7a0c Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Wed, 31 Jul 2019 15:51:45 -0300 Subject: [PATCH 21/25] Pass the Common object to the block headers --- src/block.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/block.ts b/src/block.ts index 1b69a93..d786699 100644 --- a/src/block.ts +++ b/src/block.ts @@ -54,13 +54,11 @@ export class Block { } if (Array.isArray(data)) { - // TODO: Pass the common object - this.header = new BlockHeader(data[0], opts) + this.header = new BlockHeader(data[0], { common: this._common }) rawTransactions = data[1] rawUncleHeaders = data[2] } else { - // TODO: Pass the common object - this.header = new BlockHeader(data.header, opts) + this.header = new BlockHeader(data.header, { common: this._common }) rawTransactions = data.transactions || [] rawUncleHeaders = data.uncleHeaders || [] } From ab9078f52a23eb9f481393374ab5c39d68adc80f Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Wed, 31 Jul 2019 15:57:29 -0300 Subject: [PATCH 22/25] Add TOODs to document the limitations about Common and initializing the txs --- src/block.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/block.ts b/src/block.ts index d786699..8477498 100644 --- a/src/block.ts +++ b/src/block.ts @@ -39,6 +39,8 @@ export class Block { this._common = opts.common } else { const chain = opts.chain ? opts.chain : 'mainnet' + // TODO: Compute the hardfork based on this block's number. It can be implemented right now + // because the block number is not immutable, so the Common can get out of sync. const hardfork = opts.hardfork ? opts.hardfork : null this._common = new Common(chain, hardfork) } @@ -70,6 +72,8 @@ export class Block { // parse transactions for (let i = 0; i < rawTransactions.length; i++) { + // TODO: Pass the common object instead of the options. It can't be implemented right now + // because the hardfork may be `null`. Read the above TODO for more info. const tx = new Transaction(rawTransactions[i], opts) this.transactions.push(tx) } From 1723f9bff8a4ff7af2647a5c7c2c88fa532077c1 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Wed, 31 Jul 2019 16:27:02 -0300 Subject: [PATCH 23/25] Trying new karma reporter --- karma.conf.js | 1 + 1 file changed, 1 insertion(+) diff --git a/karma.conf.js b/karma.conf.js index 45c591e..043a712 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -6,6 +6,7 @@ module.exports = function(config) { preprocessors: { './test-build/**/*.js': ['browserify'] }, + reporters: ["dots"], singleRun: true, detectBrowsers: { enabled: true, From 6adbfaeacb7f41655b5bda9fe372d5d095c4efba Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Wed, 31 Jul 2019 18:34:01 -0300 Subject: [PATCH 24/25] Rename NetworkOptions to ChainOptions --- src/block.ts | 4 ++-- src/from-rpc.ts | 14 +++++++------- src/header-from-rpc.ts | 8 ++++---- src/header.ts | 4 ++-- src/types.ts | 7 ++++--- 5 files changed, 19 insertions(+), 18 deletions(-) diff --git a/src/block.ts b/src/block.ts index 8477498..0944866 100644 --- a/src/block.ts +++ b/src/block.ts @@ -4,7 +4,7 @@ import { BN, rlp } from 'ethereumjs-util' import { Transaction } from 'ethereumjs-tx' import { BlockHeader } from './header' -import { Blockchain, BlockData, NetworkOptions } from './types' +import { Blockchain, BlockData, ChainOptions } from './types' const Trie = require('merkle-patricia-tree') @@ -27,7 +27,7 @@ export class Block { */ constructor( data: Buffer | [Buffer[], Buffer[], Buffer[]] | BlockData = {}, - opts: NetworkOptions = {}, + opts: ChainOptions = {}, ) { if (opts.common) { if (opts.chain !== undefined || opts.hardfork !== undefined) { diff --git a/src/from-rpc.ts b/src/from-rpc.ts index 5b6eba4..0b434b1 100644 --- a/src/from-rpc.ts +++ b/src/from-rpc.ts @@ -1,6 +1,6 @@ import { FakeTransaction } from 'ethereumjs-tx' import * as ethUtil from 'ethereumjs-util' -import { Block, NetworkOptions } from './index' +import { Block, ChainOptions } from './index' import blockHeaderFromRpc from './header-from-rpc' @@ -9,24 +9,24 @@ import blockHeaderFromRpc from './header-from-rpc' * * @param blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) * @param uncles - Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) - * @param networkOptions - An object describing the network + * @param chainOptions - An object describing the blockchain */ export default function blockFromRpc( blockParams: any, uncles?: any[], - networkOptions?: NetworkOptions, + chainOptions?: ChainOptions, ) { uncles = uncles || [] - const header = blockHeaderFromRpc(blockParams, networkOptions) + const header = blockHeaderFromRpc(blockParams, chainOptions) const block = new Block( { header: header.toJSON(true), transactions: [], - uncleHeaders: uncles.map(uh => blockHeaderFromRpc(uh, networkOptions).toJSON(true)), + uncleHeaders: uncles.map(uh => blockHeaderFromRpc(uh, chainOptions).toJSON(true)), }, - networkOptions, + chainOptions, ) if (blockParams.transactions) { @@ -35,7 +35,7 @@ export default function blockFromRpc( // override from address const fromAddress = ethUtil.toBuffer(txParams.from) delete txParams.from - const tx = new FakeTransaction(txParams, networkOptions) + const tx = new FakeTransaction(txParams, chainOptions) tx.from = fromAddress tx.getSenderAddress = function() { return fromAddress diff --git a/src/header-from-rpc.ts b/src/header-from-rpc.ts index 4433172..4756905 100644 --- a/src/header-from-rpc.ts +++ b/src/header-from-rpc.ts @@ -1,14 +1,14 @@ import { BlockHeader } from './header' import * as ethUtil from 'ethereumjs-util' -import { NetworkOptions } from './types' +import { ChainOptions } from './types' /** * Creates a new block header object from Ethereum JSON RPC. * * @param blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) - * @param networkOptions - An object describing the network + * @param chainOptions - An object describing the blockchain */ -export default function blockHeaderFromRpc(blockParams: any, networkOptions?: NetworkOptions) { +export default function blockHeaderFromRpc(blockParams: any, chainOptions?: ChainOptions) { const blockHeader = new BlockHeader( { parentHash: blockParams.parentHash, @@ -27,7 +27,7 @@ export default function blockHeaderFromRpc(blockParams: any, networkOptions?: Ne mixHash: blockParams.mixHash, nonce: blockParams.nonce, }, - networkOptions, + chainOptions, ) // override hash in case something was missing diff --git a/src/header.ts b/src/header.ts index 057f4f6..219360c 100644 --- a/src/header.ts +++ b/src/header.ts @@ -1,7 +1,7 @@ import Common from 'ethereumjs-common' import * as utils from 'ethereumjs-util' import { BN } from 'ethereumjs-util' -import { Blockchain, BlockHeaderData, BufferLike, NetworkOptions, PrefixedHexString } from './types' +import { Blockchain, BlockHeaderData, BufferLike, ChainOptions, PrefixedHexString } from './types' import { Buffer } from 'buffer' import { Block } from './block' @@ -35,7 +35,7 @@ export class BlockHeader { */ constructor( data: Buffer | PrefixedHexString | BufferLike[] | BlockHeaderData = {}, - opts: NetworkOptions = {}, + opts: ChainOptions = {}, ) { if (opts.common !== undefined) { if (opts.chain !== undefined || opts.hardfork !== undefined) { diff --git a/src/types.ts b/src/types.ts index 7856f62..7b4b89a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -3,10 +3,11 @@ import { TxData } from 'ethereumjs-tx' import { Block } from './block' /** - * An object to set to which network blocks and their headers belong. This could be specified using - * a Common object, or `chain` and `hardfork`. Defaults to mainnet without specifying a hardfork. + * An object to set to which blockchain the blocks and their headers belong. This could be specified + * using a Common object, or `chain` and `hardfork`. Defaults to mainnet without specifying a + * hardfork. */ -export interface NetworkOptions { +export interface ChainOptions { /** * A Common object defining the chain and the hardfork a block/block header belongs to. */ From d4d9691dc3248d51b94cb16501be89cd9cde96b8 Mon Sep 17 00:00:00 2001 From: Patricio Palladino Date: Wed, 31 Jul 2019 18:34:33 -0300 Subject: [PATCH 25/25] Rebuild docs --- docs/README.md | 32 ++++++------ docs/classes/block.md | 56 ++++++++++----------- docs/classes/blockheader.md | 62 ++++++++++++------------ docs/interfaces/blockchain.md | 2 +- docs/interfaces/blockdata.md | 6 +-- docs/interfaces/blockheaderdata.md | 30 ++++++------ docs/interfaces/chainoptions.md | 57 ++++++++++++++++++++++ docs/interfaces/networkoptions.md | 57 ---------------------- docs/interfaces/transformabletobuffer.md | 2 +- 9 files changed, 152 insertions(+), 152 deletions(-) create mode 100644 docs/interfaces/chainoptions.md delete mode 100644 docs/interfaces/networkoptions.md diff --git a/docs/README.md b/docs/README.md index 7db8c6e..3960dc5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,7 +12,7 @@ - [BlockData](interfaces/blockdata.md) - [BlockHeaderData](interfaces/blockheaderdata.md) - [Blockchain](interfaces/blockchain.md) -- [NetworkOptions](interfaces/networkoptions.md) +- [ChainOptions](interfaces/chainoptions.md) - [TransformableToBuffer](interfaces/transformabletobuffer.md) ### Type aliases @@ -35,7 +35,7 @@ **Ƭ BufferLike**: _`Buffer` \| [TransformableToBuffer](interfaces/transformabletobuffer.md) \| [PrefixedHexString](#prefixedhexstring) \| `number`_ -_Defined in [types.ts:41](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L41)_ +_Defined in [types.ts:42](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L42)_ A Buffer, hex string prefixed with `0x`, Number, or an object with a toBuffer method such as BN. @@ -47,7 +47,7 @@ A Buffer, hex string prefixed with `0x`, Number, or an object with a toBuffer me **Ƭ PrefixedHexString**: _`string`_ -_Defined in [types.ts:36](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L36)_ +_Defined in [types.ts:37](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L37)_ A hex string prefixed with `0x`. @@ -59,19 +59,19 @@ A hex string prefixed with `0x`. ### blockFromRpc -▸ **blockFromRpc**(blockParams: _`any`_, uncles?: _`any`[]_, networkOptions?: _[NetworkOptions](interfaces/networkoptions.md)_): [Block](classes/block.md) +▸ **blockFromRpc**(blockParams: _`any`_, uncles?: _`any`[]_, chainOptions?: _[ChainOptions](interfaces/chainoptions.md)_): [Block](classes/block.md) -_Defined in [from-rpc.ts:14](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/from-rpc.ts#L14)_ +_Defined in [from-rpc.ts:14](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/from-rpc.ts#L14)_ Creates a new block object from Ethereum JSON RPC. **Parameters:** -| Name | Type | Description | -| ------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------ | -| blockParams | `any` | Ethereum JSON RPC of block (eth_getBlockByNumber) | -| `Optional` uncles | `any`[] | Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) | -| `Optional` networkOptions | [NetworkOptions](interfaces/networkoptions.md) | An object describing the network | +| Name | Type | Description | +| ----------------------- | ------------------------------------------ | ------------------------------------------------------------------------------ | +| blockParams | `any` | Ethereum JSON RPC of block (eth_getBlockByNumber) | +| `Optional` uncles | `any`[] | Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex) | +| `Optional` chainOptions | [ChainOptions](interfaces/chainoptions.md) | An object describing the blockchain | **Returns:** [Block](classes/block.md) @@ -81,18 +81,18 @@ Creates a new block object from Ethereum JSON RPC. ### blockHeaderFromRpc -▸ **blockHeaderFromRpc**(blockParams: _`any`_, networkOptions?: _[NetworkOptions](interfaces/networkoptions.md)_): [BlockHeader](classes/blockheader.md) +▸ **blockHeaderFromRpc**(blockParams: _`any`_, chainOptions?: _[ChainOptions](interfaces/chainoptions.md)_): [BlockHeader](classes/blockheader.md) -_Defined in [header-from-rpc.ts:11](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header-from-rpc.ts#L11)_ +_Defined in [header-from-rpc.ts:11](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header-from-rpc.ts#L11)_ Creates a new block header object from Ethereum JSON RPC. **Parameters:** -| Name | Type | Description | -| ------------------------- | ---------------------------------------------- | ------------------------------------------------- | -| blockParams | `any` | Ethereum JSON RPC of block (eth_getBlockByNumber) | -| `Optional` networkOptions | [NetworkOptions](interfaces/networkoptions.md) | An object describing the network | +| Name | Type | Description | +| ----------------------- | ------------------------------------------ | ------------------------------------------------- | +| blockParams | `any` | Ethereum JSON RPC of block (eth_getBlockByNumber) | +| `Optional` chainOptions | [ChainOptions](interfaces/chainoptions.md) | An object describing the blockchain | **Returns:** [BlockHeader](classes/blockheader.md) diff --git a/docs/classes/block.md b/docs/classes/block.md index 7aeaa03..6d3bb1b 100644 --- a/docs/classes/block.md +++ b/docs/classes/block.md @@ -50,9 +50,9 @@ An object that represents the block ### constructor -⊕ **new Block**(data?: _`Buffer` \| [`Buffer`[], `Buffer`[], `Buffer`[]] \| [BlockData](../interfaces/blockdata.md)_, opts?: _[NetworkOptions](../interfaces/networkoptions.md)_): [Block](block.md) +⊕ **new Block**(data?: _`Buffer` \| [`Buffer`[], `Buffer`[], `Buffer`[]] \| [BlockData](../interfaces/blockdata.md)_, opts?: _[ChainOptions](../interfaces/chainoptions.md)_): [Block](block.md) -_Defined in [block.ts:20](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L20)_ +_Defined in [block.ts:20](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L20)_ Creates a new block object @@ -61,7 +61,7 @@ Creates a new block object | Name | Type | Default value | Description | | -------------------- | ------------------------------------------------------------------------------------------- | ------------- | -------------------------------------------------------------------------- | | `Default value` data | `Buffer` \| [`Buffer`[], `Buffer`[], `Buffer`[]] \| [BlockData](../interfaces/blockdata.md) | {} | The block's data. | -| `Default value` opts | [NetworkOptions](../interfaces/networkoptions.md) | {} | The network options for this block, and its header, uncle headers and txs. | +| `Default value` opts | [ChainOptions](../interfaces/chainoptions.md) | {} | The network options for this block, and its header, uncle headers and txs. | **Returns:** [Block](block.md) @@ -75,7 +75,7 @@ Creates a new block object **● \_common**: _`Common`_ -_Defined in [block.ts:20](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L20)_ +_Defined in [block.ts:20](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L20)_ --- @@ -85,7 +85,7 @@ _Defined in [block.ts:20](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● header**: _[BlockHeader](blockheader.md)_ -_Defined in [block.ts:15](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L15)_ +_Defined in [block.ts:15](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L15)_ --- @@ -95,7 +95,7 @@ _Defined in [block.ts:15](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● transactions**: _`Transaction`[]_ = [] -_Defined in [block.ts:16](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L16)_ +_Defined in [block.ts:16](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L16)_ --- @@ -105,7 +105,7 @@ _Defined in [block.ts:16](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● txTrie**: _`any`_ = new Trie() -_Defined in [block.ts:18](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L18)_ +_Defined in [block.ts:18](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L18)_ --- @@ -115,7 +115,7 @@ _Defined in [block.ts:18](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● uncleHeaders**: _[BlockHeader](blockheader.md)[]_ = [] -_Defined in [block.ts:17](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L17)_ +_Defined in [block.ts:17](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L17)_ --- @@ -127,7 +127,7 @@ _Defined in [block.ts:17](https://github.com/ethereumjs/ethereumjs-block/blob/47 **get raw**(): [`Buffer`[], `Buffer`[], `Buffer`[]] -_Defined in [block.ts:81](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L81)_ +_Defined in [block.ts:82](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L82)_ **Returns:** [`Buffer`[], `Buffer`[], `Buffer`[]] @@ -141,7 +141,7 @@ _Defined in [block.ts:81](https://github.com/ethereumjs/ethereumjs-block/blob/47 ▸ **\_putTxInTrie**(txIndex: _`number`_, tx: _`Transaction`_): `Promise`<`void`> -_Defined in [block.ts:249](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L249)_ +_Defined in [block.ts:250](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L250)_ **Parameters:** @@ -160,7 +160,7 @@ _Defined in [block.ts:249](https://github.com/ethereumjs/ethereumjs-block/blob/4 ▸ **\_validateUncleHeader**(uncleHeader: _[BlockHeader](blockheader.md)_, blockchain: _[Blockchain](../interfaces/blockchain.md)_): `Promise`<`void`> -_Defined in [block.ts:261](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L261)_ +_Defined in [block.ts:262](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L262)_ **Parameters:** @@ -179,7 +179,7 @@ _Defined in [block.ts:261](https://github.com/ethereumjs/ethereumjs-block/blob/4 ▸ **genTxTrie**(): `Promise`<`void`> -_Defined in [block.ts:130](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L130)_ +_Defined in [block.ts:131](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L131)_ Generate transaction trie. The tx trie must be generated before the transaction trie can be validated with `validateTransactionTrie` @@ -193,7 +193,7 @@ Generate transaction trie. The tx trie must be generated before the transaction ▸ **hash**(): `Buffer` -_Defined in [block.ts:88](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L88)_ +_Defined in [block.ts:89](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L89)_ Produces a hash the RLP of the block @@ -207,7 +207,7 @@ Produces a hash the RLP of the block ▸ **isGenesis**(): `boolean` -_Defined in [block.ts:95](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L95)_ +_Defined in [block.ts:96](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L96)_ Determines if this block is the genesis block @@ -225,13 +225,13 @@ Determines if this block is the genesis block ▸ **serialize**(rlpEncode: _`false`_): [`Buffer`[], `Buffer`[], `Buffer`[]] -_Defined in [block.ts:113](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L113)_ +_Defined in [block.ts:114](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L114)_ Produces a serialization of the block. **Returns:** `Buffer` -_Defined in [block.ts:114](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L114)_ +_Defined in [block.ts:115](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L115)_ **Parameters:** @@ -241,7 +241,7 @@ _Defined in [block.ts:114](https://github.com/ethereumjs/ethereumjs-block/blob/4 **Returns:** `Buffer` -_Defined in [block.ts:115](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L115)_ +_Defined in [block.ts:116](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L116)_ **Parameters:** @@ -259,7 +259,7 @@ _Defined in [block.ts:115](https://github.com/ethereumjs/ethereumjs-block/blob/4 ▸ **setGenesisParams**(): `void` -_Defined in [block.ts:102](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L102)_ +_Defined in [block.ts:103](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L103)_ Turns the block into the canonical genesis block @@ -273,7 +273,7 @@ Turns the block into the canonical genesis block ▸ **toJSON**(labeled?: _`boolean`_): `undefined` \| `string` \| `any`[] \| `object` -_Defined in [block.ts:237](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L237)_ +_Defined in [block.ts:238](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L238)_ Returns the block in JSON format @@ -295,7 +295,7 @@ _**see**_: [ethereumjs-util](https://github.com/ethereumjs/ethereumjs-util/blob/ ▸ **validate**(blockChain: _[Blockchain](../interfaces/blockchain.md)_): `Promise`<`void`> -_Defined in [block.ts:179](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L179)_ +_Defined in [block.ts:180](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L180)_ Validates the entire block, throwing if invalid. @@ -319,13 +319,13 @@ Validates the entire block, throwing if invalid. ▸ **validateTransactions**(stringError: _`true`_): `string` -_Defined in [block.ts:154](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L154)_ +_Defined in [block.ts:155](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L155)_ Validates the transactions **Returns:** `boolean` -_Defined in [block.ts:155](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L155)_ +_Defined in [block.ts:156](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L156)_ **Parameters:** @@ -335,7 +335,7 @@ _Defined in [block.ts:155](https://github.com/ethereumjs/ethereumjs-block/blob/4 **Returns:** `boolean` -_Defined in [block.ts:156](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L156)_ +_Defined in [block.ts:157](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L157)_ **Parameters:** @@ -353,7 +353,7 @@ _Defined in [block.ts:156](https://github.com/ethereumjs/ethereumjs-block/blob/4 ▸ **validateTransactionsTrie**(): `boolean` -_Defined in [block.ts:140](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L140)_ +_Defined in [block.ts:141](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L141)_ Validates the transaction trie @@ -365,9 +365,9 @@ Validates the transaction trie ### validateUncles -▸ **validateUncles**(blockchain: _[Blockchain](../interfaces/blockchain.md)_): `Promise`<`undefined` \| `void`[]> +▸ **validateUncles**(blockchain: _[Blockchain](../interfaces/blockchain.md)_): `Promise`<`void`> -_Defined in [block.ts:214](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L214)_ +_Defined in [block.ts:215](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L215)_ Validates the uncles that are in the block, if any. This method throws if they are invalid. @@ -377,7 +377,7 @@ Validates the uncles that are in the block, if any. This method throws if they a | ---------- | ----------------------------------------- | | blockchain | [Blockchain](../interfaces/blockchain.md) | -**Returns:** `Promise`<`undefined` \| `void`[]> +**Returns:** `Promise`<`void`> --- @@ -387,7 +387,7 @@ Validates the uncles that are in the block, if any. This method throws if they a ▸ **validateUnclesHash**(): `boolean` -_Defined in [block.ts:203](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/block.ts#L203)_ +_Defined in [block.ts:204](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/block.ts#L204)_ Validates the uncle's hash diff --git a/docs/classes/blockheader.md b/docs/classes/blockheader.md index e498641..c618be4 100644 --- a/docs/classes/blockheader.md +++ b/docs/classes/blockheader.md @@ -56,9 +56,9 @@ An object that represents the block header ### constructor -⊕ **new BlockHeader**(data?: _`Buffer` \| [PrefixedHexString](../#prefixedhexstring) \| [BufferLike](../#bufferlike)[] \| [BlockHeaderData](../interfaces/blockheaderdata.md)_, opts?: _[NetworkOptions](../interfaces/networkoptions.md)_): [BlockHeader](blockheader.md) +⊕ **new BlockHeader**(data?: _`Buffer` \| [PrefixedHexString](../#prefixedhexstring) \| [BufferLike](../#bufferlike)[] \| [BlockHeaderData](../interfaces/blockheaderdata.md)_, opts?: _[ChainOptions](../interfaces/chainoptions.md)_): [BlockHeader](blockheader.md) -_Defined in [header.ts:29](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L29)_ +_Defined in [header.ts:29](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L29)_ Creates a new block header. @@ -67,7 +67,7 @@ Creates a new block header. | Name | Type | Default value | Description | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------------------------------------------------------------------------- | | `Default value` data | `Buffer` \| [PrefixedHexString](../#prefixedhexstring) \| [BufferLike](../#bufferlike)[] \| [BlockHeaderData](../interfaces/blockheaderdata.md) | {} | The data of the block header. | -| `Default value` opts | [NetworkOptions](../interfaces/networkoptions.md) | {} | The network options for this block, and its header, uncle headers and txs. | +| `Default value` opts | [ChainOptions](../interfaces/chainoptions.md) | {} | The network options for this block, and its header, uncle headers and txs. | **Returns:** [BlockHeader](blockheader.md) @@ -81,7 +81,7 @@ Creates a new block header. **● \_common**: _`Common`_ -_Defined in [header.ts:29](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L29)_ +_Defined in [header.ts:29](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L29)_ --- @@ -91,7 +91,7 @@ _Defined in [header.ts:29](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● bloom**: _`Buffer`_ -_Defined in [header.ts:19](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L19)_ +_Defined in [header.ts:19](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L19)_ --- @@ -101,7 +101,7 @@ _Defined in [header.ts:19](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● coinbase**: _`Buffer`_ -_Defined in [header.ts:15](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L15)_ +_Defined in [header.ts:15](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L15)_ --- @@ -111,7 +111,7 @@ _Defined in [header.ts:15](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● difficulty**: _`Buffer`_ -_Defined in [header.ts:20](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L20)_ +_Defined in [header.ts:20](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L20)_ --- @@ -121,7 +121,7 @@ _Defined in [header.ts:20](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● extraData**: _`Buffer`_ -_Defined in [header.ts:25](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L25)_ +_Defined in [header.ts:25](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L25)_ --- @@ -131,7 +131,7 @@ _Defined in [header.ts:25](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● gasLimit**: _`Buffer`_ -_Defined in [header.ts:22](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L22)_ +_Defined in [header.ts:22](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L22)_ --- @@ -141,7 +141,7 @@ _Defined in [header.ts:22](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● gasUsed**: _`Buffer`_ -_Defined in [header.ts:23](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L23)_ +_Defined in [header.ts:23](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L23)_ --- @@ -151,7 +151,7 @@ _Defined in [header.ts:23](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● mixHash**: _`Buffer`_ -_Defined in [header.ts:26](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L26)_ +_Defined in [header.ts:26](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L26)_ --- @@ -161,7 +161,7 @@ _Defined in [header.ts:26](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● nonce**: _`Buffer`_ -_Defined in [header.ts:27](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L27)_ +_Defined in [header.ts:27](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L27)_ --- @@ -171,7 +171,7 @@ _Defined in [header.ts:27](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● number**: _`Buffer`_ -_Defined in [header.ts:21](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L21)_ +_Defined in [header.ts:21](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L21)_ --- @@ -181,7 +181,7 @@ _Defined in [header.ts:21](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● parentHash**: _`Buffer`_ -_Defined in [header.ts:13](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L13)_ +_Defined in [header.ts:13](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L13)_ --- @@ -191,7 +191,7 @@ _Defined in [header.ts:13](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● raw**: _`Buffer`[]_ -_Defined in [header.ts:12](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L12)_ +_Defined in [header.ts:12](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L12)_ --- @@ -201,7 +201,7 @@ _Defined in [header.ts:12](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● receiptTrie**: _`Buffer`_ -_Defined in [header.ts:18](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L18)_ +_Defined in [header.ts:18](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L18)_ --- @@ -211,7 +211,7 @@ _Defined in [header.ts:18](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● stateRoot**: _`Buffer`_ -_Defined in [header.ts:16](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L16)_ +_Defined in [header.ts:16](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L16)_ --- @@ -221,7 +221,7 @@ _Defined in [header.ts:16](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● timestamp**: _`Buffer`_ -_Defined in [header.ts:24](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L24)_ +_Defined in [header.ts:24](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L24)_ --- @@ -231,7 +231,7 @@ _Defined in [header.ts:24](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● transactionsTrie**: _`Buffer`_ -_Defined in [header.ts:17](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L17)_ +_Defined in [header.ts:17](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L17)_ --- @@ -241,7 +241,7 @@ _Defined in [header.ts:17](https://github.com/ethereumjs/ethereumjs-block/blob/4 **● uncleHash**: _`Buffer`_ -_Defined in [header.ts:14](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L14)_ +_Defined in [header.ts:14](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L14)_ --- @@ -253,7 +253,7 @@ _Defined in [header.ts:14](https://github.com/ethereumjs/ethereumjs-block/blob/4 ▸ **\_getBlockByHash**(blockchain: _[Blockchain](../interfaces/blockchain.md)_, hash: _`Buffer`_): `Promise`<[Block](block.md) \| `undefined`> -_Defined in [header.ts:347](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L347)_ +_Defined in [header.ts:347](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L347)_ **Parameters:** @@ -272,7 +272,7 @@ _Defined in [header.ts:347](https://github.com/ethereumjs/ethereumjs-block/blob/ ▸ **\_getHardfork**(): `string` -_Defined in [header.ts:339](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L339)_ +_Defined in [header.ts:339](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L339)_ **Returns:** `string` @@ -284,7 +284,7 @@ _Defined in [header.ts:339](https://github.com/ethereumjs/ethereumjs-block/blob/ ▸ **canonicalDifficulty**(parentBlock: _[Block](block.md)_): `BN` -_Defined in [header.ts:134](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L134)_ +_Defined in [header.ts:134](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L134)_ Returns the canonical difficulty for this block. @@ -304,7 +304,7 @@ Returns the canonical difficulty for this block. ▸ **hash**(): `Buffer` -_Defined in [header.ts:297](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L297)_ +_Defined in [header.ts:297](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L297)_ Returns the hash of the block header. @@ -318,7 +318,7 @@ Returns the hash of the block header. ▸ **isGenesis**(): `boolean` -_Defined in [header.ts:304](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L304)_ +_Defined in [header.ts:304](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L304)_ Checks if the block header is a genesis header. @@ -332,7 +332,7 @@ Checks if the block header is a genesis header. ▸ **serialize**(): `Buffer` -_Defined in [header.ts:324](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L324)_ +_Defined in [header.ts:324](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L324)_ Returns the rlp encoding of the block header @@ -346,7 +346,7 @@ Returns the rlp encoding of the block header ▸ **setGenesisParams**(): `void` -_Defined in [header.ts:311](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L311)_ +_Defined in [header.ts:311](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L311)_ Turns the header into the canonical genesis block header. @@ -360,7 +360,7 @@ Turns the header into the canonical genesis block header. ▸ **toJSON**(\_labels?: _`boolean`_): `object` \| `string`[] -_Defined in [header.ts:334](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L334)_ +_Defined in [header.ts:334](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L334)_ Returns the block header in JSON format @@ -382,7 +382,7 @@ _**see**_: [ethereumjs-util](https://github.com/ethereumjs/ethereumjs-util/blob/ ▸ **validate**(blockchain: _[Blockchain](../interfaces/blockchain.md)_, height?: _`BN`_): `Promise`<`void`> -_Defined in [header.ts:249](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L249)_ +_Defined in [header.ts:249](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L249)_ Validates the entire block header, throwing if invalid. @@ -403,7 +403,7 @@ Validates the entire block header, throwing if invalid. ▸ **validateDifficulty**(parentBlock: _[Block](block.md)_): `boolean` -_Defined in [header.ts:215](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L215)_ +_Defined in [header.ts:215](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L215)_ Checks that the block's `difficulty` matches the canonical difficulty. @@ -423,7 +423,7 @@ Checks that the block's `difficulty` matches the canonical difficulty. ▸ **validateGasLimit**(parentBlock: _[Block](block.md)_): `boolean` -_Defined in [header.ts:225](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/header.ts#L225)_ +_Defined in [header.ts:225](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/header.ts#L225)_ Validates the gasLimit. diff --git a/docs/interfaces/blockchain.md b/docs/interfaces/blockchain.md index a2332a9..af39603 100644 --- a/docs/interfaces/blockchain.md +++ b/docs/interfaces/blockchain.md @@ -22,7 +22,7 @@ ▸ **getBlock**(hash: _`Buffer`_, callback: _`function`_): `void` -_Defined in [types.ts:74](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L74)_ +_Defined in [types.ts:75](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L75)_ **Parameters:** diff --git a/docs/interfaces/blockdata.md b/docs/interfaces/blockdata.md index a0830e4..dec723e 100644 --- a/docs/interfaces/blockdata.md +++ b/docs/interfaces/blockdata.md @@ -26,7 +26,7 @@ A block's data. **● header**: _`Buffer` \| [PrefixedHexString](../#prefixedhexstring) \| [BufferLike](../#bufferlike)[] \| [BlockHeaderData](blockheaderdata.md)_ -_Defined in [types.ts:68](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L68)_ +_Defined in [types.ts:69](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L69)_ --- @@ -36,7 +36,7 @@ _Defined in [types.ts:68](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● transactions**: _`Array`<`Buffer` \| [PrefixedHexString](../#prefixedhexstring) \| [BufferLike](../#bufferlike)[] \| `TxData`>_ -_Defined in [types.ts:69](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L69)_ +_Defined in [types.ts:70](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L70)_ --- @@ -46,6 +46,6 @@ _Defined in [types.ts:69](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● uncleHeaders**: _`Array`<`Buffer` \| [PrefixedHexString](../#prefixedhexstring) \| [BufferLike](../#bufferlike)[] \| [BlockHeaderData](blockheaderdata.md)>_ -_Defined in [types.ts:70](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L70)_ +_Defined in [types.ts:71](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L71)_ --- diff --git a/docs/interfaces/blockheaderdata.md b/docs/interfaces/blockheaderdata.md index 623a485..85cea8d 100644 --- a/docs/interfaces/blockheaderdata.md +++ b/docs/interfaces/blockheaderdata.md @@ -38,7 +38,7 @@ A block header's data. **● bloom**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:53](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L53)_ +_Defined in [types.ts:54](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L54)_ --- @@ -48,7 +48,7 @@ _Defined in [types.ts:53](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● coinbase**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:49](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L49)_ +_Defined in [types.ts:50](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L50)_ --- @@ -58,7 +58,7 @@ _Defined in [types.ts:49](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● difficulty**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:54](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L54)_ +_Defined in [types.ts:55](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L55)_ --- @@ -68,7 +68,7 @@ _Defined in [types.ts:54](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● extraData**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:59](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L59)_ +_Defined in [types.ts:60](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L60)_ --- @@ -78,7 +78,7 @@ _Defined in [types.ts:59](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● gasLimit**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:56](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L56)_ +_Defined in [types.ts:57](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L57)_ --- @@ -88,7 +88,7 @@ _Defined in [types.ts:56](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● gasUsed**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:57](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L57)_ +_Defined in [types.ts:58](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L58)_ --- @@ -98,7 +98,7 @@ _Defined in [types.ts:57](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● mixHash**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:60](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L60)_ +_Defined in [types.ts:61](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L61)_ --- @@ -108,7 +108,7 @@ _Defined in [types.ts:60](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● nonce**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:61](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L61)_ +_Defined in [types.ts:62](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L62)_ --- @@ -118,7 +118,7 @@ _Defined in [types.ts:61](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● number**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:55](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L55)_ +_Defined in [types.ts:56](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L56)_ --- @@ -128,7 +128,7 @@ _Defined in [types.ts:55](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● parentHash**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:47](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L47)_ +_Defined in [types.ts:48](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L48)_ --- @@ -138,7 +138,7 @@ _Defined in [types.ts:47](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● receiptTrie**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:52](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L52)_ +_Defined in [types.ts:53](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L53)_ --- @@ -148,7 +148,7 @@ _Defined in [types.ts:52](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● stateRoot**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:50](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L50)_ +_Defined in [types.ts:51](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L51)_ --- @@ -158,7 +158,7 @@ _Defined in [types.ts:50](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● timestamp**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:58](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L58)_ +_Defined in [types.ts:59](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L59)_ --- @@ -168,7 +168,7 @@ _Defined in [types.ts:58](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● transactionsTrie**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:51](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L51)_ +_Defined in [types.ts:52](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L52)_ --- @@ -178,6 +178,6 @@ _Defined in [types.ts:51](https://github.com/ethereumjs/ethereumjs-block/blob/47 **● uncleHash**: _[BufferLike](../#bufferlike)_ -_Defined in [types.ts:48](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L48)_ +_Defined in [types.ts:49](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L49)_ --- diff --git a/docs/interfaces/chainoptions.md b/docs/interfaces/chainoptions.md new file mode 100644 index 0000000..40a72b6 --- /dev/null +++ b/docs/interfaces/chainoptions.md @@ -0,0 +1,57 @@ +[ethereumjs-block](../README.md) > [ChainOptions](../interfaces/chainoptions.md) + +# Interface: ChainOptions + +An object to set to which blockchain the blocks and their headers belong. This could be specified using a Common object, or `chain` and `hardfork`. Defaults to mainnet without specifying a hardfork. + +## Hierarchy + +**ChainOptions** + +## Index + +### Properties + +- [chain](chainoptions.md#chain) +- [common](chainoptions.md#common) +- [hardfork](chainoptions.md#hardfork) + +--- + +## Properties + + + +### `` chain + +**● chain**: _`number` \| `string`_ + +_Defined in [types.ts:19](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L19)_ + +The chain of the block/block header, default: 'mainnet' + +--- + + + +### `` common + +**● common**: _`Common`_ + +_Defined in [types.ts:14](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L14)_ + +A Common object defining the chain and the hardfork a block/block header belongs to. + +--- + + + +### `` hardfork + +**● hardfork**: _`undefined` \| `string`_ + +_Defined in [types.ts:24](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L24)_ + +The hardfork of the block/block header, default: 'petersburg' + +--- diff --git a/docs/interfaces/networkoptions.md b/docs/interfaces/networkoptions.md deleted file mode 100644 index d690212..0000000 --- a/docs/interfaces/networkoptions.md +++ /dev/null @@ -1,57 +0,0 @@ -[ethereumjs-block](../README.md) > [NetworkOptions](../interfaces/networkoptions.md) - -# Interface: NetworkOptions - -An object to set to which network blocks and their headers belong. This could be specified using a Common object, or `chain` and `hardfork`. Defaults to mainnet without specifying a hardfork. - -## Hierarchy - -**NetworkOptions** - -## Index - -### Properties - -- [chain](networkoptions.md#chain) -- [common](networkoptions.md#common) -- [hardfork](networkoptions.md#hardfork) - ---- - -## Properties - - - -### `` chain - -**● chain**: _`number` \| `string`_ - -_Defined in [types.ts:18](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L18)_ - -The chain of the block/block header, default: 'mainnet' - ---- - - - -### `` common - -**● common**: _`Common`_ - -_Defined in [types.ts:13](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L13)_ - -A Common object defining the chain and the hardfork a block/block header belongs to. - ---- - - - -### `` hardfork - -**● hardfork**: _`undefined` \| `string`_ - -_Defined in [types.ts:23](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L23)_ - -The hardfork of the block/block header, default: 'petersburg' - ---- diff --git a/docs/interfaces/transformabletobuffer.md b/docs/interfaces/transformabletobuffer.md index 1075351..4e7f7fd 100644 --- a/docs/interfaces/transformabletobuffer.md +++ b/docs/interfaces/transformabletobuffer.md @@ -24,7 +24,7 @@ Any object that can be transformed into a `Buffer` ▸ **toBuffer**(): `Buffer` -_Defined in [types.ts:30](https://github.com/ethereumjs/ethereumjs-block/blob/4769f90/src/types.ts#L30)_ +_Defined in [types.ts:31](https://github.com/ethereumjs/ethereumjs-block/blob/6adbfae/src/types.ts#L31)_ **Returns:** `Buffer`