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 6 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
1 change: 0 additions & 1 deletion config/dev.config.yaml
Copy link
Collaborator

Choose a reason for hiding this comment

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

revert please

Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,3 @@ bitcoinCore:
rpcPass: polarpass
rpcUser: polaruser
rpcPort: 18445

75 changes: 75 additions & 0 deletions package-lock.json
Copy link
Collaborator

Choose a reason for hiding this comment

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

the lock file is not up to date with package.json

diff --git a/package-lock.json b/package-lock.json
index c0b2e37..05d3cd2 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -17,6 +17,7 @@
         "@nestjs/passport": "^10.0.0",
         "@nestjs/platform-express": "^10.3.7",
         "@nestjs/platform-socket.io": "^10.3.7",
+        "@nestjs/platform-ws": "^10.4.4",
         "@nestjs/schedule": "^3.0.0",
         "@nestjs/swagger": "^7.3.1",
         "@nestjs/typeorm": "^10.0.2",
@@ -32,7 +33,6 @@
       },
       "devDependencies": {
         "@nestjs/cli": "^10.4.5",
-        "@nestjs/platform-ws": "^10.4.4",
         "@nestjs/schematics": "^9.0.0",
         "@nestjs/testing": "^10.3.7",
         "@types/express": "^4.17.13",
@@ -2044,7 +2044,6 @@
       "version": "10.4.4",
       "resolved": "https://registry.npmjs.org/@nestjs/platform-ws/-/platform-ws-10.4.4.tgz",
       "integrity": "sha512-6E476YvfO14uQUT6FzWFpGnwp58fpGq2aeGxHFdRMMptOQ5suKqD+3LsZgPiGF1elgVhQcI5uqM15qL3yH+OqQ==",
-      "dev": true,
       "dependencies": {
         "tslib": "2.7.0",
         "ws": "8.18.0"
@@ -2062,14 +2061,12 @@
     "node_modules/@nestjs/platform-ws/node_modules/tslib": {
       "version": "2.7.0",
       "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz",
-      "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==",
-      "dev": true
+      "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA=="
     },
     "node_modules/@nestjs/platform-ws/node_modules/ws": {
       "version": "8.18.0",
       "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz",
       "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==",
-      "dev": true,
       "engines": {
         "node": ">=10.0.0"
       },

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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",
"class-transformer": "^0.5.1",
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
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 @@ -28,6 +28,8 @@ import {
import { AxiosRequestConfig } from 'axios';
import * as currency from 'currency.js';
import { AxiosRetryConfig, makeRequest } from '@/common/request';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { INDEXED_BLOCK_EVENT } from '@/common/events';

@Injectable()
export class BitcoinCoreProvider
Expand All @@ -44,6 +46,7 @@ export class BitcoinCoreProvider
private readonly configService: ConfigService,
indexerService: IndexerService,
operationStateService: OperationStateService,
private eventEmitter: EventEmitter2,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
private eventEmitter: EventEmitter2,
private readonly eventEmitter: EventEmitter2,

) {
super(indexerService, operationStateService);

Expand Down Expand Up @@ -123,6 +126,8 @@ export class BitcoinCoreProvider

state.indexedBlockHeight = height;
await this.setState(state);

this.eventEmitter.emit(INDEXED_BLOCK_EVENT, height);
}
} finally {
this.isSyncing = false;
Expand Down
18 changes: 16 additions & 2 deletions src/block-data-providers/block-provider.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,45 @@ import { IndexerService } from '@/indexer/indexer.service';
import { ProviderType } from '@/common/enum';
import { BitcoinCoreProvider } from '@/block-data-providers/bitcoin-core/provider';
import { EsploraProvider } from '@/block-data-providers/esplora/provider';
import { EventEmitter2, EventEmitterModule } from '@nestjs/event-emitter';

@Module({
imports: [OperationStateModule, IndexerModule, ConfigModule],
imports: [
OperationStateModule,
IndexerModule,
ConfigModule,
EventEmitterModule,
],
controllers: [],
providers: [
{
provide: 'BlockDataProvider',
inject: [ConfigService, IndexerService, OperationStateService],
inject: [
ConfigService,
IndexerService,
OperationStateService,
EventEmitter2,
],
useFactory: (
configService: ConfigService,
indexerService: IndexerService,
operationStateService: OperationStateService,
eventEmitter: EventEmitter2,
) => {
switch (configService.get<ProviderType>('providerType')) {
case ProviderType.ESPLORA:
return new EsploraProvider(
configService,
indexerService,
operationStateService,
eventEmitter,
);
case ProviderType.BITCOIN_CORE_RPC:
return new BitcoinCoreProvider(
configService,
indexerService,
operationStateService,
eventEmitter,
);
default:
throw Error('unrecognised provider type in config');
Expand Down
3 changes: 3 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 @@ -12,6 +12,7 @@
} from '@/block-data-providers/esplora/interface';
import { TAPROOT_ACTIVATION_HEIGHT } from '@/common/constants';
import { Cron, CronExpression } from '@nestjs/schedule';
import { EventEmitter2 } from '@nestjs/event-emitter';

@Injectable()
export class EsploraProvider
Expand All @@ -29,6 +30,8 @@
private readonly configService: ConfigService,
indexerService: IndexerService,
operationStateService: OperationStateService,
private eventEmitter: EventEmitter2,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
private eventEmitter: EventEmitter2,
private readonly eventEmitter: EventEmitter2,


Check failure on line 34 in src/block-data-providers/esplora/provider.ts

View workflow job for this annotation

GitHub Actions / check-formatting-and-lint

Delete `⏎`
) {
super(indexerService, operationStateService);

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
@@ -1,11 +1,13 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from '@/app.module';
import { ConfigService } from '@nestjs/config';
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
37 changes: 37 additions & 0 deletions src/silent-blocks/silent-blocks.gateway.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
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}`);
}

// Method to broadcast silent block to all connected clients
broadcastSilentBlock(silentBlock: Buffer) {
this.server.clients.forEach((client: WebSocket) => {
if (client.readyState === WebSocket.OPEN) {
client.send(silentBlock.toString('hex')); // Send silent block as hex string
}
});
Comment on lines +31 to +35
Copy link
Collaborator

Choose a reason for hiding this comment

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

  1. because everything inside forEach is a synchronous operation, we should use a simple for..of loop. forEach is very slow.
  2. I see that you are sending the block as a hex string. This breaks the pattern we use for REST endpoints. We send the block as Buffer in REST endpoints. I think we should stick to using Buffer here as well for consistency.

}
}
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
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);
const silentBlock = await this.getSilentBlockByHeight(blockHeight);
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?

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
Loading