@neuraiproject/neurai-rpc 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts CHANGED
@@ -1,18 +1,22 @@
1
1
  import { parse, stringify, isSafeNumber, LosslessNumber } from 'lossless-json';
2
- import { methods } from "./docs";
2
+ import { methods } from './docs';
3
3
 
4
4
  export { methods };
5
+ export * from './depin';
6
+ export { assertNoDuplicateJsonKeys } from './json';
7
+ import { assertNoDuplicateJsonKeys } from './json';
8
+ import { isDepinRemoteMethod } from './depin';
5
9
 
6
- export const MAINNET_GENESIS_HASH = "00000044d33c0c0ba019be5c0249730424a69cb4c222153322f68c6104484806";
7
- export const TESTNET_GENESIS_HASH = "0000008b384aeffecdab182575dc4e86c9f07f90318c65088532660ed9a8a021";
10
+ export const MAINNET_GENESIS_HASH = '00000044d33c0c0ba019be5c0249730424a69cb4c222153322f68c6104484806';
11
+ export const TESTNET_GENESIS_HASH = '0000008b384aeffecdab182575dc4e86c9f07f90318c65088532660ed9a8a021';
8
12
 
9
13
  /** Reject an RPC endpoint that serves a different chain with the same network label. */
10
14
  export async function assertRpcGenesis(
11
15
  rpc: (method: string, params: any[]) => Promise<unknown>,
12
16
  expectedGenesisHash: string,
13
17
  ): Promise<void> {
14
- const actual = await rpc("getblockhash", [0]);
15
- if (typeof actual !== "string" || actual.toLowerCase() !== expectedGenesisHash.toLowerCase()) {
18
+ const actual = await rpc('getblockhash', [0]);
19
+ if (typeof actual !== 'string' || actual.toLowerCase() !== expectedGenesisHash.toLowerCase()) {
16
20
  throw new Error(`Unexpected genesis block: expected ${expectedGenesisHash}, received ${String(actual)}`);
17
21
  }
18
22
  }
@@ -26,17 +30,22 @@ export function rpcNumber(value: string): LosslessNumber {
26
30
  export function parseRpcJson(text: string): any {
27
31
  return parse(text, undefined, (token: string) => {
28
32
  const value = Number(token);
29
- return isSafeNumber(token) && Math.abs(value) <= Number.MAX_SAFE_INTEGER
30
- && (Number.isInteger(value) || Math.abs(value) <= Number.MAX_SAFE_INTEGER / 1e8)
31
- ? value : token;
33
+ return isSafeNumber(token) &&
34
+ Math.abs(value) <= Number.MAX_SAFE_INTEGER &&
35
+ (Number.isInteger(value) || Math.abs(value) <= Number.MAX_SAFE_INTEGER / 1e8)
36
+ ? value
37
+ : token;
32
38
  });
33
39
  }
34
40
 
35
41
  export function stringifyRpcJson(value: unknown): string {
36
42
  const result = stringify(value, (_key, item) => {
37
- if (typeof item === 'number' && (!Number.isFinite(item) ||
43
+ if (
44
+ typeof item === 'number' &&
45
+ (!Number.isFinite(item) ||
38
46
  (Number.isInteger(item) && !Number.isSafeInteger(item)) ||
39
- (!Number.isInteger(item) && Math.abs(item) > Number.MAX_SAFE_INTEGER / 1e8))) {
47
+ (!Number.isInteger(item) && Math.abs(item) > Number.MAX_SAFE_INTEGER / 1e8))
48
+ ) {
40
49
  throw new Error('Unsafe RPC numeric parameter: use bigint or rpcNumber(decimalText)');
41
50
  }
42
51
  return item;
@@ -45,11 +54,11 @@ export function stringifyRpcJson(value: unknown): string {
45
54
  return result;
46
55
  }
47
56
 
48
- // DePIN protocol 2 uses this same authenticated HTTP JSON-RPC transport. The
57
+ // DePIN protocol 5 uses this same authenticated HTTP JSON-RPC transport. The
49
58
  // former raw-TCP gateway and its dedicated port were removed from the node.
50
59
 
51
60
  function throwSyntaxError() {
52
- throw new Error("Syntax error, call getRPC with (username, password, URL)");
61
+ throw new Error('Syntax error, call getRPC with (username, password, URL)');
53
62
  }
54
63
 
55
64
  export function getRPC(username: string, password: string, URL: string) {
@@ -63,10 +72,10 @@ export function getRPC(username: string, password: string, URL: string) {
63
72
  throwSyntaxError();
64
73
  }
65
74
 
66
- return async function rpc(method: string, params: any[]) {
75
+ return async function rpc(method: string, params: any[] | Record<string, unknown>) {
67
76
  const promise = new Promise((resolutionFunc, rejectionFunc) => {
68
77
  const data = {
69
- jsonrpc: "2.0",
78
+ jsonrpc: '2.0',
70
79
  id: Math.random(),
71
80
  method,
72
81
  params,
@@ -84,13 +93,15 @@ export function getRPC(username: string, password: string, URL: string) {
84
93
  */
85
94
 
86
95
  if (response.ok) {
87
- const obj = parseRpcJson(await response.text()); //Convert to JSON
96
+ const responseText = await response.text();
97
+ if (isDepinRemoteMethod(method)) assertNoDuplicateJsonKeys(responseText);
98
+ const obj = parseRpcJson(responseText);
88
99
  // A JSON-RPC error can arrive with HTTP 200 — it must reject,
89
100
  // not resolve undefined.
90
101
  if (obj && obj.error) {
91
102
  rejectionFunc({
92
103
  error: obj.error,
93
- description: obj.error.message || "Unknown RPC error",
104
+ description: obj.error.message || 'Unknown RPC error',
94
105
  });
95
106
  } else {
96
107
  resolutionFunc(obj.result);
@@ -102,7 +113,9 @@ export function getRPC(username: string, password: string, URL: string) {
102
113
  description: null,
103
114
  };
104
115
  try {
105
- obj = parseRpcJson(await response.text());
116
+ const responseText = await response.text();
117
+ if (isDepinRemoteMethod(method)) assertNoDuplicateJsonKeys(responseText);
118
+ obj = parseRpcJson(responseText);
106
119
  } catch (e) {}
107
120
  const myError = {
108
121
  statusText: response.statusText,
@@ -117,10 +130,10 @@ export function getRPC(username: string, password: string, URL: string) {
117
130
  .catch((e) => {
118
131
  rejectionFunc({
119
132
  originalError: e,
120
- type: "ServerUnreachable",
121
- error: "Could not communicate with Neurai core node",
133
+ type: 'ServerUnreachable',
134
+ error: 'Could not communicate with Neurai core node',
122
135
  description:
123
- "Are you sure that the URL is correct? The URL is usually mainnet = http://127.0.0.1:19001 and testnet = http://127.0.0.1:19101",
136
+ 'Are you sure that the URL is correct? The URL is usually mainnet = http://127.0.0.1:19001 and testnet = http://127.0.0.1:19101',
124
137
  });
125
138
  });
126
139
  } catch (e) {
@@ -132,38 +145,31 @@ export function getRPC(username: string, password: string, URL: string) {
132
145
  }
133
146
  function getValidMethods() {
134
147
  const keys = Object.keys(methods).sort();
135
- return keys.join(" ");
148
+ return keys.join(' ');
136
149
  }
137
150
  // Example POST method implementation:
138
- async function postData(
139
- url = "",
140
- data = {},
141
- username: string,
142
- password: string
143
- ) {
144
- let base64Credentials = "";
151
+ async function postData(url = '', data = {}, username: string, password: string) {
152
+ let base64Credentials = '';
145
153
 
146
154
  //btoa or Buffer, depends if we are in Node.js or in the browser
147
- if (typeof btoa === "function") {
155
+ if (typeof btoa === 'function') {
148
156
  base64Credentials = btoa(`${username}:${password}`);
149
157
  } else if (Buffer) {
150
- base64Credentials = Buffer.from(`${username}:${password}`).toString(
151
- "base64"
152
- );
158
+ base64Credentials = Buffer.from(`${username}:${password}`).toString('base64');
153
159
  }
154
160
 
155
161
  // Default options are marked with *
156
162
  const response = await fetch(url, {
157
- method: "POST", // *GET, POST, PUT, DELETE, etc.
158
- mode: "cors", // no-cors, *cors, same-origin
163
+ method: 'POST', // *GET, POST, PUT, DELETE, etc.
164
+ mode: 'cors', // no-cors, *cors, same-origin
159
165
  headers: {
160
- Authorization: "Basic " + base64Credentials,
161
- "Content-Type": "application/json",
166
+ Authorization: 'Basic ' + base64Credentials,
167
+ 'Content-Type': 'application/json',
162
168
 
163
169
  // 'Content-Type': 'application/x-www-form-urlencoded',
164
170
  },
165
- redirect: "follow", // manual, *follow, error
166
- referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
171
+ redirect: 'follow', // manual, *follow, error
172
+ referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
167
173
  body: stringifyRpcJson(data), // body data type must match "Content-Type" header
168
174
  });
169
175
  return response;
@@ -298,7 +304,6 @@ export const methods = {
298
304
  "addmultisigaddress": "addmultisigaddress",
299
305
  "addwitnessaddress": "addwitnessaddress",
300
306
  "backupwallet": "backupwallet",
301
- "bumpfee": "bumpfee",
302
307
  "dumpprivkey": "dumpprivkey",
303
308
  "dumpwallet": "dumpwallet",
304
309
  "encryptwallet": "encryptwallet",
package/json.ts ADDED
@@ -0,0 +1,29 @@
1
+ /** Detect duplicate JSON property names, including equal values and escaped names.
2
+ * Syntax and numeric decoding are delegated to the JSON parser afterwards.
3
+ */
4
+ export function assertNoDuplicateJsonKeys(text: string): void {
5
+ const stack: Array<{ keys?: Set<string>; expectKey?: boolean; close: string }> = [];
6
+ for (let i = 0; i < text.length; i++) {
7
+ const ch = text[i];
8
+ if (ch === '"') {
9
+ const start = i++;
10
+ while (i < text.length && text[i] !== '"') {
11
+ if (text[i] === '\\') i++;
12
+ i++;
13
+ }
14
+ if (i >= text.length) throw new SyntaxError('Unterminated JSON string');
15
+ const top = stack[stack.length - 1];
16
+ if (top?.keys && top.expectKey) {
17
+ const key = JSON.parse(text.slice(start, i + 1));
18
+ if (top.keys.has(key)) throw new SyntaxError('Duplicate JSON key');
19
+ top.keys.add(key);
20
+ top.expectKey = false;
21
+ }
22
+ } else if (ch === '{' || ch === '[') {
23
+ if (stack.length >= 128) throw new SyntaxError('JSON nesting limit exceeded');
24
+ stack.push(ch === '{' ? { keys: new Set(), expectKey: true, close: '}' } : { close: ']' });
25
+ } else if (ch === '}' || ch === ']') {
26
+ if (stack.pop()?.close !== ch) throw new SyntaxError('Invalid JSON nesting');
27
+ } else if (ch === ',' && stack[stack.length - 1]?.keys) stack[stack.length - 1].expectKey = true;
28
+ }
29
+ }