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
|
use std::sync::atomic::Ordering;
use btc_wire::rpc::ChainTipsStatus;
use postgres::fallible_iterator::FallibleIterator;
use taler_common::{
config::Config,
log::log::{error, warn},
};
use crate::{
reconnect::{AutoReconnectRPC, AutoReconnectSql},
WireState,
};
/// Analyse blockchain behavior and adapt confirmations in real time
pub fn analysis(
mut rpc: AutoReconnectRPC,
mut db: AutoReconnectSql,
config: &Config,
state: &WireState,
) {
// The biggest fork ever seen
let mut max_conf = 0;
loop {
let rpc = rpc.client();
let db = db.client();
let result: Result<(), Box<dyn std::error::Error>> = (|| {
// Register as listener
db.batch_execute("LISTEN new_block")?;
loop {
// Get biggest known valid fork
let max_fork = rpc
.get_chain_tips()?
.into_iter()
.filter_map(|t| {
(t.status == ChainTipsStatus::ValidFork).then(|| t.branch_length)
})
.max()
.unwrap_or(0) as u16;
// The first time we see a fork that big
if max_fork > max_conf {
max_conf = max_fork;
let current_conf = state.confirmation.load(Ordering::SeqCst);
// If new fork is bigger than the current confirmation
if max_fork > current_conf {
// Max two time the configuration
let new_conf = max_fork.min(config.confirmation * 2);
state.confirmation.store(new_conf, Ordering::SeqCst);
warn!(
"analysis: found dangerous fork of {} blocks, adapt confirmation to {} blocks capped at {}, you should update taler.conf",
max_fork, new_conf, config.confirmation * 2
);
}
}
// TODO smarter analysis: suspicious transaction value, limit wire bitcoin throughput
// Wait for next notification
db.notifications().blocking_iter().next()?;
}
})();
if let Err(e) = result {
error!("analysis: {}", e);
}
}
}
|