1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#![warn(
    missing_debug_implementations,
    missing_docs,
    rust_2018_idioms,
    unreachable_pub
)]

//! `cashweb-relay-client` is a library providing [`RelayClient`] which allows
//! interaction with specific relay server.

pub mod services;

use std::{error, fmt};

pub use hyper::{
    client::{connect::Connect, HttpConnector},
    Uri,
};

use hyper::client::Client as HyperClient;
use hyper::http::uri::InvalidUri;
use secp256k1::key::PublicKey;
use thiserror::Error;
use tower_service::Service;
use tower_util::ServiceExt;

use relay::Profile;
use services::*;

/// RelayClient allows queries to specific relay servers.
#[derive(Clone, Debug)]
pub struct RelayClient<S> {
    inner_client: S,
}

impl<S> RelayClient<S> {
    /// Create a new client from a service.
    pub fn from_service(service: S) -> Self {
        Self {
            inner_client: service,
        }
    }
}

impl Default for RelayClient<HyperClient<HttpConnector>> {
    fn default() -> Self {
        Self {
            inner_client: HyperClient::new(),
        }
    }
}

impl RelayClient<HyperClient<HttpConnector>> {
    /// Create a new HTTP client.
    pub fn new() -> Self {
        Default::default()
    }
}

/// Error associated with sending a request to a relay server.
#[derive(Debug, Error)]
pub enum RelayError<E: fmt::Debug + fmt::Display + error::Error + 'static> {
    /// Invalid URI.
    #[error(transparent)]
    Uri(InvalidUri),
    /// Error executing the service method.
    #[error("failed to execute service method: {0}")]
    Error(#[from] E),
}

/// A [`Profile`] paired with its [`PublicKey`].
#[derive(Clone, Debug)]
pub struct ProfilePackage {
    /// Public key of the metadata.
    pub public_key: PublicKey,
    /// The profile.
    pub profile: Profile,
}

impl<S> RelayClient<S>
where
    Self: Service<(Uri, GetProfile), Response = ProfilePackage>,
    Self: Sync + Clone + Send + 'static,
    <Self as Service<(Uri, GetProfile)>>::Future: Send + Sync + 'static,
    <Self as Service<(Uri, GetProfile)>>::Error: fmt::Debug + fmt::Display + error::Error,
{
    /// Get [`Profile`] from a server. The result is wrapped in [`ProfilePackage`].
    pub async fn get_profile(
        &self,
        keyserver_url: &str,
        address: &str,
    ) -> Result<ProfilePackage, RelayError<<Self as Service<(Uri, GetProfile)>>::Error>> {
        // Construct URI
        let full_path = format!("{}/profiles/{}", keyserver_url, address);
        let uri: Uri = full_path.parse().map_err(RelayError::Uri)?;

        // Construct request
        let request = (uri, GetProfile);

        self.clone()
            .oneshot(request)
            .await
            .map_err(RelayError::Error)
    }
}

impl<S> RelayClient<S>
where
    Self: Service<(Uri, PutProfile), Response = ()>,
    Self: Sync + Clone + Send + 'static,
    <Self as Service<(Uri, PutProfile)>>::Future: Send + Sync + 'static,
    <Self as Service<(Uri, PutProfile)>>::Error: fmt::Debug + fmt::Display + error::Error,
{
    /// Put a [`Profile`] to a relay server.
    pub async fn put_profile(
        &self,
        relay_url: &str,
        address: &str,
        profile: Profile,
        token: String,
    ) -> Result<(), RelayError<<Self as Service<(Uri, PutProfile)>>::Error>> {
        // Construct URI
        let full_path = format!("{}/profiles/{}", relay_url, address);
        let uri: Uri = full_path.parse().map_err(RelayError::Uri)?;

        // Construct request
        let request = (uri, PutProfile { token, profile });

        // Get response
        self.clone()
            .oneshot(request)
            .await
            .map_err(RelayError::Error)
    }
}