Skip to content

Commit

Permalink
feat: tvf data in publish payload (#87)
Browse files Browse the repository at this point in the history
  • Loading branch information
heilhead authored Jan 20, 2025
1 parent 51e984e commit 450006a
Show file tree
Hide file tree
Showing 14 changed files with 80 additions and 17 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ jobs:
rust: nightly
- name: "Tests"
cmd: nextest
args: run --workspace --all-features
args: run --workspace
rust: stable
- name: "Documentation Tests"
cmd: test
Expand Down
1 change: 1 addition & 0 deletions relay_client/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ impl Client {
ttl_secs,
tag,
prompt,
analytics: None,
})
.await
.map(|_| ())
Expand Down
25 changes: 24 additions & 1 deletion relay_client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ pub struct ConnectionOptions {
/// Optional origin of the request. Subject to allow-list validation.
pub origin: Option<String>,

/// Optional package name. Used instead of `origin` for allow-list
/// validation.
pub package_name: Option<String>,

/// Optional bundle ID. Used instead of `origin` for allow-list validation.
pub bundle_id: Option<String>,

/// Optional user agent parameters.
pub user_agent: Option<UserAgent>,
}
Expand All @@ -60,6 +67,8 @@ impl ConnectionOptions {
auth: Authorization::Query(auth),
origin: None,
user_agent: None,
package_name: None,
bundle_id: None,
}
}

Expand All @@ -68,6 +77,16 @@ impl ConnectionOptions {
self
}

pub fn with_package_name(mut self, package_name: impl Into<String>) -> Self {
self.package_name = Some(package_name.into());
self
}

pub fn with_bundle_id(mut self, bundle_id: impl Into<String>) -> Self {
self.bundle_id = Some(bundle_id.into());
self
}

pub fn with_origin(mut self, origin: impl Into<Option<String>>) -> Self {
self.origin = origin.into();
self
Expand All @@ -85,6 +104,8 @@ impl ConnectionOptions {
project_id: &'a ProjectId,
auth: Option<&'a SerializedAuthToken>,
ua: Option<&'a UserAgent>,
package_name: Option<&'a str>,
bundle_id: Option<&'a str>,
}

let query = serde_qs::to_string(&QueryParams {
Expand All @@ -95,6 +116,8 @@ impl ConnectionOptions {
None
},
ua: self.user_agent.as_ref(),
package_name: self.package_name.as_deref(),
bundle_id: self.bundle_id.as_deref(),
})
.map_err(RequestBuildError::Query)?;

Expand Down Expand Up @@ -157,7 +180,7 @@ impl MessageIdGenerator {
pub fn next(&self) -> MessageId {
let next = self.next.fetch_add(1, Ordering::Relaxed) as u64;
let timestamp = chrono::Utc::now().timestamp_millis() as u64;
let id = timestamp << 8 | next;
let id = (timestamp << 8) | next;

MessageId::new(id)
}
Expand Down
1 change: 1 addition & 0 deletions relay_client/src/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ impl Client {
ttl_secs: ttl.as_secs() as u32,
tag,
prompt,
analytics: None,
});

self.request(request);
Expand Down
14 changes: 8 additions & 6 deletions relay_rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@ edition = "2021"
license = "Apache-2.0"

[features]
cacao = [
"dep:k256",
"dep:sha3",
"dep:alloy"
]
cacao = ["dep:k256", "dep:sha3", "dep:alloy"]
cacao-tests = []

[dependencies]
bs58 = "0.4"
Expand Down Expand Up @@ -37,7 +34,12 @@ k256 = { version = "0.13", optional = true }
sha3 = { version = "0.10", optional = true }
sha2 = { version = "0.10.6" }
url = "2"
alloy = { version = "0.3.6", optional = true, features = ["json-rpc", "provider-http", "contract", "rpc-types-eth"] }
alloy = { version = "0.3.6", optional = true, features = [
"json-rpc",
"provider-http",
"contract",
"rpc-types-eth",
] }
strum = { version = "0.26", features = ["strum_macros", "derive"] }

[dev-dependencies]
Expand Down
2 changes: 1 addition & 1 deletion relay_rpc/src/auth/cacao.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,5 +169,5 @@ impl Cacao {
}
}

#[cfg(test)]
#[cfg(all(test, feature = "cacao-tests"))]
mod tests;
2 changes: 1 addition & 1 deletion relay_rpc/src/auth/cacao/payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ impl Payload {
}
}

#[cfg(test)]
#[cfg(all(test, feature = "cacao-tests"))]
mod tests {
use super::*;

Expand Down
2 changes: 1 addition & 1 deletion relay_rpc/src/auth/cacao/signature/eip1271.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub async fn verify_eip1271(
}
}

#[cfg(test)]
#[cfg(all(test, feature = "cacao-tests"))]
mod test {
use {
super::*,
Expand Down
4 changes: 2 additions & 2 deletions relay_rpc/src/auth/cacao/signature/eip191.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub const EIP191: &str = "eip191";
pub fn eip191_bytes(message: &str) -> Vec<u8> {
format!(
"\u{0019}Ethereum Signed Message:\n{}{}",
message.as_bytes().len(),
message.len(),
message
)
.into()
Expand Down Expand Up @@ -51,7 +51,7 @@ pub fn verify_eip191(
}
}

#[cfg(test)]
#[cfg(all(test, feature = "cacao-tests"))]
mod tests {
use {
crate::auth::cacao::signature::{
Expand Down
2 changes: 1 addition & 1 deletion relay_rpc/src/auth/cacao/signature/eip6492.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ pub async fn verify_eip6492(
}
}

#[cfg(test)]
#[cfg(all(test, feature = "cacao-tests"))]
mod test {
use {
super::*,
Expand Down
2 changes: 1 addition & 1 deletion relay_rpc/src/auth/cacao/signature/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub mod eip191;
pub mod eip6492;
pub mod get_rpc_url;

#[cfg(test)]
#[cfg(all(test, feature = "cacao-tests"))]
mod test_helpers;

#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Hash)]
Expand Down
2 changes: 1 addition & 1 deletion relay_rpc/src/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl Default for JwtHeader<'_> {
}
}

impl<'a> JwtHeader<'a> {
impl JwtHeader<'_> {
pub fn is_valid(&self) -> bool {
self.typ == JWT_HEADER_TYP && self.alg == JWT_HEADER_ALG
}
Expand Down
25 changes: 25 additions & 0 deletions relay_rpc/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,12 @@ impl Payload {
Self::Response(response) => response.validate(),
}
}

pub fn strip_analytics(&mut self) {
if let Self::Request(req) = self {
req.strip_analytics();
}
}
}

impl<T> From<T> for Payload
Expand Down Expand Up @@ -520,6 +526,16 @@ impl ServiceRequest for BatchReceiveMessages {
}
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnalyticsData {
pub correlation_id: Option<Arc<str>>,
pub chain_id: Option<Arc<str>>,
pub rpc_methods: Option<Vec<Arc<str>>>,
pub tx_hashes: Option<Vec<Arc<str>>>,
pub contract_addresses: Option<Vec<Arc<str>>>,
}

/// Data structure representing publish request params.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Publish {
Expand All @@ -545,6 +561,9 @@ pub struct Publish {
/// webhook to a client through a push server.
#[serde(default, skip_serializing_if = "is_default")]
pub prompt: bool,

#[serde(default, flatten, skip_serializing_if = "is_default")]
pub analytics: Option<AnalyticsData>,
}

impl Publish {
Expand Down Expand Up @@ -860,4 +879,10 @@ impl Request {
Params::Subscription(params) => params.validate(),
}
}

pub fn strip_analytics(&mut self) {
if let Params::Publish(params) = &mut self.params {
params.analytics = None;
}
}
}
13 changes: 12 additions & 1 deletion relay_rpc/src/rpc/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,21 @@ fn request() {
ttl_secs: 12,
tag: 0,
prompt: false,
analytics: Some(AnalyticsData {
correlation_id: Some("correlation_id".into()),
chain_id: Some("chain_id".into()),
rpc_methods: Some(vec!["rpc_method".into()]),
tx_hashes: Some(vec!["tx_hash".into()]),
contract_addresses: Some(vec!["contract_address".into()]),
}),
}),
));

let serialized = serde_json::to_string(&payload).unwrap();

assert_eq!(
&serialized,
r#"{"id":1,"jsonrpc":"2.0","method":"irn_publish","params":{"topic":"topic","message":"payload","attestation":"attestation_payload","ttl":12,"tag":0}}"#
r#"{"id":1,"jsonrpc":"2.0","method":"irn_publish","params":{"topic":"topic","message":"payload","attestation":"attestation_payload","ttl":12,"tag":0,"correlationId":"correlation_id","chainId":"chain_id","rpcMethods":["rpc_method"],"txHashes":["tx_hash"],"contractAddresses":["contract_address"]}}"#
);

let deserialized: Payload = serde_json::from_str(&serialized).unwrap();
Expand Down Expand Up @@ -294,6 +301,7 @@ fn validation() {
ttl_secs: 0,
tag: 0,
prompt: false,
analytics: None,
}),
};
assert_eq!(request.validate(), Err(PayloadError::InvalidRequestId));
Expand All @@ -309,6 +317,7 @@ fn validation() {
ttl_secs: 0,
tag: 0,
prompt: false,
analytics: None,
}),
};
assert_eq!(request.validate(), Err(PayloadError::InvalidJsonRpcVersion));
Expand All @@ -324,6 +333,7 @@ fn validation() {
ttl_secs: 0,
tag: 0,
prompt: false,
analytics: None,
}),
};
assert_eq!(request.validate(), Ok(()));
Expand All @@ -339,6 +349,7 @@ fn validation() {
ttl_secs: 0,
tag: 0,
prompt: false,
analytics: None,
}),
};
assert_eq!(request.validate(), Err(PayloadError::InvalidTopic));
Expand Down

0 comments on commit 450006a

Please sign in to comment.