Skip to content
This repository has been archived by the owner on Jul 27, 2022. It is now read-only.

Commit

Permalink
Merge #613 #615
Browse files Browse the repository at this point in the history
613: Problem: (CRO-603) Bech32 address always encoded with initialized network r=tomtau a=calvinlauco

Solution: Add network argument to to_cro()

---
`to_cro()` always encoded with the initialized network, making it mpossible to encode to arbitrary network

615: Bump serde_json from 1.0.41 to 1.0.42 r=tomtau a=dependabot-preview[bot]

Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.41 to 1.0.42.
<details>
<summary>Release notes</summary>

*Sourced from [serde_json's releases](https://github.com/serde-rs/json/releases).*

> ## v1.0.42
> - Add `impl From<()> for Value` which produces Value::Null ([#585](https://github-redirect.dependabot.com/serde-rs/json/issues/585), thanks [@&#8203;Nilix007](https://github.com/Nilix007))
</details>
<details>
<summary>Commits</summary>

- [`f0471e6`](serde-rs/json@f0471e6) Release 1.0.42
- [`bf8cc66`](serde-rs/json@bf8cc66) Merge pull request [#585](https://github-redirect.dependabot.com/serde-rs/json/issues/585) from Nilix007/add_from_unit_for_value
- [`ff5a59c`](serde-rs/json@ff5a59c) Add `impl From\<()> for Value`
- [`7dda823`](serde-rs/json@7dda823) Merge pull request [#580](https://github-redirect.dependabot.com/serde-rs/json/issues/580) from andrisak/docs_read_without_blocking_eof
- [`2065227`](serde-rs/json@2065227) Added missing fake_main [#522](https://github-redirect.dependabot.com/serde-rs/json/issues/522)
- [`3a5aba3`](serde-rs/json@3a5aba3) Fix for Document how to deserialize from a prefix of an io::Read without bloc...
- [`0c72820`](serde-rs/json@0c72820) Ignore must_use_candidate pedantic lint
- [`265f1ca`](serde-rs/json@265f1ca) Upgrade to rustversion 1.0
- [`b63ad14`](serde-rs/json@b63ad14) Address needless_doctest_main lint
- See full diff in [compare view](serde-rs/json@v1.0.41...v1.0.42)
</details>
<br />

[![Dependabot compatibility score](https://api.dependabot.com/badges/compatibility_score?dependency-name=serde_json&package-manager=cargo&previous-version=1.0.41&new-version=1.0.42)](https://dependabot.com/compatibility-score.html?dependency-name=serde_json&package-manager=cargo&previous-version=1.0.41&new-version=1.0.42)

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
- `@dependabot use these labels` will set the current labels as the default for future PRs for this repo and language
- `@dependabot use these reviewers` will set the current reviewers as the default for future PRs for this repo and language
- `@dependabot use these assignees` will set the current assignees as the default for future PRs for this repo and language
- `@dependabot use this milestone` will set the current milestone as the default for future PRs for this repo and language
- `@dependabot badge me` will comment on this PR with code to add a "Dependabot enabled" badge to your readme

Additionally, you can set the following in your Dependabot [dashboard](https://app.dependabot.com):
- Update frequency (including time of day and day of week)
- Pull request limits (per update run and/or open at any time)
- Out-of-range updates (receive only lockfile updates, if desired)
- Security updates (receive only security updates, if desired)



</details>

Co-authored-by: Calvin Lau <calvinlauco@gmail.com>
Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
  • Loading branch information
3 people committed Nov 25, 2019
3 parents 9bcfd17 + 1e6e255 + 99a3ea6 commit 9d59ae6
Show file tree
Hide file tree
Showing 8 changed files with 75 additions and 62 deletions.
24 changes: 12 additions & 12 deletions Cargo.lock

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

33 changes: 21 additions & 12 deletions chain-core/src/init/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ use std::fmt;
use tiny_keccak::{Hasher, Keccak};

use crate::common::{H256, HASH_SIZE_256};
#[cfg(feature = "bech32")]
use crate::init::network::{get_bech32_human_part_from_network, Network};

#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Expand All @@ -49,8 +51,8 @@ impl ::std::error::Error for CroAddressError {}
// DCRO: devnet/regnet transfer
#[cfg(feature = "bech32")]
pub trait CroAddress<T> {
fn to_cro(&self) -> Result<String, CroAddressError>;
fn from_cro(encoded: &str) -> Result<T, CroAddressError>;
fn to_cro(&self, network: Network) -> Result<String, CroAddressError>;
fn from_cro(encoded: &str, network: Network) -> Result<T, CroAddressError>;
}

/// Keccak-256 crypto hash length in bytes
Expand Down Expand Up @@ -187,18 +189,18 @@ impl RedeemAddress {

#[cfg(all(feature = "bech32", feature = "hex"))]
impl CroAddress<RedeemAddress> for RedeemAddress {
fn to_cro(&self) -> Result<String, CroAddressError> {
fn to_cro(&self, network: Network) -> Result<String, CroAddressError> {
let checked_data: Vec<u5> = self.0.to_vec().to_base32();
let encoded = bech32::encode(super::network::get_bech32_human_part(), checked_data)
.expect("bech32 crms encoding");
let encoded = bech32::encode(get_bech32_human_part_from_network(network), checked_data)
.expect("bech32 encoding error");
Ok(encoded.to_string())
}

fn from_cro(encoded: &str) -> Result<Self, CroAddressError> {
fn from_cro(encoded: &str, network: Network) -> Result<Self, CroAddressError> {
let (human_part, u5_bytes) =
bech32::decode(encoded).map_err(|e| CroAddressError::Bech32Error(e.to_string()))?;

if human_part != super::network::get_bech32_human_part() {
if human_part != get_bech32_human_part_from_network(network) {
return Err(CroAddressError::InvalidNetwork);
}

Expand Down Expand Up @@ -384,10 +386,17 @@ mod tests {

#[test]
fn should_be_correct_textual_address() {
let a = RedeemAddress::from_str("0x0e7c045110b8dbf29765047380898919c5cb56f4").unwrap();
let b = a.to_cro().unwrap();
assert_eq!(b.to_string(), "dcro1pe7qg5gshrdl99m9q3ecpzvfr8zuk4h5rm547c");
let c = RedeemAddress::from_cro(&b).unwrap();
assert_eq!(c, a);
let network = Network::Devnet;

let redeem_address =
RedeemAddress::from_str("0x0e7c045110b8dbf29765047380898919c5cb56f4").unwrap();
let bech32_address = redeem_address.to_cro(network).unwrap();
assert_eq!(
bech32_address.to_string(),
"dcro1pe7qg5gshrdl99m9q3ecpzvfr8zuk4h5rm547c"
);

let restored_redeem_address = RedeemAddress::from_cro(&bech32_address, network).unwrap();
assert_eq!(redeem_address, restored_redeem_address);
}
}
18 changes: 11 additions & 7 deletions chain-core/src/init/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,20 +61,24 @@ pub fn get_network() -> Network {

/// Given the chosen network, it returns the human readable part of Bech32 address
pub fn get_bech32_human_part() -> &'static str {
unsafe {
match chosen_network::NETWORK {
Network::Mainnet => "cro",
Network::Testnet => "tcro",
Network::Devnet => "dcro",
}
get_bech32_human_part_from_network(get_network())
}

/// Returns the human readable part of Bech32 address of the provided network
pub fn get_bech32_human_part_from_network(network: Network) -> &'static str {
match network {
Network::Mainnet => "cro",
Network::Testnet => "tcro",
Network::Devnet => "dcro",
}
}

/// Given the chosen network, it returns bip44 cointype
pub fn get_bip44_coin_type() -> u32 {
get_bip44_coin_type_from_network(get_network())
}

/// Given the chosen network, it returns bip44 cointype
/// Returns bip44 cointype of the provided network
/// 1 0x80000001 Testnet (all coins)
/// 394 0x8000018a CRO Crypto.com Chain
pub fn get_bip44_coin_type_from_network(network: Network) -> u32 {
Expand Down
54 changes: 26 additions & 28 deletions chain-core/src/tx/data/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::init::address::{CroAddress, CroAddressError};
use bech32::{self, u5, FromBase32, ToBase32};

#[cfg(all(feature = "bech32", feature = "hex"))]
use crate::init::network::get_bech32_human_part;
use crate::init::network::{get_bech32_human_part_from_network, get_network, Network};

/// TODO: opaque types?
type TreeRoot = H256;
Expand All @@ -27,43 +27,38 @@ pub enum ExtendedAddr {
OrTree(TreeRoot),
}

#[cfg(all(feature = "bech32", feature = "hex"))]
impl ExtendedAddr {
fn get_string(&self, hash: TreeRoot) -> String {
let checked_data: Vec<u5> = hash.to_vec().to_base32();

bech32::encode(get_bech32_human_part(), checked_data)
.expect("bech32 should be successful in ExtendedAddr get_string")
}
}

#[cfg(all(feature = "bech32", feature = "hex"))]
impl CroAddress<ExtendedAddr> for ExtendedAddr {
fn to_cro(&self) -> Result<String, CroAddressError> {
fn to_cro(&self, network: Network) -> Result<String, CroAddressError> {
match self {
ExtendedAddr::OrTree(hash) => {
let encoded = self.get_string(*hash);
let checked_data: Vec<u5> = hash.to_vec().to_base32();
let encoded = bech32::encode(
get_bech32_human_part_from_network(network),
checked_data,
)
.expect("bech32 encoding error");
Ok(encoded.to_string())
}
}
}

fn from_cro(encoded: &str) -> Result<Self, CroAddressError> {
fn from_cro(encoded: &str, _network: Network) -> Result<Self, CroAddressError> {
bech32::decode(encoded)
.map_err(|e| CroAddressError::Bech32Error(e.to_string()))
.and_then(|a| Vec::from_base32(&a.1).map_err(|_e| CroAddressError::ConvertError))
.and_then(|src| {
let mut a: TreeRoot = [0 as u8; 32];
a.copy_from_slice(&src.as_slice());
Ok(ExtendedAddr::OrTree(a))
.and_then(|decoded| Vec::from_base32(&decoded.1).map_err(|_e| CroAddressError::ConvertError))
.and_then(|hash| {
let mut tree_root_hash: TreeRoot = [0 as u8; 32];
tree_root_hash.copy_from_slice(&hash.as_slice());
Ok(ExtendedAddr::OrTree(tree_root_hash))
})
}
}

#[cfg(all(feature = "bech32", feature = "hex"))]
impl fmt::Display for ExtendedAddr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_cro().unwrap())
write!(f, "{}", self.to_cro(get_network()).unwrap())
}
}

Expand All @@ -72,7 +67,7 @@ impl FromStr for ExtendedAddr {
type Err = CroAddressError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
ExtendedAddr::from_cro(s).map_err(|_e| CroAddressError::ConvertError)
ExtendedAddr::from_cro(s, get_network()).map_err(|_e| CroAddressError::ConvertError)
}
}

Expand All @@ -82,19 +77,22 @@ mod test {

#[test]
fn should_be_correct_textual_address() {
let mut ar = [0; 32];
ar.copy_from_slice(
let network = Network::Devnet;

let mut tree_root_hash = [0; 32];
tree_root_hash.copy_from_slice(
&hex::decode("0e7c045110b8dbf29765047380898919c5cb56f400112233445566778899aabb")
.unwrap(),
);
let a = ExtendedAddr::OrTree(ar);
let b = a.to_cro().unwrap();
let extended_addr = ExtendedAddr::OrTree(tree_root_hash);
let bech32_addr = extended_addr.to_cro(network).unwrap();
assert_eq!(
b,
bech32_addr,
"dcro1pe7qg5gshrdl99m9q3ecpzvfr8zuk4h5qqgjyv6y24n80zye42as88x8tg"
);
let c = ExtendedAddr::from_cro(&b).unwrap();
assert_eq!(c, a);

let restored_extended_addr = ExtendedAddr::from_cro(&bech32_addr, network).unwrap();
assert_eq!(restored_extended_addr, extended_addr);
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion client-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ rustls = {version = "0.16", features = ["dangerous_configuration"]}
yasna = { version = "0.3.0", features = ["bit-vec", "num-bigint", "chrono"] }
bit-vec = "0.6.1"
num-bigint = "0.2.3"
serde_json = "1.0.41"
serde_json = "1.0.42"
uuid = { version = "0.8.1", features = ["v4"] }
websocket = "0.24.0"
jsonrpc-core = "14.0"
Expand Down
2 changes: 1 addition & 1 deletion client-rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ chain-core = { path = "../chain-core" }
client-common = { path = "../client-common" }
client-core = { path = "../client-core" }
client-network = { path= "../client-network"}
serde_json = "1.0.41"
serde_json = "1.0.42"
jsonrpc-http-server = "14.0"
jsonrpc-core = "14.0"
jsonrpc-core-client = "14.0"
Expand Down
2 changes: 2 additions & 0 deletions client-rpc/src/rpc/transaction_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ mod test {
use super::*;
use chain_core::init::address::CroAddress;
use chain_core::init::coin::Coin;
use chain_core::init::network::Network;
use chain_core::tx::data::address::ExtendedAddr;
use client_common::PrivateKey;

Expand All @@ -95,6 +96,7 @@ mod test {
let outputs = vec![TxOut::new(
ExtendedAddr::from_cro(
"dcro1zz30nheum6vnug3mjs0j4kw4w739tca8cuqae2kdjmt8suhv693qcs3qyn",
Network::Devnet,
)
.unwrap(),
Coin::new(750).unwrap(),
Expand Down
2 changes: 1 addition & 1 deletion client-rpc/src/rpc/wallet_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ where
fn create_staking_address(&self, request: WalletRequest) -> Result<String> {
self.client
.new_staking_address(&request.name, &request.passphrase)
.map(|extended_addr| extended_addr.to_string())
.map(|staked_state_addr| staked_state_addr.to_string())
.map_err(to_rpc_error)
}

Expand Down

0 comments on commit 9d59ae6

Please sign in to comment.