Skip to content

Commit

Permalink
Split Transaction from MessagePayload
Browse files Browse the repository at this point in the history
  • Loading branch information
Ma233 committed Oct 17, 2023
1 parent 55967c0 commit eedf5ed
Show file tree
Hide file tree
Showing 33 changed files with 509 additions and 471 deletions.
2 changes: 1 addition & 1 deletion core/src/chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ pub struct ChunkMeta {
/// Created time
pub ts_ms: u128,
/// Time to live
pub ttl_ms: usize,
pub ttl_ms: u64,
}

impl Default for ChunkMeta {
Expand Down
6 changes: 3 additions & 3 deletions core/src/consts.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//! Constant variables.
///
/// default ttl in ms
pub const DEFAULT_TTL_MS: usize = 300 * 1000;
pub const MAX_TTL_MS: usize = DEFAULT_TTL_MS * 10;
pub const DEFAULT_TTL_MS: u64 = 300 * 1000;
pub const MAX_TTL_MS: u64 = DEFAULT_TTL_MS * 10;
pub const TS_OFFSET_TOLERANCE_MS: u128 = 3000;
pub const DEFAULT_SESSION_TTL_MS: usize = 30 * 24 * 3600 * 1000;
pub const DEFAULT_SESSION_TTL_MS: u64 = 30 * 24 * 3600 * 1000;
pub const TRANSPORT_MTU: usize = 60000;
pub const TRANSPORT_MAX_SIZE: usize = TRANSPORT_MTU * 16;
pub const VNODE_DATA_MAX_LEN: usize = 1024;
10 changes: 4 additions & 6 deletions core/src/dht/vnode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::cmp::max;
use std::str::FromStr;

use num_bigint::BigUint;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde::Serialize;

Expand All @@ -16,6 +15,7 @@ use crate::error::Result;
use crate::message::Encoded;
use crate::message::Encoder;
use crate::message::MessagePayload;
use crate::message::MessageVerificationExt;

/// VNode Types
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
Expand Down Expand Up @@ -108,12 +108,10 @@ impl VNodeOperation {
}
}

impl<T> TryFrom<MessagePayload<T>> for VirtualNode
where T: Serialize + DeserializeOwned
{
impl TryFrom<MessagePayload> for VirtualNode {
type Error = Error;
fn try_from(msg: MessagePayload<T>) -> Result<Self> {
let did = BigUint::from(msg.addr) + BigUint::from(1u16);
fn try_from(msg: MessagePayload) -> Result<Self> {
let did = BigUint::from(msg.signer()) + BigUint::from(1u16);
let data = msg.encode()?;
Ok(Self {
did: did.into(),
Expand Down
6 changes: 3 additions & 3 deletions core/src/ecc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,10 +272,10 @@ impl PublicKey {
}

/// Recover PublicKey from RawMessage using signature.
pub fn recover<S>(message: &str, signature: S) -> Result<PublicKey>
pub fn recover<S>(message: &[u8], signature: S) -> Result<PublicKey>
where S: AsRef<[u8]> {
let sig_bytes: SigBytes = signature.as_ref().try_into()?;
let message_hash: [u8; 32] = keccak256(message.as_bytes());
let message_hash: [u8; 32] = keccak256(message);
recover_hash(&message_hash, &sig_bytes)
}

Expand Down Expand Up @@ -353,7 +353,7 @@ pub mod tests {
fn test_recover() {
let key = SecretKey::random();
let pubkey1 = key.pubkey();
let pubkey2 = recover("hello", key.sign("hello")).unwrap();
let pubkey2 = recover("hello".as_bytes(), key.sign("hello")).unwrap();
assert_eq!(pubkey1, pubkey2);
}

Expand Down
15 changes: 7 additions & 8 deletions core/src/ecc/signers/bip137.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::ecc::PublicKeyAddress;
use crate::error::Result;

/// recover pubkey according to signature.
pub fn recover(msg: &str, sig: impl AsRef<[u8]>) -> Result<PublicKey> {
pub fn recover(msg: &[u8], sig: impl AsRef<[u8]>) -> Result<PublicKey> {
let mut sig = sig.as_ref().to_vec();
sig.rotate_left(1);
let sig = sig.as_mut_slice();
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: &PublicKeyAddress, sig: impl AsRef<[u8]>) -> bool {
pub fn verify(msg: &[u8], address: &PublicKeyAddress, sig: impl AsRef<[u8]>) -> bool {
match recover(msg, sig.as_ref()) {
Ok(recover_pk) => {
if recover_pk.address() == *address {
Expand All @@ -35,7 +35,7 @@ pub fn verify(msg: &str, address: &PublicKeyAddress, sig: impl AsRef<[u8]>) -> b
}
Err(e) => {
tracing::debug!(
"failed to recover pubkey: {:?}\nmsg: {}\nsig:{:?}",
"failed to recover pubkey: {:?}\nmsg: {:?}\nsig:{:?}",
e,
msg,
sig.as_ref(),
Expand Down Expand Up @@ -67,14 +67,13 @@ fn varint_buf_num(n: u64) -> Vec<u8> {
}
}

pub fn magic_hash(msg: &str) -> [u8; 32] {
pub fn magic_hash(msg: &[u8]) -> [u8; 32] {
let magic_bytes = "Bitcoin Signed Message:\n".as_bytes();
let msg_bytes = msg.as_bytes();
let mut buf = Vec::new();
buf.extend_from_slice(varint_buf_num(magic_bytes.len() as u64).as_slice());
buf.extend_from_slice(magic_bytes);
buf.extend_from_slice(varint_buf_num(msg_bytes.len() as u64).as_slice());
buf.extend_from_slice(msg_bytes);
buf.extend_from_slice(varint_buf_num(msg.len() as u64).as_slice());
buf.extend_from_slice(msg);
let hash = Sha256::digest(Sha256::digest(&buf));
hash.into()
}
Expand All @@ -100,7 +99,7 @@ mod test {
];
assert_eq!(sig.len(), 65);

let pk = self::recover(msg, sig).unwrap();
let pk = self::recover(msg.as_bytes(), sig).unwrap();
assert_eq!(pk, pubkey);
assert_eq!(pk.address(), pubkey.address());
}
Expand Down
11 changes: 8 additions & 3 deletions core/src/ecc/signers/ed25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::ecc::PublicKeyAddress;

/// ref <https://www.rfc-editor.org/rfc/rfc8709>
pub fn verify(
msg: &str,
msg: &[u8],
address: &PublicKeyAddress,
sig: impl AsRef<[u8]>,
pubkey: PublicKey,
Expand All @@ -22,7 +22,7 @@ pub fn verify(
TryInto::<ed25519_dalek::PublicKey>::try_into(pubkey),
ed25519_dalek::Signature::from_bytes(&sig_data),
) {
match p.verify(msg.as_bytes(), &s) {
match p.verify(msg, &s) {
Ok(()) => true,
Err(_) => false,
}
Expand Down Expand Up @@ -54,6 +54,11 @@ mod test {
PublicKey::try_from_b58t("9z1ZTaGocNSAu3DSqGKR6Dqt214X4dXucVd6C53EgqBK").unwrap();
let sig_b58 = "2V1AR5byk4a4CkVmFRWU1TVs3ns2CGkuq6xgGju1huGQGq5hGkiHUDjEaJJaL2txfqCSGnQW55jUJpcjKFkZEKq";
let sig: Vec<u8> = base58::FromBase58::from_base58(sig_b58).unwrap();
assert!(self::verify(msg, &signer.address(), sig.as_slice(), signer))
assert!(self::verify(
msg.as_bytes(),
&signer.address(),
sig.as_slice(),
signer
))
}
}
16 changes: 8 additions & 8 deletions core/src/ecc/signers/eip191.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::ecc::SecretKey;
use crate::error::Result;

/// sign function passing raw message parameter.
pub fn sign_raw(sec: SecretKey, msg: &str) -> [u8; 65] {
pub fn sign_raw(sec: SecretKey, msg: &[u8]) -> [u8; 65] {
sign(sec, &hash(msg))
}

Expand All @@ -20,14 +20,14 @@ pub fn sign(sec: SecretKey, hash: &[u8; 32]) -> [u8; 65] {
}

/// \x19Ethereum Signed Message\n is used for PersonalSign, which can encode by send `personalSign` rpc call.
pub fn hash(msg: &str) -> [u8; 32] {
pub fn hash(msg: &[u8]) -> [u8; 32] {
let mut prefix_msg = format!("\x19Ethereum Signed Message:\n{}", msg.len()).into_bytes();
prefix_msg.extend_from_slice(msg.as_bytes());
prefix_msg.extend_from_slice(msg);
keccak256(&prefix_msg)
}

/// recover pubkey according to signature.
pub fn recover(msg: &str, sig: impl AsRef<[u8]>) -> Result<PublicKey> {
pub fn recover(msg: &[u8], sig: impl AsRef<[u8]>) -> Result<PublicKey> {
let sig_byte: [u8; 65] = sig.as_ref().try_into()?;
let hash = hash(msg);
let mut sig712 = sig_byte;
Expand All @@ -36,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: &PublicKeyAddress, sig: impl AsRef<[u8]>) -> bool {
pub fn verify(msg: &[u8], address: &PublicKeyAddress, sig: impl AsRef<[u8]>) -> bool {
if let Ok(p) = recover(msg, sig) {
p.address() == *address
} else {
Expand All @@ -63,11 +63,11 @@ mod test {
// window.ethereum.request({method: "personal_sign", params: ["test", "0x11E807fcc88dD319270493fB2e822e388Fe36ab0"]})
let metamask_sig = Vec::from_hex("724fc31d9272b34d8406e2e3a12a182e72510b008de6cc44684577e31e20d9626fb760d6a0badd79a6cf4cd56b2fc0fbd60c438b809aa7d29bfb598c13e7b50e1b").unwrap();
let msg = "test";
let h = self::hash(msg);
let h = self::hash(msg.as_bytes());
let sig = self::sign(key, &h);
assert_eq!(metamask_sig.as_slice(), sig);
let pubkey = self::recover(msg, sig).unwrap();
let pubkey = self::recover(msg.as_bytes(), sig).unwrap();
assert_eq!(pubkey.address(), address);
assert!(self::verify(msg, &address, sig));
assert!(self::verify(msg.as_bytes(), &address, sig));
}
}
12 changes: 6 additions & 6 deletions core/src/ecc/signers/secp256k1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::ecc::SecretKey;
use crate::error::Result;

/// sign function passing raw message parameter.
pub fn sign_raw(sec: SecretKey, msg: &str) -> [u8; 65] {
pub fn sign_raw(sec: SecretKey, msg: &[u8]) -> [u8; 65] {
sign(sec, &hash(msg))
}

Expand All @@ -17,18 +17,18 @@ pub fn sign(sec: SecretKey, hash: &[u8; 32]) -> [u8; 65] {
}

/// generate hash data from message.
pub fn hash(msg: &str) -> [u8; 32] {
keccak256(msg.as_bytes())
pub fn hash(msg: &[u8]) -> [u8; 32] {
keccak256(msg)
}

/// recover public key from message and signature.
pub fn recover(msg: &str, sig: impl AsRef<[u8]>) -> Result<PublicKey> {
pub fn recover(msg: &[u8], sig: impl AsRef<[u8]>) -> Result<PublicKey> {
let sig_byte: [u8; 65] = sig.as_ref().try_into()?;
crate::ecc::recover(msg, sig_byte)
}

/// verify signature with message and address.
pub fn verify(msg: &str, address: &PublicKeyAddress, sig: impl AsRef<[u8]>) -> bool {
pub fn verify(msg: &[u8], address: &PublicKeyAddress, sig: impl AsRef<[u8]>) -> bool {
if let Ok(p) = recover(msg, sig) {
p.address() == *address
} else {
Expand All @@ -48,7 +48,7 @@ mod test {
.unwrap();

let msg = "hello";
let h = self::hash(msg);
let h = self::hash(msg.as_bytes());
let sig = self::sign(key, &h);
assert_eq!(sig, key.sign(msg));
}
Expand Down
Loading

0 comments on commit eedf5ed

Please sign in to comment.