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

Implement WebSocket to Stream Silent Blocks #46

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
607 changes: 605 additions & 2 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@nestjs/common": "^10.4.1",
"@nestjs/config": "^3.2.3",
"@nestjs/core": "^10.4.1",
"@nestjs/event-emitter": "^2.0.4",
"@nestjs/microservices": "^10.4.1",
"@nestjs/passport": "^10.0.0",
"@nestjs/platform-express": "^10.3.7",
Expand All @@ -36,6 +37,7 @@
"@nestjs/swagger": "^7.3.1",
"@nestjs/typeorm": "^10.0.2",
"@nestjs/websockets": "^10.3.7",
"@nestjs/platform-ws": "^10.4.4",
"axios": "^1.7.2",
"currency.js": "^2.0.4",
"js-yaml": "^4.1.0",
Expand All @@ -55,6 +57,7 @@
"@types/node": "18.15.11",
"@types/secp256k1": "^4.0.6",
"@types/supertest": "^2.0.11",
"@types/ws": "^8.5.12",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"bip32": "^2.0.0",
Expand Down
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ import { SilentBlocksModule } from '@/silent-blocks/silent-blocks.module';
import { OperationStateModule } from '@/operation-state/operation-state.module';
import { ScheduleModule } from '@nestjs/schedule';
import { BlockProviderModule } from '@/block-data-providers/block-provider.module';
import { EventEmitterModule } from '@nestjs/event-emitter';

@Module({
imports: [
ScheduleModule.forRoot(),
EventEmitterModule.forRoot(),
ConfigModule.forRoot({
ignoreEnvFile: true,
load: [configuration],
Expand Down
2 changes: 2 additions & 0 deletions src/block-data-providers/base-block-data-provider.abstract.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { OperationStateService } from '@/operation-state/operation-state.service';
import { Logger } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import {
IndexerService,
TransactionInput,
Expand All @@ -10,6 +11,7 @@ import { BlockStateService } from '@/block-state/block-state.service';
import { BlockState } from '@/block-state/block-state.entity';

export abstract class BaseBlockDataProvider<OperationState> {
protected readonly eventEmitter: EventEmitter2 = new EventEmitter2();
protected abstract readonly logger: Logger;
protected abstract readonly operationStateKey: string;

Expand Down
5 changes: 5 additions & 0 deletions src/block-data-providers/bitcoin-core/provider.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
} from '@/block-data-providers/bitcoin-core/provider-fixtures';
import { Test, TestingModule } from '@nestjs/testing';
import { BlockStateService } from '@/block-state/block-state.service';
import { EventEmitter2 } from '@nestjs/event-emitter';

describe('Bitcoin Core Provider', () => {
let provider: BitcoinCoreProvider;
Expand Down Expand Up @@ -51,6 +52,10 @@ describe('Bitcoin Core Provider', () => {
provide: BlockStateService,
useClass: jest.fn(),
},
{
provide: EventEmitter2,
useValue: jest.fn(),
},
],
}).compile();

Expand Down
5 changes: 5 additions & 0 deletions src/block-data-providers/bitcoin-core/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import { AxiosRequestConfig } from 'axios';
import * as currency from 'currency.js';
import { AxiosRetryConfig, makeRequest } from '@/common/request';
import { BlockStateService } from '@/block-state/block-state.service';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { INDEXED_BLOCK_EVENT } from '@/common/events';

@Injectable()
export class BitcoinCoreProvider
Expand All @@ -46,6 +48,7 @@ export class BitcoinCoreProvider
indexerService: IndexerService,
operationStateService: OperationStateService,
blockStateService: BlockStateService,
protected readonly eventEmitter: EventEmitter2,
) {
super(
configService,
Expand Down Expand Up @@ -144,6 +147,8 @@ export class BitcoinCoreProvider
blockHash: blockHash,
blockHeight: height,
});

this.eventEmitter.emit(INDEXED_BLOCK_EVENT, height);
}
} finally {
this.isSyncing = false;
Expand Down
6 changes: 6 additions & 0 deletions src/block-data-providers/block-provider.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ import { BitcoinCoreProvider } from '@/block-data-providers/bitcoin-core/provide
import { EsploraProvider } from '@/block-data-providers/esplora/provider';
import { BlockStateService } from '@/block-state/block-state.service';
import { BlockStateModule } from '@/block-state/block-state.module';
import { EventEmitter2, EventEmitterModule } from '@nestjs/event-emitter';

@Module({
imports: [
OperationStateModule,
IndexerModule,
ConfigModule,
BlockStateModule,
EventEmitterModule,
],
controllers: [],
providers: [
Expand All @@ -26,12 +28,14 @@ import { BlockStateModule } from '@/block-state/block-state.module';
IndexerService,
OperationStateService,
BlockStateService,
EventEmitter2,
],
useFactory: (
configService: ConfigService,
indexerService: IndexerService,
operationStateService: OperationStateService,
blockStateService: BlockStateService,
eventEmitter: EventEmitter2,
) => {
switch (configService.get<ProviderType>('providerType')) {
case ProviderType.ESPLORA:
Expand All @@ -40,13 +44,15 @@ import { BlockStateModule } from '@/block-state/block-state.module';
indexerService,
operationStateService,
blockStateService,
eventEmitter,
);
case ProviderType.BITCOIN_CORE_RPC:
return new BitcoinCoreProvider(
configService,
indexerService,
operationStateService,
blockStateService,
eventEmitter,
);
default:
throw Error('unrecognised provider type in config');
Expand Down
5 changes: 5 additions & 0 deletions src/block-data-providers/esplora/provider.ts
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to emit INDEXED_BLOCK_EVENT event in this provider as well

Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
import { TAPROOT_ACTIVATION_HEIGHT } from '@/common/constants';
import { BlockStateService } from '@/block-state/block-state.service';
import { Cron, CronExpression } from '@nestjs/schedule';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { INDEXED_BLOCK_EVENT } from '@/common/events';

@Injectable()
export class EsploraProvider
Expand All @@ -31,6 +33,7 @@ export class EsploraProvider
indexerService: IndexerService,
operationStateService: OperationStateService,
blockStateService: BlockStateService,
protected readonly eventEmitter: EventEmitter2,
) {
super(
configService,
Expand Down Expand Up @@ -175,6 +178,8 @@ export class EsploraProvider
blockHeight: height,
blockHash: hash,
});

this.eventEmitter.emit(INDEXED_BLOCK_EVENT, height);
} catch (error) {
this.logger.error(
`Error processing transactions in block at height ${height}, hash ${hash}: ${error.message}`,
Expand Down
4 changes: 4 additions & 0 deletions src/common/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,7 @@ export const varIntSize = (value: number): number => {
else if (value <= 0xffffffff) return 5;
else return 9;
};

export const delay = (ms: number): Promise<void> => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
1 change: 1 addition & 0 deletions src/common/events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const INDEXED_BLOCK_EVENT = 'INDEXED_BLOCK_EVENT';
2 changes: 2 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import { NestFactory } from '@nestjs/core';
import { AppModule } from '@/app.module';
import { ConfigService } from '@nestjs/config';
import { LogLevel } from '@nestjs/common';
import { WsAdapter } from '@nestjs/platform-ws';

declare const module: any;

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useWebSocketAdapter(new WsAdapter(app));

const configService = app.get<ConfigService>(ConfigService);
const port = configService.get<number>('app.port');
Expand Down
36 changes: 36 additions & 0 deletions src/silent-blocks/silent-blocks.gateway.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Injectable, Logger } from '@nestjs/common';
import {
WebSocketGateway,
WebSocketServer,
OnGatewayConnection,
OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Server, WebSocket } from 'ws';

@Injectable()
@WebSocketGateway()
export class SilentBlocksGateway
implements OnGatewayConnection, OnGatewayDisconnect
{
private readonly logger = new Logger(SilentBlocksGateway.name);

@WebSocketServer() server: Server;

handleConnection(client: WebSocket) {
const remoteAddress = (client as any)._socket.remoteAddress;
this.logger.debug(`Client connected: ${remoteAddress}`);
}

handleDisconnect(client: WebSocket) {
const remoteAddress = (client as any)._socket.remoteAddress;
this.logger.debug(`Client disconnected: ${remoteAddress}`);
}

broadcastSilentBlock(silentBlock: Buffer) {
for (const client of this.server.clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(silentBlock);
}
}
}
}
3 changes: 2 additions & 1 deletion src/silent-blocks/silent-blocks.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import { Transaction } from '@/transactions/transaction.entity';
import { TransactionsService } from '@/transactions/transactions.service';
import { SilentBlocksController } from '@/silent-blocks/silent-blocks.controller';
import { SilentBlocksService } from '@/silent-blocks/silent-blocks.service';
import { SilentBlocksGateway } from '@/silent-blocks/silent-blocks.gateway';

@Module({
imports: [TypeOrmModule.forFeature([Transaction])],
providers: [TransactionsService, SilentBlocksService],
providers: [TransactionsService, SilentBlocksService, SilentBlocksGateway],
controllers: [SilentBlocksController],
exports: [SilentBlocksService],
})
Expand Down
5 changes: 5 additions & 0 deletions src/silent-blocks/silent-blocks.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing';
import { TransactionsService } from '@/transactions/transactions.service';
import { SilentBlocksService } from '@/silent-blocks/silent-blocks.service';
import { silentBlockEncodingFixture } from '@/silent-blocks/silent-blocks.service.fixtures';
import { SilentBlocksGateway } from '@/silent-blocks/silent-blocks.gateway';
import { DataSource, Repository } from 'typeorm';
import { Transaction } from '@/transactions/transaction.entity';
import { getRepositoryToken } from '@nestjs/typeorm';
Expand Down Expand Up @@ -31,6 +32,10 @@ describe('SilentBlocksService', () => {
provide: getRepositoryToken(Transaction),
useValue: transactionRepository,
},
{
provide: SilentBlocksGateway,
useValue: jest.fn(),
},
],
}).compile();

Expand Down
22 changes: 19 additions & 3 deletions src/silent-blocks/silent-blocks.service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import { Transaction } from '@/transactions/transaction.entity';
import { TransactionsService } from '@/transactions/transactions.service';
import { SILENT_PAYMENT_BLOCK_TYPE } from '@/common/constants';
import { encodeVarInt, varIntSize } from '@/common/common';
import { encodeVarInt, varIntSize, delay } from '@/common/common';
import { SilentBlocksGateway } from '@/silent-blocks/silent-blocks.gateway';
import { OnEvent } from '@nestjs/event-emitter';
import { INDEXED_BLOCK_EVENT } from '@/common/events';

@Injectable()
export class SilentBlocksService {
constructor(private readonly transactionsService: TransactionsService) {}
private readonly logger = new Logger(SilentBlocksService.name);

constructor(
private readonly transactionsService: TransactionsService,
private readonly silentBlocksGateway: SilentBlocksGateway,
) {}

@OnEvent(INDEXED_BLOCK_EVENT)
async handleBlockIndexedEvent(blockHeight: number) {
this.logger.debug(`New block indexed: ${blockHeight}`);
await delay(1000);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we adding a delay here?

Comment on lines +19 to +22
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@seekersoftec , kindly research if we could use a superior way to handle the latency, we could use a while loop with a cut-off time, the cut-off which i believe may be quite unnecessary due to the operational model that requires such SiientBlock to be eventually available .

const silentBlock = await this.getSilentBlockByHeight(blockHeight);
this.silentBlocksGateway.broadcastSilentBlock(silentBlock);
}

private getSilentBlockLength(transactions: Transaction[]): number {
let length = 1 + varIntSize(transactions.length); // 1 byte for type + varint for transactions count
Expand Down