@neuraiproject/neurai-rpc 0.4.5 → 0.4.7

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.
@@ -0,0 +1,956 @@
1
+ # DePIN Implementation Technical Guide for Neurai RPC
2
+
3
+ ## Change Summary
4
+
5
+ Thirteen new RPC commands have been added for Neurai's DePIN (Decentralized Physical Infrastructure Networks) system, grouped into three categories: DePIN asset management, encrypted messaging, and AI/MCP monitoring.
6
+
7
+ **Version:** 0.4.5
8
+ **Date:** December 2025
9
+ **Branch:** master
10
+
11
+ ---
12
+
13
+ ## 1. DePIN Architecture
14
+
15
+ ### 1.1 Dual-Port Architecture
16
+
17
+ The DePIN system uses two distinct ports for different operations:
18
+
19
+ - **Port 8766** (standard RPC): Asset management commands and queries
20
+ - **Port 19002** (DePIN Server): Encrypted messaging and P2P operations
21
+
22
+ ### 1.2 DePIN Asset Types
23
+
24
+ There are two related but different concepts in the current DePIN stack:
25
+
26
+ - **DePIN messaging token:** the asset configured in `depintoken` for gateway messaging. This can be any asset.
27
+ - **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 documented here as enabled for mainnet and testnet, require the owner token `&ASSET!`, and must be issued and reissued with `units=0`.
28
+
29
+ ---
30
+
31
+ ## 2. Newly Added RPC Commands
32
+
33
+ ### 2.1 DePIN Asset Management Commands
34
+
35
+ #### **checkdepinvalidity**
36
+ Checks whether a DePIN asset is valid for a specific address.
37
+
38
+ **Signature:**
39
+ ```typescript
40
+ checkdepinvalidity(asset_name: string, address: string): Promise<{
41
+ has_asset: boolean;
42
+ amount?: number;
43
+ valid?: 0 | 1;
44
+ blocked?: boolean;
45
+ }>
46
+ ```
47
+
48
+ **Example:**
49
+ ```javascript
50
+ const rpc = getRPC('http://127.0.0.1:8766', 'username', 'password');
51
+ const result = await rpc('checkdepinvalidity', ['&FRANCE', 'NXabcd...']);
52
+ // Returns: { has_asset: true, amount: 1, valid: 1, blocked: false }
53
+ ```
54
+
55
+ **Port:** 8766
56
+ **Requires Wallet:** No
57
+
58
+ ---
59
+
60
+ #### **listdepinholders**
61
+ Lists all holders of a DePIN asset along with their validity status.
62
+
63
+ **Signature:**
64
+ ```typescript
65
+ listdepinholders(asset_name: string): Promise<Array<{
66
+ address: string;
67
+ amount: number;
68
+ valid: 0 | 1;
69
+ }>>
70
+ ```
71
+
72
+ **Example:**
73
+ ```javascript
74
+ const holders = await rpc('listdepinholders', ['&FRANCE']);
75
+ // Returns: [
76
+ // { address: 'NXabc...', amount: 1, valid: 1 },
77
+ // { address: 'NXdef...', amount: 1, valid: 0 }
78
+ // ]
79
+ ```
80
+
81
+ **Port:** 8766
82
+ **Requires:** `-assetindex` enabled on the node
83
+
84
+ ---
85
+
86
+ #### **listdepinaddresses**
87
+ Lists addresses that own an asset and have already revealed a public key on-chain.
88
+ This is useful when discovering recipients for DePIN messaging.
89
+
90
+ **Signature:**
91
+ ```typescript
92
+ listdepinaddresses(asset_name: string, count?: number, start?: number): Promise<Array<{
93
+ address: string;
94
+ pubkey: string;
95
+ }>>
96
+ ```
97
+
98
+ **Example:**
99
+ ```javascript
100
+ const recipients = await rpc('listdepinaddresses', ['&FRANCE']);
101
+ // Returns: [
102
+ // { address: 'NXabc...', pubkey: '02ab...' },
103
+ // { address: 'NXdef...', pubkey: '03cd...' }
104
+ // ]
105
+ ```
106
+
107
+ **Port:** 8766
108
+ **Requires:** `-assetindex` and `-pubkeyindex` enabled on the node
109
+
110
+ ---
111
+
112
+ #### **freezedepin**
113
+ Freezes a DePIN asset for a specific address (owner only).
114
+
115
+ **Signature:**
116
+ ```typescript
117
+ freezedepin(
118
+ asset_name: string,
119
+ address: string,
120
+ change_address?: string
121
+ ): Promise<string> // txid
122
+ ```
123
+
124
+ **Example:**
125
+ ```javascript
126
+ const txid = await rpc('freezedepin', ['&FRANCE', 'NXmalicious...']);
127
+ // Returns: "a1b2c3d4e5f6..." (transaction ID)
128
+ ```
129
+
130
+ **Port:** 8766
131
+ **Requires:** Owner token `&FRANCE!` in the wallet
132
+
133
+ ---
134
+
135
+ #### **unfreezedepin**
136
+ Unfreezes a previously frozen DePIN asset (owner only).
137
+
138
+ **Signature:**
139
+ ```typescript
140
+ unfreezedepin(
141
+ asset_name: string,
142
+ address: string,
143
+ change_address?: string
144
+ ): Promise<string> // txid
145
+ ```
146
+
147
+ **Port:** 8766
148
+ **Requires:** Owner token `ASSET!` in the wallet
149
+
150
+ ---
151
+
152
+ #### **selfrevokedepin**
153
+ Allows a holder to self-revoke their DePIN asset (this action can only be undone by the asset owner).
154
+
155
+ **Signature:**
156
+ ```typescript
157
+ selfrevokedepin(asset_name: string): Promise<string> // txid
158
+ ```
159
+
160
+ **Example:**
161
+ ```javascript
162
+ const txid = await rpc('selfrevokedepin', ['&FRANCE']);
163
+ ```
164
+
165
+ **Port:** 8766
166
+ **Requires Wallet:** Yes (the wallet must hold the asset)
167
+
168
+ ---
169
+
170
+ ### 2.2 DePIN Messaging Commands
171
+
172
+ #### **depingetmsginfo**
173
+ Returns information about the DePIN messaging system.
174
+
175
+ **Signature:**
176
+ ```typescript
177
+ depingetmsginfo(): Promise<{
178
+ enabled: boolean;
179
+ token: string;
180
+ port: number;
181
+ maxrecipients: number;
182
+ maxmessagesize: number;
183
+ messageexpiryhours: number;
184
+ maxpoolsizemb: number;
185
+ messages: number;
186
+ memoryusage: number;
187
+ memoryusagemb: number;
188
+ oldestmessage?: string;
189
+ newestmessage?: string;
190
+ }>
191
+ ```
192
+
193
+ **Example:**
194
+ ```javascript
195
+ const info = await rpc('depingetmsginfo', []);
196
+ // Returns: {
197
+ // enabled: true,
198
+ // token: "FRANCE",
199
+ // port: 19002,
200
+ // maxmessagesize: 1024,
201
+ // messages: 42,
202
+ // ...
203
+ // }
204
+ ```
205
+
206
+ **Port:** 8766
207
+
208
+ ---
209
+
210
+ #### **depinsendmsg**
211
+ Sends an encrypted message through a remote DePIN gateway using challenge/response.
212
+
213
+ **Signature:**
214
+ ```typescript
215
+ depinsendmsg(
216
+ token: string,
217
+ ip_port: string, // "192.168.1.100" or "192.168.1.100:19002"
218
+ message: string, // Max 1KB
219
+ fromaddress: string,
220
+ port?: number // Override port (default: 19002)
221
+ ): Promise<{
222
+ result: string;
223
+ hash: string;
224
+ recipients: number;
225
+ timestamp: number;
226
+ }>
227
+ ```
228
+
229
+ **Operation flow:**
230
+ 1. Client connects to remote gateway on port 19002
231
+ 2. Requests challenge: `AUTH|TOKEN|ADDRESS|SEND`
232
+ 3. Gateway responds: `CHALLENGE|<challenge>|<timeout>`
233
+ 4. Client signs the challenge with its private key
234
+ 5. Client sends: `SUBMIT|<signature>|<encrypted_message>`
235
+ 6. Gateway validates and distributes the message
236
+
237
+ **Example:**
238
+ ```javascript
239
+ const result = await rpc('depinsendmsg', [
240
+ 'FRANCE',
241
+ '192.168.1.100:19002',
242
+ 'Hello team!',
243
+ 'NXsender...'
244
+ ]);
245
+ // Returns: { result: "success", hash: "abc123...", recipients: 5, timestamp: 1702123456 }
246
+ ```
247
+
248
+ **Port:** 8766 (RPC), connects to remote node port 19002
249
+ **Encryption:** ECIES (ECDH + AES-256-CBC + HMAC-SHA256)
250
+
251
+ ---
252
+
253
+ #### **depinsubmitmsg**
254
+ Submits a pre-encrypted and signed DePIN message to the local pool (secure protocol).
255
+
256
+ **Signature:**
257
+ ```typescript
258
+ depinsubmitmsg(hexmessage: string): Promise<{
259
+ result: string;
260
+ hash: string;
261
+ timestamp: number;
262
+ }>
263
+ ```
264
+
265
+ **Message structure (CDepinMessage):**
266
+ ```cpp
267
+ class CDepinMessage {
268
+ string token; // DePIN token
269
+ string senderAddress; // Sender address
270
+ int64_t timestamp; // Unix timestamp
271
+ vector<unsigned char> encryptedPayload; // ECIES-encrypted message
272
+ vector<unsigned char> signature; // secp256k1 signature
273
+ }
274
+ ```
275
+
276
+ **Example:**
277
+ ```javascript
278
+ // The message must be serialized and encrypted by the client
279
+ const hexMsg = "0a3f2e1b4c..."; // Serialized message in hex
280
+ const result = await rpc('depinsubmitmsg', [hexMsg]);
281
+ ```
282
+
283
+ **Port:** 19002
284
+ **Note:** This endpoint is typically used by remote nodes after authentication
285
+
286
+ ---
287
+
288
+ #### **depingetmsg**
289
+ Retrieves and decrypts DePIN messages for the wallet's addresses.
290
+
291
+ **Signature:**
292
+ ```typescript
293
+ depingetmsg(
294
+ token: string,
295
+ ip_or_address?: string, // remote IP or local address
296
+ fromaddress?: string // only if arg2 is IP
297
+ ): Promise<Array<{
298
+ recipient: string;
299
+ sender: string;
300
+ message: string;
301
+ timestamp: number;
302
+ date: string;
303
+ expires: string;
304
+ }>>
305
+ ```
306
+
307
+ **Operation modes:**
308
+
309
+ 1. **Local - all addresses:**
310
+ ```javascript
311
+ const messages = await rpc('depingetmsg', ['FRANCE']);
312
+ ```
313
+
314
+ 2. **Local - specific address:**
315
+ ```javascript
316
+ const messages = await rpc('depingetmsg', ['FRANCE', 'NXyouraddr...']);
317
+ ```
318
+
319
+ 3. **Remote - IP without port:**
320
+ ```javascript
321
+ const messages = await rpc('depingetmsg', ['FRANCE', '192.168.1.78']);
322
+ ```
323
+
324
+ 4. **Remote - IP with port:**
325
+ ```javascript
326
+ const messages = await rpc('depingetmsg', ['FRANCE', '192.168.1.78:19002']);
327
+ ```
328
+
329
+ 5. **Remote - with specific address:**
330
+ ```javascript
331
+ const messages = await rpc('depingetmsg', [
332
+ 'FRANCE',
333
+ '192.168.1.78:19002',
334
+ 'NXyouraddr...'
335
+ ]);
336
+ ```
337
+
338
+ **Port:** 8766 (for local queries), 19002 (for remote queries)
339
+ **Decryption:** Automatic using the wallet's private keys
340
+
341
+ ---
342
+
343
+ #### **depinclearmsg**
344
+ Removes messages from the DePIN messaging pool.
345
+
346
+ **Signature:**
347
+ ```typescript
348
+ depinclearmsg(mode?: 'all' | number): Promise<{
349
+ removed: number;
350
+ remaining: number;
351
+ }>
352
+ ```
353
+
354
+ **Modes:**
355
+ - No parameters: Remove only expired messages (default)
356
+ - `"all"`: Remove ALL messages from the pool
357
+ - `<hours>`: Remove messages older than the specified hours
358
+
359
+ **Examples:**
360
+ ```javascript
361
+ // Remove only expired
362
+ const result = await rpc('depinclearmsg', []);
363
+
364
+ // Remove all
365
+ const result = await rpc('depinclearmsg', ['all']);
366
+
367
+ // Remove older than 7 days
368
+ const result = await rpc('depinclearmsg', [168]);
369
+ ```
370
+
371
+ **Port:** 8766
372
+
373
+ ---
374
+
375
+ #### **depingetpoolcontent**
376
+ Inspects the contents of the DePIN message pool.
377
+
378
+ **Signature:**
379
+ ```typescript
380
+ depingetpoolcontent(
381
+ verbose?: boolean | 'all' | 'raw',
382
+ sender_address?: string,
383
+ recipient_address?: string,
384
+ start_time?: number,
385
+ end_time?: number,
386
+ limit?: number, // Default: 100, Max: 1000
387
+ offset?: number
388
+ ): Promise<Array<{
389
+ hash: string;
390
+ sender: string;
391
+ timestamp: number;
392
+ date: string;
393
+ expires: string;
394
+ encryption_type: string;
395
+ size: number;
396
+ encrypted_payload_hex?: string; // Only if verbose='raw'
397
+ signature_hex?: string; // Only if verbose='raw'
398
+ }>>
399
+ ```
400
+
401
+ **Examples:**
402
+ ```javascript
403
+ // Simple view
404
+ const pool = await rpc('depingetpoolcontent', []);
405
+
406
+ // Detailed view
407
+ const pool = await rpc('depingetpoolcontent', [true]);
408
+
409
+ // All messages
410
+ const pool = await rpc('depingetpoolcontent', ['all']);
411
+
412
+ // With payload hex
413
+ const pool = await rpc('depingetpoolcontent', ['raw']);
414
+
415
+ // Filter by sender
416
+ const pool = await rpc('depingetpoolcontent', [false, 'NXsender...']);
417
+ ```
418
+
419
+ **Port:** 8766
420
+ **Note:** Recipient filtering does not work with ECIES shared encryption
421
+
422
+ ---
423
+
424
+ #### **depinpoolstats**
425
+ Returns statistical information about the DePIN message pool.
426
+
427
+ **Signature:**
428
+ ```typescript
429
+ depinpoolstats(): Promise<{
430
+ enabled: boolean;
431
+ token: string;
432
+ total_messages: number;
433
+ total_size_bytes: number;
434
+ memory_usage_bytes: number;
435
+ oldest_message: string;
436
+ newest_message: string;
437
+ messages_by_age: {
438
+ last_hour: number;
439
+ last_day: number;
440
+ last_week: number;
441
+ };
442
+ unique_senders: number;
443
+ unique_recipients: string; // "N/A (ECIES shared encryption)"
444
+ avg_message_size: number;
445
+ expiring_in_24h: number;
446
+ }>
447
+ ```
448
+
449
+ **Example:**
450
+ ```javascript
451
+ const stats = await rpc('depinpoolstats', []);
452
+ ```
453
+
454
+ **Port:** 8766
455
+
456
+ ---
457
+
458
+ ### 2.3 AI/MCP Command
459
+
460
+ #### **depinmcpstatus**
461
+ Gets the status of the MCP (Model Context Protocol) worker for AI.
462
+
463
+ **Signature:**
464
+ ```typescript
465
+ depinmcpstatus(): Promise<{
466
+ enabled: boolean;
467
+ running: boolean;
468
+ mcp_url: string;
469
+ model_name: string;
470
+ command_key: string; // e.g., "/ai"
471
+ depin_token: string;
472
+ node_address: string;
473
+ poll_interval: number;
474
+ pool_host: string;
475
+ pool_port: number;
476
+ using_remote_pool: boolean;
477
+ commands_processed: number;
478
+ total_errors: number;
479
+ last_poll_time: number;
480
+ last_poll_time_str?: string;
481
+ }>
482
+ ```
483
+
484
+ **Example:**
485
+ ```javascript
486
+ const status = await rpc('depinmcpstatus', []);
487
+ // Returns: {
488
+ // enabled: true,
489
+ // running: true,
490
+ // model_name: "claude-3-sonnet",
491
+ // command_key: "/ai",
492
+ // commands_processed: 127,
493
+ // ...
494
+ // }
495
+ ```
496
+
497
+ **Port:** 8766
498
+ **Note:** The MCP worker processes AI commands sent through the DePIN messaging system
499
+
500
+ ---
501
+
502
+ ## 3. DePIN Messaging Protocol
503
+
504
+ ### 3.1 Shared ECIES Encryption
505
+
506
+ The system uses ECIES (Elliptic Curve Integrated Encryption Scheme) with the following components:
507
+
508
+ **Components:**
509
+ - **ECDH** (secp256k1): To generate shared secret
510
+ - **KDF-SHA256**: Derives encryption and HMAC keys
511
+ - **AES-256-CBC**: Encrypts the message payload
512
+ - **HMAC-SHA256**: Message authentication
513
+
514
+ **Encryption flow:**
515
+ ```
516
+ 1. Sender generates ephemeral key pair (ephemeral_privkey, ephemeral_pubkey)
517
+ 2. For each recipient holding the DePIN token:
518
+ - Obtain recipient public key via getpubkey RPC
519
+ - Compute shared_secret = ECDH(ephemeral_privkey, recipient_pubkey)
520
+ - Derive keys: encryption_key || hmac_key = KDF-SHA256(shared_secret, 64)
521
+ 3. Encrypt message: ciphertext = AES-256-CBC(plaintext, encryption_key, iv)
522
+ 4. Compute MAC: mac = HMAC-SHA256(hmac_key, ciphertext)
523
+ 5. Build payload: ephemeral_pubkey || iv || ciphertext || mac
524
+ ```
525
+
526
+ **Decryption flow:**
527
+ ```
528
+ 1. Recipient extracts ephemeral_pubkey from the message
529
+ 2. Compute shared_secret = ECDH(recipient_privkey, ephemeral_pubkey)
530
+ 3. Derive keys: encryption_key || hmac_key = KDF-SHA256(shared_secret, 64)
531
+ 4. Verify MAC
532
+ 5. Decrypt: plaintext = AES-256-CBC-decrypt(ciphertext, encryption_key, iv)
533
+ ```
534
+
535
+ ### 3.2 Challenge/Response Authentication
536
+
537
+ For remote operations (depinsendmsg):
538
+
539
+ **Protocol:**
540
+ ```
541
+ Client → Server: AUTH|<token>|<address>|<mode>
542
+ mode = SEND | RECEIVE
543
+
544
+ Server → Client: CHALLENGE|<random_challenge>|<timeout_seconds>
545
+
546
+ Client:
547
+ 1. Sign challenge: signature = sign(sha256(challenge), privkey)
548
+ 2. Prepare encrypted message
549
+
550
+ Client → Server: SUBMIT|<signature>|<hex_encrypted_message>
551
+
552
+ Server:
553
+ 1. Verify signature with address pubkey
554
+ 2. Verify token ownership
555
+ 3. Validate and store message
556
+ 4. Return confirmation
557
+ ```
558
+
559
+ ---
560
+
561
+ ## 4. Wallet Web Implementation
562
+
563
+ ### 4.1 Recommended DePINClient Class
564
+
565
+ ```typescript
566
+ class DePINClient {
567
+ private rpcUrl: string;
568
+ private rpcPort: number = 8766;
569
+ private depinPort: number = 19002;
570
+ private username: string;
571
+ private password: string;
572
+
573
+ constructor(config: {
574
+ host: string;
575
+ rpcPort?: number;
576
+ depinPort?: number;
577
+ username: string;
578
+ password: string;
579
+ }) {
580
+ this.rpcUrl = `http://${config.host}`;
581
+ this.rpcPort = config.rpcPort || 8766;
582
+ this.depinPort = config.depinPort || 19002;
583
+ this.username = config.username;
584
+ this.password = config.password;
585
+ }
586
+
587
+ // Standard RPC operations (port 8766)
588
+ async checkValidity(asset: string, address: string) {
589
+ return this.callRPC('checkdepinvalidity', [asset, address]);
590
+ }
591
+
592
+ async listHolders(asset: string) {
593
+ return this.callRPC('listdepinholders', [asset]);
594
+ }
595
+
596
+ async getMessages(token: string, address?: string) {
597
+ const params = address ? [token, address] : [token];
598
+ return this.callRPC('depingetmsg', params);
599
+ }
600
+
601
+ async getPoolStats() {
602
+ return this.callRPC('depinpoolstats', []);
603
+ }
604
+
605
+ // Messaging operations (port 19002 for sending)
606
+ async sendMessage(
607
+ token: string,
608
+ remoteHost: string,
609
+ message: string,
610
+ fromAddress: string
611
+ ) {
612
+ return this.callRPC('depinsendmsg', [
613
+ token,
614
+ remoteHost,
615
+ message,
616
+ fromAddress
617
+ ]);
618
+ }
619
+
620
+ private async callRPC(method: string, params: any[]) {
621
+ const url = `${this.rpcUrl}:${this.rpcPort}`;
622
+ const auth = btoa(`${this.username}:${this.password}`);
623
+
624
+ const response = await fetch(url, {
625
+ method: 'POST',
626
+ headers: {
627
+ 'Content-Type': 'application/json',
628
+ 'Authorization': `Basic ${auth}`
629
+ },
630
+ body: JSON.stringify({
631
+ jsonrpc: '2.0',
632
+ id: Date.now(),
633
+ method,
634
+ params
635
+ })
636
+ });
637
+
638
+ const data = await response.json();
639
+ if (data.error) throw new Error(data.error.message);
640
+ return data.result;
641
+ }
642
+ }
643
+ ```
644
+
645
+ ### 4.2 Example Chat Component
646
+
647
+ ```typescript
648
+ interface ChatMessage {
649
+ sender: string;
650
+ recipient: string;
651
+ message: string;
652
+ timestamp: number;
653
+ date: string;
654
+ }
655
+
656
+ class DePINChat {
657
+ private client: DePINClient;
658
+ private token: string;
659
+ private myAddress: string;
660
+ private pollInterval: number = 5000; // 5 seconds
661
+
662
+ constructor(client: DePINClient, token: string, myAddress: string) {
663
+ this.client = client;
664
+ this.token = token;
665
+ this.myAddress = myAddress;
666
+ }
667
+
668
+ // Polling for new messages
669
+ async startPolling(callback: (messages: ChatMessage[]) => void) {
670
+ setInterval(async () => {
671
+ try {
672
+ const messages = await this.client.getMessages(
673
+ this.token,
674
+ this.myAddress
675
+ );
676
+ callback(messages);
677
+ } catch (error) {
678
+ console.error('Error polling messages:', error);
679
+ }
680
+ }, this.pollInterval);
681
+ }
682
+
683
+ // Send message to a remote node
684
+ async sendMessage(remoteHost: string, message: string) {
685
+ return await this.client.sendMessage(
686
+ this.token,
687
+ remoteHost,
688
+ message,
689
+ this.myAddress
690
+ );
691
+ }
692
+
693
+ // Get pool statistics
694
+ async getStats() {
695
+ return await this.client.getPoolStats();
696
+ }
697
+
698
+ // Clear old messages
699
+ async clearOldMessages(hoursOld: number) {
700
+ return await this.client.callRPC('depinclearmsg', [hoursOld]);
701
+ }
702
+ }
703
+ ```
704
+
705
+ ### 4.3 Usage in React/Vue
706
+
707
+ ```typescript
708
+ // Example React hook
709
+ function useDePINChat(token: string, myAddress: string) {
710
+ const [messages, setMessages] = useState<ChatMessage[]>([]);
711
+ const [stats, setStats] = useState<any>(null);
712
+ const client = useMemo(() => new DePINClient({
713
+ host: '127.0.0.1',
714
+ username: 'rpcuser',
715
+ password: 'rpcpass'
716
+ }), []);
717
+
718
+ useEffect(() => {
719
+ const chat = new DePINChat(client, token, myAddress);
720
+
721
+ // Polling messages
722
+ chat.startPolling((newMessages) => {
723
+ setMessages(newMessages);
724
+ });
725
+
726
+ // Get initial stats
727
+ chat.getStats().then(setStats);
728
+ }, [token, myAddress]);
729
+
730
+ const sendMessage = async (host: string, message: string) => {
731
+ const chat = new DePINChat(client, token, myAddress);
732
+ return await chat.sendMessage(host, message);
733
+ };
734
+
735
+ return { messages, stats, sendMessage };
736
+ }
737
+ ```
738
+
739
+ ---
740
+
741
+ ## 5. Security Considerations
742
+
743
+ ### 5.1 Token Validation
744
+
745
+ Always verify token ownership before sending/receiving messages:
746
+
747
+ ```typescript
748
+ async function verifyTokenOwnership(address: string, token: string) {
749
+ const validity = await client.checkValidity(token, address);
750
+ if (!validity.has_asset || validity.valid === 0) {
751
+ throw new Error('Address does not own valid DePIN token');
752
+ }
753
+ return true;
754
+ }
755
+ ```
756
+
757
+ **Note:** For DePIN messaging, the token can be any asset. For the dedicated DePIN asset-management RPCs, use the `&ASSET` asset type.
758
+
759
+ ### 5.2 Key Management
760
+
761
+ - **NEVER** send private keys to the backend
762
+ - Encryption should be performed in the client (browser)
763
+ - Use the Web Crypto API for cryptographic operations
764
+ - Signatures must be generated locally
765
+
766
+ ### 5.3 Rate Limiting
767
+
768
+ Implement rate limiting on the frontend:
769
+
770
+ ```typescript
771
+ class RateLimiter {
772
+ private requests: number[] = [];
773
+ private maxRequests: number = 10;
774
+ private windowMs: number = 60000; // 1 minute
775
+
776
+ canMakeRequest(): boolean {
777
+ const now = Date.now();
778
+ this.requests = this.requests.filter(time => now - time < this.windowMs);
779
+
780
+ if (this.requests.length >= this.maxRequests) {
781
+ return false;
782
+ }
783
+
784
+ this.requests.push(now);
785
+ return true;
786
+ }
787
+ }
788
+ ```
789
+
790
+ ---
791
+
792
+ ## 6. Node Configuration
793
+
794
+ ### 6.1 neurai.conf
795
+
796
+ To enable DePIN on the node:
797
+
798
+ ```ini
799
+ # RPC Configuration
800
+ rpcuser=yourusername
801
+ rpcpassword=yourpassword
802
+ rpcport=8766
803
+ rpcallowip=127.0.0.1
804
+ rpcallowip=192.168.1.0/24
805
+
806
+ # DePIN Messaging
807
+ depinmsg=1
808
+ depintoken=FRANCE
809
+ depinport=19002
810
+ depinmaxmessagesize=1024
811
+ depinmessageexpiry=168 # 7 days in hours
812
+ depinmaxpoolsize=100 # MB
813
+
814
+ # Asset indexes (required for DePIN holder and pubkey discovery)
815
+ assetindex=1
816
+ pubkeyindex=1
817
+
818
+ # Dedicated DePIN assets are issued separately via the standard asset RPCs
819
+ # Example on testnet: issue "&FRANCE" 1 "to_address" "change_address" 0 true
820
+
821
+ # MCP/AI Worker (optional)
822
+ depinmcp=1
823
+ depinmcpurl=http://localhost:8080
824
+ depinmcpmodel=claude-3-sonnet
825
+ depinmcpkey=/ai
826
+ ```
827
+
828
+ ### 6.2 Ports to Open
829
+
830
+ In your firewall/router:
831
+ - **8766**: RPC (only localhost or trusted IPs)
832
+ - **19002**: DePIN Messaging (public if you want to receive messages)
833
+
834
+ ---
835
+
836
+ ## 7. Testing
837
+
838
+ ### 7.1 Basic Connectivity Test
839
+
840
+ ```typescript
841
+ async function testConnection() {
842
+ const client = new DePINClient({
843
+ host: '127.0.0.1',
844
+ username: 'test',
845
+ password: 'test'
846
+ });
847
+
848
+ try {
849
+ const info = await client.callRPC('depingetmsginfo', []);
850
+ console.log('✓ Connected:', info);
851
+ return true;
852
+ } catch (error) {
853
+ console.error('✗ Connection failed:', error);
854
+ return false;
855
+ }
856
+ }
857
+ ```
858
+
859
+ ### 7.2 Messaging Test
860
+
861
+ ```typescript
862
+ async function testMessaging() {
863
+ const client = new DePINClient({
864
+ host: '127.0.0.1',
865
+ username: 'test',
866
+ password: 'test'
867
+ });
868
+
869
+ // Verify token
870
+ const validity = await client.checkValidity('&FRANCE', 'NXyouraddr...');
871
+ console.log('Token validity:', validity);
872
+
873
+ // Send message
874
+ const result = await client.sendMessage(
875
+ 'FRANCE',
876
+ '192.168.1.100:19002',
877
+ 'Test message',
878
+ 'NXyouraddr...'
879
+ );
880
+ console.log('Message sent:', result);
881
+
882
+ // Retrieve messages
883
+ const messages = await client.getMessages('FRANCE', 'NXyouraddr...');
884
+ console.log('Messages:', messages);
885
+ }
886
+ ```
887
+
888
+ ---
889
+
890
+ ## 8. Troubleshooting
891
+
892
+ ### 8.1 Common Errors
893
+
894
+ **Error: "DePIN messaging pool is not enabled"**
895
+ - Fix: Add `depinmsg=1` in `neurai.conf` and restart the node
896
+
897
+ **Error: "Sender verification failed"**
898
+ - Fix: The address does not hold the required DePIN token
899
+
900
+ **Error: "Invalid message signature"**
901
+ - Fix: The message was not correctly signed with the private key
902
+
903
+ ### 8.2 Debugging
904
+
905
+ Enable detailed logs in `neurai.conf`:
906
+
907
+ ```ini
908
+ debug=depin
909
+ debug=rpc
910
+ ```
911
+
912
+ ---
913
+
914
+ ## 9. References
915
+
916
+ - **Repository:** https://github.com/NeuraiProject/neurai-rpc
917
+ - **Version:** 0.4.5
918
+ - **RPC Documentation:** See `neurai_methods.md`
919
+ - **DePIN source code:** `Neurai/src/rpc/messages.cpp`, `Neurai/src/rpc/assets.cpp`
920
+ - **ECIES specification:** `Neurai/src/depinecies.cpp`
921
+
922
+ ---
923
+
924
+ ## 10. Changelog
925
+
926
+ ### v0.4.5 (December 2025)
927
+
928
+ **New commands added:**
929
+ - `checkdepinvalidity` - DePIN asset validation
930
+ - `listdepinholders` - List holders with validity status
931
+ - `freezedepin` - Freeze assets
932
+ - `unfreezedepin` - Unfreeze assets
933
+ - `selfrevokedepin` - Self-revoke assets
934
+ - `depingetmsginfo` - Messaging system info
935
+ - `depinsendmsg` - Send encrypted messages
936
+ - `depinsubmitmsg` - Submit pre-encrypted messages
937
+ - `depingetmsg` - Retrieve messages
938
+ - `depinclearmsg` - Clear the pool
939
+ - `depingetpoolcontent` - Inspect the pool
940
+ - `depinpoolstats` - Pool statistics
941
+ - `depinmcpstatus` - MCP (AI) worker status
942
+
943
+ **Improvements:**
944
+ - TypeScript configured with ES2015+ support (Promise, startsWith, etc.)
945
+ - Removed TypeScript compilation warnings
946
+ - Complete JSDoc documentation
947
+ - TypeScript types generated automatically
948
+
949
+ ---
950
+
951
+ ## Contact and Support
952
+
953
+ For production implementations or specific questions, consult:
954
+ - GitHub issues: https://github.com/NeuraiProject/neurai-rpc/issues
955
+ - Neurai Discord: [link]
956
+ - Official documentation: https://neurai.org/docs