Skip to content

Commit

Permalink
feat: update go-waku version
Browse files Browse the repository at this point in the history
- removes encoding functions from relay and lightpush
- adds `encode_symmetric` and `encode_asymmetric` to `WakuMessage`
  • Loading branch information
richard-ramos committed Sep 27, 2023
1 parent a487f79 commit e64fb48
Show file tree
Hide file tree
Showing 12 changed files with 158 additions and 371 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions waku-bindings/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "waku-bindings"
version = "0.2.0"
version = "0.3.0"
edition = "2021"
authors = [
"Daniel Sanchez Quiros <danielsq@status.im>"
Expand All @@ -26,7 +26,7 @@ serde_json = "1.0"
sscanf = "0.4"
smart-default = "0.6"
url = "2.3"
waku-sys = { version = "0.2.0", path = "../waku-sys" }
waku-sys = { version = "0.3.0", path = "../waku-sys" }

[dev-dependencies]
futures = "0.3.25"
Expand Down
76 changes: 76 additions & 0 deletions waku-bindings/src/encrypt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// std
use std::ffi::CString;
// crates
use aes_gcm::{Aes256Gcm, Key};
use secp256k1::{PublicKey, SecretKey};
// internal
use crate::general::{Result, WakuMessage};
use crate::utils::decode_and_free_response;

/// Optionally sign and encrypt a message using asymmetric encryption
pub fn waku_encode_asymmetric(
message: &WakuMessage,
public_key: &PublicKey,
signing_key: Option<&SecretKey>,
) -> Result<WakuMessage> {
let pk = hex::encode(public_key.serialize_uncompressed());
let sk = signing_key
.map(|signing_key| hex::encode(signing_key.secret_bytes()))
.unwrap_or_else(String::new);
let message_ptr = CString::new(
serde_json::to_string(&message)
.expect("WakuMessages should always be able to success serializing"),
)
.expect("CString should build properly from the serialized waku message")
.into_raw();
let pk_ptr = CString::new(pk)
.expect("CString should build properly from hex encoded public key")
.into_raw();
let sk_ptr = CString::new(sk)
.expect("CString should build properly from hex encoded signing key")
.into_raw();

let result_ptr = unsafe {
let res = waku_sys::waku_encode_asymmetric(message_ptr, pk_ptr, sk_ptr);
drop(CString::from_raw(message_ptr));
drop(CString::from_raw(pk_ptr));
drop(CString::from_raw(sk_ptr));
res
};

decode_and_free_response(result_ptr)
}

/// Optionally sign and encrypt a message using symmetric encryption
pub fn waku_encode_symmetric(
message: &WakuMessage,
symmetric_key: &Key<Aes256Gcm>,
signing_key: Option<&SecretKey>,
) -> Result<WakuMessage> {
let symk = hex::encode(symmetric_key.as_slice());
let sk = signing_key
.map(|signing_key| hex::encode(signing_key.secret_bytes()))
.unwrap_or_else(String::new);
let message_ptr = CString::new(
serde_json::to_string(&message)
.expect("WakuMessages should always be able to success serializing"),
)
.expect("CString should build properly from the serialized waku message")
.into_raw();
let symk_ptr = CString::new(symk)
.expect("CString should build properly from hex encoded symmetric key")
.into_raw();
let sk_ptr = CString::new(sk)
.expect("CString should build properly from hex encoded signing key")
.into_raw();

let result_ptr = unsafe {
let res = waku_sys::waku_encode_symmetric(message_ptr, symk_ptr, sk_ptr);
drop(CString::from_raw(message_ptr));
drop(CString::from_raw(symk_ptr));
drop(CString::from_raw(sk_ptr));
res
};

decode_and_free_response(result_ptr)
}
55 changes: 55 additions & 0 deletions waku-bindings/src/general/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
use sscanf::{scanf, RegexRepresentation};
// internal
use crate::decrypt::{waku_decode_asymmetric, waku_decode_symmetric};
use crate::encrypt::{waku_encode_asymmetric, waku_encode_symmetric};

/// Waku message version
pub type WakuMessageVersion = usize;
Expand Down Expand Up @@ -145,13 +146,31 @@ impl WakuMessage {
self.ephemeral
}

/// Optionally sign and encrypt a message using symmetric encryption
pub fn encode_symmetric(
&self,
symmetric_key: &Key<Aes256Gcm>,
signing_key: Option<&SecretKey>,
) -> Result<WakuMessage> {
waku_encode_symmetric(self, symmetric_key, signing_key)
}

/// Try decode the message with an expected symmetric key
///
/// As per the [specification](https://rfc.vac.dev/spec/36/#extern-char-waku_decode_symmetricchar-messagejson-char-symmetrickey)
pub fn try_decode_symmetric(&self, symmetric_key: &Key<Aes256Gcm>) -> Result<DecodedPayload> {
waku_decode_symmetric(self, symmetric_key)
}

/// Optionally sign and encrypt a message using asymmetric encryption
pub fn encode_asymmetric(
&self,
public_key: &PublicKey,
signing_key: Option<&SecretKey>,
) -> Result<WakuMessage> {
waku_encode_asymmetric(self, public_key, signing_key)
}

/// Try decode the message with an expected asymmetric key
///
/// As per the [specification](https://rfc.vac.dev/spec/36/#extern-char-waku_decode_asymmetricchar-messagejson-char-privatekey)
Expand Down Expand Up @@ -563,6 +582,8 @@ where
mod tests {
use super::*;
use crate::WakuPubSubTopic;
use secp256k1::{rand, Secp256k1};
use std::time::SystemTime;
#[test]
fn parse_waku_topic() {
let s = "/waku/2/default-waku/proto";
Expand All @@ -574,4 +595,38 @@ mod tests {
let message = "{\"payload\":\"SGkgZnJvbSDwn6aAIQ==\",\"contentTopic\":\"/toychat/2/huilong/proto\",\"timestamp\":1665580926660,\"ephemeral\":true,\"meta\":\"SGkgZnJvbSDwn6aAIQ==\"}";
let _: WakuMessage = serde_json::from_str(message).unwrap();
}

#[test]
fn encode_decode() {
let content_topic = WakuContentTopic::new("hello", 2, "world", Encoding::Proto);
let message = WakuMessage::new(
"hello",
content_topic,
1,
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_millis()
.try_into()
.unwrap(),
Vec::new(),
false,
);

let secp = Secp256k1::new();
let signing_key = SecretKey::new(&mut rand::thread_rng());
let encrypt_key = SecretKey::new(&mut rand::thread_rng());
let public_key = PublicKey::from_secret_key(&secp, &encrypt_key);

let encoded_message = message
.encode_asymmetric(&public_key, Some(&signing_key))
.expect("could not encode");
let decoded_message = encoded_message
.try_decode_asymmetric(&encrypt_key)
.expect("could not decode");

assert!(message.payload() != encoded_message.payload());
assert!(encoded_message.version() == 1);
assert!(message.payload() == decoded_message.data());
}
}
3 changes: 2 additions & 1 deletion waku-bindings/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
//!
//! Implementation on top of [`waku-bindings`](https://rfc.vac.dev/spec/36/)
mod decrypt;
mod encrypt;
mod events;
mod general;
mod node;
mod utils;

pub use node::{
waku_create_content_topic, waku_create_pubsub_topic, waku_dafault_pubsub_topic,
waku_create_content_topic, waku_create_pubsub_topic, waku_default_pubsub_topic,
waku_discv5_update_bootnodes, waku_dns_discovery, waku_new, Aes256Gcm, DnsInfo,
GossipSubParams, Initialized, Key, Multiaddr, Protocol, PublicKey, Running, SecretKey,
WakuLogLevel, WakuNodeConfig, WakuNodeHandle, WakuPeerData, WakuPeers, WebsocketParams,
Expand Down
132 changes: 2 additions & 130 deletions waku-bindings/src/node/lightpush.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,9 @@
// std
use std::ffi::CString;
use std::time::Duration;
// crates
use aes_gcm::{Aes256Gcm, Key};
use secp256k1::{PublicKey, SecretKey};
// internal
use crate::general::{MessageId, PeerId, Result, WakuMessage, WakuPubSubTopic};
use crate::node::waku_dafault_pubsub_topic;
use crate::node::waku_default_pubsub_topic;
use crate::utils::decode_and_free_response;

/// Publish a message using Waku Lightpush
Expand All @@ -20,7 +17,7 @@ pub fn waku_lightpush_publish(
timeout: Option<Duration>,
) -> Result<MessageId> {
let pubsub_topic = pubsub_topic
.unwrap_or_else(waku_dafault_pubsub_topic)
.unwrap_or_else(waku_default_pubsub_topic)
.to_string();
let message_ptr = CString::new(
serde_json::to_string(&message)
Expand Down Expand Up @@ -56,128 +53,3 @@ pub fn waku_lightpush_publish(

decode_and_free_response(result_ptr)
}

/// Optionally sign, encrypt using asymmetric encryption and publish a message using Waku Lightpush
/// As per the [specification](https://rfc.vac.dev/spec/36/#extern-char-waku_lightpush_publish_enc_asymmetricchar-messagejson-char-pubsubtopic-char-peerid-char-publickey-char-optionalsigningkey-int-timeoutms)
pub fn waku_lightpush_publish_encrypt_asymmetric(
message: &WakuMessage,
pubsub_topic: Option<WakuPubSubTopic>,
peer_id: PeerId,
public_key: &PublicKey,
signing_key: Option<&SecretKey>,
timeout: Option<Duration>,
) -> Result<MessageId> {
let pk = hex::encode(public_key.serialize_uncompressed());
let sk = signing_key
.map(|signing_key| hex::encode(signing_key.secret_bytes()))
.unwrap_or_else(String::new);
let pubsub_topic = pubsub_topic
.unwrap_or_else(waku_dafault_pubsub_topic)
.to_string();

let pubsub_topic_ptr = CString::new(pubsub_topic)
.expect("CString should build properly from pubsub topic")
.into_raw();
let peer_id_ptr = CString::new(peer_id)
.expect("CString should build properly from peer id")
.into_raw();
let pk_ptr = CString::new(pk)
.expect("CString should build properly from hex encoded public key")
.into_raw();
let sk_ptr = CString::new(sk)
.expect("CString should build properly from hex encoded signing key")
.into_raw();
let message_ptr = CString::new(
serde_json::to_string(&message)
.expect("WakuMessages should always be able to success serializing"),
)
.expect("CString should build properly from the serialized waku message")
.into_raw();
let result_ptr = unsafe {
let res = waku_sys::waku_lightpush_publish_enc_asymmetric(
message_ptr,
pubsub_topic_ptr,
peer_id_ptr,
pk_ptr,
sk_ptr,
timeout
.map(|timeout| {
timeout
.as_millis()
.try_into()
.expect("Duration as milliseconds should fit in a i32")
})
.unwrap_or(0),
);
drop(CString::from_raw(message_ptr));
drop(CString::from_raw(pubsub_topic_ptr));
drop(CString::from_raw(peer_id_ptr));
drop(CString::from_raw(pk_ptr));
drop(CString::from_raw(sk_ptr));
res
};

decode_and_free_response(result_ptr)
}

/// Optionally sign, encrypt using symmetric encryption and publish a message using Waku Lightpush
/// As per the [specification](https://rfc.vac.dev/spec/36/#extern-char-waku_lightpush_publish_enc_symmetricchar-messagejson-char-pubsubtopic-char-peerid-char-symmetrickey-char-optionalsigningkey-int-timeoutms)
pub fn waku_lightpush_publish_encrypt_symmetric(
message: &WakuMessage,
pubsub_topic: Option<WakuPubSubTopic>,
peer_id: PeerId,
symmetric_key: &Key<Aes256Gcm>,
signing_key: Option<&SecretKey>,
timeout: Option<Duration>,
) -> Result<MessageId> {
let symk = hex::encode(symmetric_key.as_slice());
let sk = signing_key
.map(|signing_key| hex::encode(signing_key.secret_bytes()))
.unwrap_or_else(String::new);
let pubsub_topic = pubsub_topic
.unwrap_or_else(waku_dafault_pubsub_topic)
.to_string();
let message_ptr = CString::new(
serde_json::to_string(&message)
.expect("WakuMessages should always be able to success serializing"),
)
.expect("CString should build properly from the serialized waku message")
.into_raw();
let pubsub_topic_ptr = CString::new(pubsub_topic)
.expect("CString should build properly from pubsub topic")
.into_raw();
let peer_id_ptr = CString::new(peer_id)
.expect("CString should build properly from peer id")
.into_raw();
let symk_ptr = CString::new(symk)
.expect("CString should build properly from hex encoded symmetric key")
.into_raw();
let sk_ptr = CString::new(sk)
.expect("CString should build properly from hex encoded signing key")
.into_raw();
let result_ptr = unsafe {
let res = waku_sys::waku_lightpush_publish_enc_symmetric(
message_ptr,
pubsub_topic_ptr,
peer_id_ptr,
symk_ptr,
sk_ptr,
timeout
.map(|timeout| {
timeout
.as_millis()
.try_into()
.expect("Duration as milliseconds should fit in a i32")
})
.unwrap_or(0),
);
drop(CString::from_raw(message_ptr));
drop(CString::from_raw(pubsub_topic_ptr));
drop(CString::from_raw(peer_id_ptr));
drop(CString::from_raw(symk_ptr));
drop(CString::from_raw(sk_ptr));
res
};

decode_and_free_response(result_ptr)
}
Loading

0 comments on commit e64fb48

Please sign in to comment.