-
Notifications
You must be signed in to change notification settings - Fork 22
/
generic.ts
183 lines (162 loc) · 6.23 KB
/
generic.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import { NodePlatformAdapter } from '.';
import { EthereumClient } from '../eth/client';
import { JsonRpcError } from '../eth/jsonrpc';
import { KNOWN_NETOWORK_NAMES } from '../eth/networks';
import {
blockNumber,
clientVersion,
gasPrice,
hashRate,
netVersion,
peerCount,
pendingTransactions,
protocolVersion,
syncing,
} from '../eth/requests';
import { formatPendingTransaction } from '../format';
import { NodeInfo, PendingTransactionMessage } from '../msgs';
import { OutputMessage } from '../output';
import { bigIntToNumber } from '../utils/bn';
import { createModuleDebug } from '../utils/debug';
import { prefixKeys } from '../utils/obj';
const { debug, warn, error } = createModuleDebug('platforms:generic');
export async function checkRpcMethodSupport(eth: EthereumClient, req: EthRequest<[], any>): Promise<boolean> {
try {
debug('Checking if RPC method %s is supported by ethereum node', req.method);
await eth.request(req, { immediate: true });
debug('Ethereum node seems to support RPC method %s', req.method);
return true;
} catch (e) {
warn('RPC method %s is not supported by ethereum node: %s', req.method, e.message);
return false;
}
}
export async function captureDefaultMetrics(
eth: EthereumClient,
captureTime: number,
supports: { hashRate?: boolean; peerCount?: boolean } = {}
): Promise<NodeMetricsMessage> {
const [blockNumberResult, hashRateResult, peerCountResult, gasPriceResult, syncStatus] = await Promise.all([
eth.request(blockNumber()),
supports.hashRate === false ? undefined : eth.request(hashRate()),
supports.peerCount === false ? undefined : eth.request(peerCount()),
eth
.request(gasPrice())
.then(value => bigIntToNumber(value))
.catch(e => {
warn('Error obtaining gas price: %s', e.message);
return undefined;
}),
eth.request(syncing()),
]);
return {
type: 'nodeMetrics',
time: captureTime,
metrics: {
blockNumber: blockNumberResult,
hashRate: hashRateResult,
peerCount: peerCountResult,
gasPrice: gasPriceResult,
...(syncStatus ? prefixKeys(syncStatus, 'syncing.', true) : undefined),
},
};
}
export async function fetchPendingTransactions(eth: EthereumClient, captureTime: number): Promise<OutputMessage[]> {
const pendingTxs = await eth.request(pendingTransactions());
return [
{
type: 'nodeMetrics',
time: captureTime,
metrics: {
pendingTransactionCount: pendingTxs.length,
},
},
...pendingTxs.map(
tx =>
({
type: 'pendingtx',
time: captureTime,
body: formatPendingTransaction(tx, 'pending'),
} as PendingTransactionMessage)
),
];
}
export interface DefaultNodeInfo {
networkId?: number;
protocolVersion?: number;
}
export async function fetchDefaultNodeInfo(ethClient: EthereumClient): Promise<DefaultNodeInfo> {
const [networkId, protocol] = await Promise.all([
ethClient.request(netVersion()),
ethClient.request(protocolVersion()),
]);
return { networkId, protocolVersion: protocol };
}
export async function checkPendingTransactionsMethodSupport(ethClient: EthereumClient): Promise<boolean> {
try {
debug('Checking if generic node supports pendingTranscations RPC method');
await ethClient.request(pendingTransactions());
debug('Pending transactions seem to be supported');
return true;
} catch (e) {
if (e instanceof JsonRpcError) {
warn('Generic node does not seem to support the eth_pendingTransactions RPC method', e);
return false;
} else {
error('Encountered unexpected error while checking for pendingTransaction method support', e);
return false;
}
}
}
export class GenericNodeAdapter implements NodePlatformAdapter {
private nodeInfo?: NodeInfo;
private supportsPendingTransactions?: boolean;
constructor(private clientVersion: string, private network?: string) {}
public async initialize(ethClient: EthereumClient) {
await this.captureNodeInfo(ethClient);
this.supportsPendingTransactions = await checkPendingTransactionsMethodSupport(ethClient);
}
public async captureNodeInfo(ethClient: EthereumClient): Promise<NodeInfo> {
const [defaultInfo, version] = await Promise.all([
fetchDefaultNodeInfo(ethClient),
ethClient.request(clientVersion()),
]);
const name = version.slice(0, version.indexOf('/'));
debug('Extracted ethereum node name %o from clientVersion response', name);
this.nodeInfo = {
transport: ethClient.transport.source,
enode: null,
networkId: defaultInfo.networkId ?? null,
protocolVersion: defaultInfo.protocolVersion ?? null,
clientVersion: version,
platform: `generic:${name}`,
network: this.networkName,
};
return this.nodeInfo;
}
public get fullVersion(): string {
return this.nodeInfo?.clientVersion ?? this.clientVersion;
}
public get name(): string {
return this.nodeInfo?.platform ?? 'generic:unknown';
}
public get enode(): string | null {
return this.nodeInfo?.enode ?? null;
}
public get networkId(): number | null {
return this.nodeInfo?.networkId ?? null;
}
public get networkName(): string | null {
return this.network ?? (this.networkId != null ? KNOWN_NETOWORK_NAMES[this.networkId] : null) ?? null;
}
public get protocolVersion(): number | null {
return this.nodeInfo?.protocolVersion ?? null;
}
public async captureNodeStats(ethClient: EthereumClient, captureTime: number): Promise<OutputMessage[]> {
const results = await Promise.all([
captureDefaultMetrics(ethClient, captureTime),
this.supportsPendingTransactions ? fetchPendingTransactions(ethClient, captureTime) : [],
]);
return results.flat(1);
}
}