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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// Copyright 2018 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use exonum::blockchain::Service;

use exonum::helpers::fabric::{
    self, keys, Argument, Command, CommandExtension, CommandName, Context, ServiceFactory,
};
use exonum::node::NodeConfig;

use bitcoin::network::constants::Network;
use failure::{ensure, format_err};
use log::info;
use toml;

use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use std::sync::{Arc, RwLock};

use crate::btc::{gen_keypair, PrivateKey, PublicKey};
use crate::config::{Config, GlobalConfig, LocalConfig};
use crate::rpc::{BitcoinRpcClient, BitcoinRpcConfig, BtcRelay};
use crate::{BtcAnchoringService, BTC_ANCHORING_SERVICE_NAME};

use self::args::{Hash, NamedArgumentOptional, NamedArgumentRequired, TypedArgument};

mod args;

const BTC_ANCHORING_NETWORK: NamedArgumentRequired<Network> = NamedArgumentRequired {
    name: "btc_anchoring_network",
    short_key: Some("n"),
    long_key: "btc-anchoring-network",
    help: "BTC Anchoring network type.",
    default: None,
};

const BTC_ANCHORING_INTERVAL: NamedArgumentRequired<u64> = NamedArgumentRequired {
    name: "btc_anchoring_interval",
    short_key: None,
    long_key: "btc-anchoring-interval",
    help: "Interval in blocks between anchored blocks.",
    default: Some(5000),
};

const BTC_ANCHORING_FEE: NamedArgumentRequired<u64> = NamedArgumentRequired {
    name: "btc_anchoring_fee",
    short_key: None,
    long_key: "btc-anchoring-fee",
    help: "Transaction fee per byte in satoshi that anchoring nodes should use.",
    default: Some(100),
};

const BTC_ANCHORING_UTXO_CONFIRMATIONS: NamedArgumentRequired<u64> = NamedArgumentRequired {
    name: "btc_anchoring_utxo_confirmations",
    short_key: None,
    long_key: "btc-anchoring-utxo-confirmations",
    help: "The minimum number of confirmations for the first funding transactions.",
    default: Some(2),
};

struct GenerateCommonConfig;

impl CommandExtension for GenerateCommonConfig {
    fn args(&self) -> Vec<Argument> {
        vec![
            BTC_ANCHORING_NETWORK.to_argument(),
            BTC_ANCHORING_INTERVAL.to_argument(),
            BTC_ANCHORING_FEE.to_argument(),
            BTC_ANCHORING_UTXO_CONFIRMATIONS.to_argument(),
        ]
    }

    fn execute(&self, mut context: Context) -> Result<Context, failure::Error> {
        let mut values: BTreeMap<String, toml::Value> = context
            .get(keys::SERVICES_CONFIG)
            .expect("Expected services_config in context.");

        values.extend(
            vec![
                BTC_ANCHORING_NETWORK.input_value_to_toml(&context)?,
                BTC_ANCHORING_INTERVAL.input_value_to_toml(&context)?,
                BTC_ANCHORING_FEE.input_value_to_toml(&context)?,
                BTC_ANCHORING_UTXO_CONFIRMATIONS.input_value_to_toml(&context)?,
            ]
            .into_iter(),
        );

        context.set(keys::SERVICES_CONFIG, values);
        Ok(context)
    }
}

struct GenerateNodeConfig;

const BTC_ANCHORING_RPC_HOST: NamedArgumentRequired<String> = NamedArgumentRequired {
    name: "btc_anchoring_rpc_host",
    short_key: None,
    long_key: "btc-anchoring-rpc-host",
    help: "Host of bitcoind.",
    default: None,
};

const BTC_ANCHORING_RPC_USERNAME: NamedArgumentOptional<String> = NamedArgumentOptional {
    name: "btc_anchoring_rpc_user",
    short_key: None,
    long_key: "btc-anchoring-rpc-user",
    help: "User to login into bitcoind.",
    default: None,
};

const BTC_ANCHORING_RPC_PASSWORD: NamedArgumentOptional<String> = NamedArgumentOptional {
    name: "btc_anchoring_rpc_password",
    short_key: None,
    long_key: "btc-anchoring-rpc-password",
    help: "Password to login into bitcoind.",
    default: None,
};

impl CommandExtension for GenerateNodeConfig {
    fn args(&self) -> Vec<Argument> {
        vec![
            BTC_ANCHORING_RPC_HOST.to_argument(),
            BTC_ANCHORING_RPC_USERNAME.to_argument(),
            BTC_ANCHORING_RPC_PASSWORD.to_argument(),
        ]
    }

    fn execute(&self, mut context: Context) -> Result<Context, failure::Error> {
        let mut services_secret_config: BTreeMap<String, toml::Value> = context
            .get(keys::SERVICES_SECRET_CONFIGS)
            .unwrap_or_default();
        let mut services_public_config: BTreeMap<String, toml::Value> = context
            .get(keys::SERVICES_PUBLIC_CONFIGS)
            .unwrap_or_default();
        let common_config = context.get(keys::COMMON_CONFIG).unwrap_or_default();

        // Inserts Bitcoin keypair.
        let network = BTC_ANCHORING_NETWORK.output_value(&common_config.services_config)?;
        let keypair = gen_keypair(network);

        services_public_config.insert(
            "btc_anchoring_public_key".to_owned(),
            toml::Value::try_from(keypair.0)?,
        );
        services_secret_config.extend(
            vec![
                (
                    "btc_anchoring_public_key".to_owned(),
                    toml::Value::try_from(keypair.0)?,
                ),
                (
                    "btc_anchoring_private_key".to_owned(),
                    toml::Value::try_from(keypair.1)?,
                ),
            ]
            .into_iter(),
        );

        // Inserts RPC host.
        let host = BTC_ANCHORING_RPC_HOST.input_value(&context)?;
        let rpc_config = BitcoinRpcConfig {
            host,
            username: BTC_ANCHORING_RPC_USERNAME.input_value(&context)?,
            password: BTC_ANCHORING_RPC_PASSWORD.input_value(&context)?,
        };
        services_secret_config.insert(
            "btc_anchoring_rpc_config".to_owned(),
            toml::Value::try_from(rpc_config)?,
        );
        // Pushes changes to the context.
        context.set(keys::SERVICES_SECRET_CONFIGS, services_secret_config);
        context.set(keys::SERVICES_PUBLIC_CONFIGS, services_public_config);
        Ok(context)
    }
}

struct Finalize;

const BTC_ANCHORING_CREATE_FUNDING_TX: NamedArgumentOptional<u64> = NamedArgumentOptional {
    name: "btc_anchoring_create_funding_tx",
    short_key: None,
    long_key: "btc-anchoring-create-funding-tx",
    help: "Create initial funding tx with given amount in satoshis",
    default: None,
};

const BTC_ANCHORING_FUNDING_TXID: NamedArgumentOptional<Hash> = NamedArgumentOptional {
    name: "btc_anchoring_funding_txid",
    short_key: None,
    long_key: "btc-anchoring-funding-txid",
    help: "Identifier of the initial funding transaction which was created earlier",
    default: None,
};

impl CommandExtension for Finalize {
    fn args(&self) -> Vec<Argument> {
        vec![
            BTC_ANCHORING_CREATE_FUNDING_TX.to_argument(),
            BTC_ANCHORING_FUNDING_TXID.to_argument(),
        ]
    }

    fn execute(&self, mut context: Context) -> Result<Context, failure::Error> {
        let mut node_config: NodeConfig<PathBuf> = context.get(keys::NODE_CONFIG)?;
        let public_config_list = context.get(keys::PUBLIC_CONFIG_LIST)?;
        let services_secret_config: BTreeMap<String, toml::Value> = context
            .get(keys::SERVICES_SECRET_CONFIGS)
            .unwrap_or_default();
        let common_config = context.get(keys::COMMON_CONFIG)?;

        // Public part.
        let network = BTC_ANCHORING_NETWORK.output_value(&common_config.services_config)?;
        let interval = BTC_ANCHORING_INTERVAL.output_value(&common_config.services_config)?;
        let fee = BTC_ANCHORING_FEE.output_value(&common_config.services_config)?;
        let confirmations =
            BTC_ANCHORING_UTXO_CONFIRMATIONS.output_value(&common_config.services_config)?;

        // Private part.
        let private_key: PrivateKey = services_secret_config
            .get("btc_anchoring_private_key")
            .ok_or_else(|| format_err!("BTC private key not found"))?
            .clone()
            .try_into()?;
        let rpc_config: BitcoinRpcConfig = services_secret_config
            .get("btc_anchoring_rpc_config")
            .ok_or_else(|| format_err!("Bitcoin RPC configuration not found"))?
            .clone()
            .try_into()?;

        // Finalize part.
        let funding_tx_amount = BTC_ANCHORING_CREATE_FUNDING_TX.input_value(&context)?;
        let funding_txid = BTC_ANCHORING_FUNDING_TXID
            .input_value(&context)?
            .map(|x| x.0);

        // Gets anchoring public keys.
        let public_keys = {
            let mut public_keys = Vec::new();
            for public_config in public_config_list {
                let public_key: PublicKey = public_config
                    .services_public_configs()
                    .get("btc_anchoring_public_key")
                    .ok_or_else(|| format_err!("BTC public key not found"))?
                    .clone()
                    .try_into()?;
                public_keys.push(public_key);
            }
            public_keys
        };

        // Creates global configuration.
        let mut global_config = GlobalConfig::with_public_keys(network, public_keys)?;
        // Generates initial funding transaction.
        let relay = BitcoinRpcClient::from(rpc_config.clone());
        let addr = global_config.anchoring_address();
        let funding_tx = if let Some(funding_txid) = funding_txid {
            let info = relay.transaction_info(&funding_txid)?.ok_or_else(|| {
                format_err!(
                    "Unable to find transaction with the given id {}",
                    funding_txid.to_hex()
                )
            })?;
            ensure!(
                info.confirmations >= confirmations,
                "Not enough confirmations to use funding transaction, actual {}, expected {}",
                info.confirmations,
                confirmations
            );
            info.content
        } else {
            let satoshis = funding_tx_amount
                .ok_or_else(|| format_err!("Expected `btc_anchoring_create_funding_tx` value"))?;
            let transaction = relay.send_to_address(&addr.0, satoshis)?;
            println!("{}", transaction.id().to_hex());
            transaction
        };

        info!("BTC anchoring address is {}", addr);

        global_config.funding_transaction = Some(funding_tx);
        global_config.anchoring_interval = interval;
        global_config.transaction_fee = fee;

        // Creates local configuration.
        let mut private_keys = HashMap::new();
        private_keys.insert(addr, private_key);

        let local_config = LocalConfig {
            rpc: Some(rpc_config),
            private_keys,
        };

        // Writes complete configuration to node_config.
        let config = Config {
            local: local_config,
            global: global_config,
        };
        node_config.services_configs.insert(
            BTC_ANCHORING_SERVICE_NAME.to_owned(),
            toml::Value::try_from(config)?,
        );
        context.set(keys::NODE_CONFIG, node_config);
        Ok(context)
    }
}

/// A BTC anchoring service creator for the `NodeBuilder`.
#[derive(Debug, Copy, Clone)]
pub struct BtcAnchoringFactory;

impl ServiceFactory for BtcAnchoringFactory {
    fn service_name(&self) -> &str {
        "btc_anchoring"
    }

    fn command(&mut self, command: CommandName) -> Option<Box<dyn CommandExtension>> {
        Some(match command {
            v if v == fabric::GenerateCommonConfig.name() => Box::new(GenerateCommonConfig),
            v if v == fabric::GenerateNodeConfig.name() => Box::new(GenerateNodeConfig),
            v if v == fabric::Finalize.name() => Box::new(Finalize),
            _ => return None,
        })
    }

    fn make_service(&mut self, context: &Context) -> Box<dyn Service> {
        let node_config = context.get(keys::NODE_CONFIG).unwrap();
        let btc_anchoring_config: Config = node_config
            .services_configs
            .get(BTC_ANCHORING_SERVICE_NAME)
            .expect("BTC anchoring config not found")
            .clone()
            .try_into()
            .unwrap();

        let btc_relay = btc_anchoring_config
            .local
            .rpc
            .map(BitcoinRpcClient::from)
            .map(Box::<dyn BtcRelay>::from);
        let service = BtcAnchoringService::new(
            btc_anchoring_config.global,
            Arc::new(RwLock::new(btc_anchoring_config.local.private_keys)),
            btc_relay,
        );
        Box::new(service)
    }
}