example/
example.rs

1#![allow(dead_code)]
2#![allow(unused_imports)]
3use bitcoind_request::{
4    client::Client,
5    command::{
6        get_best_block_hash::GetBestBlockHashCommand,
7        get_block::{
8            GetBlockCommand, GetBlockCommandResponse, GetBlockCommandTransactionResponse,
9            GetBlockCommandVerbosity,
10        },
11        get_block_count::GetBlockCountCommand,
12        get_block_hash::GetBlockHashCommand,
13        get_block_header::GetBlockHeaderCommand,
14        get_block_stats::{
15            GetBlockStatsCommand, GetBlockStatsCommandResponse,
16            GetBlockStatsCommandWithAllStatsResponse, StatsArgumentChoices, TargetBlockArgument,
17        },
18        get_blockchain_info::GetBlockchainInfoCommand,
19        get_chain_tips::GetChainTipsCommand,
20        get_chain_tx_stats::GetChainTxStatsCommand,
21        get_connection_count::GetConnectionCountCommand,
22        get_difficulty::GetDifficultyCommand,
23        get_mempool_entry::GetMempoolEntryCommand,
24        get_mempool_info::GetMempoolInfoCommand,
25        get_mining_info::GetMiningInfoCommand,
26        get_network_hash_ps::GetNetworkHashPsCommand,
27        get_network_info::GetNetworkInfoCommand,
28        get_node_addresses::{CountArg, GetNodeAddressesCommand, NetworkArg},
29        get_peer_info::GetPeerInfoCommand,
30        get_raw_mempool::GetRawMempoolCommand,
31        get_raw_transaction::{GetRawTransactionCommand, GetRawTransactionCommandResponse, Vin},
32        get_tx_out::GetTxOutCommand,
33        get_tx_out_set_info::GetTxOutSetInfoCommand,
34        CallableCommand,
35    },
36};
37
38use bitcoind_request::client;
39use bitcoind_request::{Blockhash, BlockhashHexEncoded};
40
41use chrono::{DateTime, Duration, TimeZone, Utc};
42use jsonrpc::simple_http::{self, SimpleHttpTransport};
43use std::time::SystemTime;
44use std::{env, time::SystemTimeError};
45
46struct Seconds(pub i64);
47fn format_duration(seconds: i64) -> String {
48    let seconds_formatted = seconds % 60;
49    let minutes_formatted = (seconds / 60) % 60;
50    format!("{:#?}:{:#?}", minutes_formatted, seconds_formatted)
51}
52
53fn get_block_height(client: &Client) -> u64 {
54    let block_count = GetBlockCountCommand::new().call(client);
55    return block_count.unwrap().0;
56}
57
58fn get_time_since_last_block(client: &Client) -> Seconds {
59    let block_count = GetBlockCountCommand::new().call(client);
60    let arg = TargetBlockArgument::Height(block_count.unwrap().0);
61    let maybe_block_stats_response = GetBlockStatsCommand::new(arg).call(client);
62    let time_of_last_block = match maybe_block_stats_response {
63        Ok(block_stats_response) => match block_stats_response {
64            GetBlockStatsCommandResponse::AllStats(response) => response.time,
65            GetBlockStatsCommandResponse::SelectiveStats(response) => response.time.unwrap(),
66        },
67        Err(_) => panic!("panic"),
68    };
69    let current_datetime = chrono::offset::Utc::now();
70    let current_timestamp = current_datetime.timestamp();
71    let datetime_of_last_block = Utc.timestamp(time_of_last_block as i64, 0);
72    let difference = current_datetime.signed_duration_since(datetime_of_last_block);
73    Seconds(difference.num_seconds())
74
75    //match SystemTime::now().duration_since(time_of_last_block) {
76    //    Ok(seconds) => Ok(seconds.as_secs()),
77    //    Err(err) => Err(err),
78    //}
79}
80
81fn get_average_block_time(client: &Client) -> u64 {
82    let blocks_to_calculate = 2016;
83    let maybe_chain_tx_stats = GetChainTxStatsCommand::new()
84        .set_n_blocks(2016)
85        .call(client);
86    let average_seconds_per_block =
87        maybe_chain_tx_stats.unwrap().window_interval / blocks_to_calculate;
88    average_seconds_per_block
89}
90
91fn get_total_money_supply(client: &Client) -> f64 {
92    // calls to gettxoutsetinfo are erroring out due to this: https://github.com/apoelstra/rust-jsonrpc/issues/67
93    let tx_out_set_info = GetTxOutSetInfoCommand::new().call(client);
94    tx_out_set_info.unwrap().total_amount
95}
96
97// gets the chain size in bytes
98fn get_chain_size(client: &Client) -> u64 {
99    let blockchain_info = GetBlockchainInfoCommand::new().call(client);
100    blockchain_info.unwrap().size_on_disk
101}
102
103fn main() {
104    let password = env::var("BITCOIND_PASSWORD").expect("BITCOIND_PASSWORD env variable not set");
105    let username = env::var("BITCOIND_USERNAME").expect("BITCOIND_USERNAME env variable not set");
106    let url = env::var("BITCOIND_URL").expect("BITCOIND_URL env variable not set");
107    let client = Client::new(&url, &username, &password).expect("failed to create client");
108
109    let block_height = get_block_height(&client);
110    println!("BLOCK HEIGHT: {:#?}", block_height);
111
112    let seconds_since_last_block = get_time_since_last_block(&client).0;
113    println!(
114        "TIME SINCE LAST BLOCK: {}",
115        format_duration(seconds_since_last_block)
116    );
117
118    let average_seconds_per_block = get_average_block_time(&client);
119    println!(
120        "AVERAGE BLOCK TIME (2016): {}",
121        format_duration(average_seconds_per_block as i64)
122    );
123
124    // Errors out
125    // let total_money_supply = get_total_money_supply(&client);
126    // println!("TOTAL MONEY SUPPLY: {:#?}", total_money_supply);
127
128    // let chain_size = get_chain_size(&client);
129    // let chain_size_in_gbs = chain_size as f64 / 1_000_000_000.0;
130    // println!("CHAIN SIZE: {:#?}GB", chain_size_in_gbs);
131
132    // let hash_rate = GetNetworkHashPsCommand::new()
133    //     .set_n_blocks(
134    //         bitcoind_request::command::get_network_hash_ps::BlocksToIncludeArg::NBlocks(2016),
135    //     )
136    //     .set_height(bitcoind_request::command::get_network_hash_ps::HeightArg::Height(block_height))
137    //     .call(&client);
138    // println!("hash_rate:{:#?}", hash_rate);
139
140    // let connection_count = GetConnectionCountCommand::new().call(&client);
141    // println!("connection_count:{:#?}", connection_count);
142
143    // let node_addresses = GetNodeAddressesCommand::new()
144    //     .set_count(CountArg::AllAddresses)
145    //     .set_network(NetworkArg::All)
146    //     .call(&client);
147    // println!("node addresses:{:#?}", node_addresses.unwrap().0);
148    // let mut reachable_nodes = 0;
149    // node_addresses.unwrap().0.iter().for_each(|node| {
150    //     let current_datetime = chrono::offset::Utc::now();
151    //     let datetime_of_node = Utc.timestamp(node.time as i64, 0);
152    //     let difference: Duration = current_datetime.signed_duration_since(datetime_of_node);
153    //     let seconds = difference.num_seconds();
154    //     let seconds_in_a_day = 60 * 60 * 24;
155    //     if seconds < seconds_in_a_day {
156    //         reachable_nodes = reachable_nodes + 1;
157    //     }
158    // });
159    // println!("reachable nodes count: {}", reachable_nodes);
160
161    // let peer_info = GetPeerInfoCommand::new().call(&client);
162    // println!("peerinfo:{:#?}", peer_info.unwrap().0.last());
163
164    // let network_info = GetNetworkInfoCommand::new().call(&client);
165    // println!("network info:{:#?}", network_info);
166
167    // let mempool_info = GetMempoolInfoCommand::new().call(&client);
168    // println!("mempool info:{:#?}", mempool_info);
169
170    // let raw_mempool = GetRawMempoolCommand::new()
171    //     .set_verbose(true)
172    //     .set_mempool_sequence(false)
173    //     .call(&client);
174    // println!("raw_mempool:{:#?}", raw_mempool);
175
176    // what happens if the txid is no longer in the mempool
177    //let mempool_entry = GetMempoolEntryCommand::new(
178    //    "cbcedc2a784311f24c7cce95faae32fab093b2e98417d79db1eb9620115206e7".to_string(),
179    //)
180    //.call(&client);
181    //let mempool_entry = GetMempoolEntryCommand::new(
182    //    "cbcedc2a784311f24c7cce95faae32fab093b2e98417d79db1eb9620115206e7".to_string(),
183    //)
184    //.call(&client);
185    //println!("mempool entry:{:#?}", mempool_entry);
186    //
187    let maybe_get_block_command_response = GetBlockCommand::new(Blockhash(
188        "0000000000000000000137aa8bf31a6b8ad42ce1c08c33acfc033f97f0ef2bc7".to_string(),
189    ))
190    .verbosity(GetBlockCommandVerbosity::BlockObjectWithTransactionInformation)
191    .call(&client);
192
193    match maybe_get_block_command_response {
194        Ok(get_block_command_response) => match get_block_command_response {
195            GetBlockCommandResponse::Block(block) => {
196                println!("height: {}", block.height);
197                println!("hash: {}", block.hash);
198                println!("time: {}", block.time);
199                println!("size: {}", block.size);
200                println!("weight: {}", block.weight);
201            }
202            GetBlockCommandResponse::BlockHash(hash) => panic!("not supported"),
203        },
204        Err(err) => {}
205    }
206
207    // let block = GetBlockCommand::new(Blockhash(
208    //     "000000000000000000010887fdbbc731013853dde72c31110dc7130606df9474".to_string(),
209    // ))
210    // .verbosity(GetBlockCommandVerbosity::BlockObjectWithTransactionInformation)
211    // .call(&client);
212    // println!("mempool entry:{:#?}", block);
213
214    // let transaction = GetRawTransactionCommand::new(
215    //     "ef851362b06934b0082d4e2ea8a544c1982002deacef65198e18dc85a73aa49e".to_string(),
216    // )
217    // .verbose(true)
218    // .call(&client);
219    // println!("mempool entry:{:#?}", transaction);
220    let tx_out_set_info = GetTxOutSetInfoCommand::new().call(&client);
221    let x = tx_out_set_info.unwrap().txouts;
222    println!("{}", x);
223}