Skip to content

Commit

Permalink
chore: remove web3 dependency and fix Did display prefix (#480)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ma233 authored Oct 6, 2023
1 parent 3c146c8 commit 55967c0
Show file tree
Hide file tree
Showing 17 changed files with 110 additions and 282 deletions.
221 changes: 24 additions & 197 deletions Cargo.lock

Large diffs are not rendered by default.

13 changes: 5 additions & 8 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ std = [
"webrtc",
"async-channel",
"sled",
"web3/http-rustls-tls",
"futures/default",
"uuid/v4",
"uuid/serde",
"rings-derive/default",
Expand All @@ -35,8 +33,6 @@ wasm = [
"wasm-bindgen-futures",
"rexie",
"serde-wasm-bindgen",
"web3/wasm",
"futures",
"uuid/wasm-bindgen",
"uuid/v4",
"uuid/serde",
Expand All @@ -62,7 +58,9 @@ derivative = "2.2.0"
ecies = { version = "0.2", default-features = false, features = ["pure"] }
ed25519 = "1.5.2"
ed25519-dalek = "1.0.1"
flate2 = { version = "1.0.22" }
ethereum-types = "0.14.1"
flate2 = "1.0.22"
futures = "0.3.21"
futures-timer = "3.0.2"
hex = "0.4.3"
itertools = "0.10.3"
Expand All @@ -73,17 +71,16 @@ rand_core = { version = "0.6.3", features = ["getrandom"] }
rand_hc = "0.3.1"
rings-transport = { workspace = true }
serde = { version = "1.0.130", features = ["derive"] }
serde_json = { version = "1.0.70" }
serde_json = "1.0.70"
sha1 = "0.10.1"
sha2 = "0.10.6"
thiserror = "1"
tracing = "0.1.37"
url = { version = "2", features = ["serde"] }

futures = { version = "0.3.21", default-features = false, optional = true }
rings-derive = { workspace = true, optional = true, features = ["core_crate"] }
tiny-keccak = { version = "2.0.1", features = ["keccak"] }
uuid = { version = "0.8.2", optional = true }
web3 = { version = "0.18.0", default-features = false, optional = true }

# default and dummy
async-channel = { version = "1.6.1", optional = true }
Expand Down
15 changes: 8 additions & 7 deletions core/src/dht/did.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,10 @@ use std::ops::Neg;
use std::ops::Sub;
use std::str::FromStr;

use ethereum_types::H160;
use num_bigint::BigUint;
use serde::Deserialize;
use serde::Serialize;
use web3::contract::tokens::Tokenizable;
use web3::types::H160;

use crate::ecc::HashStr;
use crate::error::Error;
Expand All @@ -56,7 +55,8 @@ pub struct Did(H160);

impl std::fmt::Display for Did {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.into_token())
let inner = &self.0;
write!(f, "0x{inner:x}")
}
}

Expand Down Expand Up @@ -355,8 +355,10 @@ mod tests {

// from_str then to_string
let did = Did::from_str("0x11E807fcc88dD319270493fB2e822e388Fe36ab0").unwrap();
// TODO: Should be "0x11e807fcc88dd319270493fb2e822e388fe36ab0"
assert_eq!(did.to_string(), "11e807fcc88dd319270493fb2e822e388fe36ab0");
assert_eq!(
did.to_string(),
"0x11e807fcc88dd319270493fb2e822e388fe36ab0"
);

// Serialize
let did = Did::from_str("0x11E807fcc88dD319270493fB2e822e388Fe36ab0").unwrap();
Expand All @@ -375,10 +377,9 @@ mod tests {

// Debug and Display
let did = Did::from_str("0x11E807fcc88dD319270493fB2e822e388Fe36ab0").unwrap();
// TODO: Should be "0x11e807fcc88dd319270493fb2e822e388fe36ab0"
assert_eq!(
format!("{}", did),
"11e807fcc88dd319270493fb2e822e388fe36ab0"
"0x11e807fcc88dd319270493fb2e822e388fe36ab0"
);
assert_eq!(
format!("{:?}", did),
Expand Down
26 changes: 19 additions & 7 deletions core/src/ecc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@ use std::fmt::Write;
use std::ops::Deref;
use std::str::FromStr;

use ethereum_types::H160;
use hex;
use rand::SeedableRng;
use rand_hc::Hc128Rng;
use serde::Deserialize;
use serde::Serialize;
use sha1::Digest;
use sha1::Sha1;
use web3::signing::keccak256;
use web3::types::Address;

use crate::error::Error;
use crate::error::Result;
Expand All @@ -27,6 +26,8 @@ pub use types::PublicKey;
pub type SigBytes = [u8; 65];
/// Alias PublicKey.
pub type CurveEle = PublicKey;
/// PublicKeyAddress is H160.
pub type PublicKeyAddress = H160;

/// Wrap libsecp256k1::SecretKey.
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
Expand All @@ -36,6 +37,17 @@ pub struct SecretKey(libsecp256k1::SecretKey);
#[derive(Deserialize, Serialize, Debug, Clone, Eq, PartialEq)]
pub struct HashStr(String);

/// Compute the Keccak-256 hash of input bytes.
pub fn keccak256(bytes: &[u8]) -> [u8; 32] {
use tiny_keccak::Hasher;
use tiny_keccak::Keccak;
let mut output = [0u8; 32];
let mut hasher = Keccak::v256();
hasher.update(bytes);
hasher.finalize(&mut output);
output
}

impl HashStr {
pub fn new<T: Into<String>>(s: T) -> Self {
HashStr(s.into())
Expand Down Expand Up @@ -196,7 +208,7 @@ impl Serialize for SecretKey {
}
}

fn public_key_address(pubkey: &PublicKey) -> Address {
fn public_key_address(pubkey: &PublicKey) -> PublicKeyAddress {
let hash = match TryInto::<libsecp256k1::PublicKey>::try_into(*pubkey) {
// if pubkey is ecdsa key
Ok(pk) => {
Expand All @@ -207,10 +219,10 @@ fn public_key_address(pubkey: &PublicKey) -> Address {
// if pubkey is eddsa key
Err(_) => keccak256(&pubkey.0[1..]),
};
Address::from_slice(&hash[12..])
PublicKeyAddress::from_slice(&hash[12..])
}

fn secret_key_address(secret_key: &SecretKey) -> Address {
fn secret_key_address(secret_key: &SecretKey) -> PublicKeyAddress {
let public_key = libsecp256k1::PublicKey::from_secret_key(secret_key);
public_key_address(&public_key.into())
}
Expand All @@ -221,7 +233,7 @@ impl SecretKey {
Self(libsecp256k1::SecretKey::random(&mut rng))
}

pub fn address(&self) -> Address {
pub fn address(&self) -> PublicKeyAddress {
secret_key_address(self)
}

Expand Down Expand Up @@ -254,7 +266,7 @@ impl SecretKey {
}

impl PublicKey {
pub fn address(&self) -> Address {
pub fn address(&self) -> PublicKeyAddress {
public_key_address(self)
}
}
Expand Down
4 changes: 2 additions & 2 deletions core/src/ecc/signers/bip137.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use arrayref::array_mut_ref;
use sha2::Digest;
use sha2::Sha256;

use crate::ecc::Address;
use crate::ecc::PublicKey;
use crate::ecc::PublicKeyAddress;
use crate::error::Result;

/// recover pubkey according to signature.
Expand All @@ -20,7 +20,7 @@ pub fn recover(msg: &str, sig: impl AsRef<[u8]>) -> Result<PublicKey> {
}

/// verify message signed by Ethereum address.
pub fn verify(msg: &str, address: &Address, sig: impl AsRef<[u8]>) -> bool {
pub fn verify(msg: &str, address: &PublicKeyAddress, sig: impl AsRef<[u8]>) -> bool {
match recover(msg, sig.as_ref()) {
Ok(recover_pk) => {
if recover_pk.address() == *address {
Expand Down
9 changes: 7 additions & 2 deletions core/src/ecc/signers/ed25519.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
//! ed25519 sign algorithm using ed25519_dalek
use ed25519_dalek::Verifier;

use crate::ecc::Address;
use crate::ecc::PublicKey;
use crate::ecc::PublicKeyAddress;

/// ref <https://www.rfc-editor.org/rfc/rfc8709>
pub fn verify(msg: &str, address: &Address, sig: impl AsRef<[u8]>, pubkey: PublicKey) -> bool {
pub fn verify(
msg: &str,
address: &PublicKeyAddress,
sig: impl AsRef<[u8]>,
pubkey: PublicKey,
) -> bool {
if pubkey.address() != *address {
return false;
}
Expand Down
11 changes: 5 additions & 6 deletions core/src/ecc/signers/eip191.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
//! eip191.
//! ref <https://eips.ethereum.org/EIPS/eip-191>

use web3::signing::keccak256;

use crate::ecc::Address;
use crate::ecc::keccak256;
use crate::ecc::PublicKey;
use crate::ecc::PublicKeyAddress;
use crate::ecc::SecretKey;
use crate::error::Result;

Expand Down Expand Up @@ -37,7 +36,7 @@ pub fn recover(msg: &str, sig: impl AsRef<[u8]>) -> Result<PublicKey> {
}

/// verify message signed by Ethereum address.
pub fn verify(msg: &str, address: &Address, sig: impl AsRef<[u8]>) -> bool {
pub fn verify(msg: &str, address: &PublicKeyAddress, sig: impl AsRef<[u8]>) -> bool {
if let Ok(p) = recover(msg, sig) {
p.address() == *address
} else {
Expand All @@ -50,7 +49,6 @@ mod test {
use std::str::FromStr;

use super::*;
use crate::ecc::Address;
use crate::ecc::SecretKey;

#[test]
Expand All @@ -59,7 +57,8 @@ mod test {
let key =
SecretKey::try_from("65860affb4b570dba06db294aa7c676f68e04a5bf2721243ad3cbc05a79c68c0")
.unwrap();
let address = Address::from_str("0x11E807fcc88dD319270493fB2e822e388Fe36ab0").unwrap();
let address =
PublicKeyAddress::from_str("0x11E807fcc88dD319270493fB2e822e388Fe36ab0").unwrap();

// window.ethereum.request({method: "personal_sign", params: ["test", "0x11E807fcc88dD319270493fB2e822e388Fe36ab0"]})
let metamask_sig = Vec::from_hex("724fc31d9272b34d8406e2e3a12a182e72510b008de6cc44684577e31e20d9626fb760d6a0badd79a6cf4cd56b2fc0fbd60c438b809aa7d29bfb598c13e7b50e1b").unwrap();
Expand Down
6 changes: 3 additions & 3 deletions core/src/ecc/signers/secp256k1.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
//! Default method signing using libsecp256k1::SecretKey.
use web3::signing::keccak256;

use crate::ecc::Address;
use crate::ecc::keccak256;
use crate::ecc::PublicKey;
use crate::ecc::PublicKeyAddress;
use crate::ecc::SecretKey;
use crate::error::Result;

Expand All @@ -28,7 +28,7 @@ pub fn recover(msg: &str, sig: impl AsRef<[u8]>) -> Result<PublicKey> {
}

/// verify signature with message and address.
pub fn verify(msg: &str, address: &Address, sig: impl AsRef<[u8]>) -> bool {
pub fn verify(msg: &str, address: &PublicKeyAddress, sig: impl AsRef<[u8]>) -> bool {
if let Ok(p) = recover(msg, sig) {
p.address() == *address
} else {
Expand Down
2 changes: 0 additions & 2 deletions core/src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ pub use futures;
pub use libsecp256k1;
pub use url;
pub use uuid;
pub use web3;
pub use web3::types::Address;

pub use crate::dht::vnode;
pub use crate::message;
Expand Down
6 changes: 3 additions & 3 deletions core/src/storage/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,15 @@ where

#[cfg(test)]
mod tests {
use web3::types::Address;

use super::*;
use crate::dht::Did;
use crate::ecc::SecretKey;

#[test]
fn memstorage_basic_interface_should_work() {
let store = MemStorage::<Address, String>::new();
let addr = SecretKey::random().address();
let store = MemStorage::<Did, String>::new();
let addr = SecretKey::random().address().into();

assert!(store.get(&addr).is_none());

Expand Down
10 changes: 4 additions & 6 deletions core/src/tests/wasm/test_idb_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ async fn test_create_put_data() {
assert!(store.count(None).await.unwrap() == 1, "indexedDB is empty");

let real_value_1 = store.get(&JsValue::from(&key)).await.unwrap();
#[allow(deprecated)]
let real_value_1: JsonValue = real_value_1.into_serde().unwrap();
let real_value_1: JsonValue = serde_wasm_bindgen::from_value(real_value_1).unwrap();
let last_visit_1 = real_value_1
.get("last_visit_time")
.unwrap()
Expand All @@ -69,8 +68,7 @@ async fn test_create_put_data() {
let (_tx, store) = instance.get_tx_store(TransactionMode::ReadOnly).unwrap();
assert!(store.count(None).await.unwrap() == 1, "indexedDB is empty");
let real_value_2 = store.get(&JsValue::from(&key)).await.unwrap();
#[allow(deprecated)]
let real_value_2: JsonValue = real_value_2.into_serde().unwrap();
let real_value_2: JsonValue = serde_wasm_bindgen::from_value(real_value_2).unwrap();
let last_visit_2 = real_value_2
.get("last_visit_time")
.unwrap()
Expand Down Expand Up @@ -241,8 +239,8 @@ async fn test_idb_total_size() {
};
instance.put(&key1, &value1).await.unwrap();
#[allow(deprecated)]
let expect_size =
size_of_val(&JsValue::from(key1)) + size_of_val(&JsValue::from_serde(&value1).unwrap());
let expect_size = size_of_val(&JsValue::from(key1))
+ size_of_val(&serde_wasm_bindgen::to_value(&value1).unwrap());
let total_size = instance.total_size().await.unwrap();
assert!(total_size > 0, "total_size should > 0");
assert!(
Expand Down
Loading

0 comments on commit 55967c0

Please sign in to comment.