Skip to content

Commit

Permalink
Merge branch 'feature/services-dependency-injection' into v8.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
nitsujlangston committed Dec 27, 2018
2 parents 2b09bb7 + ac395a5 commit 095c8de
Show file tree
Hide file tree
Showing 32 changed files with 587 additions and 357 deletions.
35 changes: 24 additions & 11 deletions packages/bitcore-node/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { homedir, cpus } from 'os';
import parseArgv from './utils/parseArgv';
import ConfigType from './types/Config';
import { ConfigType } from "./types/Config";
let program = parseArgv([], ['config']);

function findConfig(): ConfigType | undefined {
Expand Down Expand Up @@ -57,18 +57,31 @@ const Config = function(): ConfigType {
dbName: process.env.DB_NAME || 'bitcore',
dbPort: process.env.DB_PORT || '27017',
numWorkers: cpus().length,
api: {
rateLimiter: {
whitelist: [
'::ffff:127.0.0.1'
]
chains: {},
services: {
api: {
enabled: true,
rateLimiter: {
whitelist: ['::ffff:127.0.0.1']
},
wallets: {
allowCreationBeforeCompleteSync: false,
allowUnauthenticatedCalls: false
}
},
event: {
enabled: true
},
p2p: {
enabled: true
},
wallets: {
allowCreationBeforeCompleteSync: false,
allowUnauthenticatedCalls: false
socket: {
enabled: true
},
storage: {
enabled: true
}
},
chains: {}
}
};

let foundConfig = findConfig();
Expand Down
12 changes: 6 additions & 6 deletions packages/bitcore-node/src/models/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ export abstract class BaseModel<T> {
key: keyof T;
}>;

constructor(private collectionName: string) {
constructor(private collectionName: string, private storageService = Storage) {
this.handleConnection();
}

private async handleConnection() {
Storage.connection.on('CONNECTED', async () => {
if (Storage.db != undefined) {
this.storageService.connection.on('CONNECTED', async () => {
if (this.storageService.db != undefined) {
this.connected = true;
this.db = Storage.db;
this.db = this.storageService.db;
await this.onConnect();
}
});
Expand All @@ -30,8 +30,8 @@ export abstract class BaseModel<T> {
abstract async onConnect();

get collection(): Collection<MongoBound<T>> {
if (Storage.db) {
return Storage.db.collection(this.collectionName);
if (this.storageService.db) {
return this.storageService.db.collection(this.collectionName);
} else {
throw new Error('Not connected to the database yet');
}
Expand Down
27 changes: 14 additions & 13 deletions packages/bitcore-node/src/models/block.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
import { valueOrDefault } from '../utils/check';
import { CoinModel } from './coin';
import { TransactionModel } from './transaction';
import { CoinStorage } from './coin';
import { TransactionStorage } from './transaction';
import { TransformOptions } from '../types/TransformOptions';
import { LoggifyClass } from '../decorators/Loggify';
import { Bitcoin } from '../types/namespaces/Bitcoin';
import { BaseModel, MongoBound } from './base';
import logger from '../logger';
import { IBlock } from '../types/Block';
import { SpentHeightIndicators } from '../types/Coin';
import { EventModel } from './events';
import { EventStorage } from './events';
import config from '../config';
import { Event } from '../services/event';
import { StorageService } from "../services/storage";

export { IBlock };

@LoggifyClass
export class Block extends BaseModel<IBlock> {
constructor() {
super('blocks');
export class BlockModel extends BaseModel<IBlock> {
constructor(storage?: StorageService) {
super('blocks', storage);
}

chainTips: Mapping<Mapping<IBlock>> = {};
Expand Down Expand Up @@ -125,7 +126,7 @@ export class Block extends BaseModel<IBlock> {
logger.debug('Updating previous block.nextBlockHash ', header.hash);
}

await TransactionModel.batchImport({
await TransactionStorage.batchImport({
txs: block.transactions,
blockHash: header.hash,
blockTime: new Date(blockTime),
Expand All @@ -139,7 +140,7 @@ export class Block extends BaseModel<IBlock> {
});

if (initialSyncComplete) {
EventModel.signalBlock(convertedBlock);
EventStorage.signalBlock(convertedBlock);
}

return this.collection.updateOne({ hash: header.hash, chain, network }, { $set: { processed: true } });
Expand All @@ -152,7 +153,7 @@ export class Block extends BaseModel<IBlock> {
}

getLocalTip({ chain, network }) {
return BlockModel.collection.findOne({ chain, network, processed: true }, { sort: { height: -1 } });
return BlockStorage.collection.findOne({ chain, network, processed: true }, { sort: { height: -1 } });
}

async handleReorg(params: { header?: Bitcoin.Block.HeaderObj; chain: string; network: string }): Promise<boolean> {
Expand All @@ -175,12 +176,12 @@ export class Block extends BaseModel<IBlock> {
logger.info(`Resetting tip to ${localTip.height}`, { chain, network });
const reorgOps = [
this.collection.deleteMany({ chain, network, height: { $gte: localTip.height } }),
TransactionModel.collection.deleteMany({ chain, network, blockHeight: { $gte: localTip.height } }),
CoinModel.collection.deleteMany({ chain, network, mintHeight: { $gte: localTip.height } })
TransactionStorage.collection.deleteMany({ chain, network, blockHeight: { $gte: localTip.height } }),
CoinStorage.collection.deleteMany({ chain, network, mintHeight: { $gte: localTip.height } })
];
await Promise.all(reorgOps);

await CoinModel.collection.updateMany(
await CoinStorage.collection.updateMany(
{ chain, network, spentHeight: { $gte: localTip.height } },
{ $set: { spentTxid: null, spentHeight: SpentHeightIndicators.pending } }
);
Expand Down Expand Up @@ -227,4 +228,4 @@ export class Block extends BaseModel<IBlock> {
}
}

export let BlockModel = new Block();
export let BlockStorage = new BlockModel();
9 changes: 5 additions & 4 deletions packages/bitcore-node/src/models/coin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { BaseModel, MongoBound } from './base';
import { ObjectID } from 'mongodb';
import { SpentHeightIndicators, CoinJSON } from '../types/Coin';
import { valueOrDefault } from '../utils/check';
import { StorageService } from '../services/storage';

export type ICoin = {
network: string;
Expand All @@ -21,9 +22,9 @@ export type ICoin = {
};

@LoggifyClass
class Coin extends BaseModel<ICoin> {
constructor() {
super('coins');
class CoinModel extends BaseModel<ICoin> {
constructor(storage?: StorageService) {
super('coins', storage);
}

allowedPaging = [
Expand Down Expand Up @@ -166,4 +167,4 @@ class Coin extends BaseModel<ICoin> {
return JSON.stringify(transform);
}
}
export let CoinModel = new Coin();
export let CoinStorage = new CoinModel();
9 changes: 5 additions & 4 deletions packages/bitcore-node/src/models/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { BaseModel } from './base';
import { ITransaction } from './transaction';
import { IBlock } from '../types/Block';
import { ICoin } from './coin';
import { StorageService } from '../services/storage';

export namespace IEvent {
export type BlockEvent = IBlock;
Expand All @@ -13,9 +14,9 @@ interface IEvent {
type: 'block' | 'tx' | 'coin';
emitTime: Date;
}
class Event extends BaseModel<IEvent> {
constructor() {
super('events');
export class EventModel extends BaseModel<IEvent> {
constructor(storage?: StorageService) {
super('events', storage);
}

allowedPaging = [];
Expand Down Expand Up @@ -53,4 +54,4 @@ class Event extends BaseModel<IEvent> {
return this.collection.find({ type: 'coin', emitTime: { $gte: lastSeen } }).addCursorFlag('noCursorTimeout', true);
}
}
export const EventModel = new Event();
export const EventStorage = new EventModel();
15 changes: 8 additions & 7 deletions packages/bitcore-node/src/models/rateLimit.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BaseModel } from './base';
import { ObjectID } from 'mongodb';
import { StorageService } from '../services/storage';

export type IRateLimit = {
_id?: ObjectID;
Expand All @@ -11,9 +12,9 @@ export type IRateLimit = {
expireAt?: Date;
};

export class RateLimit extends BaseModel<IRateLimit> {
constructor() {
super('ratelimits');
export class RateLimitModel extends BaseModel<IRateLimit> {
constructor(storage?: StorageService) {
super('ratelimits', storage);
}
allowedPaging = [];

Expand All @@ -25,9 +26,9 @@ export class RateLimit extends BaseModel<IRateLimit> {
incrementAndCheck(identifier: string, method: string) {
return Promise.all([
this.collection.findOneAndUpdate(
{ identifier, method, period: 'second', time: {$gt: new Date(Date.now() - 1000)} },
{ identifier, method, period: 'second', time: { $gt: new Date(Date.now() - 1000) } },
{
$setOnInsert: { time: new Date(), expireAt: new Date(Date.now() + 10 * 1000) },
$setOnInsert: { time: new Date(), expireAt: new Date(Date.now() + 10 * 1000) },
$inc: { count: 1 }
},
{ upsert: true, returnOriginal: false }
Expand All @@ -47,9 +48,9 @@ export class RateLimit extends BaseModel<IRateLimit> {
$inc: { count: 1 }
},
{ upsert: true, returnOriginal: false }
),
)
]);
}
}

export let RateLimitModel = new RateLimit();
export let RateLimitStorage = new RateLimitModel();
9 changes: 5 additions & 4 deletions packages/bitcore-node/src/models/state.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { StorageService } from '../services/storage';
import { BaseModel } from './base';
import { ObjectID } from 'mongodb';

Expand All @@ -6,13 +7,13 @@ export type IState = {
initialSyncComplete: any;
};

export class State extends BaseModel<IState> {
constructor() {
super('state');
export class StateModel extends BaseModel<IState> {
constructor(storage?: StorageService) {
super('state', storage);
}
allowedPaging = [];

onConnect() {}
}

export let StateModel = new State();
export let StateStorage = new StateModel();
Loading

0 comments on commit 095c8de

Please sign in to comment.