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
// Copyright 2019 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.

//! BTC anchoring configuration data types.

pub use crate::proto::{AnchoringKeys, Config};

use anyhow::ensure;
use bitcoin::network::constants::Network;
use btc_transaction_utils::{
    multisig::{RedeemScript, RedeemScriptBuilder, RedeemScriptError},
    p2wsh,
};
use exonum::{
    crypto::PublicKey,
    helpers::{Height, ValidateInput},
};

use crate::btc::{self, Address};

impl Default for Config {
    fn default() -> Self {
        Self {
            network: Network::Testnet,
            anchoring_keys: vec![],
            anchoring_interval: 5_000,
            transaction_fee: 10,
        }
    }
}

impl Config {
    /// Current limit on the number of keys in a redeem script on the Bitcoin network.
    const MAX_NODES_COUNT: usize = 20;
    /// Minimal fee in satoshis for Bitcoin transaction.
    const MIN_TOTAL_TX_FEE: u64 = 1000;
    /// Minimal total transaction size according to
    /// https://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending-legacy-non-segwit-p2pkh-p2sh     
    const MIN_TX_LEN: u64 = 10 + 146 + 33 + 81;
    /// Minimal enough transaction fee per byte.
    const MIN_TX_FEE: u64 = Self::MIN_TOTAL_TX_FEE / Self::MIN_TX_LEN + 1; // Round up.

    /// Creates Bitcoin anchoring config instance with default parameters for the
    /// given Bitcoin network and public keys of participants.
    pub fn with_public_keys(
        network: Network,
        keys: impl IntoIterator<Item = AnchoringKeys>,
    ) -> Result<Self, RedeemScriptError> {
        let anchoring_keys = keys.into_iter().collect::<Vec<_>>();
        if anchoring_keys.is_empty() {
            return Err(RedeemScriptError::NotEnoughPublicKeys);
        }

        Ok(Self {
            network,
            anchoring_keys,
            ..Self::default()
        })
    }

    /// Tries to find bitcoin public key corresponding with the given service key.
    pub fn find_bitcoin_key(&self, service_key: &PublicKey) -> Option<(u16, btc::PublicKey)> {
        self.anchoring_keys.iter().enumerate().find_map(|(n, x)| {
            if &x.service_key == service_key {
                Some((n as u16, x.bitcoin_key))
            } else {
                None
            }
        })
    }

    /// Returns the corresponding Bitcoin address.
    pub fn anchoring_address(&self) -> Address {
        p2wsh::address(&self.redeem_script(), self.network).into()
    }

    /// Returns the corresponding redeem script.
    pub fn redeem_script(&self) -> RedeemScript {
        RedeemScriptBuilder::with_public_keys(self.anchoring_keys.iter().map(|x| x.bitcoin_key.0))
            .quorum(self.byzantine_quorum())
            .to_script()
            .unwrap()
    }

    /// Computes the P2WSH output corresponding to the actual redeem script.
    pub fn anchoring_out_script(&self) -> bitcoin::Script {
        self.redeem_script().as_ref().to_v0_p2wsh()
    }

    /// Returns the latest height below the given height which must be anchored.
    pub fn previous_anchoring_height(&self, current_height: Height) -> Height {
        Height(current_height.0 - current_height.0 % self.anchoring_interval)
    }

    /// Returns the nearest height above the given height which must be anchored.
    pub fn following_anchoring_height(&self, current_height: Height) -> Height {
        Height(self.previous_anchoring_height(current_height).0 + self.anchoring_interval)
    }

    /// Returns sufficient number of votes for the given anchoring nodes number.
    pub fn byzantine_quorum(&self) -> usize {
        exonum::helpers::byzantine_quorum(self.anchoring_keys.len())
    }
}

impl ValidateInput for Config {
    type Error = anyhow::Error;

    fn validate(&self) -> Result<(), Self::Error> {
        ensure!(
            !self.anchoring_keys.is_empty(),
            "The list of anchoring keys must not be empty."
        );
        ensure!(
            self.anchoring_keys.len() <= Self::MAX_NODES_COUNT,
            "Too many anchoring nodes: amount of anchoring nodes should be less or equal than the {}.",
            Self::MAX_NODES_COUNT
        );
        ensure!(
            self.anchoring_interval > 0,
            "Anchoring interval should be greater than zero."
        );
        ensure!(
            self.transaction_fee >= Self::MIN_TX_FEE,
            "Transaction fee should be greater than {}",
            Self::MIN_TX_FEE
        );

        // Verify that the redeem script is suitable.
        RedeemScriptBuilder::with_public_keys(self.anchoring_keys.iter().map(|x| x.bitcoin_key.0))
            .quorum(self.byzantine_quorum())
            .to_script()?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use exonum::{
        crypto,
        helpers::{Height, ValidateInput},
    };

    use bitcoin::network::constants::Network;
    use btc_transaction_utils::test_data::secp_gen_keypair;

    use crate::proto::AnchoringKeys;

    use super::Config;

    fn gen_anchoring_keys(network: bitcoin::Network, count: usize) -> Vec<AnchoringKeys> {
        (0..count)
            .map(|_| AnchoringKeys {
                bitcoin_key: secp_gen_keypair(network).0.into(),
                service_key: crypto::gen_keypair().0,
            })
            .collect::<Vec<_>>()
    }

    #[test]
    fn config_serde() {
        let public_keys = gen_anchoring_keys(Network::Bitcoin, 4);

        let config = Config::with_public_keys(Network::Bitcoin, public_keys).unwrap();
        assert_eq!(config.redeem_script().content().quorum, 3);

        let json = serde_json::to_value(&config).unwrap();
        let config2: Config = serde_json::from_value(json).unwrap();
        assert_eq!(config2, config);
    }

    #[test]
    fn config_anchoring_height() {
        let public_keys = gen_anchoring_keys(Network::Bitcoin, 4);

        let mut config = Config::with_public_keys(Network::Bitcoin, public_keys).unwrap();
        config.anchoring_interval = 1000;

        assert_eq!(config.previous_anchoring_height(Height(0)), Height(0));
        assert_eq!(config.previous_anchoring_height(Height(999)), Height(0));
        assert_eq!(config.previous_anchoring_height(Height(1000)), Height(1000));
        assert_eq!(config.previous_anchoring_height(Height(1001)), Height(1000));

        assert_eq!(config.following_anchoring_height(Height(0)), Height(1000));
        assert_eq!(config.following_anchoring_height(Height(999)), Height(1000));
        assert_eq!(
            config.following_anchoring_height(Height(1000)),
            Height(2000)
        );
        assert_eq!(
            config.following_anchoring_height(Height(1001)),
            Height(2000)
        );
    }

    // TODO test validation of the Bitcoin anchoring config

    #[test]
    fn config_validate_errors() {
        let test_cases = [
            (
                Config::default(),
                "The list of anchoring keys must not be empty",
            ),
            (
                Config {
                    anchoring_keys: gen_anchoring_keys(bitcoin::Network::Regtest, 30),
                    ..Config::default()
                },
                "Too many anchoring nodes: amount of anchoring nodes should be less or equal",
            ),
            (
                Config {
                    anchoring_keys: gen_anchoring_keys(bitcoin::Network::Regtest, 4),
                    anchoring_interval: 0,
                    ..Config::default()
                },
                "Anchoring interval should be greater than zero",
            ),
            (
                Config {
                    anchoring_keys: gen_anchoring_keys(bitcoin::Network::Regtest, 4),
                    transaction_fee: 0,
                    ..Config::default()
                },
                "Transaction fee should be greater than",
            ),
            (
                Config {
                    anchoring_keys: gen_anchoring_keys(bitcoin::Network::Regtest, 4),
                    transaction_fee: 3,
                    ..Config::default()
                },
                "Transaction fee should be greater than",
            ),
        ];

        for (config, expected_err) in &test_cases {
            let actual_err = config.validate().unwrap_err().to_string();
            assert!(actual_err.contains(expected_err), actual_err);
        }
    }
}