Fix code smells
MODIFY
WalletWasabi.Tests/ExternalApiTests.cs
WalletWasabi.Tests/ExternalApiTests.cs
@@ -107,9 +107,10 @@ namespace WalletWasabi.Tests
}
}
}
- catch
+ catch(Exception ex)
{
- Logger.LogWarning<ExternalApiTests>($"Uri wasn't reachable: {uri}");
+ Logger.LogDebug<ExternalApiTests>($"Uri wasn't reachable: {uri}");
+ Logger.LogDebug<ExternalApiTests>(ex);
}
return false;
}

MODIFY
WalletWasabi.Tests/NodeBuilding/CoreNode.cs
WalletWasabi.Tests/NodeBuilding/CoreNode.cs
@@ -50,13 +50,9 @@ namespace WalletWasabi.Tests.NodeBuilding
}
private async Task CleanFolderAsync()
- {
- try
{
await IoHelpers.DeleteRecursivelyWithMagicDustAsync(Folder);
}
- catch (DirectoryNotFoundException) { }
- }
public async Task SyncAsync(CoreNode node, bool keepConnection = false)
{
@@ -106,7 +102,7 @@ namespace WalletWasabi.Tests.NodeBuilding
public async Task StartAsync()
{
- NodeConfigParameters config = new NodeConfigParameters
+ var config = new NodeConfigParameters
{
{"regtest", "1"},
{"rest", "1"},
@@ -131,11 +127,14 @@ namespace WalletWasabi.Tests.NodeBuilding
{
try
{
- await CreateRpcClient().GetBlockHashAsync(0).ConfigureAwait(false);
+ await CreateRpcClient().GetBlockHashAsync(0);
State = CoreNodeState.Running;
break;
}
- catch { }
+ catch
+ {
+
+ }
if (_process == null || _process.HasExited)
break;
}
@@ -144,9 +143,9 @@ namespace WalletWasabi.Tests.NodeBuilding
private Process _process;
private readonly string DataDir;
- private void FindPorts(int[] portArray)
+ private static void FindPorts(int[] portArray)
{
- int i = 0;
+ var i = 0;
while (i < portArray.Length)
{
var port = RandomUtils.GetUInt32() % 4000;
@@ -155,13 +154,16 @@ namespace WalletWasabi.Tests.NodeBuilding
continue;
try
{
- TcpListener listener = new TcpListener(IPAddress.Loopback, (int)port);
+ var listener = new TcpListener(IPAddress.Loopback, (int)port);
listener.Start();
listener.Stop();
portArray[i] = (int)port;
i++;
}
- catch (SocketException) { }
+ catch (SocketException)
+ {
+
+ }
}
}
@@ -171,7 +173,7 @@ namespace WalletWasabi.Tests.NodeBuilding
public Transaction GiveMoney(Script destination, Money amount, bool broadcast = true)
{
var rpc = CreateRpcClient();
- TransactionBuilder builder = new TransactionBuilder();
+ var builder = new TransactionBuilder();
builder.AddKeys(rpc.ListSecrets().OfType<ISecret>().ToArray());
builder.AddCoins(rpc.ListUnspent().Where(c => !_locked.Contains(c.OutPoint)).Select(c => c.AsCoin()));
builder.Send(destination, amount);
@@ -228,7 +230,7 @@ namespace WalletWasabi.Tests.NodeBuilding
public void Split(Money amount, int parts)
{
var rpc = CreateRpcClient();
- TransactionBuilder builder = new TransactionBuilder();
+ var builder = new TransactionBuilder();
builder.AddKeys(rpc.ListSecrets().OfType<ISecret>().ToArray());
builder.AddCoins(rpc.ListUnspent().Select(c => c.AsCoin()));
var secret = GetFirstSecret(rpc);
@@ -292,35 +294,6 @@ namespace WalletWasabi.Tests.NodeBuilding
_toMalleate.Add(txId);
}
- private Transaction DoMalleate(Transaction transaction)
- {
- transaction = transaction.Clone();
- if (!transaction.IsCoinBase)
- foreach (var input in transaction.Inputs)
- {
- List<Op> malleated = new List<Op>();
- foreach (var op in input.ScriptSig.ToOps())
- {
- try
- {
- var sig = new TransactionSignature(op.PushData);
- sig = MakeHighS(sig);
- malleated.Add(Op.GetPushOp(sig.ToBytes()));
- }
- catch { malleated.Add(op); }
- }
- input.ScriptSig = new Script(malleated.ToArray());
- }
- return transaction;
- }
-
- private TransactionSignature MakeHighS(TransactionSignature sig)
- {
- var curveOrder = new NBitcoin.BouncyCastle.Math.BigInteger("115792089237316195423570985008687907852837564279074904382605163141518161494337", 10);
- var ecdsa = new ECDSASignature(sig.Signature.R, sig.Signature.S.Negate().Mod(curveOrder));
- return new TransactionSignature(ecdsa, sig.SigHash);
- }
-
public void BroadcastBlocks(IEnumerable<Block> blocks)
{
using (var node = CreateNodeClient())
@@ -368,42 +341,6 @@ namespace WalletWasabi.Tests.NodeBuilding
public List<TransactionNode> DependsOn = new List<TransactionNode>();
}
- private List<Transaction> Reorder(List<Transaction> txs)
- {
- if (txs.Count == 0)
- return txs;
- var result = new List<Transaction>();
- var dictionary = txs.ToDictionary(t => t.GetHash(), t => new TransactionNode(t));
- foreach (var transaction in dictionary.Select(d => d.Value))
- {
- foreach (var input in transaction.Transaction.Inputs)
- {
- var node = dictionary.TryGet(input.PrevOut.Hash);
- if (node != null)
- {
- transaction.DependsOn.Add(node);
- }
- }
- }
- while (dictionary.Count != 0)
- {
- foreach (var node in dictionary.Select(d => d.Value).ToList())
- {
- foreach (var parent in node.DependsOn.ToList())
- {
- if (!dictionary.ContainsKey(parent.Hash))
- node.DependsOn.Remove(parent);
- }
- if (node.DependsOn.Count == 0)
- {
- result.Add(node.Transaction);
- dictionary.Remove(node.Hash);
- }
- }
- }
- return result;
- }
-
private BitcoinSecret GetFirstSecret(RPCClient rpc)
{
if (MinerSecret != null)

MODIFY
WalletWasabi.Tests/NodeBuilding/NodeBuilder.cs
WalletWasabi.Tests/NodeBuilding/NodeBuilder.cs
@@ -51,13 +51,15 @@ namespace WalletWasabi.Tests.NodeBuilding
if (File.Exists(bitcoind))
return bitcoind;
zip = Path.Combine(SharedFixture.DataDir, $"bitcoin-{version}-win32.zip");
- string url = string.Format("https://bitcoin.org/bin/bitcoin-core-{0}/" + Path.GetFileName(zip), version);
- HttpClient client = new HttpClient();
+ var url = string.Format("https://bitcoin.org/bin/bitcoin-core-{0}/" + Path.GetFileName(zip), version);
+ using (var client = new HttpClient())
+ {
client.Timeout = TimeSpan.FromMinutes(10.0);
var data = await client.GetByteArrayAsync(url);
await File.WriteAllBytesAsync(zip, data);
ZipFile.ExtractToDirectory(zip, new FileInfo(zip).Directory.FullName);
}
+ }
else
{
bitcoind = Path.Combine(SharedFixture.DataDir, $"bitcoin-{version}", "bin", "bitcoind");
@@ -68,13 +70,16 @@ namespace WalletWasabi.Tests.NodeBuilding
Path.Combine(SharedFixture.DataDir, $"bitcoin-{version}-x86_64-linux-gnu.tar.gz")
: Path.Combine(SharedFixture.DataDir, $"bitcoin-{version}-osx64.tar.gz");
- string url = string.Format("https://bitcoin.org/bin/bitcoin-core-{0}/" + Path.GetFileName(zip), version);
- HttpClient client = new HttpClient();
+ var url = string.Format("https://bitcoin.org/bin/bitcoin-core-{0}/" + Path.GetFileName(zip), version);
+ using (var client = new HttpClient())
+ {
client.Timeout = TimeSpan.FromMinutes(10.0);
var data = await client.GetByteArrayAsync(url);
await File.WriteAllBytesAsync(zip, data);
+
Process.Start("tar", "-zxvf " + zip + " -C " + SharedFixture.DataDir).WaitForExit();
}
+ }
File.Delete(zip);
return bitcoind;
}

MODIFY
WalletWasabi.Tests/RegTests.cs
WalletWasabi.Tests/RegTests.cs
@@ -1165,8 +1165,8 @@ namespace WalletWasabi.Tests
// Enough money (one confirmed coin and one unconfirmed coin, unconfirmed are allowed)
var btx = await wallet.BuildTransactionAsync(password, operations, 2, true);
Assert.Equal(2, btx.SpentCoins.Count());
- Assert.Equal(1, btx.SpentCoins.Count(c => c.Confirmed == true));
- Assert.Equal(1, btx.SpentCoins.Count(c => c.Confirmed == false));
+ Assert.Equal(1, btx.SpentCoins.Count(c => c.Confirmed));
+ Assert.Equal(1, btx.SpentCoins.Count(c => !c.Confirmed));
// Only one operation with Zero money
operations = new[]{
@@ -1539,7 +1539,8 @@ namespace WalletWasabi.Tests
mempoolTxId.ToString()
});
- var coordinatorToTest = new CcjCoordinator(network, folder, rpc, coordinator.RoundConfig);
+ using (var coordinatorToTest = new CcjCoordinator(network, folder, rpc, coordinator.RoundConfig))
+ {
var txIds = await File.ReadAllLinesAsync(cjfile);
Assert.Contains(coinbaseTxId.ToString(), txIds);
@@ -1554,12 +1555,14 @@ namespace WalletWasabi.Tests
"This line is invalid (the file is corrupted)",
offchainTxId.ToString(),
});
- coordinatorToTest = new CcjCoordinator(network, folder, rpc, coordinatorToTest.RoundConfig);
+ var coordinatorToTest2 = new CcjCoordinator(network, folder, rpc, coordinatorToTest.RoundConfig);
+ coordinatorToTest2.Dispose();
txIds = await File.ReadAllLinesAsync(cjfile);
Assert.Single(txIds);
Assert.Contains(coinbaseTxId.ToString(), txIds);
Assert.DoesNotContain(offchainTxId.ToString(), txIds);
Assert.DoesNotContain("This line is invalid (the file is corrupted)", txIds);
+ }
Logger.TurnOn();
}

MODIFY
WalletWasabi/Bases/ByteArraySerializableBase.cs
WalletWasabi/Bases/ByteArraySerializableBase.cs
@@ -9,7 +9,7 @@ namespace WalletWasabi.Bases
{
#region ConstructorsAndInitializers
- public ByteArraySerializableBase()
+ protected ByteArraySerializableBase()
{
}

MODIFY
WalletWasabi/Bases/OctetSerializableBase.cs
WalletWasabi/Bases/OctetSerializableBase.cs
@@ -14,7 +14,7 @@ namespace WalletWasabi.Bases
#region ConstructorsAndInitializers
- public OctetSerializableBase()
+ protected OctetSerializableBase()
{
}

MODIFY
WalletWasabi/Extensions/HttpStatusCodeExtensions.cs
WalletWasabi/Extensions/HttpStatusCodeExtensions.cs
@@ -6,8 +6,10 @@ namespace System.Net
{
public static string ToReasonString(this HttpStatusCode me)
{
- var message = new HttpResponseMessage(me);
+ using (var message = new HttpResponseMessage(me))
+ {
return message.ReasonPhrase;
}
}
}
+}
\ No newline at end of file

MODIFY
WalletWasabi/Extensions/RPCClientExtensions.cs
WalletWasabi/Extensions/RPCClientExtensions.cs
@@ -11,7 +11,7 @@ namespace NBitcoin.RPC
/// <returns>Returns the current block on timeout or exit</returns>
public static async Task<BlockInfo> WaitForNewBlockAsync(this RPCClient rpc, long timeout = 0)
{
- var resp = await rpc.SendCommandAsync("waitfornewblock", timeout).ConfigureAwait(false);
+ var resp = await rpc.SendCommandAsync("waitfornewblock", timeout);
return new BlockInfo
{
Height = int.Parse(resp.Result["height"].ToString()),
@@ -27,7 +27,7 @@ namespace NBitcoin.RPC
/// <returns>Returns the current block on timeout or exit</returns>
public static async Task<BlockInfo> WaitForBlockAsync(this RPCClient rpc, uint256 blockhash, long timeout = 0)
{
- var resp = await rpc.SendCommandAsync("waitforblock", blockhash.ToString(), timeout).ConfigureAwait(false);
+ var resp = await rpc.SendCommandAsync("waitforblock", blockhash.ToString(), timeout);
return new BlockInfo
{
Height = int.Parse(resp.Result["height"].ToString()),

MODIFY
WalletWasabi/Helpers/HttpMessageHelper.cs
WalletWasabi/Helpers/HttpMessageHelper.cs
@@ -45,6 +45,8 @@ namespace System.Net.Http
{
var headers = "";
var firstRead = true;
+ var builder = new StringBuilder();
+ builder.Append(headers);
while (true)
{
string header = await ReadCRLFLineAsync(stream, Encoding.ASCII, ctsToken);
@@ -72,8 +74,9 @@ namespace System.Net.Http
firstRead = false;
}
- headers += header + CRLF; // CRLF is part of the headerstring
+ builder.Append(header + CRLF); // CRLF is part of the headerstring
}
+ headers = builder.ToString();
if (headers == null || headers == "")
{
headers = "";

MODIFY
WalletWasabi/Helpers/NBitcoinHelpers.cs
WalletWasabi/Helpers/NBitcoinHelpers.cs
@@ -26,13 +26,13 @@ namespace WalletWasabi.Helpers
{
return BitcoinAddress.Create(address, Network.RegTest);
}
- catch
+ catch(FormatException)
{
try
{
return BitcoinAddress.Create(address, Network.TestNet);
}
- catch
+ catch(FormatException)
{
return BitcoinAddress.Create(address, Network.Main);
}

MODIFY
WalletWasabi/Http/Models/HeaderSection.cs
WalletWasabi/Http/Models/HeaderSection.cs
@@ -126,10 +126,11 @@ namespace WalletWasabi.Http.Models
public HttpRequestContentHeaders ToHttpRequestHeaders()
{
- var message = new HttpRequestMessage()
+ using (var message = new HttpRequestMessage
{
Content = new ByteArrayContent(new byte[] { })
- };
+ })
+ {
message.Content.Headers.ContentLength = null;
foreach (var field in Fields)
{
@@ -146,12 +147,14 @@ namespace WalletWasabi.Http.Models
ContentHeaders = message.Content.Headers
};
}
+ }
public HttpResponseContentHeaders ToHttpResponseHeaders()
{
- var message = new HttpResponseMessage()
+ using (var message = new HttpResponseMessage
{
Content = new ByteArrayContent(new byte[] { })
- };
+ })
+ {
message.Content.Headers.ContentLength = null;
foreach (var field in Fields)
{
@@ -168,11 +171,11 @@ namespace WalletWasabi.Http.Models
ContentHeaders = message.Content.Headers
};
}
+ }
public static HeaderSection CreateNew(HttpHeaders headers)
{
var hs = new HeaderSection();
- var message = new HttpRequestMessage();
foreach (var header in headers)
{
hs.Fields.Add(new HeaderField(header.Key, string.Join(",", header.Value)));

MODIFY
WalletWasabi/TorSocks5/TorHttpClient.cs
WalletWasabi/TorSocks5/TorHttpClient.cs
@@ -201,8 +201,10 @@ namespace WalletWasabi.TorSocks5
await TorSocks5Client.Stream.WriteAsync(bytes, 0, bytes.Length);
await TorSocks5Client.Stream.FlushAsync();
-
- return await new HttpResponseMessage().CreateNewAsync(TorSocks5Client.Stream, request.Method);
+ using (var httpResponseMessage = new HttpResponseMessage())
+ {
+ return await httpResponseMessage.CreateNewAsync(TorSocks5Client.Stream, request.Method);
+ }
}
#region IDisposable Support
@@ -223,7 +225,7 @@ namespace WalletWasabi.TorSocks5
}
// ~TorHttpClient() {
- // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
+ // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }

MODIFY
WalletWasabi/WebClients/BlockCypher/BlockCypherClient.cs
WalletWasabi/WebClients/BlockCypher/BlockCypherClient.cs
@@ -78,7 +78,7 @@ namespace WalletWasabi.WebClients.BlockCypher
// override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~BlockCypherClient() {
- // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
+ // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }

Fix code smells