UNPKG

1.88 kBJavaScriptView Raw
1'use strict'
2const Transaction = require('ethereumjs-tx')
3const ethUtil = require('ethereumjs-util')
4const Block = require('./')
5const blockHeaderFromRpc = require('./header-from-rpc')
6
7module.exports = blockFromRpc
8
9/**
10 * Creates a new block object from Ethereum JSON RPC.
11 * @param {Object} blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber)
12 * @param {Array.<Object>} Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex)
13 */
14function blockFromRpc (blockParams, uncles) {
15 uncles = uncles || []
16 const block = new Block({
17 transactions: [],
18 uncleHeaders: []
19 })
20 block.header = blockHeaderFromRpc(blockParams)
21
22 block.transactions = (blockParams.transactions || []).map(function (_txParams) {
23 const txParams = normalizeTxParams(_txParams)
24 // override from address
25 const fromAddress = ethUtil.toBuffer(txParams.from)
26 delete txParams.from
27 const tx = new Transaction(txParams)
28 tx._from = fromAddress
29 tx.getSenderAddress = function () { return fromAddress }
30 // override hash
31 const txHash = ethUtil.toBuffer(txParams.hash)
32 tx.hash = function () { return txHash }
33 return tx
34 })
35 block.uncleHeaders = uncles.map(function (uncleParams) {
36 return blockHeaderFromRpc(uncleParams)
37 })
38
39 return block
40}
41
42function normalizeTxParams (_txParams) {
43 const txParams = Object.assign({}, _txParams)
44 // hot fix for https://github.com/ethereumjs/ethereumjs-util/issues/40
45 txParams.gasLimit = (txParams.gasLimit === undefined) ? txParams.gas : txParams.gasLimit
46 txParams.data = (txParams.data === undefined) ? txParams.input : txParams.data
47 // strict byte length checking
48 txParams.to = txParams.to ? ethUtil.setLengthLeft(ethUtil.toBuffer(txParams.to), 20) : null
49 // v as raw signature value {0,1}
50 txParams.v = txParams.v < 27 ? txParams.v + 27 : txParams.v
51 return txParams
52}