-
Notifications
You must be signed in to change notification settings - Fork 760
/
statelessVerkleStateManager.ts
707 lines (607 loc) · 23.9 KB
/
statelessVerkleStateManager.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
import { VerkleAccessedStateType } from '@ethereumjs/common'
import {
Account,
KECCAK256_NULL,
KECCAK256_NULL_S,
VERKLE_CODE_CHUNK_SIZE,
VerkleLeafType,
bigIntToBytes,
bytesToHex,
createPartialAccount,
createPartialAccountFromRLP,
decodeVerkleLeafBasicData,
encodeVerkleLeafBasicData,
getVerkleKey,
getVerkleStem,
getVerkleTreeKeyForCodeChunk,
getVerkleTreeKeyForStorageSlot,
hexToBytes,
padToEven,
setLengthLeft,
setLengthRight,
short,
toBytes,
} from '@ethereumjs/util'
import debugDefault from 'debug'
import { keccak256 } from 'ethereum-cryptography/keccak.js'
import { OriginalStorageCache } from './cache/index.js'
import { modifyAccountFields } from './util.js'
import type { Caches } from './cache/index.js'
import type { StatelessVerkleStateManagerOpts, VerkleState } from './index.js'
import type { MerkleStateManager } from './merkleStateManager.js'
import type {
AccountFields,
Common,
StateManagerInterface,
VerkleAccessWitnessInterface,
VerkleAccessedStateWithAddress,
} from '@ethereumjs/common'
import type {
Address,
PrefixedHexString,
VerkleCrypto,
VerkleExecutionWitness,
VerkleProof,
} from '@ethereumjs/util'
import type { Debugger } from 'debug'
const PUSH_OFFSET = 95
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const PUSH1 = PUSH_OFFSET + 1
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const PUSH32 = PUSH_OFFSET + 32
const ZEROVALUE = '0x0000000000000000000000000000000000000000000000000000000000000000'
/**
* Stateless Verkle StateManager implementation for the VM.
*
* Experimental.
*
* This State Manager enables stateless block execution by building a
* temporary (1-block) state from the verkle block witness.
* The Stateless Verkle State Manager then uses that populated state
* to fetch data requested by the the VM.
*
*/
export class StatelessVerkleStateManager implements StateManagerInterface {
_cachedStateRoot?: Uint8Array
originalStorageCache: OriginalStorageCache
verkleCrypto: VerkleCrypto
protected _caches?: Caches
protected _debug: Debugger
public readonly common: Common
/**
* StateManager is run in DEBUG mode (default: false)
* Taken from DEBUG environment variable
*
* Safeguards on this._debug() calls are added for
* performance reasons to avoid string literal evaluation
* @hidden
*/
protected readonly DEBUG: boolean = false
private _blockNum = BigInt(0)
private _executionWitness?: VerkleExecutionWitness
private _proof: VerkleProof | undefined
// State along execution (should update)
private _state: VerkleState = {}
// Post-state provided from the executionWitness.
// Should not update. Used for comparing our computed post-state with the canonical one.
private _postState: VerkleState = {}
private _preState: VerkleState = {}
// Checkpointing
private _checkpoints: VerkleState[] = []
private keccakFunction: Function
/**
* Instantiate the StateManager interface.
*/
constructor(opts: StatelessVerkleStateManagerOpts) {
this.originalStorageCache = new OriginalStorageCache(this.getStorage.bind(this))
this._caches = opts.caches
if (opts.common.isActivatedEIP(6800) === false) {
throw new Error('EIP-6800 required for stateless verkle state management')
}
if (opts.common.customCrypto.verkle === undefined) {
throw new Error('verkle crypto required')
}
this.common = opts.common
this.keccakFunction = opts.common.customCrypto.keccak256 ?? keccak256
this.verkleCrypto = opts.common.customCrypto.verkle
this._debug = debugDefault('statemanager:verkle:stateless')
// Skip DEBUG calls unless 'ethjs' included in environmental DEBUG variables
// Additional window check is to prevent vite browser bundling (and potentially other) to break
this.DEBUG =
typeof window === 'undefined' ? (process?.env?.DEBUG?.includes('ethjs') ?? false) : false
}
async getTransitionStateRoot(_: MerkleStateManager, __: Uint8Array): Promise<Uint8Array> {
throw Error('not implemented')
}
public initVerkleExecutionWitness(
blockNum: bigint,
executionWitness?: VerkleExecutionWitness | null,
) {
this._blockNum = blockNum
if (executionWitness === null || executionWitness === undefined) {
const errorMsg = `Invalid executionWitness=${executionWitness} for initVerkleExecutionWitness`
this._debug(errorMsg)
throw Error(errorMsg)
}
this._executionWitness = executionWitness
this._proof = executionWitness.verkleProof
// Populate the pre-state and post-state from the executionWitness
const preStateRaw = executionWitness.stateDiff.flatMap(({ stem, suffixDiffs }) => {
const suffixDiffPairs = suffixDiffs.map(({ currentValue, suffix }) => {
const key = `${stem}${padToEven(Number(suffix).toString(16))}`
return {
[key]: currentValue,
}
})
return suffixDiffPairs
})
const preState = preStateRaw.reduce((prevValue, currentValue) => {
const acc = { ...prevValue, ...currentValue }
return acc
}, {})
this._state = preState
// also maintain a separate preState unaffected by any changes in _state
this._preState = preStateRaw.reduce((prevValue, currentValue) => {
const acc = { ...prevValue, ...currentValue }
return acc
}, {})
const postStateRaw = executionWitness.stateDiff.flatMap(({ stem, suffixDiffs }) => {
const suffixDiffPairs = suffixDiffs.map(({ newValue, suffix }) => {
const key = `${stem}${padToEven(Number(suffix).toString(16))}` as PrefixedHexString
// A postState value of null means there was no change from the preState.
// In this implementation, we therefore replace null with the preState.
const value = newValue ?? this._state[key]
return {
[key]: value,
}
})
return suffixDiffPairs
})
const postState = postStateRaw.reduce((prevValue, currentValue) => {
const acc = { ...prevValue, ...currentValue }
return acc
}, {})
this._postState = postState
this._debug('initVerkleExecutionWitness preState', this._state)
this._debug('initVerkleExecutionWitness postState', this._postState)
}
async checkChunkWitnessPresent(address: Address, codeOffset: number) {
const chunkId = codeOffset / VERKLE_CODE_CHUNK_SIZE
const chunkKey = bytesToHex(
await getVerkleTreeKeyForCodeChunk(address, chunkId, this.verkleCrypto),
)
return this._state[chunkKey] !== undefined
}
/**
* Copies the current instance of the `StateManager`
* at the last fully committed point, i.e. as if all current
* checkpoints were reverted.
*/
shallowCopy(downlevelCaches = true): StatelessVerkleStateManager {
const stateManager = new StatelessVerkleStateManager({
caches: this._caches?.shallowCopy(downlevelCaches),
common: this.common,
})
return stateManager
}
/**
* Adds `value` to the state trie as code, and sets `codeHash` on the account
* corresponding to `address` to reference this.
* @param address - Address of the `account` to add the `code` for
* @param value - The value of the `code`
*/
async putCode(address: Address, value: Uint8Array): Promise<void> {
if (this.DEBUG) {
this._debug(`putCode address=${address.toString()} value=${short(value)}`)
}
this._caches?.code?.put(address, value)
const codeHash = keccak256(value)
if (KECCAK256_NULL === codeHash) {
// If the code hash is the null hash, no code has to be stored
return
}
if ((await this.getAccount(address)) === undefined) {
await this.putAccount(address, new Account())
}
await this.modifyAccountFields(address, { codeHash })
}
/**
* Gets the code corresponding to the provided `address`.
* @param address - Address to get the `code` for
* @returns {Promise<Uint8Array>} - Resolves with the code corresponding to the provided address.
* Returns an empty `Uint8Array` if the account has no associated code.
*/
async getCode(address: Address): Promise<Uint8Array> {
if (this.DEBUG) {
this._debug(`getCode address=${address.toString()}`)
}
const elem = this._caches?.code?.get(address)
if (elem !== undefined) {
return elem.code ?? new Uint8Array(0)
}
const account = await this.getAccount(address)
if (!account) {
return new Uint8Array(0)
}
if (!account.isContract()) {
return new Uint8Array(0)
}
// allocate the code and copy onto it from the available witness chunks
const codeSize = account.codeSize
// allocate enough to fit the last chunk
const accessedCode = new Uint8Array(codeSize + VERKLE_CODE_CHUNK_SIZE)
const chunks = Math.floor(codeSize / VERKLE_CODE_CHUNK_SIZE) + 1
for (let chunkId = 0; chunkId < chunks; chunkId++) {
const chunkKey = bytesToHex(
await getVerkleTreeKeyForCodeChunk(address, chunkId, this.verkleCrypto),
)
const codeChunk = this._state[chunkKey]
if (codeChunk === null) {
const errorMsg = `Invalid access to a non existent code chunk with chunkKey=${chunkKey}`
this.DEBUG && this._debug(errorMsg)
throw Error(errorMsg)
}
const codeOffset = chunkId * VERKLE_CODE_CHUNK_SIZE
// if code chunk was accessed as per the provided witnesses copy it over
if (codeChunk !== undefined) {
// actual code starts from index 1 in chunk, 0th index is if there are any push data bytes
const actualChunk = hexToBytes(codeChunk).slice(1)
accessedCode.set(actualChunk, codeOffset)
} else {
// else fill this unaccessed segment with invalid opcode since the evm execution shouldn't
// end up here
accessedCode.fill(0xfe, codeOffset, VERKLE_CODE_CHUNK_SIZE)
}
}
// Return accessedCode where only accessed code has been copied
const contactCode = accessedCode.slice(0, codeSize)
this._caches?.code?.put(address, contactCode)
return contactCode
}
async getCodeSize(address: Address): Promise<number> {
const elem = this._caches?.account?.get(address)
if (elem !== undefined) {
const account =
elem.accountRLP !== undefined ? createPartialAccountFromRLP(elem.accountRLP) : undefined
if (account === undefined) {
const errorMsg = `account=${account} in cache`
this.DEBUG && this._debug(errorMsg)
throw Error(errorMsg)
}
return account.codeSize
}
// load the account basic fields and codeSize should be in it
const account = await this.getAccount(address)
if (account === undefined) {
return 0
}
return account.codeSize
}
/**
* Gets the storage value associated with the provided `address` and `key`. This method returns
* the shortest representation of the stored value.
* @param address - Address of the account to get the storage for
* @param key - Key in the account's storage to get the value for. Must be 32 bytes long.
* @returns {Promise<Uint8Array>} - The storage value for the account
* corresponding to the provided address at the provided key.
* If this does not exist an empty `Uint8Array` is returned.
*/
async getStorage(address: Address, key: Uint8Array): Promise<Uint8Array> {
const value = this._caches?.storage?.get(address, key)
if (value !== undefined) {
return value
}
const storageKey = await getVerkleTreeKeyForStorageSlot(
address,
BigInt(bytesToHex(key)),
this.verkleCrypto,
)
const storageValue = toBytes(this._state[bytesToHex(storageKey)])
this._caches?.storage?.put(address, key, storageValue ?? hexToBytes('0x80'))
return storageValue
}
/**
* Adds value to the state for the `account`
* corresponding to `address` at the provided `key`.
* @param address - Address to set a storage value for
* @param key - Key to set the value at. Must be 32 bytes long.
* @param value - Value to set at `key` for account corresponding to `address`. Cannot be more than 32 bytes. Leading zeros are stripped. If it is a empty or filled with zeros, deletes the value.
*/
async putStorage(address: Address, key: Uint8Array, value: Uint8Array): Promise<void> {
if (this._caches?.storage !== undefined) {
this._caches.storage.put(address, key, value)
} else {
// TODO: Consider refactoring this in a writeContractStorage function? Like in stateManager.ts
const storageKey = await getVerkleTreeKeyForStorageSlot(
address,
BigInt(bytesToHex(key)),
this.verkleCrypto,
)
this._state[bytesToHex(storageKey)] = bytesToHex(setLengthRight(value, 32))
}
}
// Note from Gabriel: Clearing storage is not actually not possible in Verkle.
// This is because the storage keys are scattered throughout the verkle tree.
/**
* Clears all storage entries for the account corresponding to `address`.
* @param address - Address to clear the storage of
*/
async clearStorage(address: Address): Promise<void> {
const stem = getVerkleStem(this.verkleCrypto, address, 0)
const codeHashKey = getVerkleKey(stem, VerkleLeafType.CodeHash)
this._caches?.storage?.clearStorage(address)
// Update codeHash to `c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470`
this._state[bytesToHex(codeHashKey)] = KECCAK256_NULL_S
}
async getAccount(address: Address): Promise<Account | undefined> {
const elem = this._caches?.account?.get(address)
if (elem !== undefined) {
return elem.accountRLP !== undefined
? createPartialAccountFromRLP(elem.accountRLP)
: undefined
}
const stem = getVerkleStem(this.verkleCrypto, address, 0)
const basicDataKey = getVerkleKey(stem, VerkleLeafType.BasicData)
const codeHashKey = getVerkleKey(stem, VerkleLeafType.CodeHash)
const basicDataRaw = this._state[bytesToHex(basicDataKey)]
const codeHashRaw = this._state[bytesToHex(codeHashKey)]
// check if the account didn't exist if any of the basic keys have null
if (basicDataRaw === null || codeHashRaw === null) {
// check any of the other key shouldn't have string input available as this account didn't exist
if (typeof basicDataRaw === `string` || typeof codeHashRaw === 'string') {
const errorMsg = `Invalid witness for a non existing address=${address} stem=${bytesToHex(
stem,
)}`
this.DEBUG && this._debug(errorMsg)
throw Error(errorMsg)
} else {
return undefined
}
}
// check if codehash is correct 32 bytes prefixed hex string
if (codeHashRaw !== undefined && codeHashRaw !== null && codeHashRaw.length !== 66) {
const errorMsg = `Invalid codeHashRaw=${codeHashRaw} for address=${address} chunkKey=${bytesToHex(
codeHashKey,
)}`
this.DEBUG && this._debug(errorMsg)
throw Error(errorMsg)
}
if (basicDataRaw === undefined && codeHashRaw === undefined) {
const errorMsg = `No witness bundled for address=${address} stem=${bytesToHex(stem)}`
this.DEBUG && this._debug(errorMsg)
throw Error(errorMsg)
}
const { version, balance, nonce, codeSize } = decodeVerkleLeafBasicData(
hexToBytes(basicDataRaw),
)
const account = createPartialAccount({
version,
balance,
nonce,
codeHash: typeof codeHashRaw === 'string' ? hexToBytes(codeHashRaw) : null,
// if codeSizeRaw is null, it means account didn't exist or it was EOA either way codeSize is 0
// if codeSizeRaw is undefined, then we pass in null which in our context of partial account means
// not specified
codeSize,
storageRoot: null,
})
if (this.DEBUG) {
this._debug(`getAccount address=${address.toString()} stem=${short(stem)}`)
}
this._caches?.account?.put(address, account, true)
return account
}
async putAccount(address: Address, account: Account): Promise<void> {
if (this.DEBUG) {
this._debug(`putAccount address=${address.toString()}`)
}
if (this._caches?.account === undefined) {
const stem = getVerkleStem(this.verkleCrypto, address, 0)
const basicDataKey = getVerkleKey(stem, VerkleLeafType.BasicData)
const basicDataBytes = encodeVerkleLeafBasicData(account)
this._state[bytesToHex(basicDataKey)] = bytesToHex(basicDataBytes)
} else {
if (account !== undefined) {
this._caches?.account?.put(address, account, true)
} else {
this._caches?.account?.del(address)
}
}
}
/**
* Deletes an account from state under the provided `address`.
* @param address - Address of the account which should be deleted
*/
async deleteAccount(address: Address) {
if (this.DEBUG) {
this._debug(`Delete account ${address}`)
}
this._caches?.deleteAccount(address)
}
async modifyAccountFields(address: Address, accountFields: AccountFields): Promise<void> {
await modifyAccountFields(this, address, accountFields)
}
// Verifies that the witness post-state matches the computed post-state
verifyPostState(accessWitness: VerkleAccessWitnessInterface): Promise<boolean> {
// track what all chunks were accessed so as to compare in the end if any chunks were missed
// in access while comparing against the provided poststate in the execution witness
const accessedChunks = new Map<string, boolean>()
// switch to false if postVerify fails
let postFailures = 0
for (const accessedState of accessWitness?.accesses() ?? []) {
const { address, type } = accessedState
let extraMeta = ''
if (accessedState.type === VerkleAccessedStateType.Code) {
extraMeta = `codeOffset=${accessedState.codeOffset}`
} else if (accessedState.type === VerkleAccessedStateType.Storage) {
extraMeta = `slot=${accessedState.slot}`
}
const { chunkKey } = accessedState
accessedChunks.set(chunkKey, true)
const computedValue = this.getComputedValue(accessedState) ?? this._preState[chunkKey]
if (computedValue === undefined) {
this.DEBUG &&
this._debug(
`Block accesses missing in canonical address=${address} type=${type} ${extraMeta} chunkKey=${chunkKey}`,
)
postFailures++
continue
}
let canonicalValue: PrefixedHexString | null | undefined = this._postState[chunkKey]
if (canonicalValue === undefined) {
this.DEBUG &&
this._debug(
`Block accesses missing in canonical address=${address} type=${type} ${extraMeta} chunkKey=${chunkKey}`,
)
postFailures++
continue
}
// if the access type is code, then we can't match the first byte because since the computed value
// doesn't has the first byte for push data since previous chunk code itself might not be available
if (accessedState.type === VerkleAccessedStateType.Code) {
// computedValue = computedValue !== null ? `0x${computedValue.slice(4)}` : null
canonicalValue = canonicalValue !== null ? `0x${canonicalValue.slice(4)}` : null
} else if (
accessedState.type === VerkleAccessedStateType.Storage &&
canonicalValue === null &&
computedValue === ZEROVALUE
) {
canonicalValue = ZEROVALUE
}
if (computedValue !== canonicalValue) {
this.DEBUG &&
this._debug(
`Block accesses mismatch address=${address} type=${type} ${extraMeta} chunkKey=${chunkKey}`,
)
this.DEBUG && this._debug(`expected=${canonicalValue}`)
this.DEBUG && this._debug(`computed=${computedValue}`)
postFailures++
}
}
for (const canChunkKey of Object.keys(this._postState)) {
if (accessedChunks.get(canChunkKey) === undefined) {
this.DEBUG && this._debug(`Missing chunk access for canChunkKey=${canChunkKey}`)
postFailures++
}
}
const verifyPassed = postFailures === 0
this.DEBUG &&
this._debug(`verifyPostState verifyPassed=${verifyPassed} postFailures=${postFailures}`)
// This is async so the stateful variant can use the same interface method
return Promise.resolve(verifyPassed)
}
getComputedValue(accessedState: VerkleAccessedStateWithAddress): PrefixedHexString | null {
const { address, type } = accessedState
switch (type) {
case VerkleAccessedStateType.BasicData: {
const encodedAccount = this._caches?.account?.get(address)?.accountRLP
if (encodedAccount === undefined) {
return null
}
const basicDataBytes = encodeVerkleLeafBasicData(
createPartialAccountFromRLP(encodedAccount),
)
return bytesToHex(basicDataBytes)
}
case VerkleAccessedStateType.CodeHash: {
const encodedAccount = this._caches?.account?.get(address)?.accountRLP
if (encodedAccount === undefined) {
return null
}
return bytesToHex(createPartialAccountFromRLP(encodedAccount).codeHash)
}
case VerkleAccessedStateType.Code: {
const { codeOffset } = accessedState
const code = this._caches?.code?.get(address)?.code
if (code === undefined) {
return null
}
// we can only compare the actual code because to compare the first byte would
// be very tricky and impossible in certain scenarios like when the previous code chunk
// was not accessed and hence not even provided in the witness
return bytesToHex(
setLengthRight(
code.slice(codeOffset, codeOffset + VERKLE_CODE_CHUNK_SIZE),
VERKLE_CODE_CHUNK_SIZE,
),
)
}
case VerkleAccessedStateType.Storage: {
const { slot } = accessedState
const key = setLengthLeft(bigIntToBytes(slot), 32)
const storage = this._caches?.storage?.get(address, key)
if (storage === undefined) {
return null
}
return bytesToHex(setLengthLeft(storage, 32))
}
}
}
/**
* Checkpoints the current state of the StateManager instance.
* State changes that follow can then be committed by calling
* `commit` or `reverted` by calling rollback.
*/
async checkpoint(): Promise<void> {
this._checkpoints.push(this._state)
this._caches?.checkpoint()
}
/**
* Commits the current change-set to the instance since the
* last call to checkpoint.
*/
async commit(): Promise<void> {
this._checkpoints.pop()
this._caches?.commit()
}
// TODO
async hasStateRoot(_: Uint8Array): Promise<boolean> {
return true
}
/**
* Reverts the current change-set to the instance since the
* last call to checkpoint.
*/
async revert(): Promise<void> {
// setup trie checkpointing
this._checkpoints.pop()
this._caches?.revert()
}
/**
* Writes all cache items to the trie
*/
async flush(): Promise<void> {}
/**
* Gets the cache state root.
* This is used to persist the stateRoot between blocks, so that blocks can retrieve the stateRoot of the parent block.
* This is required to verify and prove verkle execution witnesses.
* @returns {Promise<Uint8Array>} - Returns the cached state root
*/
async getStateRoot(): Promise<Uint8Array> {
if (this._cachedStateRoot === undefined) {
throw new Error('Cache state root missing')
}
return this._cachedStateRoot
}
/**
* Sets the cache state root.
* This is used to persist the stateRoot between blocks, so that blocks can retrieve the stateRoot of the parent block.
* @param stateRoot - The stateRoot to set
*/
async setStateRoot(stateRoot: Uint8Array): Promise<void> {
this._cachedStateRoot = stateRoot
}
/**
* Clears all underlying caches
*/
clearCaches() {
this._caches?.clear()
}
// TODO: Removing this causes a Kaustinen6 test in client to fail
// Seems to point to a more general (non-severe) bug and can likely be fixed
// by having the `statelessVerkle` config option more properly set by the
// test for the check in the VM execution to call into this method
generateCanonicalGenesis(_initState: any): Promise<void> {
return Promise.resolve()
}
}