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
use chrono::{DateTime, Duration, Utc};
use interledger_service::{Account, OutgoingRequest, OutgoingService};
use log::trace;

pub const DEFAULT_ROUND_TRIP_TIME: u32 = 500;
pub const DEFAULT_MAX_EXPIRY_DURATION: u32 = 30000;

pub trait RoundTripTimeAccount: Account {
    fn round_trip_time(&self) -> u32 {
        DEFAULT_ROUND_TRIP_TIME
    }
}

/// # Expiry Shortener Service
///
/// Each node shortens the `Prepare` packet's expiry duration before passing it on.
/// Nodes shorten the expiry duration so that even if the packet is fulfilled just before the expiry,
/// they will still have enough time to pass the fulfillment to the previous node before it expires.
///
/// This service reduces the expiry time of each packet before forwarding it out.
/// Requires a `RoundtripTimeAccount` and _no store_
#[derive(Clone)]
pub struct ExpiryShortenerService<O> {
    next: O,
    max_expiry_duration: u32,
}

impl<O> ExpiryShortenerService<O> {
    pub fn new(next: O) -> Self {
        ExpiryShortenerService {
            next,
            max_expiry_duration: DEFAULT_MAX_EXPIRY_DURATION,
        }
    }

    pub fn max_expiry_duration(&mut self, milliseconds: u32) -> &mut Self {
        self.max_expiry_duration = milliseconds;
        self
    }
}

impl<O, A> OutgoingService<A> for ExpiryShortenerService<O>
where
    O: OutgoingService<A>,
    A: RoundTripTimeAccount,
{
    type Future = O::Future;

    /// On send request:
    /// 1. Get the sender and receiver's roundtrip time (default 1000ms)
    /// 2. Reduce the packet's expiry by that amount
    /// 3. Ensure that the packet expiry does not exceed the maximum expiry duration
    /// 4. Forward the request
    fn send_request(&mut self, mut request: OutgoingRequest<A>) -> Self::Future {
        let time_to_subtract =
            i64::from(request.from.round_trip_time() + request.to.round_trip_time());
        let new_expiry = DateTime::<Utc>::from(request.prepare.expires_at())
            - Duration::milliseconds(time_to_subtract);

        let latest_allowable_expiry =
            Utc::now() + Duration::milliseconds(i64::from(self.max_expiry_duration));
        let new_expiry = if new_expiry > latest_allowable_expiry {
            trace!(
                "Shortening packet expiry duration to {}ms in the future",
                self.max_expiry_duration
            );
            latest_allowable_expiry
        } else {
            new_expiry
        };

        request.prepare.set_expires_at(new_expiry.into());
        self.next.send_request(request)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::Future;
    use interledger_packet::{Address, ErrorCode, FulfillBuilder, PrepareBuilder, RejectBuilder};
    use interledger_service::{outgoing_service_fn, Username};
    use std::str::FromStr;

    use lazy_static::lazy_static;

    lazy_static! {
        pub static ref ALICE: Username = Username::from_str("alice").unwrap();
        pub static ref EXAMPLE_ADDRESS: Address = Address::from_str("example.alice").unwrap();
    }

    #[derive(Clone, Debug)]
    struct TestAccount(u64, u32);
    impl Account for TestAccount {
        type AccountId = u64;

        fn id(&self) -> u64 {
            self.0
        }

        fn username(&self) -> &Username {
            &ALICE
        }

        fn asset_code(&self) -> &str {
            "XYZ"
        }

        // All connector accounts use asset scale = 9.
        fn asset_scale(&self) -> u8 {
            9
        }

        fn ilp_address(&self) -> &Address {
            &EXAMPLE_ADDRESS
        }
    }

    impl RoundTripTimeAccount for TestAccount {
        fn round_trip_time(&self) -> u32 {
            self.1
        }
    }

    #[test]
    fn shortens_expiry_by_round_trip_time() {
        let original_expiry = Utc::now() + Duration::milliseconds(30000);
        let mut service = ExpiryShortenerService::new(outgoing_service_fn(move |request| {
            if DateTime::<Utc>::from(request.prepare.expires_at())
                == original_expiry - Duration::milliseconds(1300)
            {
                Ok(FulfillBuilder {
                    fulfillment: &[0; 32],
                    data: &[],
                }
                .build())
            } else {
                Err(RejectBuilder {
                    code: ErrorCode::F00_BAD_REQUEST,
                    message: &[],
                    data: &[],
                    triggered_by: None,
                }
                .build())
            }
        }));
        service
            .send_request(OutgoingRequest {
                from: TestAccount(0, 600),
                to: TestAccount(1, 700),
                prepare: PrepareBuilder {
                    destination: Address::from_str("example.destination").unwrap(),
                    amount: 10,
                    expires_at: original_expiry.into(),
                    data: &[],
                    execution_condition: &[0; 32],
                }
                .build(),
                original_amount: 10,
            })
            .wait()
            .expect("Should have shortened expiry");
    }

    #[test]
    fn reduces_expiry_to_max_duration() {
        let mut service = ExpiryShortenerService::new(outgoing_service_fn(move |request| {
            if DateTime::<Utc>::from(request.prepare.expires_at()) - Utc::now()
                <= Duration::milliseconds(30000)
            {
                Ok(FulfillBuilder {
                    fulfillment: &[0; 32],
                    data: &[],
                }
                .build())
            } else {
                Err(RejectBuilder {
                    code: ErrorCode::F00_BAD_REQUEST,
                    message: &[],
                    data: &[],
                    triggered_by: None,
                }
                .build())
            }
        }));
        service
            .send_request(OutgoingRequest {
                from: TestAccount(0, 500),
                to: TestAccount(1, 500),
                prepare: PrepareBuilder {
                    destination: Address::from_str("example.destination").unwrap(),
                    amount: 10,
                    expires_at: (Utc::now() + Duration::milliseconds(45000)).into(),
                    data: &[],
                    execution_condition: &[0; 32],
                }
                .build(),
                original_amount: 10,
            })
            .wait()
            .expect("Should have shortened expiry");
    }
}