Skip to main content

kaspa_sdk/
lib.rs

1pub mod batch;
2pub mod config;
3pub mod dag;
4pub mod events;
5pub mod mem;
6pub mod monitor;
7pub mod tool;
8pub mod types;
9pub mod wallet;
10
11use crate::config::KaspaConfig;
12use crate::events::{EventListenerConfig, KaspaEventListener};
13use crate::tool::default_sequence;
14use crate::types::{
15    Balance, Block, BlockHeader, DaaScoreTimestampEstimate, EstimateNetworkHashesPerSecondResponse,
16    KaspaError, MempoolEntry, NodeInfo, Result, RpcRequest, RpcResponse, SubmitTransactionResponse,
17    Transaction, UtxoEntry,
18};
19use reqwest::{Client, Response};
20use serde::de::DeserializeOwned;
21use std::collections::{HashMap, HashSet};
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::time::Duration;
24
25pub struct NetWorkStatistics {
26    pub daily_transactions: u64,
27    pub average_block_size: f64,
28    pub network_growth: f64,
29    pub active_addresses: usize,
30    pub transaction_volume: u64,
31}
32
33/// kaspa client
34pub struct KaspaClient {
35    client: Client,
36    base_url: String,
37    request_id: AtomicU64,
38    username: Option<String>,
39    password: Option<String>,
40}
41
42impl KaspaClient {
43    /// create client
44    pub fn new(base_url: &str) -> Self {
45        Self {
46            client: Client::new(),
47            base_url: base_url.to_string(),
48            request_id: AtomicU64::new(0),
49            username: None,
50            password: None,
51        }
52    }
53
54    /// create client from config
55    pub fn from_config(config: KaspaConfig) -> Self {
56        Self {
57            client: Client::new(),
58            base_url: config.rpc_url,
59            request_id: AtomicU64::new(0),
60            username: None,
61            password: None,
62        }
63    }
64
65    /// create by username and password
66    pub fn auth(mut self, username: &str, password: &str) -> Self {
67        self.username = Some(username.to_string());
68        self.password = Some(password.to_string());
69        self
70    }
71
72    /// create on timeout
73    pub fn timeout(mut self, timeout: Duration) -> Self {
74        self.client = Client::builder().timeout(timeout).build().unwrap();
75        self
76    }
77
78    /// send request
79    async fn send_request<T: DeserializeOwned>(
80        &self,
81        method: &str,
82        params: Option<serde_json::Value>,
83    ) -> Result<T> {
84        let id = self.request_id.fetch_add(1, Ordering::SeqCst);
85        let request = RpcRequest {
86            jsonrpc: "2.0".to_string(),
87            id,
88            method: method.to_string(),
89            params,
90        };
91        let mut request_builder = self
92            .client
93            .post(&self.base_url)
94            .header("Content-Type", "application/json")
95            .json(&request);
96        // Add authentication if provided
97        if let (Some(username), Some(password)) = (&self.username, &self.password) {
98            request_builder = request_builder.basic_auth(username, Some(password));
99        }
100        let response: Response = request_builder.send().await?;
101        if !response.status().is_success() {
102            return Err(KaspaError::ConnectionError(format!(
103                "HTTP error: {}",
104                response.status()
105            )));
106        }
107        let rpc_response: RpcResponse<T> = response.json().await?;
108        if let Some(error) = rpc_response.error {
109            return Err(KaspaError::RpcError {
110                code: error.code,
111                message: error.message,
112            });
113        }
114        rpc_response.result.ok_or_else(|| {
115            KaspaError::InvalidResponse("Missing result in RPC response".to_string())
116        })
117    }
118
119    /// get network statistics
120    pub async fn get_network_statistics(&self, days: u64) -> Result<NetWorkStatistics> {
121        let current_block_count = self.get_block_count().await?;
122        let start_block = current_block_count.saturating_sub(days * 144); // 假设每天144个区块
123        let mut total_transactions = 0;
124        let mut total_block_size = 0;
125        let mut active_addresses = HashSet::new();
126        let mut total_volume = 0;
127        for block_num in start_block..=current_block_count {
128            if let Ok(block) = self.get_block_by_number(block_num).await {
129                total_transactions += block.transactions.len();
130                for tx in &block.transactions {
131                    self.analyze_transaction_addresses(tx, &mut active_addresses);
132                    total_volume += self.cal_transaction_volume(tx);
133                }
134            }
135        }
136        let block_count = (current_block_count - start_block) as f64;
137        let average_block_size = total_block_size as f64 / block_count.max(1.0);
138        Ok(NetWorkStatistics {
139            daily_transactions: total_transactions as u64 / days,
140            average_block_size,
141            network_growth: self.cal_network_growth().await?,
142            active_addresses: active_addresses.len(),
143            transaction_volume: total_volume,
144        })
145    }
146
147    /// get block info by number
148    async fn get_block_by_number(&self, block_number: u64) -> Result<Block> {
149        let blocks = self.get_blocks("", false, true).await?;
150        blocks
151            .first()
152            .cloned()
153            .ok_or_else(|| KaspaError::Custom(format!("Block number {} not found", block_number)))
154    }
155
156    /// analyze transaction addresses
157    fn analyze_transaction_addresses(
158        &self,
159        transaction: &Transaction,
160        active_addresses: &mut HashSet<String>,
161    ) -> HashSet<String> {
162        for output in &transaction.outputs {
163            if let Some(verbose_data) = &output.verbose_data {
164                active_addresses.insert(verbose_data.script_public_key_address.clone());
165            }
166        }
167        active_addresses.clone()
168    }
169
170    /// Calculate the total value of all transactions in a transaction.
171    pub fn cal_transaction_volume(&self, transaction: &Transaction) -> u64 {
172        transaction.outputs.iter().map(|output| output.value).sum()
173    }
174
175    /// calculate network growth
176    pub async fn cal_network_growth(&self) -> Result<f64> {
177        // Get current block information
178        let current_info = self.get_info().await?;
179        let current_block_count = current_info.block_count;
180        // Get block information from 24 hours ago (estimated by virtual chain changes)
181        let virtual_chain = self.get_virtual_chain_from_block("", false).await?;
182        // Calculate block growth within 24 hours
183        let blocks_24h = if let Some(added_blocks) = virtual_chain.get("addedChainBlockHashes") {
184            added_blocks.as_array().map(|arr| arr.len()).unwrap_or(0)
185        } else {
186            let avg_block_time = 1.0; // Kaspa average block time (seconds)
187            let estimated_24h_blocks = (24 * 60 * 60) as f64 / avg_block_time;
188            estimated_24h_blocks as usize
189        };
190        let growth_rate = if current_block_count > 0 {
191            (blocks_24h as f64) / (current_block_count as f64) * 100.0
192        } else {
193            0.0
194        };
195        Ok(growth_rate)
196    }
197
198    /// Address cluster analysis.
199    /// Used to identify related addresses belonging to the same user or entity.
200    /// Analyze all transactions in the most recent `depth` blocks.
201    /// For each transaction, collect all output addresses and cluster together multiple addresses that appear in the same transaction.
202    ///
203    /// # Example
204    /// ```rust
205    /// let client = KaspaClient::new("http://localhost:16110");
206    /// let clusters = client.analyze_address_clusters(500).await?;
207    /// let mixing_patterns: Vec<_> = clusters
208    /// .iter()
209    /// .filter(|(_, addresses)| {
210    ///      // Detection characteristics
211    ///       addresses.len() > 20
212    /// }).collect();
213    /// ```
214    pub async fn analyze_address_clusters(
215        &self,
216        depth: u64,
217    ) -> Result<HashMap<String, Vec<String>>> {
218        let mut clusters: HashMap<String, Vec<String>> = HashMap::new();
219        let mut visited_addresses = HashSet::new();
220        let blocks = self.get_blocks("", false, true).await?;
221        let total_blocks = blocks.len();
222        let start_index = total_blocks.saturating_sub(depth as usize);
223        for i in start_index..total_blocks {
224            if let Some(block) = blocks.get(i) {
225                for tx in &block.transactions {
226                    let mut addresses_in_tx = HashSet::new();
227                    for output in &tx.outputs {
228                        if let Some(verbose_data) = &output.verbose_data {
229                            addresses_in_tx.insert(verbose_data.script_public_key_address.clone());
230                        }
231                    }
232                    if addresses_in_tx.len() > 1 {
233                        let addresses: Vec<String> = addresses_in_tx.into_iter().collect();
234                        let cluster_key = addresses[0].clone();
235                        let cluster = clusters.entry(cluster_key).or_insert_with(Vec::new);
236                        for address in addresses {
237                            if !cluster.contains(&address) && !visited_addresses.contains(&address)
238                            {
239                                cluster.push(address.clone());
240                                visited_addresses.insert(address);
241                            }
242                        }
243                    }
244                }
245            }
246        }
247        Ok(clusters)
248    }
249
250    /// get block
251    pub async fn get_block(&self, hash: &str, include_transactions: bool) -> Result<Block> {
252        let params = serde_json::json!([hash, {
253            "includeTransactions": include_transactions,
254            "includeBlockVerboseData": true
255        }]);
256        self.send_request("getBlock", Some(params)).await
257    }
258
259    /// get blocks
260    pub async fn get_blocks(
261        &self,
262        low_hash: &str,
263        include_transactions: bool,
264        include_block_verbose_data: bool,
265    ) -> Result<Vec<Block>> {
266        let params = serde_json::json!([low_hash, {
267            "includeTransactions": include_transactions,
268            "includeBlockVerboseData": include_block_verbose_data
269        }]);
270        self.send_request("getBlocks", Some(params)).await
271    }
272
273    /// get block count
274    pub async fn get_block_count(&self) -> Result<u64> {
275        self.send_request("getBlockCount", None).await
276    }
277
278    /// get block dag info
279    pub async fn get_block_dag_info(&self) -> Result<serde_json::Value> {
280        self.send_request("getBlockDagInfo", None).await
281    }
282
283    /// get block template
284    pub async fn get_block_template(
285        &self,
286        pay_address: &str,
287        extra_data: Option<&str>,
288    ) -> Result<serde_json::Value> {
289        let mut params = serde_json::json!({
290            "payAddress": pay_address
291        });
292        if let Some(extra_data) = extra_data {
293            params["extraData"] = serde_json::Value::String(extra_data.to_string());
294        }
295        self.send_request("getBlockTemplate", Some(serde_json::json!([params])))
296            .await
297    }
298
299    /// get current network
300    pub async fn get_current_network(&self) -> Result<String> {
301        self.send_request("getCurrentNetwork", None).await
302    }
303
304    /// get headers
305    pub async fn get_headers(&self, low_hash: &str) -> Result<Vec<BlockHeader>> {
306        let params = serde_json::json!([low_hash]);
307        self.send_request("getHeaders", Some(params)).await
308    }
309
310    /// get peer address
311    pub async fn get_peer_addresses(&self) -> Result<Vec<serde_json::Value>> {
312        self.send_request("getPeerAddresses", None).await
313    }
314
315    /// get sink
316    pub async fn get_sink(&self) -> Result<String> {
317        self.send_request("getSink", None).await
318    }
319
320    pub async fn get_sink_blue_score(&self) -> Result<u64> {
321        self.send_request("getSinkBlueScore", None).await
322    }
323
324    pub async fn get_mempool_entries(
325        &self,
326        include_orphan_pool: Option<bool>,
327    ) -> Result<Vec<MempoolEntry>> {
328        let params = if let Some(include_orphan) = include_orphan_pool {
329            Some(serde_json::json!([include_orphan]))
330        } else {
331            None
332        };
333        self.send_request("getMempoolEntries", params).await
334    }
335
336    pub async fn get_mempool_entries_by_addresses(
337        &self,
338        addresses: Vec<&str>,
339    ) -> Result<Vec<MempoolEntry>> {
340        let params = serde_json::json!([addresses]);
341        self.send_request("getMempoolEntriesByAddresses", Some(params))
342            .await
343    }
344
345    pub async fn get_mempool_entry(&self, transaction_id: &str) -> Result<MempoolEntry> {
346        let params = serde_json::json!([transaction_id]);
347        self.send_request("getMempoolEntry", Some(params)).await
348    }
349
350    pub async fn get_connected_peer_info(&self) -> Result<Vec<serde_json::Value>> {
351        self.send_request("getConnectedPeerInfo", None).await
352    }
353
354    pub async fn get_subnetwork(&self, subnetwork_id: &str) -> Result<serde_json::Value> {
355        let params = serde_json::json!([subnetwork_id]);
356        self.send_request("getSubnetwork", Some(params)).await
357    }
358
359    pub async fn get_utxos_by_addresses(&self, addresses: Vec<&str>) -> Result<Vec<UtxoEntry>> {
360        let params = serde_json::json!([addresses]);
361        self.send_request("getUtxosByAddresses", Some(params)).await
362    }
363
364    pub async fn get_balance_by_address(&self, address: &str) -> Result<Balance> {
365        let params = serde_json::json!([address]);
366        self.send_request("getBalanceByAddress", Some(params)).await
367    }
368
369    pub async fn get_balances_by_addresses(&self, addresses: Vec<&str>) -> Result<Vec<Balance>> {
370        let params = serde_json::json!([addresses]);
371        self.send_request("getBalancesByAddresses", Some(params))
372            .await
373    }
374
375    pub async fn get_virtual_chain_from_block(
376        &self,
377        start_hash: &str,
378        include_accepted_transaction_ids: bool,
379    ) -> Result<serde_json::Value> {
380        let params = serde_json::json!([start_hash, include_accepted_transaction_ids]);
381        self.send_request("getVirtualChainFromBlock", Some(params))
382            .await
383    }
384
385    pub async fn get_info(&self) -> Result<NodeInfo> {
386        self.send_request("getInfo", None).await
387    }
388
389    // Mining methods
390    pub async fn submit_block(&self, block: &str) -> Result<String> {
391        let params = serde_json::json!([block]);
392        self.send_request("submitBlock", Some(params)).await
393    }
394
395    pub async fn estimate_network_hashes_per_second(
396        &self,
397        window_size: Option<u32>,
398    ) -> Result<EstimateNetworkHashesPerSecondResponse> {
399        let params = if let Some(window) = window_size {
400            Some(serde_json::json!([window]))
401        } else {
402            None
403        };
404        self.send_request("estimateNetworkHashesPerSecond", params)
405            .await
406    }
407
408    pub async fn get_daa_score_timestamp_estimate(
409        &self,
410        daa_scores: Vec<u64>,
411    ) -> Result<Vec<DaaScoreTimestampEstimate>> {
412        let params = serde_json::json!([daa_scores]);
413        self.send_request("getDaaScoreTimestampEstimate", Some(params))
414            .await
415    }
416
417    // Transaction methods
418    pub async fn submit_transaction(&self, transaction: &str) -> Result<SubmitTransactionResponse> {
419        let params = serde_json::json!([transaction]);
420        self.send_request("submitTransaction", Some(params)).await
421    }
422
423    pub async fn get_transaction(&self, transaction_id: &str) -> Result<Transaction> {
424        let params = serde_json::json!([transaction_id]);
425        self.send_request("getTransaction", Some(params)).await
426    }
427
428    // Subscription methods (these would typically use WebSocket)
429    pub async fn notify_block_added(&self, command: Option<&str>) -> Result<()> {
430        let params = if let Some(cmd) = command {
431            Some(serde_json::json!([cmd]))
432        } else {
433            None
434        };
435        self.send_request("notifyBlockAdded", params).await
436    }
437
438    pub async fn notify_finality_conflict(&self, command: Option<&str>) -> Result<()> {
439        let params = if let Some(cmd) = command {
440            Some(serde_json::json!([cmd]))
441        } else {
442            None
443        };
444        self.send_request("notifyFinalityConflict", params).await
445    }
446
447    pub async fn notify_utxos_changed(
448        &self,
449        addresses: Vec<&str>,
450        command: Option<&str>,
451    ) -> Result<()> {
452        let mut params_obj = serde_json::json!({
453            "addresses": addresses
454        });
455
456        if let Some(cmd) = command {
457            params_obj["command"] = serde_json::Value::String(cmd.to_string());
458        }
459
460        self.send_request("notifyUtxosChanged", Some(serde_json::json!([params_obj])))
461            .await
462    }
463
464    pub async fn notify_virtual_chain_changed(
465        &self,
466        include_accepted_transaction_ids: bool,
467        command: Option<&str>,
468    ) -> Result<()> {
469        let mut params_obj = serde_json::json!({
470            "includeAcceptedTransactionIds": include_accepted_transaction_ids
471        });
472
473        if let Some(cmd) = command {
474            params_obj["command"] = serde_json::Value::String(cmd.to_string());
475        }
476
477        self.send_request(
478            "notifyVirtualChainChanged",
479            Some(serde_json::json!([params_obj])),
480        )
481        .await
482    }
483
484    pub async fn stop_notifying_block_added(&self) -> Result<()> {
485        self.send_request("stopNotifyingBlockAdded", None).await
486    }
487
488    pub async fn stop_notifying_finality_conflict(&self) -> Result<()> {
489        self.send_request("stopNotifyingFinalityConflict", None)
490            .await
491    }
492
493    pub async fn stop_notifying_utxos_changed(&self) -> Result<()> {
494        self.send_request("stopNotifyingUtxosChanged", None).await
495    }
496
497    pub async fn stop_notifying_virtual_chain_changed(&self) -> Result<()> {
498        self.send_request("stopNotifyingVirtualChainChanged", None)
499            .await
500    }
501
502    // Utility methods
503    pub async fn ping(&self) -> Result<bool> {
504        match self.get_info().await {
505            Ok(_) => Ok(true),
506            Err(_) => Ok(false),
507        }
508    }
509
510    pub async fn get_sync_status(&self) -> Result<bool> {
511        let info = self.get_info().await?;
512        Ok(info.is_synced)
513    }
514
515    /// create event listener
516    pub fn create_event_listener(&self) -> KaspaEventListener {
517        let ws_url = self.base_url.replace("http", "ws");
518        let config = EventListenerConfig {
519            ws_url,
520            username: self.username.clone(),
521            password: self.password.clone(),
522            ..Default::default()
523        };
524        KaspaEventListener::from_config(config)
525    }
526}
527
528/// The kaspa client includes some advanced client features.
529pub struct KaspaClient2 {
530    client: KaspaClient,
531}
532
533impl KaspaClient2 {
534    pub fn new(client: KaspaClient) -> Self {
535        Self { client }
536    }
537    /// Batch operations
538    pub async fn get_multiple_blocks(&self, hashes: Vec<&str>) -> Result<Vec<Block>> {
539        let mut blocks = Vec::new();
540        for hash in hashes {
541            match self.client.get_block(hash, false).await {
542                Ok(block) => blocks.push(block),
543                Err(e) => return Err(e),
544            }
545        }
546        Ok(blocks)
547    }
548    /// get multiple transactions
549    pub async fn get_multiple_transactions(
550        &self,
551        transaction_ids: Vec<&str>,
552    ) -> Result<Vec<Transaction>> {
553        let mut transactions = Vec::new();
554        for tx_id in transaction_ids {
555            match self.client.get_transaction(tx_id).await {
556                Ok(tx) => transactions.push(tx),
557                Err(e) => return Err(e),
558            }
559        }
560        Ok(transactions)
561    }
562    /// Address management
563    pub async fn get_combined_balance(&self, addresses: Vec<&str>) -> Result<u64> {
564        let balances = self.client.get_balances_by_addresses(addresses).await?;
565        Ok(balances.iter().map(|b| b.balance).sum())
566    }
567
568    /// get utxos for addresses
569    pub async fn get_utxos_for_addresses(&self, addresses: Vec<&str>) -> Result<Vec<UtxoEntry>> {
570        self.client.get_utxos_by_addresses(addresses).await
571    }
572
573    /// Blockchain analysis
574    pub async fn get_recent_blocks(&self, count: u64) -> Result<Vec<Block>> {
575        let current_height = self.client.get_block_count().await?;
576        let mut blocks = Vec::new();
577        for i in 0..count {
578            if current_height > i {
579                // This is simplified - in practice you'd need to get block hash by height first
580                // For now, we'll get the latest blocks using getBlocks
581                if let Ok(mut recent_blocks) = self.client.get_blocks("", false, true).await {
582                    if recent_blocks.len() > i as usize {
583                        blocks.push(recent_blocks.remove(0));
584                    }
585                }
586            }
587        }
588        Ok(blocks)
589    }
590
591    // Transaction building utilities
592    pub async fn create_transaction_template(
593        &self,
594        from_address: &str,
595        to_address: &str,
596        amount: u64,
597        fee_per_byte: u64,
598    ) -> Result<serde_json::Value> {
599        // Get UTXOs for the sender
600        let utxos = self
601            .client
602            .get_utxos_by_addresses(vec![from_address])
603            .await?;
604        // Calculate total available
605        let total_available: u64 = utxos.iter().map(|utxo| utxo.amount).sum();
606        if total_available < amount {
607            return Err(KaspaError::Custom(format!(
608                "Insufficient balance: available {}, required {}",
609                total_available, amount
610            )));
611        }
612        // Simple transaction template
613        let template = serde_json::json!({
614            "inputs": utxos.iter().map(|utxo| {
615                serde_json::json!({
616                    "previousOutpoint": {
617                        "transactionId": "TODO", // Would need transaction ID from UTXO
618                        "index": 0
619                    },
620                    "signatureScript": "",
621                    "sequence": default_sequence()
622                })
623            }).collect::<Vec<_>>(),
624            "outputs": vec![
625                serde_json::json!({
626                    "value": amount,
627                    "scriptPublicKey": {
628                        "version": 0,
629                        "scriptPublicKey": to_address // This should be converted to script
630                    }
631                })
632            ],
633            "lockTime": 0,
634            "subnetworkId": "0000000000000000000000000000000000000000",
635            "gas": 0,
636            "payload": ""
637        });
638        Ok(template)
639    }
640
641    /// Network monitoring
642    pub async fn get_network_stats(&self) -> Result<serde_json::Value> {
643        let info = self.client.get_info().await?;
644        let peer_info = self.client.get_connected_peer_info().await?;
645        let mempool_size = self.client.get_mempool_entries(None).await?.len();
646
647        Ok(serde_json::json!({
648            "node_info": info,
649            "connected_peers": peer_info.len(),
650            "mempool_transactions": mempool_size,
651            "network": "kaspa-mainnet" // This should come from getCurrentNetwork
652        }))
653    }
654
655    /// Health check
656    pub async fn health_check(&self) -> Result<serde_json::Value> {
657        let is_connected = self.client.ping().await?;
658        let is_synced = self.client.get_sync_status().await.unwrap_or(false);
659        let block_count = self.client.get_block_count().await.unwrap_or(0);
660
661        Ok(serde_json::json!({
662            "status": if is_connected && is_synced { "healthy" } else { "unhealthy" },
663            "connected": is_connected,
664            "synced": is_synced,
665            "block_count": block_count,
666            "timestamp": chrono::Utc::now().timestamp()
667        }))
668    }
669}