pot-o-extensions 0.10.0

DeFi, staking, and external-chain extensions for the PoT-O validator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Gossip client for peer-to-peer challenge distribution using async HTTP.

use crate::peer_auth::NodeIdentity;
use serde_json;
use sha2::{Digest, Sha256};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;

/// Async HTTP-based gossip client for broadcasting challenges to peers.
pub struct GossipClient {
    /// Client for making HTTP requests
    client: reqwest::Client,
    /// Thread-safe list of peer URLs
    peers: Arc<RwLock<Vec<String>>>,
    /// Request timeout duration
    timeout: Duration,
    /// Optional node identity for request signing
    identity: Option<Arc<NodeIdentity>>,
}

impl GossipClient {
    /// Create a new gossip client with the given peer URLs and timeout.
    ///
    /// # Arguments
    /// * `peer_urls` - List of peer URLs for challenge distribution
    /// * `timeout_secs` - Request timeout in seconds
    pub fn new(peer_urls: Vec<String>, timeout_secs: u64) -> Self {
        Self {
            client: reqwest::Client::new(),
            peers: Arc::new(RwLock::new(peer_urls)),
            timeout: Duration::from_secs(timeout_secs),
            identity: None,
        }
    }

    /// Create a new gossip client with authentication enabled.
    ///
    /// # Arguments
    /// * `peer_urls` - List of peer URLs for challenge distribution
    /// * `timeout_secs` - Request timeout in seconds
    /// * `identity` - Node identity for signing requests
    pub fn with_identity(
        peer_urls: Vec<String>,
        timeout_secs: u64,
        identity: Arc<NodeIdentity>,
    ) -> Self {
        Self {
            client: reqwest::Client::new(),
            peers: Arc::new(RwLock::new(peer_urls)),
            timeout: Duration::from_secs(timeout_secs),
            identity: Some(identity),
        }
    }

    /// Sign a request and return authentication headers.
    ///
    /// # Arguments
    /// * `method` - HTTP method (GET, POST, etc.)
    /// * `path` - Request path
    /// * `body` - Request body bytes
    fn sign_request(&self, method: &str, path: &str, body: &[u8]) -> Vec<(String, String)> {
        let Some(identity) = &self.identity else {
            return vec![];
        };

        let timestamp = chrono::Utc::now().timestamp();
        let body_hash = hex::encode(Sha256::digest(body));
        let message = format!("{}:{}:{}:{}", timestamp, method, path, body_hash);
        let signature = identity.sign_message(message.as_bytes());

        vec![
            ("X-Node-Id".to_string(), identity.node_id().to_string()),
            (
                "X-Node-Pubkey".to_string(),
                hex::encode(identity.public_key_bytes()),
            ),
            ("X-Node-Signature".to_string(), hex::encode(signature)),
            ("X-Node-Timestamp".to_string(), timestamp.to_string()),
        ]
    }

    /// Broadcast a challenge to all peers, returning the count of successful broadcasts.
    ///
    /// # Arguments
    /// * `challenge_id` - Unique identifier for the challenge
    /// * `challenge_json` - Challenge data as JSON
    ///
    /// # Returns
    /// Number of peers that successfully received the challenge
    pub async fn broadcast_challenge(
        &self,
        challenge_id: &str,
        challenge_json: &serde_json::Value,
    ) -> Result<usize, Box<dyn std::error::Error>> {
        let peers = self.peers.read().await.clone();
        let mut success_count = 0;

        for peer_url in peers {
            let payload = serde_json::json!({
                "challenge_id": challenge_id,
                "challenge": challenge_json,
            });
            let body_bytes = serde_json::to_vec(&payload)?;
            let headers = self.sign_request("POST", "/challenge", &body_bytes);

            let mut request = self
                .client
                .post(format!("{}/challenge", peer_url))
                .timeout(self.timeout)
                .body(body_bytes)
                .header("content-type", "application/json");

            for (key, value) in headers {
                request = request.header(key, value);
            }

            let result = request.send().await;

            if let Ok(response) = result {
                if response.status().is_success() {
                    success_count += 1;
                }
            }
        }

        Ok(success_count)
    }

    /// Pull a challenge from a specific peer.
    ///
    /// # Arguments
    /// * `peer_url` - URL of the peer to pull from
    pub async fn pull_challenge(
        &self,
        peer_url: &str,
    ) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
        let response = self
            .client
            .get(format!("{}/challenge", peer_url))
            .timeout(self.timeout)
            .send()
            .await?;

        let challenge = response.json::<serde_json::Value>().await?;
        Ok(challenge)
    }

    /// Register this node with a peer.
    ///
    /// # Arguments
    /// * `peer_url` - Peer URL to register with
    /// * `our_url` - Our node's URL
    /// * `node_id` - Our node's identifier
    pub async fn register_peer(
        &self,
        peer_url: &str,
        our_url: &str,
        node_id: &str,
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.client
            .post(format!("{}/register", peer_url))
            .timeout(self.timeout)
            .json(&serde_json::json!({
                "node_id": node_id,
                "url": our_url,
            }))
            .send()
            .await?;

        Ok(())
    }

    /// Check health status of a peer, returning false if unreachable.
    ///
    /// # Arguments
    /// * `peer_url` - URL of the peer to check
    pub async fn health_check(&self, peer_url: &str) -> bool {
        let result = self
            .client
            .get(format!("{}/health", peer_url))
            .timeout(self.timeout)
            .send()
            .await;

        result.is_ok()
    }

    /// Update the list of known peers.
    ///
    /// # Arguments
    /// * `new_peers` - New list of peer URLs
    pub async fn update_peers(&self, new_peers: Vec<String>) {
        let mut peers = self.peers.write().await;
        *peers = new_peers;
    }

    /// Broadcast a hexchain lattice snapshot to all peers.
    ///
    /// # Arguments
    /// * `node_id` - This node's identifier
    /// * `snapshot` - JSON-serialized lattice snapshot (LatticeSnapshot)
    ///
    /// # Returns
    /// Number of peers that successfully received the snapshot
    pub async fn broadcast_lattice(
        &self,
        node_id: &str,
        snapshot: &serde_json::Value,
    ) -> Result<usize, Box<dyn std::error::Error>> {
        let peers = self.peers.read().await.clone();
        let mut success_count = 0;

        for peer_url in peers {
            let payload = serde_json::json!({
                "node_id": node_id,
                "snapshot": snapshot,
            });
            let body_bytes = serde_json::to_vec(&payload)?;
            let headers = self.sign_request("POST", "/hexchain/lattice/sync", &body_bytes);

            let mut request = self
                .client
                .post(format!("{}/hexchain/lattice/sync", peer_url))
                .timeout(self.timeout)
                .body(body_bytes)
                .header("content-type", "application/json");

            for (key, value) in headers {
                request = request.header(key, value);
            }

            let result = request.send().await;

            if let Ok(response) = result {
                if response.status().is_success() {
                    success_count += 1;
                }
            }
        }

        Ok(success_count)
    }

    pub async fn broadcast_block(
        &self,
        proof: &serde_json::Value,
    ) -> Result<usize, Box<dyn std::error::Error>> {
        let peers = self.peers.read().await.clone();
        let mut success_count = 0;

        for peer_url in peers {
            let body_bytes = serde_json::to_vec(proof)?;
            let headers = self.sign_request("POST", "/hexchain/submit", &body_bytes);

            let mut request = self
                .client
                .post(format!("{}/hexchain/submit", peer_url))
                .timeout(self.timeout)
                .body(body_bytes)
                .header("content-type", "application/json");

            for (key, value) in headers {
                request = request.header(key, value);
            }

            let result = request.send().await;

            if let Ok(response) = result {
                if response.status().is_success() {
                    success_count += 1;
                }
            }
        }

        Ok(success_count)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_new_creates_client_with_correct_timeout() {
        let peer_urls = vec!["http://peer1.local".to_string()];
        let gossip = GossipClient::new(peer_urls.clone(), 30);

        // Verify timeout is set correctly
        assert_eq!(gossip.timeout, Duration::from_secs(30));
    }

    #[test]
    fn test_new_creates_client_with_peer_urls() {
        let peer_urls = vec![
            "http://peer1.local".to_string(),
            "http://peer2.local".to_string(),
        ];
        let _gossip = GossipClient::new(peer_urls.clone(), 30);

        // Verify peers are stored (we'll test this through async block)
        assert_eq!(peer_urls.len(), 2);
    }

    #[tokio::test]
    async fn test_broadcast_challenge_counts_successful_peers() {
        let mut server = mockito::Server::new_async().await;
        let peer1_url = server.url();

        // Mock successful response for peer1
        let _m = server
            .mock("POST", "/challenge")
            .with_status(200)
            .with_body(r#"{"status": "ok"}"#)
            .expect(1)
            .create_async()
            .await;

        let gossip = GossipClient::new(vec![peer1_url], 5);
        let challenge_id = "test-challenge-123";
        let challenge_json = json!({"difficulty": 100, "nonce": 42});

        let result = gossip
            .broadcast_challenge(challenge_id, &challenge_json)
            .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 1);
    }

    #[tokio::test]
    async fn test_broadcast_challenge_handles_partial_failures() {
        let mut server1 = mockito::Server::new_async().await;
        let mut server2 = mockito::Server::new_async().await;

        let peer1_url = server1.url();
        let peer2_url = server2.url();

        // Peer1 responds successfully
        let _m1 = server1
            .mock("POST", "/challenge")
            .with_status(200)
            .expect(1)
            .create_async()
            .await;

        // Peer2 doesn't respond (timeout/error)
        let _m2 = server2
            .mock("POST", "/challenge")
            .with_status(500)
            .expect(1)
            .create_async()
            .await;

        let gossip = GossipClient::new(vec![peer1_url, peer2_url], 5);
        let challenge_id = "test-challenge";
        let challenge_json = json!({"difficulty": 100});

        let result = gossip
            .broadcast_challenge(challenge_id, &challenge_json)
            .await;

        // Should succeed with count of successful peers
        assert!(result.is_ok());
        // Only 1 peer succeeded
        assert_eq!(result.unwrap(), 1);
    }

    #[tokio::test]
    async fn test_pull_challenge_returns_challenge_json() {
        let mut server = mockito::Server::new_async().await;
        let peer_url = server.url();

        let expected_challenge = json!({
            "challenge_id": "ch-123",
            "difficulty": 100,
            "nonce": 42
        });

        let _m = server
            .mock("GET", "/challenge")
            .with_status(200)
            .with_body(expected_challenge.to_string())
            .expect(1)
            .create_async()
            .await;

        let gossip = GossipClient::new(vec![], 5);
        let result = gossip.pull_challenge(&peer_url).await;

        assert!(result.is_ok());
        let received = result.unwrap();
        assert_eq!(received["challenge_id"], "ch-123");
        assert_eq!(received["difficulty"], 100);
    }

    #[tokio::test]
    async fn test_register_peer_sends_correct_payload() {
        let mut server = mockito::Server::new_async().await;
        let peer_url = server.url();

        let _m = server
            .mock("POST", "/register")
            .match_body(mockito::Matcher::Json(json!({
                "node_id": "node-123",
                "url": "http://our-node"
            })))
            .with_status(200)
            .expect(1)
            .create_async()
            .await;

        let gossip = GossipClient::new(vec![], 5);
        let result = gossip
            .register_peer(&peer_url, "http://our-node", "node-123")
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_health_check_returns_true_for_healthy_peer() {
        let mut server = mockito::Server::new_async().await;
        let peer_url = server.url();

        let _m = server
            .mock("GET", "/health")
            .with_status(200)
            .with_body(r#"{"status": "healthy"}"#)
            .expect(1)
            .create_async()
            .await;

        let gossip = GossipClient::new(vec![], 5);
        let result = gossip.health_check(&peer_url).await;

        assert!(result);
    }

    #[tokio::test]
    async fn test_health_check_returns_false_for_unreachable_peer() {
        let gossip = GossipClient::new(vec![], 1); // 1 second timeout

        // Try to reach a non-existent peer (should timeout/fail)
        let result = gossip.health_check("http://127.0.0.1:1").await;

        assert!(!result);
    }

    #[tokio::test]
    async fn test_update_peers_modifies_peer_list() {
        let initial_peers = vec!["http://peer1.local".to_string()];
        let gossip = GossipClient::new(initial_peers, 30);

        let new_peers = vec![
            "http://peer2.local".to_string(),
            "http://peer3.local".to_string(),
        ];
        gossip.update_peers(new_peers.clone()).await;

        // Verify peers were updated
        let peers = gossip.peers.read().await;
        assert_eq!(peers.len(), 2);
        assert_eq!(*peers, new_peers);
    }

    #[tokio::test]
    async fn test_broadcast_challenge_to_multiple_peers() {
        let mut server1 = mockito::Server::new_async().await;
        let mut server2 = mockito::Server::new_async().await;
        let mut server3 = mockito::Server::new_async().await;

        let peer1_url = server1.url();
        let peer2_url = server2.url();
        let peer3_url = server3.url();

        // All peers respond successfully
        let _m1 = server1
            .mock("POST", "/challenge")
            .with_status(200)
            .expect(1)
            .create_async()
            .await;

        let _m2 = server2
            .mock("POST", "/challenge")
            .with_status(200)
            .expect(1)
            .create_async()
            .await;

        let _m3 = server3
            .mock("POST", "/challenge")
            .with_status(200)
            .expect(1)
            .create_async()
            .await;

        let gossip = GossipClient::new(vec![peer1_url, peer2_url, peer3_url], 5);

        let challenge_id = "test-ch";
        let challenge_json = json!({"difficulty": 100});

        let result = gossip
            .broadcast_challenge(challenge_id, &challenge_json)
            .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 3);
    }
}