|
| 1 | +use crate::{DestinationGenerator, NodeInfo, PaymentGenerationError, PaymentGenerator}; |
| 2 | +use std::fmt; |
| 3 | +use tokio::time::Duration; |
| 4 | + |
| 5 | +#[derive(Clone)] |
| 6 | +pub struct DefinedPaymentActivity { |
| 7 | + destination: NodeInfo, |
| 8 | + wait: Duration, |
| 9 | + amount: u64, |
| 10 | +} |
| 11 | + |
| 12 | +impl DefinedPaymentActivity { |
| 13 | + pub fn new(destination: NodeInfo, wait: Duration, amount: u64) -> Self { |
| 14 | + DefinedPaymentActivity { |
| 15 | + destination, |
| 16 | + wait, |
| 17 | + amount, |
| 18 | + } |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +impl fmt::Display for DefinedPaymentActivity { |
| 23 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 24 | + write!( |
| 25 | + f, |
| 26 | + "static payment of {} to {} every {:?}", |
| 27 | + self.amount, self.destination, self.wait |
| 28 | + ) |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +impl DestinationGenerator for DefinedPaymentActivity { |
| 33 | + fn choose_destination(&self, _: bitcoin::secp256k1::PublicKey) -> (NodeInfo, Option<u64>) { |
| 34 | + (self.destination.clone(), None) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +impl PaymentGenerator for DefinedPaymentActivity { |
| 39 | + fn next_payment_wait(&self) -> Duration { |
| 40 | + self.wait |
| 41 | + } |
| 42 | + |
| 43 | + fn payment_amount( |
| 44 | + &self, |
| 45 | + destination_capacity: Option<u64>, |
| 46 | + ) -> Result<u64, crate::PaymentGenerationError> { |
| 47 | + if destination_capacity.is_some() { |
| 48 | + Err(PaymentGenerationError( |
| 49 | + "destination amount must not be set for defined activity generator".to_string(), |
| 50 | + )) |
| 51 | + } else { |
| 52 | + Ok(self.amount) |
| 53 | + } |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +#[cfg(test)] |
| 58 | +mod tests { |
| 59 | + use super::DefinedPaymentActivity; |
| 60 | + use crate::test_utils::{create_nodes, get_random_keypair}; |
| 61 | + use crate::{DestinationGenerator, PaymentGenerationError, PaymentGenerator}; |
| 62 | + use std::time::Duration; |
| 63 | + |
| 64 | + #[test] |
| 65 | + fn test_defined_activity_generator() { |
| 66 | + let node = create_nodes(1, 100000); |
| 67 | + let node = &node.first().unwrap().0; |
| 68 | + |
| 69 | + let source = get_random_keypair(); |
| 70 | + let payment_amt = 50; |
| 71 | + |
| 72 | + let generator = |
| 73 | + DefinedPaymentActivity::new(node.clone(), Duration::from_secs(60), payment_amt); |
| 74 | + |
| 75 | + let (dest, dest_capacity) = generator.choose_destination(source.1); |
| 76 | + assert_eq!(node.pubkey, dest.pubkey); |
| 77 | + assert!(dest_capacity.is_none()); |
| 78 | + |
| 79 | + assert_eq!(payment_amt, generator.payment_amount(None).unwrap()); |
| 80 | + assert!(matches!( |
| 81 | + generator.payment_amount(Some(10)), |
| 82 | + Err(PaymentGenerationError(..)) |
| 83 | + )); |
| 84 | + } |
| 85 | +} |
0 commit comments