Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
Maddiaa0 committed Dec 13, 2024
1 parent bfaa838 commit 99efbb9
Show file tree
Hide file tree
Showing 13 changed files with 200 additions and 57 deletions.
1 change: 1 addition & 0 deletions yarn-project/aztec-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
"@aztec/circuit-types": "workspace:^",
"@aztec/circuits.js": "workspace:^",
"@aztec/ethereum": "workspace:^",
"@aztec/epoch-cache": "workspace:^",
"@aztec/foundation": "workspace:^",
"@aztec/kv-store": "workspace:^",
"@aztec/merkle-tree": "workspace:^",
Expand Down
6 changes: 5 additions & 1 deletion yarn-project/aztec-node/src/aztec-node/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import {
type PublicDataTreeLeafPreimage,
} from '@aztec/circuits.js';
import { computePublicDataTreeLeafSlot } from '@aztec/circuits.js/hash';
import { createEpochCache } from '@aztec/epoch-cache';
import { type L1ContractAddresses, createEthereumChain } from '@aztec/ethereum';
import { type ContractArtifact } from '@aztec/foundation/abi';
import { AztecAddress } from '@aztec/foundation/aztec-address';
Expand Down Expand Up @@ -167,20 +168,23 @@ export class AztecNodeService implements AztecNode, Traceable {
log.warn(`Aztec node is accepting fake proofs`);
}

const epochCache = await createEpochCache(config, config.l1Contracts.rollupAddress);

// create the tx pool and the p2p client, which will need the l2 block source
const p2pClient = await createP2PClient(
P2PClientType.Full,
config,
archiver,
proofVerifier,
worldStateSynchronizer,
epochCache,
telemetry,
);

// start both and wait for them to sync from the block source
await Promise.all([p2pClient.start(), worldStateSynchronizer.start()]);

const validatorClient = await createValidatorClient(config, rollupAddress, { p2pClient, telemetry, dateProvider });
const validatorClient = createValidatorClient(config, { p2pClient, telemetry, dateProvider, epochCache });

// now create the sequencer
const sequencer = config.disableValidator
Expand Down
8 changes: 8 additions & 0 deletions yarn-project/epoch-cache/src/factory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { type EthAddress } from '@aztec/foundation/eth-address';

import { type EpochCacheConfig } from './config.js';
import { EpochCache } from './epoch_cache.js';

export function createEpochCache(config: EpochCacheConfig, rollupAddress: EthAddress): Promise<EpochCache> {
return EpochCache.create(rollupAddress, config);
}
1 change: 1 addition & 0 deletions yarn-project/epoch-cache/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './epoch_cache.js';
export * from './config.js';
export * from './factory.js';
1 change: 1 addition & 0 deletions yarn-project/p2p/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
"dependencies": {
"@aztec/circuit-types": "workspace:^",
"@aztec/circuits.js": "workspace:^",
"@aztec/epoch-cache": "workspace:^",
"@aztec/foundation": "workspace:^",
"@aztec/kv-store": "workspace:^",
"@aztec/telemetry-client": "workspace:^",
Expand Down
3 changes: 3 additions & 0 deletions yarn-project/p2p/src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
P2PClientType,
type WorldStateSynchronizer,
} from '@aztec/circuit-types';
import { type EpochCache } from '@aztec/epoch-cache';
import { createLogger } from '@aztec/foundation/log';
import { type AztecKVStore } from '@aztec/kv-store';
import { type DataStoreConfig } from '@aztec/kv-store/config';
Expand Down Expand Up @@ -39,6 +40,7 @@ export const createP2PClient = async <T extends P2PClientType>(
l2BlockSource: L2BlockSource,
proofVerifier: ClientProtocolCircuitVerifier,
worldStateSynchronizer: WorldStateSynchronizer,
epochCache: EpochCache,
telemetry: TelemetryClient = new NoopTelemetryClient(),
deps: P2PClientDeps<T> = {},
) => {
Expand Down Expand Up @@ -75,6 +77,7 @@ export const createP2PClient = async <T extends P2PClientType>(
peerId,
mempools,
l2BlockSource,
epochCache,
proofVerifier,
worldStateSynchronizer,
store,
Expand Down
3 changes: 3 additions & 0 deletions yarn-project/p2p/src/mocks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type Tx,
type WorldStateSynchronizer,
} from '@aztec/circuit-types';
import { type EpochCache } from '@aztec/epoch-cache';
import { type DataStoreConfig } from '@aztec/kv-store/config';
import { openTmpStore } from '@aztec/kv-store/lmdb';
import { type TelemetryClient } from '@aztec/telemetry-client';
Expand Down Expand Up @@ -101,6 +102,7 @@ export async function createTestLibP2PService<T extends P2PClientType>(
boostrapAddrs: string[] = [],
l2BlockSource: L2BlockSource,
worldStateSynchronizer: WorldStateSynchronizer,
epochCache: EpochCache,
mempools: MemPools<T>,
telemetry: TelemetryClient,
port: number = 0,
Expand Down Expand Up @@ -132,6 +134,7 @@ export async function createTestLibP2PService<T extends P2PClientType>(
discoveryService,
mempools,
l2BlockSource,
epochCache,
proofVerifier,
worldStateSynchronizer,
telemetry,
Expand Down
159 changes: 154 additions & 5 deletions yarn-project/p2p/src/services/libp2p/libp2p_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
} from '@aztec/circuit-types';
import { P2PClientType } from '@aztec/circuit-types';
import { Fr } from '@aztec/circuits.js';
import { type EpochCache } from '@aztec/epoch-cache';
import { createLogger } from '@aztec/foundation/log';
import { SerialQueue } from '@aztec/foundation/queue';
import { RunningPromise } from '@aztec/foundation/running-promise';
Expand Down Expand Up @@ -102,6 +103,7 @@ export class LibP2PService<T extends P2PClientType> extends WithTracer implement
private peerDiscoveryService: PeerDiscoveryService,
private mempools: MemPools<T>,
private l2BlockSource: L2BlockSource,
private epochCache: EpochCache,
private proofVerifier: ClientProtocolCircuitVerifier,
private worldStateSynchronizer: WorldStateSynchronizer,
private telemetry: TelemetryClient,
Expand Down Expand Up @@ -153,7 +155,17 @@ export class LibP2PService<T extends P2PClientType> extends WithTracer implement
}

// Add p2p topic validators
this.node.services.pubsub.topicValidators.set(Tx.p2pTopic, this.validatePropagatedTxFromMessage.bind(this));
// As they are stored within a kv pair, there is no need to register them conditionally
// based on the client type
const topicValidators = {
[Tx.p2pTopic]: this.validatePropagatedTxFromMessage.bind(this),
[BlockAttestation.p2pTopic]: this.validatePropagatedAttestationFromMessage.bind(this),
[BlockProposal.p2pTopic]: this.validatePropagatedBlockFromMessage.bind(this),
[EpochProofQuote.p2pTopic]: this.validatePropagatedEpochProofQuoteFromMessage.bind(this),
};
for (const [topic, validator] of Object.entries(topicValidators)) {
this.node.services.pubsub.topicValidators.set(topic, validator);
}

// add GossipSub listener
this.node.services.pubsub.addEventListener('gossipsub:message', async e => {
Expand Down Expand Up @@ -215,6 +227,7 @@ export class LibP2PService<T extends P2PClientType> extends WithTracer implement
peerId: PeerId,
mempools: MemPools<T>,
l2BlockSource: L2BlockSource,
epochCache: EpochCache,
proofVerifier: ClientProtocolCircuitVerifier,
worldStateSynchronizer: WorldStateSynchronizer,
store: AztecKVStore,
Expand Down Expand Up @@ -329,6 +342,7 @@ export class LibP2PService<T extends P2PClientType> extends WithTracer implement
peerDiscoveryService,
mempools,
l2BlockSource,
epochCache,
proofVerifier,
worldStateSynchronizer,
telemetry,
Expand Down Expand Up @@ -537,6 +551,12 @@ export class LibP2PService<T extends P2PClientType> extends WithTracer implement
return true;
}

/**
* Validate a tx from a peer.
* @param propagationSource - The peer ID of the peer that sent the tx.
* @param msg - The tx message.
* @returns True if the tx is valid, false otherwise.
*/
private async validatePropagatedTxFromMessage(
propagationSource: PeerId,
msg: Message,
Expand All @@ -551,11 +571,59 @@ export class LibP2PService<T extends P2PClientType> extends WithTracer implement
}

/**
* Validate a tx that has been propagated from a peer.
* @param tx - The tx to validate.
* @param peerId - The peer ID of the peer that sent the tx.
* @returns True if the tx is valid, false otherwise.
* Validate an attestation from a peer.
* @param propagationSource - The peer ID of the peer that sent the attestation.
* @param msg - The attestation message.
* @returns True if the attestation is valid, false otherwise.
*/
private async validatePropagatedAttestationFromMessage(
propagationSource: PeerId,
msg: Message,
): Promise<TopicValidatorResult> {
const attestation = BlockAttestation.fromBuffer(Buffer.from(msg.data));
const isValid = await this.validateAttestation(propagationSource, attestation);
this.logger.trace(`validatePropagatedAttestation: ${isValid}`, {
[Attributes.SLOT_NUMBER]: attestation.payload.header.globalVariables.slotNumber.toString(),
[Attributes.P2P_ID]: propagationSource.toString(),
});
return isValid ? TopicValidatorResult.Accept : TopicValidatorResult.Reject;
}

/**
* Validate a block proposal from a peer.
* @param propagationSource - The peer ID of the peer that sent the block.
* @param msg - The block proposal message.
* @returns True if the block proposal is valid, false otherwise.
*/
private async validatePropagatedBlockFromMessage(
propagationSource: PeerId,
msg: Message,
): Promise<TopicValidatorResult> {
const block = BlockProposal.fromBuffer(Buffer.from(msg.data));
const isValid = await this.validateBlockProposal(propagationSource, block);
this.logger.trace(`validatePropagatedBlock: ${isValid}`, {
[Attributes.SLOT_NUMBER]: block.payload.header.globalVariables.slotNumber.toString(),
[Attributes.P2P_ID]: propagationSource.toString(),
});
return isValid ? TopicValidatorResult.Accept : TopicValidatorResult.Reject;
}

/**
* Validate an epoch proof quote from a peer.
* @param propagationSource - The peer ID of the peer that sent the epoch proof quote.
* @param msg - The epoch proof quote message.
* @returns True if the epoch proof quote is valid, false otherwise.
*/
private validatePropagatedEpochProofQuoteFromMessage(propagationSource: PeerId, msg: Message): TopicValidatorResult {
const epochProofQuote = EpochProofQuote.fromBuffer(Buffer.from(msg.data));
const isValid = this.validateEpochProofQuote(propagationSource, epochProofQuote);
this.logger.trace(`validatePropagatedEpochProofQuote: ${isValid}`, {
[Attributes.EPOCH_NUMBER]: epochProofQuote.payload.epochToProve.toString(),
[Attributes.P2P_ID]: propagationSource.toString(),
});
return isValid ? TopicValidatorResult.Accept : TopicValidatorResult.Reject;
}

@trackSpan('Libp2pService.validatePropagatedTx', tx => ({
[Attributes.TX_HASH]: tx.getTxHash().toString(),
}))
Expand Down Expand Up @@ -687,6 +755,87 @@ export class LibP2PService<T extends P2PClientType> extends WithTracer implement
return true;
}

/**
* Validate an attestation.
*
* @param attestation - The attestation to validate.
* @returns True if the attestation is valid, false otherwise.
*/
@trackSpan('Libp2pService.validateAttestation', (_peerId, attestation) => ({
[Attributes.SLOT_NUMBER]: attestation.payload.header.globalVariables.slotNumber.toString(),
}))
public async validateAttestation(peerId: PeerId, attestation: BlockAttestation): Promise<boolean> {
const { currentSlot, nextSlot } = await this.epochCache.getProposerInCurrentOrNextSlot();

// Check that the attestation is for the current or next slot
const slotNumberBigInt = attestation.payload.header.globalVariables.slotNumber.toBigInt();
if (slotNumberBigInt !== currentSlot && slotNumberBigInt !== nextSlot) {
this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
return false;
}

// Check that the attestation is from the somebody in the committee
const attester = attestation.getSender();
if (!(await this.epochCache.isInCommittee(attester))) {
this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
return false;
}

return true;
}

/**
* Validate a block proposal.
*
* @param block - The block proposal to validate.
* @returns True if the block proposal is valid, false otherwise.
*/
@trackSpan('Libp2pService.validateBlockProposal', (_peerId, block) => ({
[Attributes.SLOT_NUMBER]: block.payload.header.globalVariables.slotNumber.toString(),
}))
public async validateBlockProposal(peerId: PeerId, block: BlockProposal): Promise<boolean> {
const { currentProposer, nextProposer, currentSlot, nextSlot } =
await this.epochCache.getProposerInCurrentOrNextSlot();

// Check that the attestation is for the current or next slot
const slotNumberBigInt = block.payload.header.globalVariables.slotNumber.toBigInt();
if (slotNumberBigInt !== currentSlot && slotNumberBigInt !== nextSlot) {
this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
return false;
}

// Check that the block proposal is from the current or next proposer
const proposer = block.getSender();
if (!proposer.equals(currentProposer) && !proposer.equals(nextProposer)) {
this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
return false;
}

return true;
}

/**
* Validate an epoch proof quote.
*
* @param epochProofQuote - The epoch proof quote to validate.
* @returns True if the epoch proof quote is valid, false otherwise.
*/
@trackSpan('Libp2pService.validateEpochProofQuote', (_peerId, epochProofQuote) => ({
[Attributes.EPOCH_NUMBER]: epochProofQuote.payload.epochToProve.toString(),
}))
public validateEpochProofQuote(peerId: PeerId, epochProofQuote: EpochProofQuote): boolean {
const { epoch } = this.epochCache.getEpochAndSlotNow();

// Check that the epoch proof quote is for the current epoch
const epochToProve = epochProofQuote.payload.epochToProve;
if (epochToProve !== epoch && epochToProve !== epoch - 1n) {
this.peerManager.penalizePeer(peerId, PeerErrorSeverity.HighToleranceError);
return false;
}

return true;
}

public getPeerScore(peerId: PeerId): number {
return this.node.services.pubsub.score.score(peerId.toString());
}
Expand Down
Loading

0 comments on commit 99efbb9

Please sign in to comment.