-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
423 lines (391 loc) · 13.7 KB
/
lib.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
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use bitcoin::{
hashes::Hash,
opcodes::{
all::{OP_NOP5, OP_PUSHBYTES_1, OP_RETURN},
OP_TRUE,
},
Amount, Opcode, Script, ScriptBuf, Transaction, TxOut,
};
use byteorder::{BigEndian, ByteOrder};
use nom::{
branch::alt,
bytes::complete::{tag, take},
combinator::{fail, rest},
multi::many0,
IResult,
};
use sha2::{Digest, Sha256};
pub use bitcoin;
pub const OP_DRIVECHAIN: Opcode = OP_NOP5;
pub struct CoinbaseBuilder {
messages: Vec<CoinbaseMessage>,
}
impl CoinbaseBuilder {
pub fn new() -> Self {
CoinbaseBuilder { messages: vec![] }
}
pub fn build(self) -> Vec<TxOut> {
self.messages
.into_iter()
.map(|message| TxOut {
value: Amount::ZERO,
script_pubkey: message.into(),
})
.collect()
}
pub fn propose_sidechain(mut self, sidechain_number: u8, data: &[u8]) -> Self {
let message = CoinbaseMessage::M1ProposeSidechain {
sidechain_number,
data: data.to_vec(),
};
self.messages.push(message);
self
}
pub fn ack_sidechain(mut self, sidechain_number: u8, data_hash: &[u8; 32]) -> Self {
let message = CoinbaseMessage::M2AckSidechain {
sidechain_number,
data_hash: data_hash.clone(),
};
self.messages.push(message);
self
}
pub fn propose_bundle(mut self, sidechain_number: u8, bundle_hash: &[u8; 32]) -> Self {
let message = CoinbaseMessage::M3ProposeBundle {
sidechain_number,
bundle_txid: bundle_hash.clone(),
};
self.messages.push(message);
self
}
pub fn ack_bundles(mut self, m4_ack_bundles: M4AckBundles) -> Self {
let message = CoinbaseMessage::M4AckBundles(m4_ack_bundles);
self.messages.push(message);
self
}
pub fn bmm_accept(mut self, sidechain_number: u8, bmm_hash: &[u8; 32]) -> Self {
let message = CoinbaseMessage::M7BmmAccept {
sidechain_number,
sidechain_block_hash: *bmm_hash,
};
self.messages.push(message);
self
}
}
#[derive(Debug)]
pub enum CoinbaseMessage {
M1ProposeSidechain {
sidechain_number: u8,
data: Vec<u8>,
},
M2AckSidechain {
sidechain_number: u8,
data_hash: [u8; 32],
},
M3ProposeBundle {
sidechain_number: u8,
bundle_txid: [u8; 32],
},
M4AckBundles(M4AckBundles),
M7BmmAccept {
sidechain_number: u8,
sidechain_block_hash: [u8; 32],
},
}
#[derive(Debug)]
pub struct M8BmmRequest {
pub sidechain_number: u8,
pub sidechain_block_hash: [u8; 32],
pub prev_mainchain_block_hash: [u8; 32],
}
const M1_PROPOSE_SIDECHAIN_TAG: &[u8] = &[0xD5, 0xE0, 0xC4, 0xAF];
const M2_ACK_SIDECHAIN_TAG: &[u8] = &[0xD6, 0xE1, 0xC5, 0xDF];
const M3_PROPOSE_BUNDLE_TAG: &[u8] = &[0xD4, 0x5A, 0xA9, 0x43];
const M4_ACK_BUNDLES_TAG: &[u8] = &[0xD7, 0x7D, 0x17, 0x76];
const M7_BMM_ACCEPT_TAG: &[u8] = &[0xD1, 0x61, 0x73, 0x68];
const M8_BMM_REQUEST_TAG: &[u8] = &[0x00, 0xBF, 0x00];
pub const ABSTAIN_ONE_BYTE: u8 = 0xFF;
pub const ABSTAIN_TWO_BYTES: u16 = 0xFFFF;
pub const ALARM_ONE_BYTE: u8 = 0xFE;
pub const ALARM_TWO_BYTES: u16 = 0xFFFE;
#[derive(Debug)]
pub enum M4AckBundles {
RepeatPrevious,
OneByte { upvotes: Vec<u8> },
TwoBytes { upvotes: Vec<u16> },
LeadingBy50,
}
const REPEAT_PREVIOUS_TAG: &[u8] = &[0x00];
const ONE_BYTE_TAG: &[u8] = &[0x01];
const TWO_BYTES_TAG: &[u8] = &[0x02];
const LEADING_BY_50_TAG: &[u8] = &[0x03];
/// 0xFF
// 0xFFFF
// const ABSTAIN_TAG: &[u8] = &[0xFF];
/// 0xFE
// 0xFFFE
// const ALARM_TAG: &[u8] = &[0xFE];
impl M4AckBundles {
fn tag(&self) -> u8 {
match self {
Self::RepeatPrevious => REPEAT_PREVIOUS_TAG[0],
Self::OneByte { .. } => ONE_BYTE_TAG[0],
Self::TwoBytes { .. } => TWO_BYTES_TAG[0],
Self::LeadingBy50 { .. } => LEADING_BY_50_TAG[0],
}
}
}
pub fn parse_coinbase_script<'a>(script: &'a Script) -> IResult<&'a [u8], CoinbaseMessage> {
let script = script.as_bytes();
let (input, _) = tag(&[OP_RETURN.to_u8()])(script)?;
let (input, message_tag) = alt((
tag(M1_PROPOSE_SIDECHAIN_TAG),
tag(M2_ACK_SIDECHAIN_TAG),
tag(M3_PROPOSE_BUNDLE_TAG),
tag(M4_ACK_BUNDLES_TAG),
))(input)?;
if message_tag == M1_PROPOSE_SIDECHAIN_TAG {
return parse_m1_propose_sidechain(input);
} else if message_tag == M2_ACK_SIDECHAIN_TAG {
return parse_m2_ack_sidechain(input);
} else if message_tag == M3_PROPOSE_BUNDLE_TAG {
return parse_m3_propose_bundle(input);
} else if message_tag == M4_ACK_BUNDLES_TAG {
return parse_m4_ack_bundles(input);
} else if message_tag == M7_BMM_ACCEPT_TAG {
return parse_m7_bmm_accept(input);
}
fail(input)
}
pub fn parse_op_drivechain(input: &[u8]) -> IResult<&[u8], u8> {
let (input, _op_drivechain_tag) = tag(&[OP_DRIVECHAIN.to_u8(), OP_PUSHBYTES_1.to_u8()])(input)?;
let (input, sidechain_number) = take(1usize)(input)?;
let sidechain_number = sidechain_number[0];
tag(&[OP_TRUE.to_u8()])(input)?;
return Ok((input, sidechain_number));
}
fn parse_m1_propose_sidechain(input: &[u8]) -> IResult<&[u8], CoinbaseMessage> {
let (input, sidechain_number) = take(1usize)(input)?;
let sidechain_number = sidechain_number[0];
let (input, data) = rest(input)?;
let data = data.to_vec();
let message = CoinbaseMessage::M1ProposeSidechain {
sidechain_number,
data,
};
return Ok((input, message));
}
fn parse_m2_ack_sidechain(input: &[u8]) -> IResult<&[u8], CoinbaseMessage> {
let (input, sidechain_number) = take(1usize)(input)?;
let sidechain_number = sidechain_number[0];
let (input, data_hash) = take(32usize)(input)?;
let data_hash: [u8; 32] = data_hash.try_into().unwrap();
let message = CoinbaseMessage::M2AckSidechain {
sidechain_number,
data_hash,
};
return Ok((input, message));
}
fn parse_m3_propose_bundle(input: &[u8]) -> IResult<&[u8], CoinbaseMessage> {
let (input, sidechain_number) = take(1usize)(input)?;
let sidechain_number = sidechain_number[0];
let (input, bundle_txid) = take(32usize)(input)?;
let bundle_txid: [u8; 32] = bundle_txid.try_into().unwrap();
let message = CoinbaseMessage::M3ProposeBundle {
sidechain_number,
bundle_txid,
};
return Ok((input, message));
}
fn parse_m4_ack_bundles(input: &[u8]) -> IResult<&[u8], CoinbaseMessage> {
let (input, m4_tag) = alt((
tag(REPEAT_PREVIOUS_TAG),
tag(ONE_BYTE_TAG),
tag(TWO_BYTES_TAG),
tag(LEADING_BY_50_TAG),
))(input)?;
if m4_tag == REPEAT_PREVIOUS_TAG {
let message = CoinbaseMessage::M4AckBundles(M4AckBundles::RepeatPrevious);
return Ok((input, message));
} else if m4_tag == ONE_BYTE_TAG {
let (input, upvotes) = rest(input)?;
let upvotes = upvotes.to_vec();
let message = CoinbaseMessage::M4AckBundles(M4AckBundles::OneByte { upvotes });
return Ok((input, message));
} else if m4_tag == TWO_BYTES_TAG {
let (input, upvotes) = many0(take(2usize))(input)?;
let upvotes: Vec<u16> = upvotes
.into_iter()
.map(|upvote| BigEndian::read_u16(upvote))
.collect();
let message = CoinbaseMessage::M4AckBundles(M4AckBundles::TwoBytes { upvotes });
return Ok((input, message));
} else if m4_tag == LEADING_BY_50_TAG {
let message = CoinbaseMessage::M4AckBundles(M4AckBundles::LeadingBy50);
return Ok((input, message));
}
return fail(input);
}
fn parse_m7_bmm_accept(input: &[u8]) -> IResult<&[u8], CoinbaseMessage> {
let (input, sidechain_number) = take(1usize)(input)?;
let sidechain_number = sidechain_number[0];
let (input, sidechain_block_hash) = take(32usize)(input)?;
// Unwrap here is fine, because if we didn't get exactly 32 bytes we'd fail on the previous
// line.
let sidechain_block_hash = sidechain_block_hash.try_into().unwrap();
let message = CoinbaseMessage::M7BmmAccept {
sidechain_number,
sidechain_block_hash,
};
Ok((input, message))
}
pub fn parse_m8_bmm_request(input: &[u8]) -> IResult<&[u8], M8BmmRequest> {
let (input, _) = tag(&[OP_RETURN.to_u8()])(input)?;
let (input, _) = tag(M8_BMM_REQUEST_TAG)(input)?;
let (input, sidechain_number) = take(1usize)(input)?;
let sidechain_number = sidechain_number[0];
let (input, sidechain_block_hash) = take(32usize)(input)?;
let (input, prev_mainchain_block_hash) = take(32usize)(input)?;
let sidechain_block_hash = sidechain_block_hash.try_into().unwrap();
let prev_mainchain_block_hash = prev_mainchain_block_hash.try_into().unwrap();
let message = M8BmmRequest {
sidechain_number,
sidechain_block_hash,
prev_mainchain_block_hash,
};
return Ok((input, message));
}
impl Into<ScriptBuf> for CoinbaseMessage {
fn into(self) -> ScriptBuf {
match self {
Self::M1ProposeSidechain {
sidechain_number,
data,
} => {
let message = [
&[OP_RETURN.to_u8()],
M1_PROPOSE_SIDECHAIN_TAG,
&[sidechain_number],
&data,
]
.concat();
let script_pubkey = ScriptBuf::from_bytes(message);
return script_pubkey;
}
Self::M2AckSidechain {
sidechain_number,
data_hash,
} => {
let message = [
&[OP_RETURN.to_u8()],
M2_ACK_SIDECHAIN_TAG,
&[sidechain_number],
&data_hash,
]
.concat();
let script_pubkey = ScriptBuf::from_bytes(message);
return script_pubkey;
}
Self::M3ProposeBundle {
sidechain_number,
bundle_txid,
} => {
let message = [
&[OP_RETURN.to_u8()],
M3_PROPOSE_BUNDLE_TAG,
&[sidechain_number],
&bundle_txid,
]
.concat();
let script_pubkey = ScriptBuf::from_bytes(message);
return script_pubkey;
}
Self::M4AckBundles(m4_ack_bundles) => {
let upvotes = match &m4_ack_bundles {
M4AckBundles::OneByte { upvotes } => upvotes.clone(),
M4AckBundles::TwoBytes { upvotes } => upvotes
.iter()
.flat_map(|upvote| upvote.to_be_bytes())
.collect(),
_ => vec![],
};
let message = [
&[OP_RETURN.to_u8()],
M4_ACK_BUNDLES_TAG,
&[m4_ack_bundles.tag()],
&upvotes,
]
.concat();
let script_pubkey = ScriptBuf::from_bytes(message);
return script_pubkey;
}
Self::M7BmmAccept {
sidechain_number,
sidechain_block_hash,
} => {
let message = [
&[OP_RETURN.to_u8()],
M7_BMM_ACCEPT_TAG,
&[sidechain_number],
&sidechain_block_hash,
]
.concat();
let script_pubkey = ScriptBuf::from_bytes(message);
return script_pubkey;
}
}
}
}
pub fn sha256d(data: &[u8]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(data);
let data_sha256_hash: [u8; 32] = hasher.finalize_reset().into();
hasher.update(data_sha256_hash);
let data_sha256d_hash: [u8; 32] = hasher.finalize().into();
data_sha256d_hash
}
pub fn m6_to_id(m6: &Transaction, previous_treasury_utxo_total: u64) -> [u8; 32] {
let mut m6 = m6.clone();
/*
1. Remove the single input spending the previous treasury UTXO from the `vin`
vector, so that the `vin` vector is empty.
*/
m6.input.clear();
/*
2. Compute `P_total` by summing the `nValue`s of all pay out outputs in this
`M6`, so `P_total` = sum of `nValue`s of all outputs of this `M6` except for
the new treasury UTXO at index 0.
*/
let p_total: Amount = m6.output[1..].iter().map(|o| o.value).sum();
/*
3. Set `T_n` equal to the `nValue` of the treasury UTXO created in this `M6`.
*/
let t_n = m6.output[0].value.to_sat();
/*
4. Compute `F_total = T_n-1 - T_n - P_total`, since we know that `T_n = T_n-1 -
P_total - F_total`, `T_n-1` was passed as an argument, and `T_n` and
`P_total` were computed in previous steps..
*/
let t_n_minus_1 = previous_treasury_utxo_total;
let f_total = t_n_minus_1 - t_n - p_total.to_sat();
/*
5. Encode `F_total` as `F_total_be_bytes`, an array of 8 bytes encoding the 64
bit unsigned integer in big endian order.
*/
let f_total_be_bytes = f_total.to_be_bytes();
/*
6. Push an output to the end of `vout` of this `M6` with the `nValue = 0` and
`scriptPubKey = OP_RETURN F_total_be_bytes`.
*/
let script_bytes = [vec![OP_RETURN.to_u8()], f_total_be_bytes.to_vec()].concat();
let script_pubkey = ScriptBuf::from_bytes(script_bytes);
let txout = TxOut {
script_pubkey,
value: Amount::ZERO,
};
m6.output.push(txout);
/*
At this point we have constructed `M6_blinded`.
*/
let m6_blinded = m6;
m6_blinded.compute_txid().to_byte_array()
}