Compare commits
11 Commits
Author | SHA1 | Date | |
---|---|---|---|
5efac45d46 | |||
c7dce280d7 | |||
04c6107196 | |||
54ce9b5dab | |||
cee955fb9d | |||
2e4b0daa48 | |||
e85ccfb47e | |||
75099b99d4 | |||
7b1b2a0f68 | |||
203c28df3d | |||
2e2c3cdec4 |
@ -46,7 +46,7 @@ services:
|
||||
- lightning-charged
|
||||
|
||||
nbxplorer:
|
||||
image: nicolasdorier/nbxplorer:1.0.1.32
|
||||
image: nicolasdorier/nbxplorer:1.0.1.34
|
||||
ports:
|
||||
- "32838:32838"
|
||||
expose:
|
||||
|
@ -50,7 +50,7 @@ namespace BTCPayServer
|
||||
public string CryptoCode { get; internal set; }
|
||||
public string BlockExplorerLink { get; internal set; }
|
||||
public string UriScheme { get; internal set; }
|
||||
public IRateProvider DefaultRateProvider { get; set; }
|
||||
public RateProviderDescription DefaultRateProvider { get; set; }
|
||||
|
||||
[Obsolete("Should not be needed")]
|
||||
public bool IsBTC
|
||||
|
@ -14,9 +14,9 @@ namespace BTCPayServer
|
||||
public void InitBitcoin()
|
||||
{
|
||||
var nbxplorerNetwork = NBXplorerNetworkProvider.GetFromCryptoCode("BTC");
|
||||
var coinaverage = new CoinAverageRateProvider("BTC");
|
||||
var bitpay = new BitpayRateProvider(new Bitpay(new Key(), new Uri("https://bitpay.com/")));
|
||||
var btcRate = new FallbackRateProvider(new IRateProvider[] { coinaverage, bitpay });
|
||||
var coinaverage = new CoinAverageRateProviderDescription("BTC");
|
||||
var bitpay = new BitpayRateProviderDescription();
|
||||
var btcRate = new FallbackRateProviderDescription(new RateProviderDescription[] { coinaverage, bitpay });
|
||||
Add(new BTCPayNetwork()
|
||||
{
|
||||
CryptoCode = nbxplorerNetwork.CryptoCode,
|
||||
|
@ -13,7 +13,6 @@ namespace BTCPayServer
|
||||
public void InitDogecoin()
|
||||
{
|
||||
NBitcoin.Altcoins.Dogecoin.EnsureRegistered();
|
||||
var ltcRate = new CoinAverageRateProvider("DOGE");
|
||||
|
||||
var nbxplorerNetwork = NBXplorerNetworkProvider.GetFromCryptoCode("DOGE");
|
||||
Add(new BTCPayNetwork()
|
||||
@ -23,7 +22,7 @@ namespace BTCPayServer
|
||||
NBitcoinNetwork = nbxplorerNetwork.NBitcoinNetwork,
|
||||
NBXplorerNetwork = nbxplorerNetwork,
|
||||
UriScheme = "dogecoin",
|
||||
DefaultRateProvider = ltcRate,
|
||||
DefaultRateProvider = new CoinAverageRateProviderDescription("DOGE"),
|
||||
CryptoImagePath = "imlegacy/dogecoin.png",
|
||||
DefaultSettings = BTCPayDefaultSettings.GetDefaultSettings(NBXplorerNetworkProvider.ChainType),
|
||||
CoinType = NBXplorerNetworkProvider.ChainType == ChainType.Main ? new KeyPath("3'") : new KeyPath("1'")
|
||||
|
@ -13,7 +13,6 @@ namespace BTCPayServer
|
||||
public void InitLitecoin()
|
||||
{
|
||||
NBitcoin.Altcoins.Litecoin.EnsureRegistered();
|
||||
var ltcRate = new CoinAverageRateProvider("LTC");
|
||||
|
||||
var nbxplorerNetwork = NBXplorerNetworkProvider.GetFromCryptoCode("LTC");
|
||||
Add(new BTCPayNetwork()
|
||||
@ -23,7 +22,7 @@ namespace BTCPayServer
|
||||
NBitcoinNetwork = nbxplorerNetwork.NBitcoinNetwork,
|
||||
NBXplorerNetwork = nbxplorerNetwork,
|
||||
UriScheme = "litecoin",
|
||||
DefaultRateProvider = ltcRate,
|
||||
DefaultRateProvider = new CoinAverageRateProviderDescription("LTC"),
|
||||
CryptoImagePath = "imlegacy/litecoin-symbol.svg",
|
||||
LightningImagePath = "imlegacy/ltc-lightning.svg",
|
||||
DefaultSettings = BTCPayDefaultSettings.GetDefaultSettings(NBXplorerNetworkProvider.ChainType),
|
||||
|
@ -2,7 +2,7 @@
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp2.0</TargetFramework>
|
||||
<Version>1.0.1.80</Version>
|
||||
<Version>1.0.1.82</Version>
|
||||
<NoWarn>NU1701,CA1816,CA1308,CA1810,CA2208</NoWarn>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
@ -39,10 +39,10 @@
|
||||
<PackageReference Include="Meziantou.AspNetCore.BundleTagHelpers" Version="1.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Filter" Version="1.1.2" />
|
||||
<PackageReference Include="Microsoft.NetCore.Analyzers" Version="2.6.0" />
|
||||
<PackageReference Include="NBitcoin" Version="4.1.0.9" />
|
||||
<PackageReference Include="NBitcoin" Version="4.1.0.11" />
|
||||
<PackageReference Include="NBitpayClient" Version="1.0.0.18" />
|
||||
<PackageReference Include="DBreeze" Version="1.87.0" />
|
||||
<PackageReference Include="NBXplorer.Client" Version="1.0.1.22" />
|
||||
<PackageReference Include="NBXplorer.Client" Version="1.0.1.24" />
|
||||
<PackageReference Include="NicolasDorier.CommandLine" Version="1.0.0.1" />
|
||||
<PackageReference Include="NicolasDorier.CommandLine.Configuration" Version="1.0.0.2" />
|
||||
<PackageReference Include="NicolasDorier.StandardConfiguration" Version="1.0.0.13" />
|
||||
|
@ -238,7 +238,8 @@ namespace BTCPayServer.Controllers
|
||||
BtcPaid = accounting.Paid.ToString(),
|
||||
Status = invoice.Status,
|
||||
CryptoImage = "/" + GetImage(paymentMethodId, network),
|
||||
NetworkFeeDescription = $"{accounting.TxRequired} transaction{(accounting.TxRequired > 1 ? "s" : "")} x {paymentMethodDetails.GetTxFee()} {network.CryptoCode}",
|
||||
NetworkFee = paymentMethodDetails.GetTxFee(),
|
||||
IsMultiCurrency = invoice.GetPayments().Select(p => p.GetPaymentMethodId()).Concat(new[] { paymentMethod.GetId() }).Distinct().Count() > 1,
|
||||
AllowCoinConversion = storeBlob.AllowCoinConversion,
|
||||
AvailableCryptos = invoice.GetPaymentMethods(_NetworkProvider)
|
||||
.Where(i => i.Network != null)
|
||||
@ -251,10 +252,6 @@ namespace BTCPayServer.Controllers
|
||||
.ToList()
|
||||
};
|
||||
|
||||
var isMultiCurrency = invoice.GetPayments().Select(p => p.GetPaymentMethodId()).Concat(new[] { paymentMethod.GetId() }).Distinct().Count() > 1;
|
||||
if (isMultiCurrency)
|
||||
model.NetworkFeeDescription = $"{accounting.NetworkFee} {network.CryptoCode}";
|
||||
|
||||
var expiration = TimeSpan.FromSeconds(model.ExpirationSeconds);
|
||||
model.TimeLeft = PrettyPrint(expiration);
|
||||
return model;
|
||||
|
@ -165,7 +165,7 @@ namespace BTCPayServer.Controllers
|
||||
{
|
||||
var btc = _NetworkProvider.BTC;
|
||||
var feeProvider = ((IFeeProviderFactory)_ServiceProvider.GetService(typeof(IFeeProviderFactory))).CreateFeeProvider(btc);
|
||||
var rateProvider = storeBlob.ApplyRateRules(btc, _RateProviders.GetRateProvider(btc, false));
|
||||
var rateProvider = storeBlob.ApplyRateRules(btc, _RateProviders.GetRateProvider(btc));
|
||||
if (feeProvider != null && rateProvider != null)
|
||||
{
|
||||
var gettingFee = feeProvider.GetFeeRateAsync();
|
||||
@ -186,7 +186,7 @@ namespace BTCPayServer.Controllers
|
||||
private async Task<PaymentMethod> CreatePaymentMethodAsync(IPaymentMethodHandler handler, ISupportedPaymentMethod supportedPaymentMethod, BTCPayNetwork network, InvoiceEntity entity, StoreData store)
|
||||
{
|
||||
var storeBlob = store.GetStoreBlob();
|
||||
var rate = await storeBlob.ApplyRateRules(network, _RateProviders.GetRateProvider(network, false)).GetRateAsync(entity.ProductInformation.Currency);
|
||||
var rate = await storeBlob.ApplyRateRules(network, _RateProviders.GetRateProvider(network)).GetRateAsync(entity.ProductInformation.Currency);
|
||||
PaymentMethod paymentMethod = new PaymentMethod();
|
||||
paymentMethod.ParentEntity = entity;
|
||||
paymentMethod.Network = network;
|
||||
@ -221,7 +221,7 @@ namespace BTCPayServer.Controllers
|
||||
if (limitValue.Currency == entity.ProductInformation.Currency)
|
||||
limitValueRate = paymentMethod.Rate;
|
||||
else
|
||||
limitValueRate = await storeBlob.ApplyRateRules(network, _RateProviders.GetRateProvider(network, false)).GetRateAsync(limitValue.Currency);
|
||||
limitValueRate = await storeBlob.ApplyRateRules(network, _RateProviders.GetRateProvider(network)).GetRateAsync(limitValue.Currency);
|
||||
|
||||
var limitValueCrypto = Money.Coins(limitValue.Value / limitValueRate);
|
||||
if (compare(paymentMethod.Calculate().Due, limitValueCrypto))
|
||||
|
@ -49,7 +49,7 @@ namespace BTCPayServer.Controllers
|
||||
var network = _NetworkProvider.GetNetwork(cryptoCode);
|
||||
if (network == null)
|
||||
return NotFound();
|
||||
var rateProvider = _RateProviderFactory.GetRateProvider(network, true);
|
||||
var rateProvider = _RateProviderFactory.GetRateProvider(network);
|
||||
if (rateProvider == null)
|
||||
return NotFound();
|
||||
|
||||
|
@ -2,6 +2,7 @@
|
||||
using BTCPayServer.Models.ServerViewModels;
|
||||
using BTCPayServer.Services;
|
||||
using BTCPayServer.Services.Mails;
|
||||
using BTCPayServer.Services.Rates;
|
||||
using BTCPayServer.Validations;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
@ -11,6 +12,7 @@ using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Mail;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@ -21,11 +23,72 @@ namespace BTCPayServer.Controllers
|
||||
{
|
||||
private UserManager<ApplicationUser> _UserManager;
|
||||
SettingsRepository _SettingsRepository;
|
||||
private IRateProviderFactory _RateProviderFactory;
|
||||
|
||||
public ServerController(UserManager<ApplicationUser> userManager, SettingsRepository settingsRepository)
|
||||
public ServerController(UserManager<ApplicationUser> userManager,
|
||||
IRateProviderFactory rateProviderFactory,
|
||||
SettingsRepository settingsRepository)
|
||||
{
|
||||
_UserManager = userManager;
|
||||
_SettingsRepository = settingsRepository;
|
||||
_RateProviderFactory = rateProviderFactory;
|
||||
}
|
||||
|
||||
[Route("server/rates")]
|
||||
public async Task<IActionResult> Rates()
|
||||
{
|
||||
var rates = (await _SettingsRepository.GetSettingAsync<RatesSetting>()) ?? new RatesSetting();
|
||||
return View(new RatesViewModel()
|
||||
{
|
||||
CacheMinutes = rates.CacheInMinutes,
|
||||
PrivateKey = rates.PrivateKey,
|
||||
PublicKey = rates.PublicKey
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
class TestCoinAverageAuthenticator : ICoinAverageAuthenticator
|
||||
{
|
||||
private RatesSetting settings;
|
||||
|
||||
public TestCoinAverageAuthenticator(RatesSetting settings)
|
||||
{
|
||||
this.settings = settings;
|
||||
}
|
||||
public Task AddHeader(HttpRequestMessage message)
|
||||
{
|
||||
var sig = settings.GetCoinAverageSignature();
|
||||
if (sig != null)
|
||||
message.Headers.Add("X-signature", settings.GetCoinAverageSignature());
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
[Route("server/rates")]
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Rates(RatesViewModel vm)
|
||||
{
|
||||
var rates = (await _SettingsRepository.GetSettingAsync<RatesSetting>()) ?? new RatesSetting();
|
||||
rates.PrivateKey = vm.PrivateKey;
|
||||
rates.PublicKey = vm.PublicKey;
|
||||
rates.CacheInMinutes = vm.CacheMinutes;
|
||||
try
|
||||
{
|
||||
if (rates.GetCoinAverageSignature() != null)
|
||||
{
|
||||
await new CoinAverageRateProvider("BTC")
|
||||
{ Authenticator = new TestCoinAverageAuthenticator(rates) }.TestAuthAsync();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
ModelState.AddModelError(nameof(vm.PrivateKey), "Invalid API key pair");
|
||||
}
|
||||
if (!ModelState.IsValid)
|
||||
return View(vm);
|
||||
await _SettingsRepository.UpdateSetting(rates);
|
||||
((BTCPayRateProviderFactory)_RateProviderFactory).CacheSpan = TimeSpan.FromMinutes(vm.CacheMinutes);
|
||||
StatusMessage = "Rate settings successfully updated";
|
||||
return RedirectToAction(nameof(Rates));
|
||||
}
|
||||
|
||||
[Route("server/users")]
|
||||
@ -72,7 +135,7 @@ namespace BTCPayServer.Controllers
|
||||
var isAdmin = IsAdmin(roles);
|
||||
bool updated = false;
|
||||
|
||||
if(isAdmin != viewModel.IsAdmin)
|
||||
if (isAdmin != viewModel.IsAdmin)
|
||||
{
|
||||
if (viewModel.IsAdmin)
|
||||
await _UserManager.AddToRoleAsync(user, Roles.ServerAdmin);
|
||||
@ -80,7 +143,7 @@ namespace BTCPayServer.Controllers
|
||||
await _UserManager.RemoveFromRoleAsync(user, Roles.ServerAdmin);
|
||||
updated = true;
|
||||
}
|
||||
if(updated)
|
||||
if (updated)
|
||||
{
|
||||
viewModel.StatusMessage = "User successfully updated";
|
||||
}
|
||||
|
32
BTCPayServer/HostedServices/RatesHostedService.cs
Normal file
32
BTCPayServer/HostedServices/RatesHostedService.cs
Normal file
@ -0,0 +1,32 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BTCPayServer.Services;
|
||||
using BTCPayServer.Services.Rates;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace BTCPayServer.HostedServices
|
||||
{
|
||||
public class RatesHostedService : IHostedService
|
||||
{
|
||||
private SettingsRepository _SettingsRepository;
|
||||
private BTCPayRateProviderFactory _RateProviderFactory;
|
||||
public RatesHostedService(SettingsRepository repo, IRateProviderFactory rateProviderFactory)
|
||||
{
|
||||
this._SettingsRepository = repo;
|
||||
_RateProviderFactory = (BTCPayRateProviderFactory)rateProviderFactory;
|
||||
}
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var rates = (await _SettingsRepository.GetSettingAsync<RatesSetting>()) ?? new RatesSetting();
|
||||
_RateProviderFactory.CacheSpan = TimeSpan.FromMinutes(rates.CacheInMinutes);
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
@ -109,6 +109,7 @@ namespace BTCPayServer.Hosting
|
||||
services.AddSingleton<BTCPayServerEnvironment>();
|
||||
services.TryAddSingleton<TokenRepository>();
|
||||
services.TryAddSingleton<EventAggregator>();
|
||||
services.TryAddSingleton<ICoinAverageAuthenticator, BTCPayCoinAverageAuthenticator>();
|
||||
services.TryAddSingleton<ApplicationDbContextFactory>(o =>
|
||||
{
|
||||
var opts = o.GetRequiredService<BTCPayServerOptions>();
|
||||
@ -154,6 +155,7 @@ namespace BTCPayServer.Hosting
|
||||
services.AddSingleton<IHostedService, NBXplorerWaiters>();
|
||||
services.AddSingleton<IHostedService, InvoiceNotificationManager>();
|
||||
services.AddSingleton<IHostedService, InvoiceWatcher>();
|
||||
services.AddSingleton<IHostedService, RatesHostedService>();
|
||||
|
||||
services.TryAddSingleton<ExplorerClientProvider>();
|
||||
services.TryAddSingleton<Bitpay>(o =>
|
||||
@ -163,7 +165,7 @@ namespace BTCPayServer.Hosting
|
||||
else
|
||||
return new Bitpay(new Key(), new Uri("https://test.bitpay.com/"));
|
||||
});
|
||||
services.TryAddSingleton<IRateProviderFactory, CachedDefaultRateProviderFactory>();
|
||||
services.TryAddSingleton<IRateProviderFactory, BTCPayRateProviderFactory>();
|
||||
|
||||
services.TryAddScoped<IHttpContextAccessor, HttpContextAccessor>();
|
||||
services.TryAddSingleton<IAuthorizationHandler, OwnStoreHandler>();
|
||||
|
@ -43,7 +43,8 @@ namespace BTCPayServer.Models.InvoicingModels
|
||||
|
||||
public string OrderId { get; set; }
|
||||
public string CryptoImage { get; set; }
|
||||
public string NetworkFeeDescription { get; internal set; }
|
||||
public decimal NetworkFee { get; set; }
|
||||
public bool IsMultiCurrency { get; set; }
|
||||
public int MaxTimeMinutes { get; internal set; }
|
||||
public string PaymentType { get; internal set; }
|
||||
public string PaymentMethodId { get; internal set; }
|
||||
|
18
BTCPayServer/Models/ServerViewModels/RatesViewModel.cs
Normal file
18
BTCPayServer/Models/ServerViewModels/RatesViewModel.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BTCPayServer.Models.ServerViewModels
|
||||
{
|
||||
public class RatesViewModel
|
||||
{
|
||||
[Display(Name = "Bitcoin average api keys")]
|
||||
public string PublicKey { get; set; }
|
||||
public string PrivateKey { get; set; }
|
||||
[Display(Name = "Cache the rates for ... minutes")]
|
||||
[Range(0, 60)]
|
||||
public int CacheMinutes { get; set; }
|
||||
}
|
||||
}
|
68
BTCPayServer/Services/Rates/BTCPayRateProviderFactory.cs
Normal file
68
BTCPayServer/Services/Rates/BTCPayRateProviderFactory.cs
Normal file
@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace BTCPayServer.Services.Rates
|
||||
{
|
||||
public class BTCPayRateProviderFactory : IRateProviderFactory
|
||||
{
|
||||
IMemoryCache _Cache;
|
||||
private IOptions<MemoryCacheOptions> _CacheOptions;
|
||||
|
||||
public IMemoryCache Cache
|
||||
{
|
||||
get
|
||||
{
|
||||
return _Cache;
|
||||
}
|
||||
}
|
||||
public BTCPayRateProviderFactory(IOptions<MemoryCacheOptions> cacheOptions, IServiceProvider serviceProvider)
|
||||
{
|
||||
if (cacheOptions == null)
|
||||
throw new ArgumentNullException(nameof(cacheOptions));
|
||||
_Cache = new MemoryCache(cacheOptions);
|
||||
_CacheOptions = cacheOptions;
|
||||
// We use 15 min because of limits with free version of bitcoinaverage
|
||||
CacheSpan = TimeSpan.FromMinutes(15.0);
|
||||
this.serviceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
IServiceProvider serviceProvider;
|
||||
TimeSpan _CacheSpan;
|
||||
public TimeSpan CacheSpan
|
||||
{
|
||||
get
|
||||
{
|
||||
return _CacheSpan;
|
||||
}
|
||||
set
|
||||
{
|
||||
_CacheSpan = value;
|
||||
InvalidateCache();
|
||||
}
|
||||
}
|
||||
|
||||
public void InvalidateCache()
|
||||
{
|
||||
_Cache = new MemoryCache(_CacheOptions);
|
||||
}
|
||||
|
||||
public IRateProvider GetRateProvider(BTCPayNetwork network)
|
||||
{
|
||||
return new CachedRateProvider(network.CryptoCode, GetDefaultRateProvider(network), _Cache) { CacheSpan = CacheSpan };
|
||||
}
|
||||
|
||||
private IRateProvider GetDefaultRateProvider(BTCPayNetwork network)
|
||||
{
|
||||
if(network.DefaultRateProvider == null)
|
||||
{
|
||||
throw new RateUnavailableException(network.CryptoCode);
|
||||
}
|
||||
return network.DefaultRateProvider.CreateRateProvider(serviceProvider);
|
||||
}
|
||||
}
|
||||
}
|
@ -4,9 +4,17 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using NBitcoin;
|
||||
|
||||
namespace BTCPayServer.Services.Rates
|
||||
{
|
||||
public class BitpayRateProviderDescription : RateProviderDescription
|
||||
{
|
||||
public IRateProvider CreateRateProvider(IServiceProvider serviceProvider)
|
||||
{
|
||||
return new BitpayRateProvider(new Bitpay(new Key(), new Uri("https://bitpay.com/")));
|
||||
}
|
||||
}
|
||||
public class BitpayRateProvider : IRateProvider
|
||||
{
|
||||
Bitpay _Bitpay;
|
||||
|
@ -1,43 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
|
||||
namespace BTCPayServer.Services.Rates
|
||||
{
|
||||
public class CachedDefaultRateProviderFactory : IRateProviderFactory
|
||||
{
|
||||
IMemoryCache _Cache;
|
||||
ConcurrentDictionary<string, IRateProvider> _Providers = new ConcurrentDictionary<string, IRateProvider>();
|
||||
ConcurrentDictionary<string, IRateProvider> _LongCacheProviders = new ConcurrentDictionary<string, IRateProvider>();
|
||||
|
||||
public IMemoryCache Cache
|
||||
{
|
||||
get
|
||||
{
|
||||
return _Cache;
|
||||
}
|
||||
}
|
||||
|
||||
public CachedDefaultRateProviderFactory(IMemoryCache cache)
|
||||
{
|
||||
if (cache == null)
|
||||
throw new ArgumentNullException(nameof(cache));
|
||||
_Cache = cache;
|
||||
// Using same providers because they are both at 15 min actually...
|
||||
_Providers = _LongCacheProviders;
|
||||
}
|
||||
|
||||
public IRateProvider RateProvider { get; set; }
|
||||
|
||||
// We use 15 min because of limits with free version of bitcoinaverage
|
||||
public TimeSpan CacheSpan { get; set; } = TimeSpan.FromMinutes(15.0);
|
||||
public TimeSpan LongCacheSpan { get; set; } = TimeSpan.FromMinutes(15.0);
|
||||
public IRateProvider GetRateProvider(BTCPayNetwork network, bool longCache)
|
||||
{
|
||||
return (longCache ? _LongCacheProviders : _Providers).GetOrAdd(network.CryptoCode, new CachedRateProvider(network.CryptoCode, RateProvider ?? network.DefaultRateProvider, _Cache) { CacheSpan = longCache ? LongCacheSpan : CacheSpan, AdditionalScope = longCache ? "LONG" : "SHORT" });
|
||||
}
|
||||
}
|
||||
}
|
@ -1,11 +1,15 @@
|
||||
using Newtonsoft.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace BTCPayServer.Services.Rates
|
||||
{
|
||||
@ -16,6 +20,69 @@ namespace BTCPayServer.Services.Rates
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public class CoinAverageRateProviderDescription : RateProviderDescription
|
||||
{
|
||||
public CoinAverageRateProviderDescription(string crypto)
|
||||
{
|
||||
CryptoCode = crypto;
|
||||
}
|
||||
|
||||
public string CryptoCode { get; set; }
|
||||
|
||||
public IRateProvider CreateRateProvider(IServiceProvider serviceProvider)
|
||||
{
|
||||
return new CoinAverageRateProvider(CryptoCode)
|
||||
{
|
||||
Authenticator = serviceProvider.GetService<ICoinAverageAuthenticator>()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public class RatesSetting
|
||||
{
|
||||
private static readonly DateTime _epochUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
public string PublicKey { get; set; }
|
||||
public string PrivateKey { get; set; }
|
||||
[DefaultValue(15)]
|
||||
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
|
||||
public int CacheInMinutes { get; set; } = 15;
|
||||
|
||||
public string GetCoinAverageSignature()
|
||||
{
|
||||
if (string.IsNullOrEmpty(PublicKey) || string.IsNullOrEmpty(PrivateKey))
|
||||
return null;
|
||||
var timestamp = (int)((DateTime.UtcNow - _epochUtc).TotalSeconds);
|
||||
var payload = timestamp + "." + PublicKey;
|
||||
var digestValueBytes = new HMACSHA256(Encoding.ASCII.GetBytes(PrivateKey)).ComputeHash(Encoding.ASCII.GetBytes(payload));
|
||||
var digestValueHex = NBitcoin.DataEncoders.Encoders.Hex.EncodeData(digestValueBytes);
|
||||
return payload + "." + digestValueHex;
|
||||
}
|
||||
}
|
||||
public class BTCPayCoinAverageAuthenticator : ICoinAverageAuthenticator
|
||||
{
|
||||
private SettingsRepository settingsRepo;
|
||||
|
||||
public BTCPayCoinAverageAuthenticator(SettingsRepository settingsRepo)
|
||||
{
|
||||
this.settingsRepo = settingsRepo;
|
||||
}
|
||||
public async Task AddHeader(HttpRequestMessage message)
|
||||
{
|
||||
var settings = (await settingsRepo.GetSettingAsync<RatesSetting>()) ?? new RatesSetting();
|
||||
var signature = settings.GetCoinAverageSignature();
|
||||
if (signature != null)
|
||||
{
|
||||
message.Headers.Add("X-signature", signature);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public interface ICoinAverageAuthenticator
|
||||
{
|
||||
Task AddHeader(HttpRequestMessage message);
|
||||
}
|
||||
|
||||
public class CoinAverageRateProvider : IRateProvider
|
||||
{
|
||||
static HttpClient _Client = new HttpClient();
|
||||
@ -48,17 +115,20 @@ namespace BTCPayServer.Services.Rates
|
||||
throw new RateUnavailableException(currency);
|
||||
}
|
||||
|
||||
public ICoinAverageAuthenticator Authenticator { get; set; }
|
||||
|
||||
private async Task<Dictionary<string, decimal>> GetRatesCore()
|
||||
{
|
||||
HttpResponseMessage resp = null;
|
||||
if (Exchange == null)
|
||||
string url = Exchange == null ? $"https://apiv2.bitcoinaverage.com/indices/{Market}/ticker/short"
|
||||
: $"https://apiv2.bitcoinaverage.com/exchanges/{Exchange}";
|
||||
|
||||
var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
var auth = Authenticator;
|
||||
if (auth != null)
|
||||
{
|
||||
resp = await _Client.GetAsync($"https://apiv2.bitcoinaverage.com/indices/{Market}/ticker/short");
|
||||
}
|
||||
else
|
||||
{
|
||||
resp = await _Client.GetAsync($"https://apiv2.bitcoinaverage.com/exchanges/{Exchange}");
|
||||
await auth.AddHeader(request);
|
||||
}
|
||||
var resp = await _Client.SendAsync(request);
|
||||
using (resp)
|
||||
{
|
||||
|
||||
@ -99,5 +169,17 @@ namespace BTCPayServer.Services.Rates
|
||||
Value = o.Value
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
public async Task TestAuthAsync()
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Get, "https://apiv2.bitcoinaverage.com/blockchain/tx_price/BTCUSD/8a3b4394ba811a9e2b0bbf3cc56888d053ea21909299b2703cdc35e156c860ff");
|
||||
var auth = Authenticator;
|
||||
if (auth != null)
|
||||
{
|
||||
await auth.AddHeader(request);
|
||||
}
|
||||
var resp = await _Client.SendAsync(request);
|
||||
resp.EnsureSuccessStatusCode();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -5,8 +5,24 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace BTCPayServer.Services.Rates
|
||||
{
|
||||
public class FallbackRateProviderDescription : RateProviderDescription
|
||||
{
|
||||
public FallbackRateProviderDescription(RateProviderDescription[] rateProviders)
|
||||
{
|
||||
RateProviders = rateProviders;
|
||||
}
|
||||
|
||||
public RateProviderDescription[] RateProviders { get; set; }
|
||||
|
||||
public IRateProvider CreateRateProvider(IServiceProvider serviceProvider)
|
||||
{
|
||||
return new FallbackRateProvider(RateProviders.Select(r => r.CreateRateProvider(serviceProvider)).ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
public class FallbackRateProvider : IRateProvider
|
||||
{
|
||||
|
||||
IRateProvider[] _Providers;
|
||||
public FallbackRateProvider(IRateProvider[] providers)
|
||||
{
|
||||
|
@ -7,6 +7,6 @@ namespace BTCPayServer.Services.Rates
|
||||
{
|
||||
public interface IRateProviderFactory
|
||||
{
|
||||
IRateProvider GetRateProvider(BTCPayNetwork network, bool longCache);
|
||||
IRateProvider GetRateProvider(BTCPayNetwork network);
|
||||
}
|
||||
}
|
||||
|
@ -18,7 +18,7 @@ namespace BTCPayServer.Services.Rates
|
||||
{
|
||||
_Mocks.Add(mock);
|
||||
}
|
||||
public IRateProvider GetRateProvider(BTCPayNetwork network, bool longCache)
|
||||
public IRateProvider GetRateProvider(BTCPayNetwork network)
|
||||
{
|
||||
return _Mocks.FirstOrDefault(m => m.CryptoCode == network.CryptoCode);
|
||||
}
|
||||
|
12
BTCPayServer/Services/Rates/RateProviderDescription.cs
Normal file
12
BTCPayServer/Services/Rates/RateProviderDescription.cs
Normal file
@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BTCPayServer.Services.Rates
|
||||
{
|
||||
public interface RateProviderDescription
|
||||
{
|
||||
IRateProvider CreateRateProvider(IServiceProvider serviceProvider);
|
||||
}
|
||||
}
|
@ -87,7 +87,14 @@
|
||||
<div class="line-items__item__label">
|
||||
<span>{{$t("Network Cost")}}</span>
|
||||
</div>
|
||||
<div class="line-items__item__value" i18n="">{{srvModel.networkFeeDescription }}</div>
|
||||
<div class="line-items__item__value">
|
||||
<span v-if="srvModel.IsMultiCurrency">
|
||||
{{ srvModel.networkFee }} {{ srvModel.cryptoCode }}
|
||||
</span>
|
||||
<span v-else>
|
||||
{{$t("txCount", {count: srvModel.txCount})}} x {{ srvModel.networkFee }} {{ srvModel.cryptoCode }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="line-items__item">
|
||||
<div class="line-items__item__label">
|
||||
@ -249,11 +256,9 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="success-message">{{$t("This invoice has been paid")}}</div>
|
||||
<button class="action-button">
|
||||
<bp-done-text>
|
||||
<span>{{$t("Return to StoreName", srvModel)}}</span>
|
||||
</bp-done-text>
|
||||
</button>
|
||||
<a class="action-button" :href="srvModel.merchantRefLink" v-show="srvModel.merchantRefLink">
|
||||
<span>{{$t("Return to StoreName", srvModel)}}</span>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="button-wrapper refund-address-form-container" id="refund-overpayment-button">
|
||||
@ -295,10 +300,9 @@
|
||||
{{srvModel.orderId}}
|
||||
</div>
|
||||
</div>
|
||||
<a class="action-button" style="margin-top: 20px;">
|
||||
<bp-done-text>
|
||||
<span>{{$t("Return to StoreName", srvModel)}}</span>
|
||||
</bp-done-text>
|
||||
<a class="action-button" :href="srvModel.merchantRefLink" v-show="srvModel.merchantRefLink"
|
||||
style="margin-top: 20px;">
|
||||
<span>{{$t("Return to StoreName", srvModel)}}</span>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
46
BTCPayServer/Views/Server/Rates.cshtml
Normal file
46
BTCPayServer/Views/Server/Rates.cshtml
Normal file
@ -0,0 +1,46 @@
|
||||
@model RatesViewModel
|
||||
@{
|
||||
ViewData["Title"] = ServerNavPages.Rates;
|
||||
ViewData.AddActivePage(ServerNavPages.Rates);
|
||||
}
|
||||
|
||||
|
||||
<h4>@ViewData["Title"]</h4>
|
||||
@Html.Partial("_StatusMessage", TempData["TempDataProperty-StatusMessage"])
|
||||
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div asp-validation-summary="All" class="text-danger"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-8">
|
||||
<div class="form-group">
|
||||
<h5>Bitcoin Average</h5>
|
||||
<p>BTCPay relies on Bitcoin Average for getting crypto-currency to fiat rates</p>
|
||||
<p>If you want BTCPay rate cache to be smaller than 15min, you should register to BitcoinAverage and get a paid API Key.</p>
|
||||
<p>If your BTCPay server instance supports lot's of merchant or is used a lot, BitcoinAverage will rate limit your server, and invoice will be created using less accurate rates. (From Bitpay)<br /></p>
|
||||
</div>
|
||||
<form method="post">
|
||||
<label asp-for="PublicKey"></label>
|
||||
<div class="form-inline">
|
||||
<input asp-for="PublicKey" style="width:50%;" class="form-control" placeholder="Public key" />
|
||||
<label class="sr-only" asp-for="PrivateKey"></label>
|
||||
<input asp-for="PrivateKey" style="width:50%;" class="form-control" placeholder="Private key" />
|
||||
<span asp-validation-for="PrivateKey" class="text-danger"></span>
|
||||
<p class="form-text text-muted">You can find the information on <a href="https://bitcoinaverage.com/en/apikeys">bitcoinaverage api key page</a></p>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label asp-for="CacheMinutes"></label>
|
||||
<input asp-for="CacheMinutes" class="form-control" />
|
||||
<span asp-validation-for="CacheMinutes" class="text-danger"></span>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary" name="command" value="Save">Save</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@section Scripts {
|
||||
@await Html.PartialAsync("_ValidationScriptsPartial")
|
||||
}
|
@ -14,12 +14,14 @@ namespace BTCPayServer.Views.Server
|
||||
|
||||
|
||||
public static string Users => "Users";
|
||||
public static string Rates => "Rates";
|
||||
public static string Emails => "Email server";
|
||||
public static string Policies => "Policies";
|
||||
public static string Hangfire => "Hangfire";
|
||||
|
||||
public static string UsersNavClass(ViewContext viewContext) => PageNavClass(viewContext, Users);
|
||||
public static string EmailsNavClass(ViewContext viewContext) => PageNavClass(viewContext, Emails);
|
||||
public static string RatesNavClass(ViewContext viewContext) => PageNavClass(viewContext, Rates);
|
||||
public static string PoliciesNavClass(ViewContext viewContext) => PageNavClass(viewContext, Policies);
|
||||
public static string HangfireNavClass(ViewContext viewContext) => PageNavClass(viewContext, Hangfire);
|
||||
|
||||
|
@ -2,6 +2,7 @@
|
||||
|
||||
<div class="nav flex-column nav-pills">
|
||||
<a class="nav-link @ServerNavPages.UsersNavClass(ViewContext)" asp-action="Users">Users</a>
|
||||
<a class="nav-link @ServerNavPages.RatesNavClass(ViewContext)" asp-action="Rates">Rates</a>
|
||||
<a class="nav-link @ServerNavPages.EmailsNavClass(ViewContext)" asp-action="Emails">Email server</a>
|
||||
<a class="nav-link @ServerNavPages.PoliciesNavClass(ViewContext)" asp-action="Policies">Policies</a>
|
||||
<a class="nav-link @ServerNavPages.HangfireNavClass(ViewContext)" href="~/hangfire" target="_blank">Hangfire</a>
|
||||
|
@ -32,15 +32,6 @@ function onDataCallback(jsonData) {
|
||||
$(".modal-dialog").removeClass("expired");
|
||||
}
|
||||
|
||||
if (srvModel.merchantRefLink !== "") {
|
||||
$(".action-button").click(function () {
|
||||
window.location.href = srvModel.merchantRefLink;
|
||||
});
|
||||
}
|
||||
else {
|
||||
$(".action-button").hide();
|
||||
}
|
||||
|
||||
$(".modal-dialog").addClass("paid");
|
||||
|
||||
resetTabsSlider();
|
||||
|
@ -47,5 +47,8 @@ You can return to {{storeName}} if you would like to submit your payment again."
|
||||
"Archived_Body": "Please contact the store for order information or assistance",
|
||||
// Lightning
|
||||
"BOLT 11 Invoice": "BOLT 11 Invoice",
|
||||
"Node Info": "Node Info"
|
||||
"Node Info": "Node Info",
|
||||
//
|
||||
"txCount": "{{count}} transaction",
|
||||
"txCount_plural": "{{count}} transactions"
|
||||
};
|
||||
|
@ -44,7 +44,10 @@ const locales_es = {
|
||||
// Invoice archived
|
||||
"This invoice has been archived": "Esta factura ha sido archivada",
|
||||
"Archived_Body": "Por favor, comuníquese con la tienda para obtener información de su pedido o asistencia",
|
||||
// Lightning
|
||||
// Lightning
|
||||
"BOLT 11 Invoice": "Factura BOLT 11",
|
||||
"Node Info": "Información del nodo"
|
||||
};
|
||||
"Node Info": "Información del nodo",
|
||||
//
|
||||
"txCount": "{{count}} transacción",
|
||||
"txCount_plural": "{{count}} transacciones"
|
||||
};
|
||||
|
@ -47,5 +47,8 @@ Vous pouvez revenir sur {{storeName}} si vous voulez resoumettre votre paiement.
|
||||
"Archived_Body": "Merci de contacter le marchand pour plus d'assistance ou d'information sur cette commande.",
|
||||
// Lightning
|
||||
"BOLT 11 Invoice": "Facture BOLT 11",
|
||||
"Node Info": "Information du noeud"
|
||||
"Node Info": "Information du noeud",
|
||||
//
|
||||
"txCount": "{{count}} transaction",
|
||||
"txCount_plural": "{{count}} transactions"
|
||||
};
|
||||
|
@ -44,5 +44,11 @@ Você pode voltar para {{storeName}} se quiser enviar o seu pagamento novamente.
|
||||
"This invoice has been paid": "Essa fatura foi paga",
|
||||
// Invoice archived
|
||||
"This invoice has been archived": "Essa fatura foi arquivada",
|
||||
"Archived_Body": "Por favor, entre em contato com o estabelecimento para informações e suporte"
|
||||
"Archived_Body": "Por favor, entre em contato com o estabelecimento para informações e suporte",
|
||||
// Lightning
|
||||
"BOLT 11 Invoice": "Fatura BOLT 11",
|
||||
"Node Info": "Informação de nó",
|
||||
//
|
||||
"txCount": "{{count}} transação",
|
||||
"txCount_plural": "{{count}} transações"
|
||||
};
|
||||
|
Reference in New Issue
Block a user