@lodestar/state-transition 1.41.0-dev.bb273175f2 → 1.41.0-dev.be5acbb8f7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/lib/block/index.d.ts +3 -3
  2. package/lib/block/processExecutionPayloadBid.d.ts +1 -1
  3. package/lib/block/processExecutionPayloadEnvelope.d.ts +5 -2
  4. package/lib/block/processExecutionPayloadEnvelope.d.ts.map +1 -1
  5. package/lib/block/processExecutionPayloadEnvelope.js +20 -14
  6. package/lib/block/processExecutionPayloadEnvelope.js.map +1 -1
  7. package/lib/block/processPayloadAttestation.d.ts +1 -1
  8. package/lib/epoch/index.d.ts +1 -1
  9. package/lib/epoch/processBuilderPendingPayments.d.ts +1 -1
  10. package/lib/testUtils/cache.d.ts +2 -0
  11. package/lib/testUtils/cache.d.ts.map +1 -0
  12. package/lib/testUtils/cache.js +7 -0
  13. package/lib/testUtils/cache.js.map +1 -0
  14. package/lib/testUtils/index.d.ts +6 -0
  15. package/lib/testUtils/index.d.ts.map +1 -0
  16. package/lib/testUtils/index.js +6 -0
  17. package/lib/testUtils/index.js.map +1 -0
  18. package/lib/testUtils/infura.d.ts +3 -0
  19. package/lib/testUtils/infura.d.ts.map +1 -0
  20. package/lib/testUtils/infura.js +8 -0
  21. package/lib/testUtils/infura.js.map +1 -0
  22. package/lib/testUtils/interop.d.ts +2 -0
  23. package/lib/testUtils/interop.d.ts.map +1 -0
  24. package/lib/testUtils/interop.js +24 -0
  25. package/lib/testUtils/interop.js.map +1 -0
  26. package/lib/testUtils/params.d.ts +18 -0
  27. package/lib/testUtils/params.d.ts.map +1 -0
  28. package/lib/testUtils/params.js +20 -0
  29. package/lib/testUtils/params.js.map +1 -0
  30. package/lib/testUtils/state.d.ts +20 -0
  31. package/lib/testUtils/state.d.ts.map +1 -0
  32. package/lib/testUtils/state.js +78 -0
  33. package/lib/testUtils/state.js.map +1 -0
  34. package/lib/testUtils/testFileCache.d.ts +17 -0
  35. package/lib/testUtils/testFileCache.d.ts.map +1 -0
  36. package/lib/testUtils/testFileCache.js +96 -0
  37. package/lib/testUtils/testFileCache.js.map +1 -0
  38. package/lib/testUtils/util.d.ts +50 -0
  39. package/lib/testUtils/util.d.ts.map +1 -0
  40. package/lib/testUtils/util.js +329 -0
  41. package/lib/testUtils/util.js.map +1 -0
  42. package/package.json +12 -7
  43. package/src/block/index.ts +3 -3
  44. package/src/block/isValidIndexedPayloadAttestation.ts +2 -2
  45. package/src/block/processAttestationsAltair.ts +1 -1
  46. package/src/block/processExecutionPayloadBid.ts +4 -4
  47. package/src/block/processExecutionPayloadEnvelope.ts +35 -21
  48. package/src/block/processOperations.ts +1 -1
  49. package/src/block/processPayloadAttestation.ts +2 -2
  50. package/src/block/processWithdrawals.ts +1 -1
  51. package/src/epoch/index.ts +1 -1
  52. package/src/epoch/processBuilderPendingPayments.ts +2 -2
  53. package/src/testUtils/cache.ts +8 -0
  54. package/src/testUtils/index.ts +5 -0
  55. package/src/testUtils/infura.ts +10 -0
  56. package/src/testUtils/interop.ts +29 -0
  57. package/src/testUtils/params.ts +23 -0
  58. package/src/testUtils/state.ts +110 -0
  59. package/src/testUtils/testFileCache.ts +127 -0
  60. package/src/testUtils/util.ts +429 -0
@@ -0,0 +1,29 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import {fromHexString, toHexString} from "@chainsafe/ssz";
4
+ import {interopSecretKey} from "../index.js";
5
+ import {testCachePath} from "./cache.js";
6
+
7
+ const interopPubkeysCachedPath = path.join(testCachePath, "interop-pubkeys.json");
8
+
9
+ export function interopPubkeysCached(validatorCount: number): Uint8Array[] {
10
+ fs.mkdirSync(path.dirname(interopPubkeysCachedPath), {recursive: true});
11
+
12
+ const cachedKeysHex = fs.existsSync(interopPubkeysCachedPath)
13
+ ? (JSON.parse(fs.readFileSync(interopPubkeysCachedPath, "utf8")) as string[])
14
+ : ([] as string[]);
15
+
16
+ const keys = cachedKeysHex.slice(0, validatorCount).map((hex) => fromHexString(hex));
17
+
18
+ if (cachedKeysHex.length < validatorCount) {
19
+ for (let i = cachedKeysHex.length; i < validatorCount; i++) {
20
+ const sk = interopSecretKey(i);
21
+ const pk = sk.toPublicKey().toBytes();
22
+ keys.push(pk);
23
+ }
24
+ const keysHex = keys.map((pk) => toHexString(pk));
25
+ fs.writeFileSync(interopPubkeysCachedPath, JSON.stringify(keysHex, null, 2));
26
+ }
27
+
28
+ return keys;
29
+ }
@@ -0,0 +1,23 @@
1
+ // DON'T MODIFY OR FORMAT THIS FILE
2
+ // USE FOR GA CACHE
3
+
4
+ export const phase0State = {
5
+ network: "mainnet" as const,
6
+ epoch: 58758, // Pre-altair fork
7
+ };
8
+
9
+ export const altairState = {
10
+ network: "mainnet" as const,
11
+ epoch: 81889, // Post altair fork
12
+ };
13
+
14
+ export const capellaState = {
15
+ network: "mainnet" as const,
16
+ epoch: 217614, // Post capella fork
17
+ };
18
+
19
+ export const rangeSyncTest = {
20
+ network: "mainnet" as const,
21
+ startSlot: 3766816, // Post altair, first slot in epoch 117713
22
+ endSlot: 3766847, // 3766816 + 31, all blocks in same epoch
23
+ };
@@ -0,0 +1,110 @@
1
+ import {ChainForkConfig, createBeaconConfig} from "@lodestar/config";
2
+ import {config, config as minimalConfig} from "@lodestar/config/default";
3
+ import {
4
+ EPOCHS_PER_HISTORICAL_VECTOR,
5
+ EPOCHS_PER_SLASHINGS_VECTOR,
6
+ GENESIS_EPOCH,
7
+ GENESIS_SLOT,
8
+ SLOTS_PER_HISTORICAL_ROOT,
9
+ } from "@lodestar/params";
10
+ import {phase0, ssz} from "@lodestar/types";
11
+ import {EpochCacheOpts} from "../cache/epochCache.js";
12
+ import {BeaconStateCache} from "../cache/stateCache.js";
13
+ import {ZERO_HASH} from "../constants/index.js";
14
+ import {
15
+ BeaconStateAllForks,
16
+ BeaconStatePhase0,
17
+ CachedBeaconStateAllForks,
18
+ createCachedBeaconState,
19
+ createPubkeyCache,
20
+ } from "../index.js";
21
+ import {newZeroedArray} from "../util/index.js";
22
+
23
+ /**
24
+ * Copy of BeaconState, but all fields are marked optional to allow for swapping out variables as needed.
25
+ */
26
+ type TestBeaconState = Partial<phase0.BeaconState>;
27
+
28
+ /**
29
+ * Generate beaconState, by default it will use the initial state defined when the `ChainStart` log is emitted.
30
+ * NOTE: All fields can be overridden through `opts`.
31
+ * @param {TestBeaconState} opts
32
+ * @returns {BeaconState}
33
+ */
34
+ export function generateState(opts?: TestBeaconState): BeaconStatePhase0 {
35
+ return ssz.phase0.BeaconState.toViewDU({
36
+ genesisTime: Math.floor(Date.now() / 1000),
37
+ genesisValidatorsRoot: ZERO_HASH,
38
+ slot: GENESIS_SLOT,
39
+ fork: {
40
+ previousVersion: config.GENESIS_FORK_VERSION,
41
+ currentVersion: config.GENESIS_FORK_VERSION,
42
+ epoch: GENESIS_EPOCH,
43
+ },
44
+ latestBlockHeader: {
45
+ slot: 0,
46
+ proposerIndex: 0,
47
+ parentRoot: Buffer.alloc(32),
48
+ stateRoot: Buffer.alloc(32),
49
+ bodyRoot: ssz.phase0.BeaconBlockBody.hashTreeRoot(ssz.phase0.BeaconBlockBody.defaultValue()),
50
+ },
51
+ blockRoots: Array.from({length: SLOTS_PER_HISTORICAL_ROOT}, () => ZERO_HASH),
52
+ stateRoots: Array.from({length: SLOTS_PER_HISTORICAL_ROOT}, () => ZERO_HASH),
53
+ historicalRoots: [],
54
+ eth1Data: {
55
+ depositRoot: Buffer.alloc(32),
56
+ blockHash: Buffer.alloc(32),
57
+ depositCount: 0,
58
+ },
59
+ eth1DataVotes: [],
60
+ eth1DepositIndex: 0,
61
+ validators: [],
62
+ balances: [],
63
+ randaoMixes: Array.from({length: EPOCHS_PER_HISTORICAL_VECTOR}, () => ZERO_HASH),
64
+ slashings: newZeroedArray(EPOCHS_PER_SLASHINGS_VECTOR),
65
+ previousEpochAttestations: [],
66
+ currentEpochAttestations: [],
67
+ justificationBits: ssz.phase0.JustificationBits.defaultValue(),
68
+ previousJustifiedCheckpoint: {
69
+ epoch: GENESIS_EPOCH,
70
+ root: ZERO_HASH,
71
+ },
72
+ currentJustifiedCheckpoint: {
73
+ epoch: GENESIS_EPOCH,
74
+ root: ZERO_HASH,
75
+ },
76
+ finalizedCheckpoint: {
77
+ epoch: GENESIS_EPOCH,
78
+ root: ZERO_HASH,
79
+ },
80
+ ...opts,
81
+ });
82
+ }
83
+
84
+ export function generateCachedState(
85
+ config: ChainForkConfig = minimalConfig,
86
+ opts: TestBeaconState = {}
87
+ ): CachedBeaconStateAllForks {
88
+ const state = generateState(opts);
89
+ return createCachedBeaconState(state, {
90
+ config: createBeaconConfig(config, state.genesisValidatorsRoot),
91
+ // This is a test state, there's no need to have a global shared cache of keys
92
+ pubkeyCache: createPubkeyCache(),
93
+ });
94
+ }
95
+
96
+ export function createCachedBeaconStateTest<T extends BeaconStateAllForks>(
97
+ state: T,
98
+ configCustom: ChainForkConfig = config,
99
+ opts?: EpochCacheOpts
100
+ ): T & BeaconStateCache {
101
+ return createCachedBeaconState<T>(
102
+ state,
103
+ {
104
+ config: createBeaconConfig(configCustom, state.genesisValidatorsRoot),
105
+ // This is a test state, there's no need to have a global shared cache of keys
106
+ pubkeyCache: createPubkeyCache(),
107
+ },
108
+ opts
109
+ );
110
+ }
@@ -0,0 +1,127 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import {getClient} from "@lodestar/api";
4
+ import {ChainForkConfig, createChainForkConfig} from "@lodestar/config";
5
+ import {NetworkName, networksChainConfig} from "@lodestar/config/networks";
6
+ import {SignedBeaconBlock} from "@lodestar/types";
7
+ import {fetch} from "@lodestar/utils";
8
+ import {CachedBeaconStateAllForks} from "../index.js";
9
+ import {testCachePath} from "./cache.js";
10
+ import {getInfuraBeaconUrl} from "./infura.js";
11
+ import {createCachedBeaconStateTest} from "./state.js";
12
+
13
+ /**
14
+ * Full link example:
15
+ * ```
16
+ * https://github.com/dapplion/ethereum-consensus-test-data/releases/download/v0.1.0/block_mainnet_3766821.ssz
17
+ * ``` */
18
+ const TEST_FILES_BASE_URL = "https://github.com/dapplion/ethereum-consensus-test-data/releases/download/v0.1.0";
19
+
20
+ /**
21
+ * Create a network config from known network params
22
+ */
23
+ export function getNetworkConfig(network: NetworkName): ChainForkConfig {
24
+ const configNetwork = networksChainConfig[network];
25
+ return createChainForkConfig(configNetwork);
26
+ }
27
+
28
+ /**
29
+ * Download a state from Infura. Caches states in local fs by network and slot to only download once.
30
+ */
31
+ export async function getNetworkCachedState(
32
+ network: NetworkName,
33
+ slot: number,
34
+ timeout?: number
35
+ ): Promise<CachedBeaconStateAllForks> {
36
+ const config = getNetworkConfig(network);
37
+ const fileId = `state_${network}_${slot}.ssz`;
38
+
39
+ const filepath = path.join(testCachePath, fileId);
40
+
41
+ if (fs.existsSync(filepath)) {
42
+ const stateSsz = fs.readFileSync(filepath);
43
+ return createCachedBeaconStateTest(config.getForkTypes(slot).BeaconState.deserializeToViewDU(stateSsz), config);
44
+ }
45
+
46
+ const stateSsz = await tryEach([
47
+ () => downloadTestFile(fileId),
48
+ () => {
49
+ const client = getClient(
50
+ {baseUrl: getInfuraBeaconUrl(network), globalInit: {timeoutMs: timeout ?? 300_000}},
51
+ {config}
52
+ );
53
+ return client.debug.getStateV2({stateId: slot}).then((r) => {
54
+ return r.ssz();
55
+ });
56
+ },
57
+ ]);
58
+
59
+ fs.writeFileSync(filepath, stateSsz);
60
+ return createCachedBeaconStateTest(config.getForkTypes(slot).BeaconState.deserializeToViewDU(stateSsz), config);
61
+ }
62
+
63
+ /**
64
+ * Download a state from Infura. Caches states in local fs by network and slot to only download once.
65
+ */
66
+ export async function getNetworkCachedBlock(
67
+ network: NetworkName,
68
+ slot: number,
69
+ timeout?: number
70
+ ): Promise<SignedBeaconBlock> {
71
+ const config = getNetworkConfig(network);
72
+ const fileId = `block_${network}_${slot}.ssz`;
73
+
74
+ const filepath = path.join(testCachePath, fileId);
75
+
76
+ if (fs.existsSync(filepath)) {
77
+ const blockSsz = fs.readFileSync(filepath);
78
+ return config.getForkTypes(slot).SignedBeaconBlock.deserialize(blockSsz);
79
+ }
80
+
81
+ const blockSsz = await tryEach([
82
+ () => downloadTestFile(fileId),
83
+ async () => {
84
+ const client = getClient(
85
+ {baseUrl: getInfuraBeaconUrl(network), globalInit: {timeoutMs: timeout ?? 300_000}},
86
+ {config}
87
+ );
88
+
89
+ return (await client.beacon.getBlockV2({blockId: slot})).ssz();
90
+ },
91
+ ]);
92
+
93
+ fs.writeFileSync(filepath, blockSsz);
94
+ return config.getForkTypes(slot).SignedBeaconBlock.deserialize(blockSsz);
95
+ }
96
+
97
+ async function downloadTestFile(fileId: string): Promise<Uint8Array> {
98
+ const fileUrl = `${TEST_FILES_BASE_URL}/${fileId}`;
99
+ // biome-ignore lint/suspicious/noConsole: We explicity need to log to console
100
+ console.log(`Downloading file ${fileUrl}`);
101
+
102
+ try {
103
+ const res = await fetch(fileUrl);
104
+ if (!res.ok) {
105
+ throw new Error(`Error downloading ${fileUrl}: ${res.status} ${res.statusText}`);
106
+ }
107
+ return new Uint8Array(await res.arrayBuffer());
108
+ } catch (e) {
109
+ const error = e as Error;
110
+ error.message = `Error downloading ${fileUrl}: ${error.message}`;
111
+ throw error;
112
+ }
113
+ }
114
+
115
+ async function tryEach<T>(promises: (() => Promise<T>)[]): Promise<T> {
116
+ const errors: Error[] = [];
117
+
118
+ for (let i = 0; i < promises.length; i++) {
119
+ try {
120
+ return await promises[i]();
121
+ } catch (e) {
122
+ errors.push(e as Error);
123
+ }
124
+ }
125
+
126
+ throw Error(errors.map((e, i) => `Error[${i}] ${e.message}`).join("\n"));
127
+ }