Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 136 additions & 2 deletions payday_core/src/aggregate/lightning_aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@ impl Aggregate for LightningInvoice {
amount,
invoice,
} => {
if !self.invoice_id.is_empty() {
return Err(Error::InvoiceAlreadyExists(invoice_id));
}

if amount.currency != Currency::Btc {
return Err(Error::InvalidCurrency(
amount.currency.to_string(),
Expand All @@ -124,10 +128,13 @@ impl Aggregate for LightningInvoice {
}])
}
LightningInvoiceCommand::SettleInvoice { received_amount } => {
if self.paid {
return Ok(vec![]);
}
Ok(vec![LightningInvoiceEvent::InvoiceSettled {
received_amount,
overpaid: received_amount.amount > self.amount.amount,
paid: received_amount.amount >= self.amount.amount,
overpaid: received_amount.cent_amount > self.amount.cent_amount,
paid: received_amount.cent_amount >= self.amount.cent_amount,
}])
}
}
Expand Down Expand Up @@ -160,3 +167,130 @@ impl Aggregate for LightningInvoice {
}
}
}

#[cfg(test)]
mod tests {
use std::str::FromStr;

use cqrs_es::test::TestFramework;

use super::*;

type LightningInvoiceTestFramework = TestFramework<LightningInvoice>;

#[test]
fn test_create_lightning_invoice() {
let expected_event = mock_created_event();
LightningInvoiceTestFramework::with(())
.given_no_previous_events()
.when(LightningInvoiceCommand::CreateInvoice {
invoice_id: "123".to_string(),
node_id: "node1".to_string(),
amount: Amount::sats(100_000),
invoice: get_invoice(),
})
.then_expect_events(vec![expected_event]);
}

#[test]
fn test_settle_lightning_invoice() {
let expected_event = mock_settled_event(Amount::sats(100_000), false, true);
LightningInvoiceTestFramework::with(())
.given(vec![mock_created_event()])
.when(LightningInvoiceCommand::SettleInvoice {
received_amount: Amount::sats(100_000),
})
.then_expect_events(vec![expected_event]);
}

#[test]
fn test_create_lightning_invoice_invalid_currency() {
let expected_error = Error::InvalidCurrency("USD".to_string(), "BTC".to_string());
LightningInvoiceTestFramework::with(())
.given_no_previous_events()
.when(LightningInvoiceCommand::CreateInvoice {
invoice_id: "123".to_string(),
node_id: "node1".to_string(),
amount: Amount::new(Currency::Usd, 100_000),
invoice: get_invoice(),
})
.then_expect_error(expected_error);
}

#[test]
fn test_settle_lightning_invoice_overpaid() {
let expected_event = mock_settled_event(Amount::sats(200_000), true, true);
LightningInvoiceTestFramework::with(())
.given(vec![mock_created_event()])
.when(LightningInvoiceCommand::SettleInvoice {
received_amount: Amount::sats(200_000),
})
.then_expect_events(vec![expected_event]);
}

#[test]
fn test_settle_lightning_invoice_underpaid() {
let expected_event = mock_settled_event(Amount::sats(50_000), false, false);
LightningInvoiceTestFramework::with(())
.given(vec![mock_created_event()])
.when(LightningInvoiceCommand::SettleInvoice {
received_amount: Amount::sats(50_000),
})
.then_expect_events(vec![expected_event]);
}
#[test]
fn test_create_lightning_invoice_already_exists() {
let expected_error = Error::InvoiceAlreadyExists("123".to_string());
LightningInvoiceTestFramework::with(())
.given(vec![mock_created_event()])
.when(LightningInvoiceCommand::CreateInvoice {
invoice_id: "123".to_string(),
node_id: "node1".to_string(),
amount: Amount::sats(100_000),
invoice: get_invoice(),
})
.then_expect_error(expected_error);
}

#[test]
fn test_set_confirmed_lightning_invoice_already_confirmed() {
LightningInvoiceTestFramework::with(())
.given(vec![
mock_created_event(),
mock_settled_event(Amount::sats(100_000), false, true),
])
.when(LightningInvoiceCommand::SettleInvoice {
received_amount: Amount::sats(100_000),
})
.then_expect_events(vec![]);
}

fn mock_created_event() -> LightningInvoiceEvent {
let invoice = get_invoice();
LightningInvoiceEvent::InvoiceCreated {
invoice_id: "123".to_string(),
node_id: "node1".to_string(),
amount: Amount::sats(100_000),
invoice: invoice.to_string(),
r_hash: invoice.payment_hash().to_string(),
}
}

fn mock_settled_event(
received_amount: Amount,
overpaid: bool,
paid: bool,
) -> LightningInvoiceEvent {
LightningInvoiceEvent::InvoiceSettled {
received_amount,
overpaid,
paid,
}
}

fn get_invoice() -> Bolt11Invoice {
Bolt11Invoice::from_str(
"lntbs3m1pnf36h3pp5dm63f7meus5thxd3h23uqkfuydw340nrf6v8y398ga7tqjfrpnfsdq5w3jhxapqd9h8vmmfvdjscqzzsxq97ztucsp5yle6azm0tpy7h3dh0d6kmpzzzpyvzqkck476l96z5p5leqaraumq9qyyssqghpt4k54rrutwumlq6hav5wdjghlrxnyxe5dde37e5t4wwz4kkq3r5284l3rcnyzzqvry6xz4s8mq42npq8fzr7j9tvvuyh32xmh97gq0h8hdp"
).expect("valid invoice")
}
}
103 changes: 81 additions & 22 deletions payday_core/src/aggregate/on_chain_aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,13 +169,19 @@ impl Aggregate for OnChainInvoice {
amount,
address,
} => {
// invalid currency
if amount.currency != Currency::Btc {
return Err(Error::InvalidCurrency(
amount.currency.to_string(),
Currency::Btc.to_string(),
));
}

// invoice already exists
if !self.invoice_id.is_empty() {
return Err(Error::InvoiceAlreadyExists(invoice_id));
}

Ok(vec![OnChainInvoiceEvent::InvoiceCreated {
invoice_id,
node_id,
Expand All @@ -184,23 +190,35 @@ impl Aggregate for OnChainInvoice {
}])
}
OnChainInvoiceCommand::SetPending { amount } => {
// already payd or pending
if self.received_amount.cent_amount > 0 {
return Ok(Vec::new());
}

Ok(vec![OnChainInvoiceEvent::PaymentPending {
received_amount: amount,
underpayment: amount.amount < self.amount.amount,
overpayment: amount.amount > self.amount.amount,
underpayment: amount.cent_amount < self.amount.cent_amount,
overpayment: amount.cent_amount > self.amount.cent_amount,
}])
}
OnChainInvoiceCommand::SetConfirmed {
confirmations,
amount,
transaction_id,
} => Ok(vec![OnChainInvoiceEvent::PaymentConfirmed {
received_amount: amount,
underpayment: amount.amount < self.amount.amount,
overpayment: amount.amount > self.amount.amount,
confirmations,
transaction_id,
}]),
} => {
// already confirmed
if self.confirmations > 0 {
return Ok(Vec::new());
}

Ok(vec![OnChainInvoiceEvent::PaymentConfirmed {
received_amount: amount,
underpayment: amount.cent_amount < self.amount.cent_amount,
overpayment: amount.cent_amount > self.amount.cent_amount,
confirmations,
transaction_id,
}])
}
}
}

Expand Down Expand Up @@ -261,16 +279,16 @@ mod aggregate_tests {
.when(OnChainInvoiceCommand::CreateInvoice {
invoice_id: "123".to_string(),
node_id: "node1".to_string(),
amount: amount_fn(100_000),
amount: Amount::sats(100_000),
address: "tb1q6xm2qgh5r83lvmmu0v7c3d4wrd9k2uxu3sgcr4".to_string(),
})
.then_expect_events(vec![expected])
}

#[test]
fn test_set_pending() {
let amount = amount_fn(100_000);
let expected = mock_pending_event(amount.amount, false, false);
let amount = Amount::sats(100_000);
let expected = mock_pending_event(amount.cent_amount, false, false);
OnChainInvoiceTestFramework::with(())
.given(vec![mock_created_event(100_000)])
.when(OnChainInvoiceCommand::SetPending { amount })
Expand All @@ -279,8 +297,8 @@ mod aggregate_tests {

#[test]
fn test_pending_overpayment() {
let amount = amount_fn(100_001);
let expected = mock_pending_event(amount.amount, false, true);
let amount = Amount::sats(100_001);
let expected = mock_pending_event(amount.cent_amount, false, true);
OnChainInvoiceTestFramework::with(())
.given(vec![mock_created_event(100_000)])
.when(OnChainInvoiceCommand::SetPending { amount })
Expand All @@ -289,8 +307,8 @@ mod aggregate_tests {

#[test]
fn test_pending_underpayment() {
let amount = amount_fn(99_999);
let expected = mock_pending_event(amount.amount, true, false);
let amount = Amount::sats(99_999);
let expected = mock_pending_event(amount.cent_amount, true, false);
OnChainInvoiceTestFramework::with(())
.given(vec![mock_created_event(100_000)])
.when(OnChainInvoiceCommand::SetPending { amount })
Expand All @@ -300,7 +318,7 @@ mod aggregate_tests {
#[test]
fn test_set_confirmed() {
let expected = OnChainInvoiceEvent::PaymentConfirmed {
received_amount: Amount::new(Currency::Btc, 100_000),
received_amount: Amount::sats(100_000),
underpayment: false,
overpayment: false,
confirmations: 1,
Expand All @@ -310,14 +328,55 @@ mod aggregate_tests {
.given(vec![mock_created_event(100_000)])
.when(OnChainInvoiceCommand::SetConfirmed {
confirmations: 1,
amount: Amount::new(Currency::Btc, 100_000),
amount: Amount::sats(100_000),
transaction_id: "txid".to_string(),
})
.then_expect_events(vec![expected])
}

fn amount_fn(amount: u64) -> Amount {
Amount::new(Currency::Btc, amount)
#[test]
fn test_create_invoice_already_exists() {
let expected_error = Error::InvoiceAlreadyExists("123".to_string());
OnChainInvoiceTestFramework::with(())
.given(vec![mock_created_event(100_000)])
.when(OnChainInvoiceCommand::CreateInvoice {
invoice_id: "123".to_string(),
node_id: "node1".to_string(),
amount: Amount::sats(100_000),
address: "tb1q6xm2qgh5r83lvmmu0v7c3d4wrd9k2uxu3sgcr4".to_string(),
})
.then_expect_error(expected_error);
}

#[test]
fn test_set_pending_already_pending() {
let amount = Amount::sats(100_000);
OnChainInvoiceTestFramework::with(())
.given(vec![
mock_created_event(100_000),
mock_pending_event(100_000, false, false),
])
.when(OnChainInvoiceCommand::SetPending { amount })
.then_expect_events(vec![]);
}

#[test]
fn test_set_confirmed_already_confirmed() {
let expected = OnChainInvoiceEvent::PaymentConfirmed {
received_amount: Amount::new(Currency::Btc, 100_000),
underpayment: false,
overpayment: false,
confirmations: 1,
transaction_id: "txid".to_string(),
};
OnChainInvoiceTestFramework::with(())
.given(vec![mock_created_event(100_000), expected.clone()])
.when(OnChainInvoiceCommand::SetConfirmed {
confirmations: 1,
amount: Amount::new(Currency::Btc, 100_000),
transaction_id: "txid".to_string(),
})
.then_expect_events(vec![]);
}

fn mock_pending_event(
Expand All @@ -326,7 +385,7 @@ mod aggregate_tests {
overpayment: bool,
) -> OnChainInvoiceEvent {
OnChainInvoiceEvent::PaymentPending {
received_amount: amount_fn(amount),
received_amount: Amount::sats(amount),
underpayment,
overpayment,
}
Expand All @@ -336,7 +395,7 @@ mod aggregate_tests {
OnChainInvoiceEvent::InvoiceCreated {
invoice_id: "123".to_string(),
node_id: "node1".to_string(),
amount: amount_fn(amount),
amount: Amount::sats(amount),
address: "tb1q6xm2qgh5r83lvmmu0v7c3d4wrd9k2uxu3sgcr4".to_string(),
}
}
Expand Down
21 changes: 21 additions & 0 deletions payday_core/src/api/lightining_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,19 @@ pub trait LightningTransactionStreamApi: Send + Sync {
) -> Result<JoinHandle<()>>;
}

#[async_trait]
pub trait LightningTransactionEventProcessorApi: Send + Sync {
fn node_id(&self) -> String;
async fn get_offset(&self) -> Result<u64>;
async fn set_offset(&self, settle_index: u64) -> Result<()>;
async fn process_event(&self, event: LightningTransactionEvent) -> Result<()>;
}

#[async_trait]
pub trait LightningTransactionEventHandler: Send + Sync {
async fn process_event(&self, event: LightningTransactionEvent) -> Result<()>;
}

#[derive(Debug, Clone)]
pub struct LnInvoice {
pub invoice: String,
Expand Down Expand Up @@ -84,6 +97,14 @@ pub enum LightningTransactionEvent {
Settled(LightningTransaction),
}

impl LightningTransactionEvent {
pub fn settle_index(&self) -> Option<u64> {
match self {
LightningTransactionEvent::Settled(tx) => Some(tx.settle_index),
}
}
}

#[derive(Debug, Clone, PartialEq)]
pub enum InvoiceState {
OPEN,
Expand Down
4 changes: 2 additions & 2 deletions payday_core/src/api/on_chain_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ pub trait OnChainTransactionApi: Send + Sync {
#[async_trait]
pub trait OnChainTransactionEventProcessorApi: Send + Sync {
fn node_id(&self) -> String;
async fn get_offset(&self) -> Result<i32>;
async fn set_block_height(&self, block_height: i32) -> Result<()>;
async fn get_offset(&self) -> Result<u64>;
async fn set_block_height(&self, block_height: u64) -> Result<()>;
async fn process_event(&self, event: OnChainTransactionEvent) -> Result<()>;
}

Expand Down
Loading