rustchain-client 0.1.0

HTTP client library for the RustChain Proof-of-Antiquity blockchain API. Query node health, epochs, miners, wallets, attestations, and governance proposals.
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! # rustchain-client
//!
//! An HTTP client for the [RustChain](https://rustchain.org) Proof-of-Antiquity blockchain API.
//!
//! RustChain is the first blockchain that rewards vintage hardware (PowerPC G4, IBM POWER8,
//! Pentium 4, etc.) for being old — not fast. This crate provides a typed Rust client for
//! querying the RustChain node API.
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use rustchain_client::RustChainClient;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), rustchain_client::Error> {
//!     let client = RustChainClient::new("https://rustchain.org")?;
//!
//!     // Check node health
//!     let health = client.health().await?;
//!     println!("Node status: {}", health.status);
//!
//!     // Get current epoch
//!     let epoch = client.epoch().await?;
//!     println!("Current epoch: {}", epoch.epoch);
//!
//!     // List active miners
//!     let miners = client.miners().await?;
//!     println!("Active miners: {}", miners.len());
//!
//!     Ok(())
//! }
//! ```
//!
//! ## Features
//!
//! - Query node health, uptime, and version
//! - Get current epoch information and reward pools
//! - List active miners with hardware details and antiquity multipliers
//! - Check wallet balances
//! - Submit and query attestations
//! - List and vote on governance proposals
//! - Uses `rustls` for TLS (no OpenSSL dependency)
//! - Supports self-signed certificates (common on RustChain nodes)

use reqwest::Client;
use serde::{Deserialize, Serialize};

mod error;
pub use error::Error;

/// Response from the `/health` endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthResponse {
    /// Node status string (e.g., "healthy").
    pub status: String,
    /// Node uptime in seconds.
    #[serde(default)]
    pub uptime: Option<f64>,
    /// Software version.
    #[serde(default)]
    pub version: Option<String>,
    /// Number of connected peers.
    #[serde(default)]
    pub peers: Option<u32>,
    /// Current block height.
    #[serde(default)]
    pub block_height: Option<u64>,
}

/// Response from the `/epoch` endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EpochResponse {
    /// Current epoch number.
    pub epoch: u64,
    /// Epoch duration in seconds.
    #[serde(default)]
    pub duration_seconds: Option<u64>,
    /// Time remaining in current epoch.
    #[serde(default)]
    pub time_remaining: Option<f64>,
    /// Base reward pool for this epoch.
    #[serde(default)]
    pub reward_pool: Option<f64>,
    /// Number of active attestations this epoch.
    #[serde(default)]
    pub attestations: Option<u64>,
    /// Epoch start timestamp.
    #[serde(default)]
    pub started_at: Option<String>,
}

/// A single miner entry from the `/api/miners` endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Miner {
    /// Miner's wallet identifier.
    #[serde(alias = "miner_id")]
    pub wallet: String,
    /// Hardware architecture (e.g., "PowerPC G4", "x86_64").
    #[serde(default)]
    pub architecture: Option<String>,
    /// Antiquity multiplier (e.g., 2.5 for PowerPC G4).
    #[serde(default)]
    pub multiplier: Option<f64>,
    /// Whether this miner is currently active.
    #[serde(default)]
    pub active: Option<bool>,
    /// Last attestation timestamp.
    #[serde(default)]
    pub last_seen: Option<String>,
    /// Total RTC earned.
    #[serde(default)]
    pub total_earned: Option<f64>,
    /// Hardware platform string.
    #[serde(default)]
    pub platform: Option<String>,
}

/// Wallet balance response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WalletBalance {
    /// Wallet/miner identifier.
    #[serde(alias = "miner_id")]
    pub wallet: String,
    /// Current balance in RTC.
    pub balance: f64,
    /// Total earned across all epochs.
    #[serde(default)]
    pub total_earned: Option<f64>,
    /// Total number of attestations submitted.
    #[serde(default)]
    pub attestation_count: Option<u64>,
}

/// Attestation submission payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttestationSubmit {
    /// Miner wallet identifier.
    pub miner: String,
    /// Hardware fingerprint data.
    pub fingerprint: serde_json::Value,
    /// Optional nonce for uniqueness.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nonce: Option<String>,
}

/// Response after submitting an attestation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttestationResponse {
    /// Whether the attestation was accepted.
    #[serde(default)]
    pub accepted: Option<bool>,
    /// Status message.
    #[serde(default)]
    pub status: Option<String>,
    /// Error message if rejected.
    #[serde(default)]
    pub error: Option<String>,
    /// Epoch the attestation was recorded for.
    #[serde(default)]
    pub epoch: Option<u64>,
}

/// A governance proposal.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Proposal {
    /// Proposal ID.
    pub id: u64,
    /// Proposal title.
    pub title: String,
    /// Proposal description / rationale.
    #[serde(default)]
    pub description: Option<String>,
    /// Proposer wallet address.
    #[serde(default)]
    pub proposer: Option<String>,
    /// Current status (Draft, Active, Passed, Failed).
    #[serde(default)]
    pub status: Option<String>,
    /// Yes-vote weight.
    #[serde(default)]
    pub yes_weight: Option<f64>,
    /// No-vote weight.
    #[serde(default)]
    pub no_weight: Option<f64>,
    /// Creation timestamp.
    #[serde(default)]
    pub created_at: Option<String>,
}

/// Governance vote payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Vote {
    /// Proposal ID to vote on.
    pub proposal_id: u64,
    /// Voter wallet address.
    pub wallet: String,
    /// Vote direction ("yes" or "no").
    pub vote: String,
    /// Nonce for replay protection.
    pub nonce: String,
    /// Ed25519 public key (hex).
    pub public_key: String,
    /// Ed25519 signature (hex).
    pub signature: String,
}

/// Vote submission response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VoteResponse {
    /// Whether the vote was recorded.
    #[serde(default)]
    pub accepted: Option<bool>,
    /// Status message.
    #[serde(default)]
    pub status: Option<String>,
    /// Error details.
    #[serde(default)]
    pub error: Option<String>,
}

/// Agent Economy job listing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentJob {
    /// Unique job identifier.
    pub job_id: String,
    /// Job title.
    #[serde(default)]
    pub title: Option<String>,
    /// Job description.
    #[serde(default)]
    pub description: Option<String>,
    /// RTC reward for completing this job.
    #[serde(default)]
    pub reward_rtc: Option<f64>,
    /// Job status (open, claimed, delivered, accepted).
    #[serde(default)]
    pub status: Option<String>,
    /// Job category.
    #[serde(default)]
    pub category: Option<String>,
    /// Poster agent name.
    #[serde(default)]
    pub posted_by: Option<String>,
}

/// Agent Economy jobs list response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentJobsResponse {
    /// Whether the request succeeded.
    #[serde(default)]
    pub ok: Option<bool>,
    /// List of jobs.
    #[serde(default)]
    pub jobs: Vec<AgentJob>,
    /// Total count of matching jobs.
    #[serde(default)]
    pub total: Option<u64>,
    /// Available job categories.
    #[serde(default)]
    pub categories: Option<Vec<String>>,
}

/// The main RustChain API client.
///
/// # Example
///
/// ```rust,no_run
/// use rustchain_client::RustChainClient;
///
/// # async fn example() -> Result<(), rustchain_client::Error> {
/// let client = RustChainClient::new("https://rustchain.org")?;
/// let health = client.health().await?;
/// println!("{:?}", health);
/// # Ok(())
/// # }
/// ```
pub struct RustChainClient {
    base_url: String,
    http: Client,
}

impl RustChainClient {
    /// Create a new RustChain API client.
    ///
    /// # Arguments
    ///
    /// * `base_url` - The base URL of the RustChain node (e.g., `"https://rustchain.org"` or
    ///   `"https://50.28.86.131"`).
    ///
    /// Accepts self-signed certificates, which is common for RustChain nodes.
    pub fn new(base_url: &str) -> Result<Self, Error> {
        let http = Client::builder()
            .danger_accept_invalid_certs(true)
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .map_err(Error::Http)?;

        Ok(Self {
            base_url: base_url.trim_end_matches('/').to_string(),
            http,
        })
    }

    /// Create a client with a custom `reqwest::Client`.
    pub fn with_client(base_url: &str, http: Client) -> Self {
        Self {
            base_url: base_url.trim_end_matches('/').to_string(),
            http,
        }
    }

    /// Check node health.
    ///
    /// Calls `GET /health`.
    pub async fn health(&self) -> Result<HealthResponse, Error> {
        let url = format!("{}/health", self.base_url);
        let resp = self.http.get(&url).send().await.map_err(Error::Http)?;
        let status = resp.status();
        if !status.is_success() {
            return Err(Error::Api {
                status: status.as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        resp.json().await.map_err(Error::Http)
    }

    /// Get current epoch information.
    ///
    /// Calls `GET /epoch`.
    pub async fn epoch(&self) -> Result<EpochResponse, Error> {
        let url = format!("{}/epoch", self.base_url);
        let resp = self.http.get(&url).send().await.map_err(Error::Http)?;
        let status = resp.status();
        if !status.is_success() {
            return Err(Error::Api {
                status: status.as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        resp.json().await.map_err(Error::Http)
    }

    /// List active miners on the network.
    ///
    /// Calls `GET /api/miners`.
    pub async fn miners(&self) -> Result<Vec<Miner>, Error> {
        let url = format!("{}/api/miners", self.base_url);
        let resp = self.http.get(&url).send().await.map_err(Error::Http)?;
        let status = resp.status();
        if !status.is_success() {
            return Err(Error::Api {
                status: status.as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        // The API may return miners as a top-level array or under a key
        let text = resp.text().await.map_err(Error::Http)?;
        // Try parsing as array first
        if let Ok(miners) = serde_json::from_str::<Vec<Miner>>(&text) {
            return Ok(miners);
        }
        // Try as object with "miners" key
        #[derive(Deserialize)]
        struct Wrapper {
            miners: Vec<Miner>,
        }
        let wrapper: Wrapper = serde_json::from_str(&text).map_err(Error::Json)?;
        Ok(wrapper.miners)
    }

    /// Check a wallet's RTC balance.
    ///
    /// Calls `GET /wallet/balance?miner_id={wallet}`.
    pub async fn wallet_balance(&self, wallet: &str) -> Result<WalletBalance, Error> {
        let url = format!("{}/wallet/balance?miner_id={}", self.base_url, wallet);
        let resp = self.http.get(&url).send().await.map_err(Error::Http)?;
        let status = resp.status();
        if !status.is_success() {
            return Err(Error::Api {
                status: status.as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        resp.json().await.map_err(Error::Http)
    }

    /// Submit a mining attestation.
    ///
    /// Calls `POST /attest/submit`.
    pub async fn submit_attestation(
        &self,
        attestation: &AttestationSubmit,
    ) -> Result<AttestationResponse, Error> {
        let url = format!("{}/attest/submit", self.base_url);
        let resp = self
            .http
            .post(&url)
            .json(attestation)
            .send()
            .await
            .map_err(Error::Http)?;
        let status = resp.status();
        if !status.is_success() && status.as_u16() != 429 {
            return Err(Error::Api {
                status: status.as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        resp.json().await.map_err(Error::Http)
    }

    /// List governance proposals.
    ///
    /// Calls `GET /governance/proposals`.
    pub async fn proposals(&self) -> Result<Vec<Proposal>, Error> {
        let url = format!("{}/governance/proposals", self.base_url);
        let resp = self.http.get(&url).send().await.map_err(Error::Http)?;
        let status = resp.status();
        if !status.is_success() {
            return Err(Error::Api {
                status: status.as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        let text = resp.text().await.map_err(Error::Http)?;
        if let Ok(proposals) = serde_json::from_str::<Vec<Proposal>>(&text) {
            return Ok(proposals);
        }
        #[derive(Deserialize)]
        struct Wrapper {
            proposals: Vec<Proposal>,
        }
        let wrapper: Wrapper = serde_json::from_str(&text).map_err(Error::Json)?;
        Ok(wrapper.proposals)
    }

    /// Get a single governance proposal by ID.
    ///
    /// Calls `GET /governance/proposal/{id}`.
    pub async fn proposal(&self, id: u64) -> Result<Proposal, Error> {
        let url = format!("{}/governance/proposal/{}", self.base_url, id);
        let resp = self.http.get(&url).send().await.map_err(Error::Http)?;
        let status = resp.status();
        if !status.is_success() {
            return Err(Error::Api {
                status: status.as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        resp.json().await.map_err(Error::Http)
    }

    /// Submit a governance vote.
    ///
    /// Calls `POST /governance/vote`.
    pub async fn vote(&self, vote: &Vote) -> Result<VoteResponse, Error> {
        let url = format!("{}/governance/vote", self.base_url);
        let resp = self
            .http
            .post(&url)
            .json(vote)
            .send()
            .await
            .map_err(Error::Http)?;
        let status = resp.status();
        if !status.is_success() {
            return Err(Error::Api {
                status: status.as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        resp.json().await.map_err(Error::Http)
    }

    /// List open Agent Economy jobs.
    ///
    /// Calls `GET /agent/jobs`.
    pub async fn agent_jobs(&self) -> Result<AgentJobsResponse, Error> {
        let url = format!("{}/agent/jobs", self.base_url);
        let resp = self.http.get(&url).send().await.map_err(Error::Http)?;
        let status = resp.status();
        if !status.is_success() {
            return Err(Error::Api {
                status: status.as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }
        resp.json().await.map_err(Error::Http)
    }

    /// Get the base URL of this client.
    pub fn base_url(&self) -> &str {
        &self.base_url
    }
}

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

    #[test]
    fn test_client_creation() {
        let client = RustChainClient::new("https://rustchain.org").unwrap();
        assert_eq!(client.base_url(), "https://rustchain.org");
    }

    #[test]
    fn test_trailing_slash_stripped() {
        let client = RustChainClient::new("https://rustchain.org/").unwrap();
        assert_eq!(client.base_url(), "https://rustchain.org");
    }

    #[test]
    fn test_health_deserialize() {
        let json = r#"{"status":"healthy","uptime":3600.5,"version":"2.2.1","peers":3}"#;
        let health: HealthResponse = serde_json::from_str(json).unwrap();
        assert_eq!(health.status, "healthy");
        assert_eq!(health.uptime, Some(3600.5));
        assert_eq!(health.version.as_deref(), Some("2.2.1"));
        assert_eq!(health.peers, Some(3));
    }

    #[test]
    fn test_epoch_deserialize() {
        let json = r#"{"epoch":42,"duration_seconds":600,"reward_pool":1.5}"#;
        let epoch: EpochResponse = serde_json::from_str(json).unwrap();
        assert_eq!(epoch.epoch, 42);
        assert_eq!(epoch.duration_seconds, Some(600));
        assert_eq!(epoch.reward_pool, Some(1.5));
    }

    #[test]
    fn test_miner_deserialize() {
        let json = r#"{"wallet":"nox-ventures","architecture":"x86_64","multiplier":1.0,"active":true}"#;
        let miner: Miner = serde_json::from_str(json).unwrap();
        assert_eq!(miner.wallet, "nox-ventures");
        assert_eq!(miner.multiplier, Some(1.0));
    }

    #[test]
    fn test_miner_alias_field() {
        let json = r#"{"miner_id":"test-wallet","architecture":"PowerPC G4","multiplier":2.5}"#;
        let miner: Miner = serde_json::from_str(json).unwrap();
        assert_eq!(miner.wallet, "test-wallet");
        assert_eq!(miner.multiplier, Some(2.5));
    }

    #[test]
    fn test_agent_job_deserialize() {
        let json = r#"{"job_id":"job_abc123","title":"Write docs","reward_rtc":5.0,"status":"open","category":"writing"}"#;
        let job: AgentJob = serde_json::from_str(json).unwrap();
        assert_eq!(job.job_id, "job_abc123");
        assert_eq!(job.reward_rtc, Some(5.0));
        assert_eq!(job.status.as_deref(), Some("open"));
    }

    #[test]
    fn test_proposal_deserialize() {
        let json = r#"{"id":1,"title":"Enable feature X","status":"Active","yes_weight":100.5,"no_weight":20.0}"#;
        let prop: Proposal = serde_json::from_str(json).unwrap();
        assert_eq!(prop.id, 1);
        assert_eq!(prop.title, "Enable feature X");
        assert_eq!(prop.yes_weight, Some(100.5));
    }
}