@neuraiproject/neurai-rpc 0.5.1 → 0.6.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.
@@ -1,1125 +1,104 @@
1
- # DePIN Implementation Technical Guide for Neurai RPC
1
+ # Neurai DePIN protocol 2 integration guide
2
2
 
3
- ## Change Summary
3
+ ## Architecture
4
4
 
5
- This guide covers the RPC commands of Neurai's DePIN (Decentralized Physical
6
- Infrastructure Networks) system — asset management, encrypted messaging and
7
- AI/MCP monitoring — and the library's DePIN client. As of 0.5.0 the client
8
- speaks the gateway's real raw-TCP line protocol from the Node.js-only entry
9
- `@neuraiproject/neurai-rpc/depin` (see §3.2 and the changelog in §10).
5
+ DePIN protocol 2 is served through Neurai's standard authenticated HTTP
6
+ JSON-RPC interface: port `19001` on mainnet and `19101` on testnet. There is no
7
+ separate TCP gateway. Applications use `getRPC` for every DePIN operation.
10
8
 
11
- **Version:** 0.5.0
12
- **Date:** August 2026
13
- **Branch:** master
9
+ ## Roles
14
10
 
15
- ---
11
+ - The service node owns a dedicated wallet key used as the pool key. Its
12
+ public key is published by `depingetmsginfo`.
13
+ - A holder address must have its public key revealed on chain before the node
14
+ can encrypt responses for it.
15
+ - Clients pin the pool public key on first use, verify `poolsig` on replies,
16
+ and encrypt `depinsubmitmsg` envelopes for that key.
17
+ - `depinsignrequest`, `depinsignchallenge`, and `depindecrypt` are convenience
18
+ RPCs for keys held by the local node wallet. External wallets implement the
19
+ same signing and ECIES operations client-side.
16
20
 
17
- ## 1. DePIN Architecture
21
+ ## Challenge authentication
18
22
 
19
- ### 1.1 Dual-Port Architecture
23
+ Authenticated reads use type `receive`; destructive cleanup uses type
24
+ `admin`.
20
25
 
21
- The DePIN system uses two distinct ports for different operations:
26
+ 1. Sign `DEPIN-REQ|<type>|<token>|<address>|<unix_time_ms>`.
27
+ 2. Call `depinchallenge(token, address, timestamp, signature, type)`.
28
+ 3. Verify the response's `poolsig` and decrypt its `encrypted` field.
29
+ 4. Sign `DEPIN-GET|<token>|<address>|<nonce>` for reads or
30
+ `DEPIN-CLEAR|<token>|<address>|<nonce>` for cleanup.
31
+ 5. Pass the nonce and signature to the protected RPC.
22
32
 
23
- - **Ports 19001 (mainnet) / 19101 (testnet)** (standard RPC, HTTP): Asset management commands and queries
24
- - **Port 19002** (DePIN gateway, raw TCP): Encrypted messaging and P2P operations (default of `-depinmsgport`, same on every network)
33
+ Request signatures are time-bounded and replay-protected. Challenges are
34
+ bound to type, token/scope, and address; they expire and are consumed by their
35
+ first successful use. Read responses can include `next_challenge` to avoid
36
+ another challenge-request round trip.
25
37
 
26
- ### 1.2 DePIN Asset Types
38
+ ## Messaging RPCs
27
39
 
28
- There are two related but different concepts in the current DePIN stack:
40
+ Public and diagnostic:
29
41
 
30
- - **DePIN messaging token:** the DEPIN asset configured in `depinmsgtoken` for gateway messaging. It must start with `&` (e.g. `&FRANCE`); sections like `&FRANCE/GENERAL` scope hierarchical pools.
31
- - **Dedicated DePIN asset type:** a newer asset class used by the asset-management RPCs (`checkdepinvalidity`, `listdepinholders`, `freezedepin`, `unfreezedepin`, `selfrevokedepin`). These assets use the `&` prefix, are soulbound, are currently enabled on **testnet and regtest only** in the node, require the owner token `&ASSET!`, and must be issued and reissued with `units=0`.
42
+ - `depingetmsginfo()` publishes protocol configuration and the pool key.
43
+ - `depinpoolstats()` returns pool statistics.
44
+ - `depinmcpstatus()` returns MCP worker state.
45
+ - `depinlistsections()` returns public section names.
46
+ - `depingetancestorrecipients(token, max_results?, stop_at?)` resolves active
47
+ holders with revealed public keys.
32
48
 
33
- ---
49
+ Wallet-backed local operations:
34
50
 
35
- ## 2. Newly Added RPC Commands
51
+ - `depinsendmsg(token, message, fromaddress)` signs, encrypts, and stores a
52
+ message in the local pool.
53
+ - `depingetmsg(token, fromaddress?)` decrypts local-pool messages.
54
+ - `depinpoolpkey()` derives the pool key from the service wallet.
55
+ - `depinsignrequest`, `depinsignchallenge`, and `depindecrypt` assist scripts.
36
56
 
37
- ### 2.1 DePIN Asset Management Commands
57
+ Remote and non-custodial operations:
38
58
 
39
- #### **checkdepinvalidity**
40
- Checks whether a DePIN asset is valid for a specific address.
59
+ - `depinsubmitmsg({sender, encrypted})` accepts a signed message wrapped in an
60
+ ECIES envelope for the pool key. Bare serialized hex is invalid.
61
+ - `depinreceivemsg(token, address, challenge, signature, timestamp?,
62
+ after_hash?, limit?)` returns an encrypted, pool-signed page.
63
+ - `depinlistsections(address, scope, challenge, signature)` returns encrypted
64
+ personal access and counters for the selected subtree.
65
+ - `depinclearmsg(scope, address, challenge, signature, mode?)` performs an
66
+ owner-authorized purge. Omit mode for expired messages, use `"all"` for all
67
+ messages, or pass a numeric age in hours.
41
68
 
42
- **Signature:**
43
- ```typescript
44
- checkdepinvalidity(asset_name: string, address: string): Promise<{
45
- has_asset: boolean;
46
- amount?: number;
47
- valid?: 0 | 1;
48
- blocked?: boolean;
49
- }>
50
- ```
51
-
52
- **Example:**
53
- ```javascript
54
- const rpc = getRPC('username', 'password', 'http://127.0.0.1:19001');
55
- const result = await rpc('checkdepinvalidity', ['&FRANCE', 'NXabcd...']);
56
- // Returns: { has_asset: true, amount: 1, valid: 1, blocked: false }
57
- ```
58
-
59
- **Port:** standard RPC (19001 mainnet / 19101 testnet)
60
- **Requires Wallet:** No
61
-
62
- ---
63
-
64
- #### **listdepinholders**
65
- Lists all holders of a DePIN asset along with their validity status.
66
-
67
- **Signature:**
68
- ```typescript
69
- listdepinholders(asset_name: string): Promise<Array<{
70
- address: string;
71
- amount: number;
72
- valid: 0 | 1;
73
- }>>
74
- ```
75
-
76
- **Example:**
77
- ```javascript
78
- const holders = await rpc('listdepinholders', ['&FRANCE']);
79
- // Returns: [
80
- // { address: 'NXabc...', amount: 1, valid: 1 },
81
- // { address: 'NXdef...', amount: 1, valid: 0 }
82
- // ]
83
- ```
84
-
85
- **Port:** standard RPC (19001 mainnet / 19101 testnet)
86
- **Requires:** `-assetindex` enabled on the node
87
-
88
- ---
89
-
90
- #### **listdepinaddresses**
91
- Lists addresses that own an asset and have already revealed a public key on-chain.
92
- This is useful when discovering recipients for DePIN messaging.
93
-
94
- **Signature:**
95
- ```typescript
96
- listdepinaddresses(asset_name: string, count?: number, start?: number): Promise<Array<{
97
- address: string;
98
- pubkey: string;
99
- }>>
100
- ```
101
-
102
- **Example:**
103
- ```javascript
104
- const recipients = await rpc('listdepinaddresses', ['&FRANCE']);
105
- // Returns: [
106
- // { address: 'NXabc...', pubkey: '02ab...' },
107
- // { address: 'NXdef...', pubkey: '03cd...' }
108
- // ]
109
- ```
110
-
111
- **Port:** standard RPC (19001 mainnet / 19101 testnet)
112
- **Requires:** `-assetindex` and `-pubkeyindex` enabled on the node
113
-
114
- ---
115
-
116
- #### **freezedepin**
117
- Freezes a DePIN asset for a specific address (owner only).
118
-
119
- **Signature:**
120
- ```typescript
121
- freezedepin(
122
- asset_name: string,
123
- address: string,
124
- change_address?: string
125
- ): Promise<string> // txid
126
- ```
127
-
128
- **Example:**
129
- ```javascript
130
- const txid = await rpc('freezedepin', ['&FRANCE', 'NXmalicious...']);
131
- // Returns: "a1b2c3d4e5f6..." (transaction ID)
132
- ```
69
+ `depingetpoolcontent` was removed because it exposed pool-wide metadata
70
+ without an identity to authenticate.
133
71
 
134
- **Port:** standard RPC (19001 mainnet / 19101 testnet)
135
- **Requires:** Owner token `&FRANCE!` in the wallet
72
+ ## DePIN asset RPCs
136
73
 
137
- ---
74
+ - `checkdepinvalidity(asset_name, address)`
75
+ - `listdepinholders(asset_name)`
76
+ - `listdepinaddresses(asset_name, count?, start?)`
77
+ - `freezedepin(asset_name, address, change_address?)`
78
+ - `unfreezedepin(asset_name, address, change_address?)`
79
+ - `selfrevokedepin(asset_name)`
138
80
 
139
- #### **unfreezedepin**
140
- Unfreezes a previously frozen DePIN asset (owner only).
81
+ Wallet-changing methods require an enabled wallet. Chain-wide holder queries
82
+ require the indexes specified by the node's RPC help.
141
83
 
142
- **Signature:**
143
- ```typescript
144
- unfreezedepin(
145
- asset_name: string,
146
- address: string,
147
- change_address?: string
148
- ): Promise<string> // txid
149
- ```
150
-
151
- **Port:** standard RPC (19001 mainnet / 19101 testnet)
152
- **Requires:** Owner token `ASSET!` in the wallet
153
-
154
- ---
155
-
156
- #### **selfrevokedepin**
157
- Allows a holder to self-revoke their DePIN asset (this action can only be undone by the asset owner).
84
+ ## JavaScript client
158
85
 
159
- **Signature:**
160
- ```typescript
161
- selfrevokedepin(asset_name: string): Promise<string> // txid
162
- ```
86
+ ```js
87
+ import { getRPC, methods } from "@neuraiproject/neurai-rpc";
163
88
 
164
- **Example:**
165
- ```javascript
166
- const txid = await rpc('selfrevokedepin', ['&FRANCE']);
89
+ const rpc = getRPC("rpcuser", "rpcpassword", "http://127.0.0.1:19001");
90
+ const info = await rpc(methods.depingetmsginfo, []);
167
91
  ```
168
92
 
169
- **Port:** standard RPC (19001 mainnet / 19101 testnet)
170
- **Requires Wallet:** Yes (the wallet must hold the asset)
171
-
172
- ---
173
-
174
- ### 2.2 DePIN Messaging Commands
175
-
176
- #### **depingetmsginfo**
177
- Returns information about the DePIN messaging system.
178
-
179
- **Signature:**
180
- ```typescript
181
- depingetmsginfo(): Promise<{
182
- enabled: boolean;
183
- token: string;
184
- port: number;
185
- maxrecipients: number;
186
- maxmessagesize: number;
187
- messageexpiryhours: number;
188
- maxpoolsizemb: number;
189
- messages: number;
190
- memoryusage: number;
191
- memoryusagemb: number;
192
- oldestmessage?: string;
193
- newestmessage?: string;
194
- }>
195
- ```
196
-
197
- **Example:**
198
- ```javascript
199
- const info = await rpc('depingetmsginfo', []);
200
- // Returns: {
201
- // enabled: true,
202
- // token: "&FRANCE",
203
- // port: 19002,
204
- // maxmessagesize: 1024,
205
- // messages: 42,
206
- // ...
207
- // }
208
- ```
209
-
210
- **Port:** standard RPC (19001 mainnet / 19101 testnet)
211
-
212
- ---
213
-
214
- #### **depinsendmsg**
215
- Sends an encrypted message through a remote DePIN gateway using challenge/response.
216
-
217
- **Signature:**
218
- ```typescript
219
- depinsendmsg(
220
- token: string,
221
- ip_port: string, // "192.168.1.100" or "192.168.1.100:19002"
222
- message: string, // Max 1KB
223
- fromaddress: string,
224
- port?: number // Override port (default: 19002)
225
- ): Promise<{
226
- result: string;
227
- hash: string;
228
- recipients: number;
229
- timestamp: number;
230
- }>
231
- ```
232
-
233
- **Operation flow:**
234
- 1. Client connects to remote gateway on port 19002
235
- 2. Requests challenge: `AUTH|TOKEN|ADDRESS|SEND`
236
- 3. Gateway responds: `CHALLENGE|<challenge>|<timeout>`
237
- 4. Client signs `DEPIN-SEND|token|address|challenge` with its private key
238
- 5. Client sends the JSON-RPC request with challenge and signature appended
239
- to the params — the gateway validates and trims them (see §3.2)
240
- 6. Gateway validates and distributes the message
241
-
242
- **Example:**
243
- ```javascript
244
- const result = await rpc('depinsendmsg', [
245
- '&FRANCE',
246
- '192.168.1.100:19002',
247
- 'Hello team!',
248
- 'NXsender...'
249
- ]);
250
- // Returns: { result: "success", hash: "abc123...", recipients: 5, timestamp: 1702123456 }
251
- ```
252
-
253
- **Port:** standard RPC (19001/19101); the node connects out to the remote gateway on TCP 19002
254
- **Encryption:** ECIES (ECDH + AES-256-CBC + HMAC-SHA256)
255
-
256
- ---
257
-
258
- #### **depinsubmitmsg**
259
- Submits a pre-encrypted and signed DePIN message to the local pool (secure protocol).
260
-
261
- **Signature:**
262
- ```typescript
263
- depinsubmitmsg(hexmessage: string): Promise<{
264
- result: string;
265
- hash: string;
266
- timestamp: number;
267
- }>
268
- ```
269
-
270
- **Message structure (CDepinMessage):**
271
- ```cpp
272
- class CDepinMessage {
273
- string token; // DePIN token
274
- string senderAddress; // Sender address
275
- int64_t timestamp; // Unix timestamp
276
- vector<unsigned char> encryptedPayload; // ECIES-encrypted message
277
- vector<unsigned char> signature; // secp256k1 signature
278
- }
279
- ```
280
-
281
- **Example:**
282
- ```javascript
283
- // The message must be serialized and encrypted by the client
284
- const hexMsg = "0a3f2e1b4c..."; // Serialized message in hex
285
- const result = await rpc('depinsubmitmsg', [hexMsg]);
286
- ```
287
-
288
- **Port:** 19002
289
- **Note:** This endpoint is typically used by remote nodes after authentication
290
-
291
- ---
292
-
293
- #### **depingetmsg**
294
- Retrieves and decrypts DePIN messages for the wallet's addresses.
295
-
296
- **Signature:**
297
- ```typescript
298
- depingetmsg(
299
- token: string,
300
- ip_or_address?: string, // remote IP or local address
301
- fromaddress?: string // only if arg2 is IP
302
- ): Promise<Array<{
303
- recipient: string;
304
- sender: string;
305
- message: string;
306
- timestamp: number;
307
- date: string;
308
- expires: string;
309
- }>>
310
- ```
311
-
312
- **Operation modes:**
313
-
314
- 1. **Local - all addresses:**
315
- ```javascript
316
- const messages = await rpc('depingetmsg', ['&FRANCE']);
317
- ```
318
-
319
- 2. **Local - specific address:**
320
- ```javascript
321
- const messages = await rpc('depingetmsg', ['&FRANCE', 'NXyouraddr...']);
322
- ```
323
-
324
- 3. **Remote - IP without port:**
325
- ```javascript
326
- const messages = await rpc('depingetmsg', ['&FRANCE', '192.168.1.78']);
327
- ```
328
-
329
- 4. **Remote - IP with port:**
330
- ```javascript
331
- const messages = await rpc('depingetmsg', ['&FRANCE', '192.168.1.78:19002']);
332
- ```
333
-
334
- 5. **Remote - with specific address:**
335
- ```javascript
336
- const messages = await rpc('depingetmsg', [
337
- '&FRANCE',
338
- '192.168.1.78:19002',
339
- 'NXyouraddr...'
340
- ]);
341
- ```
342
-
343
- **Port:** standard RPC (19001/19101) for local queries; remote queries reach the remote gateway on TCP 19002
344
- **Decryption:** Automatic using the wallet's private keys
345
-
346
- > **Gateway note:** calling `depingetmsg` directly against the TCP gateway
347
- > (port 19002) is currently blocked by a node-side parameter bug — see §3.2.
348
- > Through the standard RPC port (shown above) it works normally.
349
-
350
- ---
351
-
352
- #### **depinclearmsg**
353
- Removes messages from the DePIN messaging pool.
354
-
355
- **Signature:**
356
- ```typescript
357
- depinclearmsg(
358
- mode?: 'all' | number,
359
- scope?: string // section token, e.g. "&TOKEN/GENERAL"
360
- ): Promise<{
361
- removed: number;
362
- remaining: number;
363
- }>
364
- ```
365
-
366
- **Modes:**
367
- - No parameters: Remove only expired messages (default)
368
- - `"all"`: Remove ALL messages from the pool
369
- - `<hours>`: Remove messages older than the specified hours
370
- - With `scope`: restrict the purge to one section's subtree (owner of the
371
- section or of an ancestor required over the gateway; purging a subtree
372
- never touches parents or siblings)
373
-
374
- **Examples:**
375
- ```javascript
376
- // Remove only expired
377
- const result = await rpc('depinclearmsg', []);
378
-
379
- // Remove all
380
- const result = await rpc('depinclearmsg', ['all']);
381
-
382
- // Remove older than 7 days
383
- const result = await rpc('depinclearmsg', [168]);
384
-
385
- // Remove everything in one section only
386
- const result = await rpc('depinclearmsg', ['all', '&FRANCE/GENERAL']);
387
- ```
388
-
389
- **Port:** standard RPC (19001/19101); over the gateway (19002) it requires an ADMIN challenge — see §3.2
390
-
391
- ---
392
-
393
- #### **depingetpoolcontent**
394
- Inspects the contents of the DePIN message pool.
395
-
396
- **Signature:**
397
- ```typescript
398
- depingetpoolcontent(
399
- verbose?: boolean | 'all' | 'raw',
400
- sender_address?: string,
401
- recipient_address?: string,
402
- start_time?: number,
403
- end_time?: number,
404
- limit?: number, // Default: 100, Max: 1000
405
- offset?: number
406
- ): Promise<Array<{
407
- hash: string;
408
- sender: string;
409
- timestamp: number;
410
- date: string;
411
- expires: string;
412
- encryption_type: string;
413
- size: number;
414
- encrypted_payload_hex?: string; // Only if verbose='raw'
415
- signature_hex?: string; // Only if verbose='raw'
416
- }>>
417
- ```
418
-
419
- **Examples:**
420
- ```javascript
421
- // Simple view
422
- const pool = await rpc('depingetpoolcontent', []);
423
-
424
- // Detailed view
425
- const pool = await rpc('depingetpoolcontent', [true]);
426
-
427
- // All messages
428
- const pool = await rpc('depingetpoolcontent', ['all']);
429
-
430
- // With payload hex
431
- const pool = await rpc('depingetpoolcontent', ['raw']);
432
-
433
- // Filter by sender
434
- const pool = await rpc('depingetpoolcontent', [false, 'NXsender...']);
435
- ```
436
-
437
- **Port:** standard RPC (19001 mainnet / 19101 testnet)
438
- **Note:** Recipient filtering does not work with ECIES shared encryption
439
-
440
- ---
441
-
442
- #### **depinpoolstats**
443
- Returns statistical information about the DePIN message pool.
444
-
445
- **Signature:**
446
- ```typescript
447
- depinpoolstats(): Promise<{
448
- enabled: boolean;
449
- token: string;
450
- total_messages: number;
451
- total_size_bytes: number;
452
- memory_usage_bytes: number;
453
- oldest_message: string;
454
- newest_message: string;
455
- messages_by_age: {
456
- last_hour: number;
457
- last_day: number;
458
- last_week: number;
459
- };
460
- unique_senders: number;
461
- unique_recipients: string; // "N/A (ECIES shared encryption)"
462
- avg_message_size: number;
463
- expiring_in_24h: number;
464
- }>
465
- ```
466
-
467
- **Example:**
468
- ```javascript
469
- const stats = await rpc('depinpoolstats', []);
470
- ```
471
-
472
- **Port:** standard RPC (19001 mainnet / 19101 testnet)
473
-
474
- ---
475
-
476
- #### **depinreceivemsg**
477
- Retrieves DePIN messages from the pool with optional pagination. If the
478
- server has a DePIN pool key and the requester's address has a revealed
479
- public key, the response is fully encrypted using the privacy layer.
480
-
481
- **Signature:**
482
- ```typescript
483
- depinreceivemsg(
484
- token: string,
485
- address: string,
486
- timestamp?: number, // only messages with timestamp >= (timestamp-1)
487
- after_hash?: string, // hash of last received message, "" = from beginning
488
- limit?: number // max messages, 0/omitted = all
489
- ): Promise<Array<object> | object>
490
- ```
491
-
492
- **Examples:**
493
- ```javascript
494
- // Everything for one address
495
- const msgs = await rpc('depinreceivemsg', ['&FRANCE', 'NXyouraddr...']);
496
-
497
- // Paginated: 50 messages after a known hash
498
- const page = await rpc('depinreceivemsg', [
499
- '&FRANCE', 'NXyouraddr...', 0, 'abcdef123...', 50,
500
- ]);
501
- ```
502
-
503
- **Port:** standard RPC (19001/19101) and 19002 (served without auth by the gateway)
504
- **Node:** requires July 2026+ for `after_hash`/`limit` pagination
505
-
506
- ---
507
-
508
- #### **depingetancestorrecipients**
509
- Lists the active holders of a DEPIN branch: the deduplicated union of the
510
- holders of the given token and of every one of its `/`-separated ancestors,
511
- each with the public key revealed on chain. Active means: positive balance,
512
- public key revealed, and not blocked by an owner freeze or self-revocation.
513
-
514
- **Signature:**
515
- ```typescript
516
- depingetancestorrecipients(
517
- token: string,
518
- max_results?: number,
519
- stop_at?: string // ancestor at which to stop climbing
520
- ): Promise<object>
521
- ```
522
-
523
- **Example:**
524
- ```javascript
525
- const holders = await rpc('depingetancestorrecipients', ['&FRANCE/PARIS']);
526
- ```
527
-
528
- **Port:** standard RPC (19001 mainnet / 19101 testnet)
529
- **Node:** requires July 2026+
530
-
531
- ---
532
-
533
- #### **depinlistsections**
534
- Lists the hierarchical DePIN sections known to the wallet. With an address it
535
- also reports access and per-section message counters — that mode requires the
536
- standard RPC port (over the gateway only section names are served).
537
-
538
- **Signature:**
539
- ```typescript
540
- depinlistsections(address?: string): Promise<object>
541
- ```
542
-
543
- **Example:**
544
- ```javascript
545
- const sections = await rpc('depinlistsections', []);
546
- const mine = await rpc('depinlistsections', ['NXyouraddr...']);
547
- ```
548
-
549
- **Port:** standard RPC (19001/19101) (names also on 19002)
550
- **Node:** requires July 2026+
551
-
552
- ---
553
-
554
- #### **depinpoolpkey**
555
- Returns the public key of the DePIN pool address from the internal wallet
556
- (wallet must be loaded and unlocked at node startup). Derivation paths:
557
- mainnet `m/44'/0'/200'/0/0`, testnet `m/44'/0'/200'/1/0`.
558
-
559
- **Signature:**
560
- ```typescript
561
- depinpoolpkey(): Promise<{
562
- pubkey: string;
563
- address: string;
564
- path: string;
565
- }>
566
- ```
567
-
568
- **Example:**
569
- ```javascript
570
- const poolKey = await rpc('depinpoolpkey', []);
571
- ```
572
-
573
- **Port:** standard RPC (19001/19101) and 19002 (served without auth by the gateway)
574
-
575
- ---
576
-
577
- ### 2.3 AI/MCP Command
578
-
579
- #### **depinmcpstatus**
580
- Gets the status of the MCP (Model Context Protocol) worker for AI.
581
-
582
- **Signature:**
583
- ```typescript
584
- depinmcpstatus(): Promise<{
585
- enabled: boolean;
586
- running: boolean;
587
- mcp_url: string;
588
- model_name: string;
589
- command_key: string; // e.g., "/ai"
590
- depin_token: string;
591
- node_address: string;
592
- poll_interval: number;
593
- pool_host: string;
594
- pool_port: number;
595
- using_remote_pool: boolean;
596
- commands_processed: number;
597
- total_errors: number;
598
- last_poll_time: number;
599
- last_poll_time_str?: string;
600
- }>
601
- ```
602
-
603
- **Example:**
604
- ```javascript
605
- const status = await rpc('depinmcpstatus', []);
606
- // Returns: {
607
- // enabled: true,
608
- // running: true,
609
- // model_name: "claude-3-sonnet",
610
- // command_key: "/ai",
611
- // commands_processed: 127,
612
- // ...
613
- // }
614
- ```
615
-
616
- **Port:** standard RPC (19001 mainnet / 19101 testnet)
617
- **Note:** The MCP worker processes AI commands sent through the DePIN messaging system
618
-
619
- ---
620
-
621
- ## 3. DePIN Messaging Protocol
622
-
623
- ### 3.1 Shared ECIES Encryption
624
-
625
- The system uses ECIES (Elliptic Curve Integrated Encryption Scheme) with the following components:
626
-
627
- **Components:**
628
- - **ECDH** (secp256k1): To generate shared secret
629
- - **KDF-SHA256**: Derives encryption and HMAC keys
630
- - **AES-256-CBC**: Encrypts the message payload
631
- - **HMAC-SHA256**: Message authentication
632
-
633
- **Encryption flow:**
634
- ```
635
- 1. Sender generates ephemeral key pair (ephemeral_privkey, ephemeral_pubkey)
636
- 2. For each recipient holding the DePIN token:
637
- - Obtain recipient public key via getpubkey RPC
638
- - Compute shared_secret = ECDH(ephemeral_privkey, recipient_pubkey)
639
- - Derive keys: encryption_key || hmac_key = KDF-SHA256(shared_secret, 64)
640
- 3. Encrypt message: ciphertext = AES-256-CBC(plaintext, encryption_key, iv)
641
- 4. Compute MAC: mac = HMAC-SHA256(hmac_key, ciphertext)
642
- 5. Build payload: ephemeral_pubkey || iv || ciphertext || mac
643
- ```
644
-
645
- **Decryption flow:**
646
- ```
647
- 1. Recipient extracts ephemeral_pubkey from the message
648
- 2. Compute shared_secret = ECDH(recipient_privkey, ephemeral_pubkey)
649
- 3. Derive keys: encryption_key || hmac_key = KDF-SHA256(shared_secret, 64)
650
- 4. Verify MAC
651
- 5. Decrypt: plaintext = AES-256-CBC-decrypt(ciphertext, encryption_key, iv)
652
- ```
653
-
654
- ### 3.2 Gateway Transport and Challenge/Response Authentication
655
-
656
- The gateway (default port 19002) speaks a **raw TCP line protocol, not HTTP**:
657
- each connection carries exactly one request line terminated by `\n` and
658
- receives one response line back. A request line is either a protocol command
659
- (`PING`, `INFO`, `AUTH|...`) or a serialized JSON-RPC object.
660
-
661
- **Protocol:**
662
- ```
663
- Client → Server: AUTH|<token>|<address>|<mode>\n
664
- mode = SEND | RECEIVE | ADMIN
665
-
666
- Server → Client: CHALLENGE|<random_challenge>|<timeout_seconds>\n
667
-
668
- Client signs the mode-specific message with the address key:
669
- SEND → "DEPIN-SEND|<token>|<address>|<challenge>" (depinsendmsg)
670
- RECEIVE → "DEPIN-GET|<token>|<address>|<challenge>"
671
- ADMIN → "DEPIN-CLEAR|<token>|<address>|<challenge>" (depinclearmsg, owner only)
672
-
673
- Client → Server (new connection): {"jsonrpc":"2.0","id":...,"method":...,"params":[...]}\n
674
- Challenge and signature placement depends on the method:
675
- - depinsendmsg: [token, ip, message, fromaddress, (port), challenge, signature]
676
- (the gateway validates and trims the last two)
677
- - depinclearmsg: [mode, address, challenge, signature] or
678
- [mode, scope, address, challenge, signature]
679
- - depinreceivemsg, depinsubmitmsg, depingetmsginfo, depingetpoolcontent,
680
- depinpoolstats, depinmcpstatus, depinlistsections, depinpoolpkey:
681
- params untouched — the gateway serves them without auth
682
-
683
- Server → Client: JSON-RPC response line
684
- ```
685
-
686
- Note: `depingetmsg` over the gateway is currently blocked by a node-side bug
687
- (the gateway reads `fromaddress` from `params[3]`, where this method carries
688
- it at index 1 or 2 and accepts at most 3 arguments). Use `depinreceivemsg`
689
- over the gateway, or `depingetmsg` through the standard RPC port.
690
-
691
- ---
692
-
693
- ## 4. Wallet Web Implementation
694
-
695
- > **Transport note:** the class below talks to the node's **standard HTTP RPC
696
- > port** with Basic auth, which works from a browser and is the right choice
697
- > for wallet web apps (for `depinsendmsg` the local node opens the TCP
698
- > connection to the remote gateway itself). Direct access to the DePIN
699
- > gateway (TCP 19002) is only possible from Node.js — use
700
- > `import { getDePinRPC } from "@neuraiproject/neurai-rpc/depin"` for that.
701
-
702
- ### 4.1 Recommended DePINClient Class
703
-
704
- ```typescript
705
- class DePINClient {
706
- private rpcUrl: string;
707
- private rpcPort: number = 19001;
708
- private depinPort: number = 19002;
709
- private username: string;
710
- private password: string;
711
-
712
- constructor(config: {
713
- host: string;
714
- rpcPort?: number;
715
- depinPort?: number;
716
- username: string;
717
- password: string;
718
- }) {
719
- this.rpcUrl = `http://${config.host}`;
720
- this.rpcPort = config.rpcPort || 19001;
721
- this.depinPort = config.depinPort || 19002;
722
- this.username = config.username;
723
- this.password = config.password;
724
- }
725
-
726
- // Standard RPC operations (standard RPC port)
727
- async checkValidity(asset: string, address: string) {
728
- return this.callRPC('checkdepinvalidity', [asset, address]);
729
- }
730
-
731
- async listHolders(asset: string) {
732
- return this.callRPC('listdepinholders', [asset]);
733
- }
734
-
735
- async getMessages(token: string, address?: string) {
736
- const params = address ? [token, address] : [token];
737
- return this.callRPC('depingetmsg', params);
738
- }
739
-
740
- async getPoolStats() {
741
- return this.callRPC('depinpoolstats', []);
742
- }
743
-
744
- // Messaging operations (the local node opens the TCP gateway connection)
745
- async sendMessage(
746
- token: string,
747
- remoteHost: string,
748
- message: string,
749
- fromAddress: string
750
- ) {
751
- return this.callRPC('depinsendmsg', [
752
- token,
753
- remoteHost,
754
- message,
755
- fromAddress
756
- ]);
757
- }
758
-
759
- private async callRPC(method: string, params: any[]) {
760
- const url = `${this.rpcUrl}:${this.rpcPort}`;
761
- const auth = btoa(`${this.username}:${this.password}`);
762
-
763
- const response = await fetch(url, {
764
- method: 'POST',
765
- headers: {
766
- 'Content-Type': 'application/json',
767
- 'Authorization': `Basic ${auth}`
768
- },
769
- body: JSON.stringify({
770
- jsonrpc: '2.0',
771
- id: Date.now(),
772
- method,
773
- params
774
- })
775
- });
776
-
777
- const data = await response.json();
778
- if (data.error) throw new Error(data.error.message);
779
- return data.result;
780
- }
781
- }
782
- ```
783
-
784
- ### 4.2 Example Chat Component
785
-
786
- ```typescript
787
- interface ChatMessage {
788
- sender: string;
789
- recipient: string;
790
- message: string;
791
- timestamp: number;
792
- date: string;
793
- }
794
-
795
- class DePINChat {
796
- private client: DePINClient;
797
- private token: string;
798
- private myAddress: string;
799
- private pollInterval: number = 5000; // 5 seconds
800
-
801
- constructor(client: DePINClient, token: string, myAddress: string) {
802
- this.client = client;
803
- this.token = token;
804
- this.myAddress = myAddress;
805
- }
806
-
807
- // Polling for new messages
808
- async startPolling(callback: (messages: ChatMessage[]) => void) {
809
- setInterval(async () => {
810
- try {
811
- const messages = await this.client.getMessages(
812
- this.token,
813
- this.myAddress
814
- );
815
- callback(messages);
816
- } catch (error) {
817
- console.error('Error polling messages:', error);
818
- }
819
- }, this.pollInterval);
820
- }
821
-
822
- // Send message to a remote node
823
- async sendMessage(remoteHost: string, message: string) {
824
- return await this.client.sendMessage(
825
- this.token,
826
- remoteHost,
827
- message,
828
- this.myAddress
829
- );
830
- }
831
-
832
- // Get pool statistics
833
- async getStats() {
834
- return await this.client.getPoolStats();
835
- }
836
-
837
- // Clear old messages
838
- async clearOldMessages(hoursOld: number) {
839
- return await this.client.callRPC('depinclearmsg', [hoursOld]);
840
- }
841
- }
842
- ```
843
-
844
- ### 4.3 Usage in React/Vue
845
-
846
- ```typescript
847
- // Example React hook
848
- function useDePINChat(token: string, myAddress: string) {
849
- const [messages, setMessages] = useState<ChatMessage[]>([]);
850
- const [stats, setStats] = useState<any>(null);
851
- const client = useMemo(() => new DePINClient({
852
- host: '127.0.0.1',
853
- username: 'rpcuser',
854
- password: 'rpcpass'
855
- }), []);
856
-
857
- useEffect(() => {
858
- const chat = new DePINChat(client, token, myAddress);
859
-
860
- // Polling messages
861
- chat.startPolling((newMessages) => {
862
- setMessages(newMessages);
863
- });
864
-
865
- // Get initial stats
866
- chat.getStats().then(setStats);
867
- }, [token, myAddress]);
868
-
869
- const sendMessage = async (host: string, message: string) => {
870
- const chat = new DePINChat(client, token, myAddress);
871
- return await chat.sendMessage(host, message);
872
- };
873
-
874
- return { messages, stats, sendMessage };
875
- }
876
- ```
877
-
878
- ---
879
-
880
- ## 5. Security Considerations
881
-
882
- ### 5.1 Token Validation
883
-
884
- Always verify token ownership before sending/receiving messages:
885
-
886
- ```typescript
887
- async function verifyTokenOwnership(address: string, token: string) {
888
- const validity = await client.checkValidity(token, address);
889
- if (!validity.has_asset || validity.valid === 0) {
890
- throw new Error('Address does not own valid DePIN token');
891
- }
892
- return true;
893
- }
894
- ```
895
-
896
- **Note:** Both DePIN messaging and the asset-management RPCs use the dedicated `&ASSET` DEPIN asset type — `-depinmsgtoken` must start with `&`, and DEPIN assets are currently testnet/regtest only.
897
-
898
- ### 5.2 Key Management
899
-
900
- - **NEVER** send private keys to the backend
901
- - Encryption should be performed in the client (browser)
902
- - Use the Web Crypto API for cryptographic operations
903
- - Signatures must be generated locally
904
-
905
- ### 5.3 Rate Limiting
906
-
907
- Implement rate limiting on the frontend:
908
-
909
- ```typescript
910
- class RateLimiter {
911
- private requests: number[] = [];
912
- private maxRequests: number = 10;
913
- private windowMs: number = 60000; // 1 minute
914
-
915
- canMakeRequest(): boolean {
916
- const now = Date.now();
917
- this.requests = this.requests.filter(time => now - time < this.windowMs);
918
-
919
- if (this.requests.length >= this.maxRequests) {
920
- return false;
921
- }
922
-
923
- this.requests.push(now);
924
- return true;
925
- }
926
- }
927
- ```
928
-
929
- ---
930
-
931
- ## 6. Node Configuration
932
-
933
- ### 6.1 neurai.conf
934
-
935
- To enable DePIN on the node:
936
-
937
- ```ini
938
- # RPC Configuration
939
- rpcuser=yourusername
940
- rpcpassword=yourpassword
941
- rpcport=19001 # 19101 on testnet
942
- rpcallowip=127.0.0.1
943
- rpcallowip=192.168.1.0/24
944
-
945
- # DePIN Messaging
946
- depinmsg=1
947
- depinmsgtoken=&FRANCE # must start with '&' (DEPIN assets: testnet/regtest only)
948
- depinmsgport=19002
949
- depinmsgbind=0.0.0.0 # use 127.0.0.1 for local-only
950
- depinmsgsize=1024 # max message size in bytes (default 1024)
951
- depinmsgexpire=168 # message expiry in hours (default 168 = 7 days)
952
- depinpoolsize=100 # max pool size in MB (default 100)
953
- depinpoolpersist=0 # save/load the pool across restarts
954
-
955
- # Asset indexes (required for DePIN holder and pubkey discovery)
956
- assetindex=1
957
- pubkeyindex=1
958
-
959
- # Dedicated DePIN assets are issued separately via the standard asset RPCs
960
- # Example on testnet: issue "&FRANCE" 1 "to_address" "change_address" 0 true
961
-
962
- # MCP/AI Worker (optional)
963
- depinmcp=1
964
- depinmcpurl=http://localhost:1234 # MCP server (default http://localhost:1234)
965
- depinmcpendpoint=/v1/chat/completions
966
- depinmcpaddress=NXbotaddress # required: address that signs bot responses
967
- depinmcpkey=/ai # command prefix that triggers the AI
968
- ```
969
-
970
- ### 6.2 Ports to Open
971
-
972
- In your firewall/router:
973
- - **19001** (mainnet) / **19101** (testnet): standard RPC (only localhost or trusted IPs)
974
- - **19002**: DePIN Messaging gateway, raw TCP (public if you want to receive messages; configurable with `-depinmsgport`)
975
-
976
- ---
977
-
978
- ## 7. Testing
979
-
980
- ### 7.1 Basic Connectivity Test
981
-
982
- ```typescript
983
- async function testConnection() {
984
- const client = new DePINClient({
985
- host: '127.0.0.1',
986
- username: 'test',
987
- password: 'test'
988
- });
989
-
990
- try {
991
- const info = await client.callRPC('depingetmsginfo', []);
992
- console.log('✓ Connected:', info);
993
- return true;
994
- } catch (error) {
995
- console.error('✗ Connection failed:', error);
996
- return false;
997
- }
998
- }
999
- ```
1000
-
1001
- ### 7.2 Messaging Test
1002
-
1003
- ```typescript
1004
- async function testMessaging() {
1005
- const client = new DePINClient({
1006
- host: '127.0.0.1',
1007
- username: 'test',
1008
- password: 'test'
1009
- });
1010
-
1011
- // Verify token
1012
- const validity = await client.checkValidity('&FRANCE', 'NXyouraddr...');
1013
- console.log('Token validity:', validity);
1014
-
1015
- // Send message
1016
- const result = await client.sendMessage(
1017
- '&FRANCE',
1018
- '192.168.1.100:19002',
1019
- 'Test message',
1020
- 'NXyouraddr...'
1021
- );
1022
- console.log('Message sent:', result);
1023
-
1024
- // Retrieve messages
1025
- const messages = await client.getMessages('&FRANCE', 'NXyouraddr...');
1026
- console.log('Messages:', messages);
1027
- }
1028
- ```
1029
-
1030
- ---
1031
-
1032
- ## 8. Troubleshooting
1033
-
1034
- ### 8.1 Common Errors
1035
-
1036
- **Error: "DePIN messaging pool is not enabled"**
1037
- - Fix: Add `depinmsg=1` in `neurai.conf` and restart the node
1038
-
1039
- **Error: "Sender verification failed"**
1040
- - Fix: The address does not hold the required DePIN token
1041
-
1042
- **Error: "Invalid message signature"**
1043
- - Fix: The message was not correctly signed with the private key
1044
-
1045
- ### 8.2 Debugging
1046
-
1047
- Enable detailed logs in `neurai.conf`:
1048
-
1049
- ```ini
1050
- debug=net # the DePIN gateway logs under the net category
1051
- debug=mempool # the DePIN message pool logs under mempool
1052
- debug=rpc
1053
- ```
1054
-
1055
- ---
1056
-
1057
- ## 9. References
1058
-
1059
- - **Repository:** https://github.com/NeuraiProject/neurai-rpc
1060
- - **Version:** 0.5.0
1061
- - **RPC Documentation:** See `neurai_methods.md`
1062
- - **DePIN source code:** `Neurai/src/rpc/messages.cpp`, `Neurai/src/rpc/assets.cpp`
1063
- - **ECIES specification:** `Neurai/src/depinecies.cpp`
1064
-
1065
- ---
1066
-
1067
- ## 10. Changelog
1068
-
1069
- ### v0.5.0 (August 2026)
1070
-
1071
- **Library breaking change:**
1072
- - The DePIN client now speaks the gateway's real raw-TCP line protocol
1073
- (it previously used HTTP, which the gateway never supported) and moved to
1074
- the Node.js-only entry `@neuraiproject/neurai-rpc/depin` with a
1075
- `{ host, port }` constructor.
1076
- - Per-method authentication: `DEPIN-SEND|`/`DEPIN-GET|`/`DEPIN-CLEAR|` sign
1077
- formats, ADMIN challenges for `depinclearmsg`, and no auth appended to the
1078
- gateway's unauthenticated methods.
1079
-
1080
- **Documentation corrections:**
1081
- - Real Neurai ports throughout (standard RPC 19001/19101 — 8766 was
1082
- Ravencoin's), real `-depinmsg*`/`-depinmcp*` option names in §6, `debug=net`
1083
- instead of the nonexistent `depin` category, the obsolete `SUBMIT|` step
1084
- replaced by the real JSON-RPC flow, and the `&` messaging-token requirement
1085
- (DEPIN assets are testnet/regtest only in the current node).
1086
-
1087
- **New commands documented:**
1088
- - `depinreceivemsg` - Pool retrieval with pagination
1089
- - `depingetancestorrecipients` - Active holders of a DEPIN branch
1090
- - `depinlistsections` - Hierarchical sections
1091
- - `depinpoolpkey` - Pool public key
1092
- - `depinclearmsg` scope parameter
1093
- - `dumpextkeypq` / `exportxpqpub` - Post-quantum wallet (see neurai_methods.md)
1094
-
1095
- ### v0.4.5 (December 2025)
1096
-
1097
- **New commands added:**
1098
- - `checkdepinvalidity` - DePIN asset validation
1099
- - `listdepinholders` - List holders with validity status
1100
- - `freezedepin` - Freeze assets
1101
- - `unfreezedepin` - Unfreeze assets
1102
- - `selfrevokedepin` - Self-revoke assets
1103
- - `depingetmsginfo` - Messaging system info
1104
- - `depinsendmsg` - Send encrypted messages
1105
- - `depinsubmitmsg` - Submit pre-encrypted messages
1106
- - `depingetmsg` - Retrieve messages
1107
- - `depinclearmsg` - Clear the pool
1108
- - `depingetpoolcontent` - Inspect the pool
1109
- - `depinpoolstats` - Pool statistics
1110
- - `depinmcpstatus` - MCP (AI) worker status
1111
-
1112
- **Improvements:**
1113
- - TypeScript configured with ES2015+ support (Promise, startsWith, etc.)
1114
- - Removed TypeScript compilation warnings
1115
- - Complete JSDoc documentation
1116
- - TypeScript types generated automatically
1117
-
1118
- ---
93
+ The library transports JSON-RPC and exposes current method names. It does not
94
+ hold private keys or silently trust pool keys. See
95
+ [DEPIN_EXAMPLES.md](./DEPIN_EXAMPLES.md) for the wallet-assisted sequence.
1119
96
 
1120
- ## Contact and Support
97
+ ## Migration from protocol 1
1121
98
 
1122
- For production implementations or specific questions, consult:
1123
- - GitHub issues: https://github.com/NeuraiProject/neurai-rpc/issues
1124
- - Neurai Discord: [link]
1125
- - Official documentation: https://neurai.org/docs
99
+ - Replace imports from `@neuraiproject/neurai-rpc/depin` with the package root.
100
+ - Replace `getDePinRPC({host, port}, ...)` with `getRPC(user, password, URL)`.
101
+ - Remove DePIN host/port arguments and configuration fields.
102
+ - Update protected calls to the signed challenge flow.
103
+ - Replace bare `depinsubmitmsg` payloads with encrypted envelope objects.
104
+ - Remove calls to `depingetpoolcontent`.