@neuraiproject/neurai-rpc 0.6.2 → 0.8.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,7 +1,25 @@
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';
9
+
10
+ export const MAINNET_GENESIS_HASH = '00000044d33c0c0ba019be5c0249730424a69cb4c222153322f68c6104484806';
11
+ export const TESTNET_GENESIS_HASH = '0000008b384aeffecdab182575dc4e86c9f07f90318c65088532660ed9a8a021';
12
+
13
+ /** Reject an RPC endpoint that serves a different chain with the same network label. */
14
+ export async function assertRpcGenesis(
15
+ rpc: (method: string, params: any[]) => Promise<unknown>,
16
+ expectedGenesisHash: string,
17
+ ): Promise<void> {
18
+ const actual = await rpc('getblockhash', [0]);
19
+ if (typeof actual !== 'string' || actual.toLowerCase() !== expectedGenesisHash.toLowerCase()) {
20
+ throw new Error(`Unexpected genesis block: expected ${expectedGenesisHash}, received ${String(actual)}`);
21
+ }
22
+ }
5
23
 
6
24
  /** Exact decimal parameter, emitted as a JSON number rather than a quoted string. */
7
25
  export function rpcNumber(value: string): LosslessNumber {
@@ -12,17 +30,22 @@ export function rpcNumber(value: string): LosslessNumber {
12
30
  export function parseRpcJson(text: string): any {
13
31
  return parse(text, undefined, (token: string) => {
14
32
  const value = Number(token);
15
- return isSafeNumber(token) && Math.abs(value) <= Number.MAX_SAFE_INTEGER
16
- && (Number.isInteger(value) || Math.abs(value) <= Number.MAX_SAFE_INTEGER / 1e8)
17
- ? 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;
18
38
  });
19
39
  }
20
40
 
21
41
  export function stringifyRpcJson(value: unknown): string {
22
42
  const result = stringify(value, (_key, item) => {
23
- if (typeof item === 'number' && (!Number.isFinite(item) ||
43
+ if (
44
+ typeof item === 'number' &&
45
+ (!Number.isFinite(item) ||
24
46
  (Number.isInteger(item) && !Number.isSafeInteger(item)) ||
25
- (!Number.isInteger(item) && Math.abs(item) > Number.MAX_SAFE_INTEGER / 1e8))) {
47
+ (!Number.isInteger(item) && Math.abs(item) > Number.MAX_SAFE_INTEGER / 1e8))
48
+ ) {
26
49
  throw new Error('Unsafe RPC numeric parameter: use bigint or rpcNumber(decimalText)');
27
50
  }
28
51
  return item;
@@ -31,11 +54,11 @@ export function stringifyRpcJson(value: unknown): string {
31
54
  return result;
32
55
  }
33
56
 
34
- // 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
35
58
  // former raw-TCP gateway and its dedicated port were removed from the node.
36
59
 
37
60
  function throwSyntaxError() {
38
- throw new Error("Syntax error, call getRPC with (username, password, URL)");
61
+ throw new Error('Syntax error, call getRPC with (username, password, URL)');
39
62
  }
40
63
 
41
64
  export function getRPC(username: string, password: string, URL: string) {
@@ -49,10 +72,10 @@ export function getRPC(username: string, password: string, URL: string) {
49
72
  throwSyntaxError();
50
73
  }
51
74
 
52
- return async function rpc(method: string, params: any[]) {
75
+ return async function rpc(method: string, params: any[] | Record<string, unknown>) {
53
76
  const promise = new Promise((resolutionFunc, rejectionFunc) => {
54
77
  const data = {
55
- jsonrpc: "2.0",
78
+ jsonrpc: '2.0',
56
79
  id: Math.random(),
57
80
  method,
58
81
  params,
@@ -70,13 +93,15 @@ export function getRPC(username: string, password: string, URL: string) {
70
93
  */
71
94
 
72
95
  if (response.ok) {
73
- 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);
74
99
  // A JSON-RPC error can arrive with HTTP 200 — it must reject,
75
100
  // not resolve undefined.
76
101
  if (obj && obj.error) {
77
102
  rejectionFunc({
78
103
  error: obj.error,
79
- description: obj.error.message || "Unknown RPC error",
104
+ description: obj.error.message || 'Unknown RPC error',
80
105
  });
81
106
  } else {
82
107
  resolutionFunc(obj.result);
@@ -88,7 +113,9 @@ export function getRPC(username: string, password: string, URL: string) {
88
113
  description: null,
89
114
  };
90
115
  try {
91
- obj = parseRpcJson(await response.text());
116
+ const responseText = await response.text();
117
+ if (isDepinRemoteMethod(method)) assertNoDuplicateJsonKeys(responseText);
118
+ obj = parseRpcJson(responseText);
92
119
  } catch (e) {}
93
120
  const myError = {
94
121
  statusText: response.statusText,
@@ -103,10 +130,10 @@ export function getRPC(username: string, password: string, URL: string) {
103
130
  .catch((e) => {
104
131
  rejectionFunc({
105
132
  originalError: e,
106
- type: "ServerUnreachable",
107
- error: "Could not communicate with Neurai core node",
133
+ type: 'ServerUnreachable',
134
+ error: 'Could not communicate with Neurai core node',
108
135
  description:
109
- "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',
110
137
  });
111
138
  });
112
139
  } catch (e) {
@@ -118,38 +145,31 @@ export function getRPC(username: string, password: string, URL: string) {
118
145
  }
119
146
  function getValidMethods() {
120
147
  const keys = Object.keys(methods).sort();
121
- return keys.join(" ");
148
+ return keys.join(' ');
122
149
  }
123
150
  // Example POST method implementation:
124
- async function postData(
125
- url = "",
126
- data = {},
127
- username: string,
128
- password: string
129
- ) {
130
- let base64Credentials = "";
151
+ async function postData(url = '', data = {}, username: string, password: string) {
152
+ let base64Credentials = '';
131
153
 
132
154
  //btoa or Buffer, depends if we are in Node.js or in the browser
133
- if (typeof btoa === "function") {
155
+ if (typeof btoa === 'function') {
134
156
  base64Credentials = btoa(`${username}:${password}`);
135
157
  } else if (Buffer) {
136
- base64Credentials = Buffer.from(`${username}:${password}`).toString(
137
- "base64"
138
- );
158
+ base64Credentials = Buffer.from(`${username}:${password}`).toString('base64');
139
159
  }
140
160
 
141
161
  // Default options are marked with *
142
162
  const response = await fetch(url, {
143
- method: "POST", // *GET, POST, PUT, DELETE, etc.
144
- mode: "cors", // no-cors, *cors, same-origin
163
+ method: 'POST', // *GET, POST, PUT, DELETE, etc.
164
+ mode: 'cors', // no-cors, *cors, same-origin
145
165
  headers: {
146
- Authorization: "Basic " + base64Credentials,
147
- "Content-Type": "application/json",
166
+ Authorization: 'Basic ' + base64Credentials,
167
+ 'Content-Type': 'application/json',
148
168
 
149
169
  // 'Content-Type': 'application/x-www-form-urlencoded',
150
170
  },
151
- redirect: "follow", // manual, *follow, error
152
- 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
153
173
  body: stringifyRpcJson(data), // body data type must match "Content-Type" header
154
174
  });
155
175
  return response;
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
+ }