Skip to content

Commit

Permalink
Clean up changes
Browse files Browse the repository at this point in the history
  • Loading branch information
dapplion committed Nov 16, 2022
1 parent 3d86a02 commit 46f58a4
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 30 deletions.
2 changes: 1 addition & 1 deletion packages/beacon-node/src/api/impl/lodestar/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export function getLodestarApi({
return (chain as BeaconChain)["blockProcessor"].jobQueue.getItems().map((item) => {
const [blocks, opts] = item.args;
return {
blockSlots: blocks.map((block) => block.message.slot),
blockSlots: blocks.map(({block}) => block.message.slot),
jobOpts: opts,
addedTimeMs: item.addedTimeMs,
};
Expand Down
7 changes: 4 additions & 3 deletions packages/beacon-node/src/chain/blocks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export async function processBlocks(
const {postStates, proposerBalanceDeltas, segmentExecStatus} = await verifyBlocksInEpoch.call(
this,
parentBlock,
relevantBlocks,
relevantBlocks.map(({block}) => block),
opts
);

Expand All @@ -86,8 +86,9 @@ export async function processBlocks(

const {executionStatuses} = segmentExecStatus;
const fullyVerifiedBlocks = relevantBlocks.map(
(block, i): FullyVerifiedBlock => ({
({block, blobs}, i): FullyVerifiedBlock => ({
block,
blobs,
postState: postStates[i],
parentBlockSlot: parentSlots[i],
executionStatus: executionStatuses[i],
Expand All @@ -104,7 +105,7 @@ export async function processBlocks(
}
} catch (e) {
// above functions should only throw BlockError
const err = getBlockError(e, blocks[0]);
const err = getBlockError(e, blocks[0].block);

// TODO: De-duplicate with logic above
// ChainEvent.errorBlock
Expand Down
10 changes: 5 additions & 5 deletions packages/beacon-node/src/chain/blocks/verifyBlock.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {CachedBeaconStateAllForks, computeEpochAtSlot} from "@lodestar/state-transition";
import {bellatrix} from "@lodestar/types";
import {allForks, bellatrix} from "@lodestar/types";
import {toHexString} from "@chainsafe/ssz";
import {ProtoBlock} from "@lodestar/fork-choice";
import {IChainForkConfig} from "@lodestar/config";
Expand All @@ -8,7 +8,7 @@ import {BlockError, BlockErrorCode} from "../errors/index.js";
import {BlockProcessOpts} from "../options.js";
import {RegenCaller} from "../regen/index.js";
import type {BeaconChain} from "../chain.js";
import {BlockImport, ImportBlockOpts} from "./types.js";
import {ImportBlockOpts} from "./types.js";
import {POS_PANDA_MERGE_TRANSITION_BANNER} from "./utils/pandaMergeTransitionBanner.js";
import {verifyBlocksStateTransitionOnly} from "./verifyBlocksStateTransitionOnly.js";
import {verifyBlocksSignatures} from "./verifyBlocksSignatures.js";
Expand All @@ -28,7 +28,7 @@ import {verifyBlocksExecutionPayload, SegmentExecStatus} from "./verifyBlocksExe
export async function verifyBlocksInEpoch(
this: BeaconChain,
parentBlock: ProtoBlock,
blocks: BlockImport[],
blocks: allForks.SignedBeaconBlock[],
opts: BlockProcessOpts & ImportBlockOpts
): Promise<{
postStates: CachedBeaconStateAllForks[];
Expand All @@ -39,12 +39,12 @@ export async function verifyBlocksInEpoch(
throw Error("Empty partiallyVerifiedBlocks");
}

const block0 = blocks[0].block;
const block0 = blocks[0];
const block0Epoch = computeEpochAtSlot(block0.message.slot);

// Ensure all blocks are in the same epoch
for (let i = 1; i < blocks.length; i++) {
const blockSlot = blocks[i].block.message.slot;
const blockSlot = blocks[i].message.slot;
if (block0Epoch !== computeEpochAtSlot(blockSlot)) {
throw Error(`Block ${i} slot ${blockSlot} not in same epoch ${block0Epoch}`);
}
Expand Down
1 change: 1 addition & 0 deletions packages/beacon-node/src/chain/errors/blobsSidecarError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export type BlobsSidecarErrorType =
| {code: BlobsSidecarErrorCode.INVALID_KZG; kzgIdx: number}
| {code: BlobsSidecarErrorCode.INVALID_KZG_TXS}
| {code: BlobsSidecarErrorCode.INCORRECT_SLOT; blockSlot: Slot; blobSlot: Slot}
| {code: BlobsSidecarErrorCode.INVALID_BLOB; blobIdx: number}
| {code: BlobsSidecarErrorCode.INVALID_KZG_PROOF};

export class BlobsSidecarError extends GossipActionError<BlobsSidecarErrorType> {}
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import {CachedBeaconStateAllForks, stateTransition} from "@lodestar/state-transition";
import {
CachedBeaconStateAllForks,
DataAvailableStatus,
ExecutionPayloadStatus,
stateTransition,
} from "@lodestar/state-transition";
import {allForks, Root} from "@lodestar/types";
import {ZERO_HASH} from "../../constants/index.js";
import {IMetrics} from "../../metrics/index.js";
Expand All @@ -22,6 +27,9 @@ export function computeNewStateRoot(
const postState = stateTransition(
state,
blockEmptySig,
// ExecutionPayloadStatus.valid: Assume payload valid, it has been produced by a trusted EL
// DataAvailableStatus.available: Assume the blobs to be available, have just been produced by trusted EL
{executionPayloadStatus: ExecutionPayloadStatus.valid, dataAvailableStatus: DataAvailableStatus.available},
// verifyStateRoot: false | the root in the block is zero-ed, it's being computed here
// verifyProposer: false | as the block signature is zero-ed
// verifySignatures: false | since the data to assemble the block is trusted
Expand Down
7 changes: 7 additions & 0 deletions packages/beacon-node/src/chain/regen/regen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import {
CachedBeaconStateAllForks,
computeEpochAtSlot,
computeStartSlotAtEpoch,
DataAvailableStatus,
ExecutionPayloadStatus,
processSlots,
stateTransition,
} from "@lodestar/state-transition";
Expand Down Expand Up @@ -172,6 +174,11 @@ export class StateRegenerator implements IStateRegenerator {
state = stateTransition(
state,
block,
// Replay previously imported blocks, assume valid and available
{
executionPayloadStatus: ExecutionPayloadStatus.valid,
dataAvailableStatus: DataAvailableStatus.available,
},
{
verifyStateRoot: false,
verifyProposer: false,
Expand Down
59 changes: 40 additions & 19 deletions packages/beacon-node/src/chain/validation/blobsSidecar.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import {IChainForkConfig} from "@lodestar/config";
import bls from "@chainsafe/bls";
import {CoordType} from "@chainsafe/bls/types";
import {eip4844} from "@lodestar/types";
import {bytesToBigInt} from "@lodestar/utils";
import {FIELD_ELEMENTS_PER_BLOB} from "@lodestar/params";
import {verifyKzgCommitmentsAgainstTransactions} from "@lodestar/state-transition";
import {IBeaconChain} from "../interface.js";
import {BlobsSidecarError, BlobsSidecarErrorCode} from "../errors/blobsSidecarError.js";
import {GossipAction} from "../errors/gossipValidation.js";

const BLS_MODULUS = BigInt("52435875175126190479447740508185965837690552500527637822603658699938581184513");

export async function validateGossipBlobsSidecar(
config: IChainForkConfig,
chain: IBeaconChain,
signedBlock: eip4844.SignedBeaconBlock,
blobsSidecar: eip4844.BlobsSidecar
): Promise<void> {
Expand All @@ -18,7 +20,7 @@ export async function validateGossipBlobsSidecar(
// -- i.e. all(bls.KeyValidate(commitment) for commitment in block.body.blob_kzg_commitments)
const {blobKzgCommitments} = block.body;
for (let i = 0; i < blobKzgCommitments.length; i++) {
if (!bls.keyValidate(blobKzgCommitments[i])) {
if (!blsKeyValidate(blobKzgCommitments[i])) {
throw new BlobsSidecarError(GossipAction.REJECT, {code: BlobsSidecarErrorCode.INVALID_KZG, kzgIdx: i});
}
}
Expand All @@ -42,27 +44,46 @@ export async function validateGossipBlobsSidecar(
}

// [REJECT] the sidecar.blobs are all well formatted, i.e. the BLSFieldElement in valid range (x < BLS_MODULUS).
TODO;
for (let i = 0; blobsSidecar.blobs.length; i++) {
if (!blobIsValidRange(blobsSidecar.blobs[i])) {
throw new BlobsSidecarError(GossipAction.REJECT, {code: BlobsSidecarErrorCode.INVALID_BLOB, blobIdx: i});
}
}

// [REJECT] The KZG proof is a correctly encoded compressed BLS G1 Point
// -- i.e. bls.KeyValidate(blobs_sidecar.kzg_aggregated_proof)
if (!bls.KeyValidate(blobsSidecar.kzgAggregatedProof)) {
// -- i.e. blsKeyValidate(blobs_sidecar.kzg_aggregated_proof)
if (!blsKeyValidate(blobsSidecar.kzgAggregatedProof)) {
throw new BlobsSidecarError(GossipAction.REJECT, {code: BlobsSidecarErrorCode.INVALID_KZG_PROOF});
}
}

type Result<T> = {ok: true; result: T} | {ok: false; error: Error};

function rustOk(): Result<string>;

function Ok<T>(result: T): Result<T> {
return {ok: true, result};
/**
* From https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-04#section-2.5
* KeyValidate = valid, non-identity point that is in the correct subgroup
*/
function blsKeyValidate(g1Point: Uint8Array): boolean {
try {
bls.PublicKey.fromBytes(g1Point, CoordType.jacobian, true);
return true;
} catch (e) {
return false;
}
}

function okUser(): Result<number> {
const res = rustOk();
if (!res.ok) return res;
const resStr = res.result;
/**
* ```
* Blob = new ByteVectorType(BYTES_PER_FIELD_ELEMENT * FIELD_ELEMENTS_PER_BLOB);
* ```
* Check that each FIELD_ELEMENT as a uint256 < BLS_MODULUS
*/
function blobIsValidRange(blob: eip4844.Blob): boolean {
for (let i = 0; i < FIELD_ELEMENTS_PER_BLOB; i++) {
const fieldElement = blob.subarray(i, i * 32);
const fieldElementBN = bytesToBigInt(fieldElement, "be");
if (fieldElementBN >= BLS_MODULUS) {
return false;
}
}

return Ok(parseInt(resStr));
return true;
}
2 changes: 1 addition & 1 deletion packages/beacon-node/src/network/gossip/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ export function getGossipHandlers(modules: ValidatorFnsModules, options: GossipH

// Validate block + blob. Then forward, then handle both
await validateBeaconBlock(beaconBlock, topic.fork, peerIdStr);
await validateGossipBlobsSidecar(config, chain, beaconBlock, blobsSidecar);
await validateGossipBlobsSidecar(beaconBlock, blobsSidecar);
handleValidBeaconBlock({block: beaconBlock, blobs: blobsSidecar}, peerIdStr, seenTimestampSec);
},

Expand Down

0 comments on commit 46f58a4

Please sign in to comment.