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
// Copyright 2017 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 std::collections::hash_map::{Entry, HashMap};

use byteorder::{BigEndian, ByteOrder};
use serde_json::value::from_value;

use exonum::blockchain::{gen_prefix, Schema, StoredConfiguration};
use exonum::storage::{Fork, ListIndex, MapIndex, ProofListIndex, Snapshot, StorageKey};
use exonum::crypto::Hash;
use exonum::helpers::{Height, ValidatorId};

use blockchain::consensus_storage::AnchoringConfig;
use blockchain::dto::{LectContent, MsgAnchoringSignature};
use details::btc;
use details::btc::transactions::{AnchoringTx, BitcoinTx};
use service::ANCHORING_SERVICE_NAME;
use super::Error as ValidateError;

/// Unique identifier of signature for the `AnchoringTx`.
#[derive(Debug, Clone)]
pub struct KnownSignatureId {
    /// Normalized txid of the `AnchoringTx`.
    pub txid: btc::TxId,
    /// Identifier of the anchoring node in the current configuration.
    pub validator_id: ValidatorId,
    /// Transaction input for the signature.
    pub input: u32,
}

impl StorageKey for KnownSignatureId {
    fn size(&self) -> usize {
        self.txid.size() + 6
    }

    fn write(&self, buffer: &mut [u8]) {
        buffer[0..32].copy_from_slice(self.txid.as_bytes());
        BigEndian::write_u16(&mut buffer[32..34], self.validator_id.0);
        BigEndian::write_u32(&mut buffer[34..38], self.input);
    }

    fn read(buffer: &[u8]) -> Self {
        let txid = btc::TxId::read(&buffer[0..32]);
        let validator_id = ValidatorId(u16::read(&buffer[32..34]));
        let input = u32::read(&buffer[34..38]);
        KnownSignatureId {
            txid,
            validator_id,
            input,
        }
    }
}

impl<'a> From<&'a MsgAnchoringSignature> for KnownSignatureId {
    fn from(msg: &'a MsgAnchoringSignature) -> KnownSignatureId {
        KnownSignatureId {
            txid: msg.tx().id(),
            validator_id: msg.validator(),
            input: msg.input(),
        }
    }
}

/// Anchoring information schema.
#[derive(Debug)]
pub struct AnchoringSchema<T> {
    view: T,
}

impl<T> AnchoringSchema<T>
where
    T: AsRef<Snapshot>,
{
    /// Creates anchoring schema for the given `snapshot`.
    pub fn new(snapshot: T) -> AnchoringSchema<T> {
        AnchoringSchema { view: snapshot }
    }

    /// Returns table that contains signatures for the anchoring transaction with
    /// the given normalized `txid`.
    pub fn signatures(&self, txid: &btc::TxId) -> ListIndex<&T, MsgAnchoringSignature> {
        ListIndex::with_prefix("btc_anchoring.signatures", gen_prefix(txid), &self.view)
    }

    /// Returns table that saves a list of lects for the validator with the given `validator_key`.
    pub fn lects(&self, validator_key: &btc::PublicKey) -> ProofListIndex<&T, LectContent> {
        ProofListIndex::with_prefix("btc_anchoring.lects", gen_prefix(validator_key), &self.view)
    }

    /// Returns table that keeps the lect index for every anchoring txid for the validator
    /// with given `validator_key`.
    pub fn lect_indexes(&self, validator_key: &btc::PublicKey) -> MapIndex<&T, btc::TxId, u64> {
        MapIndex::with_prefix(
            "btc_anchoring.lect_indexes",
            gen_prefix(validator_key),
            &self.view,
        )
    }

    /// Returns the table of known signatures, where key is the tuple `(txid, validator_id, input)`.
    ///
    /// [Read more](struct.KnownSignatureId.html).
    pub fn known_signatures(&self) -> MapIndex<&T, KnownSignatureId, MsgAnchoringSignature> {
        MapIndex::new("btc_anchoring.known_signatures", &self.view)
    }

    /// Returns the table that keeps the anchoring transaction for any known txid.
    pub fn known_txs(&self) -> MapIndex<&T, btc::TxId, BitcoinTx> {
        MapIndex::new("btc_anchoring.known_txs", &self.view)
    }

    /// Returns table that maps anchoring transactions to their heights.
    pub fn anchoring_tx_chain(&self) -> MapIndex<&T, u64, AnchoringTx> {
        MapIndex::new("btc_anchoring.tx_chain", &self.view)
    }

    /// Returns the actual anchoring configuration.
    pub fn actual_anchoring_config(&self) -> AnchoringConfig {
        let schema = Schema::new(&self.view);
        let actual = schema.actual_configuration();
        self.parse_config(&actual)
    }

    /// Returns the nearest following configuration if it exists.
    pub fn following_anchoring_config(&self) -> Option<AnchoringConfig> {
        let schema = Schema::new(&self.view);
        if let Some(stored) = schema.following_configuration() {
            Some(self.parse_config(&stored))
        } else {
            None
        }
    }

    /// Returns the previous anchoring configuration if it exists.
    pub fn previous_anchoring_config(&self) -> Option<AnchoringConfig> {
        let schema = Schema::new(&self.view);
        if let Some(stored) = schema.previous_configuration() {
            Some(self.parse_config(&stored))
        } else {
            None
        }
    }

    /// Returns the anchoring configuration from the genesis block.
    pub fn genesis_anchoring_config(&self) -> AnchoringConfig {
        self.anchoring_config_by_height(Height::zero())
    }

    /// Returns the configuration that is the actual for the given `height`.
    /// For non-existent heights, it will return the configuration closest to them.
    pub fn anchoring_config_by_height(&self, height: Height) -> AnchoringConfig {
        let schema = Schema::new(&self.view);
        let stored = schema.configuration_by_height(height);
        self.parse_config(&stored)
    }

    /// Returns `lect` for validator with the given `public_key`.
    pub fn lect(&self, validator_key: &btc::PublicKey) -> Option<BitcoinTx> {
        self.lects(validator_key).last().map(|x| x.tx())
    }

    /// Returns previous `lect` for validator with the given `public_key`.
    pub fn prev_lect(&self, validator_key: &btc::PublicKey) -> Option<BitcoinTx> {
        let lects = self.lects(validator_key);

        let idx = lects.len();
        if idx > 1 {
            lects.get(idx - 2).map(|content| content.tx())
        } else {
            None
        }
    }

    /// Returns a lect that is currently supported by at least 2/3 of the current set of validators.
    pub fn collect_lects(&self, cfg: &AnchoringConfig) -> Option<BitcoinTx> {
        let mut lects = HashMap::new();
        for anchoring_key in &cfg.anchoring_keys {
            if let Some(last_lect) = self.lect(anchoring_key) {
                match lects.entry(last_lect.0) {
                    Entry::Occupied(mut v) => {
                        *v.get_mut() += 1;
                    }
                    Entry::Vacant(v) => {
                        v.insert(1);
                    }
                }
            }
        }

        if let Some((lect, count)) = lects.iter().max_by_key(|&(_, v)| v) {
            if *count >= cfg.majority_count() {
                Some(BitcoinTx::from(lect.clone()))
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Returns position in `lects` table of validator with the given `anchoring_key`
    /// for transaction with the given `txid`.
    pub fn find_lect_position(
        &self,
        anchoring_key: &btc::PublicKey,
        txid: &btc::TxId,
    ) -> Option<u64> {
        self.lect_indexes(anchoring_key).get(txid)
    }

    /// Returns the `state_hash` for anchoring tables.
    ///
    /// It contains a list of `root_hash` of the actual `lects` tables.
    pub fn state_hash(&self) -> Vec<Hash> {
        let cfg = self.actual_anchoring_config();
        let mut lect_hashes = Vec::new();
        for key in &cfg.anchoring_keys {
            lect_hashes.push(self.lects(key).root_hash());
        }
        lect_hashes
    }

    fn parse_config(&self, cfg: &StoredConfiguration) -> AnchoringConfig {
        from_value(cfg.services[ANCHORING_SERVICE_NAME].clone())
            .expect("Anchoring config does not exist")
    }
}

impl<'a> AnchoringSchema<&'a mut Fork> {
    /// Mutable variant of the [`signatures`][1] index.
    ///
    /// [1]: struct.AnchoringSchema.html#method.signatures
    pub fn signatures_mut(
        &mut self,
        txid: &btc::TxId,
    ) -> ListIndex<&mut Fork, MsgAnchoringSignature> {
        ListIndex::with_prefix("btc_anchoring.signatures", gen_prefix(txid), &mut self.view)
    }

    /// Mutable variant of the [`lects`][1] index.
    ///
    /// [1]: struct.AnchoringSchema.html#method.lects
    pub fn lects_mut(
        &mut self,
        validator_key: &btc::PublicKey,
    ) -> ProofListIndex<&mut Fork, LectContent> {
        ProofListIndex::with_prefix(
            "btc_anchoring.lects",
            gen_prefix(validator_key),
            &mut self.view,
        )
    }

    /// Mutable variant of the [`lect_indexes`][1] index.
    ///
    /// [1]: struct.AnchoringSchema.html#method.lect_indexes
    pub fn lect_indexes_mut(
        &mut self,
        validator_key: &btc::PublicKey,
    ) -> MapIndex<&mut Fork, btc::TxId, u64> {
        MapIndex::with_prefix(
            "btc_anchoring.lect_indexes",
            gen_prefix(validator_key),
            &mut self.view,
        )
    }

    /// Mutable variant of the [`known_signatures`][1] index.
    ///
    /// [1]: struct.AnchoringSchema.html#method.known_signatures
    pub fn known_signatures_mut(
        &mut self,
    ) -> MapIndex<&mut Fork, KnownSignatureId, MsgAnchoringSignature> {
        MapIndex::new("btc_anchoring.known_signatures", &mut self.view)
    }

    /// Mutable variant of the [`known_txs`][1] index.
    ///
    /// [1]: struct.AnchoringSchema.html#method.known_txs
    pub fn known_txs_mut(&mut self) -> MapIndex<&mut Fork, btc::TxId, BitcoinTx> {
        MapIndex::new("btc_anchoring.known_txs", &mut self.view)
    }

    /// Mutable variant of the [`signatures`][1] index.
    ///
    /// [1]: struct.AnchoringSchema.html#method.anchoring_tx_chain
    pub fn anchoring_tx_chain_mut(&mut self) -> MapIndex<&mut Fork, u64, AnchoringTx> {
        MapIndex::new("btc_anchoring.tx_chain", &mut self.view)
    }

    /// Creates and commits the genesis anchoring configuration from the proposed `cfg`.
    pub fn create_genesis_config(&mut self, cfg: &AnchoringConfig) {
        for validator_key in &cfg.anchoring_keys {
            self.add_lect(validator_key, cfg.funding_tx().clone(), Hash::zero());
        }
    }

    /// Adds `lect` from validator with the given `public key`.
    pub fn add_lect<Tx>(&mut self, validator_key: &btc::PublicKey, tx: Tx, msg_hash: Hash)
    where
        Tx: Into<BitcoinTx>,
    {
        let (tx, txid, idx) = {
            let mut lects = self.lects_mut(validator_key);
            let tx = tx.into();
            let idx = lects.len();
            let txid = tx.id();
            lects.push(LectContent::new(&msg_hash, tx.clone()));
            (tx, txid, idx)
        };

        self.known_txs_mut().put(&txid, tx.clone());
        self.lect_indexes_mut(validator_key).put(&txid, idx)
    }

    /// Adds signature to known if it is correct.
    pub fn add_known_signature(&mut self, msg: MsgAnchoringSignature) -> Result<(), ValidateError> {
        let ntxid = msg.tx().nid();
        let signature_id = KnownSignatureId::from(&msg);
        if self.known_signatures().get(&signature_id).is_some() {
            Err(ValidateError::SignatureDifferent)
        } else {
            self.signatures_mut(&ntxid).push(msg.clone());
            self.known_signatures_mut().put(&signature_id, msg);
            Ok(())
        }
    }
}

impl<T> AnchoringSchema<T> {
    /// Converts schema back into snapshot.
    pub fn into_snapshot(self) -> T {
        self.view
    }
}