forked from ethereumjs/ultralight
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheth.ts
340 lines (320 loc) · 12.1 KB
/
eth.ts
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import { Common } from '@ethereumjs/common'
import { EVM } from '@ethereumjs/evm'
import { Address, TypeOutput, bytesToHex, hexToBytes, toType } from '@ethereumjs/util'
import { keccak256 } from 'ethereum-cryptography/keccak.js'
import {
BlockHeaderByNumberKey,
BlockHeaderWithProof,
ContentLookup,
HistoryNetworkContentType,
NetworkId,
UltralightStateManager,
getContentKey,
reassembleBlock,
} from '../networks/index.js'
import type { Block } from '@ethereumjs/block'
import type { capella } from '@lodestar/types'
import type { Debugger } from 'debug'
import type {
BeaconLightClientNetwork,
ContentLookupResponse,
HistoryNetwork,
StateNetwork,
} from '../networks/index.js'
import type { PortalNetwork } from './client.js'
import type { RpcTx } from './types.js'
export class ETH {
history?: HistoryNetwork
state?: StateNetwork
beacon?: BeaconLightClientNetwork
activeNetworks: NetworkId[]
logger: Debugger
constructor(portal: PortalNetwork) {
this.activeNetworks = Array.from(portal.networks.keys()) as NetworkId[]
this.history = portal.network()['0x500b']
this.state = portal.network()['0x500a']
this.beacon = portal.network()['0x500c']
this.logger = portal.logger.extend(`ETH`)
}
/**
* Implements logic required for `eth_getBalance` JSON-RPC call
* @param address address to be looked up
* @param blockNumber block number from which balance should be returned
* @returns returns the ETH balance of an address at the specified block number or undefined if not available
*/
getBalance = async (address: Uint8Array, blockNumber: bigint): Promise<bigint | undefined> => {
this.networkCheck([NetworkId.StateNetwork, NetworkId.HistoryNetwork])
const stateRoot = await this.history!.getStateRoot(blockNumber)
if (!stateRoot) {
this.logger.extend('getBalance')(`Unable to find StateRoot for block ${blockNumber}`)
return undefined
}
return this.state!.manager.getBalance(address, stateRoot)
}
public getBlockByHash = async (
blockHash: Uint8Array,
includeTransactions: boolean,
): Promise<Block | undefined> => {
let lookupResponse: ContentLookupResponse
let header: any
let body: any
let block
this.networkCheck([NetworkId.HistoryNetwork])
const headerContentKey = getContentKey(HistoryNetworkContentType.BlockHeader, blockHash)
const bodyContentKey = includeTransactions
? getContentKey(HistoryNetworkContentType.BlockBody, blockHash)
: undefined
try {
let lookup = new ContentLookup(this.history!, headerContentKey)
this.logger.extend('getBlockByHash')(`Looking for ${bytesToHex(blockHash)}`)
lookupResponse = await lookup.startLookup()
this.logger.extend('getBlockByHash')(lookupResponse)
if (!lookupResponse || !('content' in lookupResponse)) {
// Header not found by hash, try to find by number if known
const blockNumber = this.history!.blockHashToNumber(blockHash)
if (blockNumber !== undefined) {
const block = await this.getBlockByNumber(blockNumber, includeTransactions)
return block
}
return undefined
} else {
header = lookupResponse.content
header = BlockHeaderWithProof.deserialize(header as Uint8Array).header
}
if (!includeTransactions) {
block = reassembleBlock(header, undefined)
return block
} else {
lookup = new ContentLookup(this.history!, bodyContentKey!)
lookupResponse = await lookup.startLookup()
if (!lookupResponse || !('content' in lookupResponse)) {
block = reassembleBlock(header)
} else {
body = lookupResponse.content
block = reassembleBlock(header, body)
}
}
} catch {
/** NOOP */
}
return block
}
getBlockByTag = async (
blockTag: 'latest' | 'finalized',
includeTransactions: boolean,
): Promise<Block | undefined> => {
// Requires beacon light client to be running to get `latest` or `finalized` blocks
this.networkCheck([NetworkId.BeaconChainNetwork])
let clHeader
switch (blockTag) {
case 'latest': {
clHeader = this.beacon!.lightClient?.getHead() as capella.LightClientHeader
if (clHeader === undefined) throw new Error('light client is not tracking head')
return this.getBlockByHash(clHeader.execution.blockHash, includeTransactions)
}
case 'finalized': {
clHeader = this.beacon!.lightClient?.getFinalized() as capella.LightClientHeader
if (clHeader === undefined) throw new Error('no finalized head available')
return this.getBlockByHash(clHeader.execution.blockHash, includeTransactions)
}
}
}
/**
* Implements logic required for `eth_getBlockByNumber` JSON-RPC call
* @param blockNumber number of block sought, `latest`, `finalized`
* @param includeTransactions whether to include transactions with the block
* @returns returns an @ethereumjs/block formatted `Block` object
*/
public getBlockByNumber = async (
blockNumber: number | bigint | 'latest' | 'finalized',
includeTransactions: boolean,
): Promise<Block | undefined> => {
this.networkCheck([NetworkId.HistoryNetwork])
if (blockNumber === 'latest' || blockNumber === 'finalized') {
return this.getBlockByTag(blockNumber, includeTransactions)
}
// Try to find block locally
try {
const block = await this.history!.getBlockFromDB(
{ blockNumber: BigInt(blockNumber) },
includeTransactions,
)
return block
} catch {
this.logger(`Block ${blockNumber} not found locally - looking on the network`)
}
// Try to find header on the network via block number
let header: Uint8Array | undefined
const headerNumberContentKey = BlockHeaderByNumberKey(BigInt(blockNumber))
const lookup = new ContentLookup(this.history!, headerNumberContentKey)
const lookupResponse = await lookup.startLookup()
if (lookupResponse && 'content' in lookupResponse) {
// Header found by number. Now get the body via hash
header = BlockHeaderWithProof.deserialize(lookupResponse.content).header
const hash = keccak256(header)
if (!includeTransactions) {
return reassembleBlock(header)
}
const bodyContentKey = getContentKey(HistoryNetworkContentType.BlockBody, hash)
const bodyLookup = new ContentLookup(this.history!, bodyContentKey)
const bodyLookupResponse = await bodyLookup.startLookup()
if (bodyLookupResponse && 'content' in bodyLookupResponse) {
// Body found by hash. Reassemble block
const body = bodyLookupResponse.content
return reassembleBlock(header, body)
} else {
// Body not found by hash. Reassemble block without body
return reassembleBlock(header)
}
} else {
// Header not found by number. If block hash is known, search for header by hash
const blockHash = this.history!.blockNumberToHash(BigInt(blockNumber))
if (blockHash !== undefined) {
return this.getBlockByHash(blockHash, includeTransactions)
}
}
}
/**
* Implements functionality needed for making `eth_call` RPC calls over Portal Network data
* @param tx an `RpcTx` object matching the `eth_call` input spec
* @param blockNumber a block number as a `bigint`
* @returns An execution result as defined by the `eth_call` spec
*/
call = async (tx: RpcTx, blockNumber: bigint): Promise<any> => {
this.networkCheck([NetworkId.HistoryNetwork, NetworkId.StateNetwork])
const stateRoot = await this.history!.getStateRoot(blockNumber)
const common = new Common({ chain: 'mainnet' })
if (!stateRoot) {
throw new Error(`Unable to find StateRoot for block ${blockNumber}`)
}
const usm = new UltralightStateManager(this.state!)
const evm = await EVM.create({ stateManager: usm, common })
await evm.stateManager.setStateRoot(stateRoot)
const { from, to, gas: gasLimit, gasPrice, value, data } = tx
const runCallOpts = {
caller: from !== undefined ? Address.fromString(from) : undefined,
to: to !== undefined ? Address.fromString(to) : undefined,
gasLimit: toType(gasLimit, TypeOutput.BigInt),
gasPrice: toType(gasPrice, TypeOutput.BigInt),
value: toType(value, TypeOutput.BigInt),
data: data !== undefined ? hexToBytes(data) : undefined,
}
const res = (await evm.runCall(runCallOpts)).execResult.returnValue
return bytesToHex(res)
}
private networkCheck = (networks: NetworkId[]) => {
for (const network of networks) {
if (this.activeNetworks.findIndex((el) => el === network) === -1)
throw new Error(
`${Object.entries(NetworkId).find((el) => el[1] === network)?.[0] ??
'Unsupported network ' + network
} required for this call`,
)
}
}
/**
*
* @param this StateNetwork
* @param address address of the storage
* @param slot integer of the position in the storage
* @param blockTag integer block number, or the string "latest", "earliest" or "pending"
* @returns the value at this storage position
*/
async getStorageAt(
address: Uint8Array,
slot: Uint8Array,
blockTag?: string,
): Promise<string | undefined> {
this.networkCheck([NetworkId.StateNetwork, NetworkId.HistoryNetwork])
if (
blockTag === undefined ||
blockTag === 'pending' ||
blockTag === 'earliest' ||
blockTag === 'latest'
) {
throw new Error(`Unsupported blockTag ${blockTag}`)
}
const blockNumber = BigInt(blockTag)
const stateRoot = await this.history!.getStateRoot(blockNumber)
if (!stateRoot) {
this.logger.extend('getTransactionCount')(`Unable to find StateRoot for block ${blockNumber}`)
return undefined
}
}
/**
*
* @param this state network
* @param address address
* @param blockTag integer block number, or the string "latest", "earliest" or "pending"
* @returns
*/
async getTransactionCount(address: Uint8Array, blockTag?: string): Promise<bigint | undefined> {
this.networkCheck([NetworkId.StateNetwork, NetworkId.HistoryNetwork])
if (
blockTag === undefined ||
blockTag === 'pending' ||
blockTag === 'earliest' ||
blockTag === 'latest'
) {
throw new Error(`Unsupported blockTag ${blockTag}`)
}
const blockNumber = BigInt(blockTag)
const stateRoot = await this.history!.getStateRoot(blockNumber)
if (!stateRoot) {
this.logger.extend('getTransactionCount')(`Unable to find StateRoot for block ${blockNumber}`)
return undefined
}
return this.state!.manager.getNonce(address, stateRoot)
}
/**
*
* @param this state network
* @param address address
* @param blockTag integer block number, or the string "latest", "earliest" or "pending"
* @returns code at a given address
*/
async getCode(address: Uint8Array, blockTag?: string) {
this.networkCheck([NetworkId.StateNetwork, NetworkId.HistoryNetwork])
if (
blockTag === undefined ||
blockTag === 'pending' ||
blockTag === 'earliest' ||
blockTag === 'latest'
) {
throw new Error(`Unsupported blockTag ${blockTag}`)
}
const blockNumber = BigInt(blockTag)
const stateRoot = await this.history!.getStateRoot(blockNumber)
if (!stateRoot) {
this.logger.extend('getTransactionCount')(`Unable to find StateRoot for block ${blockNumber}`)
return undefined
}
return this.state!.manager.getCode(address, stateRoot)
}
/**
* Generates and returns an estimate of how much gas is necessary to allow the transaction to complete. The transaction will not be added to the blockchain.
* @param this state network
* @param txObject transaction object
* @param blockTag integer block number, or the string "latest", "earliest" or "pending"
* @returns
*/
async estimateGas(_txObject: TxEstimateObject, _blockTag?: string): Promise<string | undefined> {
return undefined
}
}
export type TxCallObject = {
from?: string
to: string
gas?: string
gasPrice?: string
value?: string
data?: string
}
export type TxEstimateObject = {
from?: string
to?: string
gas?: string
gasPrice?: string
value?: string
data?: string
}