@neuraiproject/neurai-rpc 0.4.5 → 0.4.6

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