hopr_crypto_packet/
validation.rs

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
use tracing::debug;

use hopr_crypto_types::types::Hash;
use hopr_internal_types::prelude::*;
use hopr_primitive_types::prelude::*;

use crate::errors::TicketValidationError;

/// Performs validations of the given unacknowledged ticket and channel.
/// This is a higher-level function, hence it is not in `hopr-internal-types` crate.
pub fn validate_unacknowledged_ticket(
    ticket: Ticket,
    channel: &ChannelEntry,
    min_ticket_amount: Balance,
    required_win_prob: f64,
    unrealized_balance: Balance,
    domain_separator: &Hash,
) -> Result<VerifiedTicket, TicketValidationError> {
    debug!(source = %channel.source, "validating unack ticket");

    // ticket signer MUST be the sender
    let verified_ticket = ticket
        .verify(&channel.source, domain_separator)
        .map_err(|ticket| TicketValidationError {
            reason: format!("ticket signer does not match the sender: {ticket}"),
            ticket,
        })?;

    let inner_ticket = verified_ticket.verified_ticket();

    // ticket amount MUST be greater or equal to minTicketAmount
    if !inner_ticket.amount.ge(&min_ticket_amount) {
        return Err(TicketValidationError {
            reason: format!(
                "ticket amount {} in not at least {min_ticket_amount}",
                inner_ticket.amount
            ),
            ticket: inner_ticket.clone().into(),
        });
    }

    // ticket must have at least required winning probability
    if !f64_approx_eq(
        verified_ticket.win_prob(),
        required_win_prob,
        LOWEST_POSSIBLE_WINNING_PROB,
    ) && verified_ticket.win_prob() < required_win_prob
    {
        return Err(TicketValidationError {
            reason: format!(
                "ticket winning probability {} is lower than required winning probability {required_win_prob}",
                verified_ticket.win_prob()
            ),
            ticket: inner_ticket.clone().into(),
        });
    }

    // channel MUST be open or pending to close
    if channel.status == ChannelStatus::Closed {
        return Err(TicketValidationError {
            reason: format!("payment channel {} is not opened or pending to close", channel.get_id()),
            ticket: inner_ticket.clone().into(),
        });
    }

    // ticket's channelEpoch MUST match the current channel's epoch
    if !channel.channel_epoch.eq(&inner_ticket.channel_epoch.into()) {
        return Err(TicketValidationError {
            reason: format!(
                "ticket was created for a different channel iteration {} != {} of channel {}",
                inner_ticket.channel_epoch,
                channel.channel_epoch,
                channel.get_id()
            ),
            ticket: inner_ticket.clone().into(),
        });
    }

    // ensure sender has enough funds
    if inner_ticket.amount.gt(&unrealized_balance) {
        return Err(TicketValidationError {
            reason: format!(
                "ticket value {} is greater than remaining unrealized balance {unrealized_balance} for channel {}",
                inner_ticket.amount,
                channel.get_id()
            ),
            ticket: inner_ticket.clone().into(),
        });
    }

    Ok(verified_ticket)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::validation::validate_unacknowledged_ticket;
    use hex_literal::hex;
    use hopr_crypto_types::prelude::*;
    use lazy_static::lazy_static;
    use std::ops::Add;

    const SENDER_PRIV_BYTES: [u8; 32] = hex!("492057cf93e99b31d2a85bc5e98a9c3aa0021feec52c227cc8170e8f7d047775");
    const TARGET_PRIV_BYTES: [u8; 32] = hex!("5bf21ea8cccd69aa784346b07bf79c84dac606e00eecaa68bf8c31aff397b1ca");

    lazy_static! {
        static ref SENDER_PRIV_KEY: ChainKeypair =
            ChainKeypair::from_secret(&SENDER_PRIV_BYTES).expect("lazy static keypair should be valid");
        static ref TARGET_PRIV_KEY: ChainKeypair =
            ChainKeypair::from_secret(&TARGET_PRIV_BYTES).expect("lazy static keypair should be valid");
    }

    fn create_valid_ticket() -> anyhow::Result<Ticket> {
        Ok(TicketBuilder::default()
            .addresses(&*SENDER_PRIV_KEY, &*TARGET_PRIV_KEY)
            .amount(1)
            .index(1)
            .index_offset(1)
            .win_prob(1.0)
            .channel_epoch(1)
            .challenge(Default::default())
            .build_signed(&SENDER_PRIV_KEY, &Hash::default())?
            .leak())
    }

    fn create_channel_entry() -> ChannelEntry {
        ChannelEntry::new(
            SENDER_PRIV_KEY.public().to_address(),
            TARGET_PRIV_KEY.public().to_address(),
            Balance::new(100_u64, BalanceType::HOPR),
            U256::zero(),
            ChannelStatus::Open,
            U256::one(),
        )
    }

    #[async_std::test]
    async fn test_ticket_validation_should_pass_if_ticket_ok() -> anyhow::Result<()> {
        let ticket = create_valid_ticket()?;
        let channel = create_channel_entry();

        let more_than_ticket_balance = ticket.amount.add(&Balance::new(U256::from(500u128), BalanceType::HOPR));

        let ret = validate_unacknowledged_ticket(
            ticket,
            &channel,
            Balance::new(1_u64, BalanceType::HOPR),
            1.0f64,
            more_than_ticket_balance,
            &Hash::default(),
        );

        assert!(ret.is_ok());

        Ok(())
    }

    #[async_std::test]
    async fn test_ticket_validation_should_fail_if_signer_not_sender() -> anyhow::Result<()> {
        let ticket = create_valid_ticket()?;
        let channel = create_channel_entry();

        let ret = validate_unacknowledged_ticket(
            ticket,
            &channel,
            Balance::new(1_u64, BalanceType::HOPR),
            1.0f64,
            Balance::zero(BalanceType::HOPR),
            &Hash::default(),
        );

        assert!(ret.is_err());

        Ok(())
    }

    #[async_std::test]
    async fn test_ticket_validation_should_fail_if_ticket_amount_is_low() -> anyhow::Result<()> {
        let ticket = create_valid_ticket()?;
        let channel = create_channel_entry();

        let ret = validate_unacknowledged_ticket(
            ticket,
            &channel,
            Balance::new(2_u64, BalanceType::HOPR),
            1.0f64,
            Balance::zero(BalanceType::HOPR),
            &Hash::default(),
        );

        assert!(ret.is_err());

        Ok(())
    }

    #[async_std::test]
    async fn test_ticket_validation_should_fail_if_ticket_chance_is_low() -> anyhow::Result<()> {
        let mut ticket = create_valid_ticket()?;
        ticket.encoded_win_prob = f64_to_win_prob(0.5f64)?;
        let ticket = ticket
            .sign(&SENDER_PRIV_KEY, &Hash::default())
            .verified_ticket()
            .clone();

        let channel = create_channel_entry();

        let ret = validate_unacknowledged_ticket(
            ticket,
            &channel,
            Balance::new(1_u64, BalanceType::HOPR),
            1.0_f64,
            Balance::zero(BalanceType::HOPR),
            &Hash::default(),
        );

        assert!(ret.is_err());

        Ok(())
    }

    #[async_std::test]
    async fn test_ticket_validation_should_fail_if_channel_is_closed() -> anyhow::Result<()> {
        let ticket = create_valid_ticket()?;
        let mut channel = create_channel_entry();
        channel.status = ChannelStatus::Closed;

        let ret = validate_unacknowledged_ticket(
            ticket,
            &channel,
            Balance::new(1_u64, BalanceType::HOPR),
            1.0_f64,
            Balance::zero(BalanceType::HOPR),
            &Hash::default(),
        );

        assert!(ret.is_err());

        Ok(())
    }

    #[async_std::test]
    async fn test_ticket_validation_should_fail_if_ticket_epoch_does_not_match_2() -> anyhow::Result<()> {
        let mut ticket = create_valid_ticket()?;
        ticket.channel_epoch = 2u32;
        let ticket = ticket
            .sign(&SENDER_PRIV_KEY, &Hash::default())
            .verified_ticket()
            .clone();

        let channel = create_channel_entry();

        let ret = validate_unacknowledged_ticket(
            ticket,
            &channel,
            Balance::new(1_u64, BalanceType::HOPR),
            1.0_f64,
            Balance::zero(BalanceType::HOPR),
            &Hash::default(),
        );

        assert!(ret.is_err());

        Ok(())
    }

    #[async_std::test]
    async fn test_ticket_validation_fail_if_does_not_have_funds() -> anyhow::Result<()> {
        let ticket = create_valid_ticket()?;
        let mut channel = create_channel_entry();
        channel.balance = Balance::zero(BalanceType::HOPR);
        channel.channel_epoch = U256::from(ticket.channel_epoch);

        let ret = validate_unacknowledged_ticket(
            ticket,
            &channel,
            Balance::new(1_u64, BalanceType::HOPR),
            1.0_f64,
            Balance::zero(BalanceType::HOPR),
            &Hash::default(),
        );

        assert!(ret.is_err());

        Ok(())
    }
}