-
Notifications
You must be signed in to change notification settings - Fork 722
/
manager.ts
249 lines (218 loc) · 7.62 KB
/
manager.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
import { Block, BlockHeader, valuesArrayToHeaderData } from '@ethereumjs/block'
import { RLP } from '@ethereumjs/rlp'
import {
DB,
KECCAK256_RLP,
KECCAK256_RLP_ARRAY,
bytesToBigInt,
equalsBytes,
toBytes,
} from '@ethereumjs/util'
import { hexToBytes } from 'ethereum-cryptography/utils'
import { Cache } from './cache'
import { DBOp, DBTarget } from './operation'
import type { DBOpData, DatabaseKey } from './operation'
import type { BlockBodyBytes, BlockBytes, BlockOptions } from '@ethereumjs/block'
import type { Common } from '@ethereumjs/common'
class NotFoundError extends Error {
public code: string = 'LEVEL_NOT_FOUND'
constructor(blockNumber: bigint) {
super(`Key ${blockNumber.toString()} was not found`)
// `Error.captureStackTrace` is not defined in some browser contexts
if (typeof Error.captureStackTrace !== 'undefined') {
Error.captureStackTrace(this, this.constructor)
}
}
}
/**
* @hidden
*/
export interface GetOpts {
keyEncoding?: string
valueEncoding?: string
cache?: string
}
export type CacheMap = { [key: string]: Cache<Uint8Array> }
/**
* Abstraction over a DB to facilitate storing/fetching blockchain-related
* data, such as blocks and headers, indices, and the head block.
* @hidden
*/
export class DBManager {
private _cache: CacheMap
private _common: Common
private _db: DB<Uint8Array | string, Uint8Array | string>
constructor(db: DB<Uint8Array | string, Uint8Array | string>, common: Common) {
this._db = db
this._common = common
this._cache = {
td: new Cache({ max: 1024 }),
header: new Cache({ max: 512 }),
body: new Cache({ max: 256 }),
numberToHash: new Cache({ max: 2048 }),
hashToNumber: new Cache({ max: 2048 }),
}
}
/**
* Fetches iterator heads from the db.
*/
async getHeads(): Promise<{ [key: string]: Uint8Array }> {
const heads = await this.get(DBTarget.Heads)
for (const key of Object.keys(heads)) {
// Heads are stored in DB as hex strings since Level converts Uint8Arrays
// to nested JSON objects when they are included in a value being stored
// in the DB
heads[key] = hexToBytes(heads[key])
}
return heads
}
/**
* Fetches header of the head block.
*/
async getHeadHeader(): Promise<Uint8Array> {
return this.get(DBTarget.HeadHeader)
}
/**
* Fetches head block.
*/
async getHeadBlock(): Promise<Uint8Array> {
return this.get(DBTarget.HeadBlock)
}
/**
* Fetches a block (header and body) given a block id,
* which can be either its hash or its number.
*/
async getBlock(blockId: Uint8Array | bigint | number): Promise<Block> {
if (typeof blockId === 'number' && Number.isInteger(blockId)) {
blockId = BigInt(blockId)
}
let number
let hash
if (blockId instanceof Uint8Array) {
hash = blockId
number = await this.hashToNumber(blockId)
} else if (typeof blockId === 'bigint') {
number = blockId
hash = await this.numberToHash(blockId)
} else {
throw new Error('Unknown blockId type')
}
const header = await this.getHeader(hash, number)
let body: BlockBodyBytes
try {
body = await this.getBody(hash, number)
} catch (error: any) {
if (error.code !== 'LEVEL_NOT_FOUND') {
throw error
}
// Do extra validations on the header since we are assuming empty transactions and uncles
if (
!equalsBytes(header.transactionsTrie, KECCAK256_RLP) ||
!equalsBytes(header.uncleHash, KECCAK256_RLP_ARRAY)
) {
throw error
}
body = [[], []]
// If this block had empty withdrawals push an empty array in body
if (header.withdrawalsRoot !== undefined) {
// Do extra validations for withdrawal before assuming empty withdrawals
if (!equalsBytes(header.withdrawalsRoot, KECCAK256_RLP)) {
throw error
}
body.push([])
}
}
const blockData = [header.raw(), ...body] as BlockBytes
const opts: BlockOptions = { common: this._common }
if (number === BigInt(0)) {
opts.hardforkByTTD = await this.getTotalDifficulty(hash, BigInt(0))
} else {
opts.hardforkByTTD = await this.getTotalDifficulty(header.parentHash, number - BigInt(1))
}
return Block.fromValuesArray(blockData, opts)
}
/**
* Fetches body of a block given its hash and number.
*/
async getBody(blockHash: Uint8Array, blockNumber: bigint): Promise<BlockBodyBytes> {
const body = await this.get(DBTarget.Body, { blockHash, blockNumber })
return RLP.decode(body) as BlockBodyBytes
}
/**
* Fetches header of a block given its hash and number.
*/
async getHeader(blockHash: Uint8Array, blockNumber: bigint) {
const encodedHeader = await this.get(DBTarget.Header, { blockHash, blockNumber })
const headerValues = RLP.decode(encodedHeader)
const opts: BlockOptions = { common: this._common }
if (blockNumber === BigInt(0)) {
opts.hardforkByTTD = await this.getTotalDifficulty(blockHash, BigInt(0))
} else {
// Lets fetch the parent hash but not by number since this block might not
// be in canonical chain
const headerData = valuesArrayToHeaderData(headerValues as Uint8Array[])
const parentHash = headerData.parentHash as Uint8Array
opts.hardforkByTTD = await this.getTotalDifficulty(parentHash, blockNumber - BigInt(1))
}
return BlockHeader.fromValuesArray(headerValues as Uint8Array[], opts)
}
/**
* Fetches total difficulty for a block given its hash and number.
*/
async getTotalDifficulty(blockHash: Uint8Array, blockNumber: bigint): Promise<bigint> {
const td = await this.get(DBTarget.TotalDifficulty, { blockHash, blockNumber })
return bytesToBigInt(RLP.decode(td) as Uint8Array)
}
/**
* Performs a block hash to block number lookup.
*/
async hashToNumber(blockHash: Uint8Array): Promise<bigint> {
const value = await this.get(DBTarget.HashToNumber, { blockHash })
return bytesToBigInt(value)
}
/**
* Performs a block number to block hash lookup.
*/
async numberToHash(blockNumber: bigint): Promise<Uint8Array> {
if (blockNumber < BigInt(0)) {
throw new NotFoundError(blockNumber)
}
return this.get(DBTarget.NumberToHash, { blockNumber })
}
/**
* Fetches a key from the db. If `opts.cache` is specified
* it first tries to load from cache, and on cache miss will
* try to put the fetched item on cache afterwards.
*/
async get(dbOperationTarget: DBTarget, key?: DatabaseKey): Promise<any> {
const dbGetOperation = DBOp.get(dbOperationTarget, key)
const cacheString = dbGetOperation.cacheString
const dbKey = dbGetOperation.baseDBOp.key
const dbOpts = dbGetOperation.baseDBOp
if (cacheString !== undefined) {
if (this._cache[cacheString] === undefined) {
throw new Error(`Invalid cache: ${cacheString}`)
}
let value = this._cache[cacheString].get(dbKey)
if (!value) {
value = ((await this._db.get(dbKey)) as Uint8Array | null) ?? undefined
if (value !== undefined) {
// TODO: Check if this comment is still valid
// Always cast values to Uint8Array since db sometimes returns values as `Buffer`
this._cache[cacheString].set(dbKey, Uint8Array.from(value))
}
}
return value
}
return this._db.get(dbKey /* , dbOpts */)
}
/**
* Performs a batch operation on db.
*/
async batch(ops: DBOp[]) {
const convertedOps: DBOpData[] = ops.map((op) => op.baseDBOp)
// update the current cache for each operation
ops.map((op) => op.updateCache(this._cache))
return this._db.batch(convertedOps as any)
}
}