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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
use bytes::Bytes;
use futures::Future;
use interledger_http::{HttpAccount, HttpStore};
use interledger_packet::Address;
use interledger_router::RouterStore;
use interledger_service::{Account, AddressStore, IncomingService, OutgoingService, Username};
use interledger_service_util::{BalanceStore, ExchangeRateStore};
use interledger_settlement::core::types::{SettlementAccount, SettlementStore};
use interledger_stream::StreamNotificationsStore;
use serde::{de, Deserialize, Serialize};
use std::{boxed::*, collections::HashMap, fmt::Display, net::SocketAddr, str::FromStr};
use warp::{self, Filter};
mod routes;
use interledger_btp::{BtpAccount, BtpOutgoingService};
use interledger_ccp::CcpRoutingAccount;
use secrecy::SecretString;
use url::Url;

pub(crate) mod http_retry;

// This enum and the following functions are used to allow clients to send either
// numbers or strings and have them be properly deserialized into the appropriate
// integer type.
#[derive(Deserialize)]
#[serde(untagged)]
enum NumOrStr<T> {
    Num(T),
    Str(String),
}

pub fn number_or_string<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: de::Deserializer<'de>,
    T: FromStr + Deserialize<'de>,
    <T as FromStr>::Err: Display,
{
    match NumOrStr::deserialize(deserializer)? {
        NumOrStr::Num(n) => Ok(n),
        NumOrStr::Str(s) => T::from_str(&s).map_err(de::Error::custom),
    }
}

pub fn optional_number_or_string<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: de::Deserializer<'de>,
    T: FromStr + Deserialize<'de>,
    <T as FromStr>::Err: Display,
{
    match NumOrStr::deserialize(deserializer)? {
        NumOrStr::Num(n) => Ok(Some(n)),
        NumOrStr::Str(s) => T::from_str(&s)
            .map_err(de::Error::custom)
            .and_then(|n| Ok(Some(n))),
    }
}

pub fn map_of_number_or_string<'de, D>(deserializer: D) -> Result<HashMap<String, f64>, D::Error>
where
    D: de::Deserializer<'de>,
{
    #[derive(Deserialize)]
    struct Wrapper(#[serde(deserialize_with = "number_or_string")] f64);

    let v = HashMap::<String, Wrapper>::deserialize(deserializer)?;
    Ok(v.into_iter().map(|(k, Wrapper(v))| (k, v)).collect())
}

// TODO should the methods from this trait be split up and put into the
// traits that are more specific to what they're doing?
// One argument against doing that is that the NodeStore allows admin-only
// modifications to the values, whereas many of the other traits mostly
// read from the configured values.
pub trait NodeStore: AddressStore + Clone + Send + Sync + 'static {
    type Account: Account;

    fn insert_account(
        &self,
        account: AccountDetails,
    ) -> Box<dyn Future<Item = Self::Account, Error = ()> + Send>;

    fn delete_account(
        &self,
        id: <Self::Account as Account>::AccountId,
    ) -> Box<dyn Future<Item = Self::Account, Error = ()> + Send>;

    fn update_account(
        &self,
        id: <Self::Account as Account>::AccountId,
        account: AccountDetails,
    ) -> Box<dyn Future<Item = Self::Account, Error = ()> + Send>;

    fn modify_account_settings(
        &self,
        id: <Self::Account as Account>::AccountId,
        settings: AccountSettings,
    ) -> Box<dyn Future<Item = Self::Account, Error = ()> + Send>;

    // TODO limit the number of results and page through them
    fn get_all_accounts(&self) -> Box<dyn Future<Item = Vec<Self::Account>, Error = ()> + Send>;

    fn set_static_routes<R>(&self, routes: R) -> Box<dyn Future<Item = (), Error = ()> + Send>
    where
        R: IntoIterator<Item = (String, <Self::Account as Account>::AccountId)>;

    fn set_static_route(
        &self,
        prefix: String,
        account_id: <Self::Account as Account>::AccountId,
    ) -> Box<dyn Future<Item = (), Error = ()> + Send>;

    fn set_default_route(
        &self,
        account_id: <Self::Account as Account>::AccountId,
    ) -> Box<dyn Future<Item = (), Error = ()> + Send>;

    fn set_settlement_engines(
        &self,
        asset_to_url_map: impl IntoIterator<Item = (String, Url)>,
    ) -> Box<dyn Future<Item = (), Error = ()> + Send>;

    fn get_asset_settlement_engine(
        &self,
        asset_code: &str,
    ) -> Box<dyn Future<Item = Option<Url>, Error = ()> + Send>;
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExchangeRates(
    #[serde(deserialize_with = "map_of_number_or_string")] HashMap<String, f64>,
);

/// AccountSettings is a subset of the user parameters defined in
/// AccountDetails. Its purpose is to allow a user to modify certain of their
/// parameters which they may want to re-configure in the future, such as their
/// tokens (which act as passwords), their settlement frequency preferences, or
/// their HTTP/BTP endpoints, since they may change their network configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AccountSettings {
    pub ilp_over_http_incoming_token: Option<SecretString>,
    pub ilp_over_btp_incoming_token: Option<SecretString>,
    pub ilp_over_http_outgoing_token: Option<SecretString>,
    pub ilp_over_btp_outgoing_token: Option<SecretString>,
    pub ilp_over_http_url: Option<String>,
    pub ilp_over_btp_url: Option<String>,
    #[serde(default, deserialize_with = "optional_number_or_string")]
    pub settle_threshold: Option<i64>,
    // Note that this is intentionally an unsigned integer because users should
    // not be able to set the settle_to value to be negative (meaning the node
    // would pre-fund with the user)
    #[serde(default, deserialize_with = "optional_number_or_string")]
    pub settle_to: Option<u64>,
}

/// EncryptedAccountSettings is created by encrypting the incoming and outgoing
/// HTTP and BTP tokens of an AccountSettings object. The rest of the fields
/// remain the same. It is intended to be consumed by the internal store
/// implementation which operates only on encrypted data.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct EncryptedAccountSettings {
    pub ilp_over_http_incoming_token: Option<Bytes>,
    pub ilp_over_btp_incoming_token: Option<Bytes>,
    pub ilp_over_http_outgoing_token: Option<Bytes>,
    pub ilp_over_btp_outgoing_token: Option<Bytes>,
    pub ilp_over_http_url: Option<String>,
    pub ilp_over_btp_url: Option<String>,
    #[serde(default, deserialize_with = "optional_number_or_string")]
    pub settle_threshold: Option<i64>,
    #[serde(default, deserialize_with = "optional_number_or_string")]
    pub settle_to: Option<u64>,
}

/// The Account type for the RedisStore.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountDetails {
    pub ilp_address: Option<Address>,
    pub username: Username,
    pub asset_code: String,
    #[serde(deserialize_with = "number_or_string")]
    pub asset_scale: u8,
    #[serde(default = "u64::max_value", deserialize_with = "number_or_string")]
    pub max_packet_amount: u64,
    #[serde(default, deserialize_with = "optional_number_or_string")]
    pub min_balance: Option<i64>,
    pub ilp_over_http_url: Option<String>,
    pub ilp_over_http_incoming_token: Option<SecretString>,
    pub ilp_over_http_outgoing_token: Option<SecretString>,
    pub ilp_over_btp_url: Option<String>,
    pub ilp_over_btp_outgoing_token: Option<SecretString>,
    pub ilp_over_btp_incoming_token: Option<SecretString>,
    #[serde(default, deserialize_with = "optional_number_or_string")]
    pub settle_threshold: Option<i64>,
    #[serde(default, deserialize_with = "optional_number_or_string")]
    pub settle_to: Option<i64>,
    pub routing_relation: Option<String>,
    #[serde(default, deserialize_with = "optional_number_or_string")]
    pub round_trip_time: Option<u32>,
    #[serde(default, deserialize_with = "optional_number_or_string")]
    pub amount_per_minute_limit: Option<u64>,
    #[serde(default, deserialize_with = "optional_number_or_string")]
    pub packets_per_minute_limit: Option<u32>,
    pub settlement_engine_url: Option<String>,
}

pub struct NodeApi<S, I, O, B, A: Account> {
    store: S,
    admin_api_token: String,
    default_spsp_account: Option<Username>,
    incoming_handler: I,
    // The outgoing service is included so that the API can send outgoing
    // requests to specific accounts (namely ILDCP requests)
    outgoing_handler: O,
    // The BTP service is included here so that we can add a new client
    // connection when an account is added with BTP details
    btp: BtpOutgoingService<B, A>,
    server_secret: Bytes,
    node_version: Option<String>,
}

impl<S, I, O, B, A> NodeApi<S, I, O, B, A>
where
    S: NodeStore<Account = A>
        + HttpStore<Account = A>
        + BalanceStore<Account = A>
        + SettlementStore<Account = A>
        + StreamNotificationsStore<Account = A>
        + RouterStore
        + ExchangeRateStore,
    I: IncomingService<A> + Clone + Send + Sync + 'static,
    O: OutgoingService<A> + Clone + Send + Sync + 'static,
    B: OutgoingService<A> + Clone + Send + Sync + 'static,
    A: BtpAccount
        + CcpRoutingAccount
        + Account
        + HttpAccount
        + SettlementAccount
        + Serialize
        + Send
        + Sync
        + 'static,
{
    pub fn new(
        server_secret: Bytes,
        admin_api_token: String,
        store: S,
        incoming_handler: I,
        outgoing_handler: O,
        btp: BtpOutgoingService<B, A>,
    ) -> Self {
        NodeApi {
            store,
            admin_api_token,
            default_spsp_account: None,
            incoming_handler,
            outgoing_handler,
            btp,
            server_secret,
            node_version: None,
        }
    }

    pub fn default_spsp_account(&mut self, username: Username) -> &mut Self {
        self.default_spsp_account = Some(username);
        self
    }

    pub fn node_version(&mut self, version: String) -> &mut Self {
        self.node_version = Some(version);
        self
    }

    pub fn into_warp_filter(self) -> warp::filters::BoxedFilter<(impl warp::Reply,)> {
        routes::accounts_api(
            self.server_secret,
            self.admin_api_token.clone(),
            self.default_spsp_account,
            self.incoming_handler,
            self.outgoing_handler,
            self.btp,
            self.store.clone(),
        )
        .or(routes::node_settings_api(
            self.admin_api_token,
            self.node_version,
            self.store,
        ))
        .boxed()
    }

    pub fn bind(self, addr: SocketAddr) -> impl Future<Item = (), Error = ()> {
        warp::serve(self.into_warp_filter()).bind(addr)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{self, json};

    #[test]
    fn number_or_string_deserialization() {
        #[derive(PartialEq, Deserialize, Debug)]
        struct One {
            #[serde(deserialize_with = "number_or_string")]
            val: u64,
        }
        assert_eq!(
            serde_json::from_str::<One>("{\"val\":1}").unwrap(),
            One { val: 1 }
        );
        assert_eq!(
            serde_json::from_str::<One>("{\"val\":\"1\"}").unwrap(),
            One { val: 1 }
        );

        assert!(serde_json::from_str::<One>("{\"val\":\"not-a-number\"}").is_err());
        assert!(serde_json::from_str::<One>("{\"val\":\"-1\"}").is_err());
    }

    #[test]
    fn optional_number_or_string_deserialization() {
        #[derive(PartialEq, Deserialize, Debug)]
        struct One {
            #[serde(deserialize_with = "optional_number_or_string")]
            val: Option<u64>,
        }
        assert_eq!(
            serde_json::from_str::<One>("{\"val\":1}").unwrap(),
            One { val: Some(1) }
        );
        assert_eq!(
            serde_json::from_str::<One>("{\"val\":\"1\"}").unwrap(),
            One { val: Some(1) }
        );
        assert!(serde_json::from_str::<One>("{}").is_err());

        #[derive(PartialEq, Deserialize, Debug)]
        struct Two {
            #[serde(default, deserialize_with = "optional_number_or_string")]
            val: Option<u64>,
        }
        assert_eq!(
            serde_json::from_str::<Two>("{\"val\":2}").unwrap(),
            Two { val: Some(2) }
        );
        assert_eq!(
            serde_json::from_str::<Two>("{\"val\":\"2\"}").unwrap(),
            Two { val: Some(2) }
        );
        assert_eq!(
            serde_json::from_str::<Two>("{}").unwrap(),
            Two { val: None }
        );
    }

    #[test]
    fn account_settings_deserialization() {
        let settings: AccountSettings = serde_json::from_value(json!({
            "ilp_over_http_url": "https://example.com/ilp",
            "ilp_over_http_incoming_token": "secret",
            "settle_to": 0,
            "settle_threshold": "1000",
        }))
        .unwrap();
        assert_eq!(settings.settle_threshold, Some(1000));
        assert_eq!(settings.settle_to, Some(0));
        assert_eq!(
            settings.ilp_over_http_url,
            Some("https://example.com/ilp".to_string())
        );
        assert!(settings.ilp_over_btp_url.is_none());
    }
}