-
Notifications
You must be signed in to change notification settings - Fork 846
Expand file tree
/
Copy pathfrom-rpc.ts
More file actions
72 lines (55 loc) · 2.22 KB
/
from-rpc.ts
File metadata and controls
72 lines (55 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { Transaction, TxData } from '@ethereumjs/tx'
import { toBuffer, setLengthLeft, Address } from 'ethereumjs-util'
import { Block, BlockOptions } 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 chainOptions - An object describing the blockchain
*/
export default function blockFromRpc(blockParams: any, uncles?: any[], options?: BlockOptions) {
uncles = uncles || []
const header = blockHeaderFromRpc(blockParams, options)
const transactions: TxData[] = []
if (blockParams.transactions) {
const txOpts = { common: header._common }
for (const _txParams of blockParams.transactions) {
const txParams = normalizeTxParams(_txParams)
// override from address
const fromAddress = txParams.from ? Address.fromString(txParams.from) : Address.zero()
delete txParams.from
const tx = Transaction.fromTxData(txParams as TxData, txOpts)
const fakeTx = Object.create(tx)
// override getSenderAddress
fakeTx.getSenderAddress = () => {
return fromAddress
}
// override hash
fakeTx.hash = () => {
return toBuffer(txParams.hash)
}
transactions.push(fakeTx)
}
}
const block = Block.fromBlockData({
header,
transactions,
uncleHeaders: uncles.map((uh) => blockHeaderFromRpc(uh, options)),
})
return block
}
function normalizeTxParams(_txParams: any) {
const txParams = Object.assign({}, _txParams)
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 ? setLengthLeft(toBuffer(txParams.to), 20) : null
// v as raw signature value {0,1}
// v is the recovery bit and can be either {0,1} or {27,28}.
// https://ethereum.stackexchange.com/questions/40679/why-the-value-of-v-is-always-either-27-11011-or-28-11100
const v: number = txParams.v
txParams.v = v < 27 ? v + 27 : v
return txParams
}