Skip to content

Commit 066f436

Browse files
authored
Refactor/binding addr (paritytech#176)
* let to_base58 accept bytes ref * let BtcAddress be Vec<u8> * refactor addrbinding * integrate staking
1 parent 0573e8a commit 066f436

File tree

20 files changed

+271
-154
lines changed

20 files changed

+271
-154
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

primitives/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ pub type Token = Vec<u8>;
5757
pub type Name = Vec<u8>;
5858
pub type Precision = u8;
5959
pub type AddrStr = Vec<u8>;
60+
pub type ChainAddress = Vec<u8>;
6061
pub type AssetId = u32;
6162

6263
/// Referral ID of validator.

runtime/src/lib.rs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,8 @@ pub use pallet_timestamp::Call as TimestampCall;
6565
pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment};
6666

6767
pub use chainx_primitives::{
68-
AccountId, AccountIndex, AddrStr, AssetId, Balance, BlockNumber, Hash, Index, Moment, Name,
69-
ReferralId, Signature, Token,
68+
AccountId, AccountIndex, AddrStr, AssetId, Balance, BlockNumber, ChainAddress, Hash, Index,
69+
Moment, Name, ReferralId, Signature, Token,
7070
};
7171
pub use xp_runtime::Memo;
7272

@@ -721,6 +721,7 @@ impl xpallet_gateway_bitcoin::Trait for Runtime {
721721
type TrusteeSessionProvider = trustees::bitcoin::BtcTrusteeSessionManager<Runtime>;
722722
type TrusteeMultiSigProvider = trustees::bitcoin::BtcTrusteeMultisig<Runtime>;
723723
type Channel = XGatewayCommon;
724+
type AddrBinding = XGatewayCommon;
724725
}
725726

726727
impl xpallet_dex_spot::Trait for Runtime {
@@ -759,18 +760,18 @@ impl xpallet_mining_staking::Trait for Runtime {
759760
xpallet_mining_staking::SimpleValidatorRewardPotAccountDeterminer<Runtime>;
760761
}
761762

762-
pub struct DummyReferralGetter;
763-
impl xpallet_mining_asset::GatewayInterface<AccountId> for DummyReferralGetter {
764-
fn referral_of(_who: &AccountId, _asset_id: AssetId) -> Option<AccountId> {
765-
// FIXME impl this in gateway
766-
None
763+
pub struct ReferralGetter;
764+
impl xpallet_mining_asset::GatewayInterface<AccountId> for ReferralGetter {
765+
fn referral_of(who: &AccountId, asset_id: AssetId) -> Option<AccountId> {
766+
use xpallet_gateway_common::traits::ChannelBinding;
767+
XGatewayCommon::get_binding_info(&asset_id, who)
767768
}
768769
}
769770

770771
impl xpallet_mining_asset::Trait for Runtime {
771772
type Event = Event;
772773
type StakingInterface = Self;
773-
type GatewayInterface = DummyReferralGetter;
774+
type GatewayInterface = ReferralGetter;
774775
type TreasuryAccount = SimpleTreasuryAccount;
775776
type DetermineRewardPotAccount =
776777
xpallet_mining_asset::SimpleAssetRewardPotAccountDeterminer<Runtime>;
@@ -1031,6 +1032,10 @@ impl_runtime_apis! {
10311032
}
10321033

10331034
impl xpallet_gateway_common_rpc_runtime_api::XGatewayCommonApi<Block, AccountId, Balance> for Runtime {
1035+
fn bound_addrs(who: AccountId) -> BTreeMap<Chain, Vec<ChainAddress>> {
1036+
XGatewayCommon::bound_addrs(&who)
1037+
}
1038+
10341039
fn withdrawal_limit(asset_id: AssetId) -> Result<WithdrawalLimit<Balance>, DispatchError> {
10351040
XGatewayCommon::withdrawal_limit(&asset_id)
10361041
}

scripts/chainx-js/chainx_types_manual.json

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -126,24 +126,13 @@
126126
"hot_address": "BtcTrusteeAddrInfo",
127127
"cold_address": "BtcTrusteeAddrInfo"
128128
},
129-
"AddressHash": "H160",
130129
"BtcNetwork": {
131130
"_enum": [
132131
"Mainnet",
133132
"Testnet"
134133
]
135134
},
136-
"BtcAddrType": {
137-
"_enum": [
138-
"P2PKH",
139-
"P2SH"
140-
]
141-
},
142-
"BtcAddress": {
143-
"kind": "BtcAddrType",
144-
"network": "BtcNetwork",
145-
"hash": "AddressHash"
146-
},
135+
"BtcAddress": "Text",
147136
"BtcCompact": "u32",
148137
"BtcHeader": {
149138
"version": "u32",

scripts/chainx-js/res/chainx_types.json

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@
150150
"TradingPairId": "u32",
151151
"TradingHistoryIndex": "u64",
152152
"PriceFluctuation": "u32",
153+
"BtcAddress": "Text",
153154
"FixedAssetPower": "u32",
154155
"StakingRequirement": "u32",
155156
"Precision": "u8",
@@ -191,11 +192,6 @@
191192
]
192193
},
193194
"AssetRestrictions": "u32",
194-
"BtcAddress": {
195-
"kind": "BtcAddrType",
196-
"network": "BtcNetwork",
197-
"hash": "AddressHash"
198-
},
199195
"BtcHeader": {
200196
"version": "u32",
201197
"previousHeaderHash": "H256",
@@ -302,13 +298,6 @@
302298
"hotAddress": "BtcTrusteeAddrInfo",
303299
"coldAddress": "BtcTrusteeAddrInfo"
304300
},
305-
"AddressHash": "H160",
306-
"BtcAddrType": {
307-
"_enum": [
308-
"P2PKH",
309-
"P2SH"
310-
]
311-
},
312301
"BtcCompact": "u32",
313302
"BtcTransaction": "Vec<u8>",
314303
"BtcHeaderIndex": {

xpallets/gateway/bitcoin/src/lib.rs

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use frame_system::{self as system, ensure_root, ensure_signed};
2929
use chainx_primitives::{AddrStr, AssetId};
3030
use xpallet_assets::{Chain, ChainT, WithdrawalLimit};
3131
use xpallet_gateway_common::{
32-
traits::{ChannelBinding, Extractable, TrusteeSession},
32+
traits::{AddrBinding, ChannelBinding, Extractable, TrusteeSession},
3333
trustees::bitcoin::BtcTrusteeAddrInfo,
3434
};
3535
use xpallet_support::{
@@ -39,7 +39,7 @@ use xpallet_support::{
3939

4040
// light-bitcoin
4141
use btc_chain::Transaction;
42-
use btc_keys::{Address as BtcAddress, DisplayLayout};
42+
use btc_keys::{Address, DisplayLayout};
4343
use btc_ser::deserialize;
4444
// re-export
4545
pub use btc_chain::BlockHeader as BtcHeader;
@@ -48,12 +48,12 @@ pub use btc_keys::Network as BtcNetwork;
4848
pub use btc_primitives::h256_conv_endian_from_str;
4949
pub use btc_primitives::{Compact, H256, H264};
5050

51+
pub use self::types::{BtcAddress, BtcParams, BtcTxVerifier, BtcWithdrawalProposal};
5152
use self::types::{
5253
BtcDepositCache, BtcHeaderIndex, BtcHeaderInfo, BtcRelayedTx, BtcTxResult, BtcTxState,
5354
};
54-
pub use self::types::{BtcParams, BtcTxVerifier, BtcWithdrawalProposal};
5555
use crate::trustee::get_trustee_address_pair;
56-
use crate::tx::{remove_pending_deposit, utils::addr2vecu8};
56+
use crate::tx::remove_pending_deposit;
5757

5858
pub type BalanceOf<T> = <<T as xpallet_assets::Trait>::Currency as Currency<
5959
<T as frame_system::Trait>::AccountId,
@@ -70,6 +70,7 @@ pub trait Trait:
7070
type TrusteeSessionProvider: TrusteeSession<Self::AccountId, BtcTrusteeAddrInfo>;
7171
type TrusteeMultiSigProvider: MultiSig<Self::AccountId>;
7272
type Channel: ChannelBinding<Self::AccountId>;
73+
type AddrBinding: AddrBinding<Self::AccountId, BtcAddress>;
7374
}
7475

7576
decl_error! {
@@ -189,11 +190,6 @@ decl_storage! {
189190
pub TxState get(fn tx_state): map hasher(identity) H256 => Option<BtcTxState>;
190191
/// unclaimed deposit info, addr => tx_hash, btc value,
191192
pub PendingDeposits get(fn pending_deposits): map hasher(blake2_128_concat) BtcAddress => Vec<BtcDepositCache>;
192-
// todo may move binding to common
193-
///
194-
pub AddressBinding get(fn address_binding): map hasher(blake2_128_concat) BtcAddress => Option<T::AccountId>;
195-
///
196-
pub BoundAddressOf get(fn bound_address_of): map hasher(blake2_128_concat) T::AccountId => Vec<BtcAddress>;
197193

198194
/// withdrawal tx outs for account, tx_hash => outs ( out index => withdrawal account )
199195
pub WithdrawalProposal get(fn withdrawal_proposal): Option<BtcWithdrawalProposal<T::AccountId>>;
@@ -349,7 +345,7 @@ decl_module! {
349345
if let Some(w) = who {
350346
remove_pending_deposit::<T>(&addr, &w);
351347
} else {
352-
info!("[remove_pending]|release pending deposit directly, not deposit to someone|addr:{:?}", str!(addr2vecu8(&addr)));
348+
info!("[remove_pending]|release pending deposit directly, not deposit to someone|addr:{:?}", str!(&addr));
353349
PendingDeposits::remove(&addr);
354350
}
355351
Ok(())
@@ -417,15 +413,13 @@ impl<T: Trait> ChainT<BalanceOf<T>> for Module<T> {
417413

418414
fn check_addr(addr: &[u8], _: &[u8]) -> DispatchResult {
419415
// this addr is base58 addr
420-
let address = Self::verify_btc_address(addr)
421-
.map_err(|_| Error::<T>::InvalidAddress)
422-
.map_err(|e| {
423-
error!(
424-
"[verify_btc_address]|failed, source addr is:{:?}",
425-
try_addr!(addr)
426-
);
427-
e
428-
})?;
416+
let address = Self::verify_btc_address(addr).map_err(|e| {
417+
error!(
418+
"[verify_btc_address]|failed, source addr is:{:?}",
419+
try_addr!(addr)
420+
);
421+
e
422+
})?;
429423

430424
let (hot_addr, cold_addr) = get_trustee_address_pair::<T>()?;
431425
if address == hot_addr || address == cold_addr {
@@ -451,9 +445,9 @@ impl<T: Trait> ChainT<BalanceOf<T>> for Module<T> {
451445
}
452446

453447
impl<T: Trait> Module<T> {
454-
pub fn verify_btc_address(data: &[u8]) -> result::Result<BtcAddress, DispatchError> {
448+
pub fn verify_btc_address(data: &[u8]) -> result::Result<Address, DispatchError> {
455449
let r = base58::from(data).map_err(|_| Error::<T>::InvalidBase58)?;
456-
let addr = BtcAddress::from_layout(&r).map_err(|_| Error::<T>::InvalidAddr)?;
450+
let addr = Address::from_layout(&r).map_err(|_| Error::<T>::InvalidAddr)?;
457451
Ok(addr)
458452
}
459453

xpallets/gateway/bitcoin/src/trustee.rs

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use xpallet_gateway_common::{
2121
};
2222
use xpallet_support::{debug, error, info, RUNTIME_TARGET};
2323

24-
use crate::tx::utils::{ensure_identical, parse_output_addr};
24+
use crate::tx::utils::{addr2vecu8, ensure_identical, parse_output_addr};
2525
use crate::tx::validator::parse_and_check_signed_tx;
2626
use crate::types::{BtcWithdrawalProposal, VoteResult};
2727
use crate::{Error, Module, RawEvent, Trait, WithdrawalProposal};
@@ -40,21 +40,31 @@ fn trustee_addr_info_pair<T: Trait>(
4040

4141
#[inline]
4242
pub fn get_trustee_address_pair<T: Trait>() -> Result<(Address, Address), DispatchError> {
43-
trustee_addr_info_pair::<T>().map(|(hot_info, cold_info)| (hot_info.addr, cold_info.addr))
43+
trustee_addr_info_pair::<T>().map(|(hot_info, cold_info)| {
44+
(
45+
Module::<T>::verify_btc_address(&hot_info.addr)
46+
.expect("should not parse error from storage data; qed"),
47+
Module::<T>::verify_btc_address(&cold_info.addr)
48+
.expect("should not parse error from storage data; qed"),
49+
)
50+
})
4451
}
4552

4653
#[inline]
4754
pub fn get_last_trustee_address_pair<T: Trait>() -> Result<(Address, Address), DispatchError> {
4855
T::TrusteeSessionProvider::last_trustee_session().map(|session_info| {
4956
(
50-
session_info.hot_address.addr,
51-
session_info.cold_address.addr,
57+
Module::<T>::verify_btc_address(&session_info.hot_address.addr)
58+
.expect("should not parse error from storage data; qed"),
59+
Module::<T>::verify_btc_address(&session_info.cold_address.addr)
60+
.expect("should not parse error from storage data; qed"),
5261
)
5362
})
5463
}
5564

5665
pub fn get_hot_trustee_address<T: Trait>() -> Result<Address, DispatchError> {
57-
trustee_addr_info_pair::<T>().map(|(addr_info, _)| addr_info.addr)
66+
trustee_addr_info_pair::<T>()
67+
.and_then(|(addr_info, _)| Module::<T>::verify_btc_address(&addr_info.addr))
5868
}
5969

6070
pub fn get_hot_trustee_redeem_script<T: Trait>() -> Result<Script, DispatchError> {
@@ -418,7 +428,7 @@ fn create_multi_address<T: Trait>(
418428
};
419429
let script_bytes: Bytes = redeem_script.into();
420430
Some(BtcTrusteeAddrInfo {
421-
addr,
431+
addr: addr2vecu8(&addr),
422432
redeem_script: script_bytes.into(),
423433
})
424434
}
@@ -462,8 +472,7 @@ fn check_withdraw_tx<T: Trait>(tx: &Transaction, withdrawal_id_list: &[u32]) ->
462472
.ok_or(Error::<T>::NoWithdrawalRecord)?;
463473
// record.addr() is base58
464474
// verify btc address would conveRelayedTx a base58 addr to Address
465-
let addr: Address = Module::<T>::verify_btc_address(&record.addr())
466-
.map_err(|_| Error::<T>::InvalidPublicKey)?;
475+
let addr: Address = Module::<T>::verify_btc_address(&record.addr())?;
467476

468477
appl_withdrawal_list.push((addr, record.balance().saturated_into() as u64));
469478
}

xpallets/gateway/bitcoin/src/tx/mod.rs

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use sp_std::{fmt::Debug, prelude::*, result};
1515
// ChainX
1616
use chainx_primitives::{AssetId, Name};
1717
use xpallet_assets::ChainT;
18-
use xpallet_gateway_common::traits::{ChannelBinding, Extractable};
18+
use xpallet_gateway_common::traits::{AddrBinding, ChannelBinding, Extractable};
1919
use xpallet_support::{debug, error, info, str, warn, RUNTIME_TARGET};
2020

2121
// light-bitcoin
@@ -35,12 +35,9 @@ pub use self::validator::validate_transaction;
3535
use crate::trustee::{get_last_trustee_address_pair, get_trustee_address_pair};
3636
use crate::tx::utils::{addr2vecu8, ensure_identical};
3737
use crate::types::{
38-
AccountInfo, BtcDepositCache, BtcTxResult, BtcTxState, DepositInfo, MetaTxType,
39-
};
40-
use crate::{
41-
AddressBinding, BalanceOf, BoundAddressOf, Module, PendingDeposits, RawEvent, Trait,
42-
WithdrawalProposal,
38+
AccountInfo, BtcAddress, BtcDepositCache, BtcTxResult, BtcTxState, DepositInfo, MetaTxType,
4339
};
40+
use crate::{BalanceOf, Module, PendingDeposits, RawEvent, Trait, WithdrawalProposal};
4441

4542
pub fn process_tx<T: Trait>(
4643
tx: Transaction,
@@ -295,10 +292,11 @@ fn deposit<T: Trait>(hash: H256, deposit_info: DepositInfo<T::AccountId>) -> Btc
295292
let account_info = match deposit_info.op_return {
296293
Some((accountid, channel_name)) => {
297294
if let Some(addr) = deposit_info.input_addr {
295+
let addr = addr2vecu8(&addr);
298296
// remove old unbinding deposit info
299297
remove_pending_deposit::<T>(&addr, &accountid);
300298
// update or override binding info
301-
update_binding::<T>(&addr, &accountid);
299+
T::AddrBinding::update_binding(Module::<T>::chain(), addr, accountid.clone());
302300
} else {
303301
// no input addr
304302
debug!("[deposit]|no input addr for this deposit tx, but has opreturn to get accountid|tx_hash:{:?}|who:{:?}", hash, accountid);
@@ -308,7 +306,8 @@ fn deposit<T: Trait>(hash: H256, deposit_info: DepositInfo<T::AccountId>) -> Btc
308306
None => {
309307
if let Some(addr) = deposit_info.input_addr {
310308
// no opreturn, use addr to get accountid
311-
match Module::<T>::address_binding(&addr) {
309+
let addr_bytes = addr2vecu8(&addr);
310+
match T::AddrBinding::get_binding(Module::<T>::chain(), addr_bytes) {
312311
Some(accountid) => AccountInfo::Account((accountid, None)),
313312
None => AccountInfo::Address(addr.clone()),
314313
}
@@ -361,7 +360,7 @@ fn deposit_token<T: Trait>(who: &T::AccountId, balance: u64) -> DispatchResult {
361360
})?;
362361
Ok(())
363362
}
364-
363+
/*
365364
fn update_binding<T: Trait>(address: &Address, who: &T::AccountId) {
366365
if let Some(accountid) = AddressBinding::<T>::get(&address) {
367366
if &accountid != who {
@@ -391,8 +390,8 @@ fn update_binding<T: Trait>(address: &Address, who: &T::AccountId) {
391390
);
392391
AddressBinding::<T>::insert(address, who.clone());
393392
}
394-
395-
pub fn remove_pending_deposit<T: Trait>(input_address: &Address, who: &T::AccountId) {
393+
*/
394+
pub fn remove_pending_deposit<T: Trait>(input_address: &BtcAddress, who: &T::AccountId) {
396395
// notice this would delete this cache
397396
let records = PendingDeposits::take(input_address);
398397
for r in records {
@@ -407,23 +406,25 @@ pub fn remove_pending_deposit<T: Trait>(input_address: &Address, who: &T::Accoun
407406
who.clone(),
408407
r.balance.saturated_into(),
409408
r.txid,
410-
addr2vecu8(input_address),
409+
input_address.clone(),
411410
));
412411
}
413412
}
414413

415414
fn insert_pending_deposit<T: Trait>(input_address: &Address, txid: &H256, balance: u64) {
415+
let addr_bytes = addr2vecu8(input_address);
416+
416417
let cache = BtcDepositCache {
417418
txid: txid.clone(),
418419
balance,
419420
};
420421

421-
PendingDeposits::mutate(input_address, |list| {
422+
PendingDeposits::mutate(&addr_bytes, |list| {
422423
if !list.contains(&cache) {
423424
native::debug!(
424425
target: RUNTIME_TARGET,
425426
"[insert_pending_deposit]|Add pending deposit|address:{:?}|txhash:{:}|balance:{:}",
426-
str!(addr2vecu8(input_address)),
427+
str!(addr_bytes),
427428
txid,
428429
balance
429430
);

0 commit comments

Comments
 (0)