Use ArgumentNullException.ThrowIfNull everywhere (#3239)

This commit is contained in:
Nicolas Dorier
2021-12-28 17:39:54 +09:00
committed by GitHub
parent 9b7ca76b99
commit ed5b159fb6
50 changed files with 122 additions and 244 deletions

View File

@@ -96,8 +96,7 @@ namespace BTCPayServer.Security
/// <param name="script"></param> /// <param name="script"></param>
public void AllowInline(string script) public void AllowInline(string script)
{ {
if (script is null) ArgumentNullException.ThrowIfNull(script);
throw new ArgumentNullException(nameof(script));
var sha = GetSha256(script); var sha = GetSha256(script);
Add("script-src", $"'sha256-{sha}'"); Add("script-src", $"'sha256-{sha}'");
} }

View File

@@ -121,8 +121,7 @@ namespace BTCPayServer
} }
public T GetNetwork<T>(string cryptoCode) where T : BTCPayNetworkBase public T GetNetwork<T>(string cryptoCode) where T : BTCPayNetworkBase
{ {
if (cryptoCode == null) ArgumentNullException.ThrowIfNull(cryptoCode);
throw new ArgumentNullException(nameof(cryptoCode));
if (!_Networks.TryGetValue(cryptoCode.ToUpperInvariant(), out BTCPayNetworkBase network)) if (!_Networks.TryGetValue(cryptoCode.ToUpperInvariant(), out BTCPayNetworkBase network))
{ {
if (cryptoCode == "XBT") if (cryptoCode == "XBT")

View File

@@ -145,8 +145,7 @@ namespace BTCPayServer.Services.Rates
public CurrencyData GetCurrencyData(string currency, bool useFallback) public CurrencyData GetCurrencyData(string currency, bool useFallback)
{ {
if (currency == null) ArgumentNullException.ThrowIfNull(currency);
throw new ArgumentNullException(nameof(currency));
CurrencyData result; CurrencyData result;
if (!_Currencies.TryGetValue(currency.ToUpperInvariant(), out result)) if (!_Currencies.TryGetValue(currency.ToUpperInvariant(), out result))
{ {

View File

@@ -7,10 +7,8 @@ namespace BTCPayServer.Rating
{ {
public CurrencyPair(string left, string right) public CurrencyPair(string left, string right)
{ {
if (right == null) ArgumentNullException.ThrowIfNull(right);
throw new ArgumentNullException(nameof(right)); ArgumentNullException.ThrowIfNull(left);
if (left == null)
throw new ArgumentNullException(nameof(left));
Right = right.ToUpperInvariant(); Right = right.ToUpperInvariant();
Left = left.ToUpperInvariant(); Left = left.ToUpperInvariant();
} }
@@ -25,8 +23,7 @@ namespace BTCPayServer.Rating
} }
public static bool TryParse(string str, out CurrencyPair value) public static bool TryParse(string str, out CurrencyPair value)
{ {
if (str == null) ArgumentNullException.ThrowIfNull(str);
throw new ArgumentNullException(nameof(str));
value = null; value = null;
str = str.Trim(); str = str.Trim();
if (str.Length > 12) if (str.Length > 12)

View File

@@ -232,10 +232,8 @@ namespace BTCPayServer.Rating
{ {
public PairRate(CurrencyPair currencyPair, BidAsk bidAsk) public PairRate(CurrencyPair currencyPair, BidAsk bidAsk)
{ {
if (currencyPair == null) ArgumentNullException.ThrowIfNull(currencyPair);
throw new ArgumentNullException(nameof(currencyPair)); ArgumentNullException.ThrowIfNull(bidAsk);
if (bidAsk == null)
throw new ArgumentNullException(nameof(bidAsk));
this.CurrencyPair = currencyPair; this.CurrencyPair = currencyPair;
this.BidAsk = bidAsk; this.BidAsk = bidAsk;
} }

View File

@@ -85,8 +85,7 @@ namespace BTCPayServer.Services.Rates
public BackgroundFetcherRateProvider(IRateProvider inner) public BackgroundFetcherRateProvider(IRateProvider inner)
{ {
if (inner == null) ArgumentNullException.ThrowIfNull(inner);
throw new ArgumentNullException(nameof(inner));
_Inner = inner; _Inner = inner;
} }

View File

@@ -15,8 +15,7 @@ namespace BTCPayServer.Services.Rates
readonly HttpClient _httpClient; readonly HttpClient _httpClient;
public ExchangeSharpRateProvider(HttpClient httpClient, bool reverseCurrencyPair = false) public ExchangeSharpRateProvider(HttpClient httpClient, bool reverseCurrencyPair = false)
{ {
if (httpClient == null) ArgumentNullException.ThrowIfNull(httpClient);
throw new ArgumentNullException(nameof(httpClient));
ReverseCurrencyPair = reverseCurrencyPair; ReverseCurrencyPair = reverseCurrencyPair;
_httpClient = httpClient; _httpClient = httpClient;
} }

View File

@@ -11,8 +11,7 @@ namespace BTCPayServer.Services.Rates
readonly IRateProvider[] _Providers; readonly IRateProvider[] _Providers;
public FallbackRateProvider(IRateProvider[] providers) public FallbackRateProvider(IRateProvider[] providers)
{ {
if (providers == null) ArgumentNullException.ThrowIfNull(providers);
throw new ArgumentNullException(nameof(providers));
_Providers = providers; _Providers = providers;
} }

View File

@@ -96,10 +96,8 @@ namespace BTCPayServer.Services.Rates
public HttpClientRequestMaker(IAPIRequestHandler api, HttpClient httpClient, CancellationToken cancellationToken) public HttpClientRequestMaker(IAPIRequestHandler api, HttpClient httpClient, CancellationToken cancellationToken)
{ {
if (api == null) ArgumentNullException.ThrowIfNull(api);
throw new ArgumentNullException(nameof(api)); ArgumentNullException.ThrowIfNull(httpClient);
if (httpClient == null)
throw new ArgumentNullException(nameof(httpClient));
this.api = api; this.api = api;
_httpClient = httpClient; _httpClient = httpClient;
_cancellationToken = cancellationToken; _cancellationToken = cancellationToken;

View File

@@ -41,8 +41,7 @@ namespace BTCPayServer.Services.Rates
public Dictionary<CurrencyPair, Task<RateResult>> FetchRates(HashSet<CurrencyPair> pairs, RateRules rules, CancellationToken cancellationToken) public Dictionary<CurrencyPair, Task<RateResult>> FetchRates(HashSet<CurrencyPair> pairs, RateRules rules, CancellationToken cancellationToken)
{ {
if (rules == null) ArgumentNullException.ThrowIfNull(rules);
throw new ArgumentNullException(nameof(rules));
var fetchingRates = new Dictionary<CurrencyPair, Task<RateResult>>(); var fetchingRates = new Dictionary<CurrencyPair, Task<RateResult>>();
var fetchingExchanges = new Dictionary<string, Task<QueryRateResult>>(); var fetchingExchanges = new Dictionary<string, Task<QueryRateResult>>();
@@ -67,8 +66,7 @@ namespace BTCPayServer.Services.Rates
public Task<RateResult> FetchRate(RateRule rateRule, CancellationToken cancellationToken) public Task<RateResult> FetchRate(RateRule rateRule, CancellationToken cancellationToken)
{ {
if (rateRule == null) ArgumentNullException.ThrowIfNull(rateRule);
throw new ArgumentNullException(nameof(rateRule));
var fetchingExchanges = new Dictionary<string, Task<QueryRateResult>>(); var fetchingExchanges = new Dictionary<string, Task<QueryRateResult>>();
var dependentQueries = new List<Task<QueryRateResult>>(); var dependentQueries = new List<Task<QueryRateResult>>();
foreach (var requiredExchange in rateRule.ExchangeRates) foreach (var requiredExchange in rateRule.ExchangeRates)

View File

@@ -147,8 +147,7 @@ namespace BTCPayServer.Configuration
} }
public static bool TryParse(string str, out ExternalConnectionString result, out string error) public static bool TryParse(string str, out ExternalConnectionString result, out string error)
{ {
if (str == null) ArgumentNullException.ThrowIfNull(str);
throw new ArgumentNullException(nameof(str));
error = null; error = null;
result = null; result = null;
var resultTemp = new ExternalConnectionString(); var resultTemp = new ExternalConnectionString();

View File

@@ -19,8 +19,7 @@ namespace BTCPayServer.Controllers
} }
public static async Task<Macaroons> GetFromDirectoryAsync(string directoryPath) public static async Task<Macaroons> GetFromDirectoryAsync(string directoryPath)
{ {
if (directoryPath == null) ArgumentNullException.ThrowIfNull(directoryPath);
throw new ArgumentNullException(nameof(directoryPath));
Macaroons macaroons = new Macaroons(); Macaroons macaroons = new Macaroons();
if (!Directory.Exists(directoryPath)) if (!Directory.Exists(directoryPath))
throw new DirectoryNotFoundException("Macaroons directory not found"); throw new DirectoryNotFoundException("Macaroons directory not found");

View File

@@ -9,8 +9,7 @@ namespace BTCPayServer.Data
public AddressClaimDestination(BitcoinAddress bitcoinAddress) public AddressClaimDestination(BitcoinAddress bitcoinAddress)
{ {
if (bitcoinAddress == null) ArgumentNullException.ThrowIfNull(bitcoinAddress);
throw new ArgumentNullException(nameof(bitcoinAddress));
_bitcoinAddress = bitcoinAddress; _bitcoinAddress = bitcoinAddress;
} }
public BitcoinAddress Address => _bitcoinAddress; public BitcoinAddress Address => _bitcoinAddress;

View File

@@ -11,8 +11,7 @@ namespace BTCPayServer.Data
public UriClaimDestination(BitcoinUrlBuilder bitcoinUrl) public UriClaimDestination(BitcoinUrlBuilder bitcoinUrl)
{ {
if (bitcoinUrl == null) ArgumentNullException.ThrowIfNull(bitcoinUrl);
throw new ArgumentNullException(nameof(bitcoinUrl));
if (bitcoinUrl.Address is null) if (bitcoinUrl.Address is null)
throw new ArgumentException(nameof(bitcoinUrl)); throw new ArgumentException(nameof(bitcoinUrl));
_bitcoinUrl = bitcoinUrl; _bitcoinUrl = bitcoinUrl;

View File

@@ -68,8 +68,7 @@ namespace BTCPayServer.Data
public static IEnumerable<ISupportedPaymentMethod> GetSupportedPaymentMethods(this StoreData storeData, BTCPayNetworkProvider networks) public static IEnumerable<ISupportedPaymentMethod> GetSupportedPaymentMethods(this StoreData storeData, BTCPayNetworkProvider networks)
{ {
if (storeData == null) ArgumentNullException.ThrowIfNull(storeData);
throw new ArgumentNullException(nameof(storeData));
#pragma warning disable CS0618 #pragma warning disable CS0618
bool btcReturned = false; bool btcReturned = false;

View File

@@ -15,8 +15,7 @@ namespace BTCPayServer
public DerivationSchemeParser(BTCPayNetwork expectedNetwork) public DerivationSchemeParser(BTCPayNetwork expectedNetwork)
{ {
if (expectedNetwork == null) ArgumentNullException.ThrowIfNull(expectedNetwork);
throw new ArgumentNullException(nameof(expectedNetwork));
BtcPayNetwork = expectedNetwork; BtcPayNetwork = expectedNetwork;
} }
@@ -44,8 +43,7 @@ namespace BTCPayServer
} }
} }
if (str == null) ArgumentNullException.ThrowIfNull(str);
throw new ArgumentNullException(nameof(str));
str = str.Trim(); str = str.Trim();
var outputDescriptor = OutputDescriptor.Parse(str, Network); var outputDescriptor = OutputDescriptor.Parse(str, Network);
switch(outputDescriptor) switch(outputDescriptor)
@@ -95,8 +93,7 @@ namespace BTCPayServer
public DerivationStrategyBase ParseElectrum(string str) public DerivationStrategyBase ParseElectrum(string str)
{ {
if (str == null) ArgumentNullException.ThrowIfNull(str);
throw new ArgumentNullException(nameof(str));
str = str.Trim(); str = str.Trim();
var data = Network.GetBase58CheckEncoder().DecodeData(str); var data = Network.GetBase58CheckEncoder().DecodeData(str);
if (data.Length < 4) if (data.Length < 4)
@@ -123,8 +120,7 @@ namespace BTCPayServer
public DerivationStrategyBase Parse(string str) public DerivationStrategyBase Parse(string str)
{ {
if (str == null) ArgumentNullException.ThrowIfNull(str);
throw new ArgumentNullException(nameof(str));
str = str.Trim(); str = str.Trim();
HashSet<string> hintedLabels = new HashSet<string>(); HashSet<string> hintedLabels = new HashSet<string>();

View File

@@ -15,10 +15,8 @@ namespace BTCPayServer
{ {
public static DerivationSchemeSettings Parse(string derivationStrategy, BTCPayNetwork network) public static DerivationSchemeSettings Parse(string derivationStrategy, BTCPayNetwork network)
{ {
if (network == null) ArgumentNullException.ThrowIfNull(network);
throw new ArgumentNullException(nameof(network)); ArgumentNullException.ThrowIfNull(derivationStrategy);
if (derivationStrategy == null)
throw new ArgumentNullException(nameof(derivationStrategy));
var result = new DerivationSchemeSettings(); var result = new DerivationSchemeSettings();
result.Network = network; result.Network = network;
var parser = new DerivationSchemeParser(network); var parser = new DerivationSchemeParser(network);
@@ -32,10 +30,8 @@ namespace BTCPayServer
public static bool TryParseFromJson(string config, BTCPayNetwork network, out DerivationSchemeSettings strategy) public static bool TryParseFromJson(string config, BTCPayNetwork network, out DerivationSchemeSettings strategy)
{ {
if (network == null) ArgumentNullException.ThrowIfNull(network);
throw new ArgumentNullException(nameof(network)); ArgumentNullException.ThrowIfNull(config);
if (config == null)
throw new ArgumentNullException(nameof(config));
strategy = null; strategy = null;
try try
{ {
@@ -90,10 +86,8 @@ namespace BTCPayServer
public static bool TryParseFromWalletFile(string fileContents, BTCPayNetwork network, out DerivationSchemeSettings settings) public static bool TryParseFromWalletFile(string fileContents, BTCPayNetwork network, out DerivationSchemeSettings settings)
{ {
settings = null; settings = null;
if (fileContents == null) ArgumentNullException.ThrowIfNull(fileContents);
throw new ArgumentNullException(nameof(fileContents)); ArgumentNullException.ThrowIfNull(network);
if (network == null)
throw new ArgumentNullException(nameof(network));
var result = new DerivationSchemeSettings(); var result = new DerivationSchemeSettings();
var derivationSchemeParser = new DerivationSchemeParser(network); var derivationSchemeParser = new DerivationSchemeParser(network);
JObject jobj = null; JObject jobj = null;
@@ -247,10 +241,8 @@ namespace BTCPayServer
public DerivationSchemeSettings(DerivationStrategyBase derivationStrategy, BTCPayNetwork network) public DerivationSchemeSettings(DerivationStrategyBase derivationStrategy, BTCPayNetwork network)
{ {
if (network == null) ArgumentNullException.ThrowIfNull(network);
throw new ArgumentNullException(nameof(network)); ArgumentNullException.ThrowIfNull(derivationStrategy);
if (derivationStrategy == null)
throw new ArgumentNullException(nameof(derivationStrategy));
AccountDerivation = derivationStrategy; AccountDerivation = derivationStrategy;
Network = network; Network = network;
AccountKeySettings = derivationStrategy.GetExtPubKeys().Select(c => new AccountKeySettings() AccountKeySettings = derivationStrategy.GetExtPubKeys().Select(c => new AccountKeySettings()

View File

@@ -81,8 +81,7 @@ namespace BTCPayServer
public void Publish(object evt, Type evtType) public void Publish(object evt, Type evtType)
{ {
if (evt == null) ArgumentNullException.ThrowIfNull(evt);
throw new ArgumentNullException(nameof(evt));
List<Action<object>> actionList = new List<Action<object>>(); List<Action<object>> actionList = new List<Action<object>>();
lock (_Subscriptions) lock (_Subscriptions)
{ {

View File

@@ -6,8 +6,7 @@ namespace BTCPayServer.Events
{ {
public InvoiceNeedUpdateEvent(string invoiceId) public InvoiceNeedUpdateEvent(string invoiceId)
{ {
if (invoiceId == null) ArgumentNullException.ThrowIfNull(invoiceId);
throw new ArgumentNullException(nameof(invoiceId));
InvoiceId = invoiceId; InvoiceId = invoiceId;
} }

View File

@@ -83,8 +83,7 @@ namespace BTCPayServer
public ExplorerClient GetExplorerClient(BTCPayNetworkBase network) public ExplorerClient GetExplorerClient(BTCPayNetworkBase network)
{ {
if (network == null) ArgumentNullException.ThrowIfNull(network);
throw new ArgumentNullException(nameof(network));
return GetExplorerClient(network.CryptoCode); return GetExplorerClient(network.CryptoCode);
} }

View File

@@ -215,8 +215,7 @@ namespace BTCPayServer
public static bool IsLocalNetwork(string server) public static bool IsLocalNetwork(string server)
{ {
if (server == null) ArgumentNullException.ThrowIfNull(server);
throw new ArgumentNullException(nameof(server));
if (Uri.CheckHostName(server) == UriHostNameType.Dns) if (Uri.CheckHostName(server) == UriHostNameType.Dns)
{ {
return server.EndsWith(".internal", StringComparison.OrdinalIgnoreCase) || return server.EndsWith(".internal", StringComparison.OrdinalIgnoreCase) ||

View File

@@ -10,8 +10,7 @@ namespace BTCPayServer
{ {
public static async Task<SshClient> ConnectAsync(this SSHSettings sshSettings, CancellationToken cancellationToken = default) public static async Task<SshClient> ConnectAsync(this SSHSettings sshSettings, CancellationToken cancellationToken = default)
{ {
if (sshSettings == null) ArgumentNullException.ThrowIfNull(sshSettings);
throw new ArgumentNullException(nameof(sshSettings));
TaskCompletionSource<SshClient> tcs = new TaskCompletionSource<SshClient>(TaskCreationOptions.RunContinuationsAsynchronously); TaskCompletionSource<SshClient> tcs = new TaskCompletionSource<SshClient>(TaskCreationOptions.RunContinuationsAsynchronously);
new Thread(() => new Thread(() =>
{ {
@@ -58,10 +57,8 @@ namespace BTCPayServer
public static Task<SSHCommandResult> RunBash(this SshClient sshClient, string command, TimeSpan? timeout = null) public static Task<SSHCommandResult> RunBash(this SshClient sshClient, string command, TimeSpan? timeout = null)
{ {
if (sshClient == null) ArgumentNullException.ThrowIfNull(sshClient);
throw new ArgumentNullException(nameof(sshClient)); ArgumentNullException.ThrowIfNull(command);
if (command == null)
throw new ArgumentNullException(nameof(command));
command = $"bash -c '{command.EscapeSingleQuotes()}'"; command = $"bash -c '{command.EscapeSingleQuotes()}'";
var sshCommand = sshClient.CreateCommand(command); var sshCommand = sshClient.CreateCommand(command);
if (timeout is TimeSpan v) if (timeout is TimeSpan v)
@@ -106,8 +103,7 @@ namespace BTCPayServer
public static async Task DisconnectAsync(this SshClient sshClient, CancellationToken cancellationToken = default) public static async Task DisconnectAsync(this SshClient sshClient, CancellationToken cancellationToken = default)
{ {
if (sshClient == null) ArgumentNullException.ThrowIfNull(sshClient);
throw new ArgumentNullException(nameof(sshClient));
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
new Thread(() => new Thread(() =>

View File

@@ -235,8 +235,7 @@ namespace BTCPayServer.HostedServices
private void Watch(string invoiceId) private void Watch(string invoiceId)
{ {
if (invoiceId == null) ArgumentNullException.ThrowIfNull(invoiceId);
throw new ArgumentNullException(nameof(invoiceId));
if (!_WatchRequests.Writer.TryWrite(invoiceId)) if (!_WatchRequests.Writer.TryWrite(invoiceId))
{ {

View File

@@ -41,14 +41,12 @@ namespace BTCPayServer.HostedServices
{ {
public CancelRequest(string pullPaymentId) public CancelRequest(string pullPaymentId)
{ {
if (pullPaymentId == null) ArgumentNullException.ThrowIfNull(pullPaymentId);
throw new ArgumentNullException(nameof(pullPaymentId));
PullPaymentId = pullPaymentId; PullPaymentId = pullPaymentId;
} }
public CancelRequest(string[] payoutIds) public CancelRequest(string[] payoutIds)
{ {
if (payoutIds == null) ArgumentNullException.ThrowIfNull(payoutIds);
throw new ArgumentNullException(nameof(payoutIds));
PayoutIds = payoutIds; PayoutIds = payoutIds;
} }
public string PullPaymentId { get; set; } public string PullPaymentId { get; set; }
@@ -91,8 +89,7 @@ namespace BTCPayServer.HostedServices
} }
public async Task<string> CreatePullPayment(CreatePullPayment create) public async Task<string> CreatePullPayment(CreatePullPayment create)
{ {
if (create == null) ArgumentNullException.ThrowIfNull(create);
throw new ArgumentNullException(nameof(create));
if (create.Amount <= 0.0m) if (create.Amount <= 0.0m)
throw new ArgumentException("Amount out of bound", nameof(create)); throw new ArgumentException("Amount out of bound", nameof(create));
using var ctx = this._dbContextFactory.CreateContext(); using var ctx = this._dbContextFactory.CreateContext();
@@ -137,10 +134,8 @@ namespace BTCPayServer.HostedServices
{ {
public PayoutRequest(TaskCompletionSource<ClaimRequest.ClaimResponse> completionSource, ClaimRequest request) public PayoutRequest(TaskCompletionSource<ClaimRequest.ClaimResponse> completionSource, ClaimRequest request)
{ {
if (request == null) ArgumentNullException.ThrowIfNull(request);
throw new ArgumentNullException(nameof(request)); ArgumentNullException.ThrowIfNull(completionSource);
if (completionSource == null)
throw new ArgumentNullException(nameof(completionSource));
Completion = completionSource; Completion = completionSource;
ClaimRequest = request; ClaimRequest = request;
} }
@@ -536,10 +531,8 @@ namespace BTCPayServer.HostedServices
{ {
public InternalPayoutPaidRequest(TaskCompletionSource<PayoutPaidRequest.PayoutPaidResult> completionSource, PayoutPaidRequest request) public InternalPayoutPaidRequest(TaskCompletionSource<PayoutPaidRequest.PayoutPaidResult> completionSource, PayoutPaidRequest request)
{ {
if (request == null) ArgumentNullException.ThrowIfNull(request);
throw new ArgumentNullException(nameof(request)); ArgumentNullException.ThrowIfNull(completionSource);
if (completionSource == null)
throw new ArgumentNullException(nameof(completionSource));
Completion = completionSource; Completion = completionSource;
Request = request; Request = request;
} }

View File

@@ -16,8 +16,7 @@ namespace BTCPayServer.Models
readonly BitTokenEntity[] _Tokens; readonly BitTokenEntity[] _Tokens;
public GetTokensResponse(BitTokenEntity[] tokens) public GetTokensResponse(BitTokenEntity[] tokens)
{ {
if (tokens == null) ArgumentNullException.ThrowIfNull(tokens);
throw new ArgumentNullException(nameof(tokens));
this._Tokens = tokens; this._Tokens = tokens;
} }

View File

@@ -83,16 +83,13 @@ namespace BTCPayServer.Payments
} }
public static IPaymentFilter Where(Func<PaymentMethodId, bool> predicate) public static IPaymentFilter Where(Func<PaymentMethodId, bool> predicate)
{ {
if (predicate == null) ArgumentNullException.ThrowIfNull(predicate);
throw new ArgumentNullException(nameof(predicate));
return new PredicateFilter(predicate); return new PredicateFilter(predicate);
} }
public static IPaymentFilter Or(IPaymentFilter a, IPaymentFilter b) public static IPaymentFilter Or(IPaymentFilter a, IPaymentFilter b)
{ {
if (a == null) ArgumentNullException.ThrowIfNull(a);
throw new ArgumentNullException(nameof(a)); ArgumentNullException.ThrowIfNull(b);
if (b == null)
throw new ArgumentNullException(nameof(b));
return new OrPaymentFilter(a, b); return new OrPaymentFilter(a, b);
} }
public static IPaymentFilter Never() public static IPaymentFilter Never()
@@ -101,14 +98,12 @@ namespace BTCPayServer.Payments
} }
public static IPaymentFilter Any(IPaymentFilter[] filters) public static IPaymentFilter Any(IPaymentFilter[] filters)
{ {
if (filters == null) ArgumentNullException.ThrowIfNull(filters);
throw new ArgumentNullException(nameof(filters));
return new CompositePaymentFilter(filters); return new CompositePaymentFilter(filters);
} }
public static IPaymentFilter WhereIs(PaymentMethodId paymentMethodId) public static IPaymentFilter WhereIs(PaymentMethodId paymentMethodId)
{ {
if (paymentMethodId == null) ArgumentNullException.ThrowIfNull(paymentMethodId);
throw new ArgumentNullException(nameof(paymentMethodId));
return new PaymentIdFilter(paymentMethodId); return new PaymentIdFilter(paymentMethodId);
} }
} }

View File

@@ -415,8 +415,7 @@ namespace BTCPayServer.Payments.Lightning
PaymentService paymentService, PaymentService paymentService,
Logs logs) Logs logs)
{ {
if (connectionString == null) ArgumentNullException.ThrowIfNull(connectionString);
throw new ArgumentNullException(nameof(connectionString));
Logs = logs; Logs = logs;
this._invoiceRepository = invoiceRepository; this._invoiceRepository = invoiceRepository;
_eventAggregator = eventAggregator; _eventAggregator = eventAggregator;

View File

@@ -37,8 +37,7 @@ namespace BTCPayServer.Payments.Lightning
public void SetLightningUrl(LightningConnectionString connectionString) public void SetLightningUrl(LightningConnectionString connectionString)
{ {
if (connectionString == null) ArgumentNullException.ThrowIfNull(connectionString);
throw new ArgumentNullException(nameof(connectionString));
#pragma warning disable CS0618 // Type or member is obsolete #pragma warning disable CS0618 // Type or member is obsolete
LightningConnectionString = connectionString.ToString(); LightningConnectionString = connectionString.ToString();
#pragma warning restore CS0618 // Type or member is obsolete #pragma warning restore CS0618 // Type or member is obsolete

View File

@@ -59,10 +59,8 @@ namespace BTCPayServer.Payments.PayJoin
public static UTXODeterministicComparer Instance => _Instance; public static UTXODeterministicComparer Instance => _Instance;
public int Compare([AllowNull] UTXO x, [AllowNull] UTXO y) public int Compare([AllowNull] UTXO x, [AllowNull] UTXO y)
{ {
if (x == null) ArgumentNullException.ThrowIfNull(x);
throw new ArgumentNullException(nameof(x)); ArgumentNullException.ThrowIfNull(y);
if (y == null)
throw new ArgumentNullException(nameof(y));
Span<byte> tmpx = stackalloc byte[32]; Span<byte> tmpx = stackalloc byte[32];
Span<byte> tmpy = stackalloc byte[32]; Span<byte> tmpy = stackalloc byte[32];
x.Outpoint.Hash.ToBytes(tmpx); x.Outpoint.Hash.ToBytes(tmpx);

View File

@@ -13,17 +13,14 @@ namespace BTCPayServer.Payments
{ {
public PaymentMethodId? FindNearest(PaymentMethodId[] others) public PaymentMethodId? FindNearest(PaymentMethodId[] others)
{ {
if (others is null) ArgumentNullException.ThrowIfNull(others);
throw new ArgumentNullException(nameof(others));
return others.FirstOrDefault(f => f == this) ?? return others.FirstOrDefault(f => f == this) ??
others.FirstOrDefault(f => f.CryptoCode == CryptoCode); others.FirstOrDefault(f => f.CryptoCode == CryptoCode);
} }
public PaymentMethodId(string cryptoCode, PaymentType paymentType) public PaymentMethodId(string cryptoCode, PaymentType paymentType)
{ {
if (cryptoCode == null) ArgumentNullException.ThrowIfNull(cryptoCode);
throw new ArgumentNullException(nameof(cryptoCode)); ArgumentNullException.ThrowIfNull(paymentType);
if (paymentType == null)
throw new ArgumentNullException(nameof(paymentType));
PaymentType = paymentType; PaymentType = paymentType;
CryptoCode = cryptoCode.ToUpperInvariant(); CryptoCode = cryptoCode.ToUpperInvariant();
} }

View File

@@ -44,10 +44,8 @@ namespace BTCPayServer.Payments
public override ISupportedPaymentMethod DeserializeSupportedPaymentMethod(BTCPayNetworkBase network, JToken value) public override ISupportedPaymentMethod DeserializeSupportedPaymentMethod(BTCPayNetworkBase network, JToken value)
{ {
if (network == null) ArgumentNullException.ThrowIfNull(network);
throw new ArgumentNullException(nameof(network)); ArgumentNullException.ThrowIfNull(value);
if (value == null)
throw new ArgumentNullException(nameof(value));
var net = (BTCPayNetwork)network; var net = (BTCPayNetwork)network;
if (value is JObject jobj) if (value is JObject jobj)
{ {
@@ -61,8 +59,7 @@ namespace BTCPayServer.Payments
public override string GetTransactionLink(BTCPayNetworkBase network, string txId) public override string GetTransactionLink(BTCPayNetworkBase network, string txId)
{ {
if (txId == null) ArgumentNullException.ThrowIfNull(txId);
throw new ArgumentNullException(nameof(txId));
if (network?.BlockExplorerLink == null) if (network?.BlockExplorerLink == null)
return null; return null;
txId = txId.Split('-').First(); txId = txId.Split('-').First();

View File

@@ -10,8 +10,7 @@ namespace BTCPayServer.SSH
{ {
public static bool TryParse(string str, out SSHFingerprint fingerPrint) public static bool TryParse(string str, out SSHFingerprint fingerPrint)
{ {
if (str == null) ArgumentNullException.ThrowIfNull(str);
throw new ArgumentNullException(nameof(str));
fingerPrint = null; fingerPrint = null;
str = str.Trim(); str = str.Trim();
try try
@@ -77,10 +76,8 @@ namespace BTCPayServer.SSH
public bool Match(byte[] shortFingerprint, byte[] hostKey) public bool Match(byte[] shortFingerprint, byte[] hostKey)
{ {
if (shortFingerprint == null) ArgumentNullException.ThrowIfNull(shortFingerprint);
throw new ArgumentNullException(nameof(shortFingerprint)); ArgumentNullException.ThrowIfNull(hostKey);
if (hostKey == null)
throw new ArgumentNullException(nameof(hostKey));
if (_ShortFingerprint != null) if (_ShortFingerprint != null)
return Utils.ArrayEqual(shortFingerprint, _ShortFingerprint); return Utils.ArrayEqual(shortFingerprint, _ShortFingerprint);
return Utils.ArrayEqual(_FullHash, NBitcoin.Crypto.Hashes.SHA256(hostKey)); return Utils.ArrayEqual(_FullHash, NBitcoin.Crypto.Hashes.SHA256(hostKey));

View File

@@ -21,8 +21,7 @@ namespace BTCPayServer.Security.Bitpay
readonly ApplicationDbContextFactory _Factory; readonly ApplicationDbContextFactory _Factory;
public TokenRepository(ApplicationDbContextFactory dbFactory) public TokenRepository(ApplicationDbContextFactory dbFactory)
{ {
if (dbFactory == null) ArgumentNullException.ThrowIfNull(dbFactory);
throw new ArgumentNullException(nameof(dbFactory));
_Factory = dbFactory; _Factory = dbFactory;
} }

View File

@@ -7,8 +7,7 @@ namespace BTCPayServer.Security
{ {
public PolicyRequirement(string policy) public PolicyRequirement(string policy)
{ {
if (policy == null) ArgumentNullException.ThrowIfNull(policy);
throw new ArgumentNullException(nameof(policy));
Policy = policy; Policy = policy;
} }
public string Policy { get; } public string Policy { get; }

View File

@@ -45,20 +45,17 @@ namespace BTCPayServer.Services
public JsonSerializerSettings GetSerializer(Network network) public JsonSerializerSettings GetSerializer(Network network)
{ {
if (network == null) ArgumentNullException.ThrowIfNull(network);
throw new ArgumentNullException(nameof(network));
return GetSerializer(network.NetworkSet.CryptoCode); return GetSerializer(network.NetworkSet.CryptoCode);
} }
public JsonSerializerSettings GetSerializer(BTCPayNetwork network) public JsonSerializerSettings GetSerializer(BTCPayNetwork network)
{ {
if (network == null) ArgumentNullException.ThrowIfNull(network);
throw new ArgumentNullException(nameof(network));
return GetSerializer(network.CryptoCode); return GetSerializer(network.CryptoCode);
} }
public JsonSerializerSettings GetSerializer(string cryptoCode) public JsonSerializerSettings GetSerializer(string cryptoCode)
{ {
if (cryptoCode == null) ArgumentNullException.ThrowIfNull(cryptoCode);
throw new ArgumentNullException(nameof(cryptoCode));
_Serializers.TryGetValue(cryptoCode, out var serializer); _Serializers.TryGetValue(cryptoCode, out var serializer);
return serializer; return serializer;
} }

View File

@@ -33,8 +33,7 @@ namespace BTCPayServer.Services
Data.ApplicationDbContextFactory dbContextFactory, Data.ApplicationDbContextFactory dbContextFactory,
Logs logs) Logs logs)
{ {
if (explorerClientProvider == null) ArgumentNullException.ThrowIfNull(explorerClientProvider);
throw new ArgumentNullException(nameof(explorerClientProvider));
_networkProvider = networkProvider; _networkProvider = networkProvider;
_explorerClientProvider = explorerClientProvider; _explorerClientProvider = explorerClientProvider;
_dbContextFactory = dbContextFactory; _dbContextFactory = dbContextFactory;
@@ -43,10 +42,8 @@ namespace BTCPayServer.Services
public async Task Schedule(DateTimeOffset broadcastTime, Transaction transaction, BTCPayNetwork network) public async Task Schedule(DateTimeOffset broadcastTime, Transaction transaction, BTCPayNetwork network)
{ {
if (transaction == null) ArgumentNullException.ThrowIfNull(transaction);
throw new ArgumentNullException(nameof(transaction)); ArgumentNullException.ThrowIfNull(network);
if (network == null)
throw new ArgumentNullException(nameof(network));
using (var db = _dbContextFactory.CreateContext()) using (var db = _dbContextFactory.CreateContext())
{ {
db.PlannedTransactions.Add(new PlannedTransaction() db.PlannedTransactions.Add(new PlannedTransaction()

View File

@@ -10,8 +10,7 @@ namespace BTCPayServer.Services.Fees
{ {
public NBXplorerFeeProviderFactory(ExplorerClientProvider explorerClients) public NBXplorerFeeProviderFactory(ExplorerClientProvider explorerClients)
{ {
if (explorerClients == null) ArgumentNullException.ThrowIfNull(explorerClients);
throw new ArgumentNullException(nameof(explorerClients));
_ExplorerClients = explorerClients; _ExplorerClients = explorerClients;
} }
@@ -27,8 +26,7 @@ namespace BTCPayServer.Services.Fees
{ {
public NBXplorerFeeProvider(NBXplorerFeeProviderFactory parent, ExplorerClient explorerClient) public NBXplorerFeeProvider(NBXplorerFeeProviderFactory parent, ExplorerClient explorerClient)
{ {
if (explorerClient == null) ArgumentNullException.ThrowIfNull(explorerClient);
throw new ArgumentNullException(nameof(explorerClient));
_Factory = parent; _Factory = parent;
_ExplorerClient = explorerClient; _ExplorerClient = explorerClient;
} }

View File

@@ -114,8 +114,7 @@ namespace BTCPayServer.Services.Invoices
public async Task<AppData[]> GetAppsTaggingStore(string storeId) public async Task<AppData[]> GetAppsTaggingStore(string storeId)
{ {
if (storeId == null) ArgumentNullException.ThrowIfNull(storeId);
throw new ArgumentNullException(nameof(storeId));
using (var ctx = _applicationDbContextFactory.CreateContext()) using (var ctx = _applicationDbContextFactory.CreateContext())
{ {
return await ctx.Apps.Where(a => a.StoreDataId == storeId && a.TagAllInvoices).ToArrayAsync(); return await ctx.Apps.Where(a => a.StoreDataId == storeId && a.TagAllInvoices).ToArrayAsync();

View File

@@ -32,8 +32,7 @@ namespace BTCPayServer.Services.Invoices
} }
public bool TryGetValue(PaymentMethodId paymentMethodId, out PaymentMethod data) public bool TryGetValue(PaymentMethodId paymentMethodId, out PaymentMethod data)
{ {
if (paymentMethodId == null) ArgumentNullException.ThrowIfNull(paymentMethodId);
throw new ArgumentNullException(nameof(paymentMethodId));
return _Inner.TryGetValue(paymentMethodId, out data); return _Inner.TryGetValue(paymentMethodId, out data);
} }
@@ -56,15 +55,13 @@ namespace BTCPayServer.Services.Invoices
public PaymentMethod TryGet(PaymentMethodId paymentMethodId) public PaymentMethod TryGet(PaymentMethodId paymentMethodId)
{ {
if (paymentMethodId == null) ArgumentNullException.ThrowIfNull(paymentMethodId);
throw new ArgumentNullException(nameof(paymentMethodId));
_Inner.TryGetValue(paymentMethodId, out var value); _Inner.TryGetValue(paymentMethodId, out var value);
return value; return value;
} }
public PaymentMethod TryGet(string network, PaymentType paymentType) public PaymentMethod TryGet(string network, PaymentType paymentType)
{ {
if (network == null) ArgumentNullException.ThrowIfNull(network);
throw new ArgumentNullException(nameof(network));
var id = new PaymentMethodId(network, paymentType); var id = new PaymentMethodId(network, paymentType);
return TryGet(id); return TryGet(id);
} }

View File

@@ -34,8 +34,7 @@ namespace BTCPayServer.Services.Labels
} }
public static Label Parse(string str) public static Label Parse(string str)
{ {
if (str == null) ArgumentNullException.ThrowIfNull(str);
throw new ArgumentNullException(nameof(str));
if (str.StartsWith("{", StringComparison.InvariantCultureIgnoreCase)) if (str.StartsWith("{", StringComparison.InvariantCultureIgnoreCase))
{ {
var jObj = JObject.Parse(str); var jObj = JObject.Parse(str);

View File

@@ -40,8 +40,7 @@ namespace BTCPayServer.Services.Labels
const string DefaultColor = "#000"; const string DefaultColor = "#000";
private ColoredLabel CreateLabel(LabelData uncoloredLabel, string color, HttpRequest request) private ColoredLabel CreateLabel(LabelData uncoloredLabel, string color, HttpRequest request)
{ {
if (uncoloredLabel == null) ArgumentNullException.ThrowIfNull(uncoloredLabel);
throw new ArgumentNullException(nameof(uncoloredLabel));
color = color ?? DefaultColor; color = color ?? DefaultColor;
ColoredLabel coloredLabel = new ColoredLabel() ColoredLabel coloredLabel = new ColoredLabel()

View File

@@ -15,10 +15,8 @@ namespace BTCPayServer.Services
public ILightningClient Create(LightningConnectionString lightningConnectionString, BTCPayNetwork network) public ILightningClient Create(LightningConnectionString lightningConnectionString, BTCPayNetwork network)
{ {
if (lightningConnectionString == null) ArgumentNullException.ThrowIfNull(lightningConnectionString);
throw new ArgumentNullException(nameof(lightningConnectionString)); ArgumentNullException.ThrowIfNull(network);
if (network == null)
throw new ArgumentNullException(nameof(network));
return new Lightning.LightningClientFactory(network.NBitcoinNetwork) return new Lightning.LightningClientFactory(network.NBitcoinNetwork)
{ {
HttpClient = _httpClientFactory.CreateClient($"{network.CryptoCode}: Lightning client") HttpClient = _httpClientFactory.CreateClient($"{network.CryptoCode}: Lightning client")

View File

@@ -10,8 +10,7 @@ namespace BTCPayServer.Services.Mails
IBackgroundJobClient backgroundJobClient, IBackgroundJobClient backgroundJobClient,
Logs logs) : base(backgroundJobClient, logs) Logs logs) : base(backgroundJobClient, logs)
{ {
if (settingsRepository == null) ArgumentNullException.ThrowIfNull(settingsRepository);
throw new ArgumentNullException(nameof(settingsRepository));
SettingsRepository = settingsRepository; SettingsRepository = settingsRepository;
} }

View File

@@ -12,8 +12,7 @@ namespace BTCPayServer.Services.Notifications
{ {
public StoreScope(string storeId) public StoreScope(string storeId)
{ {
if (storeId == null) ArgumentNullException.ThrowIfNull(storeId);
throw new ArgumentNullException(nameof(storeId));
StoreId = storeId; StoreId = storeId;
} }
public string StoreId { get; } public string StoreId { get; }
@@ -22,8 +21,7 @@ namespace BTCPayServer.Services.Notifications
{ {
public UserScope(string userId) public UserScope(string userId)
{ {
if (userId == null) ArgumentNullException.ThrowIfNull(userId);
throw new ArgumentNullException(nameof(userId));
UserId = userId; UserId = userId;
} }
public string UserId { get; } public string UserId { get; }

View File

@@ -33,10 +33,8 @@ namespace BTCPayServer.Services.Notifications
public async Task SendNotification(NotificationScope scope, BaseNotification notification) public async Task SendNotification(NotificationScope scope, BaseNotification notification)
{ {
if (scope == null) ArgumentNullException.ThrowIfNull(scope);
throw new ArgumentNullException(nameof(scope)); ArgumentNullException.ThrowIfNull(notification);
if (notification == null)
throw new ArgumentNullException(nameof(notification));
var users = await GetUsers(scope, notification.Identifier); var users = await GetUsers(scope, notification.Identifier);
await using (var db = _contextFactory.CreateContext()) await using (var db = _contextFactory.CreateContext())
{ {

View File

@@ -35,8 +35,7 @@ namespace BTCPayServer.Services.Stores
public async Task<StoreData> FindStore(string storeId, string userId) public async Task<StoreData> FindStore(string storeId, string userId)
{ {
if (userId == null) ArgumentNullException.ThrowIfNull(userId);
throw new ArgumentNullException(nameof(userId));
await using var ctx = _ContextFactory.CreateContext(); await using var ctx = _ContextFactory.CreateContext();
return (await ctx return (await ctx
.UserStore .UserStore
@@ -62,8 +61,7 @@ namespace BTCPayServer.Services.Stores
} }
public async Task<StoreUser[]> GetStoreUsers(string storeId) public async Task<StoreUser[]> GetStoreUsers(string storeId)
{ {
if (storeId == null) ArgumentNullException.ThrowIfNull(storeId);
throw new ArgumentNullException(nameof(storeId));
using (var ctx = _ContextFactory.CreateContext()) using (var ctx = _ContextFactory.CreateContext())
{ {
return await ctx return await ctx
@@ -183,8 +181,7 @@ namespace BTCPayServer.Services.Stores
throw new ArgumentException("id should be empty", nameof(storeData.StoreName)); throw new ArgumentException("id should be empty", nameof(storeData.StoreName));
if (string.IsNullOrEmpty(storeData.StoreName)) if (string.IsNullOrEmpty(storeData.StoreName))
throw new ArgumentException("name should not be empty", nameof(storeData.StoreName)); throw new ArgumentException("name should not be empty", nameof(storeData.StoreName));
if (ownerId == null) ArgumentNullException.ThrowIfNull(ownerId);
throw new ArgumentNullException(nameof(ownerId));
using (var ctx = _ContextFactory.CreateContext()) using (var ctx = _ContextFactory.CreateContext())
{ {
storeData.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(32)); storeData.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(32));
@@ -221,10 +218,8 @@ namespace BTCPayServer.Services.Stores
public async Task<WebhookDeliveryData> GetWebhookDelivery(string storeId, string webhookId, string deliveryId) public async Task<WebhookDeliveryData> GetWebhookDelivery(string storeId, string webhookId, string deliveryId)
{ {
if (webhookId == null) ArgumentNullException.ThrowIfNull(webhookId);
throw new ArgumentNullException(nameof(webhookId)); ArgumentNullException.ThrowIfNull(storeId);
if (storeId == null)
throw new ArgumentNullException(nameof(storeId));
using var ctx = _ContextFactory.CreateContext(); using var ctx = _ContextFactory.CreateContext();
return await ctx.StoreWebhooks return await ctx.StoreWebhooks
.Where(d => d.StoreId == storeId && d.WebhookId == webhookId) .Where(d => d.StoreId == storeId && d.WebhookId == webhookId)
@@ -251,10 +246,8 @@ namespace BTCPayServer.Services.Stores
public async Task<WebhookDeliveryData[]> GetWebhookDeliveries(string storeId, string webhookId, int? count) public async Task<WebhookDeliveryData[]> GetWebhookDeliveries(string storeId, string webhookId, int? count)
{ {
if (webhookId == null) ArgumentNullException.ThrowIfNull(webhookId);
throw new ArgumentNullException(nameof(webhookId)); ArgumentNullException.ThrowIfNull(storeId);
if (storeId == null)
throw new ArgumentNullException(nameof(storeId));
using var ctx = _ContextFactory.CreateContext(); using var ctx = _ContextFactory.CreateContext();
IQueryable<WebhookDeliveryData> req = ctx.StoreWebhooks IQueryable<WebhookDeliveryData> req = ctx.StoreWebhooks
.Where(s => s.StoreId == storeId && s.WebhookId == webhookId) .Where(s => s.StoreId == storeId && s.WebhookId == webhookId)
@@ -268,10 +261,8 @@ namespace BTCPayServer.Services.Stores
public async Task<string> CreateWebhook(string storeId, WebhookBlob blob) public async Task<string> CreateWebhook(string storeId, WebhookBlob blob)
{ {
if (storeId == null) ArgumentNullException.ThrowIfNull(storeId);
throw new ArgumentNullException(nameof(storeId)); ArgumentNullException.ThrowIfNull(blob);
if (blob == null)
throw new ArgumentNullException(nameof(blob));
using var ctx = _ContextFactory.CreateContext(); using var ctx = _ContextFactory.CreateContext();
WebhookData data = new WebhookData(); WebhookData data = new WebhookData();
data.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16)); data.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16));
@@ -289,10 +280,8 @@ namespace BTCPayServer.Services.Stores
public async Task<WebhookData> GetWebhook(string storeId, string webhookId) public async Task<WebhookData> GetWebhook(string storeId, string webhookId)
{ {
if (webhookId == null) ArgumentNullException.ThrowIfNull(webhookId);
throw new ArgumentNullException(nameof(webhookId)); ArgumentNullException.ThrowIfNull(storeId);
if (storeId == null)
throw new ArgumentNullException(nameof(storeId));
using var ctx = _ContextFactory.CreateContext(); using var ctx = _ContextFactory.CreateContext();
return await ctx.StoreWebhooks return await ctx.StoreWebhooks
.Where(s => s.StoreId == storeId && s.WebhookId == webhookId) .Where(s => s.StoreId == storeId && s.WebhookId == webhookId)
@@ -301,8 +290,7 @@ namespace BTCPayServer.Services.Stores
} }
public async Task<WebhookData> GetWebhook(string webhookId) public async Task<WebhookData> GetWebhook(string webhookId)
{ {
if (webhookId == null) ArgumentNullException.ThrowIfNull(webhookId);
throw new ArgumentNullException(nameof(webhookId));
using var ctx = _ContextFactory.CreateContext(); using var ctx = _ContextFactory.CreateContext();
return await ctx.StoreWebhooks return await ctx.StoreWebhooks
.Where(s => s.WebhookId == webhookId) .Where(s => s.WebhookId == webhookId)
@@ -311,10 +299,8 @@ namespace BTCPayServer.Services.Stores
} }
public async Task DeleteWebhook(string storeId, string webhookId) public async Task DeleteWebhook(string storeId, string webhookId)
{ {
if (webhookId == null) ArgumentNullException.ThrowIfNull(webhookId);
throw new ArgumentNullException(nameof(webhookId)); ArgumentNullException.ThrowIfNull(storeId);
if (storeId == null)
throw new ArgumentNullException(nameof(storeId));
using var ctx = _ContextFactory.CreateContext(); using var ctx = _ContextFactory.CreateContext();
var hook = await ctx.StoreWebhooks var hook = await ctx.StoreWebhooks
.Where(s => s.StoreId == storeId && s.WebhookId == webhookId) .Where(s => s.StoreId == storeId && s.WebhookId == webhookId)
@@ -328,12 +314,9 @@ namespace BTCPayServer.Services.Stores
public async Task UpdateWebhook(string storeId, string webhookId, WebhookBlob webhookBlob) public async Task UpdateWebhook(string storeId, string webhookId, WebhookBlob webhookBlob)
{ {
if (webhookId == null) ArgumentNullException.ThrowIfNull(webhookId);
throw new ArgumentNullException(nameof(webhookId)); ArgumentNullException.ThrowIfNull(storeId);
if (storeId == null) ArgumentNullException.ThrowIfNull(webhookBlob);
throw new ArgumentNullException(nameof(storeId));
if (webhookBlob == null)
throw new ArgumentNullException(nameof(webhookBlob));
using var ctx = _ContextFactory.CreateContext(); using var ctx = _ContextFactory.CreateContext();
var hook = await ctx.StoreWebhooks var hook = await ctx.StoreWebhooks
.Where(s => s.StoreId == storeId && s.WebhookId == webhookId) .Where(s => s.StoreId == storeId && s.WebhookId == webhookId)

View File

@@ -18,8 +18,7 @@ namespace BTCPayServer.Services
public async Task SetWalletInfo(WalletId walletId, WalletBlobInfo blob) public async Task SetWalletInfo(WalletId walletId, WalletBlobInfo blob)
{ {
if (walletId == null) ArgumentNullException.ThrowIfNull(walletId);
throw new ArgumentNullException(nameof(walletId));
using (var ctx = _ContextFactory.CreateContext()) using (var ctx = _ContextFactory.CreateContext())
{ {
var walletData = new WalletData() { Id = walletId.ToString() }; var walletData = new WalletData() { Id = walletId.ToString() };
@@ -40,8 +39,7 @@ namespace BTCPayServer.Services
public async Task<Dictionary<string, WalletTransactionInfo>> GetWalletTransactionsInfo(WalletId walletId, string[] transactionIds = null) public async Task<Dictionary<string, WalletTransactionInfo>> GetWalletTransactionsInfo(WalletId walletId, string[] transactionIds = null)
{ {
if (walletId == null) ArgumentNullException.ThrowIfNull(walletId);
throw new ArgumentNullException(nameof(walletId));
using (var ctx = _ContextFactory.CreateContext()) using (var ctx = _ContextFactory.CreateContext())
{ {
return (await ctx.WalletTransactions return (await ctx.WalletTransactions
@@ -55,8 +53,7 @@ namespace BTCPayServer.Services
public async Task<WalletBlobInfo> GetWalletInfo(WalletId walletId) public async Task<WalletBlobInfo> GetWalletInfo(WalletId walletId)
{ {
if (walletId == null) ArgumentNullException.ThrowIfNull(walletId);
throw new ArgumentNullException(nameof(walletId));
using (var ctx = _ContextFactory.CreateContext()) using (var ctx = _ContextFactory.CreateContext())
{ {
var data = await ctx.Wallets var data = await ctx.Wallets
@@ -69,10 +66,8 @@ namespace BTCPayServer.Services
public async Task SetWalletTransactionInfo(WalletId walletId, string transactionId, WalletTransactionInfo walletTransactionInfo) public async Task SetWalletTransactionInfo(WalletId walletId, string transactionId, WalletTransactionInfo walletTransactionInfo)
{ {
if (walletId == null) ArgumentNullException.ThrowIfNull(walletId);
throw new ArgumentNullException(nameof(walletId)); ArgumentNullException.ThrowIfNull(transactionId);
if (transactionId == null)
throw new ArgumentNullException(nameof(transactionId));
using (var ctx = _ContextFactory.CreateContext()) using (var ctx = _ContextFactory.CreateContext())
{ {
var walletData = new WalletTransactionData() { WalletDataId = walletId.ToString(), TransactionId = transactionId }; var walletData = new WalletTransactionData() { WalletDataId = walletId.ToString(), TransactionId = transactionId };

View File

@@ -46,10 +46,8 @@ namespace BTCPayServer.Services.Wallets
public BTCPayWallet(ExplorerClient client, IMemoryCache memoryCache, BTCPayNetwork network, public BTCPayWallet(ExplorerClient client, IMemoryCache memoryCache, BTCPayNetwork network,
ApplicationDbContextFactory dbContextFactory, Logs logs) ApplicationDbContextFactory dbContextFactory, Logs logs)
{ {
if (client == null) ArgumentNullException.ThrowIfNull(client);
throw new ArgumentNullException(nameof(client)); ArgumentNullException.ThrowIfNull(memoryCache);
if (memoryCache == null)
throw new ArgumentNullException(nameof(memoryCache));
Logs = logs; Logs = logs;
_Client = client; _Client = client;
_Network = network; _Network = network;
@@ -73,8 +71,7 @@ namespace BTCPayServer.Services.Wallets
public async Task<KeyPathInformation> ReserveAddressAsync(DerivationStrategyBase derivationStrategy) public async Task<KeyPathInformation> ReserveAddressAsync(DerivationStrategyBase derivationStrategy)
{ {
if (derivationStrategy == null) ArgumentNullException.ThrowIfNull(derivationStrategy);
throw new ArgumentNullException(nameof(derivationStrategy));
var pathInfo = await _Client.GetUnusedAsync(derivationStrategy, DerivationFeature.Deposit, 0, true).ConfigureAwait(false); var pathInfo = await _Client.GetUnusedAsync(derivationStrategy, DerivationFeature.Deposit, 0, true).ConfigureAwait(false);
// Might happen on some broken install // Might happen on some broken install
if (pathInfo == null) if (pathInfo == null)
@@ -87,8 +84,7 @@ namespace BTCPayServer.Services.Wallets
public async Task<(BitcoinAddress, KeyPath)> GetChangeAddressAsync(DerivationStrategyBase derivationStrategy) public async Task<(BitcoinAddress, KeyPath)> GetChangeAddressAsync(DerivationStrategyBase derivationStrategy)
{ {
if (derivationStrategy == null) ArgumentNullException.ThrowIfNull(derivationStrategy);
throw new ArgumentNullException(nameof(derivationStrategy));
var pathInfo = await _Client.GetUnusedAsync(derivationStrategy, DerivationFeature.Change, 0, false).ConfigureAwait(false); var pathInfo = await _Client.GetUnusedAsync(derivationStrategy, DerivationFeature.Change, 0, false).ConfigureAwait(false);
// Might happen on some broken install // Might happen on some broken install
if (pathInfo == null) if (pathInfo == null)
@@ -109,8 +105,7 @@ namespace BTCPayServer.Services.Wallets
public async Task<TransactionResult> GetTransactionAsync(uint256 txId, bool includeOffchain = false, CancellationToken cancellation = default(CancellationToken)) public async Task<TransactionResult> GetTransactionAsync(uint256 txId, bool includeOffchain = false, CancellationToken cancellation = default(CancellationToken))
{ {
if (txId == null) ArgumentNullException.ThrowIfNull(txId);
throw new ArgumentNullException(nameof(txId));
var tx = await _Client.GetTransactionAsync(txId, cancellation); var tx = await _Client.GetTransactionAsync(txId, cancellation);
if (tx is null && includeOffchain) if (tx is null && includeOffchain)
{ {
@@ -252,8 +247,7 @@ namespace BTCPayServer.Services.Wallets
public async Task<ReceivedCoin[]> GetUnspentCoins(DerivationStrategyBase derivationStrategy, CancellationToken cancellation = default(CancellationToken)) public async Task<ReceivedCoin[]> GetUnspentCoins(DerivationStrategyBase derivationStrategy, CancellationToken cancellation = default(CancellationToken))
{ {
if (derivationStrategy == null) ArgumentNullException.ThrowIfNull(derivationStrategy);
throw new ArgumentNullException(nameof(derivationStrategy));
return (await GetUTXOChanges(derivationStrategy, cancellation)) return (await GetUTXOChanges(derivationStrategy, cancellation))
.GetUnspentUTXOs() .GetUnspentUTXOs()
.Select(c => new ReceivedCoin() .Select(c => new ReceivedCoin()

View File

@@ -20,8 +20,7 @@ namespace BTCPayServer.Services.Wallets
BTCPayNetworkProvider networkProvider, BTCPayNetworkProvider networkProvider,
Logs logs) Logs logs)
{ {
if (client == null) ArgumentNullException.ThrowIfNull(client);
throw new ArgumentNullException(nameof(client));
this.Logs = logs; this.Logs = logs;
_Client = client; _Client = client;
_NetworkProvider = networkProvider; _NetworkProvider = networkProvider;
@@ -40,14 +39,12 @@ namespace BTCPayServer.Services.Wallets
public BTCPayWallet GetWallet(BTCPayNetworkBase network) public BTCPayWallet GetWallet(BTCPayNetworkBase network)
{ {
if (network == null) ArgumentNullException.ThrowIfNull(network);
throw new ArgumentNullException(nameof(network));
return GetWallet(network.CryptoCode); return GetWallet(network.CryptoCode);
} }
public BTCPayWallet GetWallet(string cryptoCode) public BTCPayWallet GetWallet(string cryptoCode)
{ {
if (cryptoCode == null) ArgumentNullException.ThrowIfNull(cryptoCode);
throw new ArgumentNullException(nameof(cryptoCode));
_Wallets.TryGetValue(cryptoCode.ToUpperInvariant(), out var result); _Wallets.TryGetValue(cryptoCode.ToUpperInvariant(), out var result);
return result; return result;
} }

View File

@@ -9,8 +9,7 @@ namespace BTCPayServer
static readonly Regex _WalletStoreRegex = new Regex("^S-([a-zA-Z0-9]{30,60})-([a-zA-Z]{2,5})$"); static readonly Regex _WalletStoreRegex = new Regex("^S-([a-zA-Z0-9]{30,60})-([a-zA-Z]{2,5})$");
public static bool TryParse(string str, out WalletId walletId) public static bool TryParse(string str, out WalletId walletId)
{ {
if (str == null) ArgumentNullException.ThrowIfNull(str);
throw new ArgumentNullException(nameof(str));
walletId = null; walletId = null;
WalletId w = new WalletId(); WalletId w = new WalletId();
var match = _WalletStoreRegex.Match(str); var match = _WalletStoreRegex.Match(str);