-
Notifications
You must be signed in to change notification settings - Fork 37
/
rpc.controller.ts
101 lines (91 loc) · 2.5 KB
/
rpc.controller.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import {
ArgumentMetadata,
Body,
Controller,
ForbiddenException,
HttpCode,
Injectable,
Param,
PipeTransform,
Post
} from '@nestjs/common'
import { JsonRpcClient } from '@defichain/jellyfish-api-jsonrpc'
import { IsArray, IsIn, IsNotEmpty, IsOptional, IsString } from 'class-validator'
import { ApiRawResponse } from '../module.api/_core/api.response'
import { RpcApiError } from '@defichain/jellyfish-api-core'
import { Transform } from 'class-transformer'
/**
* MethodWhitelist is a whitelist validation pipe to check
* whether a plain old rpc can be routed through whale.
* Non whitelisted method call will result in a ForbiddenException.
*
* Direct access to DeFiD should not be allowed,
* that could be used as an attack against DeFi whale services.
* (by changing our peers)
*/
@Injectable()
export class MethodWhitelist implements PipeTransform {
static methods = [
'getblockchaininfo',
'getblockhash',
'getblockcount',
'getblock',
'getblockstats',
'getgov',
'validateaddress',
'listcommunitybalances',
'getaccounthistory'
]
transform (value: string, metadata: ArgumentMetadata): string {
if (!MethodWhitelist.methods.includes(value)) {
throw new ForbiddenException('RPC method not whitelisted')
}
return value
}
}
export class JSONRPCParams {
params?: any[]
}
export class JSONRPC {
@IsString()
@IsNotEmpty()
@IsIn(MethodWhitelist.methods, {
message: 'RPC method not whitelisted'
})
method!: string
@IsOptional()
@IsArray()
@Transform(({ value }) => value !== undefined ? value : [])
params?: any[]
}
@Controller('/rpc')
export class RpcController {
constructor (private readonly client: JsonRpcClient) {
}
@Post()
async post (@Body() rpc: JSONRPC): Promise<ApiRpcResponse> {
try {
const result = await this.client.call(rpc.method, rpc.params ?? [], 'lossless')
return new ApiRpcResponse(result)
} catch (err: any) {
if (err instanceof RpcApiError || err.payload !== undefined) {
return new ApiRpcResponse(null, err.payload)
}
throw err
}
}
@Post('/:method')
@HttpCode(200)
async call (@Param('method', MethodWhitelist) method: string, @Body() callDto?: JSONRPCParams): Promise<any> {
return await this.client.call(method, callDto?.params ?? [], 'lossless')
}
}
class ApiRpcResponse extends ApiRawResponse {
constructor (
public readonly result: any | null,
public readonly error: any = null,
public readonly id: null = null
) {
super()
}
}