-
Notifications
You must be signed in to change notification settings - Fork 23
/
schema.rs
303 lines (259 loc) · 9.68 KB
/
schema.rs
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
use std::fmt;
use byteorder::{BigEndian, ByteOrder};
use serde_json::value::from_value;
use exonum::blockchain::{Schema, StoredConfiguration};
use exonum::storage::{ListTable, MerkleTable, List, MapTable, View, Map, Error as StorageError};
use exonum::crypto::{PublicKey, Hash};
use exonum::messages::{RawTransaction, Message, FromRaw, Error as MessageError};
use bitcoin::util::base58::ToBase58;
use btc;
use btc::TxId;
use transactions::{AnchoringTx, BitcoinTx};
use service::config::AnchoringConfig;
#[doc(hidden)]
pub const ANCHORING_SERVICE: u16 = 3;
const ANCHORING_MESSAGE_SIGNATURE: u16 = 0;
const ANCHORING_MESSAGE_LATEST: u16 = 1;
message! {
MsgAnchoringSignature {
const TYPE = ANCHORING_SERVICE;
const ID = ANCHORING_MESSAGE_SIGNATURE;
const SIZE = 56;
from: &PublicKey [00 => 32]
validator: u32 [32 => 36]
tx: AnchoringTx [36 => 44]
input: u32 [44 => 48]
signature: &[u8] [48 => 56]
}
}
message! {
MsgAnchoringUpdateLatest {
const TYPE = ANCHORING_SERVICE;
const ID = ANCHORING_MESSAGE_LATEST;
const SIZE = 52;
from: &PublicKey [00 => 32]
validator: u32 [32 => 36]
tx: BitcoinTx [36 => 44]
lect_count: u64 [44 => 52]
}
}
#[doc(hidden)]
#[derive(Clone)]
pub enum AnchoringMessage {
Signature(MsgAnchoringSignature),
UpdateLatest(MsgAnchoringUpdateLatest),
}
#[doc(hidden)]
pub struct AnchoringSchema<'a> {
view: &'a View,
}
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq)]
pub struct FollowingConfig {
pub actual_from: u64,
pub config: AnchoringConfig,
}
impl Into<AnchoringMessage> for MsgAnchoringSignature {
fn into(self) -> AnchoringMessage {
AnchoringMessage::Signature(self)
}
}
impl Into<AnchoringMessage> for MsgAnchoringUpdateLatest {
fn into(self) -> AnchoringMessage {
AnchoringMessage::UpdateLatest(self)
}
}
impl AnchoringMessage {
pub fn from(&self) -> &PublicKey {
match *self {
AnchoringMessage::UpdateLatest(ref msg) => msg.from(),
AnchoringMessage::Signature(ref msg) => msg.from(),
}
}
}
impl Message for AnchoringMessage {
fn raw(&self) -> &RawTransaction {
match *self {
AnchoringMessage::UpdateLatest(ref msg) => msg.raw(),
AnchoringMessage::Signature(ref msg) => msg.raw(),
}
}
fn verify_signature(&self, public_key: &PublicKey) -> bool {
match *self {
AnchoringMessage::UpdateLatest(ref msg) => msg.verify_signature(public_key),
AnchoringMessage::Signature(ref msg) => msg.verify_signature(public_key),
}
}
fn hash(&self) -> Hash {
match *self {
AnchoringMessage::UpdateLatest(ref msg) => Message::hash(msg),
AnchoringMessage::Signature(ref msg) => Message::hash(msg),
}
}
}
impl FromRaw for AnchoringMessage {
fn from_raw(raw: RawTransaction) -> ::std::result::Result<AnchoringMessage, MessageError> {
match raw.message_type() {
ANCHORING_MESSAGE_SIGNATURE => {
Ok(AnchoringMessage::Signature(MsgAnchoringSignature::from_raw(raw)?))
}
ANCHORING_MESSAGE_LATEST => {
Ok(AnchoringMessage::UpdateLatest(MsgAnchoringUpdateLatest::from_raw(raw)?))
}
_ => Err(MessageError::IncorrectMessageType { message_type: raw.message_type() }),
}
}
}
impl fmt::Debug for AnchoringMessage {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
AnchoringMessage::UpdateLatest(ref msg) => write!(fmt, "{:?}", msg),
AnchoringMessage::Signature(ref msg) => write!(fmt, "{:?}", msg),
}
}
}
impl<'a> AnchoringSchema<'a> {
pub fn new(view: &'a View) -> AnchoringSchema {
AnchoringSchema { view: view }
}
pub fn signatures(&self,
txid: &TxId)
-> ListTable<MapTable<View, [u8], Vec<u8>>, u64, MsgAnchoringSignature> {
let prefix = [&[ANCHORING_SERVICE as u8, 2], txid.as_ref()].concat();
ListTable::new(MapTable::new(prefix, self.view))
}
pub fn lects(&self,
validator: u32)
-> MerkleTable<MapTable<View, [u8], Vec<u8>>, u64, BitcoinTx> {
let mut prefix = vec![ANCHORING_SERVICE as u8, 3, 0, 0, 0, 0, 0, 0, 0, 0];
BigEndian::write_u32(&mut prefix[2..], validator);
MerkleTable::new(MapTable::new(prefix, self.view))
}
pub fn lect_indexes(&self, validator: u32) -> MapTable<View, TxId, u64> {
let mut prefix = vec![ANCHORING_SERVICE as u8, 4, 0, 0, 0, 0, 0, 0, 0, 0];
BigEndian::write_u32(&mut prefix[2..], validator);
MapTable::new(prefix, self.view)
}
// List of known anchoring addresses
pub fn known_addresses(&self) -> MapTable<View, str, Vec<u8>> {
let prefix = vec![ANCHORING_SERVICE as u8, 5];
MapTable::new(prefix, self.view)
}
pub fn current_anchoring_config(&self) -> Result<AnchoringConfig, StorageError> {
let actual = Schema::new(self.view).get_actual_configuration()?;
Ok(self.parse_config(&actual))
}
pub fn following_anchoring_config(&self) -> Result<Option<FollowingConfig>, StorageError> {
let schema = Schema::new(self.view);
if let Some(stored) = schema.get_following_configuration()? {
let following_cfg = FollowingConfig {
actual_from: stored.actual_from,
config: self.parse_config(&stored),
};
Ok(Some(following_cfg))
} else {
Ok(None)
}
}
pub fn create_genesis_config(&self, cfg: &AnchoringConfig) -> Result<(), StorageError> {
let (_, addr) = cfg.redeem_script();
self.add_known_address(&addr)?;
for idx in 0..cfg.validators.len() {
self.add_lect(idx as u32, cfg.funding_tx.clone())?;
}
Ok(())
}
pub fn add_lect<Tx>(&self, validator: u32, tx: Tx) -> Result<(), StorageError>
where Tx: Into<BitcoinTx>
{
let lects = self.lects(validator);
let tx = tx.into();
let idx = lects.len()?;
let txid = tx.id();
lects.append(tx)?;
self.lect_indexes(validator).put(&txid, idx)
}
pub fn lect(&self, validator: u32) -> Result<BitcoinTx, StorageError> {
self.lects(validator).last().map(|x| x.unwrap())
}
pub fn prev_lect(&self, validator: u32) -> Result<Option<BitcoinTx>, StorageError> {
let lects = self.lects(validator);
let idx = lects.len()?;
if idx > 1 {
lects.get(idx - 2)
} else {
Ok(None)
}
}
pub fn find_lect_position(&self,
validator: u32,
txid: &TxId)
-> Result<Option<u64>, StorageError> {
self.lect_indexes(validator).get(txid)
}
pub fn add_known_address(&self, addr: &btc::Address) -> Result<(), StorageError> {
self.known_addresses().put(&addr.to_base58check(), vec![])
}
pub fn is_address_known(&self, addr: &btc::Address) -> Result<bool, StorageError> {
self.known_addresses().get(&addr.to_base58check()).map(|x| x.is_some())
}
pub fn state_hash(&self) -> Result<Vec<Hash>, StorageError> {
let cfg = Schema::new(self.view).get_actual_configuration()?;
let service_id = ANCHORING_SERVICE.to_string();
if let Some(cfg) = cfg.services.get(&service_id) {
let cfg: AnchoringConfig =
from_value(cfg.clone()).expect("Valid configuration expected");
let mut lect_hashes = Vec::new();
for id in 0..cfg.validators.len() as u32 {
lect_hashes.push(self.lects(id).root_hash()?);
}
Ok(lect_hashes)
} else {
Ok(Vec::new())
}
}
fn parse_config(&self, cfg: &StoredConfiguration) -> AnchoringConfig {
let service_id = ANCHORING_SERVICE.to_string();
from_value(cfg.services[&service_id].clone()).unwrap()
}
}
impl MsgAnchoringSignature {
pub fn execute(&self, view: &View) -> Result<(), StorageError> {
let schema = AnchoringSchema::new(view);
let tx = self.tx();
let id = self.validator();
let cfg = schema.current_anchoring_config()?;
// Verify signature
if let Some(pub_key) = cfg.validators.get(id as usize) {
let (redeem_script, _) = cfg.redeem_script();
if tx.input.len() as u32 <= self.input() {
error!("Received msg with incorrect signature content={:#?}", self);
return Ok(());
}
if !tx.verify(&redeem_script, self.input(), pub_key, self.signature()) {
error!("Received msg with incorrect signature content={:#?}", self);
return Ok(());
}
schema.signatures(&tx.id()).append(self.clone())
} else {
Ok(())
}
}
}
impl MsgAnchoringUpdateLatest {
pub fn execute(&self, view: &View) -> Result<(), StorageError> {
let schema = AnchoringSchema::new(view);
let tx = self.tx();
let id = self.validator();
// Verify lect with actual cfg
let actual_cfg = Schema::new(view).get_actual_configuration()?;
if actual_cfg.validators.get(id as usize) != Some(self.from()) {
error!("Received weird lect msg={:#?}", self);
return Ok(());
}
if schema.lects(id).len()? != self.lect_count() {
return Ok(());
}
schema.add_lect(id, tx)
}
}