Skip to content

Commit

Permalink
refactor: replace proxy services with container bindings
Browse files Browse the repository at this point in the history
  • Loading branch information
Brian Faust committed Sep 16, 2019
1 parent 3c12f5a commit 5d7d3d6
Show file tree
Hide file tree
Showing 41 changed files with 240 additions and 349 deletions.
5 changes: 1 addition & 4 deletions packages/core-api/src/handlers/blocks/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ export class BlocksController extends Controller {
public async first(request: Hapi.Request, h: Hapi.ResponseToolkit) {
try {
return super.respondWithResource(
app
.get<Contracts.State.StateService>(Container.Identifiers.StateService)
.getStore()
.getGenesisBlock().data,
app.get<Contracts.State.StateStore>(Container.Identifiers.StateStore).getGenesisBlock().data,
"block",
(request.query.transform as unknown) as boolean,
);
Expand Down
8 changes: 6 additions & 2 deletions packages/core-api/src/handlers/node/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ export class NodeController extends Controller {
public async status(request: Hapi.Request, h: Hapi.ResponseToolkit) {
try {
const lastBlock = this.blockchain.getLastBlock();
const networkHeight = this.blockchain.p2p.getMonitor().getNetworkHeight();
const networkHeight = app
.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor)
.getNetworkHeight();

return {
data: {
Expand All @@ -27,7 +29,9 @@ export class NodeController extends Controller {
public async syncing(request: Hapi.Request, h: Hapi.ResponseToolkit) {
try {
const lastBlock = this.blockchain.getLastBlock();
const networkHeight = this.blockchain.p2p.getMonitor().getNetworkHeight();
const networkHeight = app
.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor)
.getNetworkHeight();

return {
data: {
Expand Down
11 changes: 8 additions & 3 deletions packages/core-api/src/handlers/peers/controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Contracts } from "@arkecosystem/core-kernel";
import { app, Container, Contracts } from "@arkecosystem/core-kernel";
import Boom from "@hapi/boom";
import Hapi from "@hapi/hapi";
import semver from "semver";
Expand All @@ -7,7 +7,9 @@ import { Controller } from "../shared/controller";

export class PeersController extends Controller {
public async index(request: Hapi.Request, h: Hapi.ResponseToolkit) {
const allPeers: Contracts.P2P.Peer[] = this.blockchain.p2p.getStorage().getPeers();
const allPeers: Contracts.P2P.Peer[] = app
.get<Contracts.P2P.PeerStorage>(Container.Identifiers.PeerStorage)
.getPeers();

let result = allPeers.sort((a, b) => a.latency - b.latency);
result = request.query.version
Expand Down Expand Up @@ -35,7 +37,10 @@ export class PeersController extends Controller {

public async show(request: Hapi.Request, h: Hapi.ResponseToolkit) {
try {
const peers: Contracts.P2P.Peer[] = this.blockchain.p2p.getStorage().getPeers();
const peers: Contracts.P2P.Peer[] = app
.get<Contracts.P2P.PeerStorage>(Container.Identifiers.PeerStorage)
.getPeers();

const peer: Contracts.P2P.Peer = peers.find(p => p.ip === request.params.ip);

if (!peer) {
Expand Down
6 changes: 3 additions & 3 deletions packages/core-api/src/handlers/transactions/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ export class TransactionsController extends Controller {
const result = await processor.validate((request.payload as any).transactions);

if (result.broadcast.length > 0) {
app.get<Contracts.P2P.PeerService>(Container.Identifiers.PeerService)
.getMonitor()
.broadcastTransactions(processor.getBroadcastTransactions());
app.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor).broadcastTransactions(
processor.getBroadcastTransactions(),
);
}

return {
Expand Down
29 changes: 15 additions & 14 deletions packages/core-blockchain/src/blockchain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,14 @@ import { stateMachine } from "./state-machine";

const { BlockFactory } = Blocks;

@Container.injectable()
export class Blockchain implements Contracts.Blockchain.Blockchain {
/**
* Get the state of the blockchain.
* @return {StateStore}
*/
get state(): Contracts.State.StateStore {
return app.get<Contracts.State.StateService>(Container.Identifiers.StateService).getStore();
}

/**
* Get the network (p2p) interface.
* @return {PeerService}
*/
get p2p(): Contracts.P2P.PeerService {
return app.get<Contracts.P2P.PeerService>(Container.Identifiers.PeerService);
return app.get<Contracts.State.StateStore>(Container.Identifiers.StateStore);
}

/**
Expand Down Expand Up @@ -52,14 +45,15 @@ export class Blockchain implements Contracts.Blockchain.Blockchain {
* @param {Object} options
* @return {void}
*/
constructor(options: { networkStart?: boolean }) {
init(options: { networkStart?: boolean }): this {
// flag to force a network start
this.state.networkStart = !!options.networkStart;

if (this.state.networkStart) {
app.log.warning(
"ARK Core is launched in Genesis Start mode. This is usually for starting the first node on the blockchain. Unless you know what you are doing, this is likely wrong.",
);

app.log.info("Starting ARK Core for a new world, welcome aboard");
}

Expand All @@ -80,6 +74,8 @@ export class Blockchain implements Contracts.Blockchain.Blockchain {

// @ts-ignore
this.queue.drain(() => this.dispatch("PROCESSFINISHED"));

return this;
}

/**
Expand Down Expand Up @@ -138,7 +134,10 @@ export class Blockchain implements Contracts.Blockchain.Blockchain {
await delay(1000);
}

this.p2p.getMonitor().cleansePeers({ forcePing: true, peerCount: 10 });
app.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor).cleansePeers({
forcePing: true,
peerCount: 10,
});

return true;
}
Expand Down Expand Up @@ -179,7 +178,7 @@ export class Blockchain implements Contracts.Blockchain.Blockchain {
* @return {void}
*/
public async updateNetworkStatus(): Promise<void> {
await this.p2p.getMonitor().updateNetworkStatus();
await app.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor).updateNetworkStatus();
}

/**
Expand Down Expand Up @@ -417,7 +416,9 @@ export class Blockchain implements Contracts.Blockchain.Blockchain {
const blocktime: number = Managers.configManager.getMilestone(currentBlock.data.height).blocktime;

if (this.state.started && Crypto.Slots.getSlotNumber() * blocktime <= currentBlock.data.timestamp) {
this.p2p.getMonitor().broadcastBlock(currentBlock);
app.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor).broadcastBlock(
currentBlock,
);
}
}

Expand Down Expand Up @@ -458,7 +459,7 @@ export class Blockchain implements Contracts.Blockchain.Blockchain {
* Determine if the blockchain is synced.
*/
public isSynced(block?: Interfaces.IBlockData): boolean {
if (!this.p2p.getStorage().hasPeers()) {
if (!app.get<Contracts.P2P.PeerStorage>(Container.Identifiers.PeerStorage).hasPeers()) {
return true;
}

Expand Down
6 changes: 1 addition & 5 deletions packages/core-blockchain/src/replay/replay-blockchain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class ReplayBlockchain extends Blockchain {
}

public constructor() {
super({});
super();

this.walletRepository = new Wallets.WalletRepository();
this.walletState = app.resolve<Wallets.WalletState>(Wallets.WalletState).init(this.walletRepository);
Expand All @@ -36,10 +36,6 @@ export class ReplayBlockchain extends Blockchain {
this.queue.drain(() => undefined);
}

public get p2p(): Contracts.P2P.PeerService {
return undefined;
}

public get transactionPool(): Contracts.TransactionPool.Connection {
return undefined;
}
Expand Down
10 changes: 4 additions & 6 deletions packages/core-blockchain/src/service-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,19 @@ import { ReplayBlockchain } from "./replay";

export class ServiceProvider extends Providers.ServiceProvider {
public async register(): Promise<void> {
this.app.bind("blockchain.options").toConstantValue(this.config().all());

const blockchain: Blockchain = this.config().get("replay")
? new ReplayBlockchain()
: new Blockchain(this.config().all());
: this.app.resolve<Blockchain>(Blockchain).init(this.config().all());

this.app
.get<Contracts.State.StateService>(Container.Identifiers.StateService)
.getStore()
.reset(blockchainMachine);
this.app.get<Contracts.State.StateStore>(Container.Identifiers.StateStore).reset(blockchainMachine);

if (!process.env.CORE_SKIP_BLOCKCHAIN && !this.config().get("replay")) {
await blockchain.start();
}

this.app.bind(Container.Identifiers.BlockchainService).toConstantValue(blockchain);
this.app.bind("blockchain.options").toConstantValue(this.config().all());
}

public async dispose(): Promise<void> {
Expand Down
18 changes: 10 additions & 8 deletions packages/core-blockchain/src/state-machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ blockchainMachine.actionMap = (blockchain: Blockchain) => ({
if (stateStorage.p2pUpdateCounter + 1 > 3) {
logger.info("Network keeps missing blocks.");

const networkStatus = await blockchain.p2p.getMonitor().checkNetworkHealth();
const networkStatus = await app
.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor)
.checkNetworkHealth();
if (networkStatus.forked) {
stateStorage.numberOfBlocksToRollback = networkStatus.blocksToRollback;
event = "FORK";
Expand Down Expand Up @@ -112,7 +114,7 @@ blockchainMachine.actionMap = (blockchain: Blockchain) => ({

async init() {
logger = app.log;
stateStorage = app.get<Contracts.State.StateService>(Container.Identifiers.StateService).getStore();
stateStorage = app.get<Contracts.State.StateStore>(Container.Identifiers.StateStore);
blockchainMachine.state = stateStorage;

try {
Expand Down Expand Up @@ -154,7 +156,7 @@ blockchainMachine.actionMap = (blockchain: Blockchain) => ({
await blockchain.database.buildWallets();
await blockchain.database.applyRound(block.data.height);
await blockchain.transactionPool.buildWallets();
await blockchain.p2p.getMonitor().start();
await app.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor).start();

return blockchain.dispatch("STARTED");
}
Expand All @@ -164,7 +166,7 @@ blockchainMachine.actionMap = (blockchain: Blockchain) => ({

stateStorage.setLastBlock(BlockFactory.fromJson(Managers.configManager.get("genesisBlock")));
await blockchain.database.buildWallets();
await blockchain.p2p.getMonitor().start();
await app.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor).start();

return blockchain.dispatch("STARTED");
}
Expand All @@ -180,7 +182,7 @@ blockchainMachine.actionMap = (blockchain: Blockchain) => ({
await blockchain.database.restoreCurrentRound(block.data.height);
await blockchain.transactionPool.buildWallets();

await blockchain.p2p.getMonitor().start();
await app.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor).start();

return blockchain.dispatch("STARTED");
} catch (error) {
Expand All @@ -193,8 +195,8 @@ blockchainMachine.actionMap = (blockchain: Blockchain) => ({
async downloadBlocks() {
const lastDownloadedBlock: Interfaces.IBlockData =
stateStorage.lastDownloadedBlock || stateStorage.getLastBlock().data;
const blocks: Interfaces.IBlockData[] = await blockchain.p2p
.getMonitor()
const blocks: Interfaces.IBlockData[] = await app
.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor)
.syncWithNetwork(lastDownloadedBlock.height);

if (blockchain.isStopped) {
Expand Down Expand Up @@ -271,7 +273,7 @@ blockchainMachine.actionMap = (blockchain: Blockchain) => ({
logger.info(`Removed ${AppUtils.pluralize("block", random, true)}`);

await blockchain.transactionPool.buildWallets();
await blockchain.p2p.getMonitor().refreshPeersAfterFork();
await app.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor).refreshPeersAfterFork();

blockchain.dispatch("SUCCESS");
},
Expand Down
3 changes: 1 addition & 2 deletions packages/core-blockchain/src/utils/tick-sync-tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ export const tickSyncTracker = (blockCount, count): void => {
tracker = {
start: new Date().getTime(),
networkHeight: app
.get<Contracts.P2P.PeerService>(Container.Identifiers.PeerService)
.getMonitor()
.get<Contracts.P2P.NetworkMonitor>(Container.Identifiers.PeerNetworkMonitor)
.getNetworkHeight(),
blocksInitial: +count,
blocksDownloaded: +count,
Expand Down
34 changes: 12 additions & 22 deletions packages/core-database/src/database-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ export class DatabaseService implements Contracts.Database.DatabaseService {
}

public async init(): Promise<void> {
app.get<Contracts.State.StateService>(Container.Identifiers.StateService)
.getStore()
.setGenesisBlock(Blocks.BlockFactory.fromJson(Managers.configManager.get("genesisBlock")));
app.get<Contracts.State.StateStore>(Container.Identifiers.StateStore).setGenesisBlock(
Blocks.BlockFactory.fromJson(Managers.configManager.get("genesisBlock")),
);

if (process.env.CORE_RESET_DATABASE) {
await this.reset();
Expand Down Expand Up @@ -228,8 +228,7 @@ export class DatabaseService implements Contracts.Database.DatabaseService {
const end: number = offset + limit - 1;

let blocks: Interfaces.IBlockData[] = app
.get<Contracts.State.StateService>(Container.Identifiers.StateService)
.getStore()
.get<Contracts.State.StateStore>(Container.Identifiers.StateStore)
.getLastBlocksByHeight(start, end, headersOnly);

if (blocks.length !== limit) {
Expand Down Expand Up @@ -292,8 +291,7 @@ export class DatabaseService implements Contracts.Database.DatabaseService {

for (const [i, height] of heights.entries()) {
const stateBlocks = app
.get<Contracts.State.StateService>(Container.Identifiers.StateService)
.getStore()
.get<Contracts.State.StateStore>(Container.Identifiers.StateStore)
.getLastBlocksByHeight(height, height, true);

if (Array.isArray(stateBlocks) && stateBlocks.length > 0) {
Expand All @@ -320,8 +318,7 @@ export class DatabaseService implements Contracts.Database.DatabaseService {

public async getBlocksForRound(roundInfo?: Contracts.Shared.RoundInfo): Promise<Interfaces.IBlock[]> {
let lastBlock: Interfaces.IBlock = app
.get<Contracts.State.StateService>(Container.Identifiers.StateService)
.getStore()
.get<Contracts.State.StateStore>(Container.Identifiers.StateStore)
.getLastBlock();

if (!lastBlock) {
Expand Down Expand Up @@ -372,8 +369,7 @@ export class DatabaseService implements Contracts.Database.DatabaseService {

public async getCommonBlocks(ids: string[]): Promise<Interfaces.IBlockData[]> {
let commonBlocks: Interfaces.IBlockData[] = app
.get<Contracts.State.StateService>(Container.Identifiers.StateService)
.getStore()
.get<Contracts.State.StateStore>(Container.Identifiers.StateStore)
.getCommonBlocks(ids);

if (commonBlocks.length < ids.length) {
Expand All @@ -385,8 +381,7 @@ export class DatabaseService implements Contracts.Database.DatabaseService {

public async getRecentBlockIds(): Promise<string[]> {
let blocks: any[] = app
.get<Contracts.State.StateService>(Container.Identifiers.StateService)
.getStore()
.get<Contracts.State.StateStore>(Container.Identifiers.StateStore)
.getLastBlockIds()
.reverse()
.slice(0, 10);
Expand Down Expand Up @@ -653,8 +648,7 @@ export class DatabaseService implements Contracts.Database.DatabaseService {

private async createGenesisBlock(): Promise<Interfaces.IBlock> {
const genesisBlock: Interfaces.IBlock = app
.get<Contracts.State.StateService>(Container.Identifiers.StateService)
.getStore()
.get<Contracts.State.StateStore>(Container.Identifiers.StateStore)
.getGenesisBlock();

await this.saveBlock(genesisBlock);
Expand All @@ -663,17 +657,13 @@ export class DatabaseService implements Contracts.Database.DatabaseService {
}

private configureState(lastBlock: Interfaces.IBlock): void {
const state: Contracts.State.StateService = app.get<Contracts.State.StateService>(
Container.Identifiers.StateService,
);

state.getStore().setLastBlock(lastBlock);
app.get<Contracts.State.StateStore>(Container.Identifiers.StateStore).setLastBlock(lastBlock);

const { blocktime, block } = Managers.configManager.getMilestone();

const blocksPerDay: number = Math.ceil(86400 / blocktime);
state.getBlocks().resize(blocksPerDay);
state.getTransactions().resize(blocksPerDay * block.maxTransactions);
app.get<any>(Container.Identifiers.StateBlockStore).resize(blocksPerDay);
app.get<any>(Container.Identifiers.StateTransactionStore).resize(blocksPerDay * block.maxTransactions);
}

private async initializeActiveDelegates(height: number): Promise<void> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ export class RegisterServiceProviders implements Bootstrapper {
await serviceProviders.register(name);
}
} catch (error) {
console.log(error); // remove after debug

// Determine if the plugin is required to decide how to handle errors.
const isRequired: boolean = await serviceProvider.required();

Expand Down
Loading

0 comments on commit 5d7d3d6

Please sign in to comment.