Skip to content

Commit

Permalink
Stage/poc (paritytech#143)
Browse files Browse the repository at this point in the history
* btcbridge CandidateTx and records withdraw cache

* Fix precision and initialization error

* Initialize balance of alice same with activation_per_share

* Tweak initial intention profile

* fix bug for withdraw in canonize, add no_withdrawal flag

* Can not unstake when still in frozen

* Fix some bug

* Tweak session_length and sessions_per_era

* Fix bug: Only candidate confirmed can create new proposal

* Fix unexpect deposit

* Tweak staking fees

* Fix bug: Add unexpect in Candidate to handle unexpect deposit

* Fix/match precision (paritytech#131)

* fix pending order precision

* add tests

* Update genesis_config

* Fix when candidate initialize

* Recover AccountMap to support btc register

* Update genesis BlockHeader

* Fix select utxo must balance > 0

* move best index set before deposit/withdraw in canonize

* Fix build error

* Modify > irr_block as >=

* Fix bug: Only candidate is not confirmed can modifi it status

* Fix btc transaction correlation

* Adjust PCX precision in session reward (paritytech#134)

* Fix/match precision (paritytech#132)

* fix pending order precision

* add tests

* add reserve last

* 1. Fix UTXOList bug (paritytech#136)

2. Update genesis_config irr_block from 0 to 2

* Remove String (paritytech#137)

* Reserve initial nomination (paritytech#138)

* Fix wasm build error

* Init nominees of initial intenions (paritytech#139)

* UTXO only store value > 0

* Init channel (paritytech#140)

* Init channel relationship

* Init genesis intention

* chance channel name (paritytech#141)

* fix fill fee (paritytech#142)

* Tweak parameters
  • Loading branch information
gguoss authored Dec 4, 2018
1 parent eaff0be commit 6ac8fb3
Show file tree
Hide file tree
Showing 16 changed files with 815 additions and 433 deletions.
12 changes: 6 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

171 changes: 93 additions & 78 deletions cxrml/bridge/btc/src/blockchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ use script::Script;
use staking;

use {
AccountMap, BestIndex, BlockHeaderFor, CertCache, DepositCache, HashsForNumber, Module,
NumberForHash, Params, ParamsInfo, Trait, TxProposal,
BestIndex, BlockHeaderFor, CertCache, DepositCache, HashsForNumber, Module, NumberForHash,
Params, ParamsInfo, Trait, TxProposal,
};

use tx::{Proposal, RollBack, TxStorage};
Expand Down Expand Up @@ -165,6 +165,20 @@ impl<T: Trait> Chain<T> {
best_number + 1
},
};

<NumberForHash<T>>::insert(new_best_header.hash.clone(), new_best_header.number);
runtime_io::print("------------");
runtime_io::print(new_best_header.hash.to_vec().as_slice());
<HashsForNumber<T>>::mutate(new_best_header.number, |v| {
let h = new_best_header.hash.clone();
if v.contains(&h) == false {
v.push(h);
}
});
// best chain choose finish
<BestIndex<T>>::put(new_best_header.clone());

// deposit/withdraw handle start
let symbol: Symbol = Module::<T>::SYMBOL.to_vec();
let irr_block = <IrrBlock<T>>::get();
// Deposit
Expand All @@ -174,9 +188,10 @@ impl<T: Trait> Chain<T> {
for (account_id, amount, tx_hash, block_hash) in vec {
match <NumberForHash<T>>::get(block_hash.clone()) {
Some(height) => {
if new_best_header.number > height + irr_block {
if new_best_header.number >= height + irr_block {
runtime_io::print("-----------financial_records deposit");
<financial_records::Module<T>>::deposit(
// TODO handle err
let _ = <financial_records::Module<T>>::deposit(
&account_id,
&symbol,
As::sa(amount),
Expand All @@ -195,75 +210,86 @@ impl<T: Trait> Chain<T> {
}

// Withdraw
let candidate = <TxProposal<T>>::get();
if candidate.is_some() {
let tx = candidate.unwrap();
match <NumberForHash<T>>::get(tx.block_hash) {
Some(height) => {
if new_best_header.number > height + irr_block {
runtime_io::print("----new_best_header.number-----");
let txid = tx.tx.hash();
for output in tx.tx.outputs.iter() {
let script: Script = output.clone().script_pubkey.into();
let script_address =
script.extract_destinations().unwrap_or(Vec::new());
let network_id = <NetworkId<T>>::get();
let network = if network_id == 1 {
keys::Network::Testnet
} else {
keys::Network::Mainnet
};
let address = keys::Address {
kind: script_address[0].kind,
network,
hash: script_address[0].hash.clone(),
};
let account_id = <AddressMap<T>>::get(address);
if account_id.is_some() {
<financial_records::Module<T>>::withdrawal_finish(
&account_id.unwrap(),
&symbol,
Some(txid.as_ref().to_vec()),
);
}
}
let vec = <financial_records::Module<T>>::get_withdraw_cache(&symbol);
if vec.is_some() {
let mut address_vec = Vec::new();
for (account_id, balance) in vec.unwrap() {
let address = <AccountMap<T>>::get(account_id);
if address.is_some() {
address_vec.push((address.unwrap(), balance.as_() as u64));
}
}
let btc_fee = <BtcFee<T>>::get();
if let Err(e) = <Proposal<T>>::create_proposal(address_vec, btc_fee) {
return Err(ChainErr::OtherErr(e));
let len = Module::<T>::tx_proposal_len();
// get last proposal
if len > 0 {
let mut candidate = Module::<T>::tx_proposal(len - 1).unwrap();
// candidate: CandidateTx
if candidate.confirmed == false {
match <NumberForHash<T>>::get(&candidate.block_hash) {
Some(height) => {
if new_best_header.number >= height + irr_block {
runtime_io::print("----new_best_header.number-----");
let txid = candidate.tx.hash();
/*for output in candidate.tx.outputs.iter() {
let script: Script = output.clone().script_pubkey.into();
let script_address =
script.extract_destinations().unwrap_or(Vec::new());
let network_id = <NetworkId<T>>::get();
let network = if network_id == 1 {
keys::Network::Testnet
} else {
keys::Network::Mainnet
};
let address = keys::Address {
kind: script_address[0].kind,
network,
hash: script_address[0].hash.clone(),
};*/
//let account_id = <AddressMap<T>>::get(address);
//if account_id.is_some() {
for (account_id, _) in candidate.outs.clone() {
// TODO handle err
let _ = <financial_records::Module<T>>::withdrawal_finish(
&account_id,
&symbol,
Some(txid.as_ref().to_vec()),
);
}
//}
candidate.confirmed = true;
// mark this tx withdraw finish!
TxProposal::<T>::insert(len - 1, candidate);
}
} else {
<TxProposal<T>>::kill();
}
None => {}
}
}
None => {}
}

// case 0: 当刚启动时Candidate lenth = 0 时
// case 1: 所有提现交易都是正常逻辑执行,会confirmed.
// case 2: 非正常逻辑提现,candidate.unexpect 会在handle_input时设置,
// 标记该链上这笔proposal由于BTC 托管人没有按着正常逻辑签名广播, 该proposal可能永远不会confirmed.
// 所以开始重新创建proposal.
if len == 0 {
// no withdraw cache would return None
if let Some(indexs) = financial_records::Module::<T>::withdrawal_cache_indexs(&symbol) {
let btc_fee = <BtcFee<T>>::get();
if let Err(e) = <Proposal<T>>::create_proposal(indexs, btc_fee) {
return Err(ChainErr::OtherErr(e));
}
}

}
} else {
let vec = <financial_records::Module<T>>::get_withdraw_cache(&symbol);
if vec.is_some() {
runtime_io::print("-----------first withdraw");
let mut address_vec = Vec::new();
for (account_id, balance) in vec.unwrap() {
let address = <AccountMap<T>>::get(account_id);
if address.is_some() {
address_vec.push((address.unwrap(), balance.as_() as u64));
}
}
let btc_fee = <BtcFee<T>>::get();
if let Err(e) = <Proposal<T>>::create_proposal(address_vec, btc_fee) {
return Err(ChainErr::OtherErr(e));
}
if len > 0 {
let candidate = Module::<T>::tx_proposal(len - 1).unwrap();
if candidate.confirmed || candidate.unexpect {
// no withdraw cache would return None
if let Some(indexs) = financial_records::Module::<T>::withdrawal_cache_indexs(&symbol) {
let btc_fee = <BtcFee<T>>::get();
if let Err(e) = <Proposal<T>>::create_proposal(indexs, btc_fee) {
return Err(ChainErr::OtherErr(e));
}
}
}
}
}
// let candidate = <TxProposal<T>>::get();
// if candidate.is_some() {
// let tx = candidate.unwrap();
// } else {
//
// }
// SendCert
if let Some(cert_info) = <CertCache<T>>::take() {
runtime_io::print("------CertCache take");
Expand All @@ -272,17 +298,6 @@ impl<T: Trait> Chain<T> {
}
}

<NumberForHash<T>>::insert(new_best_header.hash.clone(), new_best_header.number);
runtime_io::print("------------");
runtime_io::print(new_best_header.hash.to_vec().as_slice());
<HashsForNumber<T>>::mutate(new_best_header.number, |v| {
let h = new_best_header.hash.clone();
if v.contains(&h) == false {
v.push(h);
}
});

<BestIndex<T>>::put(new_best_header);
Ok(())
}
/// Rollbacks single best block
Expand Down
27 changes: 24 additions & 3 deletions cxrml/bridge/btc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ mod b58;
mod blockchain;
mod tx;
mod verify_header;
mod utils;

use chain::{BlockHeader, Transaction as BTCTransaction};
use codec::Decode;
Expand Down Expand Up @@ -189,10 +190,25 @@ impl Default for TxType {

#[derive(PartialEq, Clone, Encode, Decode)]
pub struct CandidateTx<AccountId: Parameter + Ord + Default> {
pub proposer: Vec<AccountId>,
pub tx: BTCTransaction,
pub perfection: bool,
pub unexpect: bool,
pub confirmed: bool,
pub block_hash: H256,
pub outs: Vec<(AccountId, u32)>,
pub proposers: Vec<AccountId>,
}

impl<AccountId: Parameter + Ord + Default> CandidateTx<AccountId> {
pub fn new(tx: BTCTransaction, outs: Vec<(AccountId, u32)>) -> Self {
CandidateTx {
tx,
unexpect: false,
confirmed: false,
block_hash: Default::default(),
outs,
proposers: Vec::new(),
}
}
}

#[derive(PartialEq, Clone, Encode, Decode)]
Expand Down Expand Up @@ -261,7 +277,12 @@ decl_storage! {
pub BlockTxids get(block_txids): map H256 => Vec<H256>;
pub AddressMap get(address_map): map Address => Option<T::AccountId>;
pub AccountMap get(account_map): map T::AccountId => Option<keys::Address>;
pub TxProposal get(tx_proposal): Option<CandidateTx<T::AccountId>>;
/// withdrawal tx outs for account, tx_hash => outs ( out index => withdrawal account )
// pub WithdrawalOutsAccount get(withdrawal_outs_account): map H256 => Vec<(u32, T::AccountId)>

pub TxProposalLen get(tx_proposal_len): u32;
pub TxProposal get(tx_proposal): map u32 => Option<CandidateTx<T::AccountId>>;

/// account, btc value, txhash, blockhash
pub DepositCache get(deposit_cache): Option<Vec<(T::AccountId, u64, H256, H256)>>;
/// tx_hash, utxo index, btc value, blockhash
Expand Down
Loading

0 comments on commit 6ac8fb3

Please sign in to comment.