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

Delegate without valid hash onion is unable to forge - Closes #5793 #5802

Merged
merged 5 commits into from Sep 14, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 3 additions & 3 deletions elements/lisk-bft/src/bft.ts
Expand Up @@ -15,16 +15,16 @@
import { codec } from '@liskhq/lisk-codec';
import * as assert from 'assert';
import { EventEmitter } from 'events';

import {
BlockHeader,
Chain,
CONSENSUS_STATE_FINALIZED_HEIGHT_KEY,
getValidators,
StateStore,
} from '@liskhq/lisk-chain';
import { EVENT_BFT_FINALIZED_HEIGHT_CHANGED, FinalityManager } from './finality_manager';
import * as forkChoiceRule from './fork_choice_rule';
import { BFTPersistedValues, ForkStatus, StateStore } from './types';
import { BFTPersistedValues, ForkStatus } from './types';

export const EVENT_BFT_BLOCK_FINALIZED = 'EVENT_BFT_BLOCK_FINALIZED';

Expand Down Expand Up @@ -96,7 +96,7 @@ export class BFT extends EventEmitter {

public async verifyBlockHeader(blockHeader: BlockHeader, stateStore: StateStore): Promise<void> {
const isCompliant = await this.isBFTProtocolCompliant(blockHeader, stateStore);
const reward = this._chain.calculateReward(blockHeader.height);
const reward = this._chain.calculateExpectedReward(blockHeader, stateStore);
const expectedReward = isCompliant ? reward : reward / BigInt(4);
if (blockHeader.reward !== expectedReward) {
throw new Error(
Expand Down
3 changes: 1 addition & 2 deletions elements/lisk-bft/src/finality_manager.ts
Expand Up @@ -14,14 +14,13 @@

import { codec } from '@liskhq/lisk-codec';
import { getAddressFromPublicKey } from '@liskhq/lisk-cryptography';
import { BlockHeader, Chain, getValidators } from '@liskhq/lisk-chain';
import { BlockHeader, Chain, getValidators, StateStore } from '@liskhq/lisk-chain';
import * as assert from 'assert';
import * as Debug from 'debug';
import { EventEmitter } from 'events';
import { dataStructures } from '@liskhq/lisk-utils';
import { BFT_ROUND_THRESHOLD } from './constant';
import {
StateStore,
BFTChainDisjointError,
BFTForkChoiceRuleError,
BFTInvalidAttributeError,
Expand Down
20 changes: 1 addition & 19 deletions elements/lisk-bft/src/types.ts
Expand Up @@ -13,7 +13,7 @@
*/
/* eslint-disable max-classes-per-file */

import { BlockHeader, Account } from '@liskhq/lisk-chain';
import { BlockHeader } from '@liskhq/lisk-chain';

export enum ForkStatus {
IDENTICAL_BLOCK = 1,
Expand Down Expand Up @@ -55,21 +55,3 @@ export interface BFTPersistedValues {
}

export type BlockHeaderWithReceivedAt = BlockHeader & { receivedAt?: number };

export interface StateStore {
readonly account: {
readonly get: (primaryValue: Buffer) => Promise<Account>;
readonly getUpdated: () => ReadonlyArray<Account>;
// eslint-disable-next-line @typescript-eslint/method-signature-style
set(key: Buffer, value: Account): void;
};
readonly consensus: {
readonly get: (key: string) => Promise<Buffer | undefined>;
readonly set: (key: string, value: Buffer) => void;
};
readonly chain: {
readonly get: (key: string) => Promise<Buffer | undefined>;
readonly set: (key: string, value: Buffer) => void;
readonly lastBlockHeaders: ReadonlyArray<BlockHeader>;
};
}
Expand Up @@ -20,6 +20,7 @@ import {
validatorsSchema,
Validator,
BlockHeader,
StateStore,
} from '@liskhq/lisk-chain';
import { getAddressFromPublicKey } from '@liskhq/lisk-cryptography';
import * as scenario4DelegatesMissedSlots from '../bft_specs/4_delegates_missed_slots.json';
Expand All @@ -44,7 +45,7 @@ const bftScenarios = [
scenario11DelegatesPartialSwitch,
];

const preVotesAndCommits = async (stateStore: StateStoreMock) => {
const preVotesAndCommits = async (stateStore: StateStore) => {
const delegateLedgerBuffer = await stateStore.consensus.get(CONSENSUS_STATE_VALIDATOR_LEDGER_KEY);

const delegateLedger = codec.decode<VotingLedger>(
Expand All @@ -71,7 +72,7 @@ const preVotesAndCommits = async (stateStore: StateStoreMock) => {

describe('FinalityManager', () => {
let chainStub: Chain;
let stateStore: StateStoreMock;
let stateStore: StateStore;

describe('addBlockHeader', () => {
for (const scenario of bftScenarios) {
Expand All @@ -98,7 +99,7 @@ describe('FinalityManager', () => {
threshold: Math.floor((scenario.config.activeDelegates * 2) / 3) + 1,
});

stateStore = new StateStoreMock();
stateStore = (new StateStoreMock() as unknown) as StateStore;

const blockHeaders = (scenario.testCases as any).map((tc: any) =>
convertHeader(tc.input.blockHeader),
Expand Down Expand Up @@ -134,7 +135,7 @@ describe('FinalityManager', () => {
CONSENSUS_STATE_VALIDATORS_KEY,
codec.encode(validatorsSchema, { validators: validatorsMap.values() }),
);
stateStore.chain.lastBlockHeaders = filteredBlockHeaders;
(stateStore.chain as any).lastBlockHeaders = filteredBlockHeaders;

// Act
await finalityManager.addBlockHeader(
Expand Down
Expand Up @@ -18,6 +18,7 @@ import {
Validator,
CONSENSUS_STATE_VALIDATORS_KEY,
validatorsSchema,
StateStore,
} from '@liskhq/lisk-chain';
import { codec } from '@liskhq/lisk-codec';
import * as invalidBlockHeaderSpec from '../bft_specs/bft_invalid_block_headers.json';
Expand All @@ -28,7 +29,7 @@ import { convertHeader } from '../fixtures/blocks';

describe('FinalityManager', () => {
describe('addBlockHeader', () => {
let stateStore: StateStoreMock;
let stateStore: StateStore;
let chainStub: Chain;

beforeEach(() => {
Expand All @@ -43,7 +44,7 @@ describe('FinalityManager', () => {
},
numberOfValidators: 103,
} as unknown) as Chain;
stateStore = new StateStoreMock();
stateStore = (new StateStoreMock() as unknown) as StateStore;
});

invalidBlockHeaderSpec.testCases.forEach(testCase => {
Expand All @@ -62,7 +63,7 @@ describe('FinalityManager', () => {
codec.encode(validatorsSchema, { validators: validatorsMap.values() }),
);
// Arrange
stateStore.chain.lastBlockHeaders = testCase.config.blockHeaders.map(bh =>
(stateStore.chain as any).lastBlockHeaders = testCase.config.blockHeaders.map(bh =>
convertHeader(bh),
);

Expand Down
31 changes: 16 additions & 15 deletions elements/lisk-bft/test/unit/bft.spec.ts
Expand Up @@ -20,6 +20,7 @@ import {
CONSENSUS_STATE_FINALIZED_HEIGHT_KEY,
CONSENSUS_STATE_VALIDATORS_KEY,
validatorsSchema,
StateStore,
} from '@liskhq/lisk-chain';
import { createFakeBlockHeader } from '../fixtures/blocks';
import {
Expand Down Expand Up @@ -59,7 +60,7 @@ describe('bft', () => {
beforeEach(() => {
lastBlock = createFakeBlockHeader({ height: 1, version: 2 });
chainStub = ({
calculateReward: jest.fn(),
calculateExpectedReward: jest.fn(),
slots: {
getSlotNumber: jest.fn(),
isWithinTimeslot: jest.fn(),
Expand Down Expand Up @@ -96,7 +97,7 @@ describe('bft', () => {

describe('#init', () => {
it('should initialize finality manager', async () => {
const stateStore = new StateStoreMock();
const stateStore = (new StateStoreMock() as unknown) as StateStore;
const bft = new BFT(bftParams);

await bft.init(stateStore);
Expand All @@ -106,7 +107,7 @@ describe('bft', () => {

it('should set the finality height to the value from chain state', async () => {
const finalizedHeight = 5;
const stateStore = new StateStoreMock(
const stateStore = (new StateStoreMock(
[],
{
[CONSENSUS_STATE_FINALIZED_HEIGHT_KEY]: codec.encode(BFTFinalizedHeightCodecSchema, {
Expand All @@ -119,7 +120,7 @@ describe('bft', () => {
}),
},
{ lastBlockHeaders: [lastBlock] },
);
) as unknown) as StateStore;
const bft = new BFT(bftParams);

await bft.init(stateStore);
Expand All @@ -131,7 +132,7 @@ describe('bft', () => {
describe('#verifyBlockHeader', () => {
let bft: BFT;
let blocks: BlockHeader[];
let stateStore: StateStoreMock;
let stateStore: StateStore;

beforeEach(async () => {
// Arrange
Expand All @@ -143,7 +144,7 @@ describe('bft', () => {
});

bft = new BFT(bftParams);
stateStore = new StateStoreMock(
stateStore = (new StateStoreMock(
[],
{
[CONSENSUS_STATE_FINALIZED_HEIGHT_KEY]: codec.encode(BFTFinalizedHeightCodecSchema, {
Expand All @@ -158,13 +159,13 @@ describe('bft', () => {
}),
},
{ lastBlockHeaders: blocks },
);
) as unknown) as StateStore;
await bft.init(stateStore);
});

describe('when BFT protocol is followed', () => {
it('should resolve without error', async () => {
(chainStub.calculateReward as jest.Mock).mockReturnValue(BigInt(500000000));
(chainStub.calculateExpectedReward as jest.Mock).mockReturnValue(BigInt(500000000));
const blockHeader = {
height: 102,
reward: BigInt(500000000),
Expand All @@ -183,7 +184,7 @@ describe('bft', () => {

describe('when BFT protocol is not followed', () => {
it('should throw an error if reward is not deducted', async () => {
(chainStub.calculateReward as jest.Mock).mockReturnValue(BigInt(500000000));
(chainStub.calculateExpectedReward as jest.Mock).mockReturnValue(BigInt(500000000));
const blockHeader = {
height: 203,
reward: BigInt(500000000),
Expand Down Expand Up @@ -222,10 +223,10 @@ describe('bft', () => {
};

let bft: BFT;
let stateStore: StateStoreMock;
let stateStore: StateStore;

beforeEach(async () => {
stateStore = new StateStoreMock(
stateStore = (new StateStoreMock(
[],
{
[CONSENSUS_STATE_FINALIZED_HEIGHT_KEY]: codec.encode(BFTFinalizedHeightCodecSchema, {
Expand All @@ -246,7 +247,7 @@ describe('bft', () => {
}),
},
{ lastBlockHeaders: [lastBlock] },
);
) as unknown) as StateStore;

bft = new BFT(bftParams);
await bft.init(stateStore);
Expand All @@ -272,7 +273,7 @@ describe('bft', () => {
describe('#isBFTProtocolCompliant', () => {
let bft: BFT;
let blocks: BlockHeader[];
let stateStore: StateStoreMock;
let stateStore: StateStore;

beforeEach(async () => {
// Arrange
Expand All @@ -284,7 +285,7 @@ describe('bft', () => {
});

bft = new BFT(bftParams);
stateStore = new StateStoreMock(
stateStore = (new StateStoreMock(
[],
{
[CONSENSUS_STATE_FINALIZED_HEIGHT_KEY]: codec.encode(BFTFinalizedHeightCodecSchema, {
Expand All @@ -299,7 +300,7 @@ describe('bft', () => {
}),
},
{ lastBlockHeaders: blocks },
);
) as unknown) as StateStore;
await bft.init(stateStore);
});

Expand Down