-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathlib.rs
More file actions
1465 lines (1268 loc) · 57 KB
/
lib.rs
File metadata and controls
1465 lines (1268 loc) · 57 KB
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # BTC-Relay Pallet
//!
//! Based on the [specification](https://spec.interlay.io/spec/btc-relay/index.html).
//!
//! This pallet implements a Bitcoin light client to store and verify block headers in accordance
//! with SPV assumptions - i.e. longest chain.
//!
//! Unless otherwise stated, the primary source of truth for code contained herein is the
//! [Bitcoin Core repository](https://github.com/bitcoin/bitcoin), though implementation
//! details may vary.
//!
//! ## Overview
//!
//! The BTC-Relay pallet provides functions for:
//!
//! - Initializing and updating the relay.
//! - Transaction inclusion verification.
//! - Transaction validation.
//!
//! ### Terminology
//!
//! - **Bitcoin Confirmations:** The minimum number of Bitcoin confirmations a Bitcoin block header must have to be seen
//! as included in the main chain.
//!
//! - **Parachain Confirmations:** The minimum number of Parachain confirmations a Bitcoin block header must have to be
//! usable in transaction inclusion verification.
#![deny(warnings)]
#![cfg_attr(test, feature(proc_macro_hygiene))]
#![cfg_attr(not(feature = "std"), no_std)]
mod ext;
pub mod types;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
mod default_weights;
pub use default_weights::WeightInfo;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod mock;
#[cfg(test)]
extern crate mocktopus;
#[cfg(test)]
use mocktopus::macros::mockable;
#[cfg(feature = "runtime-benchmarks")]
use bitcoin::types::{BlockBuilder, TransactionBuilder, TransactionOutput};
use bitcoin::{
merkle::ProofResult,
types::{BlockChain, BlockHeader, H256Le, Transaction, Value},
Error as BitcoinError, SetCompact,
};
use frame_support::{
dispatch::{DispatchError, DispatchResult},
ensure, runtime_print,
traits::Get,
transactional,
};
use frame_system::ensure_signed;
use sp_core::{H256, U256};
use sp_runtime::traits::{CheckedAdd, CheckedDiv, CheckedSub, One};
use sp_std::{
convert::{TryFrom, TryInto},
prelude::*,
};
pub use bitcoin::{
self, merkle::PartialTransactionProof, types::FullTransactionProof, Address as BtcAddress,
PublicKey as BtcPublicKey,
};
pub use pallet::*;
pub use types::{OpReturnPaymentData, RichBlockHeader};
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config + security::Config {
/// The overarching event type.
type RuntimeEvent: From<Event<Self>>
+ Into<<Self as frame_system::Config>::RuntimeEvent>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Weight information for the extrinsics in this module.
type WeightInfo: WeightInfo;
#[pallet::constant]
type ParachainBlocksPerBitcoinBlock: Get<<Self as frame_system::Config>::BlockNumber>;
}
#[pallet::hooks]
impl<T: Config> Hooks<T::BlockNumber> for Pallet<T> {}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// One time function to initialize the BTC-Relay with the first block
///
/// # Arguments
///
/// * `block_header` - Bitcoin block header.
/// * `block_height` - starting Bitcoin block height of the submitted block header.
///
/// ## Complexity
/// - O(1)
#[pallet::call_index(0)]
#[pallet::weight((
<T as Config>::WeightInfo::initialize(),
DispatchClass::Operational
))]
#[transactional]
pub fn initialize(
origin: OriginFor<T>,
mut block_header: BlockHeader,
block_height: u32,
) -> DispatchResultWithPostInfo {
let relayer = ensure_signed(origin)?;
Self::_validate_block_header(&mut block_header)?;
Self::_initialize(relayer, block_header, block_height)?;
// don't take tx fees on success
Ok(Pays::No.into())
}
/// Stores a single new block header
///
/// # Arguments
///
/// * `block_header` - Bitcoin block header.
///
/// ## Complexity
/// - `O(F)` where `F` is the number of forks
#[pallet::call_index(1)]
#[pallet::weight((
{
let f = *fork_bound;
<T as Config>::WeightInfo::store_block_header()
.max(<T as Config>::WeightInfo::store_block_header_new_fork_sorted(f))
.max(<T as Config>::WeightInfo::store_block_header_new_fork_unsorted(f))
.max(<T as Config>::WeightInfo::store_block_header_reorganize_chains(f))
},
DispatchClass::Operational
))]
#[transactional]
pub fn store_block_header(
origin: OriginFor<T>,
mut block_header: BlockHeader,
fork_bound: u32,
) -> DispatchResultWithPostInfo {
let relayer = ensure_signed(origin)?;
// the worst-case complexity is always dictated by the number of chains
// TODO: as the growth of `Chains` is unbounded this extrinsic may become
// prohibitively expensive, we should remove old forks from storage
ensure!(
// ideally we would compare the number of entries in `Chains` here but
// since we never delete from that this should be equal to the length
Self::get_chain_counter().saturating_add(1) <= fork_bound,
Error::<T>::WrongForkBound
);
Self::_validate_block_header(&mut block_header)?;
Self::_store_block_header(&relayer, block_header)?;
// don't take tx fees on success
Ok(Pays::No.into())
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
Initialized {
block_height: u32,
block_hash: H256Le,
relayer_id: T::AccountId,
},
StoreMainChainHeader {
block_height: u32,
block_hash: H256Le,
relayer_id: T::AccountId,
},
StoreForkHeader {
chain_id: u32,
fork_height: u32,
block_hash: H256Le,
relayer_id: T::AccountId,
},
ChainReorg {
new_chain_tip_hash: H256Le,
new_chain_tip_height: u32,
fork_depth: u32,
},
ForkAheadOfMainChain {
main_chain_height: u32,
fork_height: u32,
fork_id: u32,
},
}
#[pallet::error]
pub enum Error<T> {
/// Already initialized
AlreadyInitialized,
/// Start height must be start of difficulty period
InvalidStartHeight,
/// Missing the block at this height
MissingBlockHeight,
/// Invalid block header size
InvalidHeaderSize,
/// Block already stored
DuplicateBlock,
/// Previous block hash not found
PrevBlock,
/// Invalid chain ID
InvalidChainID,
/// PoW hash does not meet difficulty target of header
LowDiff,
/// Incorrect difficulty target specified in block header
DiffTargetHeader,
/// Malformed transaction identifier
MalformedTxid,
/// Transaction has less confirmations of Bitcoin blocks than required
BitcoinConfirmations,
/// Transaction has less confirmations of Parachain blocks than required
ParachainConfirmations,
/// Current fork ongoing
OngoingFork,
/// Merkle proof is malformed
MalformedMerkleProof,
/// Invalid merkle proof
InvalidMerkleProof,
/// BTC Parachain has shut down
Shutdown,
/// Transaction hash does not match given txid
InvalidTxid,
/// Invalid payment amount
InvalidPaymentAmount,
/// Transaction has incorrect format
MalformedTransaction,
/// Incorrect recipient Bitcoin address
InvalidPayment,
/// Incorrect transaction output format
InvalidOutputFormat,
/// Incorrect identifier in OP_RETURN field
InvalidOpReturn,
/// Invalid transaction version
InvalidTxVersion,
/// Error code not applicable to blocks
UnknownErrorcode,
/// Blockchain with requested ID not found
ForkIdNotFound,
/// Block header not found for given hash
BlockNotFound,
/// Error code already reported
AlreadyReported,
/// Unauthorized staked relayer
UnauthorizedRelayer,
/// Overflow of chain counter
ChainCounterOverflow,
/// Overflow of block height
BlockHeightOverflow,
/// Underflow of stored blockchains counter
ChainsUnderflow,
/// EndOfFile reached while parsing
EndOfFile,
/// Format of the header is invalid
MalformedHeader,
/// Invalid block header version
InvalidBlockVersion,
/// Format of the BIP141 witness transaction output is invalid
MalformedWitnessOutput,
// Format of the P2PKH transaction output is invalid
MalformedP2PKHOutput,
// Format of the P2SH transaction output is invalid
MalformedP2SHOutput,
/// Format of the OP_RETURN transaction output is invalid
MalformedOpReturnOutput,
// Output does not match format of supported output types (Witness, P2PKH, P2SH)
UnsupportedOutputFormat,
// Input does not match format of supported input types (Witness, P2PKH, P2SH)
UnsupportedInputFormat,
/// User supplied an invalid address
InvalidBtcHash,
/// User supplied an invalid script
InvalidScript,
/// Specified invalid Bitcoin address
InvalidBtcAddress,
/// Arithmetic overflow
ArithmeticOverflow,
/// Arithmetic underflow
ArithmeticUnderflow,
/// TryInto failed on integer
TryIntoIntError,
/// Transaction does meet the requirements to be considered valid
InvalidTransaction,
/// Transaction does meet the requirements to be a valid op-return payment
InvalidOpReturnTransaction,
/// Invalid compact value in header
InvalidCompact,
/// Wrong fork bound, should be higher
WrongForkBound,
/// Weight bound exceeded
BoundExceeded,
/// Coinbase tx must be the first transaction in the block
InvalidCoinbasePosition,
}
/// Store Bitcoin block headers
#[pallet::storage]
pub(super) type BlockHeaders<T: Config> =
StorageMap<_, Blake2_128Concat, H256Le, RichBlockHeader<T::BlockNumber>, ValueQuery>;
/// Priority queue of BlockChain elements, ordered by the maximum height (descending).
/// The first index into this mapping (0) is considered to be the longest chain. The value
/// of the entry is the index into `ChainsIndex` to retrieve the `BlockChain`.
#[pallet::storage]
// TODO: migrate this to sorted vec
pub(super) type Chains<T: Config> = StorageMap<_, Blake2_128Concat, u32, u32>;
/// Auxiliary mapping of chains ids to `BlockChain` entries. The first index into this
/// mapping (0) is considered to be the Bitcoin main chain.
#[pallet::storage]
pub(super) type ChainsIndex<T: Config> = StorageMap<_, Blake2_128Concat, u32, BlockChain>;
/// Stores a mapping from (chain_index, block_height) to block hash
#[pallet::storage]
pub type ChainsHashes<T: Config> =
StorageDoubleMap<_, Blake2_128Concat, u32, Blake2_128Concat, u32, H256Le, ValueQuery>;
/// Store the current blockchain tip
#[pallet::storage]
pub(super) type BestBlock<T: Config> = StorageValue<_, H256Le, ValueQuery>;
/// Store the height of the best block
#[pallet::storage]
pub(super) type BestBlockHeight<T: Config> = StorageValue<_, u32, ValueQuery>;
/// BTC height when the relay was initialized
#[pallet::storage]
pub type StartBlockHeight<T: Config> = StorageValue<_, u32, ValueQuery>;
/// Increment-only counter used to track new BlockChain entries
#[pallet::storage]
pub(super) type ChainCounter<T: Config> = StorageValue<_, u32, ValueQuery>;
/// Global security parameter k for stable Bitcoin transactions
#[pallet::storage]
#[pallet::getter(fn bitcoin_confirmations)]
pub(super) type StableBitcoinConfirmations<T: Config> = StorageValue<_, u32, ValueQuery>;
/// Global security parameter k for stable Parachain transactions
#[pallet::storage]
#[pallet::getter(fn parachain_confirmations)]
pub(super) type StableParachainConfirmations<T: Config> = StorageValue<_, T::BlockNumber, ValueQuery>;
/// Whether the module should perform difficulty checks.
#[pallet::storage]
#[pallet::getter(fn disable_difficulty_check)]
pub(super) type DisableDifficultyCheck<T: Config> = StorageValue<_, bool, ValueQuery>;
/// Whether the module should perform inclusion checks.
#[pallet::storage]
#[pallet::getter(fn disable_inclusion_check)]
pub(super) type DisableInclusionCheck<T: Config> = StorageValue<_, bool, ValueQuery>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
/// Global security parameter k for stable Bitcoin transactions
pub bitcoin_confirmations: u32,
/// Global security parameter k for stable Parachain transactions
pub parachain_confirmations: T::BlockNumber,
/// Whether the module should perform difficulty checks.
pub disable_difficulty_check: bool,
/// Whether the module should perform inclusion checks.
pub disable_inclusion_check: bool,
}
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self {
bitcoin_confirmations: Default::default(),
parachain_confirmations: Default::default(),
disable_difficulty_check: Default::default(),
disable_inclusion_check: Default::default(),
}
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
StableBitcoinConfirmations::<T>::put(self.bitcoin_confirmations);
StableParachainConfirmations::<T>::put(self.parachain_confirmations);
DisableDifficultyCheck::<T>::put(self.disable_difficulty_check);
DisableInclusionCheck::<T>::put(self.disable_inclusion_check);
}
}
}
/// Difficulty Adjustment Interval
pub const DIFFICULTY_ADJUSTMENT_INTERVAL: u32 = 2016;
/// Target Spacing: 10 minutes (600 seconds)
// https://github.com/bitcoin/bitcoin/blob/5ba5becbb5d8c794efe579caeea7eea64f895a13/src/chainparams.cpp#L78
pub const TARGET_SPACING: u32 = 10 * 60;
/// Accepted maximum number of transaction outputs for validation of redeem or replace
/// See: <https://spec.interlay.io/intro/accepted-format.html#accepted-bitcoin-transaction-format>
pub const ACCEPTED_MAX_TRANSACTION_OUTPUTS: usize = 3;
/// Unrounded Maximum Target
/// 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
pub const UNROUNDED_MAX_TARGET: U256 = U256([
<u64>::max_value(),
<u64>::max_value(),
<u64>::max_value(),
0x0000_0000_ffff_ffffu64,
]);
/// Main chain id
pub const MAIN_CHAIN_ID: u32 = 0;
#[cfg_attr(test, mockable)]
impl<T: Config> Pallet<T> {
pub fn _initialize(relayer: T::AccountId, basic_block_header: BlockHeader, block_height: u32) -> DispatchResult {
// Check if BTC-Relay was already initialized
ensure!(!Self::best_block_exists(), Error::<T>::AlreadyInitialized);
// header must be the start of a difficulty period
ensure!(
Self::disable_difficulty_check() || block_height % DIFFICULTY_ADJUSTMENT_INTERVAL == 0,
Error::<T>::InvalidStartHeight
);
// construct the BlockChain struct
Self::create_and_store_blockchain(block_height, &basic_block_header)?;
// Set BestBlock and BestBlockHeight to the submitted block
Self::update_chain_head(&basic_block_header, block_height);
StartBlockHeight::<T>::set(block_height);
// Emit a Initialized Event
Self::deposit_event(Event::<T>::Initialized {
block_height,
block_hash: basic_block_header.hash,
relayer_id: relayer,
});
Ok(())
}
pub fn _store_block_header(relayer: &T::AccountId, basic_block_header: BlockHeader) -> DispatchResult {
let prev_header = Self::get_block_header_from_hash(basic_block_header.hash_prev_block)?;
// check if the prev block is the highest block in the chain
// load the previous block header block height
let prev_block_height = prev_header.block_height;
// update the current block header with height and chain ref
// Set the height of the block header
let current_block_height = prev_block_height.checked_add(1).ok_or(Error::<T>::ArithmeticOverflow)?;
// get the block chain of the previous header
let prev_blockchain = Self::get_block_chain_from_id(prev_header.chain_id)?;
// ensure the block header is valid
Self::verify_block_header(&basic_block_header, current_block_height, prev_header)?;
// Update the blockchain
// check if we create a new blockchain or extend the existing one
runtime_print!("Prev max height: {:?}", prev_blockchain.max_height);
runtime_print!("Prev block height: {:?}", prev_block_height);
let is_new_fork = prev_blockchain.max_height != prev_block_height;
runtime_print!("Fork detected: {:?}", is_new_fork);
let chain_id = if is_new_fork {
// create new blockchain element
Self::create_and_store_blockchain(current_block_height, &basic_block_header)?
} else {
// extend the current chain
let blockchain = Self::extend_blockchain(current_block_height, &basic_block_header, prev_blockchain)?;
if blockchain.chain_id != MAIN_CHAIN_ID {
// if we added a block to a fork, we may need to reorder the chains
Self::reorganize_chains(&blockchain)?;
} else {
Self::update_chain_head(&basic_block_header, current_block_height);
}
blockchain.chain_id
};
// Determine if this block extends the main chain or a fork
let current_best_block = Self::get_best_block();
if current_best_block == basic_block_header.hash {
// extends the main chain
Self::deposit_event(Event::<T>::StoreMainChainHeader {
block_height: current_block_height,
block_hash: basic_block_header.hash,
relayer_id: relayer.clone(),
});
} else {
// created a new fork or updated an existing one
Self::deposit_event(Event::<T>::StoreForkHeader {
chain_id,
fork_height: current_block_height,
block_hash: basic_block_header.hash,
relayer_id: relayer.clone(),
});
};
Ok(())
}
pub fn _validate_block_header(block_header: &mut BlockHeader) -> Result<(), DispatchError> {
block_header.ensure_version().map_err(Error::<T>::from)?;
block_header.update_hash().map_err(Error::<T>::from)?;
Ok(())
}
// helper for the dispatchable
fn _validate_transaction(
transaction: Transaction,
expected_btc: Value,
recipient_btc_address: BtcAddress,
op_return_id: Option<H256>,
) -> Result<(), DispatchError> {
match op_return_id {
Some(op_return) => {
Self::validate_op_return_transaction(transaction, recipient_btc_address, expected_btc, op_return)?;
}
None => {
let payment = Self::get_issue_payment::<i64>(transaction, recipient_btc_address)?;
ensure!(payment == expected_btc, Error::<T>::InvalidPaymentAmount);
}
};
Ok(())
}
/// interface to the issue pallet; verifies inclusion and returns the payment amount
pub fn get_and_verify_issue_payment<V: TryFrom<Value>>(
unchecked_transaction: FullTransactionProof,
recipient_btc_address: BtcAddress,
) -> Result<V, DispatchError> {
// Verify that the transaction is indeed included in the main chain
let transaction = Self::_verify_transaction_inclusion(unchecked_transaction, None)?;
Self::get_issue_payment(transaction, recipient_btc_address)
}
fn get_issue_payment<V: TryFrom<i64>>(
transaction: Transaction,
recipient_btc_address: BtcAddress,
) -> Result<V, DispatchError> {
// using the on-chain key derivation scheme we only expect a simple
// payment to the vault's new deposit address
let payment_value = transaction
.outputs
.into_iter()
.find_map(|x| match x.extract_address() {
Ok(address) if address == recipient_btc_address => Some(x.value),
_ => None,
})
.ok_or(Error::<T>::MalformedTransaction)?
.try_into()
.map_err(|_| Error::<T>::InvalidPaymentAmount)?;
Ok(payment_value)
}
/// interface to redeem,replace,refund to check that the payment is included and is valid
pub fn verify_and_validate_op_return_transaction<V: TryInto<Value>>(
unchecked_transaction: FullTransactionProof,
recipient_btc_address: BtcAddress,
expected_btc: V,
op_return_id: H256,
) -> Result<(), DispatchError> {
// Verify that the transaction is indeed included in the main chain
let transaction = Self::_verify_transaction_inclusion(unchecked_transaction, None)?;
// Check that the transaction matches the given parameters
Self::validate_op_return_transaction(transaction, recipient_btc_address, expected_btc, op_return_id)?;
Ok(())
}
pub fn _verify_transaction_inclusion(
unchecked_transaction: FullTransactionProof,
confirmations: Option<u32>,
) -> Result<Transaction, DispatchError> {
if Self::disable_inclusion_check() {
return Ok(unchecked_transaction.user_tx_proof.transaction);
}
let user_proof_result = Self::verify_merkle_proof(unchecked_transaction.user_tx_proof)?;
let coinbase_proof_result = Self::verify_merkle_proof(unchecked_transaction.coinbase_proof)?;
// make sure the the coinbase tx is the first tx in the block. Otherwise a fake coinbase
// could be included in a leaf-node attack. Related:
// https://bitslog.com/2018/06/09/leaf-node-weakness-in-bitcoin-merkle-tree-design/ .
ensure!(
coinbase_proof_result.transaction_position == 0,
Error::<T>::InvalidCoinbasePosition
);
// Make sure the coinbase tx is for the same block as the user tx
ensure!(
user_proof_result.extracted_root == coinbase_proof_result.extracted_root,
Error::<T>::InvalidMerkleProof
);
ensure!(
user_proof_result.block_hash == coinbase_proof_result.block_hash,
Error::<T>::InvalidMerkleProof
);
// ensure that the tx count for the coinbase tx matches the user's
ensure!(
user_proof_result.tx_count == coinbase_proof_result.tx_count,
Error::<T>::InvalidMerkleProof
);
// Ensure that it's actually the coinbase tx
ensure!(
coinbase_proof_result.transaction.is_coinbase(),
Error::<T>::InvalidMerkleProof
);
let stored_block_header = Self::verify_block_header_inclusion(user_proof_result.block_hash, confirmations)?;
// fail if the merkle root is invalid
ensure!(
Self::block_matches_merkle_root(&stored_block_header, &user_proof_result),
Error::<T>::InvalidMerkleProof
);
Ok(user_proof_result.transaction)
}
// util function extracted for mocking purposes
fn block_matches_merkle_root(block_header: &BlockHeader, proof_result: &ProofResult) -> bool {
proof_result.extracted_root == block_header.merkle_root
}
pub fn verify_block_header_inclusion(
block_hash: H256Le,
confirmations: Option<u32>,
) -> Result<BlockHeader, DispatchError> {
let best_block_height = Self::get_best_block_height();
Self::ensure_no_ongoing_fork(best_block_height)?;
let rich_header = Self::get_block_header_from_hash(block_hash)?;
ensure!(rich_header.chain_id == MAIN_CHAIN_ID, Error::<T>::InvalidChainID);
let block_height = rich_header.block_height;
// This call fails if not enough confirmations
Self::check_bitcoin_confirmations(best_block_height, confirmations, block_height)?;
// This call fails if the block was stored too recently
Self::check_parachain_confirmations(rich_header.para_height)?;
Ok(rich_header.block_header)
}
/// Checks if transaction is valid. Returns the return-to-self address, if any, for theft checking purposes
fn validate_op_return_transaction<V: TryInto<i64>>(
transaction: Transaction,
recipient_btc_address: BtcAddress,
expected_btc: V,
op_return_id: H256,
) -> Result<Option<BtcAddress>, DispatchError> {
let payment_data = OpReturnPaymentData::<T>::try_from(transaction)?;
payment_data.ensure_valid_payment_to(
expected_btc.try_into().map_err(|_| Error::<T>::InvalidPaymentAmount)?,
recipient_btc_address,
Some(op_return_id),
)
}
pub fn is_fully_initialized() -> Result<bool, DispatchError> {
if !StartBlockHeight::<T>::exists() {
return Ok(false);
}
let required_height = StartBlockHeight::<T>::get()
.checked_add(StableBitcoinConfirmations::<T>::get())
.ok_or(Error::<T>::ArithmeticOverflow)?;
let best = BestBlockHeight::<T>::get();
Ok(best >= required_height)
}
pub fn has_request_expired(
opentime: T::BlockNumber,
btc_open_height: u32,
period: T::BlockNumber,
) -> Result<bool, DispatchError> {
Ok(ext::security::parachain_block_expired::<T>(opentime, period)?
&& Self::bitcoin_block_expired(btc_open_height, period)?)
}
pub fn bitcoin_expiry_height(btc_open_height: u32, period: T::BlockNumber) -> Result<u32, DispatchError> {
// calculate num_bitcoin_blocks as ceil(period / ParachainBlocksPerBitcoinBlock)
let num_bitcoin_blocks: u32 = period
.checked_add(&T::ParachainBlocksPerBitcoinBlock::get())
.ok_or(Error::<T>::ArithmeticOverflow)?
.checked_sub(&T::BlockNumber::one())
.ok_or(Error::<T>::ArithmeticUnderflow)?
.checked_div(&T::ParachainBlocksPerBitcoinBlock::get())
.ok_or(Error::<T>::ArithmeticUnderflow)?
.try_into()
.map_err(|_| Error::<T>::TryIntoIntError)?;
Ok(btc_open_height
.checked_add(num_bitcoin_blocks)
.ok_or(Error::<T>::ArithmeticOverflow)?)
}
pub fn bitcoin_block_expired(btc_open_height: u32, period: T::BlockNumber) -> Result<bool, DispatchError> {
let expiration_height = Self::bitcoin_expiry_height(btc_open_height, period)?;
// Note that we check stictly greater than. This ensures that at least
// `num_bitcoin_blocks` FULL periods have expired.
Ok(Self::get_best_block_height() > expiration_height)
}
// ********************************
// START: Storage getter functions
// ********************************
/// Get chain id from position (sorted by max block height)
fn get_chain_id_from_position(position: u32) -> Result<u32, DispatchError> {
Chains::<T>::get(position).ok_or(Error::<T>::InvalidChainID.into())
}
/// Get the position of the fork in Chains
fn get_chain_position_from_chain_id(chain_id: u32) -> Result<u32, DispatchError> {
for (k, v) in Chains::<T>::iter() {
if v == chain_id {
return Ok(k);
}
}
Err(Error::<T>::ForkIdNotFound.into())
}
/// Get a blockchain from the id
fn get_block_chain_from_id(chain_id: u32) -> Result<BlockChain, DispatchError> {
ChainsIndex::<T>::get(chain_id).ok_or(Error::<T>::InvalidChainID.into())
}
/// Get the current best block hash
pub fn get_best_block() -> H256Le {
BestBlock::<T>::get()
}
/// Check if a best block hash is set
fn best_block_exists() -> bool {
BestBlock::<T>::exists()
}
/// get the best block height
pub fn get_best_block_height() -> u32 {
BestBlockHeight::<T>::get()
}
/// Get the current chain counter
fn get_chain_counter() -> u32 {
ChainCounter::<T>::get()
}
/// Get a block hash from a blockchain
///
/// # Arguments
///
/// * `chain_id`: the id of the blockchain to search in
/// * `block_height`: the height of the block header
fn get_block_hash(chain_id: u32, block_height: u32) -> Result<H256Le, DispatchError> {
if !Self::block_exists(chain_id, block_height) {
return Err(Error::<T>::MissingBlockHeight.into());
}
Ok(ChainsHashes::<T>::get(chain_id, block_height))
}
/// Get a block header from its hash
fn get_block_header_from_hash(block_hash: H256Le) -> Result<RichBlockHeader<T::BlockNumber>, DispatchError> {
BlockHeaders::<T>::try_get(block_hash).or(Err(Error::<T>::BlockNotFound.into()))
}
/// Check if a block header exists
pub fn block_header_exists(block_hash: H256Le) -> bool {
BlockHeaders::<T>::contains_key(block_hash)
}
/// Get a block header from
fn get_block_header_from_height(
blockchain: &BlockChain,
block_height: u32,
) -> Result<RichBlockHeader<T::BlockNumber>, DispatchError> {
let block_hash = Self::get_block_hash(blockchain.chain_id, block_height)?;
Self::get_block_header_from_hash(block_hash)
}
/// Storage setter functions
/// Set a new chain with position and id
fn set_chain_from_position_and_id(position: u32, id: u32) {
Chains::<T>::insert(position, id);
}
/// Swap chain elements
fn swap_chain(pos_1: u32, pos_2: u32) {
// swaps the values of two keys
Chains::<T>::swap(pos_1, pos_2)
}
/// Set a new blockchain in ChainsIndex
fn set_block_chain_from_id(id: u32, chain: &BlockChain) {
ChainsIndex::<T>::insert(id, &chain);
}
/// Update a blockchain in ChainsIndex
fn mutate_block_chain_from_id(id: u32, chain: BlockChain) {
ChainsIndex::<T>::mutate(id, |b| *b = Some(chain));
}
/// Set a new block header
fn set_block_header_from_hash(hash: H256Le, header: &RichBlockHeader<T::BlockNumber>) {
BlockHeaders::<T>::insert(hash, header);
}
/// Set a new best block
fn set_best_block(hash: H256Le) {
BestBlock::<T>::put(hash);
}
/// Set a new best block height
fn set_best_block_height(height: u32) {
BestBlockHeight::<T>::put(height);
}
/// Set a new chain counter
fn increment_chain_counter() -> Result<u32, DispatchError> {
let ret = Self::get_chain_counter();
let next_value = ret.checked_add(1).ok_or(Error::<T>::ArithmeticOverflow)?;
ChainCounter::<T>::put(next_value);
Ok(ret)
}
/// Create a new blockchain element with a new chain id
fn create_and_store_blockchain(block_height: u32, basic_block_header: &BlockHeader) -> Result<u32, DispatchError> {
// get a new chain id
let chain_id = Self::increment_chain_counter()?;
// generate an empty blockchain
let blockchain = Self::generate_blockchain(chain_id, block_height, basic_block_header.hash);
// Store a pointer to BlockChain in ChainsIndex
Self::set_block_chain_from_id(blockchain.chain_id, &blockchain);
// Store the reference to the blockchain in Chains
Self::insert_sorted(&blockchain)?;
Self::store_rich_header(basic_block_header.clone(), block_height, blockchain.chain_id);
Ok(blockchain.chain_id)
}
/// Generate the raw blockchain from a chain Id and with a single block
fn generate_blockchain(chain_id: u32, block_height: u32, block_hash: H256Le) -> BlockChain {
// initialize an empty chain
Self::insert_block_hash(chain_id, block_height, block_hash);
BlockChain {
chain_id,
start_height: block_height,
max_height: block_height,
}
}
fn insert_block_hash(chain_id: u32, block_height: u32, block_hash: H256Le) {
ChainsHashes::<T>::insert(chain_id, block_height, block_hash);
}
fn block_exists(chain_id: u32, block_height: u32) -> bool {
ChainsHashes::<T>::contains_key(chain_id, block_height)
}
/// Add a new block header to an existing blockchain
fn extend_blockchain(
block_height: u32,
basic_block_header: &BlockHeader,
prev_blockchain: BlockChain,
) -> Result<BlockChain, DispatchError> {
let mut blockchain = prev_blockchain;
if Self::block_exists(blockchain.chain_id, block_height) {
return Err(Error::<T>::DuplicateBlock.into());
}
Self::insert_block_hash(blockchain.chain_id, block_height, basic_block_header.hash);
blockchain.max_height = block_height;
Self::set_block_chain_from_id(blockchain.chain_id, &blockchain);
Self::store_rich_header(basic_block_header.clone(), block_height, blockchain.chain_id);
Ok(blockchain)
}
// Get require conformations for stable transactions
fn get_stable_transaction_confirmations() -> u32 {
Self::bitcoin_confirmations()
}
// *********************************
// END: Storage getter functions
// *********************************
// Wrapper functions around bitcoin lib for testing purposes
fn verify_merkle_proof(unchecked_transaction: PartialTransactionProof) -> Result<ProofResult, DispatchError> {
unchecked_transaction
.verify_proof()
.map_err(|err| Error::<T>::from(err).into())
}
/// Verifies a Bitcoin block header.
///
/// # Arguments
///
/// * `block_header` - block header
/// * `block_height` - Height of the new block
/// * `prev_block_header` - the previous block header in the chain
///
/// # Returns
///
/// * `Ok(())` iff header is valid
fn verify_block_header(
block_header: &BlockHeader,
block_height: u32,
prev_block_header: RichBlockHeader<T::BlockNumber>,
) -> Result<(), DispatchError> {
// Check that the block header is not yet stored in BTC-Relay
ensure!(
!Self::block_header_exists(block_header.hash),
Error::<T>::DuplicateBlock
);
// Check that the PoW hash satisfies the target set in the block header
ensure!(block_header.hash.as_u256() < block_header.target, Error::<T>::LowDiff);
if Self::disable_difficulty_check() {
return Ok(());
}
let expected_target =
if block_height >= DIFFICULTY_ADJUSTMENT_INTERVAL && block_height % DIFFICULTY_ADJUSTMENT_INTERVAL == 0 {
Self::compute_new_target(&prev_block_header, block_height)?
} else {
prev_block_header.block_header.target
};
ensure!(block_header.target == expected_target, Error::<T>::DiffTargetHeader);
Ok(())
}
/// Computes Bitcoin's PoW retarget algorithm for a given block height
///
/// # Arguments
///
/// * `prev_block_header`: previous block header
/// * `block_height` : block height of new target
fn compute_new_target(
prev_block_header: &RichBlockHeader<T::BlockNumber>,
block_height: u32,
) -> Result<U256, DispatchError> {
// time of last retarget (first block in current difficulty period)
let first_block_time = Self::get_last_retarget_time(prev_block_header.chain_id, block_height)?;
let last_block_time = prev_block_header.block_header.timestamp as u64;
let previous_target = prev_block_header.block_header.target;
// compute new target
Ok(U256::set_compact(
bitcoin::pow::calculate_next_work_required(previous_target, first_block_time, last_block_time)
.map_err(Error::<T>::from)?,