summaryrefslogtreecommitdiff
path: root/btc-wire/src/main.rs
blob: 2d7829400a94e307bbf3eaae63c9c15048de4902 (plain)
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
/*
  This file is part of TALER
  Copyright (C) 2022 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free Software
  Foundation; either version 3, or (at your option) any later version.

  TALER is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License along with
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
use bitcoin::{Amount as BtcAmount, Network};
use btc_wire::{
    config::{BitcoinConfig, WIRE_WALLET_NAME},
    config_bounce_fee,
    rpc::{self, auto_rpc_common, auto_rpc_wallet, ErrorCode, Rpc},
    rpc_utils::default_data_dir,
};
use clap::StructOpt;
use common::{
    config::{load_btc_config, BtcConfig, Config, CoreConfig},
    log::log::info,
    named_spawn, password,
    postgres::{Client, NoTls},
    reconnect::auto_reconnect_db,
};
use std::{path::PathBuf, sync::atomic::AtomicU16};

use crate::loops::{analysis::analysis, watcher::watcher, worker::worker};

mod fail_point;
mod loops;
mod sql;

const DEFAULT_CONFIRMATION: u16 = 6;
pub struct WireState {
    confirmation: AtomicU16,
    max_confirmation: u16,
    config: BtcConfig,
    bounce_fee: BtcAmount,
}

/// Taler wire for bitcoincore
#[derive(clap::Parser, Debug)]
struct Args {
    /// Override default configuration file path
    #[clap(global = true, short, long)]
    config: Option<PathBuf>,
    #[clap(subcommand)]
    init: Option<Init>,
}

#[derive(clap::Subcommand, Debug)]
enum Init {
    /// Initialize database schema and state
    Initdb,
    /// Generate bitcoin wallet and initialize state
    Initwallet,
}

/// TODO support external signer https://github.com/bitcoin/bitcoin/blob/master/doc/external-signer.md

fn main() {
    common::log::init();
    let args = Args::parse();

    match args.init {
        Some(cmd) => init(args.config, cmd),
        None => run(args.config),
    }
}

fn init(config: Option<PathBuf>, init: Init) {
    // Parse taler config
    let config = CoreConfig::load_taler_config(config.as_deref(), Some("BTC"));
    // Connect to database
    let mut db = Client::connect(&config.db_url, NoTls).expect("Failed to connect to database");
    // Parse bitcoin config
    let btc_conf = BitcoinConfig::load(config.data_dir.unwrap_or_else(default_data_dir))
        .expect("Failed to load bitcoin configuration");
    // Connect to bitcoin node
    let mut rpc = Rpc::common(&btc_conf).expect("Failed to connect to bitcoin RPC server");
    match init {
        Init::Initdb => {
            // Load schema
            db.batch_execute(include_str!("../../db/btc.sql"))
                .expect("Failed to load database schema");
            // Init status to true
            db
                .execute(
                    "INSERT INTO state (name, value) VALUES ('status', $1) ON CONFLICT (name) DO NOTHING",
                    &[&[1u8].as_ref()],
                )
                .expect("Failed to initialise database state");
            // Init last_hash if not already set
            let genesis_hash = rpc.get_genesis().expect("Failed to get genesis hash");
            db
                        .execute(
                            "INSERT INTO state (name, value) VALUES ('last_hash', $1) ON CONFLICT (name) DO NOTHING",
                            &[&genesis_hash.as_ref()],
                        )
                        .expect("Failed to update database state");
            println!("Database initialised");
        }
        Init::Initwallet => {
            // Skip past blocks
            let info = rpc
                .get_blockchain_info()
                .expect("Failed to get blockchain info");
            let nb_row = db
                .execute(
                    "INSERT INTO state (name, value) VALUES ('last_hash', $1) ON CONFLICT (name) DO NOTHING",
                    &[&info.best_block_hash.as_ref()],
                )
                .expect("Failed to update database state");
            if nb_row > 0 {
                println!("Skip previous block until now");
            }

            // Create wallet
            let passwd = password();
            let created = match rpc.create_wallet(WIRE_WALLET_NAME, &passwd) {
                Err(rpc::Error::RPC { code, .. }) if code == ErrorCode::RpcWalletError => false,
                Err(e) => panic!("{}", e),
                Ok(_) => true,
            };

            rpc.load_wallet(WIRE_WALLET_NAME).ok();

            // Load previous address
            let prev_addr = db
                .query_opt("SELECT value FROM state WHERE name = 'addr'", &[])
                .expect("Failed to query database state");
            let addr = if let Some(row) = prev_addr {
                String::from_utf8(row.get(0)).expect("Stored address is not a valid string")
            } else {
                // Or generate a new one
                let new = Rpc::wallet(&btc_conf, WIRE_WALLET_NAME)
                    .expect("Failed to connect to wallet bitcoin RPC server")
                    .gen_addr()
                    .expect("Failed to generate new address")
                    .to_string();
                db.execute(
                    "INSERT INTO state (name, value) VALUES ('addr', $1)",
                    &[&new.as_bytes()],
                )
                .expect("Failed to update database state");
                new
            };

            if created {
                println!("Created new wallet");
            } else {
                println!("Found already existing wallet")
            }
            println!("You must backup the generated key file and your chosen password, more info there: https://github.com/bitcoin/bitcoin/blob/master/doc/managing-wallets.md#14-backing-up-the-wallet");
            println!("Public address is {}", &addr);
            println!("Add the following line into taler.conf:");
            println!("[depolymerizer-bitcoin]");
            println!("PAYTO = payto://bitcoin/{}", addr);
        }
    }
}

fn run(config: Option<PathBuf>) {
    let config = load_btc_config(config.as_deref());
    let data_dir = config
        .core
        .data_dir
        .as_ref()
        .cloned()
        .unwrap_or_else(default_data_dir);
    let btc_config = BitcoinConfig::load(&data_dir).unwrap();

    #[cfg(feature = "fail")]
    if btc_config.network == Network::Regtest {
        common::log::log::warn!("Running with random failures");
    } else {
        common::log::log::error!("Running with random failures is unsuitable for production");
        std::process::exit(1);
    }
    let chain_name = match btc_config.network {
        Network::Bitcoin => "main",
        Network::Testnet => "test",
        Network::Signet => "signet",
        Network::Regtest => "regtest",
    };
    info!("Running on {} chain", chain_name);

    let init_confirmation = config.confirmation.unwrap_or(DEFAULT_CONFIRMATION);
    let state: &'static WireState = Box::leak(Box::new(WireState {
        confirmation: AtomicU16::new(init_confirmation),
        max_confirmation: init_confirmation * 2,
        bounce_fee: config_bounce_fee(&config),
        config,
    }));

    let mut rpc = Rpc::common(&btc_config).unwrap();
    rpc.load_wallet(WIRE_WALLET_NAME).ok();
    let rpc_watcher = auto_rpc_common(btc_config.clone());
    let rpc_analysis = auto_rpc_common(btc_config.clone());
    let rpc_worker = auto_rpc_wallet(btc_config, WIRE_WALLET_NAME);

    let db_watcher = auto_reconnect_db(state.config.core.db_url.clone());
    let db_analysis = auto_reconnect_db(state.config.core.db_url.clone());
    let db_worker = auto_reconnect_db(state.config.core.db_url.clone());
    named_spawn("watcher", move || watcher(rpc_watcher, db_watcher));
    named_spawn("analysis", move || {
        analysis(rpc_analysis, db_analysis, state)
    });
    worker(rpc_worker, db_worker, state);
}