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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use hash::H256;
use chain::{IndexedBlock, IndexedBlockHeader, BlockHeader, Transaction};
use storage::{SharedStore, TransactionOutputProvider, BlockHeaderProvider, BlockOrigin};
use network::ConsensusParams;
use error::{Error, TransactionError};
use canon::{CanonBlock, CanonTransaction};
use duplex_store::{DuplexTransactionOutputProvider, NoopStore};
use verify_chain::ChainVerifier;
use verify_header::HeaderVerifier;
use verify_transaction::MemoryPoolTransactionVerifier;
use accept_chain::ChainAcceptor;
use accept_transaction::MemoryPoolTransactionAcceptor;
use deployments::{Deployments, BlockDeployments};
use timestamp::median_timestamp_inclusive;
use {Verify, VerificationLevel};
pub struct BackwardsCompatibleChainVerifier {
store: SharedStore,
consensus: ConsensusParams,
deployments: Deployments,
}
impl BackwardsCompatibleChainVerifier {
pub fn new(store: SharedStore, consensus: ConsensusParams) -> Self {
BackwardsCompatibleChainVerifier {
store: store,
consensus: consensus,
deployments: Deployments::new(),
}
}
fn verify_block(&self, verification_level: VerificationLevel, block: &IndexedBlock) -> Result<(), Error> {
if verification_level == VerificationLevel::NoVerification {
return Ok(());
}
let current_time = ::time::get_time().sec as u32;
let chain_verifier = ChainVerifier::new(block, self.consensus.network, current_time);
chain_verifier.check()?;
assert_eq!(Some(self.store.best_block().hash), self.store.block_hash(self.store.best_block().number));
let block_origin = self.store.block_origin(&block.header)?;
trace!(target: "verification", "verify_block: {:?} best_block: {:?} block_origin: {:?}", block.hash().reversed(), self.store.best_block(), block_origin);
let median_time_past = median_timestamp_inclusive(block.header.raw.previous_header_hash.clone(), self.store.as_block_header_provider());
match block_origin {
BlockOrigin::KnownBlock => {
unreachable!();
},
BlockOrigin::CanonChain { block_number } => {
let header_provider = self.store.as_store().as_block_header_provider();
let deployments = BlockDeployments::new(&self.deployments, block_number, header_provider, &self.consensus);
let canon_block = CanonBlock::new(block);
let chain_acceptor = ChainAcceptor::new(self.store.as_store(), &self.consensus, verification_level,
canon_block, block_number, median_time_past, &deployments);
chain_acceptor.check()?;
},
BlockOrigin::SideChain(origin) => {
let block_number = origin.block_number;
let header_provider = self.store.as_store().as_block_header_provider();
let deployments = BlockDeployments::new(&self.deployments, block_number, header_provider, &self.consensus);
let fork = self.store.fork(origin)?;
let canon_block = CanonBlock::new(block);
let chain_acceptor = ChainAcceptor::new(fork.store(), &self.consensus, verification_level, canon_block,
block_number, median_time_past, &deployments);
chain_acceptor.check()?;
},
BlockOrigin::SideChainBecomingCanonChain(origin) => {
let block_number = origin.block_number;
let header_provider = self.store.as_store().as_block_header_provider();
let deployments = BlockDeployments::new(&self.deployments, block_number, header_provider, &self.consensus);
let fork = self.store.fork(origin)?;
let canon_block = CanonBlock::new(block);
let chain_acceptor = ChainAcceptor::new(fork.store(), &self.consensus, verification_level, canon_block,
block_number, median_time_past, &deployments);
chain_acceptor.check()?;
},
}
assert_eq!(Some(self.store.best_block().hash), self.store.block_hash(self.store.best_block().number));
Ok(())
}
pub fn verify_block_header(
&self,
_block_header_provider: &BlockHeaderProvider,
hash: &H256,
header: &BlockHeader
) -> Result<(), Error> {
let current_time = ::time::get_time().sec as u32;
let header = IndexedBlockHeader::new(hash.clone(), header.clone());
let header_verifier = HeaderVerifier::new(&header, self.consensus.network, current_time);
header_verifier.check()
}
pub fn verify_mempool_transaction<T>(
&self,
block_header_provider: &BlockHeaderProvider,
prevout_provider: &T,
height: u32,
time: u32,
transaction: &Transaction,
) -> Result<(), TransactionError> where T: TransactionOutputProvider {
let indexed_tx = transaction.clone().into();
let deployments = BlockDeployments::new(&self.deployments, height, block_header_provider, &self.consensus);
let tx_verifier = MemoryPoolTransactionVerifier::new(&indexed_tx, &self.consensus, &deployments);
try!(tx_verifier.check());
let canon_tx = CanonTransaction::new(&indexed_tx);
let noop = NoopStore;
let output_store = DuplexTransactionOutputProvider::new(prevout_provider, &noop);
let previous_block_number = height.checked_sub(1)
.expect("height is the height of future block of new tx; genesis block can't be in the future; qed");
let previous_block_header = block_header_provider.block_header(previous_block_number.into())
.expect("blocks up to height should be in db; qed");
let median_time_past = median_timestamp_inclusive(previous_block_header.hash(), block_header_provider);
let tx_acceptor = MemoryPoolTransactionAcceptor::new(
self.store.as_transaction_meta_provider(),
output_store,
&self.consensus,
canon_tx,
height,
time,
median_time_past,
&deployments,
);
tx_acceptor.check()
}
}
impl Verify for BackwardsCompatibleChainVerifier {
fn verify(&self, level: VerificationLevel, block: &IndexedBlock) -> Result<(), Error> {
let result = self.verify_block(level, block);
trace!(
target: "verification", "Block {} (transactions: {}) verification finished. Result {:?}",
block.hash().to_reversed_str(),
block.transactions.len(),
result,
);
result
}
}
#[cfg(test)]
mod tests {
extern crate test_data;
use std::sync::Arc;
use chain::{IndexedBlock, Transaction, Block};
use storage::Error as DBError;
use db::BlockChainDatabase;
use network::{Network, ConsensusParams, ConsensusFork, BitcoinCashConsensusParams};
use script;
use constants::DOUBLE_SPACING_SECONDS;
use super::BackwardsCompatibleChainVerifier as ChainVerifier;
use {Verify, Error, TransactionError, VerificationLevel};
#[test]
fn verify_orphan() {
let storage = Arc::new(BlockChainDatabase::init_test_chain(vec![test_data::genesis().into()]));
let b2 = test_data::block_h2().into();
let verifier = ChainVerifier::new(storage, ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore));
assert_eq!(Err(Error::Database(DBError::UnknownParent)), verifier.verify(VerificationLevel::Full, &b2));
}
#[test]
fn verify_smoky() {
let storage = Arc::new(BlockChainDatabase::init_test_chain(vec![test_data::genesis().into()]));
let b1 = test_data::block_h1();
let verifier = ChainVerifier::new(storage, ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore));
assert!(verifier.verify(VerificationLevel::Full, &b1.into()).is_ok());
}
#[test]
fn first_tx() {
let storage = BlockChainDatabase::init_test_chain(
vec![
test_data::block_h0().into(),
test_data::block_h1().into(),
]);
let b1 = test_data::block_h2();
let verifier = ChainVerifier::new(Arc::new(storage), ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore));
assert!(verifier.verify(VerificationLevel::Full, &b1.into()).is_ok());
}
#[test]
fn coinbase_maturity() {
let genesis = test_data::block_builder()
.transaction()
.coinbase()
.output().value(50).build()
.build()
.merkled_header().build()
.build();
let storage = BlockChainDatabase::init_test_chain(vec![genesis.clone().into()]);
let genesis_coinbase = genesis.transactions()[0].hash();
let block = test_data::block_builder()
.transaction()
.coinbase()
.output().value(1).build()
.build()
.transaction()
.input().hash(genesis_coinbase).build()
.output().value(2).build()
.build()
.merkled_header().parent(genesis.hash()).build()
.build();
let verifier = ChainVerifier::new(Arc::new(storage), ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore));
let expected = Err(Error::Transaction(
1,
TransactionError::Maturity,
));
assert_eq!(expected, verifier.verify(VerificationLevel::Full, &block.into()));
}
#[test]
fn non_coinbase_happy() {
let genesis = test_data::block_builder()
.transaction()
.coinbase()
.output().value(1).build()
.build()
.transaction()
.output().value(50).build()
.build()
.merkled_header().build()
.build();
let storage = BlockChainDatabase::init_test_chain(vec![genesis.clone().into()]);
let reference_tx = genesis.transactions()[1].hash();
let block = test_data::block_builder()
.transaction()
.coinbase()
.output().value(2).build()
.build()
.transaction()
.input().hash(reference_tx).build()
.output().value(1).build()
.build()
.merkled_header().parent(genesis.hash()).build()
.build();
let verifier = ChainVerifier::new(Arc::new(storage), ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore));
assert!(verifier.verify(VerificationLevel::Full, &block.into()).is_ok());
}
#[test]
fn transaction_references_same_block_happy() {
let genesis = test_data::block_builder()
.transaction()
.coinbase()
.output().value(1).build()
.build()
.transaction()
.output().value(50).build()
.build()
.merkled_header().build()
.build();
let storage = BlockChainDatabase::init_test_chain(vec![genesis.clone().into()]);
let first_tx_hash = genesis.transactions()[1].hash();
let block = test_data::block_builder()
.transaction()
.coinbase()
.output().value(2).build()
.build()
.transaction()
.input().hash(first_tx_hash).build()
.output().value(30).build()
.output().value(20).build()
.build()
.derived_transaction(1, 0)
.output().value(30).build()
.build()
.merkled_header().parent(genesis.hash()).build()
.build();
let verifier = ChainVerifier::new(Arc::new(storage), ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore));
assert!(verifier.verify(VerificationLevel::Full, &block.into()).is_ok());
}
#[test]
fn transaction_references_same_block_overspend() {
let genesis = test_data::block_builder()
.transaction()
.coinbase()
.output().value(1).build()
.build()
.transaction()
.output().value(50).build()
.build()
.merkled_header().build()
.build();
let storage = BlockChainDatabase::init_test_chain(vec![genesis.clone().into()]);
let first_tx_hash = genesis.transactions()[1].hash();
let block = test_data::block_builder()
.transaction()
.coinbase()
.output().value(2).build()
.build()
.transaction()
.input().hash(first_tx_hash).build()
.output().value(19).build()
.output().value(31).build()
.build()
.derived_transaction(1, 0)
.output().value(20).build()
.build()
.derived_transaction(1, 1)
.output().value(20).build()
.build()
.merkled_header().parent(genesis.hash()).build()
.build();
let verifier = ChainVerifier::new(Arc::new(storage), ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore));
let expected = Err(Error::Transaction(2, TransactionError::Overspend));
assert_eq!(expected, verifier.verify(VerificationLevel::Full, &block.into()));
}
#[test]
fn transaction_references_same_block_and_goes_before_previous() {
let mut blocks = vec![test_data::block_builder()
.transaction()
.coinbase()
.output().value(50).build()
.build()
.merkled_header().build()
.build()];
let input_tx = blocks[0].transactions()[0].clone();
let mut parent_hash = blocks[0].hash();
for _ in 0..100 {
let block: Block = test_data::block_builder()
.transaction().coinbase().build()
.merkled_header().parent(parent_hash).build()
.build()
.into();
parent_hash = block.hash();
blocks.push(block);
}
let storage = Arc::new(BlockChainDatabase::init_test_chain(blocks.into_iter().map(Into::into).collect()));
let tx1: Transaction = test_data::TransactionBuilder::with_version(4)
.add_input(&input_tx, 0)
.add_output(10).add_output(10).add_output(10)
.add_output(5).add_output(5).add_output(5)
.into();
let tx2: Transaction = test_data::TransactionBuilder::with_version(1)
.add_input(&tx1, 0)
.add_output(1).add_output(1).add_output(1)
.add_output(2).add_output(2).add_output(2)
.into();
assert!(tx1.hash() > tx2.hash());
let block = test_data::block_builder()
.transaction()
.coinbase()
.output().value(2).script_pubkey_with_sigops(100).build()
.build()
.with_transaction(tx2)
.with_transaction(tx1)
.merkled_header()
.time(DOUBLE_SPACING_SECONDS + 101)
.parent(parent_hash)
.build()
.build();
let topological_consensus = ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore);
let verifier = ChainVerifier::new(storage.clone(), topological_consensus);
let expected = Err(Error::Transaction(1, TransactionError::Overspend));
assert_eq!(expected, verifier.verify(VerificationLevel::Header, &block.clone().into()));
let mut canonical_params = BitcoinCashConsensusParams::new(Network::Unitest);
canonical_params.magnetic_anomaly_time = 0;
let canonical_consensus = ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCash(canonical_params));
let verifier = ChainVerifier::new(storage, canonical_consensus);
let expected = Ok(());
assert_eq!(expected, verifier.verify(VerificationLevel::Header, &block.into()));
}
#[test]
#[ignore]
fn coinbase_happy() {
let genesis = test_data::block_builder()
.transaction()
.coinbase()
.output().value(50).build()
.build()
.merkled_header().build()
.build();
let storage = BlockChainDatabase::init_test_chain(vec![genesis.clone().into()]);
let genesis_coinbase = genesis.transactions()[0].hash();
for _ in 0..100 {
let block: IndexedBlock = test_data::block_builder()
.transaction().coinbase().build()
.merkled_header().parent(genesis.hash()).build()
.build()
.into();
let hash = block.hash().clone();
storage.insert(block).expect("All dummy blocks should be inserted");
storage.canonize(&hash).unwrap();
}
let best_hash = storage.best_block().hash;
let block = test_data::block_builder()
.transaction().coinbase().build()
.transaction()
.input().hash(genesis_coinbase.clone()).build()
.build()
.merkled_header().parent(best_hash).build()
.build();
let verifier = ChainVerifier::new(Arc::new(storage), ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore));
assert!(verifier.verify(VerificationLevel::Full, &block.into()).is_ok());
}
#[test]
fn absoulte_sigops_overflow_block() {
let genesis = test_data::block_builder()
.transaction()
.coinbase()
.build()
.transaction()
.output().value(50).build()
.build()
.merkled_header().build()
.build();
let storage = BlockChainDatabase::init_test_chain(vec![genesis.clone().into()]);
let reference_tx = genesis.transactions()[1].hash();
let mut builder_tx1 = script::Builder::default();
for _ in 0..81000 {
builder_tx1 = builder_tx1.push_opcode(script::Opcode::OP_CHECKSIG)
}
let mut builder_tx2 = script::Builder::default();
for _ in 0..81001 {
builder_tx2 = builder_tx2.push_opcode(script::Opcode::OP_CHECKSIG)
}
let block: IndexedBlock = test_data::block_builder()
.transaction().coinbase().build()
.transaction()
.input()
.hash(reference_tx.clone())
.signature_bytes(builder_tx1.into_script().to_bytes())
.build()
.build()
.transaction()
.input()
.hash(reference_tx)
.signature_bytes(builder_tx2.into_script().to_bytes())
.build()
.build()
.merkled_header().parent(genesis.hash()).build()
.build()
.into();
let verifier = ChainVerifier::new(Arc::new(storage), ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore));
let expected = Err(Error::MaximumSigops);
assert_eq!(expected, verifier.verify(VerificationLevel::Full, &block.into()));
}
#[test]
fn coinbase_overspend() {
let genesis = test_data::block_builder()
.transaction().coinbase().build()
.merkled_header().build()
.build();
let storage = BlockChainDatabase::init_test_chain(vec![genesis.clone().into()]);
let block: IndexedBlock = test_data::block_builder()
.transaction()
.coinbase()
.output().value(5000000001).build()
.build()
.merkled_header().parent(genesis.hash()).build()
.build()
.into();
let verifier = ChainVerifier::new(Arc::new(storage), ConsensusParams::new(Network::Unitest, ConsensusFork::BitcoinCore));
let expected = Err(Error::CoinbaseOverspend {
expected_max: 5000000000,
actual: 5000000001
});
assert_eq!(expected, verifier.verify(VerificationLevel::Full, &block.into()));
}
}