btcpayserver/BTCPayServer/HostedServices/InvoiceWatcher.cs

442 lines
19 KiB
C#
Raw Normal View History

2020-06-29 04:44:35 +02:00
using System;
2017-09-13 08:47:34 +02:00
using System.Collections.Generic;
using System.Linq;
using System.Threading;
2020-06-28 10:55:27 +02:00
using System.Threading.Channels;
using System.Threading.Tasks;
2020-07-24 09:40:37 +02:00
using BTCPayServer.Client.Models;
using BTCPayServer.Events;
2020-06-28 10:55:27 +02:00
using BTCPayServer.Logging;
using BTCPayServer.Services.Invoices;
using BTCPayServer.Services.Notifications;
using BTCPayServer.Services.Notifications.Blobs;
2020-06-28 10:55:27 +02:00
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NBitcoin;
using NBXplorer;
2017-09-13 08:47:34 +02:00
namespace BTCPayServer.HostedServices
2017-09-13 08:47:34 +02:00
{
public class InvoiceWatcher : IHostedService
{
class UpdateInvoiceContext
{
2018-02-17 05:18:16 +01:00
public UpdateInvoiceContext(InvoiceEntity invoice)
{
2018-02-17 05:18:16 +01:00
Invoice = invoice;
}
public InvoiceEntity Invoice { get; set; }
public List<object> Events { get; set; } = new List<object>();
bool _Dirty = false;
private bool _Unaffect;
public void MarkDirty()
{
_Dirty = true;
}
public void UnaffectAddresses()
{
_Unaffect = true;
}
public bool Dirty => _Dirty;
public bool Unaffect => _Unaffect;
2021-08-03 10:03:00 +02:00
bool _IsBlobUpdated;
public bool IsBlobUpdated => _IsBlobUpdated;
public void BlobUpdated()
{
_IsBlobUpdated = true;
}
}
readonly InvoiceRepository _invoiceRepository;
readonly EventAggregator _eventAggregator;
readonly ExplorerClientProvider _explorerClientProvider;
private readonly NotificationSender _notificationSender;
private readonly PaymentService _paymentService;
2021-11-22 09:16:08 +01:00
public Logs Logs { get; }
public InvoiceWatcher(
InvoiceRepository invoiceRepository,
EventAggregator eventAggregator,
2020-06-28 10:55:27 +02:00
ExplorerClientProvider explorerClientProvider,
NotificationSender notificationSender,
2021-11-22 09:16:08 +01:00
PaymentService paymentService,
Logs logs)
{
_invoiceRepository = invoiceRepository ?? throw new ArgumentNullException(nameof(invoiceRepository));
_eventAggregator = eventAggregator ?? throw new ArgumentNullException(nameof(eventAggregator));
_explorerClientProvider = explorerClientProvider;
_notificationSender = notificationSender;
_paymentService = paymentService;
2021-11-22 09:16:08 +01:00
this.Logs = logs;
}
readonly CompositeDisposable leases = new CompositeDisposable();
2020-10-26 06:18:38 +01:00
private void UpdateInvoice(UpdateInvoiceContext context)
{
var invoice = context.Invoice;
if (invoice.Status == InvoiceStatusLegacy.New && invoice.ExpirationTime <= DateTimeOffset.UtcNow)
{
context.MarkDirty();
context.UnaffectAddresses();
invoice.Status = InvoiceStatusLegacy.Expired;
var paidPartial = invoice.ExceptionStatus == InvoiceExceptionStatus.PaidPartial;
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.Expired) { PaidPartial = paidPartial });
if (invoice.ExceptionStatus == InvoiceExceptionStatus.PaidPartial)
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.ExpiredPaidPartial) { PaidPartial = paidPartial });
}
var allPaymentMethods = invoice.GetPaymentMethods();
var paymentMethod = GetNearestClearedPayment(allPaymentMethods, out var accounting);
if (allPaymentMethods.Any() && paymentMethod == null)
return;
if (accounting is null && invoice.Price is 0m)
{
accounting = new PaymentMethodAccounting()
{
Due = Money.Zero,
Paid = Money.Zero,
CryptoPaid = Money.Zero,
DueUncapped = Money.Zero,
NetworkFee = Money.Zero,
TotalDue = Money.Zero,
TxCount = 0,
TxRequired = 0,
MinimumTotalDue = Money.Zero,
NetworkFeeAlreadyPaid = Money.Zero
};
}
if (invoice.Status == InvoiceStatusLegacy.New || invoice.Status == InvoiceStatusLegacy.Expired)
{
2021-08-03 10:03:00 +02:00
var isPaid = invoice.IsUnsetTopUp() ?
accounting.Paid > Money.Zero :
accounting.Paid >= accounting.MinimumTotalDue;
if (isPaid)
{
if (invoice.Status == InvoiceStatusLegacy.New)
{
2020-07-24 09:40:37 +02:00
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.PaidInFull));
invoice.Status = InvoiceStatusLegacy.Paid;
2021-08-03 10:03:00 +02:00
if (invoice.IsUnsetTopUp())
{
invoice.ExceptionStatus = InvoiceExceptionStatus.None;
invoice.Price = (accounting.Paid - accounting.NetworkFeeAlreadyPaid).ToDecimal(MoneyUnit.BTC) * paymentMethod.Rate;
accounting = paymentMethod.Calculate();
context.BlobUpdated();
}
else
{
invoice.ExceptionStatus = accounting.Paid > accounting.TotalDue ? InvoiceExceptionStatus.PaidOver : InvoiceExceptionStatus.None;
}
context.UnaffectAddresses();
context.MarkDirty();
}
else if (invoice.Status == InvoiceStatusLegacy.Expired && invoice.ExceptionStatus != InvoiceExceptionStatus.PaidLate)
{
invoice.ExceptionStatus = InvoiceExceptionStatus.PaidLate;
2020-07-24 09:40:37 +02:00
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.PaidAfterExpiration));
context.MarkDirty();
}
}
if (accounting.Paid < accounting.MinimumTotalDue && invoice.GetPayments(true).Count != 0 && invoice.ExceptionStatus != InvoiceExceptionStatus.PaidPartial)
{
invoice.ExceptionStatus = InvoiceExceptionStatus.PaidPartial;
context.MarkDirty();
}
}
// Just make sure RBF did not cancelled a payment
if (invoice.Status == InvoiceStatusLegacy.Paid)
{
if (accounting.MinimumTotalDue <= accounting.Paid && accounting.Paid <= accounting.TotalDue && invoice.ExceptionStatus == InvoiceExceptionStatus.PaidOver)
{
invoice.ExceptionStatus = InvoiceExceptionStatus.None;
context.MarkDirty();
}
if (accounting.Paid > accounting.TotalDue && invoice.ExceptionStatus != InvoiceExceptionStatus.PaidOver)
{
invoice.ExceptionStatus = InvoiceExceptionStatus.PaidOver;
context.MarkDirty();
}
2018-05-05 16:07:22 +02:00
if (accounting.Paid < accounting.MinimumTotalDue)
{
invoice.Status = InvoiceStatusLegacy.New;
invoice.ExceptionStatus = accounting.Paid == Money.Zero ? InvoiceExceptionStatus.None : InvoiceExceptionStatus.PaidPartial;
context.MarkDirty();
}
}
if (invoice.Status == InvoiceStatusLegacy.Paid)
{
var confirmedAccounting =
paymentMethod?.Calculate(p => p.GetCryptoPaymentData().PaymentConfirmed(p, invoice.SpeedPolicy)) ??
accounting;
2018-05-05 16:07:22 +02:00
if (// Is after the monitoring deadline
(invoice.MonitoringExpiration < DateTimeOffset.UtcNow)
&&
// And not enough amount confirmed
2018-05-05 16:07:22 +02:00
(confirmedAccounting.Paid < accounting.MinimumTotalDue))
{
context.UnaffectAddresses();
2020-07-24 09:40:37 +02:00
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.FailedToConfirm));
invoice.Status = InvoiceStatusLegacy.Invalid;
context.MarkDirty();
}
2018-05-05 16:07:22 +02:00
else if (confirmedAccounting.Paid >= accounting.MinimumTotalDue)
{
context.UnaffectAddresses();
invoice.Status = InvoiceStatusLegacy.Confirmed;
2020-07-24 09:40:37 +02:00
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.Confirmed));
context.MarkDirty();
}
}
if (invoice.Status == InvoiceStatusLegacy.Confirmed)
{
var completedAccounting = paymentMethod?.Calculate(p => p.GetCryptoPaymentData().PaymentCompleted(p)) ??
accounting;
2018-05-05 16:07:22 +02:00
if (completedAccounting.Paid >= accounting.MinimumTotalDue)
{
2020-07-24 09:40:37 +02:00
context.Events.Add(new InvoiceEvent(invoice, InvoiceEvent.Completed));
invoice.Status = InvoiceStatusLegacy.Complete;
context.MarkDirty();
}
}
}
public static PaymentMethod GetNearestClearedPayment(PaymentMethodDictionary allPaymentMethods, out PaymentMethodAccounting accounting)
{
PaymentMethod result = null;
accounting = null;
decimal nearestToZero = 0.0m;
foreach (var paymentMethod in allPaymentMethods)
{
var currentAccounting = paymentMethod.Calculate();
var distanceFromZero = Math.Abs(currentAccounting.DueUncapped.ToDecimal(MoneyUnit.BTC));
if (result == null || distanceFromZero < nearestToZero)
{
result = paymentMethod;
nearestToZero = distanceFromZero;
accounting = currentAccounting;
}
}
return result;
}
private void Watch(string invoiceId)
{
if (invoiceId == null)
throw new ArgumentNullException(nameof(invoiceId));
2020-06-28 10:55:27 +02:00
if (!_WatchRequests.Writer.TryWrite(invoiceId))
{
Logs.PayServer.LogWarning($"Failed to write invoice {invoiceId} into WatchRequests channel");
}
}
private async Task Wait(string invoiceId)
{
var invoice = await _invoiceRepository.GetInvoice(invoiceId);
try
{
2020-02-21 09:14:49 +01:00
// add 1 second to ensure watch won't trigger moments before invoice expires
var delay = invoice.ExpirationTime.AddSeconds(1) - DateTimeOffset.UtcNow;
if (delay > TimeSpan.Zero)
{
await Task.Delay(delay, _Cts.Token);
}
2018-02-17 05:18:16 +01:00
Watch(invoiceId);
2020-02-21 09:14:49 +01:00
// add 1 second to ensure watch won't trigger moments before monitoring expires
delay = invoice.MonitoringExpiration.AddSeconds(1) - DateTimeOffset.UtcNow;
if (delay > TimeSpan.Zero)
{
await Task.Delay(delay, _Cts.Token);
}
2018-02-17 05:18:16 +01:00
Watch(invoiceId);
}
catch when (_Cts.IsCancellationRequested)
{ }
}
readonly Channel<string> _WatchRequests = Channel.CreateUnbounded<string>();
2018-01-09 18:07:42 +01:00
Task _Loop;
CancellationTokenSource _Cts;
public Task StartAsync(CancellationToken cancellationToken)
{
_Cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
2018-01-09 18:07:42 +01:00
_Loop = StartLoop(_Cts.Token);
_ = WaitPendingInvoices();
leases.Add(_eventAggregator.Subscribe<Events.InvoiceNeedUpdateEvent>(b =>
{
Watch(b.InvoiceId);
}));
leases.Add(_eventAggregator.SubscribeAsync<Events.InvoiceEvent>(async b =>
2018-01-18 12:56:55 +01:00
{
if (InvoiceEventNotification.HandlesEvent(b.Name))
{
await _notificationSender.SendNotification(new StoreScope(b.Invoice.StoreId),
new InvoiceEventNotification(b.Invoice.Id, b.Name));
}
2019-01-06 10:12:45 +01:00
if (b.Name == InvoiceEvent.Created)
{
Watch(b.Invoice.Id);
_ = Wait(b.Invoice.Id);
2018-01-18 12:56:55 +01:00
}
2019-01-06 10:12:45 +01:00
if (b.Name == InvoiceEvent.ReceivedPayment)
{
Watch(b.Invoice.Id);
}
}));
return Task.CompletedTask;
}
private async Task WaitPendingInvoices()
{
await Task.WhenAll((await _invoiceRepository.GetPendingInvoices())
.Select(id => Wait(id)).ToArray());
2018-01-09 18:07:42 +01:00
}
async Task StartLoop(CancellationToken cancellation)
{
Logs.PayServer.LogInformation("Start watching invoices");
while (await _WatchRequests.Reader.WaitToReadAsync(cancellation) && _WatchRequests.Reader.TryRead(out var invoiceId))
{
int maxLoop = 5;
int loopCount = -1;
while (loopCount < maxLoop)
{
loopCount++;
try
2018-01-09 18:07:42 +01:00
{
cancellation.ThrowIfCancellationRequested();
var invoice = await _invoiceRepository.GetInvoice(invoiceId, true);
if (invoice == null)
break;
var updateContext = new UpdateInvoiceContext(invoice);
2020-10-26 06:18:38 +01:00
UpdateInvoice(updateContext);
if (updateContext.Unaffect)
{
await _invoiceRepository.UnaffectAddress(invoice.Id);
}
if (updateContext.Dirty)
2018-01-09 18:07:42 +01:00
{
await _invoiceRepository.UpdateInvoiceStatus(invoice.Id, invoice.GetInvoiceState());
updateContext.Events.Insert(0, new InvoiceDataChangedEvent(invoice));
2018-01-09 18:07:42 +01:00
}
2021-08-03 10:03:00 +02:00
if (updateContext.IsBlobUpdated)
{
await _invoiceRepository.UpdateInvoicePrice(invoice.Id, invoice);
2021-08-03 10:03:00 +02:00
}
foreach (var evt in updateContext.Events)
2018-01-09 18:07:42 +01:00
{
_eventAggregator.Publish(evt, evt.GetType());
2018-02-17 05:18:16 +01:00
}
if (invoice.Status == InvoiceStatusLegacy.Complete ||
((invoice.Status == InvoiceStatusLegacy.Invalid || invoice.Status == InvoiceStatusLegacy.Expired) && invoice.MonitoringExpiration < DateTimeOffset.UtcNow))
2018-02-17 05:18:16 +01:00
{
var extendInvoiceMonitoring = await UpdateConfirmationCount(invoice);
// we extend monitor time if we haven't reached max confirmation count
// say user used low fee and we only got 3 confirmations right before it's time to remove
if (extendInvoiceMonitoring)
{
await _invoiceRepository.ExtendInvoiceMonitor(invoice.Id);
}
else if (await _invoiceRepository.RemovePendingInvoice(invoice.Id))
{
_eventAggregator.Publish(new InvoiceStopWatchedEvent(invoice.Id));
}
break;
2018-01-18 10:33:26 +01:00
}
if (updateContext.Events.Count == 0)
break;
}
catch (Exception ex) when (!cancellation.IsCancellationRequested)
{
Logs.PayServer.LogError(ex, "Unhandled error on watching invoice " + invoiceId);
_ = Task.Delay(10000, cancellation)
.ContinueWith(t => Watch(invoiceId), TaskScheduler.Default);
break;
}
}
2018-01-09 18:07:42 +01:00
}
}
private async Task<bool> UpdateConfirmationCount(InvoiceEntity invoice)
{
bool extendInvoiceMonitoring = false;
var updateConfirmationCountIfNeeded = invoice
.GetPayments(false)
.Select<PaymentEntity, Task<PaymentEntity>>(async payment =>
{
var paymentData = payment.GetCryptoPaymentData();
if (paymentData is Payments.Bitcoin.BitcoinLikePaymentData onChainPaymentData)
{
var network = payment.Network as BTCPayNetwork;
// Do update if confirmation count in the paymentData is not up to date
if ((onChainPaymentData.ConfirmationCount < network.MaxTrackedConfirmation && payment.Accounted)
&& (onChainPaymentData.Legacy || invoice.MonitoringExpiration < DateTimeOffset.UtcNow))
{
var transactionResult = await _explorerClientProvider.GetExplorerClient(payment.GetCryptoCode())?.GetTransactionAsync(onChainPaymentData.Outpoint.Hash);
var confirmationCount = transactionResult?.Confirmations ?? 0;
onChainPaymentData.ConfirmationCount = confirmationCount;
payment.SetCryptoPaymentData(onChainPaymentData);
// we want to extend invoice monitoring until we reach max confirmations on all onchain payment methods
if (confirmationCount < network.MaxTrackedConfirmation)
extendInvoiceMonitoring = true;
2020-06-28 10:55:27 +02:00
return payment;
}
}
return null;
})
.ToArray();
await Task.WhenAll(updateConfirmationCountIfNeeded);
var updatedPaymentData = updateConfirmationCountIfNeeded.Where(a => a.Result != null).Select(a => a.Result).ToList();
if (updatedPaymentData.Count > 0)
{
await _paymentService.UpdatePayments(updatedPaymentData);
}
return extendInvoiceMonitoring;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
if (_Cts == null)
return;
leases.Dispose();
_Cts.Cancel();
try
{
await _Loop;
}
catch { }
finally
{
Logs.PayServer.LogInformation("Stop watching invoices");
}
}
}
2017-09-13 08:47:34 +02:00
}