Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(core-p2p): improve peer block header check #2719

Merged
merged 3 commits into from
Jun 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions __tests__/integration/core-p2p/mocks/core-container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ jest.mock("@arkecosystem/core-container", () => {
return {
getStore: () => ({
getLastBlock: () => genesisBlock,
getLastBlocks: () => [genesisBlock],
getLastHeight: () => genesisBlock.data.height,
cacheTransactions: jest.fn().mockImplementation(txs => ({ notAdded: txs, added: [] })),
removeCachedTransactionIds: jest.fn().mockReturnValue(undefined),
Expand Down
21 changes: 14 additions & 7 deletions packages/core-p2p/src/peer-verifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ export class PeerVerifier {
return undefined;
}

const claimedHeight = Number(claimedState.header.height);
const ourHeight: number = await this.ourHeight();
const claimedHeight: number = Number(claimedState.header.height);
const ourHeight: number = this.ourHeight();
if (await this.weHavePeersHighestBlock(claimedState, ourHeight)) {
// Case3 and Case5
return new PeerVerificationResult(ourHeight, claimedHeight, claimedHeight);
Expand Down Expand Up @@ -118,6 +118,17 @@ export class PeerVerifier {
}

try {
const ownBlock: Interfaces.IBlock = app
.resolvePlugin<State.IStateService>("state")
.getStore()
.getLastBlocks()
.find(block => block.data.height === blockHeader.height);

// Use shortcut to prevent expensive crypto if the block header equals our own.
if (ownBlock && JSON.stringify(ownBlock.getHeader()) === JSON.stringify(blockHeader)) {
return true;
}

const claimedBlock: Interfaces.IBlock = Blocks.BlockFactory.fromData(blockHeader);
if (claimedBlock.verifySignature()) {
return true;
Expand All @@ -137,11 +148,7 @@ export class PeerVerifier {
}
}

/**
* Retrieve the height of the highest block in our chain.
* @return {Number} chain height
*/
private async ourHeight(): Promise<number> {
private ourHeight(): number {
const height: number = app
.resolvePlugin<State.IStateService>("state")
.getStore()
Expand Down