Skip to content

Commit 1ef4bdc

Browse files
author
supr
authored
Instant time instead of SystemTime (#625)
* Instant time instead of SystemTime Changed functions to use std::time::Instant which is monotonic, to avoid Rust panics with SystemTime. Replaced some unwraps with an expect. Removed redundant brackets, and secp256k1:: * fn clean_old_pending_outpoints + lint Changed fn clean_old_pending_outpoints to retain keys that are younger than an hour, instead of collecting older than an hour ones as a vector, and then using a new for loop to deleting them. linting with cargo fmt
1 parent b6b344e commit 1ef4bdc

File tree

1 file changed

+20
-19
lines changed

1 file changed

+20
-19
lines changed

rothschild/src/main.rs

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use secp256k1::{
2121
rand::{thread_rng, Rng},
2222
Keypair,
2323
};
24-
use tokio::time::{interval, MissedTickBehavior};
24+
use tokio::time::{interval, Instant, MissedTickBehavior};
2525

2626
const DEFAULT_SEND_AMOUNT: u64 = 10 * SOMPI_PER_KASPA;
2727
const FEE_RATE: u64 = 10;
@@ -161,14 +161,16 @@ async fn main() {
161161
Default::default(),
162162
)
163163
.await
164-
.unwrap();
164+
.expect("Critical error: failed to connect to the RPC server.");
165+
165166
info!("Connected to RPC");
166-
let mut pending = HashMap::new();
167+
168+
let mut pending: HashMap<TransactionOutpoint, Instant> = HashMap::new();
167169

168170
let schnorr_key = if let Some(private_key_hex) = args.private_key {
169171
let mut private_key_bytes = [0u8; 32];
170172
faster_hex::hex_decode(private_key_hex.as_bytes(), &mut private_key_bytes).unwrap();
171-
secp256k1::Keypair::from_seckey_slice(secp256k1::SECP256K1, &private_key_bytes).unwrap()
173+
Keypair::from_seckey_slice(secp256k1::SECP256K1, &private_key_bytes).unwrap()
172174
} else {
173175
let (sk, pk) = &secp256k1::generate_keypair(&mut thread_rng());
174176
let kaspa_addr = Address::new(ADDRESS_PREFIX, ADDRESS_VERSION, &pk.x_only_public_key().0.serialize());
@@ -208,7 +210,8 @@ async fn main() {
208210
}
209211
info!("{}", log_message);
210212

211-
let info = rpc_client.get_block_dag_info().await.unwrap();
213+
let info = rpc_client.get_block_dag_info().await.expect("Failed to get block dag info.");
214+
212215
let coinbase_maturity = match info.network.suffix {
213216
Some(11) => TESTNET11_PARAMS.coinbase_maturity,
214217
None | Some(_) => TESTNET_PARAMS.coinbase_maturity,
@@ -251,7 +254,7 @@ async fn main() {
251254
info!(
252255
"Tx rate: {:.1}/sec, avg UTXO amount: {}, avg UTXOs per tx: {}, avg outs per tx: {}, estimated available UTXOs: {}",
253256
1000f64 * (stats.num_txs as f64) / (time_past as f64),
254-
(stats.utxos_amount / stats.num_utxos as u64),
257+
stats.utxos_amount / stats.num_utxos as u64,
255258
stats.num_utxos / stats.num_txs,
256259
stats.num_outs / stats.num_txs,
257260
utxos_len.saturating_sub(pending_len),
@@ -332,7 +335,7 @@ async fn main() {
332335
fn should_maximize_inputs(
333336
old_value: bool,
334337
utxos: &[(TransactionOutpoint, UtxoEntry)],
335-
pending: &HashMap<TransactionOutpoint, u64>,
338+
pending: &HashMap<TransactionOutpoint, Instant>,
336339
) -> bool {
337340
let estimated_utxos = if utxos.len() > pending.len() { utxos.len() - pending.len() } else { 0 };
338341
if !old_value && estimated_utxos > 1_000_000 {
@@ -362,7 +365,7 @@ async fn pause_if_mempool_is_full(rpc_client: &GrpcClient) {
362365
async fn refresh_utxos(
363366
rpc_client: &GrpcClient,
364367
kaspa_addr: Address,
365-
pending: &mut HashMap<TransactionOutpoint, u64>,
368+
pending: &mut HashMap<TransactionOutpoint, Instant>,
366369
coinbase_maturity: u64,
367370
) -> Vec<(TransactionOutpoint, UtxoEntry)> {
368371
populate_pending_outpoints_from_mempool(rpc_client, kaspa_addr.clone(), pending).await;
@@ -372,10 +375,11 @@ async fn refresh_utxos(
372375
async fn populate_pending_outpoints_from_mempool(
373376
rpc_client: &GrpcClient,
374377
kaspa_addr: Address,
375-
pending_outpoints: &mut HashMap<TransactionOutpoint, u64>,
378+
pending_outpoints: &mut HashMap<TransactionOutpoint, Instant>,
376379
) {
377380
let entries = rpc_client.get_mempool_entries_by_addresses(vec![kaspa_addr], true, false).await.unwrap();
378-
let now = unix_now();
381+
let now = Instant::now();
382+
379383
for entry in entries {
380384
for entry in entry.sending {
381385
for input in entry.transaction.inputs {
@@ -389,7 +393,7 @@ async fn fetch_spendable_utxos(
389393
rpc_client: &GrpcClient,
390394
kaspa_addr: Address,
391395
coinbase_maturity: u64,
392-
pending: &mut HashMap<TransactionOutpoint, u64>,
396+
pending: &mut HashMap<TransactionOutpoint, Instant>,
393397
) -> Vec<(TransactionOutpoint, UtxoEntry)> {
394398
let resp = rpc_client.get_utxos_by_addresses(vec![kaspa_addr]).await.unwrap();
395399
let dag_info = rpc_client.get_block_dag_info().await.unwrap();
@@ -420,7 +424,7 @@ async fn maybe_send_tx(
420424
tx_sender: &async_channel::Sender<ClientPoolArg>,
421425
kaspa_addr: Address,
422426
utxos: &mut [(TransactionOutpoint, UtxoEntry)],
423-
pending: &mut HashMap<TransactionOutpoint, u64>,
427+
pending: &mut HashMap<TransactionOutpoint, Instant>,
424428
schnorr_key: Keypair,
425429
stats: Arc<Mutex<Stats>>,
426430
maximize_inputs: bool,
@@ -443,7 +447,7 @@ async fn maybe_send_tx(
443447
// have funds in this tick
444448
has_fund = true;
445449

446-
let now = unix_now();
450+
let now = Instant::now();
447451
for input in selected_utxos.iter() {
448452
pending.insert(input.0, now);
449453
}
@@ -486,12 +490,9 @@ async fn maybe_send_tx(
486490
true
487491
}
488492

489-
fn clean_old_pending_outpoints(pending: &mut HashMap<TransactionOutpoint, u64>) {
490-
let now = unix_now();
491-
let old_keys = pending.iter().filter(|(_, time)| now - *time > 3600 * 1000).map(|(op, _)| *op).collect_vec();
492-
for key in old_keys {
493-
pending.remove(&key).unwrap();
494-
}
493+
fn clean_old_pending_outpoints(pending: &mut HashMap<TransactionOutpoint, Instant>) {
494+
let now = Instant::now();
495+
pending.retain(|_, &mut time| now.duration_since(time) <= Duration::from_secs(3600));
495496
}
496497

497498
fn required_fee(num_utxos: usize, num_outs: u64) -> u64 {

0 commit comments

Comments
 (0)