Compare commits
18 Commits
Author | SHA1 | Date | |
---|---|---|---|
a6b92a0dd5 | |||
2f3238c65e | |||
65f5a38b4a | |||
271cbf682f | |||
a634593903 | |||
af94de93d1 | |||
35f669aa15 | |||
4795bd8108 | |||
29aed99fd1 | |||
aa4519ac30 | |||
752133b01c | |||
fe0c21ba08 | |||
90904a6b5e | |||
8e3f7ea68d | |||
a239104a28 | |||
3bc232e1da | |||
a1ee09cd85 | |||
b898cc030c |
@ -4,7 +4,7 @@
|
||||
<TargetFramework>netcoreapp2.0</TargetFramework>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<NoWarn>NU1701</NoWarn>
|
||||
<NoWarn>NU1701,CA1816,CA1308,CA1810,CA2208</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
@ -18,6 +18,7 @@ using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Threading;
|
||||
using BTCPayServer.Eclair;
|
||||
using System.Globalization;
|
||||
|
||||
namespace BTCPayServer.Tests
|
||||
{
|
||||
@ -60,7 +61,7 @@ namespace BTCPayServer.Tests
|
||||
LTCNBXplorerUri = LTCExplorerClient.Address,
|
||||
Postgres = GetEnvironment("TESTS_POSTGRES", "User ID=postgres;Host=127.0.0.1;Port=39372;Database=btcpayserver")
|
||||
};
|
||||
PayTester.Port = int.Parse(GetEnvironment("TESTS_PORT", Utils.FreeTcpPort().ToString()));
|
||||
PayTester.Port = int.Parse(GetEnvironment("TESTS_PORT", Utils.FreeTcpPort().ToString(CultureInfo.InvariantCulture)), CultureInfo.InvariantCulture);
|
||||
PayTester.HostName = GetEnvironment("TESTS_HOSTNAME", "127.0.0.1");
|
||||
PayTester.Start();
|
||||
|
||||
|
@ -26,6 +26,10 @@ using BTCPayServer.Eclair;
|
||||
using System.Collections.Generic;
|
||||
using BTCPayServer.Models.StoreViewModels;
|
||||
using System.Threading.Tasks;
|
||||
using System.Globalization;
|
||||
using BTCPayServer.Payments;
|
||||
using BTCPayServer.Payments.Bitcoin;
|
||||
using BTCPayServer.HostedServices;
|
||||
|
||||
namespace BTCPayServer.Tests
|
||||
{
|
||||
@ -37,6 +41,63 @@ namespace BTCPayServer.Tests
|
||||
Logs.LogProvider = new XUnitLogProvider(helper);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanCalculateCryptoDue2()
|
||||
{
|
||||
var dummy = new Key().PubKey.GetAddress(Network.RegTest);
|
||||
#pragma warning disable CS0618
|
||||
InvoiceEntity invoiceEntity = new InvoiceEntity();
|
||||
invoiceEntity.Payments = new System.Collections.Generic.List<PaymentEntity>();
|
||||
invoiceEntity.ProductInformation = new ProductInformation() { Price = 100 };
|
||||
PaymentMethodDictionary paymentMethods = new PaymentMethodDictionary();
|
||||
paymentMethods.Add(new PaymentMethod()
|
||||
{
|
||||
CryptoCode = "BTC",
|
||||
Rate = 10513.44m,
|
||||
}.SetPaymentMethodDetails(new BTCPayServer.Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod()
|
||||
{
|
||||
TxFee = Money.Coins(0.00000100m),
|
||||
DepositAddress = dummy
|
||||
}));
|
||||
paymentMethods.Add(new PaymentMethod()
|
||||
{
|
||||
CryptoCode = "LTC",
|
||||
Rate = 216.79m
|
||||
}.SetPaymentMethodDetails(new BTCPayServer.Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod()
|
||||
{
|
||||
TxFee = Money.Coins(0.00010000m),
|
||||
DepositAddress = dummy
|
||||
}));
|
||||
invoiceEntity.SetPaymentMethods(paymentMethods);
|
||||
|
||||
var btc = invoiceEntity.GetPaymentMethod(new PaymentMethodId("BTC", PaymentTypes.BTCLike), null);
|
||||
var accounting = btc.Calculate();
|
||||
|
||||
invoiceEntity.Payments.Add(new PaymentEntity() { Accounted = true, CryptoCode = "BTC" }.SetCryptoPaymentData(new BitcoinLikePaymentData()
|
||||
{
|
||||
Output = new TxOut() { Value = Money.Coins(0.00151263m) }
|
||||
}));
|
||||
accounting = btc.Calculate();
|
||||
invoiceEntity.Payments.Add(new PaymentEntity() { Accounted = true, CryptoCode = "BTC" }.SetCryptoPaymentData(new BitcoinLikePaymentData()
|
||||
{
|
||||
Output = new TxOut() { Value = accounting.Due }
|
||||
}));
|
||||
accounting = btc.Calculate();
|
||||
Assert.Equal(Money.Zero, accounting.Due);
|
||||
Assert.Equal(Money.Zero, accounting.DueUncapped);
|
||||
|
||||
var ltc = invoiceEntity.GetPaymentMethod(new PaymentMethodId("LTC", PaymentTypes.BTCLike), null);
|
||||
accounting = ltc.Calculate();
|
||||
|
||||
Assert.Equal(Money.Zero, accounting.Due);
|
||||
// LTC might have over paid due to BTC paying above what it should (round 1 satoshi up)
|
||||
Assert.True(accounting.DueUncapped < Money.Zero);
|
||||
|
||||
var paymentMethod = InvoiceWatcher.GetNearestClearedPayment(paymentMethods, out var accounting2, null);
|
||||
Assert.Equal(btc.CryptoCode, paymentMethod.CryptoCode);
|
||||
#pragma warning restore CS0618
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CanCalculateCryptoDue()
|
||||
{
|
||||
@ -49,79 +110,81 @@ namespace BTCPayServer.Tests
|
||||
entity.ProductInformation = new ProductInformation() { Price = 5000 };
|
||||
|
||||
// Some check that handling legacy stuff does not break things
|
||||
var cryptoData = entity.GetCryptoData("BTC", null, true);
|
||||
cryptoData.Calculate();
|
||||
Assert.NotNull(cryptoData);
|
||||
Assert.Null(entity.GetCryptoData("BTC", null, false));
|
||||
entity.SetCryptoData(new CryptoData() { ParentEntity = entity, Rate = entity.Rate, CryptoCode = "BTC", TxFee = entity.TxFee });
|
||||
Assert.NotNull(entity.GetCryptoData("BTC", null, false));
|
||||
Assert.NotNull(entity.GetCryptoData("BTC", null, true));
|
||||
var paymentMethod = entity.GetPaymentMethods(null, true).TryGet("BTC", PaymentTypes.BTCLike);
|
||||
paymentMethod.Calculate();
|
||||
Assert.NotNull(paymentMethod);
|
||||
Assert.Null(entity.GetPaymentMethods(null, false).TryGet("BTC", PaymentTypes.BTCLike));
|
||||
entity.SetPaymentMethod(new PaymentMethod() { ParentEntity = entity, Rate = entity.Rate, CryptoCode = "BTC", TxFee = entity.TxFee });
|
||||
Assert.NotNull(entity.GetPaymentMethods(null, false).TryGet("BTC", PaymentTypes.BTCLike));
|
||||
Assert.NotNull(entity.GetPaymentMethods(null, true).TryGet("BTC", PaymentTypes.BTCLike));
|
||||
////////////////////
|
||||
|
||||
var accounting = cryptoData.Calculate();
|
||||
var accounting = paymentMethod.Calculate();
|
||||
Assert.Equal(Money.Coins(1.1m), accounting.Due);
|
||||
Assert.Equal(Money.Coins(1.1m), accounting.TotalDue);
|
||||
|
||||
entity.Payments.Add(new PaymentEntity() { Output = new TxOut(Money.Coins(0.5m), new Key()), Accounted = true });
|
||||
|
||||
accounting = cryptoData.Calculate();
|
||||
accounting = paymentMethod.Calculate();
|
||||
//Since we need to spend one more txout, it should be 1.1 - 0,5 + 0.1
|
||||
Assert.Equal(Money.Coins(0.7m), accounting.Due);
|
||||
Assert.Equal(Money.Coins(1.2m), accounting.TotalDue);
|
||||
|
||||
entity.Payments.Add(new PaymentEntity() { Output = new TxOut(Money.Coins(0.2m), new Key()), Accounted = true });
|
||||
|
||||
accounting = cryptoData.Calculate();
|
||||
accounting = paymentMethod.Calculate();
|
||||
Assert.Equal(Money.Coins(0.6m), accounting.Due);
|
||||
Assert.Equal(Money.Coins(1.3m), accounting.TotalDue);
|
||||
|
||||
entity.Payments.Add(new PaymentEntity() { Output = new TxOut(Money.Coins(0.6m), new Key()), Accounted = true });
|
||||
|
||||
accounting = cryptoData.Calculate();
|
||||
accounting = paymentMethod.Calculate();
|
||||
Assert.Equal(Money.Zero, accounting.Due);
|
||||
Assert.Equal(Money.Coins(1.3m), accounting.TotalDue);
|
||||
|
||||
entity.Payments.Add(new PaymentEntity() { Output = new TxOut(Money.Coins(0.2m), new Key()), Accounted = true });
|
||||
|
||||
accounting = cryptoData.Calculate();
|
||||
accounting = paymentMethod.Calculate();
|
||||
Assert.Equal(Money.Zero, accounting.Due);
|
||||
Assert.Equal(Money.Coins(1.3m), accounting.TotalDue);
|
||||
|
||||
entity = new InvoiceEntity();
|
||||
entity.ProductInformation = new ProductInformation() { Price = 5000 };
|
||||
entity.SetCryptoData(new System.Collections.Generic.Dictionary<string, CryptoData>(new KeyValuePair<string, CryptoData>[] {
|
||||
new KeyValuePair<string,CryptoData>("BTC", new CryptoData()
|
||||
{
|
||||
Rate = 1000,
|
||||
TxFee = Money.Coins(0.1m)
|
||||
}),
|
||||
new KeyValuePair<string,CryptoData>("LTC", new CryptoData()
|
||||
{
|
||||
Rate = 500,
|
||||
TxFee = Money.Coins(0.01m)
|
||||
})
|
||||
}));
|
||||
PaymentMethodDictionary paymentMethods = new PaymentMethodDictionary();
|
||||
paymentMethods.Add(new PaymentMethod()
|
||||
{
|
||||
CryptoCode = "BTC",
|
||||
Rate = 1000,
|
||||
TxFee = Money.Coins(0.1m)
|
||||
});
|
||||
paymentMethods.Add(new PaymentMethod()
|
||||
{
|
||||
CryptoCode = "LTC",
|
||||
Rate = 500,
|
||||
TxFee = Money.Coins(0.01m)
|
||||
});
|
||||
entity.SetPaymentMethods(paymentMethods);
|
||||
entity.Payments = new List<PaymentEntity>();
|
||||
cryptoData = entity.GetCryptoData("BTC", null);
|
||||
accounting = cryptoData.Calculate();
|
||||
paymentMethod = entity.GetPaymentMethod(new PaymentMethodId("BTC", PaymentTypes.BTCLike), null);
|
||||
accounting = paymentMethod.Calculate();
|
||||
Assert.Equal(Money.Coins(5.1m), accounting.Due);
|
||||
|
||||
cryptoData = entity.GetCryptoData("LTC", null);
|
||||
accounting = cryptoData.Calculate();
|
||||
paymentMethod = entity.GetPaymentMethod(new PaymentMethodId("LTC", PaymentTypes.BTCLike), null);
|
||||
accounting = paymentMethod.Calculate();
|
||||
Assert.Equal(Money.Coins(10.01m), accounting.TotalDue);
|
||||
|
||||
entity.Payments.Add(new PaymentEntity() { CryptoCode = "BTC", Output = new TxOut(Money.Coins(1.0m), new Key()), Accounted = true });
|
||||
|
||||
cryptoData = entity.GetCryptoData("BTC", null);
|
||||
accounting = cryptoData.Calculate();
|
||||
paymentMethod = entity.GetPaymentMethod(new PaymentMethodId("BTC", PaymentTypes.BTCLike), null);
|
||||
accounting = paymentMethod.Calculate();
|
||||
Assert.Equal(Money.Coins(4.2m), accounting.Due);
|
||||
Assert.Equal(Money.Coins(1.0m), accounting.CryptoPaid);
|
||||
Assert.Equal(Money.Coins(1.0m), accounting.Paid);
|
||||
Assert.Equal(Money.Coins(5.2m), accounting.TotalDue);
|
||||
Assert.Equal(2, accounting.TxCount);
|
||||
|
||||
cryptoData = entity.GetCryptoData("LTC", null);
|
||||
accounting = cryptoData.Calculate();
|
||||
paymentMethod = entity.GetPaymentMethod(new PaymentMethodId("LTC", PaymentTypes.BTCLike), null);
|
||||
accounting = paymentMethod.Calculate();
|
||||
Assert.Equal(Money.Coins(10.01m + 0.1m * 2 - 2.0m /* 8.21m */), accounting.Due);
|
||||
Assert.Equal(Money.Coins(0.0m), accounting.CryptoPaid);
|
||||
Assert.Equal(Money.Coins(2.0m), accounting.Paid);
|
||||
@ -130,16 +193,16 @@ namespace BTCPayServer.Tests
|
||||
entity.Payments.Add(new PaymentEntity() { CryptoCode = "LTC", Output = new TxOut(Money.Coins(1.0m), new Key()), Accounted = true });
|
||||
|
||||
|
||||
cryptoData = entity.GetCryptoData("BTC", null);
|
||||
accounting = cryptoData.Calculate();
|
||||
paymentMethod = entity.GetPaymentMethod(new PaymentMethodId("BTC", PaymentTypes.BTCLike), null);
|
||||
accounting = paymentMethod.Calculate();
|
||||
Assert.Equal(Money.Coins(4.2m - 0.5m + 0.01m / 2), accounting.Due);
|
||||
Assert.Equal(Money.Coins(1.0m), accounting.CryptoPaid);
|
||||
Assert.Equal(Money.Coins(1.5m), accounting.Paid);
|
||||
Assert.Equal(Money.Coins(5.2m + 0.01m / 2), accounting.TotalDue); // The fee for LTC added
|
||||
Assert.Equal(2, accounting.TxCount);
|
||||
|
||||
cryptoData = entity.GetCryptoData("LTC", null);
|
||||
accounting = cryptoData.Calculate();
|
||||
paymentMethod = entity.GetPaymentMethod(new PaymentMethodId("LTC", PaymentTypes.BTCLike), null);
|
||||
accounting = paymentMethod.Calculate();
|
||||
Assert.Equal(Money.Coins(8.21m - 1.0m + 0.01m), accounting.Due);
|
||||
Assert.Equal(Money.Coins(1.0m), accounting.CryptoPaid);
|
||||
Assert.Equal(Money.Coins(3.0m), accounting.Paid);
|
||||
@ -149,8 +212,8 @@ namespace BTCPayServer.Tests
|
||||
var remaining = Money.Coins(4.2m - 0.5m + 0.01m / 2);
|
||||
entity.Payments.Add(new PaymentEntity() { CryptoCode = "BTC", Output = new TxOut(remaining, new Key()), Accounted = true });
|
||||
|
||||
cryptoData = entity.GetCryptoData("BTC", null);
|
||||
accounting = cryptoData.Calculate();
|
||||
paymentMethod = entity.GetPaymentMethod(new PaymentMethodId("BTC", PaymentTypes.BTCLike), null);
|
||||
accounting = paymentMethod.Calculate();
|
||||
Assert.Equal(Money.Zero, accounting.Due);
|
||||
Assert.Equal(Money.Coins(1.0m) + remaining, accounting.CryptoPaid);
|
||||
Assert.Equal(Money.Coins(1.5m) + remaining, accounting.Paid);
|
||||
@ -158,8 +221,8 @@ namespace BTCPayServer.Tests
|
||||
Assert.Equal(accounting.Paid, accounting.TotalDue);
|
||||
Assert.Equal(2, accounting.TxCount);
|
||||
|
||||
cryptoData = entity.GetCryptoData("LTC", null);
|
||||
accounting = cryptoData.Calculate();
|
||||
paymentMethod = entity.GetPaymentMethod(new PaymentMethodId("LTC", PaymentTypes.BTCLike), null);
|
||||
accounting = paymentMethod.Calculate();
|
||||
Assert.Equal(Money.Zero, accounting.Due);
|
||||
Assert.Equal(Money.Coins(1.0m), accounting.CryptoPaid);
|
||||
Assert.Equal(Money.Coins(3.0m) + remaining * 2, accounting.Paid);
|
||||
@ -167,7 +230,6 @@ namespace BTCPayServer.Tests
|
||||
Assert.Equal(Money.Coins(10.01m + 0.1m * 2 + 0.1m * 2 /* + 0.01m no need to pay this fee anymore */), accounting.TotalDue);
|
||||
Assert.Equal(1, accounting.TxCount);
|
||||
Assert.Equal(accounting.Paid, accounting.TotalDue);
|
||||
|
||||
#pragma warning restore CS0618
|
||||
}
|
||||
|
||||
@ -312,7 +374,7 @@ namespace BTCPayServer.Tests
|
||||
pairingCode = acc.BitPay.RequestClientAuthorization("test1", Facade.Merchant);
|
||||
var store2 = acc.CreateStore();
|
||||
store2.Pair(pairingCode.ToString(), store2.CreatedStoreId).GetAwaiter().GetResult();
|
||||
Assert.Contains(nameof(PairingResult.ReusedKey), store2.StatusMessage);
|
||||
Assert.Contains(nameof(PairingResult.ReusedKey), store2.StatusMessage, StringComparison.CurrentCultureIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
@ -330,11 +392,11 @@ namespace BTCPayServer.Tests
|
||||
Currency = "USD"
|
||||
}, Facade.Merchant);
|
||||
|
||||
var payment1 = Money.Coins(0.04m);
|
||||
var payment2 = Money.Coins(0.08m);
|
||||
var payment1 = invoice.BtcDue + Money.Coins(0.0001m);
|
||||
var payment2 = invoice.BtcDue;
|
||||
var tx1 = new uint256(tester.ExplorerNode.SendCommand("sendtoaddress", new object[]
|
||||
{
|
||||
invoice.BitcoinAddress.ToString(),
|
||||
invoice.BitcoinAddress,
|
||||
payment1.ToString(),
|
||||
null, //comment
|
||||
null, //comment_to
|
||||
@ -347,6 +409,8 @@ namespace BTCPayServer.Tests
|
||||
{
|
||||
invoice = user.BitPay.GetInvoice(invoice.Id);
|
||||
Assert.Equal(payment1, invoice.BtcPaid);
|
||||
Assert.Equal("paid", invoice.Status);
|
||||
Assert.Equal("paidOver", invoice.ExceptionStatus.ToString());
|
||||
invoiceAddress = BitcoinAddress.Create(invoice.BitcoinAddress, user.SupportedNetwork.NBitcoinNetwork);
|
||||
});
|
||||
|
||||
@ -355,11 +419,9 @@ namespace BTCPayServer.Tests
|
||||
{
|
||||
input.ScriptSig = Script.Empty; //Strip signatures
|
||||
}
|
||||
var change = tx.Outputs.First(o => o.Value != payment1);
|
||||
var output = tx.Outputs.First(o => o.Value == payment1);
|
||||
output.Value = payment2;
|
||||
output.ScriptPubKey = invoiceAddress.ScriptPubKey;
|
||||
change.Value -= (payment2 - payment1) * 2; //Add more fees
|
||||
var replaced = tester.ExplorerNode.SignRawTransaction(tx);
|
||||
tester.ExplorerNode.SendRawTransaction(replaced);
|
||||
var test = tester.ExplorerClient.GetUTXOs(user.DerivationScheme, null);
|
||||
@ -367,6 +429,7 @@ namespace BTCPayServer.Tests
|
||||
{
|
||||
invoice = user.BitPay.GetInvoice(invoice.Id);
|
||||
Assert.Equal(payment2, invoice.BtcPaid);
|
||||
Assert.Equal("False", invoice.ExceptionStatus.ToString());
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -565,7 +628,7 @@ namespace BTCPayServer.Tests
|
||||
var ltcCryptoInfo = invoice.CryptoInfo.FirstOrDefault(c => c.CryptoCode == "LTC");
|
||||
Assert.NotNull(ltcCryptoInfo);
|
||||
invoiceAddress = BitcoinAddress.Create(ltcCryptoInfo.Address, cashCow.Network);
|
||||
var secondPayment = Money.Coins(decimal.Parse(ltcCryptoInfo.Due));
|
||||
var secondPayment = Money.Coins(decimal.Parse(ltcCryptoInfo.Due, CultureInfo.InvariantCulture));
|
||||
cashCow.Generate(2); // LTC is not worth a lot, so just to make sure we have money...
|
||||
cashCow.SendToAddress(invoiceAddress, secondPayment);
|
||||
Logs.Tester.LogInformation("Second payment sent to " + invoiceAddress);
|
||||
@ -667,9 +730,9 @@ namespace BTCPayServer.Tests
|
||||
Assert.True(IsMapped(localInvoice, ctx));
|
||||
|
||||
invoiceEntity = repo.GetInvoice(null, invoice.Id, true).GetAwaiter().GetResult();
|
||||
var historical1 = invoiceEntity.HistoricalAddresses.FirstOrDefault(h => h.GetAddress() == invoice.BitcoinAddress.ToString());
|
||||
var historical1 = invoiceEntity.HistoricalAddresses.FirstOrDefault(h => h.GetAddress() == invoice.BitcoinAddress);
|
||||
Assert.NotNull(historical1.UnAssigned);
|
||||
var historical2 = invoiceEntity.HistoricalAddresses.FirstOrDefault(h => h.GetAddress() == localInvoice.BitcoinAddress.ToString());
|
||||
var historical2 = invoiceEntity.HistoricalAddresses.FirstOrDefault(h => h.GetAddress() == localInvoice.BitcoinAddress);
|
||||
Assert.Null(historical2.UnAssigned);
|
||||
invoiceAddress = BitcoinAddress.Create(localInvoice.BitcoinAddress, cashCow.Network);
|
||||
secondPayment = localInvoice.BtcDue;
|
||||
@ -761,8 +824,8 @@ namespace BTCPayServer.Tests
|
||||
|
||||
private static bool IsMapped(Invoice invoice, ApplicationDbContext ctx)
|
||||
{
|
||||
var h = BitcoinAddress.Create(invoice.BitcoinAddress).ScriptPubKey.Hash;
|
||||
return ctx.AddressInvoices.FirstOrDefault(i => i.InvoiceDataId == invoice.Id && i.GetHash() == h) != null;
|
||||
var h = BitcoinAddress.Create(invoice.BitcoinAddress).ScriptPubKey.Hash.ToString();
|
||||
return ctx.AddressInvoices.FirstOrDefault(i => i.InvoiceDataId == invoice.Id && i.GetAddress() == h) != null;
|
||||
}
|
||||
|
||||
private void Eventually(Action act)
|
||||
|
@ -66,7 +66,7 @@ namespace BTCPayServer
|
||||
|
||||
public BTCPayDefaultSettings DefaultSettings { get; set; }
|
||||
public KeyPath CoinType { get; internal set; }
|
||||
public int MaxTrackedConfirmation { get; internal set; } = 7;
|
||||
public int MaxTrackedConfirmation { get; internal set; } = 6;
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
|
@ -2,8 +2,8 @@
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp2.0</TargetFramework>
|
||||
<Version>1.0.1.33</Version>
|
||||
<NoWarn>NU1701</NoWarn>
|
||||
<Version>1.0.1.37</Version>
|
||||
<NoWarn>NU1701,CA1816,CA1308,CA1810,CA2208</NoWarn>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Remove="Build\dockerfiles\**" />
|
||||
@ -22,9 +22,11 @@
|
||||
<PackageReference Include="Hangfire.MemoryStorage" Version="1.5.2" />
|
||||
<PackageReference Include="Hangfire.PostgreSql" Version="1.4.8.1" />
|
||||
<PackageReference Include="LedgerWallet" Version="1.0.1.32" />
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="2.6.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Filter" Version="1.1.2" />
|
||||
<PackageReference Include="NBitcoin" Version="4.0.0.54" />
|
||||
<PackageReference Include="NBitpayClient" Version="1.0.0.16" />
|
||||
<PackageReference Include="Microsoft.NetCore.Analyzers" Version="2.6.0" />
|
||||
<PackageReference Include="NBitcoin" Version="4.0.0.55" />
|
||||
<PackageReference Include="NBitpayClient" Version="1.0.0.17" />
|
||||
<PackageReference Include="DBreeze" Version="1.87.0" />
|
||||
<PackageReference Include="NBXplorer.Client" Version="1.0.1.9" />
|
||||
<PackageReference Include="NicolasDorier.CommandLine" Version="1.0.0.1" />
|
||||
@ -33,12 +35,12 @@
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.0.1" />
|
||||
<PackageReference Include="System.ValueTuple" Version="4.4.0" />
|
||||
<PackageReference Include="System.Xml.XmlSerializer" Version="4.0.11" />
|
||||
<PackageReference Include="Text.Analyzers" Version="2.6.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.5" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.1" PrivateAssets="All" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.2" PrivateAssets="All" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
72
BTCPayServer/BTCPayServer.ruleset
Normal file
72
BTCPayServer/BTCPayServer.ruleset
Normal file
@ -0,0 +1,72 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<RuleSet Name="Microsoft Managed Recommended Rules" Description="These rules focus on the most critical problems in your code, including potential security holes, application crashes, and other important logic and design errors. It is recommended to include this rule set in any custom rule set you create for your projects." ToolsVersion="10.0">
|
||||
<Localization ResourceAssembly="Microsoft.VisualStudio.CodeAnalysis.RuleSets.Strings.dll" ResourceBaseName="Microsoft.VisualStudio.CodeAnalysis.RuleSets.Strings.Localized">
|
||||
<Name Resource="MinimumRecommendedRules_Name" />
|
||||
<Description Resource="MinimumRecommendedRules_Description" />
|
||||
</Localization>
|
||||
<Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
|
||||
<Rule Id="CA1001" Action="Warning" />
|
||||
<Rule Id="CA1009" Action="Warning" />
|
||||
<Rule Id="CA1016" Action="Warning" />
|
||||
<Rule Id="CA1033" Action="Warning" />
|
||||
<Rule Id="CA1049" Action="Warning" />
|
||||
<Rule Id="CA1060" Action="Warning" />
|
||||
<Rule Id="CA1061" Action="Warning" />
|
||||
<Rule Id="CA1063" Action="Warning" />
|
||||
<Rule Id="CA1065" Action="Warning" />
|
||||
<Rule Id="CA1301" Action="Warning" />
|
||||
<Rule Id="CA1400" Action="Warning" />
|
||||
<Rule Id="CA1401" Action="Warning" />
|
||||
<Rule Id="CA1403" Action="Warning" />
|
||||
<Rule Id="CA1404" Action="Warning" />
|
||||
<Rule Id="CA1405" Action="Warning" />
|
||||
<Rule Id="CA1410" Action="Warning" />
|
||||
<Rule Id="CA1415" Action="Warning" />
|
||||
<Rule Id="CA1821" Action="Warning" />
|
||||
<Rule Id="CA1900" Action="Warning" />
|
||||
<Rule Id="CA1901" Action="Warning" />
|
||||
<Rule Id="CA2002" Action="Warning" />
|
||||
<Rule Id="CA2100" Action="Warning" />
|
||||
<Rule Id="CA2101" Action="Warning" />
|
||||
<Rule Id="CA2108" Action="Warning" />
|
||||
<Rule Id="CA2111" Action="Warning" />
|
||||
<Rule Id="CA2112" Action="Warning" />
|
||||
<Rule Id="CA2114" Action="Warning" />
|
||||
<Rule Id="CA2116" Action="Warning" />
|
||||
<Rule Id="CA2117" Action="Warning" />
|
||||
<Rule Id="CA2122" Action="Warning" />
|
||||
<Rule Id="CA2123" Action="Warning" />
|
||||
<Rule Id="CA2124" Action="Warning" />
|
||||
<Rule Id="CA2126" Action="Warning" />
|
||||
<Rule Id="CA2131" Action="Warning" />
|
||||
<Rule Id="CA2132" Action="Warning" />
|
||||
<Rule Id="CA2133" Action="Warning" />
|
||||
<Rule Id="CA2134" Action="Warning" />
|
||||
<Rule Id="CA2137" Action="Warning" />
|
||||
<Rule Id="CA2138" Action="Warning" />
|
||||
<Rule Id="CA2140" Action="Warning" />
|
||||
<Rule Id="CA2141" Action="Warning" />
|
||||
<Rule Id="CA2146" Action="Warning" />
|
||||
<Rule Id="CA2147" Action="Warning" />
|
||||
<Rule Id="CA2149" Action="Warning" />
|
||||
<Rule Id="CA2200" Action="Warning" />
|
||||
<Rule Id="CA2202" Action="Warning" />
|
||||
<Rule Id="CA2207" Action="Warning" />
|
||||
<Rule Id="CA2212" Action="Warning" />
|
||||
<Rule Id="CA2213" Action="Warning" />
|
||||
<Rule Id="CA2214" Action="Warning" />
|
||||
<Rule Id="CA2216" Action="Warning" />
|
||||
<Rule Id="CA2220" Action="Warning" />
|
||||
<Rule Id="CA2229" Action="Warning" />
|
||||
<Rule Id="CA2231" Action="Warning" />
|
||||
<Rule Id="CA2232" Action="Warning" />
|
||||
<Rule Id="CA2235" Action="Warning" />
|
||||
<Rule Id="CA2236" Action="Warning" />
|
||||
<Rule Id="CA2237" Action="Warning" />
|
||||
<Rule Id="CA2238" Action="Warning" />
|
||||
<Rule Id="CA2240" Action="Warning" />
|
||||
<Rule Id="CA2241" Action="Warning" />
|
||||
<Rule Id="CA2242" Action="Warning" />
|
||||
</Rules>
|
||||
<Rules AnalyzerId="Microsoft.CodeAnalysis.CSharp.Analyzers" RuleNamespace="Microsoft.CodeAnalysis.CSharp.Analyzers" />
|
||||
</RuleSet>
|
@ -13,7 +13,7 @@ namespace BTCPayServer.Configuration
|
||||
{
|
||||
public static T GetOrDefault<T>(this IConfiguration configuration, string key, T defaultValue)
|
||||
{
|
||||
var str = configuration[key] ?? configuration[key.Replace(".", string.Empty)];
|
||||
var str = configuration[key] ?? configuration[key.Replace(".", string.Empty, StringComparison.InvariantCulture)];
|
||||
if (str == null)
|
||||
return defaultValue;
|
||||
if (typeof(T) == typeof(bool))
|
||||
@ -32,12 +32,12 @@ namespace BTCPayServer.Configuration
|
||||
return (T)(object)str;
|
||||
else if (typeof(T) == typeof(IPEndPoint))
|
||||
{
|
||||
var separator = str.LastIndexOf(":");
|
||||
var separator = str.LastIndexOf(":", StringComparison.InvariantCulture);
|
||||
if (separator == -1)
|
||||
throw new FormatException();
|
||||
var ip = str.Substring(0, separator);
|
||||
var port = str.Substring(separator + 1);
|
||||
return (T)(object)new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
|
||||
return (T)(object)new IPEndPoint(IPAddress.Parse(ip), int.Parse(port, CultureInfo.InvariantCulture));
|
||||
}
|
||||
else if (typeof(T) == typeof(int))
|
||||
{
|
||||
|
@ -150,7 +150,7 @@ namespace BTCPayServer.Controllers
|
||||
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
|
||||
}
|
||||
|
||||
var authenticatorCode = model.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);
|
||||
var authenticatorCode = model.TwoFactorCode.Replace(" ", string.Empty, StringComparison.InvariantCulture).Replace("-", string.Empty, StringComparison.InvariantCulture);
|
||||
|
||||
var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, model.RememberMachine);
|
||||
|
||||
@ -204,7 +204,7 @@ namespace BTCPayServer.Controllers
|
||||
throw new ApplicationException($"Unable to load two-factor authentication user.");
|
||||
}
|
||||
|
||||
var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty);
|
||||
var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty, StringComparison.InvariantCulture);
|
||||
|
||||
var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode);
|
||||
|
||||
|
@ -9,13 +9,14 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using BTCPayServer.Services.Invoices;
|
||||
|
||||
namespace BTCPayServer.Controllers
|
||||
{
|
||||
public partial class InvoiceController
|
||||
{
|
||||
[HttpGet]
|
||||
[Route("i/{invoiceId}")]
|
||||
[Route("i/{invoiceId}/{cryptoCode?}")]
|
||||
[AcceptMediaTypeConstraint("application/bitcoin-paymentrequest")]
|
||||
public async Task<IActionResult> GetInvoiceRequest(string invoiceId, string cryptoCode = null)
|
||||
{
|
||||
@ -23,11 +24,12 @@ namespace BTCPayServer.Controllers
|
||||
cryptoCode = "BTC";
|
||||
var invoice = await _InvoiceRepository.GetInvoice(null, invoiceId);
|
||||
var network = _NetworkProvider.GetNetwork(cryptoCode);
|
||||
if (invoice == null || invoice.IsExpired() || network == null || !invoice.Support(network))
|
||||
var paymentMethodId = new PaymentMethodId(cryptoCode, Payments.PaymentTypes.BTCLike);
|
||||
if (invoice == null || invoice.IsExpired() || network == null || !invoice.Support(paymentMethodId))
|
||||
return NotFound();
|
||||
|
||||
var dto = invoice.EntityToDTO(_NetworkProvider);
|
||||
var cryptoData = dto.CryptoInfo.First(c => c.CryptoCode.Equals(cryptoCode, StringComparison.OrdinalIgnoreCase));
|
||||
var paymentMethod = dto.CryptoInfo.First(c => c.GetpaymentMethodId() == paymentMethodId);
|
||||
PaymentRequest request = new PaymentRequest
|
||||
{
|
||||
DetailsVersion = 1
|
||||
@ -35,7 +37,7 @@ namespace BTCPayServer.Controllers
|
||||
request.Details.Expires = invoice.ExpirationTime;
|
||||
request.Details.Memo = invoice.ProductInformation.ItemDesc;
|
||||
request.Details.Network = network.NBitcoinNetwork;
|
||||
request.Details.Outputs.Add(new PaymentOutput() { Amount = cryptoData.Due, Script = BitcoinAddress.Create(cryptoData.Address, network.NBitcoinNetwork).ScriptPubKey });
|
||||
request.Details.Outputs.Add(new PaymentOutput() { Amount = paymentMethod.Due, Script = BitcoinAddress.Create(paymentMethod.Address, network.NBitcoinNetwork).ScriptPubKey });
|
||||
request.Details.MerchantData = Encoding.UTF8.GetBytes(invoice.Id);
|
||||
request.Details.Time = DateTimeOffset.UtcNow;
|
||||
request.Details.PaymentUrl = new Uri(invoice.ServerUrl.WithTrailingSlash() + ($"i/{invoice.Id}"), UriKind.Absolute);
|
||||
@ -69,7 +71,7 @@ namespace BTCPayServer.Controllers
|
||||
if (cryptoCode == null)
|
||||
cryptoCode = "BTC";
|
||||
var network = _NetworkProvider.GetNetwork(cryptoCode);
|
||||
if (network == null || invoice == null || invoice.IsExpired() || !invoice.Support(network))
|
||||
if (network == null || invoice == null || invoice.IsExpired() || !invoice.Support(new Services.Invoices.PaymentMethodId(cryptoCode, Payments.PaymentTypes.BTCLike)))
|
||||
return NotFound();
|
||||
|
||||
var wallet = _WalletProvider.GetWallet(network);
|
||||
|
@ -20,6 +20,7 @@ using System.Net.WebSockets;
|
||||
using System.Threading;
|
||||
using BTCPayServer.Events;
|
||||
using NBXplorer;
|
||||
using BTCPayServer.Payments;
|
||||
|
||||
namespace BTCPayServer.Controllers
|
||||
{
|
||||
@ -63,33 +64,58 @@ namespace BTCPayServer.Controllers
|
||||
Events = invoice.Events
|
||||
};
|
||||
|
||||
foreach (var data in invoice.GetCryptoData(null))
|
||||
foreach (var data in invoice.GetPaymentMethods(null))
|
||||
{
|
||||
var cryptoInfo = dto.CryptoInfo.First(o => o.CryptoCode.Equals(data.Key, StringComparison.OrdinalIgnoreCase));
|
||||
var accounting = data.Value.Calculate();
|
||||
var paymentNetwork = _NetworkProvider.GetNetwork(data.Key);
|
||||
var cryptoInfo = dto.CryptoInfo.First(o => o.GetpaymentMethodId() == data.GetId());
|
||||
var accounting = data.Calculate();
|
||||
var paymentNetwork = _NetworkProvider.GetNetwork(data.GetId().CryptoCode);
|
||||
var cryptoPayment = new InvoiceDetailsModel.CryptoPayment();
|
||||
cryptoPayment.CryptoCode = paymentNetwork.CryptoCode;
|
||||
cryptoPayment.Due = accounting.Due.ToString() + $" {paymentNetwork.CryptoCode}";
|
||||
cryptoPayment.Paid = accounting.CryptoPaid.ToString() + $" {paymentNetwork.CryptoCode}";
|
||||
cryptoPayment.Address = data.Value.DepositAddress.ToString();
|
||||
cryptoPayment.Rate = FormatCurrency(data.Value);
|
||||
|
||||
var onchainMethod = data.GetPaymentMethodDetails() as Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod;
|
||||
if(onchainMethod != null)
|
||||
{
|
||||
cryptoPayment.Address = onchainMethod.DepositAddress.ToString();
|
||||
}
|
||||
cryptoPayment.Rate = FormatCurrency(data);
|
||||
cryptoPayment.PaymentUrl = cryptoInfo.PaymentUrls.BIP21;
|
||||
model.CryptoPayments.Add(cryptoPayment);
|
||||
}
|
||||
|
||||
var payments = invoice
|
||||
.GetPayments()
|
||||
.Where(p => p.GetpaymentMethodId().PaymentType == PaymentTypes.BTCLike)
|
||||
.Select(async payment =>
|
||||
{
|
||||
var paymentData = (Payments.Bitcoin.BitcoinLikePaymentData)payment.GetCryptoPaymentData();
|
||||
var m = new InvoiceDetailsModel.Payment();
|
||||
var paymentNetwork = _NetworkProvider.GetNetwork(payment.GetCryptoCode());
|
||||
m.CryptoCode = payment.GetCryptoCode();
|
||||
m.DepositAddress = payment.GetScriptPubKey().GetDestinationAddress(paymentNetwork.NBitcoinNetwork);
|
||||
m.Confirmations = (await _ExplorerClients.GetExplorerClient(payment.GetCryptoCode())?.GetTransactionAsync(payment.Outpoint.Hash))?.Confirmations ?? 0;
|
||||
m.TransactionId = payment.Outpoint.Hash.ToString();
|
||||
m.DepositAddress = paymentData.Output.ScriptPubKey.GetDestinationAddress(paymentNetwork.NBitcoinNetwork);
|
||||
|
||||
int confirmationCount = 0;
|
||||
if(paymentData.Legacy) // The confirmation count in the paymentData is not up to date
|
||||
{
|
||||
confirmationCount = (await _ExplorerClients.GetExplorerClient(payment.GetCryptoCode())?.GetTransactionAsync(paymentData.Outpoint.Hash))?.Confirmations ?? 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
confirmationCount = paymentData.ConfirmationCount;
|
||||
}
|
||||
if(confirmationCount >= paymentNetwork.MaxTrackedConfirmation)
|
||||
{
|
||||
m.Confirmations = "At least " + (paymentNetwork.MaxTrackedConfirmation);
|
||||
}
|
||||
else
|
||||
{
|
||||
m.Confirmations = confirmationCount.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
m.TransactionId = paymentData.Outpoint.Hash.ToString();
|
||||
m.ReceivedTime = payment.ReceivedTime;
|
||||
m.TransactionLink = string.Format(paymentNetwork.BlockExplorerLink, m.TransactionId);
|
||||
m.TransactionLink = string.Format(CultureInfo.InvariantCulture, paymentNetwork.BlockExplorerLink, m.TransactionId);
|
||||
m.Replaced = !payment.Accounted;
|
||||
return m;
|
||||
})
|
||||
@ -103,60 +129,65 @@ namespace BTCPayServer.Controllers
|
||||
|
||||
[HttpGet]
|
||||
[Route("i/{invoiceId}")]
|
||||
[Route("i/{invoiceId}/{cryptoCode}")]
|
||||
[Route("i/{invoiceId}/{paymentMethodId}")]
|
||||
[Route("invoice")]
|
||||
[AcceptMediaTypeConstraint("application/bitcoin-paymentrequest", false)]
|
||||
[XFrameOptionsAttribute(null)]
|
||||
public async Task<IActionResult> Checkout(string invoiceId, string id = null, string cryptoCode = null)
|
||||
public async Task<IActionResult> Checkout(string invoiceId, string id = null, string paymentMethodId = null)
|
||||
{
|
||||
//Keep compatibility with Bitpay
|
||||
invoiceId = invoiceId ?? id;
|
||||
id = invoiceId;
|
||||
////
|
||||
|
||||
var model = await GetInvoiceModel(invoiceId, cryptoCode);
|
||||
var model = await GetInvoiceModel(invoiceId, paymentMethodId);
|
||||
if (model == null)
|
||||
return NotFound();
|
||||
|
||||
return View(nameof(Checkout), model);
|
||||
}
|
||||
|
||||
private async Task<PaymentModel> GetInvoiceModel(string invoiceId, string cryptoCode)
|
||||
private async Task<PaymentModel> GetInvoiceModel(string invoiceId, string paymentMethodIdStr)
|
||||
{
|
||||
var invoice = await _InvoiceRepository.GetInvoice(null, invoiceId);
|
||||
if (invoice == null)
|
||||
return null;
|
||||
var store = await _StoreRepository.FindStore(invoice.StoreId);
|
||||
bool isDefaultCrypto = false;
|
||||
if (cryptoCode == null)
|
||||
{
|
||||
cryptoCode = store.GetDefaultCrypto();
|
||||
if (paymentMethodIdStr == null)
|
||||
{
|
||||
paymentMethodIdStr = store.GetDefaultCrypto();
|
||||
isDefaultCrypto = true;
|
||||
}
|
||||
var network = _NetworkProvider.GetNetwork(cryptoCode);
|
||||
|
||||
var paymentMethodId = PaymentMethodId.Parse(paymentMethodIdStr);
|
||||
var network = _NetworkProvider.GetNetwork(paymentMethodId.CryptoCode);
|
||||
if (invoice == null || network == null)
|
||||
return null;
|
||||
|
||||
if(!invoice.Support(network))
|
||||
if (!invoice.Support(paymentMethodId))
|
||||
{
|
||||
if(!isDefaultCrypto)
|
||||
return null;
|
||||
network = invoice.GetCryptoData(_NetworkProvider).First().Value.Network;
|
||||
var paymentMethodTemp = invoice.GetPaymentMethods(_NetworkProvider).First();
|
||||
network = paymentMethodTemp.Network;
|
||||
paymentMethodId = paymentMethodTemp.GetId();
|
||||
}
|
||||
var cryptoData = invoice.GetCryptoData(network, _NetworkProvider);
|
||||
|
||||
var paymentMethod = invoice.GetPaymentMethod(paymentMethodId, _NetworkProvider);
|
||||
var paymentMethodDetails = paymentMethod.GetPaymentMethodDetails();
|
||||
var dto = invoice.EntityToDTO(_NetworkProvider);
|
||||
var cryptoInfo = dto.CryptoInfo.First(o => o.CryptoCode == network.CryptoCode);
|
||||
var cryptoInfo = dto.CryptoInfo.First(o => o.GetpaymentMethodId() == paymentMethodId);
|
||||
|
||||
var currency = invoice.ProductInformation.Currency;
|
||||
var accounting = cryptoData.Calculate();
|
||||
var accounting = paymentMethod.Calculate();
|
||||
var model = new PaymentModel()
|
||||
{
|
||||
CryptoCode = network.CryptoCode,
|
||||
PaymentMethodId = paymentMethodId.ToString(),
|
||||
ServerUrl = HttpContext.Request.GetAbsoluteRoot(),
|
||||
OrderId = invoice.OrderId,
|
||||
InvoiceId = invoice.Id,
|
||||
BtcAddress = cryptoData.DepositAddress,
|
||||
BtcAddress = paymentMethodDetails.GetPaymentDestination(),
|
||||
OrderAmount = (accounting.TotalDue - accounting.NetworkFee).ToString(),
|
||||
BtcDue = accounting.Due.ToString(),
|
||||
CustomerEmail = invoice.RefundMail,
|
||||
@ -164,7 +195,7 @@ namespace BTCPayServer.Controllers
|
||||
MaxTimeSeconds = (int)(invoice.ExpirationTime - invoice.InvoiceTime).TotalSeconds,
|
||||
MaxTimeMinutes = (int)(invoice.ExpirationTime - invoice.InvoiceTime).TotalMinutes,
|
||||
ItemDesc = invoice.ProductInformation.ItemDesc,
|
||||
Rate = FormatCurrency(cryptoData),
|
||||
Rate = FormatCurrency(paymentMethod),
|
||||
MerchantRefLink = invoice.RedirectURL ?? "/",
|
||||
StoreName = store.StoreName,
|
||||
InvoiceBitcoinUrl = cryptoInfo.PaymentUrls.BIP21,
|
||||
@ -172,14 +203,14 @@ namespace BTCPayServer.Controllers
|
||||
BtcPaid = accounting.Paid.ToString(),
|
||||
Status = invoice.Status,
|
||||
CryptoImage = "/" + Url.Content(network.CryptoImagePath),
|
||||
NetworkFeeDescription = $"{accounting.TxCount} transaction{(accounting.TxCount > 1 ? "s" : "")} x {cryptoData.TxFee} {network.CryptoCode}",
|
||||
AvailableCryptos = invoice.GetCryptoData(_NetworkProvider)
|
||||
.Where(i => i.Value.Network != null)
|
||||
NetworkFeeDescription = $"{accounting.TxCount} transaction{(accounting.TxCount > 1 ? "s" : "")} x {paymentMethodDetails.GetTxFee()} {network.CryptoCode}",
|
||||
AvailableCryptos = invoice.GetPaymentMethods(_NetworkProvider)
|
||||
.Where(i => i.Network != null)
|
||||
.Select(kv=> new PaymentModel.AvailableCrypto()
|
||||
{
|
||||
CryptoCode = kv.Key,
|
||||
CryptoImage = "/" + kv.Value.Network.CryptoImagePath,
|
||||
Link = Url.Action(nameof(Checkout), new { invoiceId = invoiceId, cryptoCode = kv.Key })
|
||||
PaymentMethodId = kv.GetId().ToString(),
|
||||
CryptoImage = "/" + kv.Network.CryptoImagePath,
|
||||
Link = Url.Action(nameof(Checkout), new { invoiceId = invoiceId, paymentMethodId = kv.GetId().ToString() })
|
||||
}).Where(c => c.CryptoImage != "/")
|
||||
.ToList()
|
||||
};
|
||||
@ -193,10 +224,10 @@ namespace BTCPayServer.Controllers
|
||||
return model;
|
||||
}
|
||||
|
||||
private string FormatCurrency(CryptoData cryptoData)
|
||||
private string FormatCurrency(PaymentMethod paymentMethod)
|
||||
{
|
||||
string currency = cryptoData.ParentEntity.ProductInformation.Currency;
|
||||
return FormatCurrency(cryptoData.Rate, currency);
|
||||
string currency = paymentMethod.ParentEntity.ProductInformation.Currency;
|
||||
return FormatCurrency(paymentMethod.Rate, currency);
|
||||
}
|
||||
public string FormatCurrency(decimal price, string currency)
|
||||
{
|
||||
@ -207,19 +238,19 @@ namespace BTCPayServer.Controllers
|
||||
{
|
||||
StringBuilder builder = new StringBuilder();
|
||||
if (expiration.Days >= 1)
|
||||
builder.Append(expiration.Days.ToString());
|
||||
builder.Append(expiration.Days.ToString(CultureInfo.InvariantCulture));
|
||||
if (expiration.Hours >= 1)
|
||||
builder.Append(expiration.Hours.ToString("00"));
|
||||
builder.Append($"{expiration.Minutes.ToString("00")}:{expiration.Seconds.ToString("00")}");
|
||||
builder.Append(expiration.Hours.ToString("00", CultureInfo.InvariantCulture));
|
||||
builder.Append($"{expiration.Minutes.ToString("00", CultureInfo.InvariantCulture)}:{expiration.Seconds.ToString("00", CultureInfo.InvariantCulture)}");
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Route("i/{invoiceId}/status")]
|
||||
[Route("i/{invoiceId}/{cryptoCode}/status")]
|
||||
public async Task<IActionResult> GetStatus(string invoiceId, string cryptoCode)
|
||||
[Route("i/{invoiceId}/{paymentMethodId}/status")]
|
||||
public async Task<IActionResult> GetStatus(string invoiceId, string paymentMethodId = null)
|
||||
{
|
||||
var model = await GetInvoiceModel(invoiceId, cryptoCode);
|
||||
var model = await GetInvoiceModel(invoiceId, paymentMethodId);
|
||||
if (model == null)
|
||||
return NotFound();
|
||||
return Json(model);
|
||||
|
@ -39,6 +39,7 @@ using Microsoft.AspNetCore.Mvc.Routing;
|
||||
using NBXplorer.DerivationStrategy;
|
||||
using NBXplorer;
|
||||
using BTCPayServer.HostedServices;
|
||||
using BTCPayServer.Payments;
|
||||
|
||||
namespace BTCPayServer.Controllers
|
||||
{
|
||||
@ -136,26 +137,27 @@ namespace BTCPayServer.Controllers
|
||||
});
|
||||
|
||||
bool legacyBTCisSet = false;
|
||||
var cryptoDatas = new Dictionary<string, CryptoData>();
|
||||
var paymentMethods = new PaymentMethodDictionary();
|
||||
foreach (var q in queries)
|
||||
{
|
||||
CryptoData cryptoData = new CryptoData();
|
||||
cryptoData.CryptoCode = q.network.CryptoCode;
|
||||
cryptoData.FeeRate = (await q.getFeeRate);
|
||||
cryptoData.TxFee = GetTxFee(storeBlob, cryptoData.FeeRate); // assume price for 100 bytes
|
||||
cryptoData.Rate = await q.getRate;
|
||||
cryptoData.DepositAddress = (await q.getAddress).ToString();
|
||||
|
||||
PaymentMethod paymentMethod = new PaymentMethod();
|
||||
paymentMethod.SetId(new PaymentMethodId(q.network.CryptoCode, PaymentTypes.BTCLike));
|
||||
Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod onchainMethod = new Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod();
|
||||
onchainMethod.FeeRate = (await q.getFeeRate);
|
||||
onchainMethod.TxFee = GetTxFee(storeBlob, onchainMethod.FeeRate); // assume price for 100 bytes
|
||||
paymentMethod.Rate = await q.getRate;
|
||||
onchainMethod.DepositAddress = (await q.getAddress);
|
||||
paymentMethod.SetPaymentMethodDetails(onchainMethod);
|
||||
#pragma warning disable CS0618
|
||||
if (q.network.IsBTC)
|
||||
{
|
||||
legacyBTCisSet = true;
|
||||
entity.TxFee = cryptoData.TxFee;
|
||||
entity.Rate = cryptoData.Rate;
|
||||
entity.DepositAddress = cryptoData.DepositAddress;
|
||||
entity.TxFee = paymentMethod.TxFee;
|
||||
entity.Rate = paymentMethod.Rate;
|
||||
entity.DepositAddress = paymentMethod.DepositAddress;
|
||||
}
|
||||
#pragma warning restore CS0618
|
||||
cryptoDatas.Add(cryptoData.CryptoCode, cryptoData);
|
||||
paymentMethods.Add(paymentMethod);
|
||||
}
|
||||
|
||||
if (!legacyBTCisSet)
|
||||
@ -175,7 +177,7 @@ namespace BTCPayServer.Controllers
|
||||
#pragma warning restore CS0618
|
||||
}
|
||||
|
||||
entity.SetCryptoData(cryptoDatas);
|
||||
entity.SetPaymentMethods(paymentMethods);
|
||||
entity.PosData = invoice.PosData;
|
||||
entity = await _InvoiceRepository.CreateInvoiceAsync(store.Id, entity, _NetworkProvider);
|
||||
_EventAggregator.Publish(new Events.InvoiceEvent(entity, 1001, "invoice_created"));
|
||||
|
@ -20,6 +20,7 @@ using NBitcoin;
|
||||
using BTCPayServer.Services.Stores;
|
||||
using BTCPayServer.Services.Wallets;
|
||||
using BTCPayServer.Services.Mails;
|
||||
using System.Globalization;
|
||||
|
||||
namespace BTCPayServer.Controllers
|
||||
{
|
||||
@ -434,7 +435,7 @@ namespace BTCPayServer.Controllers
|
||||
}
|
||||
|
||||
// Strip spaces and hypens
|
||||
var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty);
|
||||
var verificationCode = model.Code.Replace(" ", string.Empty, StringComparison.InvariantCulture).Replace("-", string.Empty, StringComparison.InvariantCulture);
|
||||
|
||||
var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
|
||||
user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);
|
||||
@ -524,7 +525,7 @@ namespace BTCPayServer.Controllers
|
||||
|
||||
private string GenerateQrCodeUri(string email, string unformattedKey)
|
||||
{
|
||||
return string.Format(
|
||||
return string.Format(CultureInfo.InvariantCulture,
|
||||
AuthenicatorUriFormat,
|
||||
_urlEncoder.Encode("BTCPayServer"),
|
||||
_urlEncoder.Encode(email),
|
||||
|
@ -21,6 +21,7 @@ using NBXplorer.DerivationStrategy;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.WebSockets;
|
||||
@ -179,7 +180,7 @@ namespace BTCPayServer.Controllers
|
||||
{
|
||||
try
|
||||
{
|
||||
feeRateValue = new FeeRate(Money.Satoshis(int.Parse(feeRate)), 1);
|
||||
feeRateValue = new FeeRate(Money.Satoshis(int.Parse(feeRate, CultureInfo.InvariantCulture)), 1);
|
||||
}
|
||||
catch { }
|
||||
if (feeRateValue == null || feeRateValue.FeePerK <= Money.Zero)
|
||||
@ -315,7 +316,7 @@ namespace BTCPayServer.Controllers
|
||||
.Select(d => ((Wallet: _WalletProvider.GetWallet(d.Network),
|
||||
DerivationStrategy: d.DerivationStrategyBase)))
|
||||
.Where(_ => _.Wallet != null)
|
||||
.Select(async _ => (await GetBalanceString(_)).ToString() + " " + _.Wallet.Network.CryptoCode))
|
||||
.Select(async _ => (await GetBalanceString(_)) + " " + _.Wallet.Network.CryptoCode))
|
||||
.ToArray();
|
||||
|
||||
await Task.WhenAll(balances.SelectMany(_ => _));
|
||||
@ -604,7 +605,7 @@ namespace BTCPayServer.Controllers
|
||||
var p2wpkh_p2sh = 0x049d7cb2U;
|
||||
electrumMapping.Add(p2wpkh_p2sh, new string[] { "p2sh" });
|
||||
var p2wpkh = 0x4b24746U;
|
||||
electrumMapping.Add(p2wpkh, new string[] { });
|
||||
electrumMapping.Add(p2wpkh, Array.Empty<string>());
|
||||
|
||||
var data = Encoders.Base58Check.DecodeData(derivationScheme);
|
||||
if (data.Length < 4)
|
||||
|
@ -2,6 +2,7 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using BTCPayServer.Services.Invoices;
|
||||
using NBitcoin;
|
||||
|
||||
namespace BTCPayServer.Data
|
||||
@ -20,28 +21,30 @@ namespace BTCPayServer.Data
|
||||
|
||||
|
||||
#pragma warning disable CS0618
|
||||
public ScriptId GetHash()
|
||||
public string GetAddress()
|
||||
{
|
||||
if (Address == null)
|
||||
return null;
|
||||
var index = Address.IndexOf("#");
|
||||
var index = Address.LastIndexOf("#", StringComparison.InvariantCulture);
|
||||
if (index == -1)
|
||||
return new ScriptId(Address);
|
||||
return new ScriptId(Address.Substring(0, index));
|
||||
return Address;
|
||||
return Address.Substring(0, index);
|
||||
}
|
||||
public AddressInvoiceData SetHash(ScriptId scriptId, string cryptoCode)
|
||||
public AddressInvoiceData Set(string address, PaymentMethodId paymentMethodId)
|
||||
{
|
||||
Address = scriptId + "#" + cryptoCode;
|
||||
Address = address + "#" + paymentMethodId?.ToString();
|
||||
return this;
|
||||
}
|
||||
public string GetCryptoCode()
|
||||
public PaymentMethodId GetpaymentMethodId()
|
||||
{
|
||||
if (Address == null)
|
||||
return null;
|
||||
var index = Address.IndexOf("#");
|
||||
var index = Address.LastIndexOf("#", StringComparison.InvariantCulture);
|
||||
// Legacy AddressInvoiceData does not have the paymentMethodId attached to the Address
|
||||
if (index == -1)
|
||||
return "BTC";
|
||||
return Address.Substring(index + 1);
|
||||
return PaymentMethodId.Parse("BTC");
|
||||
/////////////////////////
|
||||
return PaymentMethodId.Parse(Address.Substring(index + 1));
|
||||
}
|
||||
#pragma warning restore CS0618
|
||||
|
||||
|
@ -35,7 +35,7 @@ namespace BTCPayServer.Data
|
||||
{
|
||||
if (Address == null)
|
||||
return null;
|
||||
var index = Address.IndexOf("#");
|
||||
var index = Address.IndexOf("#", StringComparison.InvariantCulture);
|
||||
if (index == -1)
|
||||
return Address;
|
||||
return Address.Substring(0, index);
|
||||
|
@ -33,7 +33,7 @@ namespace BTCPayServer.Eclair
|
||||
|
||||
public Task<GetInfoResponse> GetInfoAsync()
|
||||
{
|
||||
return SendCommandAsync<GetInfoResponse>(new RPCRequest("getinfo", new object[] { }));
|
||||
return SendCommandAsync<GetInfoResponse>(new RPCRequest("getinfo", Array.Empty<object>()));
|
||||
}
|
||||
|
||||
public async Task<T> SendCommandAsync<T>(RPCRequest request, bool throwIfRPCError = true)
|
||||
@ -104,7 +104,7 @@ namespace BTCPayServer.Eclair
|
||||
|
||||
public async Task<AllChannelResponse[]> AllChannelsAsync()
|
||||
{
|
||||
return await SendCommandAsync<AllChannelResponse[]>(new RPCRequest("allchannels", new object[] { })).ConfigureAwait(false);
|
||||
return await SendCommandAsync<AllChannelResponse[]>(new RPCRequest("allchannels", Array.Empty<object>())).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public string[] Channels()
|
||||
@ -114,7 +114,7 @@ namespace BTCPayServer.Eclair
|
||||
|
||||
public async Task<string[]> ChannelsAsync()
|
||||
{
|
||||
return await SendCommandAsync<string[]>(new RPCRequest("channels", new object[] { })).ConfigureAwait(false);
|
||||
return await SendCommandAsync<string[]>(new RPCRequest("channels", Array.Empty<object>())).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public void Close(string channelId)
|
||||
@ -155,7 +155,7 @@ namespace BTCPayServer.Eclair
|
||||
|
||||
public async Task<string[]> AllNodesAsync()
|
||||
{
|
||||
return await SendCommandAsync<string[]>(new RPCRequest("allnodes", new object[] { })).ConfigureAwait(false);
|
||||
return await SendCommandAsync<string[]>(new RPCRequest("allnodes", Array.Empty<object>())).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public Uri Address { get; private set; }
|
||||
|
@ -139,7 +139,7 @@ namespace BTCPayServer.Eclair
|
||||
public IEnumerable<LightMoney> Split(int parts)
|
||||
{
|
||||
if (parts <= 0)
|
||||
throw new ArgumentOutOfRangeException("Parts should be more than 0", "parts");
|
||||
throw new ArgumentOutOfRangeException(nameof(parts), "Parts should be more than 0");
|
||||
long remain;
|
||||
long result = DivRem(_MilliSatoshis, parts, out remain);
|
||||
|
||||
@ -431,7 +431,7 @@ namespace BTCPayServer.Eclair
|
||||
/// <returns></returns>
|
||||
public string ToString(bool fplus, bool trimExcessZero = true)
|
||||
{
|
||||
var fmt = string.Format("{{0:{0}{1}B}}",
|
||||
var fmt = string.Format(CultureInfo.InvariantCulture, "{{0:{0}{1}B}}",
|
||||
(fplus ? "+" : null),
|
||||
(trimExcessZero ? "2" : "11"));
|
||||
return string.Format(BitcoinFormatter.Formatter, fmt, _MilliSatoshis);
|
||||
@ -479,7 +479,7 @@ namespace BTCPayServer.Eclair
|
||||
unitToUseInCalc = LightMoneyUnit.BTC;
|
||||
break;
|
||||
}
|
||||
var val = Convert.ToDecimal(arg) / (long)unitToUseInCalc;
|
||||
var val = Convert.ToDecimal(arg, CultureInfo.InvariantCulture) / (long)unitToUseInCalc;
|
||||
var zeros = new string('0', decPos);
|
||||
var rest = new string('#', 11 - decPos);
|
||||
var fmt = plus && val > 0 ? "+" : string.Empty;
|
||||
|
@ -2,11 +2,18 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using BTCPayServer.Services.Invoices;
|
||||
|
||||
namespace BTCPayServer.Events
|
||||
{
|
||||
public class InvoiceDataChangedEvent
|
||||
{
|
||||
public InvoiceDataChangedEvent(InvoiceEntity invoice)
|
||||
{
|
||||
InvoiceId = invoice.Id;
|
||||
Status = invoice.Status;
|
||||
ExceptionStatus = invoice.ExceptionStatus;
|
||||
}
|
||||
public string InvoiceId { get; set; }
|
||||
public string Status { get; internal set; }
|
||||
public string ExceptionStatus { get; internal set; }
|
||||
|
@ -7,6 +7,10 @@ namespace BTCPayServer.Events
|
||||
{
|
||||
public class InvoiceStopWatchedEvent
|
||||
{
|
||||
public InvoiceStopWatchedEvent(string invoiceId)
|
||||
{
|
||||
this.InvoiceId = invoiceId;
|
||||
}
|
||||
public string InvoiceId { get; set; }
|
||||
public override string ToString()
|
||||
{
|
||||
|
@ -22,11 +22,18 @@ using System.IO;
|
||||
using BTCPayServer.Logging;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Net.WebSockets;
|
||||
using BTCPayServer.Services.Invoices;
|
||||
using NBitpayClient;
|
||||
using BTCPayServer.Payments;
|
||||
|
||||
namespace BTCPayServer
|
||||
{
|
||||
public static class Extensions
|
||||
{
|
||||
public static PaymentMethodId GetpaymentMethodId(this InvoiceCryptoInfo info)
|
||||
{
|
||||
return new PaymentMethodId(info.CryptoCode, Enum.Parse<PaymentTypes>(info.PaymentType));
|
||||
}
|
||||
public static async Task CloseSocket(this WebSocket webSocket)
|
||||
{
|
||||
try
|
||||
@ -63,7 +70,7 @@ namespace BTCPayServer
|
||||
}
|
||||
public static string WithTrailingSlash(this string str)
|
||||
{
|
||||
if (str.EndsWith("/"))
|
||||
if (str.EndsWith("/", StringComparison.InvariantCulture))
|
||||
return str;
|
||||
return str + "/";
|
||||
}
|
||||
|
@ -137,7 +137,7 @@ namespace BTCPayServer.HostedServices
|
||||
reschedule = true;
|
||||
|
||||
List<string> messages = new List<string>();
|
||||
while(ex != null)
|
||||
while (ex != null)
|
||||
{
|
||||
messages.Add(ex.Message);
|
||||
ex = ex.InnerException;
|
||||
@ -201,7 +201,7 @@ namespace BTCPayServer.HostedServices
|
||||
|
||||
// We keep backward compatibility with bitpay by passing BTC info to the notification
|
||||
// we don't pass other info, as it is a bad idea to use IPN data for logic processing (can be faked)
|
||||
var btcCryptoInfo = dto.CryptoInfo.FirstOrDefault(c => c.CryptoCode == "BTC");
|
||||
var btcCryptoInfo = dto.CryptoInfo.FirstOrDefault(c => c.GetpaymentMethodId() == new PaymentMethodId("BTC", Payments.PaymentTypes.BTCLike));
|
||||
if (btcCryptoInfo != null)
|
||||
{
|
||||
#pragma warning disable CS0618
|
||||
@ -228,10 +228,68 @@ namespace BTCPayServer.HostedServices
|
||||
|
||||
request.RequestUri = new Uri(invoice.NotificationURL, UriKind.Absolute);
|
||||
request.Content = new StringContent(notificationString, UTF8, "application/json");
|
||||
var response = await _Client.SendAsync(request, cancellation);
|
||||
var response = await Enqueue(invoice.Id, async () => await _Client.SendAsync(request, cancellation));
|
||||
return response;
|
||||
}
|
||||
|
||||
Dictionary<string, Task> _SendingRequestsByInvoiceId = new Dictionary<string, Task>();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Will make sure only one callback is called at once on the same invoiceId
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="sendRequest"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<T> Enqueue<T>(string id, Func<Task<T>> sendRequest)
|
||||
{
|
||||
Task<T> sending = null;
|
||||
lock (_SendingRequestsByInvoiceId)
|
||||
{
|
||||
if (_SendingRequestsByInvoiceId.TryGetValue(id, out var executing))
|
||||
{
|
||||
var completion = new TaskCompletionSource<T>();
|
||||
sending = completion.Task;
|
||||
_SendingRequestsByInvoiceId.Remove(id);
|
||||
_SendingRequestsByInvoiceId.Add(id, sending);
|
||||
executing.ContinueWith(_ =>
|
||||
{
|
||||
sendRequest()
|
||||
.ContinueWith(t =>
|
||||
{
|
||||
if(t.Status == TaskStatus.RanToCompletion)
|
||||
{
|
||||
completion.TrySetResult(t.Result);
|
||||
}
|
||||
if(t.Status == TaskStatus.Faulted)
|
||||
{
|
||||
completion.TrySetException(t.Exception);
|
||||
}
|
||||
if(t.Status == TaskStatus.Canceled)
|
||||
{
|
||||
completion.TrySetCanceled();
|
||||
}
|
||||
}, TaskScheduler.Default);
|
||||
}, TaskScheduler.Default);
|
||||
}
|
||||
else
|
||||
{
|
||||
sending = sendRequest();
|
||||
_SendingRequestsByInvoiceId.Add(id, sending);
|
||||
}
|
||||
sending.ContinueWith(o =>
|
||||
{
|
||||
lock (_SendingRequestsByInvoiceId)
|
||||
{
|
||||
_SendingRequestsByInvoiceId.TryGetValue(id, out var executing2);
|
||||
if(executing2 == sending)
|
||||
_SendingRequestsByInvoiceId.Remove(id);
|
||||
}
|
||||
}, TaskScheduler.Default);
|
||||
}
|
||||
return await sending;
|
||||
}
|
||||
|
||||
int MaxTry = 6;
|
||||
|
||||
private static string GetHttpJobId(InvoiceEntity invoice)
|
||||
|
@ -25,9 +25,9 @@ namespace BTCPayServer.HostedServices
|
||||
{
|
||||
class UpdateInvoiceContext
|
||||
{
|
||||
public UpdateInvoiceContext()
|
||||
public UpdateInvoiceContext(InvoiceEntity invoice)
|
||||
{
|
||||
|
||||
Invoice = invoice;
|
||||
}
|
||||
public InvoiceEntity Invoice { get; set; }
|
||||
public List<object> Events { get; set; } = new List<object>();
|
||||
@ -55,62 +55,7 @@ namespace BTCPayServer.HostedServices
|
||||
_EventAggregator = eventAggregator ?? throw new ArgumentNullException(nameof(eventAggregator));
|
||||
_NetworkProvider = networkProvider;
|
||||
}
|
||||
CompositeDisposable leases = new CompositeDisposable();
|
||||
|
||||
private async Task UpdateInvoice(string invoiceId, CancellationToken cancellation)
|
||||
{
|
||||
Dictionary<BTCPayNetwork, KnownState> changes = new Dictionary<BTCPayNetwork, KnownState>();
|
||||
int maxLoop = 5;
|
||||
int loopCount = -1;
|
||||
while (!cancellation.IsCancellationRequested && loopCount < maxLoop)
|
||||
{
|
||||
loopCount++;
|
||||
try
|
||||
{
|
||||
var invoice = await _InvoiceRepository.GetInvoice(null, invoiceId, true).ConfigureAwait(false);
|
||||
if (invoice == null)
|
||||
break;
|
||||
var stateBefore = invoice.Status;
|
||||
var updateContext = new UpdateInvoiceContext()
|
||||
{
|
||||
Invoice = invoice
|
||||
};
|
||||
await UpdateInvoice(updateContext).ConfigureAwait(false);
|
||||
if (updateContext.Dirty)
|
||||
{
|
||||
await _InvoiceRepository.UpdateInvoiceStatus(invoice.Id, invoice.Status, invoice.ExceptionStatus).ConfigureAwait(false);
|
||||
updateContext.Events.Add(new InvoiceDataChangedEvent() { Status = invoice.Status, ExceptionStatus = invoice.ExceptionStatus, InvoiceId = invoice.Id });
|
||||
}
|
||||
|
||||
var changed = stateBefore != invoice.Status;
|
||||
|
||||
foreach (var evt in updateContext.Events)
|
||||
{
|
||||
_EventAggregator.Publish(evt, evt.GetType());
|
||||
}
|
||||
|
||||
if (invoice.Status == "complete" ||
|
||||
((invoice.Status == "invalid" || invoice.Status == "expired") && invoice.MonitoringExpiration < DateTimeOffset.UtcNow))
|
||||
{
|
||||
if (await _InvoiceRepository.RemovePendingInvoice(invoice.Id).ConfigureAwait(false))
|
||||
_EventAggregator.Publish<InvoiceStopWatchedEvent>(new InvoiceStopWatchedEvent() { InvoiceId = invoice.Id });
|
||||
break;
|
||||
}
|
||||
|
||||
if (updateContext.Events.Count == 0 || cancellation.IsCancellationRequested)
|
||||
break;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logs.PayServer.LogError(ex, "Unhandled error on watching invoice " + invoiceId);
|
||||
await Task.Delay(10000, cancellation).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
CompositeDisposable leases = new CompositeDisposable();
|
||||
|
||||
|
||||
private async Task UpdateInvoice(UpdateInvoiceContext context)
|
||||
@ -127,80 +72,117 @@ namespace BTCPayServer.HostedServices
|
||||
|
||||
var derivationStrategies = invoice.GetDerivationStrategies(_NetworkProvider).ToArray();
|
||||
var payments = invoice.GetPayments().Where(p => p.Accounted).ToArray();
|
||||
foreach (BTCPayNetwork network in _NetworkProvider.GetAll())
|
||||
var allPaymentMethods = invoice.GetPaymentMethods(_NetworkProvider);
|
||||
var paymentMethod = GetNearestClearedPayment(allPaymentMethods, out var accounting, _NetworkProvider);
|
||||
if (paymentMethod == null)
|
||||
return;
|
||||
var network = _NetworkProvider.GetNetwork(paymentMethod.GetId().CryptoCode);
|
||||
if (invoice.Status == "new" || invoice.Status == "expired")
|
||||
{
|
||||
var cryptoData = invoice.GetCryptoData(network, _NetworkProvider);
|
||||
if (cryptoData == null) // Altcoin not supported
|
||||
continue;
|
||||
var cryptoDataAll = invoice.GetCryptoData(_NetworkProvider);
|
||||
var accounting = cryptoData.Calculate();
|
||||
|
||||
if (invoice.Status == "new" || invoice.Status == "expired")
|
||||
if (accounting.Paid >= accounting.TotalDue)
|
||||
{
|
||||
var totalPaid = payments.Select(p => p.GetValue(cryptoDataAll, cryptoData.CryptoCode)).Sum();
|
||||
if (totalPaid >= accounting.TotalDue)
|
||||
if (invoice.Status == "new")
|
||||
{
|
||||
if (invoice.Status == "new")
|
||||
{
|
||||
context.Events.Add(new InvoiceEvent(invoice, 1003, "invoice_paidInFull"));
|
||||
invoice.Status = "paid";
|
||||
invoice.ExceptionStatus = totalPaid > accounting.TotalDue ? "paidOver" : null;
|
||||
await _InvoiceRepository.UnaffectAddress(invoice.Id);
|
||||
context.MarkDirty();
|
||||
}
|
||||
else if (invoice.Status == "expired" && invoice.ExceptionStatus != "paidLate")
|
||||
{
|
||||
invoice.ExceptionStatus = "paidLate";
|
||||
context.Events.Add(new InvoiceEvent(invoice, 1009, "invoice_paidAfterExpiration"));
|
||||
context.MarkDirty();
|
||||
}
|
||||
context.Events.Add(new InvoiceEvent(invoice, 1003, "invoice_paidInFull"));
|
||||
invoice.Status = "paid";
|
||||
invoice.ExceptionStatus = accounting.Paid > accounting.TotalDue ? "paidOver" : null;
|
||||
await _InvoiceRepository.UnaffectAddress(invoice.Id);
|
||||
context.MarkDirty();
|
||||
}
|
||||
|
||||
if (totalPaid < accounting.TotalDue && invoice.GetPayments().Count != 0 && invoice.ExceptionStatus != "paidPartial")
|
||||
else if (invoice.Status == "expired" && invoice.ExceptionStatus != "paidLate")
|
||||
{
|
||||
invoice.ExceptionStatus = "paidPartial";
|
||||
invoice.ExceptionStatus = "paidLate";
|
||||
context.Events.Add(new InvoiceEvent(invoice, 1009, "invoice_paidAfterExpiration"));
|
||||
context.MarkDirty();
|
||||
}
|
||||
}
|
||||
|
||||
if (invoice.Status == "paid")
|
||||
if (accounting.Paid < accounting.TotalDue && invoice.GetPayments().Count != 0 && invoice.ExceptionStatus != "paidPartial")
|
||||
{
|
||||
var transactions = payments.Where(p => p.GetCryptoPaymentData().PaymentConfirmed(p, invoice.SpeedPolicy, network));
|
||||
|
||||
var totalConfirmed = transactions.Select(t => t.GetValue(cryptoDataAll, cryptoData.CryptoCode)).Sum();
|
||||
|
||||
if (// Is after the monitoring deadline
|
||||
(invoice.MonitoringExpiration < DateTimeOffset.UtcNow)
|
||||
&&
|
||||
// And not enough amount confirmed
|
||||
(totalConfirmed < accounting.TotalDue))
|
||||
{
|
||||
await _InvoiceRepository.UnaffectAddress(invoice.Id);
|
||||
context.Events.Add(new InvoiceEvent(invoice, 1013, "invoice_failedToConfirm"));
|
||||
invoice.Status = "invalid";
|
||||
context.MarkDirty();
|
||||
}
|
||||
else if (totalConfirmed >= accounting.TotalDue)
|
||||
{
|
||||
await _InvoiceRepository.UnaffectAddress(invoice.Id);
|
||||
context.Events.Add(new InvoiceEvent(invoice, 1005, "invoice_confirmed"));
|
||||
invoice.Status = "confirmed";
|
||||
context.MarkDirty();
|
||||
}
|
||||
}
|
||||
|
||||
if (invoice.Status == "confirmed")
|
||||
{
|
||||
var transactions = payments.Where(p => p.GetCryptoPaymentData().PaymentCompleted(p, network));
|
||||
var totalConfirmed = transactions.Select(t => t.GetValue(cryptoDataAll, cryptoData.CryptoCode)).Sum();
|
||||
if (totalConfirmed >= accounting.TotalDue)
|
||||
{
|
||||
context.Events.Add(new InvoiceEvent(invoice, 1006, "invoice_completed"));
|
||||
invoice.Status = "complete";
|
||||
context.MarkDirty();
|
||||
}
|
||||
invoice.ExceptionStatus = "paidPartial";
|
||||
context.MarkDirty();
|
||||
}
|
||||
}
|
||||
|
||||
// Just make sure RBF did not cancelled a payment
|
||||
if (invoice.Status == "paid")
|
||||
{
|
||||
if (accounting.Paid == accounting.TotalDue && invoice.ExceptionStatus == "paidOver")
|
||||
{
|
||||
invoice.ExceptionStatus = null;
|
||||
context.MarkDirty();
|
||||
}
|
||||
|
||||
if (accounting.Paid > accounting.TotalDue && invoice.ExceptionStatus != "paidOver")
|
||||
{
|
||||
invoice.ExceptionStatus = "paidOver";
|
||||
context.MarkDirty();
|
||||
}
|
||||
|
||||
if (accounting.Paid < accounting.TotalDue)
|
||||
{
|
||||
invoice.Status = "new";
|
||||
invoice.ExceptionStatus = accounting.Paid == Money.Zero ? null : "paidPartial";
|
||||
context.MarkDirty();
|
||||
}
|
||||
}
|
||||
|
||||
if (invoice.Status == "paid")
|
||||
{
|
||||
var confirmedAccounting = paymentMethod.Calculate(p => p.GetCryptoPaymentData().PaymentConfirmed(p, invoice.SpeedPolicy, network));
|
||||
|
||||
if (// Is after the monitoring deadline
|
||||
(invoice.MonitoringExpiration < DateTimeOffset.UtcNow)
|
||||
&&
|
||||
// And not enough amount confirmed
|
||||
(confirmedAccounting.Paid < accounting.TotalDue))
|
||||
{
|
||||
await _InvoiceRepository.UnaffectAddress(invoice.Id);
|
||||
context.Events.Add(new InvoiceEvent(invoice, 1013, "invoice_failedToConfirm"));
|
||||
invoice.Status = "invalid";
|
||||
context.MarkDirty();
|
||||
}
|
||||
else if (confirmedAccounting.Paid >= accounting.TotalDue)
|
||||
{
|
||||
await _InvoiceRepository.UnaffectAddress(invoice.Id);
|
||||
context.Events.Add(new InvoiceEvent(invoice, 1005, "invoice_confirmed"));
|
||||
invoice.Status = "confirmed";
|
||||
context.MarkDirty();
|
||||
}
|
||||
}
|
||||
|
||||
if (invoice.Status == "confirmed")
|
||||
{
|
||||
var completedAccounting = paymentMethod.Calculate(p => p.GetCryptoPaymentData().PaymentCompleted(p, network));
|
||||
if (completedAccounting.Paid >= accounting.TotalDue)
|
||||
{
|
||||
context.Events.Add(new InvoiceEvent(invoice, 1006, "invoice_completed"));
|
||||
invoice.Status = "complete";
|
||||
context.MarkDirty();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static PaymentMethod GetNearestClearedPayment(PaymentMethodDictionary allPaymentMethods, out PaymentMethodAccounting accounting, BTCPayNetworkProvider networkProvider)
|
||||
{
|
||||
PaymentMethod result = null;
|
||||
accounting = null;
|
||||
decimal nearestToZero = 0.0m;
|
||||
foreach (var paymentMethod in allPaymentMethods)
|
||||
{
|
||||
if (networkProvider != null && networkProvider.GetNetwork(paymentMethod.GetId().CryptoCode) == null)
|
||||
continue;
|
||||
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;
|
||||
}
|
||||
|
||||
TimeSpan _PollInterval;
|
||||
@ -233,13 +215,13 @@ namespace BTCPayServer.HostedServices
|
||||
{
|
||||
await Task.Delay(invoice.ExpirationTime - now, _Cts.Token);
|
||||
}
|
||||
_WatchRequests.Add(invoiceId);
|
||||
Watch(invoiceId);
|
||||
now = DateTimeOffset.UtcNow;
|
||||
if (invoice.MonitoringExpiration > now)
|
||||
{
|
||||
await Task.Delay(invoice.MonitoringExpiration - now, _Cts.Token);
|
||||
}
|
||||
_WatchRequests.Add(invoiceId);
|
||||
Watch(invoiceId);
|
||||
}
|
||||
catch when (_Cts.IsCancellationRequested)
|
||||
{ }
|
||||
@ -258,9 +240,9 @@ namespace BTCPayServer.HostedServices
|
||||
_Loop = StartLoop(_Cts.Token);
|
||||
_WaitingInvoices = WaitPendingInvoices();
|
||||
|
||||
leases.Add(_EventAggregator.Subscribe<Events.InvoiceNeedUpdateEvent>(async b =>
|
||||
leases.Add(_EventAggregator.Subscribe<Events.InvoiceNeedUpdateEvent>(b =>
|
||||
{
|
||||
Watch(b.InvoiceId);
|
||||
Watch(b.InvoiceId);
|
||||
}));
|
||||
leases.Add(_EventAggregator.Subscribe<Events.InvoiceEvent>(async b =>
|
||||
{
|
||||
@ -289,41 +271,63 @@ namespace BTCPayServer.HostedServices
|
||||
{
|
||||
Logs.PayServer.LogInformation("Start watching invoices");
|
||||
await Task.Delay(1).ConfigureAwait(false); // Small hack so that the caller does not block on GetConsumingEnumerable
|
||||
ConcurrentDictionary<string, Lazy<Task>> executing = new ConcurrentDictionary<string, Lazy<Task>>();
|
||||
try
|
||||
{
|
||||
// This loop just make sure an invoice will not be updated at the same time by two tasks.
|
||||
// If an update is happening while a request come, then the update is deferred when the executing task is over
|
||||
foreach (var item in _WatchRequests.GetConsumingEnumerable(cancellation))
|
||||
foreach (var invoiceId in _WatchRequests.GetConsumingEnumerable(cancellation))
|
||||
{
|
||||
var localItem = item;
|
||||
var toExecute = new Lazy<Task>(async () =>
|
||||
int maxLoop = 5;
|
||||
int loopCount = -1;
|
||||
while (!cancellation.IsCancellationRequested && loopCount < maxLoop)
|
||||
{
|
||||
loopCount++;
|
||||
try
|
||||
{
|
||||
await UpdateInvoice(localItem, cancellation);
|
||||
var invoice = await _InvoiceRepository.GetInvoice(null, invoiceId, true);
|
||||
if (invoice == null)
|
||||
break;
|
||||
var updateContext = new UpdateInvoiceContext(invoice);
|
||||
await UpdateInvoice(updateContext);
|
||||
if (updateContext.Dirty)
|
||||
{
|
||||
await _InvoiceRepository.UpdateInvoiceStatus(invoice.Id, invoice.Status, invoice.ExceptionStatus);
|
||||
updateContext.Events.Add(new InvoiceDataChangedEvent(invoice));
|
||||
}
|
||||
|
||||
foreach (var evt in updateContext.Events)
|
||||
{
|
||||
_EventAggregator.Publish(evt, evt.GetType());
|
||||
}
|
||||
|
||||
if (invoice.Status == "complete" ||
|
||||
((invoice.Status == "invalid" || invoice.Status == "expired") && invoice.MonitoringExpiration < DateTimeOffset.UtcNow))
|
||||
{
|
||||
if (await _InvoiceRepository.RemovePendingInvoice(invoice.Id))
|
||||
_EventAggregator.Publish(new InvoiceStopWatchedEvent(invoice.Id));
|
||||
break;
|
||||
}
|
||||
|
||||
if (updateContext.Events.Count == 0 || cancellation.IsCancellationRequested)
|
||||
break;
|
||||
}
|
||||
finally
|
||||
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
|
||||
{
|
||||
executing.TryRemove(localItem, out Lazy<Task> unused);
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logs.PayServer.LogError(ex, "Unhandled error on watching invoice " + invoiceId);
|
||||
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
Task.Delay(10000, cancellation)
|
||||
.ContinueWith(t => _WatchRequests.Add(invoiceId), TaskScheduler.Default);
|
||||
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
|
||||
break;
|
||||
}
|
||||
}, false);
|
||||
var executingTask = executing.GetOrAdd(item, toExecute);
|
||||
executingTask.Value.GetAwaiter(); // Make sure it run
|
||||
if (executingTask != toExecute)
|
||||
{
|
||||
// What was planned can't run for now, rebook it when the executingTask finish
|
||||
var unused = executingTask.Value.ContinueWith(t => _WatchRequests.Add(localItem));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch when (cancellation.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
await Task.WhenAll(executing.Values.Select(v => v.Value).ToArray());
|
||||
}
|
||||
Logs.PayServer.LogInformation("Stop watching invoices");
|
||||
}
|
||||
|
||||
|
@ -143,7 +143,7 @@ namespace BTCPayServer.Hosting
|
||||
});
|
||||
|
||||
services.AddSingleton<IHostedService, NBXplorerWaiters>();
|
||||
services.AddSingleton<IHostedService, NBXplorerListener>();
|
||||
services.AddSingleton<IHostedService, Payments.Bitcoin.NBXplorerListener>();
|
||||
services.AddSingleton<IHostedService, InvoiceNotificationManager>();
|
||||
services.AddSingleton<IHostedService, InvoiceWatcher>();
|
||||
|
||||
|
@ -70,7 +70,7 @@ namespace BTCPayServer.Hosting
|
||||
if (BitIdExtensions.CheckBitIDSignature(key, sig, url, body))
|
||||
{
|
||||
var bitid = new BitIdentity(key);
|
||||
httpContext.User = new GenericPrincipal(bitid, new string[0]);
|
||||
httpContext.User = new GenericPrincipal(bitid, Array.Empty<string>());
|
||||
Logs.PayServer.LogDebug($"BitId signature check success for SIN {bitid.SIN}");
|
||||
}
|
||||
}
|
||||
|
@ -6,6 +6,7 @@ using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BTCPayServer.Logging
|
||||
@ -333,7 +334,8 @@ namespace BTCPayServer.Logging
|
||||
_outputTask = Task.Factory.StartNew(
|
||||
ProcessLogQueue,
|
||||
this,
|
||||
TaskCreationOptions.LongRunning);
|
||||
default(CancellationToken),
|
||||
TaskCreationOptions.LongRunning, TaskScheduler.Default);
|
||||
}
|
||||
|
||||
public virtual void EnqueueMessage(LogMessageEntry message)
|
||||
|
@ -22,7 +22,7 @@ namespace BTCPayServer.Models.InvoicingModels
|
||||
public class Payment
|
||||
{
|
||||
public string CryptoCode { get; set; }
|
||||
public int Confirmations
|
||||
public string Confirmations
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
|
@ -9,7 +9,7 @@ namespace BTCPayServer.Models.InvoicingModels
|
||||
{
|
||||
public class AvailableCrypto
|
||||
{
|
||||
public string CryptoCode { get; set; }
|
||||
public string PaymentMethodId { get; set; }
|
||||
public string CryptoImage { get; set; }
|
||||
public string Link { get; set; }
|
||||
}
|
||||
@ -40,5 +40,7 @@ namespace BTCPayServer.Models.InvoicingModels
|
||||
public string CryptoImage { get; set; }
|
||||
public string NetworkFeeDescription { get; internal set; }
|
||||
public int MaxTimeMinutes { get; internal set; }
|
||||
public string PaymentType { get; internal set; }
|
||||
public string PaymentMethodId { get; internal set; }
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using BTCPayServer.Services.Invoices;
|
||||
using NBitcoin;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace BTCPayServer.Payments.Bitcoin
|
||||
{
|
||||
public class BitcoinLikeOnChainPaymentMethod : IPaymentMethodDetails
|
||||
{
|
||||
public PaymentTypes GetPaymentType()
|
||||
{
|
||||
return PaymentTypes.BTCLike;
|
||||
}
|
||||
|
||||
public string GetPaymentDestination()
|
||||
{
|
||||
return DepositAddress?.ToString();
|
||||
}
|
||||
|
||||
public decimal GetTxFee()
|
||||
{
|
||||
return TxFee.ToDecimal(MoneyUnit.BTC);
|
||||
}
|
||||
|
||||
public void SetPaymentDestination(string newPaymentDestination)
|
||||
{
|
||||
if (newPaymentDestination == null)
|
||||
DepositAddress = null;
|
||||
else
|
||||
DepositAddress = BitcoinAddress.Create(newPaymentDestination, DepositAddress.Network);
|
||||
}
|
||||
|
||||
// Those properties are JsonIgnore because their data is inside CryptoData class for legacy reason
|
||||
[JsonIgnore]
|
||||
public FeeRate FeeRate { get; set; }
|
||||
[JsonIgnore]
|
||||
public Money TxFee { get; set; }
|
||||
[JsonIgnore]
|
||||
public BitcoinAddress DepositAddress { get; set; }
|
||||
///////////////////////////////////////////////////////////////////////////////////////
|
||||
}
|
||||
}
|
78
BTCPayServer/Payments/Bitcoin/BitcoinLikePaymentData.cs
Normal file
78
BTCPayServer/Payments/Bitcoin/BitcoinLikePaymentData.cs
Normal file
@ -0,0 +1,78 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using BTCPayServer.Services.Invoices;
|
||||
using NBitcoin;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace BTCPayServer.Payments.Bitcoin
|
||||
{
|
||||
|
||||
public class BitcoinLikePaymentData : CryptoPaymentData
|
||||
{
|
||||
public PaymentTypes GetPaymentType()
|
||||
{
|
||||
return PaymentTypes.BTCLike;
|
||||
}
|
||||
public BitcoinLikePaymentData()
|
||||
{
|
||||
|
||||
}
|
||||
public BitcoinLikePaymentData(Coin coin, bool rbf)
|
||||
{
|
||||
Outpoint = coin.Outpoint;
|
||||
Output = coin.TxOut;
|
||||
ConfirmationCount = 0;
|
||||
RBF = rbf;
|
||||
}
|
||||
[JsonIgnore]
|
||||
public OutPoint Outpoint { get; set; }
|
||||
[JsonIgnore]
|
||||
public TxOut Output { get; set; }
|
||||
public int ConfirmationCount { get; set; }
|
||||
public bool RBF { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// This is set to true if the payment was created before CryptoPaymentData existed in BTCPayServer
|
||||
/// </summary>
|
||||
public bool Legacy { get; set; }
|
||||
|
||||
public string GetPaymentId()
|
||||
{
|
||||
return Outpoint.ToString();
|
||||
}
|
||||
|
||||
public string[] GetSearchTerms()
|
||||
{
|
||||
return new[] { Outpoint.Hash.ToString() };
|
||||
}
|
||||
|
||||
public decimal GetValue()
|
||||
{
|
||||
return Output.Value.ToDecimal(MoneyUnit.BTC);
|
||||
}
|
||||
|
||||
public bool PaymentCompleted(PaymentEntity entity, BTCPayNetwork network)
|
||||
{
|
||||
return ConfirmationCount >= network.MaxTrackedConfirmation;
|
||||
}
|
||||
|
||||
public bool PaymentConfirmed(PaymentEntity entity, SpeedPolicy speedPolicy, BTCPayNetwork network)
|
||||
{
|
||||
if (speedPolicy == SpeedPolicy.HighSpeed)
|
||||
{
|
||||
return ConfirmationCount >= 1 || !RBF;
|
||||
}
|
||||
else if (speedPolicy == SpeedPolicy.MediumSpeed)
|
||||
{
|
||||
return ConfirmationCount >= 1;
|
||||
}
|
||||
else if (speedPolicy == SpeedPolicy.LowSpeed)
|
||||
{
|
||||
return ConfirmationCount >= 6;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
@ -16,8 +16,10 @@ using BTCPayServer.Services;
|
||||
using BTCPayServer.Services.Wallets;
|
||||
using NBitcoin;
|
||||
using NBXplorer.Models;
|
||||
using BTCPayServer.Payments;
|
||||
using BTCPayServer.HostedServices;
|
||||
|
||||
namespace BTCPayServer.HostedServices
|
||||
namespace BTCPayServer.Payments.Bitcoin
|
||||
{
|
||||
public class NBXplorerListener : IHostedService
|
||||
{
|
||||
@ -137,7 +139,7 @@ namespace BTCPayServer.HostedServices
|
||||
await session.ListenNewBlockAsync(_Cts.Token).ConfigureAwait(false);
|
||||
await session.ListenDerivationSchemesAsync((await GetStrategies(network)).ToArray(), _Cts.Token).ConfigureAwait(false);
|
||||
|
||||
Logs.PayServer.LogInformation($"{network.CryptoCode}: if any pending invoice got paid while offline...");
|
||||
Logs.PayServer.LogInformation($"{network.CryptoCode}: Checking if any pending invoice got paid while offline...");
|
||||
int paymentCount = await FindPaymentViaPolling(wallet, network);
|
||||
Logs.PayServer.LogInformation($"{network.CryptoCode}: {paymentCount} payments happened while offline");
|
||||
|
||||
@ -165,10 +167,11 @@ namespace BTCPayServer.HostedServices
|
||||
var invoice = await _InvoiceRepository.GetInvoiceFromScriptPubKey(output.ScriptPubKey, network.CryptoCode);
|
||||
if (invoice != null)
|
||||
{
|
||||
var payment = invoice.GetPayments().FirstOrDefault(p => p.Outpoint == txCoin.Outpoint);
|
||||
if (payment == null)
|
||||
var paymentData = new BitcoinLikePaymentData(txCoin, evt.TransactionData.Transaction.RBF);
|
||||
var alreadyExist = GetAllBitcoinPaymentData(invoice).Where(c => c.GetPaymentId() == paymentData.GetPaymentId()).Any();
|
||||
if (!alreadyExist)
|
||||
{
|
||||
payment = await _InvoiceRepository.AddPayment(invoice.Id, DateTimeOffset.UtcNow, txCoin, network.CryptoCode);
|
||||
var payment = await _InvoiceRepository.AddPayment(invoice.Id, DateTimeOffset.UtcNow, paymentData, network.CryptoCode);
|
||||
await ReceivedPayment(wallet, invoice.Id, payment, evt.DerivationStrategy);
|
||||
}
|
||||
else
|
||||
@ -205,17 +208,27 @@ namespace BTCPayServer.HostedServices
|
||||
}
|
||||
}
|
||||
|
||||
IEnumerable<BitcoinLikePaymentData> GetAllBitcoinPaymentData(InvoiceEntity invoice)
|
||||
{
|
||||
return invoice.GetPayments()
|
||||
.Where(p => p.GetpaymentMethodId().PaymentType == PaymentTypes.BTCLike)
|
||||
.Select(p => (BitcoinLikePaymentData)p.GetCryptoPaymentData());
|
||||
}
|
||||
|
||||
async Task<InvoiceEntity> UpdatePaymentStates(BTCPayWallet wallet, string invoiceId)
|
||||
{
|
||||
var invoice = await _InvoiceRepository.GetInvoice(null, invoiceId, false);
|
||||
List<PaymentEntity> updatedPaymentEntities = new List<PaymentEntity>();
|
||||
var transactions = await wallet.GetTransactions(invoice.GetPayments(wallet.Network)
|
||||
.Select(t => t.Outpoint.Hash)
|
||||
var transactions = await wallet.GetTransactions(GetAllBitcoinPaymentData(invoice)
|
||||
.Select(p => p.Outpoint.Hash)
|
||||
.ToArray());
|
||||
var conflicts = GetConflicts(transactions.Select(t => t.Value));
|
||||
foreach (var payment in invoice.GetPayments(wallet.Network))
|
||||
{
|
||||
if (!transactions.TryGetValue(payment.Outpoint.Hash, out TransactionResult tx))
|
||||
if (payment.GetpaymentMethodId().PaymentType != PaymentTypes.BTCLike)
|
||||
continue;
|
||||
var paymentData = (BitcoinLikePaymentData)payment.GetCryptoPaymentData();
|
||||
if (!transactions.TryGetValue(paymentData.Outpoint.Hash, out TransactionResult tx))
|
||||
continue;
|
||||
var txId = tx.Transaction.GetHash();
|
||||
var txConflict = conflicts.GetConflict(txId);
|
||||
@ -228,27 +241,12 @@ namespace BTCPayServer.HostedServices
|
||||
payment.Accounted = accounted;
|
||||
}
|
||||
|
||||
var bitcoinLike = payment.GetCryptoPaymentData() as BitcoinLikePaymentData;
|
||||
|
||||
// Legacy
|
||||
if (bitcoinLike == null)
|
||||
if (paymentData.ConfirmationCount != tx.Confirmations)
|
||||
{
|
||||
#pragma warning disable CS0618 // Type or member is obsolete
|
||||
payment.CryptoPaymentDataType = "BTCLike";
|
||||
#pragma warning restore CS0618 // Type or member is obsolete
|
||||
bitcoinLike = new BitcoinLikePaymentData();
|
||||
bitcoinLike.ConfirmationCount = tx.Confirmations;
|
||||
bitcoinLike.RBF = tx.Transaction.RBF;
|
||||
payment.SetCryptoPaymentData(bitcoinLike);
|
||||
updated = true;
|
||||
}
|
||||
|
||||
if (bitcoinLike.ConfirmationCount != tx.Confirmations)
|
||||
{
|
||||
if(wallet.Network.MaxTrackedConfirmation >= bitcoinLike.ConfirmationCount)
|
||||
{
|
||||
bitcoinLike.ConfirmationCount = tx.Confirmations;
|
||||
payment.SetCryptoPaymentData(bitcoinLike);
|
||||
if(wallet.Network.MaxTrackedConfirmation >= paymentData.ConfirmationCount)
|
||||
{
|
||||
paymentData.ConfirmationCount = tx.Confirmations;
|
||||
payment.SetCryptoPaymentData(paymentData);
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
@ -328,16 +326,21 @@ namespace BTCPayServer.HostedServices
|
||||
foreach (var invoiceId in invoices)
|
||||
{
|
||||
var invoice = await _InvoiceRepository.GetInvoice(null, invoiceId, true);
|
||||
var alreadyAccounted = new HashSet<OutPoint>(invoice.GetPayments(network).Select(p => p.Outpoint));
|
||||
var alreadyAccounted = GetAllBitcoinPaymentData(invoice).Select(p => p.Outpoint).ToHashSet();
|
||||
var strategy = invoice.GetDerivationStrategy(network);
|
||||
if (strategy == null)
|
||||
continue;
|
||||
var cryptoId = new PaymentMethodId(network.CryptoCode, PaymentTypes.BTCLike);
|
||||
if (!invoice.Support(cryptoId))
|
||||
continue;
|
||||
var coins = (await wallet.GetUnspentCoins(strategy))
|
||||
.Where(c => invoice.AvailableAddressHashes.Contains(c.Coin.ScriptPubKey.Hash.ToString() + network.CryptoCode))
|
||||
.Where(c => invoice.AvailableAddressHashes.Contains(c.Coin.ScriptPubKey.Hash.ToString() + cryptoId))
|
||||
.ToArray();
|
||||
foreach (var coin in coins.Where(c => !alreadyAccounted.Contains(c.Coin.Outpoint)))
|
||||
{
|
||||
var payment = await _InvoiceRepository.AddPayment(invoice.Id, coin.Timestamp, coin.Coin, network.CryptoCode).ConfigureAwait(false);
|
||||
var transaction = await wallet.GetTransactionAsync(coin.Coin.Outpoint.Hash);
|
||||
var paymentData = new BitcoinLikePaymentData(coin.Coin, transaction.Transaction.RBF);
|
||||
var payment = await _InvoiceRepository.AddPayment(invoice.Id, coin.Timestamp, paymentData, network.CryptoCode).ConfigureAwait(false);
|
||||
alreadyAccounted.Add(coin.Coin.Outpoint);
|
||||
invoice = await ReceivedPayment(wallet, invoice.Id, payment, strategy);
|
||||
totalPayment++;
|
||||
@ -348,15 +351,20 @@ namespace BTCPayServer.HostedServices
|
||||
|
||||
private async Task<InvoiceEntity> ReceivedPayment(BTCPayWallet wallet, string invoiceId, PaymentEntity payment, DerivationStrategyBase strategy)
|
||||
{
|
||||
var paymentData = (BitcoinLikePaymentData)payment.GetCryptoPaymentData();
|
||||
var invoice = (await UpdatePaymentStates(wallet, invoiceId));
|
||||
var cryptoData = invoice.GetCryptoData(wallet.Network, _ExplorerClients.NetworkProviders);
|
||||
if (cryptoData.GetDepositAddress().ScriptPubKey == payment.GetScriptPubKey() && cryptoData.Calculate().Due > Money.Zero)
|
||||
var paymentMethod = invoice.GetPaymentMethod(wallet.Network, PaymentTypes.BTCLike, _ExplorerClients.NetworkProviders);
|
||||
if (paymentMethod != null &&
|
||||
paymentMethod.GetPaymentMethodDetails() is BitcoinLikeOnChainPaymentMethod btc &&
|
||||
btc.DepositAddress.ScriptPubKey == paymentData.Output.ScriptPubKey &&
|
||||
paymentMethod.Calculate().Due > Money.Zero)
|
||||
{
|
||||
var address = await wallet.ReserveAddressAsync(strategy);
|
||||
await _InvoiceRepository.NewAddress(invoiceId, address, wallet.Network);
|
||||
btc.DepositAddress = address;
|
||||
await _InvoiceRepository.NewAddress(invoiceId, btc, wallet.Network);
|
||||
_Aggregator.Publish(new InvoiceNewAddressEvent(invoiceId, address.ToString(), wallet.Network));
|
||||
cryptoData.DepositAddress = address.ToString();
|
||||
invoice.SetCryptoData(cryptoData);
|
||||
paymentMethod.SetPaymentMethodDetails(btc);
|
||||
invoice.SetPaymentMethod(paymentMethod);
|
||||
}
|
||||
wallet.InvalidateCache(strategy);
|
||||
_Aggregator.Publish(new InvoiceEvent(invoiceId, 1002, "invoice_receivedPayment"));
|
16
BTCPayServer/Payments/IPaymentMethodDetails.cs
Normal file
16
BTCPayServer/Payments/IPaymentMethodDetails.cs
Normal file
@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using NBitcoin;
|
||||
|
||||
namespace BTCPayServer.Payments
|
||||
{
|
||||
public interface IPaymentMethodDetails
|
||||
{
|
||||
string GetPaymentDestination();
|
||||
PaymentTypes GetPaymentType();
|
||||
decimal GetTxFee();
|
||||
void SetPaymentDestination(string newPaymentDestination);
|
||||
}
|
||||
}
|
12
BTCPayServer/Payments/PaymentTypes.cs
Normal file
12
BTCPayServer/Payments/PaymentTypes.cs
Normal file
@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BTCPayServer.Payments
|
||||
{
|
||||
public enum PaymentTypes
|
||||
{
|
||||
BTCLike
|
||||
}
|
||||
}
|
@ -27,7 +27,7 @@ namespace BTCPayServer
|
||||
{
|
||||
if(filter.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Length == 2)
|
||||
{
|
||||
TextSearch = TextSearch.Replace(filter, string.Empty);
|
||||
TextSearch = TextSearch.Replace(filter, string.Empty, StringComparison.InvariantCulture);
|
||||
}
|
||||
}
|
||||
TextSearch = TextSearch.Trim();
|
||||
|
@ -113,7 +113,7 @@ namespace BTCPayServer.Services
|
||||
public async Task<bool> SupportDerivation(BTCPayNetwork network, DirectDerivationStrategy strategy)
|
||||
{
|
||||
if (network == null)
|
||||
throw new ArgumentNullException(nameof(Network));
|
||||
throw new ArgumentNullException(nameof(network));
|
||||
if (strategy == null)
|
||||
throw new ArgumentNullException(nameof(strategy));
|
||||
if (!strategy.Segwit)
|
||||
|
81
BTCPayServer/Services/Invoices/CryptoDataDictionary.cs
Normal file
81
BTCPayServer/Services/Invoices/CryptoDataDictionary.cs
Normal file
@ -0,0 +1,81 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using BTCPayServer.Payments;
|
||||
|
||||
namespace BTCPayServer.Services.Invoices
|
||||
{
|
||||
public class PaymentMethodDictionary : IEnumerable<PaymentMethod>
|
||||
{
|
||||
Dictionary<PaymentMethodId, PaymentMethod> _Inner = new Dictionary<PaymentMethodId, PaymentMethod>();
|
||||
public PaymentMethodDictionary()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public PaymentMethodDictionary(BTCPayNetworkProvider networkProvider)
|
||||
{
|
||||
NetworkProvider = networkProvider;
|
||||
}
|
||||
|
||||
|
||||
public BTCPayNetworkProvider NetworkProvider { get; set; }
|
||||
public PaymentMethod this[PaymentMethodId index]
|
||||
{
|
||||
get
|
||||
{
|
||||
return _Inner[index];
|
||||
}
|
||||
}
|
||||
|
||||
public void Add(PaymentMethod paymentMethod)
|
||||
{
|
||||
_Inner.Add(paymentMethod.GetId(), paymentMethod);
|
||||
}
|
||||
|
||||
public void Remove(PaymentMethod paymentMethod)
|
||||
{
|
||||
_Inner.Remove(paymentMethod.GetId());
|
||||
}
|
||||
public bool TryGetValue(PaymentMethodId paymentMethodId, out PaymentMethod data)
|
||||
{
|
||||
if (paymentMethodId == null)
|
||||
throw new ArgumentNullException(nameof(paymentMethodId));
|
||||
return _Inner.TryGetValue(paymentMethodId, out data);
|
||||
}
|
||||
|
||||
public void AddOrReplace(PaymentMethod paymentMethod)
|
||||
{
|
||||
var key = paymentMethod.GetId();
|
||||
_Inner.Remove(key);
|
||||
_Inner.Add(key, paymentMethod);
|
||||
}
|
||||
|
||||
public IEnumerator<PaymentMethod> GetEnumerator()
|
||||
{
|
||||
return _Inner.Values.GetEnumerator();
|
||||
}
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
return GetEnumerator();
|
||||
}
|
||||
|
||||
public PaymentMethod TryGet(PaymentMethodId paymentMethodId)
|
||||
{
|
||||
if (paymentMethodId == null)
|
||||
throw new ArgumentNullException(nameof(paymentMethodId));
|
||||
_Inner.TryGetValue(paymentMethodId, out var value);
|
||||
return value;
|
||||
}
|
||||
public PaymentMethod TryGet(string network, PaymentTypes paymentType)
|
||||
{
|
||||
if (network == null)
|
||||
throw new ArgumentNullException(nameof(network));
|
||||
var id = new PaymentMethodId(network, paymentType);
|
||||
return TryGet(id);
|
||||
}
|
||||
}
|
||||
}
|
@ -11,6 +11,7 @@ using BTCPayServer.Data;
|
||||
using NBXplorer.Models;
|
||||
using NBXplorer;
|
||||
using NBXplorer.DerivationStrategy;
|
||||
using BTCPayServer.Payments;
|
||||
|
||||
namespace BTCPayServer.Services.Invoices
|
||||
{
|
||||
@ -121,7 +122,7 @@ namespace BTCPayServer.Services.Invoices
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
[Obsolete("Use GetCryptoData(network).Rate instead")]
|
||||
[Obsolete("Use GetPaymentMethod(network) instead")]
|
||||
public decimal Rate
|
||||
{
|
||||
get; set;
|
||||
@ -135,7 +136,7 @@ namespace BTCPayServer.Services.Invoices
|
||||
get; set;
|
||||
}
|
||||
|
||||
[Obsolete("Use GetCryptoData(network).DepositAddress instead")]
|
||||
[Obsolete("Use GetPaymentMethod(network).GetPaymentMethodDetails().GetDestinationAddress() instead")]
|
||||
public string DepositAddress
|
||||
{
|
||||
get; set;
|
||||
@ -171,16 +172,18 @@ namespace BTCPayServer.Services.Invoices
|
||||
public DerivationStrategyBase GetDerivationStrategy(BTCPayNetwork network)
|
||||
{
|
||||
#pragma warning disable CS0618
|
||||
JObject strategies = JObject.Parse(DerivationStrategies);
|
||||
#pragma warning restore CS0618
|
||||
foreach (var strat in strategies.Properties())
|
||||
if (!string.IsNullOrEmpty(DerivationStrategies))
|
||||
{
|
||||
if (strat.Name == network.CryptoCode)
|
||||
JObject strategies = JObject.Parse(DerivationStrategies);
|
||||
#pragma warning restore CS0618
|
||||
foreach (var strat in strategies.Properties())
|
||||
{
|
||||
return BTCPayServer.DerivationStrategy.Parse(strat.Value.Value<string>(), network).DerivationStrategyBase;
|
||||
if (strat.Name == network.CryptoCode)
|
||||
{
|
||||
return BTCPayServer.DerivationStrategy.Parse(strat.Value.Value<string>(), network).DerivationStrategyBase;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma warning disable CS0618
|
||||
if (network.IsBTC && !string.IsNullOrEmpty(DerivationStrategy))
|
||||
{
|
||||
@ -279,7 +282,7 @@ namespace BTCPayServer.Services.Invoices
|
||||
set;
|
||||
}
|
||||
|
||||
[Obsolete("Use GetCryptoData(network).TxFee instead")]
|
||||
[Obsolete("Use GetPaymentMethod(network).GetTxFee() instead")]
|
||||
public Money TxFee
|
||||
{
|
||||
get;
|
||||
@ -301,8 +304,9 @@ namespace BTCPayServer.Services.Invoices
|
||||
set;
|
||||
}
|
||||
|
||||
[Obsolete("Use Set/GetCryptoData() instead")]
|
||||
public JObject CryptoData { get; set; }
|
||||
[Obsolete("Use Set/GetPaymentMethod() instead")]
|
||||
[JsonProperty(PropertyName = "cryptoData")]
|
||||
public JObject PaymentMethod { get; set; }
|
||||
|
||||
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
|
||||
public DateTimeOffset MonitoringExpiration
|
||||
@ -347,11 +351,12 @@ namespace BTCPayServer.Services.Invoices
|
||||
};
|
||||
|
||||
dto.CryptoInfo = new List<NBitpayClient.InvoiceCryptoInfo>();
|
||||
foreach (var info in this.GetCryptoData(networkProvider, true).Values)
|
||||
foreach (var info in this.GetPaymentMethods(networkProvider, true))
|
||||
{
|
||||
var accounting = info.Calculate();
|
||||
var cryptoInfo = new NBitpayClient.InvoiceCryptoInfo();
|
||||
cryptoInfo.CryptoCode = info.CryptoCode;
|
||||
cryptoInfo.CryptoCode = info.GetId().CryptoCode;
|
||||
cryptoInfo.PaymentType = info.GetId().PaymentType.ToString();
|
||||
cryptoInfo.Rate = info.Rate;
|
||||
cryptoInfo.Price = Money.Coins(ProductInformation.Price / cryptoInfo.Rate).ToString();
|
||||
|
||||
@ -362,7 +367,7 @@ namespace BTCPayServer.Services.Invoices
|
||||
cryptoInfo.TxCount = accounting.TxCount;
|
||||
cryptoInfo.CryptoPaid = accounting.CryptoPaid.ToString();
|
||||
|
||||
cryptoInfo.Address = info.DepositAddress;
|
||||
cryptoInfo.Address = info.GetPaymentMethodDetails()?.GetPaymentDestination();
|
||||
cryptoInfo.ExRates = new Dictionary<string, double>
|
||||
{
|
||||
{ ProductInformation.Currency, (double)cryptoInfo.Rate }
|
||||
@ -413,48 +418,50 @@ namespace BTCPayServer.Services.Invoices
|
||||
JsonConvert.PopulateObject(str, dest);
|
||||
}
|
||||
|
||||
internal bool Support(BTCPayNetwork network)
|
||||
internal bool Support(PaymentMethodId paymentMethodId)
|
||||
{
|
||||
var rates = GetCryptoData(null);
|
||||
return rates.TryGetValue(network.CryptoCode, out var data);
|
||||
var rates = GetPaymentMethods(null);
|
||||
return rates.TryGet(paymentMethodId) != null;
|
||||
}
|
||||
|
||||
public CryptoData GetCryptoData(string cryptoCode, BTCPayNetworkProvider networkProvider, bool alwaysIncludeBTC = false)
|
||||
public PaymentMethod GetPaymentMethod(PaymentMethodId paymentMethodId, BTCPayNetworkProvider networkProvider)
|
||||
{
|
||||
GetCryptoData(networkProvider, alwaysIncludeBTC).TryGetValue(cryptoCode, out var data);
|
||||
GetPaymentMethods(networkProvider).TryGetValue(paymentMethodId, out var data);
|
||||
return data;
|
||||
}
|
||||
|
||||
public CryptoData GetCryptoData(BTCPayNetwork network, BTCPayNetworkProvider networkProvider)
|
||||
public PaymentMethod GetPaymentMethod(BTCPayNetwork network, PaymentTypes paymentType, BTCPayNetworkProvider networkProvider)
|
||||
{
|
||||
GetCryptoData(networkProvider).TryGetValue(network.CryptoCode, out var data);
|
||||
return data;
|
||||
return GetPaymentMethod(new PaymentMethodId(network.CryptoCode, paymentType), networkProvider);
|
||||
}
|
||||
|
||||
public Dictionary<string, CryptoData> GetCryptoData(BTCPayNetworkProvider networkProvider, bool alwaysIncludeBTC = false)
|
||||
public PaymentMethodDictionary GetPaymentMethods(BTCPayNetworkProvider networkProvider, bool alwaysIncludeBTC = false)
|
||||
{
|
||||
Dictionary<string, CryptoData> rates = new Dictionary<string, CryptoData>();
|
||||
PaymentMethodDictionary rates = new PaymentMethodDictionary(networkProvider);
|
||||
var serializer = new Serializer(Dummy);
|
||||
CryptoData phantom = null;
|
||||
PaymentMethod phantom = null;
|
||||
#pragma warning disable CS0618
|
||||
// Legacy
|
||||
if (alwaysIncludeBTC)
|
||||
{
|
||||
var btcNetwork = networkProvider?.GetNetwork("BTC");
|
||||
phantom = new CryptoData() { ParentEntity = this, IsPhantomBTC = true, Rate = Rate, CryptoCode = "BTC", TxFee = TxFee, FeeRate = new FeeRate(TxFee, 100), DepositAddress = DepositAddress, Network = btcNetwork };
|
||||
rates.Add("BTC", phantom);
|
||||
phantom = new PaymentMethod() { ParentEntity = this, IsPhantomBTC = true, Rate = Rate, CryptoCode = "BTC", TxFee = TxFee, FeeRate = new FeeRate(TxFee, 100), DepositAddress = DepositAddress, Network = btcNetwork };
|
||||
if (btcNetwork != null || networkProvider == null)
|
||||
rates.Add(phantom);
|
||||
}
|
||||
if (CryptoData != null)
|
||||
if (PaymentMethod != null)
|
||||
{
|
||||
foreach (var prop in CryptoData.Properties())
|
||||
foreach (var prop in PaymentMethod.Properties())
|
||||
{
|
||||
if (prop.Name == "BTC" && phantom != null)
|
||||
rates.Remove("BTC");
|
||||
var r = serializer.ToObject<CryptoData>(prop.Value.ToString());
|
||||
r.CryptoCode = prop.Name;
|
||||
rates.Remove(phantom);
|
||||
var r = serializer.ToObject<PaymentMethod>(prop.Value.ToString());
|
||||
var paymentMethodId = PaymentMethodId.Parse(prop.Name);
|
||||
r.CryptoCode = paymentMethodId.CryptoCode;
|
||||
r.PaymentType = paymentMethodId.PaymentType.ToString();
|
||||
r.ParentEntity = this;
|
||||
r.Network = networkProvider?.GetNetwork(r.CryptoCode);
|
||||
rates.Add(r.CryptoCode, r);
|
||||
if (r.Network != null || networkProvider == null)
|
||||
rates.Add(r);
|
||||
}
|
||||
}
|
||||
#pragma warning restore CS0618
|
||||
@ -463,30 +470,37 @@ namespace BTCPayServer.Services.Invoices
|
||||
|
||||
Network Dummy = Network.Main;
|
||||
|
||||
public void SetCryptoData(CryptoData cryptoData)
|
||||
public void SetPaymentMethod(PaymentMethod paymentMethod)
|
||||
{
|
||||
var dict = GetCryptoData(null);
|
||||
dict.AddOrReplace(cryptoData.CryptoCode, cryptoData);
|
||||
SetCryptoData(dict);
|
||||
var dict = GetPaymentMethods(null);
|
||||
dict.AddOrReplace(paymentMethod);
|
||||
SetPaymentMethods(dict);
|
||||
}
|
||||
|
||||
public void SetCryptoData(Dictionary<string, CryptoData> cryptoData)
|
||||
public void SetPaymentMethods(PaymentMethodDictionary paymentMethods)
|
||||
{
|
||||
if (paymentMethods.NetworkProvider != null)
|
||||
throw new InvalidOperationException($"{nameof(paymentMethods)} should have NetworkProvider to null");
|
||||
var obj = new JObject();
|
||||
var serializer = new Serializer(Dummy);
|
||||
foreach (var kv in cryptoData)
|
||||
{
|
||||
var clone = serializer.ToObject<CryptoData>(serializer.ToString(kv.Value));
|
||||
clone.CryptoCode = null;
|
||||
obj.Add(new JProperty(kv.Key, JObject.Parse(serializer.ToString(clone))));
|
||||
}
|
||||
#pragma warning disable CS0618
|
||||
CryptoData = obj;
|
||||
foreach (var v in paymentMethods)
|
||||
{
|
||||
var clone = serializer.ToObject<PaymentMethod>(serializer.ToString(v));
|
||||
clone.CryptoCode = null;
|
||||
clone.PaymentType = null;
|
||||
obj.Add(new JProperty(v.GetId().ToString(), JObject.Parse(serializer.ToString(clone))));
|
||||
}
|
||||
PaymentMethod = obj;
|
||||
foreach(var cryptoData in paymentMethods)
|
||||
{
|
||||
cryptoData.ParentEntity = this;
|
||||
}
|
||||
#pragma warning restore CS0618
|
||||
}
|
||||
}
|
||||
|
||||
public class CryptoDataAccounting
|
||||
public class PaymentMethodAccounting
|
||||
{
|
||||
/// <summary>
|
||||
/// Total amount of this invoice
|
||||
@ -498,6 +512,10 @@ namespace BTCPayServer.Services.Invoices
|
||||
/// </summary>
|
||||
public Money Due { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Same as Due, can be negative
|
||||
/// </summary>
|
||||
public Money DueUncapped { get; set; }
|
||||
/// <summary>
|
||||
/// Total amount of the invoice paid after conversion to this crypto currency
|
||||
/// </summary>
|
||||
@ -518,62 +536,195 @@ namespace BTCPayServer.Services.Invoices
|
||||
public Money NetworkFee { get; set; }
|
||||
}
|
||||
|
||||
public class CryptoData
|
||||
public class PaymentMethodId
|
||||
{
|
||||
public PaymentMethodId(string cryptoCode, PaymentTypes paymentType)
|
||||
{
|
||||
if (cryptoCode == null)
|
||||
throw new ArgumentNullException(nameof(cryptoCode));
|
||||
PaymentType = paymentType;
|
||||
CryptoCode = cryptoCode;
|
||||
}
|
||||
public string CryptoCode { get; private set; }
|
||||
public PaymentTypes PaymentType { get; private set; }
|
||||
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
PaymentMethodId item = obj as PaymentMethodId;
|
||||
if (item == null)
|
||||
return false;
|
||||
return ToString().Equals(item.ToString(), StringComparison.InvariantCulture);
|
||||
}
|
||||
public static bool operator ==(PaymentMethodId a, PaymentMethodId b)
|
||||
{
|
||||
if (System.Object.ReferenceEquals(a, b))
|
||||
return true;
|
||||
if (((object)a == null) || ((object)b == null))
|
||||
return false;
|
||||
return a.ToString() == b.ToString();
|
||||
}
|
||||
|
||||
public static bool operator !=(PaymentMethodId a, PaymentMethodId b)
|
||||
{
|
||||
return !(a == b);
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
#pragma warning disable CA1307 // Specify StringComparison
|
||||
return ToString().GetHashCode();
|
||||
#pragma warning restore CA1307 // Specify StringComparison
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
if (PaymentType == PaymentTypes.BTCLike)
|
||||
return CryptoCode;
|
||||
return CryptoCode + "_" + PaymentType.ToString();
|
||||
}
|
||||
|
||||
public static PaymentMethodId Parse(string str)
|
||||
{
|
||||
var parts = str.Split('_');
|
||||
return new PaymentMethodId(parts[0], parts.Length == 1 ? PaymentTypes.BTCLike : Enum.Parse<PaymentTypes>(parts[1]));
|
||||
}
|
||||
}
|
||||
|
||||
public class PaymentMethod
|
||||
{
|
||||
[JsonIgnore]
|
||||
public InvoiceEntity ParentEntity { get; set; }
|
||||
[JsonIgnore]
|
||||
public BTCPayNetwork Network { get; set; }
|
||||
[JsonProperty(PropertyName = "cryptoCode", DefaultValueHandling = DefaultValueHandling.Ignore)]
|
||||
[Obsolete("Use GetId().CryptoCode instead")]
|
||||
public string CryptoCode { get; set; }
|
||||
[JsonProperty(PropertyName = "paymentType", DefaultValueHandling = DefaultValueHandling.Ignore)]
|
||||
[Obsolete("Use GetId().PaymentType instead")]
|
||||
public string PaymentType { get; set; }
|
||||
|
||||
|
||||
public PaymentMethodId GetId()
|
||||
{
|
||||
#pragma warning disable CS0618 // Type or member is obsolete
|
||||
return new PaymentMethodId(CryptoCode, string.IsNullOrEmpty(PaymentType) ? PaymentTypes.BTCLike : Enum.Parse<PaymentTypes>(PaymentType));
|
||||
#pragma warning restore CS0618 // Type or member is obsolete
|
||||
}
|
||||
|
||||
public void SetId(PaymentMethodId id)
|
||||
{
|
||||
#pragma warning disable CS0618 // Type or member is obsolete
|
||||
CryptoCode = id.CryptoCode;
|
||||
PaymentType = id.PaymentType.ToString();
|
||||
#pragma warning restore CS0618 // Type or member is obsolete
|
||||
}
|
||||
|
||||
[JsonProperty(PropertyName = "rate")]
|
||||
public decimal Rate { get; set; }
|
||||
|
||||
[Obsolete("Use GetPaymentMethodDetails() instead")]
|
||||
[JsonProperty(PropertyName = "paymentMethod")]
|
||||
public JObject PaymentMethodDetails { get; set; }
|
||||
public IPaymentMethodDetails GetPaymentMethodDetails()
|
||||
{
|
||||
#pragma warning disable CS0618 // Type or member is obsolete
|
||||
// Legacy, old code does not have PaymentMethods
|
||||
if (string.IsNullOrEmpty(PaymentType) || PaymentMethodDetails == null)
|
||||
{
|
||||
return new Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod()
|
||||
{
|
||||
FeeRate = FeeRate,
|
||||
DepositAddress = string.IsNullOrEmpty(DepositAddress) ? null : BitcoinAddress.Create(DepositAddress, Network?.NBitcoinNetwork),
|
||||
TxFee = TxFee
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
if (GetId().PaymentType == PaymentTypes.BTCLike)
|
||||
{
|
||||
var method = DeserializePaymentMethodDetails<Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod>(PaymentMethodDetails);
|
||||
method.TxFee = TxFee;
|
||||
method.DepositAddress = BitcoinAddress.Create(DepositAddress, Network?.NBitcoinNetwork);
|
||||
method.FeeRate = FeeRate;
|
||||
return method;
|
||||
}
|
||||
}
|
||||
throw new NotSupportedException(PaymentType);
|
||||
#pragma warning restore CS0618 // Type or member is obsolete
|
||||
}
|
||||
|
||||
private T DeserializePaymentMethodDetails<T>(JObject jobj) where T : class, IPaymentMethodDetails
|
||||
{
|
||||
return JsonConvert.DeserializeObject<T>(jobj.ToString());
|
||||
}
|
||||
|
||||
public PaymentMethod SetPaymentMethodDetails(IPaymentMethodDetails paymentMethod)
|
||||
{
|
||||
#pragma warning disable CS0618 // Type or member is obsolete
|
||||
// Legacy, need to fill the old fields
|
||||
|
||||
if (PaymentType == null)
|
||||
PaymentType = paymentMethod.GetPaymentType().ToString();
|
||||
else if (PaymentType != paymentMethod.GetPaymentType().ToString())
|
||||
throw new InvalidOperationException("Invalid payment method affected");
|
||||
|
||||
if (paymentMethod is Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod bitcoinPaymentMethod)
|
||||
{
|
||||
TxFee = bitcoinPaymentMethod.TxFee;
|
||||
FeeRate = bitcoinPaymentMethod.FeeRate;
|
||||
DepositAddress = bitcoinPaymentMethod.DepositAddress.ToString();
|
||||
}
|
||||
var jobj = JObject.Parse(JsonConvert.SerializeObject(paymentMethod));
|
||||
PaymentMethodDetails = jobj;
|
||||
|
||||
#pragma warning restore CS0618 // Type or member is obsolete
|
||||
return this;
|
||||
}
|
||||
|
||||
[JsonProperty(PropertyName = "feeRate")]
|
||||
[Obsolete("Use ((BitcoinLikeOnChainPaymentMethod)GetPaymentMethod()).FeeRate")]
|
||||
public FeeRate FeeRate { get; set; }
|
||||
[JsonProperty(PropertyName = "txFee")]
|
||||
[Obsolete("Use ((BitcoinLikeOnChainPaymentMethod)GetPaymentMethod()).TxFee")]
|
||||
public Money TxFee { get; set; }
|
||||
[JsonProperty(PropertyName = "depositAddress")]
|
||||
[Obsolete("Use ((BitcoinLikeOnChainPaymentMethod)GetPaymentMethod()).DepositAddress")]
|
||||
public string DepositAddress { get; set; }
|
||||
|
||||
public BitcoinAddress GetDepositAddress()
|
||||
{
|
||||
if(string.IsNullOrEmpty(DepositAddress))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return BitcoinAddress.Create(DepositAddress, Network.NBitcoinNetwork);
|
||||
}
|
||||
|
||||
[JsonIgnore]
|
||||
public bool IsPhantomBTC { get; set; }
|
||||
|
||||
public CryptoDataAccounting Calculate()
|
||||
public PaymentMethodAccounting Calculate(Func<PaymentEntity, bool> paymentPredicate = null)
|
||||
{
|
||||
var cryptoData = ParentEntity.GetCryptoData(null, IsPhantomBTC);
|
||||
var totalDue = Money.Coins(ParentEntity.ProductInformation.Price / Rate);
|
||||
var paid = Money.Zero;
|
||||
var cryptoPaid = Money.Zero;
|
||||
paymentPredicate = paymentPredicate ?? new Func<PaymentEntity, bool>((p) => true);
|
||||
var paymentMethods = ParentEntity.GetPaymentMethods(null, IsPhantomBTC);
|
||||
|
||||
var paidTxFee = Money.Zero;
|
||||
bool paidEnough = totalDue <= paid;
|
||||
var totalDue = ParentEntity.ProductInformation.Price / Rate;
|
||||
var paid = 0m;
|
||||
var cryptoPaid = 0.0m;
|
||||
|
||||
var paidTxFee = 0m;
|
||||
bool paidEnough = paid >= RoundUp(totalDue, 8);
|
||||
int txCount = 0;
|
||||
var payments =
|
||||
ParentEntity.GetPayments()
|
||||
.Where(p => p.Accounted)
|
||||
.Where(p => p.Accounted && paymentPredicate(p))
|
||||
.OrderBy(p => p.ReceivedTime)
|
||||
.Select(_ =>
|
||||
{
|
||||
var txFee = _.GetValue(cryptoData, CryptoCode, cryptoData[_.GetCryptoCode()].TxFee);
|
||||
paid += _.GetValue(cryptoData, CryptoCode);
|
||||
var txFee = _.GetValue(paymentMethods, GetId(), paymentMethods[_.GetpaymentMethodId()].GetTxFee());
|
||||
paid += _.GetValue(paymentMethods, GetId());
|
||||
if (!paidEnough)
|
||||
{
|
||||
totalDue += txFee;
|
||||
paidTxFee += txFee;
|
||||
}
|
||||
paidEnough |= totalDue <= paid;
|
||||
if (CryptoCode == _.GetCryptoCode())
|
||||
paidEnough |= paid >= RoundUp(totalDue, 8);
|
||||
if (GetId() == _.GetpaymentMethodId())
|
||||
{
|
||||
cryptoPaid += _.GetValue();
|
||||
cryptoPaid += _.GetCryptoPaymentData().GetValue();
|
||||
txCount++;
|
||||
}
|
||||
return _;
|
||||
@ -583,19 +734,41 @@ namespace BTCPayServer.Services.Invoices
|
||||
if (!paidEnough)
|
||||
{
|
||||
txCount++;
|
||||
totalDue += TxFee;
|
||||
paidTxFee += TxFee;
|
||||
totalDue += GetTxFee();
|
||||
paidTxFee += GetTxFee();
|
||||
}
|
||||
var accounting = new CryptoDataAccounting();
|
||||
accounting.TotalDue = totalDue;
|
||||
accounting.Paid = paid;
|
||||
var accounting = new PaymentMethodAccounting();
|
||||
accounting.TotalDue = Money.Coins(RoundUp(totalDue, 8));
|
||||
accounting.Paid = Money.Coins(paid);
|
||||
accounting.TxCount = txCount;
|
||||
accounting.CryptoPaid = cryptoPaid;
|
||||
accounting.CryptoPaid = Money.Coins(cryptoPaid);
|
||||
accounting.Due = Money.Max(accounting.TotalDue - accounting.Paid, Money.Zero);
|
||||
accounting.NetworkFee = paidTxFee;
|
||||
accounting.DueUncapped = accounting.TotalDue - accounting.Paid;
|
||||
accounting.NetworkFee = Money.Coins(paidTxFee);
|
||||
return accounting;
|
||||
}
|
||||
|
||||
private static decimal RoundUp(decimal value, int precision)
|
||||
{
|
||||
for (int i = 0; i < precision; i++)
|
||||
{
|
||||
value = value * 10m;
|
||||
}
|
||||
value = Math.Ceiling(value);
|
||||
for (int i = 0; i < precision; i++)
|
||||
{
|
||||
value = value / 10m;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private decimal GetTxFee()
|
||||
{
|
||||
var method = GetPaymentMethodDetails();
|
||||
if (method == null)
|
||||
return 0.0m;
|
||||
return method.GetTxFee();
|
||||
}
|
||||
}
|
||||
|
||||
public class PaymentEntity
|
||||
@ -604,30 +777,26 @@ namespace BTCPayServer.Services.Invoices
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
|
||||
[Obsolete("Use ((BitcoinLikePaymentData)GetCryptoPaymentData()).Outpoint")]
|
||||
public OutPoint Outpoint
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
|
||||
[Obsolete("Use GetValue() or GetScriptPubKey() instead")]
|
||||
[Obsolete("Use ((BitcoinLikePaymentData)GetCryptoPaymentData()).Output")]
|
||||
public TxOut Output
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
|
||||
public Script GetScriptPubKey()
|
||||
{
|
||||
#pragma warning disable CS0618
|
||||
return Output.ScriptPubKey;
|
||||
#pragma warning restore CS0618
|
||||
}
|
||||
|
||||
public bool Accounted
|
||||
{
|
||||
get; set;
|
||||
}
|
||||
|
||||
[Obsolete("Use GetCryptoCode() instead")]
|
||||
|
||||
[Obsolete("Use GetpaymentMethodId().CryptoCode instead")]
|
||||
public string CryptoCode
|
||||
{
|
||||
get;
|
||||
@ -636,59 +805,76 @@ namespace BTCPayServer.Services.Invoices
|
||||
|
||||
[Obsolete("Use GetCryptoPaymentData() instead")]
|
||||
public string CryptoPaymentData { get; set; }
|
||||
[Obsolete("Use GetCryptoPaymentData() instead")]
|
||||
[Obsolete("Use GetpaymentMethodId().PaymentType instead")]
|
||||
public string CryptoPaymentDataType { get; set; }
|
||||
|
||||
|
||||
public CryptoPaymentData GetCryptoPaymentData()
|
||||
{
|
||||
#pragma warning disable CS0618
|
||||
if (string.IsNullOrEmpty(CryptoPaymentDataType))
|
||||
{
|
||||
return NullPaymentData.Instance;
|
||||
// In case this is a payment done before this update, consider it unconfirmed with RBF for safety
|
||||
var paymentData = new Payments.Bitcoin.BitcoinLikePaymentData();
|
||||
paymentData.Outpoint = Outpoint;
|
||||
paymentData.Output = Output;
|
||||
paymentData.RBF = true;
|
||||
paymentData.ConfirmationCount = 0;
|
||||
paymentData.Legacy = true;
|
||||
return paymentData;
|
||||
}
|
||||
if (CryptoPaymentDataType == "BTCLike")
|
||||
if (GetpaymentMethodId().PaymentType == PaymentTypes.BTCLike)
|
||||
{
|
||||
return JsonConvert.DeserializeObject<BitcoinLikePaymentData>(CryptoPaymentData);
|
||||
var paymentData = JsonConvert.DeserializeObject<Payments.Bitcoin.BitcoinLikePaymentData>(CryptoPaymentData);
|
||||
// legacy
|
||||
paymentData.Output = Output;
|
||||
paymentData.Outpoint = Outpoint;
|
||||
return paymentData;
|
||||
}
|
||||
else
|
||||
return NullPaymentData.Instance;
|
||||
|
||||
throw new NotSupportedException(nameof(CryptoPaymentDataType) + " does not support " + CryptoPaymentDataType);
|
||||
#pragma warning restore CS0618
|
||||
}
|
||||
|
||||
public void SetCryptoPaymentData(CryptoPaymentData cryptoPaymentData)
|
||||
public PaymentEntity SetCryptoPaymentData(CryptoPaymentData cryptoPaymentData)
|
||||
{
|
||||
#pragma warning disable CS0618
|
||||
if (cryptoPaymentData is BitcoinLikePaymentData)
|
||||
if (cryptoPaymentData is Payments.Bitcoin.BitcoinLikePaymentData paymentData)
|
||||
{
|
||||
CryptoPaymentDataType = "BTCLike";
|
||||
// Legacy
|
||||
Outpoint = paymentData.Outpoint;
|
||||
Output = paymentData.Output;
|
||||
///
|
||||
}
|
||||
else
|
||||
throw new NotSupportedException(cryptoPaymentData.ToString());
|
||||
CryptoPaymentDataType = paymentData.GetPaymentType().ToString();
|
||||
CryptoPaymentData = JsonConvert.SerializeObject(cryptoPaymentData);
|
||||
#pragma warning restore CS0618
|
||||
return this;
|
||||
}
|
||||
|
||||
public Money GetValue()
|
||||
internal decimal GetValue(PaymentMethodDictionary paymentMethods, PaymentMethodId paymentMethodId, decimal? value = null)
|
||||
{
|
||||
#pragma warning disable CS0618
|
||||
return Output.Value;
|
||||
value = value ?? Output.Value.ToDecimal(MoneyUnit.BTC);
|
||||
#pragma warning restore CS0618
|
||||
}
|
||||
public Money GetValue(Dictionary<string, CryptoData> cryptoData, string cryptoCode, Money value = null)
|
||||
{
|
||||
#pragma warning disable CS0618
|
||||
value = value ?? Output.Value;
|
||||
#pragma warning restore CS0618
|
||||
var to = cryptoCode;
|
||||
var from = GetCryptoCode();
|
||||
var to = paymentMethodId;
|
||||
var from = this.GetpaymentMethodId();
|
||||
if (to == from)
|
||||
return value;
|
||||
var fromRate = cryptoData[from].Rate;
|
||||
var toRate = cryptoData[to].Rate;
|
||||
return decimal.Round(value.Value, 8);
|
||||
var fromRate = paymentMethods[from].Rate;
|
||||
var toRate = paymentMethods[to].Rate;
|
||||
|
||||
var fiatValue = fromRate * value.ToDecimal(MoneyUnit.BTC);
|
||||
var fiatValue = fromRate * decimal.Round(value.Value, 8);
|
||||
var otherCurrencyValue = toRate == 0 ? 0.0m : fiatValue / toRate;
|
||||
return Money.Coins(otherCurrencyValue);
|
||||
return otherCurrencyValue;
|
||||
}
|
||||
|
||||
public PaymentMethodId GetpaymentMethodId()
|
||||
{
|
||||
#pragma warning disable CS0618 // Type or member is obsolete
|
||||
return new PaymentMethodId(CryptoCode ?? "BTC", string.IsNullOrEmpty(CryptoPaymentDataType) ? PaymentTypes.BTCLike : Enum.Parse<PaymentTypes>(CryptoPaymentDataType));
|
||||
#pragma warning restore CS0618 // Type or member is obsolete
|
||||
}
|
||||
|
||||
public string GetCryptoCode()
|
||||
@ -701,58 +887,24 @@ namespace BTCPayServer.Services.Invoices
|
||||
|
||||
public interface CryptoPaymentData
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns an identifier which uniquely identify the payment
|
||||
/// </summary>
|
||||
/// <returns>The payment id</returns>
|
||||
string GetPaymentId();
|
||||
|
||||
/// <summary>
|
||||
/// Returns terms which will be indexed and searchable in the search bar of invoice
|
||||
/// </summary>
|
||||
/// <returns>The search terms</returns>
|
||||
string[] GetSearchTerms();
|
||||
/// <summary>
|
||||
/// Get value of what as been paid
|
||||
/// </summary>
|
||||
/// <returns>The amount paid</returns>
|
||||
decimal GetValue();
|
||||
bool PaymentCompleted(PaymentEntity entity, BTCPayNetwork network);
|
||||
bool PaymentConfirmed(PaymentEntity entity, SpeedPolicy speedPolicy, BTCPayNetwork network);
|
||||
|
||||
}
|
||||
|
||||
public class NullPaymentData : CryptoPaymentData
|
||||
{
|
||||
|
||||
private static readonly NullPaymentData _Instance = new NullPaymentData();
|
||||
public static NullPaymentData Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
return _Instance;
|
||||
}
|
||||
}
|
||||
public bool PaymentCompleted(PaymentEntity entity, BTCPayNetwork network)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool PaymentConfirmed(PaymentEntity entity, SpeedPolicy speedPolicy, BTCPayNetwork network)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public class BitcoinLikePaymentData : CryptoPaymentData
|
||||
{
|
||||
public int ConfirmationCount { get; set; }
|
||||
public bool RBF { get; set; }
|
||||
|
||||
public bool PaymentCompleted(PaymentEntity entity, BTCPayNetwork network)
|
||||
{
|
||||
return ConfirmationCount >= 6;
|
||||
}
|
||||
|
||||
public bool PaymentConfirmed(PaymentEntity entity, SpeedPolicy speedPolicy, BTCPayNetwork network)
|
||||
{
|
||||
if (speedPolicy == SpeedPolicy.HighSpeed)
|
||||
{
|
||||
return ConfirmationCount >= 1 || !RBF;
|
||||
}
|
||||
else if (speedPolicy == SpeedPolicy.MediumSpeed)
|
||||
{
|
||||
return ConfirmationCount >= 1;
|
||||
}
|
||||
else if (speedPolicy == SpeedPolicy.LowSpeed)
|
||||
{
|
||||
return ConfirmationCount >= 6;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -18,6 +18,7 @@ using BTCPayServer.Data;
|
||||
using System.Globalization;
|
||||
using BTCPayServer.Models.InvoicingModels;
|
||||
using BTCPayServer.Logging;
|
||||
using BTCPayServer.Payments;
|
||||
|
||||
namespace BTCPayServer.Services.Invoices
|
||||
{
|
||||
@ -123,22 +124,26 @@ namespace BTCPayServer.Services.Invoices
|
||||
CustomerEmail = invoice.RefundMail
|
||||
});
|
||||
|
||||
foreach (var cryptoData in invoice.GetCryptoData(networkProvider).Values)
|
||||
foreach (var paymentMethod in invoice.GetPaymentMethods(networkProvider))
|
||||
{
|
||||
if (cryptoData.Network == null)
|
||||
if (paymentMethod.Network == null)
|
||||
throw new InvalidOperationException("CryptoCode unsupported");
|
||||
var paymentDestination = paymentMethod.GetPaymentMethodDetails().GetPaymentDestination();
|
||||
|
||||
string address = GetDestination(paymentMethod);
|
||||
context.AddressInvoices.Add(new AddressInvoiceData()
|
||||
{
|
||||
InvoiceDataId = invoice.Id,
|
||||
CreatedTime = DateTimeOffset.UtcNow,
|
||||
}.SetHash(cryptoData.GetDepositAddress().ScriptPubKey.Hash, cryptoData.CryptoCode));
|
||||
}.Set(address, paymentMethod.GetId()));
|
||||
|
||||
context.HistoricalAddressInvoices.Add(new HistoricalAddressInvoiceData()
|
||||
{
|
||||
InvoiceDataId = invoice.Id,
|
||||
Assigned = DateTimeOffset.UtcNow
|
||||
}.SetAddress(cryptoData.DepositAddress, cryptoData.CryptoCode));
|
||||
textSearch.Add(cryptoData.DepositAddress);
|
||||
textSearch.Add(cryptoData.Calculate().TotalDue.ToString());
|
||||
}.SetAddress(paymentDestination, paymentMethod.GetId().ToString()));
|
||||
textSearch.Add(paymentDestination);
|
||||
textSearch.Add(paymentMethod.Calculate().TotalDue.ToString());
|
||||
}
|
||||
context.PendingInvoices.Add(new PendingInvoiceData() { Id = invoice.Id });
|
||||
await context.SaveChangesAsync().ConfigureAwait(false);
|
||||
@ -157,7 +162,18 @@ namespace BTCPayServer.Services.Invoices
|
||||
return invoice;
|
||||
}
|
||||
|
||||
public async Task<bool> NewAddress(string invoiceId, BitcoinAddress bitcoinAddress, BTCPayNetwork network)
|
||||
private static string GetDestination(PaymentMethod paymentMethod)
|
||||
{
|
||||
// For legacy reason, BitcoinLikeOnChain is putting the hashes of addresses in database
|
||||
if (paymentMethod.GetId().PaymentType == Payments.PaymentTypes.BTCLike)
|
||||
{
|
||||
return ((Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod)paymentMethod.GetPaymentMethodDetails()).DepositAddress.ScriptPubKey.Hash.ToString();
|
||||
}
|
||||
///////////////
|
||||
return paymentMethod.GetPaymentMethodDetails().GetPaymentDestination();
|
||||
}
|
||||
|
||||
public async Task<bool> NewAddress(string invoiceId, IPaymentMethodDetails paymentMethod, BTCPayNetwork network)
|
||||
{
|
||||
using (var context = _ContextFactory.CreateContext())
|
||||
{
|
||||
@ -166,24 +182,26 @@ namespace BTCPayServer.Services.Invoices
|
||||
return false;
|
||||
|
||||
var invoiceEntity = ToObject<InvoiceEntity>(invoice.Blob, network.NBitcoinNetwork);
|
||||
var currencyData = invoiceEntity.GetCryptoData(network, null);
|
||||
var currencyData = invoiceEntity.GetPaymentMethod(network, paymentMethod.GetPaymentType(), null);
|
||||
if (currencyData == null)
|
||||
return false;
|
||||
|
||||
if (currencyData.DepositAddress != null)
|
||||
var existingPaymentMethod = currencyData.GetPaymentMethodDetails();
|
||||
if (existingPaymentMethod.GetPaymentDestination() != null)
|
||||
{
|
||||
MarkUnassigned(invoiceId, invoiceEntity, context, network.CryptoCode);
|
||||
MarkUnassigned(invoiceId, invoiceEntity, context, currencyData.GetId());
|
||||
}
|
||||
|
||||
currencyData.DepositAddress = bitcoinAddress.ToString();
|
||||
existingPaymentMethod.SetPaymentDestination(paymentMethod.GetPaymentDestination());
|
||||
|
||||
currencyData.SetPaymentMethodDetails(existingPaymentMethod);
|
||||
#pragma warning disable CS0618
|
||||
if (network.IsBTC)
|
||||
{
|
||||
invoiceEntity.DepositAddress = currencyData.DepositAddress;
|
||||
}
|
||||
#pragma warning restore CS0618
|
||||
invoiceEntity.SetCryptoData(currencyData);
|
||||
invoiceEntity.SetPaymentMethod(currencyData);
|
||||
invoice.Blob = ToBytes(invoiceEntity, network.NBitcoinNetwork);
|
||||
|
||||
context.AddressInvoices.Add(new AddressInvoiceData()
|
||||
@ -191,15 +209,15 @@ namespace BTCPayServer.Services.Invoices
|
||||
InvoiceDataId = invoiceId,
|
||||
CreatedTime = DateTimeOffset.UtcNow
|
||||
}
|
||||
.SetHash(bitcoinAddress.ScriptPubKey.Hash, network.CryptoCode));
|
||||
.Set(GetDestination(currencyData), currencyData.GetId()));
|
||||
context.HistoricalAddressInvoices.Add(new HistoricalAddressInvoiceData()
|
||||
{
|
||||
InvoiceDataId = invoiceId,
|
||||
Assigned = DateTimeOffset.UtcNow
|
||||
}.SetAddress(bitcoinAddress.ToString(), network.CryptoCode));
|
||||
}.SetAddress(paymentMethod.GetPaymentDestination(), network.CryptoCode));
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
AddToTextSearch(invoice.Id, bitcoinAddress.ToString());
|
||||
AddToTextSearch(invoice.Id, paymentMethod.GetPaymentDestination());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -219,15 +237,15 @@ namespace BTCPayServer.Services.Invoices
|
||||
}
|
||||
}
|
||||
|
||||
private static void MarkUnassigned(string invoiceId, InvoiceEntity entity, ApplicationDbContext context, string cryptoCode)
|
||||
private static void MarkUnassigned(string invoiceId, InvoiceEntity entity, ApplicationDbContext context, PaymentMethodId paymentMethodId)
|
||||
{
|
||||
foreach (var address in entity.GetCryptoData(null))
|
||||
foreach (var address in entity.GetPaymentMethods(null))
|
||||
{
|
||||
if (cryptoCode != null && cryptoCode != address.Value.CryptoCode)
|
||||
if (paymentMethodId != null && paymentMethodId != address.GetId())
|
||||
continue;
|
||||
var historical = new HistoricalAddressInvoiceData();
|
||||
historical.InvoiceDataId = invoiceId;
|
||||
historical.SetAddress(address.Value.DepositAddress, address.Value.CryptoCode);
|
||||
historical.SetAddress(address.GetPaymentMethodDetails().GetPaymentDestination(), address.GetId().ToString());
|
||||
historical.UnAssigned = DateTimeOffset.UtcNow;
|
||||
context.Attach(historical);
|
||||
context.Entry(historical).Property(o => o.UnAssigned).IsModified = true;
|
||||
@ -343,7 +361,7 @@ namespace BTCPayServer.Services.Invoices
|
||||
}
|
||||
if (invoice.AddressInvoices != null)
|
||||
{
|
||||
entity.AvailableAddressHashes = invoice.AddressInvoices.Select(a => a.GetHash() + a.GetCryptoCode()).ToHashSet();
|
||||
entity.AvailableAddressHashes = invoice.AddressInvoices.Select(a => a.GetAddress() + a.GetpaymentMethodId().ToString()).ToHashSet();
|
||||
}
|
||||
if(invoice.Events != null)
|
||||
{
|
||||
@ -384,7 +402,7 @@ namespace BTCPayServer.Services.Invoices
|
||||
{
|
||||
var ids = new HashSet<string>(SearchInvoice(queryObject.TextSearch));
|
||||
if (ids.Count == 0)
|
||||
return new InvoiceEntity[0];
|
||||
return Array.Empty<InvoiceEntity>();
|
||||
query = query.Where(i => ids.Contains(i.Id));
|
||||
}
|
||||
|
||||
@ -443,24 +461,24 @@ namespace BTCPayServer.Services.Invoices
|
||||
AddToTextSearch(invoiceId, addresses.Select(a => a.ToString()).ToArray());
|
||||
}
|
||||
|
||||
public async Task<PaymentEntity> AddPayment(string invoiceId, DateTimeOffset date, Coin receivedCoin, string cryptoCode)
|
||||
public async Task<PaymentEntity> AddPayment(string invoiceId, DateTimeOffset date, CryptoPaymentData paymentData, string cryptoCode)
|
||||
{
|
||||
using (var context = _ContextFactory.CreateContext())
|
||||
{
|
||||
PaymentEntity entity = new PaymentEntity
|
||||
{
|
||||
Outpoint = receivedCoin.Outpoint,
|
||||
#pragma warning disable CS0618
|
||||
Output = receivedCoin.TxOut,
|
||||
CryptoCode = cryptoCode,
|
||||
#pragma warning restore CS0618
|
||||
ReceivedTime = date.UtcDateTime,
|
||||
Accounted = false
|
||||
};
|
||||
entity.SetCryptoPaymentData(new BitcoinLikePaymentData());
|
||||
entity.SetCryptoPaymentData(paymentData);
|
||||
|
||||
|
||||
PaymentData data = new PaymentData
|
||||
{
|
||||
Id = receivedCoin.Outpoint.ToString(),
|
||||
Id = paymentData.GetPaymentId(),
|
||||
Blob = ToBytes(entity, null),
|
||||
InvoiceDataId = invoiceId,
|
||||
Accounted = false
|
||||
@ -469,7 +487,7 @@ namespace BTCPayServer.Services.Invoices
|
||||
context.Payments.Add(data);
|
||||
|
||||
await context.SaveChangesAsync().ConfigureAwait(false);
|
||||
AddToTextSearch(invoiceId, receivedCoin.Outpoint.Hash.ToString());
|
||||
AddToTextSearch(invoiceId, paymentData.GetSearchTerms());
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
@ -482,8 +500,9 @@ namespace BTCPayServer.Services.Invoices
|
||||
{
|
||||
foreach (var payment in payments)
|
||||
{
|
||||
var paymentData = payment.GetCryptoPaymentData();
|
||||
var data = new PaymentData();
|
||||
data.Id = payment.Outpoint.ToString();
|
||||
data.Id = paymentData.GetPaymentId();
|
||||
data.Accounted = payment.Accounted;
|
||||
data.Blob = ToBytes(payment, null);
|
||||
context.Attach(data);
|
||||
|
@ -16,11 +16,6 @@ using System.Collections.Concurrent;
|
||||
|
||||
namespace BTCPayServer.Services.Wallets
|
||||
{
|
||||
public class KnownState
|
||||
{
|
||||
public UTXOChanges PreviousCall { get; set; }
|
||||
}
|
||||
|
||||
public class ReceivedCoin
|
||||
{
|
||||
public Coin Coin { get; set; }
|
||||
|
@ -613,7 +613,7 @@
|
||||
<div style="text-align:center">
|
||||
@foreach(var crypto in Model.AvailableCryptos)
|
||||
{
|
||||
<a style="text-decoration:none;" href="@crypto.Link" onclick="srvModel.cryptoCode='@crypto.CryptoCode'; fetchStatus(); return false;"><img style="height:32px; margin-right:5px; margin-left:5px;" alt="@crypto.CryptoCode" src="@crypto.CryptoImage" /></a>
|
||||
<a style="text-decoration:none;" href="@crypto.Link" onclick="srvModel.paymentMethodId='@crypto.PaymentMethodId'; fetchStatus(); return false;"><img style="height:32px; margin-right:5px; margin-left:5px;" alt="@crypto.PaymentMethodId" src="@crypto.CryptoImage" /></a>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
@ -198,7 +198,7 @@ function onDataCallback(jsonData) {
|
||||
}
|
||||
|
||||
function fetchStatus() {
|
||||
var path = srvModel.serverUrl + "/i/" + srvModel.invoiceId + "/" + srvModel.cryptoCode + "/status";
|
||||
var path = srvModel.serverUrl + "/i/" + srvModel.invoiceId + "/" + srvModel.paymentMethodId + "/status";
|
||||
$.ajax({
|
||||
url: path,
|
||||
type: "GET"
|
||||
|
Reference in New Issue
Block a user