@neuraiproject/neurai-rpc 0.4.7 → 0.5.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/CHANGELOG.md +80 -0
- package/DEPIN_EXAMPLES.md +148 -220
- package/DEPIN_IMPLEMENTATION_GUIDE_EN.md +239 -70
- package/README.md +98 -46
- package/depin.ts +465 -214
- package/dist/depin.cjs +305 -0
- package/dist/depin.d.cts +96 -0
- package/dist/depin.d.ts +96 -0
- package/dist/depin.mjs +280 -0
- package/dist/index.cjs +5251 -4941
- package/dist/{types.d.ts → index.d.cts} +10 -63
- package/dist/index.d.ts +200 -0
- package/dist/index.mjs +5224 -4933
- package/docs.json +140 -134
- package/docs.ts +512 -64
- package/index.ts +13 -9
- package/neurai_methods.md +482 -64
- package/package.json +39 -11
- package/createDocs.mjs +0 -61
- package/dist/index.cjs.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/types.d.ts.map +0 -1
- package/test-depin.ts +0 -187
- package/test.js +0 -56
- package/tsconfig.json +0 -26
package/depin.ts
CHANGED
|
@@ -1,294 +1,545 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* DePIN RPC Client for Neurai
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* DePIN RPC Client for Neurai — Node.js only.
|
|
3
|
+
*
|
|
4
|
+
* The Neurai DePIN messaging gateway (default port 19002) speaks a raw TCP
|
|
5
|
+
* line protocol, NOT HTTP: the server reads bytes up to the first '\n' and
|
|
6
|
+
* processes that single line as either a protocol command (PING, INFO,
|
|
7
|
+
* AUTH|..., ...) or a serialized JSON-RPC object, answering with a single
|
|
8
|
+
* line as well. Because of that, this module uses `node:net` sockets and can
|
|
9
|
+
* only run in Node.js. Browsers cannot open raw TCP connections; to use DePIN
|
|
10
|
+
* from a browser you need an external HTTP/WebSocket proxy in front of the
|
|
11
|
+
* gateway.
|
|
12
|
+
*
|
|
13
|
+
* Import this module through the package subpath:
|
|
14
|
+
*
|
|
15
|
+
* ```typescript
|
|
16
|
+
* import { getDePinRPC } from "@neuraiproject/neurai-rpc/depin";
|
|
17
|
+
* ```
|
|
6
18
|
*/
|
|
7
19
|
|
|
20
|
+
import { createConnection } from "node:net";
|
|
21
|
+
|
|
22
|
+
/** Matches DEPIN_SOCKET_TIMEOUT in the node (seconds → ms). */
|
|
23
|
+
const DEPIN_SOCKET_TIMEOUT_MS = 30_000;
|
|
24
|
+
|
|
25
|
+
/** Matches DEPIN_MAX_PROTOCOL_SIZE in the node (10 MB) plus slack. */
|
|
26
|
+
const MAX_RESPONSE_BYTES = 10 * 1024 * 1024 + 1024;
|
|
27
|
+
|
|
28
|
+
/** Challenge type as issued by the gateway (AUTH|token|address|MODE). */
|
|
29
|
+
export type DePinChallengeMode = "SEND" | "RECEIVE" | "ADMIN";
|
|
30
|
+
|
|
31
|
+
export interface DePinTarget {
|
|
32
|
+
/** Gateway host, e.g. "127.0.0.1" */
|
|
33
|
+
host: string;
|
|
34
|
+
|
|
35
|
+
/** Gateway TCP port, e.g. 19002 */
|
|
36
|
+
port: number;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Socket timeout in milliseconds. Defaults to 30 000, matching the node's
|
|
40
|
+
* DEPIN_SOCKET_TIMEOUT.
|
|
41
|
+
*/
|
|
42
|
+
timeoutMs?: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
8
45
|
export interface DePinAuthOptions {
|
|
9
|
-
/** DePIN token name (e.g
|
|
46
|
+
/** DePIN token name (must start with '&', e.g. "&MYTOKEN" or a section like "&MYTOKEN/GENERAL") */
|
|
10
47
|
token: string;
|
|
11
|
-
|
|
48
|
+
|
|
12
49
|
/** Neurai address that will sign challenges */
|
|
13
50
|
address: string;
|
|
14
|
-
|
|
51
|
+
|
|
15
52
|
/** Function to sign messages (must return base64 signature) */
|
|
16
53
|
signMessage: (message: string) => Promise<string>;
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Challenge mode. Only honored by requestDePinChallenge(); getDePinRPC()
|
|
57
|
+
* derives the mode from the method being called and rejects a conflicting
|
|
58
|
+
* value here.
|
|
59
|
+
*/
|
|
60
|
+
mode?: DePinChallengeMode;
|
|
20
61
|
}
|
|
21
62
|
|
|
22
63
|
export interface DePinChallenge {
|
|
23
64
|
/** Challenge string from server */
|
|
24
65
|
challenge: string;
|
|
25
|
-
|
|
66
|
+
|
|
26
67
|
/** Timeout in seconds */
|
|
27
68
|
timeout: number;
|
|
28
|
-
|
|
69
|
+
|
|
29
70
|
/** Complete message that needs to be signed */
|
|
30
71
|
messageToSign: string;
|
|
31
72
|
}
|
|
32
73
|
|
|
74
|
+
/**
|
|
75
|
+
* Message-to-sign prefix per challenge mode, as verified by the node:
|
|
76
|
+
* DEPIN-SEND (depinsendmsg), DEPIN-GET (RECEIVE challenges) and
|
|
77
|
+
* DEPIN-CLEAR (ADMIN challenges for depinclearmsg).
|
|
78
|
+
*/
|
|
79
|
+
const SIGN_PREFIX: Record<DePinChallengeMode, string> = {
|
|
80
|
+
SEND: "DEPIN-SEND",
|
|
81
|
+
RECEIVE: "DEPIN-GET",
|
|
82
|
+
ADMIN: "DEPIN-CLEAR",
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Gateway authentication requirements per JSON-RPC method.
|
|
87
|
+
*
|
|
88
|
+
* - SEND: challenge/signature appended to params; the gateway validates and
|
|
89
|
+
* trims them before dispatching.
|
|
90
|
+
* - ADMIN: depinclearmsg only — the gateway expects
|
|
91
|
+
* [mode, address, challenge, signature] or
|
|
92
|
+
* [mode, scope, address, challenge, signature].
|
|
93
|
+
* - BLOCKED: depingetmsg over the gateway is blocked by a node-side bug (the
|
|
94
|
+
* gateway reads fromaddress from params[3], where depingetmsg carries it at
|
|
95
|
+
* index 1 or 2 and only accepts up to 3 arguments).
|
|
96
|
+
*
|
|
97
|
+
* Every other method is dispatched by the gateway without authentication and
|
|
98
|
+
* must be sent with its params untouched.
|
|
99
|
+
*/
|
|
100
|
+
const METHOD_AUTH: Record<string, "SEND" | "ADMIN" | "BLOCKED"> = {
|
|
101
|
+
depinsendmsg: "SEND",
|
|
102
|
+
depinclearmsg: "ADMIN",
|
|
103
|
+
depingetmsg: "BLOCKED",
|
|
104
|
+
};
|
|
105
|
+
|
|
33
106
|
interface DePinRPCContext {
|
|
34
|
-
|
|
35
|
-
authOptions
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
107
|
+
target: DePinTarget;
|
|
108
|
+
authOptions?: DePinAuthOptions;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function validateTarget(target: DePinTarget): void {
|
|
112
|
+
if (typeof target === "string") {
|
|
113
|
+
throw new Error(
|
|
114
|
+
"getDePinRPC no longer accepts a URL string. The DePIN gateway speaks " +
|
|
115
|
+
"raw TCP, not HTTP: pass an object { host, port }, e.g. " +
|
|
116
|
+
'{ host: "127.0.0.1", port: 19002 }'
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
if (!target || typeof target !== "object") {
|
|
120
|
+
throw new Error("A target object { host, port } is required for DePIN RPC");
|
|
121
|
+
}
|
|
122
|
+
if (!target.host || typeof target.host !== "string") {
|
|
123
|
+
throw new Error("target.host must be a non-empty string");
|
|
124
|
+
}
|
|
125
|
+
if (
|
|
126
|
+
typeof target.port !== "number" ||
|
|
127
|
+
!Number.isInteger(target.port) ||
|
|
128
|
+
target.port < 1 ||
|
|
129
|
+
target.port > 65535
|
|
130
|
+
) {
|
|
131
|
+
throw new Error("target.port must be an integer between 1 and 65535");
|
|
132
|
+
}
|
|
133
|
+
if (
|
|
134
|
+
target.timeoutMs !== undefined &&
|
|
135
|
+
(typeof target.timeoutMs !== "number" || target.timeoutMs <= 0)
|
|
136
|
+
) {
|
|
137
|
+
throw new Error("target.timeoutMs must be a positive number");
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function validateAuthOptions(authOptions: DePinAuthOptions): void {
|
|
142
|
+
if (!authOptions.token) {
|
|
143
|
+
throw new Error("Token is required for DePIN authentication");
|
|
144
|
+
}
|
|
145
|
+
if (!authOptions.address) {
|
|
146
|
+
throw new Error("Address is required for DePIN authentication");
|
|
147
|
+
}
|
|
148
|
+
if (
|
|
149
|
+
!authOptions.signMessage ||
|
|
150
|
+
typeof authOptions.signMessage !== "function"
|
|
151
|
+
) {
|
|
152
|
+
throw new Error("signMessage function is required for DePIN authentication");
|
|
153
|
+
}
|
|
41
154
|
}
|
|
42
155
|
|
|
43
156
|
/**
|
|
44
|
-
*
|
|
45
|
-
*
|
|
157
|
+
* Send one line over TCP and read one line back.
|
|
158
|
+
*
|
|
159
|
+
* The gateway protocol is strictly one request line, one response line, one
|
|
160
|
+
* connection per request (the server closes after answering). Bytes are
|
|
161
|
+
* accumulated as Buffers and only decoded once the newline is seen, so a
|
|
162
|
+
* multi-byte UTF-8 character split across 'data' events cannot be corrupted.
|
|
46
163
|
*/
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
try {
|
|
55
|
-
const response = await fetch(url, {
|
|
56
|
-
method: 'POST',
|
|
57
|
-
headers: {
|
|
58
|
-
'Content-Type': 'text/plain',
|
|
59
|
-
},
|
|
60
|
-
body: authCommand,
|
|
61
|
-
});
|
|
164
|
+
function sendLine(target: DePinTarget, line: string): Promise<string> {
|
|
165
|
+
const timeoutMs = target.timeoutMs ?? DEPIN_SOCKET_TIMEOUT_MS;
|
|
166
|
+
return new Promise((resolve, reject) => {
|
|
167
|
+
const socket = createConnection({ host: target.host, port: target.port });
|
|
168
|
+
const chunks: Buffer[] = [];
|
|
169
|
+
let received = 0;
|
|
170
|
+
let settled = false;
|
|
62
171
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
172
|
+
const finish = (error: Error | null, response?: string) => {
|
|
173
|
+
if (settled) {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
settled = true;
|
|
177
|
+
socket.destroy();
|
|
178
|
+
if (error) {
|
|
179
|
+
reject(error);
|
|
180
|
+
} else {
|
|
181
|
+
resolve(response as string);
|
|
182
|
+
}
|
|
183
|
+
};
|
|
66
184
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
185
|
+
socket.setTimeout(timeoutMs, () => {
|
|
186
|
+
finish(
|
|
187
|
+
new Error(
|
|
188
|
+
`DePIN request timed out after ${timeoutMs} ms (${target.host}:${target.port})`
|
|
189
|
+
)
|
|
190
|
+
);
|
|
191
|
+
});
|
|
73
192
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
193
|
+
socket.on("error", (e: Error) => {
|
|
194
|
+
finish(
|
|
195
|
+
new Error(
|
|
196
|
+
`Could not communicate with DePIN gateway at ${target.host}:${target.port}: ${e.message}`
|
|
197
|
+
)
|
|
198
|
+
);
|
|
199
|
+
});
|
|
78
200
|
|
|
79
|
-
|
|
80
|
-
|
|
201
|
+
socket.on("connect", () => {
|
|
202
|
+
socket.write(line.endsWith("\n") ? line : line + "\n");
|
|
203
|
+
});
|
|
81
204
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
205
|
+
socket.on("data", (chunk: Buffer) => {
|
|
206
|
+
chunks.push(chunk);
|
|
207
|
+
received += chunk.length;
|
|
85
208
|
|
|
86
|
-
|
|
87
|
-
|
|
209
|
+
if (received > MAX_RESPONSE_BYTES) {
|
|
210
|
+
finish(new Error("DePIN response exceeded the 10 MB protocol limit"));
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
88
213
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
214
|
+
if (chunk.includes(0x0a)) {
|
|
215
|
+
const all = Buffer.concat(chunks);
|
|
216
|
+
const nl = all.indexOf(0x0a);
|
|
217
|
+
finish(null, all.subarray(0, nl).toString("utf8"));
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
socket.on("close", () => {
|
|
222
|
+
finish(
|
|
223
|
+
new Error(
|
|
224
|
+
"DePIN gateway closed the connection before sending a complete response"
|
|
225
|
+
)
|
|
226
|
+
);
|
|
227
|
+
});
|
|
228
|
+
});
|
|
97
229
|
}
|
|
98
230
|
|
|
99
231
|
/**
|
|
100
|
-
*
|
|
232
|
+
* Request a challenge from the DePIN gateway: AUTH|token|address|mode
|
|
101
233
|
*/
|
|
102
|
-
async function
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
): Promise<
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
mode
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
234
|
+
async function requestChallenge(
|
|
235
|
+
target: DePinTarget,
|
|
236
|
+
token: string,
|
|
237
|
+
address: string,
|
|
238
|
+
mode: DePinChallengeMode
|
|
239
|
+
): Promise<DePinChallenge> {
|
|
240
|
+
const responseText = await sendLine(
|
|
241
|
+
target,
|
|
242
|
+
`AUTH|${token}|${address}|${mode}`
|
|
243
|
+
);
|
|
244
|
+
|
|
245
|
+
// Parse response: CHALLENGE|<challenge>|<timeout>
|
|
246
|
+
if (!responseText.startsWith("CHALLENGE|")) {
|
|
247
|
+
throw new Error(`Invalid challenge response: ${responseText}`);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const parts = responseText.split("|");
|
|
251
|
+
if (parts.length < 3) {
|
|
252
|
+
throw new Error(`Malformed challenge response: ${responseText}`);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const challenge = parts[1];
|
|
256
|
+
const timeout = parseInt(parts[2], 10);
|
|
257
|
+
|
|
258
|
+
if (!challenge || isNaN(timeout)) {
|
|
259
|
+
throw new Error(`Invalid challenge data: ${responseText}`);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return {
|
|
263
|
+
challenge,
|
|
264
|
+
timeout,
|
|
265
|
+
messageToSign: `${SIGN_PREFIX[mode]}|${token}|${address}|${challenge}`,
|
|
266
|
+
};
|
|
118
267
|
}
|
|
119
268
|
|
|
120
269
|
/**
|
|
121
|
-
*
|
|
270
|
+
* Request a fresh challenge for one authenticated call.
|
|
271
|
+
*
|
|
272
|
+
* Challenges are strictly single-use: the node erases the nonce from its map
|
|
273
|
+
* when it validates it (ValidateChallenge in depinmsgpoolnet.cpp), so they
|
|
274
|
+
* must never be cached or reused — a second request with the same nonce
|
|
275
|
+
* fails with "Challenge not found".
|
|
122
276
|
*/
|
|
123
|
-
async function
|
|
277
|
+
async function freshChallenge(
|
|
124
278
|
context: DePinRPCContext,
|
|
125
|
-
|
|
279
|
+
mode: DePinChallengeMode,
|
|
280
|
+
token: string
|
|
126
281
|
): Promise<string> {
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
282
|
+
const auth = context.authOptions as DePinAuthOptions;
|
|
283
|
+
const challengeData = await requestChallenge(
|
|
284
|
+
context.target,
|
|
285
|
+
token,
|
|
286
|
+
auth.address,
|
|
287
|
+
mode
|
|
288
|
+
);
|
|
289
|
+
return challengeData.challenge;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async function signChallenge(
|
|
293
|
+
auth: DePinAuthOptions,
|
|
294
|
+
mode: DePinChallengeMode,
|
|
295
|
+
token: string,
|
|
296
|
+
challenge: string
|
|
297
|
+
): Promise<string> {
|
|
298
|
+
const messageToSign = `${SIGN_PREFIX[mode]}|${token}|${auth.address}|${challenge}`;
|
|
299
|
+
const signature = await auth.signMessage(messageToSign);
|
|
300
|
+
if (!signature) {
|
|
301
|
+
throw new Error("Signature function returned empty result");
|
|
136
302
|
}
|
|
303
|
+
return signature;
|
|
304
|
+
}
|
|
137
305
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
306
|
+
/**
|
|
307
|
+
* Build the params the gateway expects for an authenticated method, using a
|
|
308
|
+
* fresh single-use challenge.
|
|
309
|
+
*/
|
|
310
|
+
async function buildAuthenticatedParams(
|
|
311
|
+
context: DePinRPCContext,
|
|
312
|
+
method: string,
|
|
313
|
+
params: any[]
|
|
314
|
+
): Promise<{ params: any[]; mode: DePinChallengeMode; token: string }> {
|
|
315
|
+
const auth = context.authOptions as DePinAuthOptions;
|
|
141
316
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
317
|
+
if (method === "depinsendmsg") {
|
|
318
|
+
// Gateway shape: [token, ip, message, fromaddress, (port), challenge, signature]
|
|
319
|
+
// It requires >= 4 params before the appended pair, reads fromaddress
|
|
320
|
+
// from params[3] and validates the challenge against (params[0], params[3]).
|
|
321
|
+
const sendParams = [...params];
|
|
322
|
+
if (sendParams.length === 3) {
|
|
323
|
+
// Fill in fromaddress with the authenticated address.
|
|
324
|
+
sendParams.push(auth.address);
|
|
325
|
+
}
|
|
326
|
+
if (sendParams.length < 4 || typeof sendParams[3] !== "string") {
|
|
327
|
+
throw new Error(
|
|
328
|
+
"depinsendmsg over the gateway needs [token, ip, message, fromaddress]"
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
if (sendParams[3] !== auth.address) {
|
|
332
|
+
throw new Error(
|
|
333
|
+
`depinsendmsg fromaddress (${sendParams[3]}) must be the authenticated address (${auth.address})`
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
const token = String(sendParams[0]);
|
|
337
|
+
const challenge = await freshChallenge(context, "SEND", token);
|
|
338
|
+
const signature = await signChallenge(auth, "SEND", token, challenge);
|
|
339
|
+
return {
|
|
340
|
+
params: [...sendParams, challenge, signature],
|
|
341
|
+
mode: "SEND",
|
|
342
|
+
token,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
148
345
|
|
|
149
|
-
|
|
346
|
+
// depinclearmsg — ADMIN challenge, owner only. Caller shape: [] | [mode] |
|
|
347
|
+
// [mode, scope]. Gateway shape: [mode, address, challenge, signature] or
|
|
348
|
+
// [mode, scope, address, challenge, signature]. With a scope the challenge
|
|
349
|
+
// must have been issued FOR that scope token.
|
|
350
|
+
if (params.length > 2) {
|
|
351
|
+
throw new Error(
|
|
352
|
+
'depinclearmsg accepts at most [mode, scope], e.g. ["all", "&TOKEN/GENERAL"]'
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
const mode = params.length >= 1 ? params[0] : null;
|
|
356
|
+
const scope = params.length === 2 ? params[1] : undefined;
|
|
357
|
+
if (scope !== undefined && typeof scope !== "string") {
|
|
358
|
+
throw new Error("depinclearmsg scope must be a string");
|
|
359
|
+
}
|
|
360
|
+
const token = scope || auth.token;
|
|
361
|
+
const challenge = await freshChallenge(context, "ADMIN", token);
|
|
362
|
+
const signature = await signChallenge(auth, "ADMIN", token, challenge);
|
|
363
|
+
return {
|
|
364
|
+
params:
|
|
365
|
+
scope === undefined
|
|
366
|
+
? [mode, auth.address, challenge, signature]
|
|
367
|
+
: [mode, scope, auth.address, challenge, signature],
|
|
368
|
+
mode: "ADMIN",
|
|
369
|
+
token,
|
|
370
|
+
};
|
|
150
371
|
}
|
|
151
372
|
|
|
152
373
|
/**
|
|
153
|
-
* Create a DePIN RPC client
|
|
154
|
-
*
|
|
155
|
-
* @param
|
|
156
|
-
* @param authOptions
|
|
374
|
+
* Create a DePIN RPC client for the raw-TCP gateway. Node.js only.
|
|
375
|
+
*
|
|
376
|
+
* @param target Gateway address, e.g. { host: "127.0.0.1", port: 19002 }
|
|
377
|
+
* @param authOptions Optional authentication. Without it the client can call
|
|
378
|
+
* the unauthenticated gateway methods (depinreceivemsg, depinsubmitmsg,
|
|
379
|
+
* depingetmsginfo, depingetpoolcontent, depinpoolstats, depinmcpstatus,
|
|
380
|
+
* depinlistsections, depinpoolpkey); calling an authenticated method then
|
|
381
|
+
* fails with a clear error.
|
|
157
382
|
* @returns Async RPC function
|
|
158
|
-
*
|
|
383
|
+
*
|
|
159
384
|
* @example
|
|
160
385
|
* ```typescript
|
|
161
|
-
* import { getDePinRPC } from "@neuraiproject/neurai-rpc";
|
|
162
|
-
*
|
|
163
|
-
* const depinRpc = getDePinRPC(
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
* }
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
* "MYTOKEN",
|
|
176
|
-
* "localhost",
|
|
177
|
-
* "Hello from DePIN!",
|
|
178
|
-
* "NXmyaddress..."
|
|
386
|
+
* import { getDePinRPC } from "@neuraiproject/neurai-rpc/depin";
|
|
387
|
+
*
|
|
388
|
+
* const depinRpc = getDePinRPC(
|
|
389
|
+
* { host: "127.0.0.1", port: 19002 },
|
|
390
|
+
* {
|
|
391
|
+
* token: "&MYTOKEN",
|
|
392
|
+
* address: "NXmyaddress...",
|
|
393
|
+
* signMessage: async (msg) => wallet.signMessage(msg),
|
|
394
|
+
* }
|
|
395
|
+
* );
|
|
396
|
+
*
|
|
397
|
+
* // Authenticated send (challenge/signature handled automatically)
|
|
398
|
+
* await depinRpc("depinsendmsg", [
|
|
399
|
+
* "&MYTOKEN", "127.0.0.1", "Hello from DePIN!", "NXmyaddress...",
|
|
179
400
|
* ]);
|
|
401
|
+
*
|
|
402
|
+
* // Unauthenticated query (params sent untouched)
|
|
403
|
+
* const info = await depinRpc("depingetmsginfo", []);
|
|
180
404
|
* ```
|
|
181
405
|
*/
|
|
182
|
-
export function getDePinRPC(
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
if (!authOptions.address) {
|
|
190
|
-
throw new Error('Address is required for DePIN authentication');
|
|
191
|
-
}
|
|
192
|
-
if (!authOptions.signMessage || typeof authOptions.signMessage !== 'function') {
|
|
193
|
-
throw new Error('signMessage function is required for DePIN authentication');
|
|
406
|
+
export function getDePinRPC(
|
|
407
|
+
target: DePinTarget,
|
|
408
|
+
authOptions?: DePinAuthOptions
|
|
409
|
+
) {
|
|
410
|
+
validateTarget(target);
|
|
411
|
+
if (authOptions !== undefined) {
|
|
412
|
+
validateAuthOptions(authOptions);
|
|
194
413
|
}
|
|
195
414
|
|
|
196
415
|
const context: DePinRPCContext = {
|
|
197
|
-
|
|
416
|
+
target,
|
|
198
417
|
authOptions,
|
|
199
418
|
};
|
|
200
419
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
// Get valid challenge
|
|
210
|
-
const challenge = await ensureValidChallenge(context, requiredMode);
|
|
420
|
+
async function depinRpc(
|
|
421
|
+
method: string,
|
|
422
|
+
params: any[],
|
|
423
|
+
isRetry: boolean = false
|
|
424
|
+
): Promise<any> {
|
|
425
|
+
try {
|
|
426
|
+
const authKind = METHOD_AUTH[method];
|
|
211
427
|
|
|
212
|
-
|
|
213
|
-
|
|
428
|
+
if (authKind === "BLOCKED") {
|
|
429
|
+
throw new Error(
|
|
430
|
+
"depingetmsg over the DePIN gateway is blocked by a node-side bug " +
|
|
431
|
+
"(the gateway reads fromaddress from params[3], but depingetmsg " +
|
|
432
|
+
"carries it at index 1 or 2 and accepts at most 3 arguments). " +
|
|
433
|
+
"Use depinreceivemsg over the gateway, or call depingetmsg " +
|
|
434
|
+
"through the node RPC port instead."
|
|
435
|
+
);
|
|
436
|
+
}
|
|
214
437
|
|
|
215
|
-
|
|
216
|
-
|
|
438
|
+
let mode: DePinChallengeMode | undefined;
|
|
439
|
+
let token: string | undefined;
|
|
440
|
+
let requestParams = params;
|
|
217
441
|
|
|
218
|
-
|
|
219
|
-
|
|
442
|
+
if (authKind !== undefined) {
|
|
443
|
+
if (!context.authOptions) {
|
|
444
|
+
throw new Error(
|
|
445
|
+
`${method} requires authentication: create the client with ` +
|
|
446
|
+
"getDePinRPC(target, { token, address, signMessage })"
|
|
447
|
+
);
|
|
448
|
+
}
|
|
449
|
+
const derived: DePinChallengeMode =
|
|
450
|
+
authKind === "SEND" ? "SEND" : "ADMIN";
|
|
451
|
+
if (context.authOptions.mode && context.authOptions.mode !== derived) {
|
|
452
|
+
throw new Error(
|
|
453
|
+
`${method} needs a ${derived} challenge, which conflicts with ` +
|
|
454
|
+
`mode "${context.authOptions.mode}" in the auth options. The ` +
|
|
455
|
+
"mode option is only honored by requestDePinChallenge(); omit " +
|
|
456
|
+
"it here — getDePinRPC derives it per method."
|
|
457
|
+
);
|
|
220
458
|
}
|
|
459
|
+
const built = await buildAuthenticatedParams(context, method, params);
|
|
460
|
+
requestParams = built.params;
|
|
461
|
+
mode = built.mode;
|
|
462
|
+
token = built.token;
|
|
463
|
+
}
|
|
221
464
|
|
|
222
|
-
|
|
223
|
-
|
|
465
|
+
const requestData = {
|
|
466
|
+
jsonrpc: "2.0",
|
|
467
|
+
id: Math.random(),
|
|
468
|
+
method,
|
|
469
|
+
params: requestParams,
|
|
470
|
+
};
|
|
224
471
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
472
|
+
const responseText = await sendLine(
|
|
473
|
+
context.target,
|
|
474
|
+
JSON.stringify(requestData)
|
|
475
|
+
);
|
|
476
|
+
|
|
477
|
+
if (responseText.startsWith("ERROR|")) {
|
|
478
|
+
throw new Error(responseText.slice("ERROR|".length));
|
|
479
|
+
}
|
|
232
480
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
481
|
+
let responseData: any;
|
|
482
|
+
try {
|
|
483
|
+
responseData = JSON.parse(responseText);
|
|
484
|
+
} catch (e) {
|
|
485
|
+
throw new Error(
|
|
486
|
+
`Invalid JSON-RPC response from DePIN gateway: ${responseText.slice(0, 200)}`
|
|
239
487
|
);
|
|
488
|
+
}
|
|
240
489
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
// Retry the request with a new challenge
|
|
254
|
-
return depinRpc(method, params).then(resolve).catch(reject);
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
reject({
|
|
258
|
-
error: responseData.error,
|
|
259
|
-
description: responseData.error.message || 'Unknown error',
|
|
260
|
-
});
|
|
261
|
-
} else {
|
|
262
|
-
resolve(responseData.result);
|
|
263
|
-
}
|
|
264
|
-
} else {
|
|
265
|
-
const errorData = await response.json().catch(() => ({}));
|
|
266
|
-
reject({
|
|
267
|
-
statusText: response.statusText,
|
|
268
|
-
status: response.status,
|
|
269
|
-
error: errorData.error,
|
|
270
|
-
description: errorData.error?.message || 'Request failed',
|
|
271
|
-
});
|
|
490
|
+
if (responseData.error) {
|
|
491
|
+
// On an expired challenge: retry once — the retry requests a fresh
|
|
492
|
+
// nonce, since every authenticated attempt does.
|
|
493
|
+
if (
|
|
494
|
+
!isRetry &&
|
|
495
|
+
mode !== undefined &&
|
|
496
|
+
token !== undefined &&
|
|
497
|
+
responseData.error.message &&
|
|
498
|
+
responseData.error.message.includes("expired")
|
|
499
|
+
) {
|
|
500
|
+
return depinRpc(method, params, true);
|
|
272
501
|
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
description: 'Check that the DePIN server URL is correct and that the server is running',
|
|
279
|
-
});
|
|
502
|
+
|
|
503
|
+
throw {
|
|
504
|
+
error: responseData.error,
|
|
505
|
+
description: responseData.error.message || "Unknown error",
|
|
506
|
+
};
|
|
280
507
|
}
|
|
281
|
-
|
|
282
|
-
|
|
508
|
+
|
|
509
|
+
return responseData.result;
|
|
510
|
+
} catch (error: any) {
|
|
511
|
+
if (error && (error.error || error.description)) {
|
|
512
|
+
// Already a structured RPC error
|
|
513
|
+
throw error;
|
|
514
|
+
}
|
|
515
|
+
throw {
|
|
516
|
+
originalError: error,
|
|
517
|
+
type: "DePinRequestError",
|
|
518
|
+
error:
|
|
519
|
+
(error && error.message) ||
|
|
520
|
+
"Failed to communicate with DePIN gateway",
|
|
521
|
+
description:
|
|
522
|
+
"Check that the DePIN gateway host/port are correct and that the " +
|
|
523
|
+
"node is running with the gateway enabled",
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
return (method: string, params: any[]) => depinRpc(method, params);
|
|
283
529
|
}
|
|
284
530
|
|
|
285
531
|
/**
|
|
286
|
-
*
|
|
287
|
-
*
|
|
532
|
+
* Request a challenge without making an RPC call. Useful for testing or
|
|
533
|
+
* manual challenge handling. Honors authOptions.mode ("SEND", "RECEIVE" or
|
|
534
|
+
* "ADMIN"; default "RECEIVE") and returns the exact message that must be
|
|
535
|
+
* signed for that mode (DEPIN-SEND|, DEPIN-GET| or DEPIN-CLEAR|).
|
|
288
536
|
*/
|
|
289
537
|
export async function requestDePinChallenge(
|
|
290
|
-
|
|
538
|
+
target: DePinTarget,
|
|
291
539
|
authOptions: DePinAuthOptions
|
|
292
540
|
): Promise<DePinChallenge> {
|
|
293
|
-
|
|
541
|
+
validateTarget(target);
|
|
542
|
+
validateAuthOptions(authOptions);
|
|
543
|
+
const mode: DePinChallengeMode = authOptions.mode || "RECEIVE";
|
|
544
|
+
return requestChallenge(target, authOptions.token, authOptions.address, mode);
|
|
294
545
|
}
|