Commit a7ce9631 authored by Pavel Pavlov's avatar Pavel Pavlov

Merge DeStream-Blockchain with solution Stratis.Bitcoin.FullNode

- NBitcoin
	- move folder JsonConverters
	- remove Protobuf
	- move RPC
- NBitcoin.Tests
- Stratis.Bitcoin.Features.Notification
- Stratis.Bitcoin.Features.Notifications.Tests
- Stratis.Bitcoin.Features.Dns
- Stratis.Bitcoin.Features.Dns.Tests
- Stratis.Bitcoin.Features.BlockStore
	- added BlockStoreQueue.cs
	- remove BlockPair.cs
	- remove BlockStoreLoop.cs
	- remove BlockStoreLoopStep.cs
	- remove BlockStoreLoopStats.cs
	- remove \LoopSteps\BlockStoreInnerStepContext.cs
	- remove \LoopSteps\BlockStoreInnerStepFindBlocks.cs
	- remove \LoopSteps\BlockStoreInnerStepReadBlocks.cs
	- remove \LoopSteps\CheckNextChainedBlockExistStep.cs
	- remove \LoopSteps\DownloadBlockStep.cs
	- remove \LoopSteps\ProcessPendingStorageStep.cs
	- remove \LoopSteps\ReorganiseBlockRepositoryStep.cs
- Stratis.Bitcoin.Features.Consensus
	- added RuleContextOverrides.cs
	- added CoinviewRule.cs
	- added PosCoinviewRule.cs
	- added PowCoinviewRule.cs
	- remove Checkpoints.cs
	- remove ConsensusManager.cs
	- remove ConsensusPerformanceCounter.cs
	- remove ConsensusSettings.cs
	- remove ContextualInformation.cs
	- remove IPosConsensusValidator.cs
	- remove IPowConsensusValidator.cs
	- remove PosConsensusValidator.cs
	- remove IConsensusRules.cs
	- remove PowConsensusValidator.cs
- Stratis.Bitcoin.Features.Api
- Stratis.Bitcoin.Api.Tests
- Stratis.Bitcoin.Features.LightWallet
- Stratis.Bitcoin.Features.MemoryPool
- Stratis.Bitcoin.Features.Miner
- Stratis.Bitcoin.Features.RPC
- Stratis.Bitcoin.Features.Wallet
- Stratis.Bitcoin.Features.WatchOnlyWallet

- Stratis.Bitcoin
- Stratis.Bitcoin.Cli
- Stratis.BitcoinD
- Stratis.BreezeD
- Stratis.StratisD
- Stratis.StratisDnsD
parent 2cfa0f42
......@@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AssemblyName>DeStream.Bitcoin.Cli</AssemblyName>
<RootNamespace>DeStream.Bitcoin.Cli</RootNamespace>
</PropertyGroup>
......
......@@ -5,13 +5,13 @@ using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using NBitcoin;
using NBitcoin.RPC;
using Newtonsoft.Json;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Features.RPC;
using Stratis.Bitcoin.Utilities.Extensions;
using DeStream.Stratis.Bitcoin.Configuration;
namespace DeStream.Bitcoin.Cli
{
......
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AssemblyName>DeStream.BreezeD</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>DeStream.BreezeD</PackageId>
......
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AssemblyName>DeStream.DeStreamD</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>DeStream.DeStreamD</PackageId>
......

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2010
VisualStudioVersion = 15.0.27130.2024
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "global", "global", "{5B331FD3-D493-46A9-928B-B786FC6F3103}"
ProjectSection(SolutionItems) = preProject
......@@ -101,6 +101,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Stratis.Bitcoin.Tests.Commo
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Stratis.Bitcoin.Tests.Wallet.Common", "Stratis.Bitcoin.Tests.Wallet.Common\Stratis.Bitcoin.Tests.Wallet.Common.csproj", "{F1755154-88DC-4434-98FB-7D22C95BA640}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Stratis.Bitcoin.IntegrationTests.Common", "Stratis.Bitcoin.IntegrationTests.Common\Stratis.Bitcoin.IntegrationTests.Common.csproj", "{F7DD01DA-B888-4817-A5FA-3A87B69BFCA7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -259,6 +261,10 @@ Global
{F1755154-88DC-4434-98FB-7D22C95BA640}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F1755154-88DC-4434-98FB-7D22C95BA640}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F1755154-88DC-4434-98FB-7D22C95BA640}.Release|Any CPU.Build.0 = Release|Any CPU
{F7DD01DA-B888-4817-A5FA-3A87B69BFCA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F7DD01DA-B888-4817-A5FA-3A87B69BFCA7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F7DD01DA-B888-4817-A5FA-3A87B69BFCA7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F7DD01DA-B888-4817-A5FA-3A87B69BFCA7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......@@ -298,6 +304,7 @@ Global
{978482B2-AE17-421E-AD6F-ED9667C6B8A1} = {A0CEDD86-D446-436E-8C35-261B30CEE5D3}
{B6FB52FE-F754-49B0-A65F-02F5C82B33EE} = {EAE139C2-B19C-4905-9117-8A4068ABD3D2}
{F1755154-88DC-4434-98FB-7D22C95BA640} = {EAE139C2-B19C-4905-9117-8A4068ABD3D2}
{F7DD01DA-B888-4817-A5FA-3A87B69BFCA7} = {EAE139C2-B19C-4905-9117-8A4068ABD3D2}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6C780ABA-5872-4B83-AD3F-A5BD423AD907}
......
......@@ -26,7 +26,7 @@ namespace NBitcoin.Tests
for(int i = 0; i < actual.Length; i++)
{
if(!Object.Equals(actual[i], expected[i]))
if(!Equals(actual[i], expected[i]))
Assert.False(true, "Actual[" + i + "](" + actual[i] + ") != Expected[" + i + "](" + expected[i] + ")");
}
}
......@@ -34,9 +34,9 @@ namespace NBitcoin.Tests
[DebuggerHidden]
internal static void StackEquals(ContextStack<byte[]> stack1, ContextStack<byte[]> stack2)
{
var hash1 = stack1.Select(o => Hashes.Hash256(o)).ToArray();
var hash2 = stack2.Select(o => Hashes.Hash256(o)).ToArray();
AssertEx.CollectionEquals(hash1, hash2);
uint256[] hash1 = stack1.Select(o => Hashes.Hash256(o)).ToArray();
uint256[] hash2 = stack2.Select(o => Hashes.Hash256(o)).ToArray();
CollectionEquals(hash1, hash2);
}
internal static void CollectionEquals(System.Collections.BitArray bitArray, int p)
......
......@@ -9,8 +9,8 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void AssetMoneyToStringTest()
{
OpenAsset.AssetId assetId = new OpenAsset.AssetId("8f316d9a09");
OpenAsset.AssetMoney assetMoney = new OpenAsset.AssetMoney(assetId, 1);
var assetId = new OpenAsset.AssetId("8f316d9a09");
var assetMoney = new OpenAsset.AssetMoney(assetId, 1);
String actual = assetMoney.ToString();
Assert.Equal("1-8f316d9a09", actual);
......@@ -20,8 +20,8 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void AssetMoneyMultiply()
{
OpenAsset.AssetId assetId = new OpenAsset.AssetId("8f316d9a09");
OpenAsset.AssetMoney assetMoney = new OpenAsset.AssetMoney(assetId, 2);
var assetId = new OpenAsset.AssetId("8f316d9a09");
var assetMoney = new OpenAsset.AssetMoney(assetId, 2);
OpenAsset.AssetMoney actual = assetMoney * 2;
......@@ -35,9 +35,9 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void AssetMoneyGreaterThan()
{
OpenAsset.AssetId assetId = new OpenAsset.AssetId("8f316d9a09");
OpenAsset.AssetMoney smallAssetMoney = new OpenAsset.AssetMoney(assetId, 2);
OpenAsset.AssetMoney largeAssetMoney = new OpenAsset.AssetMoney(assetId, 5);
var assetId = new OpenAsset.AssetId("8f316d9a09");
var smallAssetMoney = new OpenAsset.AssetMoney(assetId, 2);
var largeAssetMoney = new OpenAsset.AssetMoney(assetId, 5);
Assert.True(largeAssetMoney > smallAssetMoney);
Assert.False(smallAssetMoney > largeAssetMoney);
......@@ -47,9 +47,9 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void AssetMoneyLessThan()
{
OpenAsset.AssetId assetId = new OpenAsset.AssetId("8f316d9a09");
OpenAsset.AssetMoney smallAssetMoney = new OpenAsset.AssetMoney(assetId, 2);
OpenAsset.AssetMoney largeAssetMoney = new OpenAsset.AssetMoney(assetId, 5);
var assetId = new OpenAsset.AssetId("8f316d9a09");
var smallAssetMoney = new OpenAsset.AssetMoney(assetId, 2);
var largeAssetMoney = new OpenAsset.AssetMoney(assetId, 5);
Assert.True(smallAssetMoney < largeAssetMoney);
Assert.False(largeAssetMoney < smallAssetMoney);
......
......@@ -44,10 +44,10 @@ namespace NBitcoin.Tests
Parallel.ForEach(tests, test =>
{
var secret = new BitcoinSecret(test.Unencrypted, Network.Main);
var encryptedKey = secret.PrivateKey.GetEncryptedBitcoinSecret(test.Passphrase, Network.Main);
BitcoinEncryptedSecretNoEC encryptedKey = secret.PrivateKey.GetEncryptedBitcoinSecret(test.Passphrase, Network.Main);
Assert.Equal(test.Encrypted, encryptedKey.ToString());
var actualSecret = encryptedKey.GetKey(test.Passphrase);
Key actualSecret = encryptedKey.GetKey(test.Passphrase);
Assert.Equal(test.Unencrypted, actualSecret.GetBitcoinSecret(Network.Main).ToString());
Assert.Equal(test.Compressed, actualSecret.IsCompressed);
......@@ -61,7 +61,7 @@ namespace NBitcoin.Tests
public void DoNotThrowFormatExceptionIfNetworkInformationNotPresentInBase58()
{
Network network = Network.TestNet;
var encryptedPrivateKey = new Key().GetEncryptedBitcoinSecret("abc123", network).ToString();
string encryptedPrivateKey = new Key().GetEncryptedBitcoinSecret("abc123", network).ToString();
Key key = Key.Parse(encryptedPrivateKey, "abc123", network);
}
......@@ -69,11 +69,11 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void KeyParseWorksOnBothTypeOfEncryptedKey()
{
var encryptedkey = new Key().GetEncryptedBitcoinSecret("abc", Network.Main);
BitcoinEncryptedSecretNoEC encryptedkey = new Key().GetEncryptedBitcoinSecret("abc", Network.Main);
Key.Parse(encryptedkey.ToString(), "abc", Network.Main);
var code = new BitcoinPassphraseCode("abc", Network.Main, null);
var encryptedkey2 = code.GenerateEncryptedSecret().EncryptedKey;
BitcoinEncryptedSecretEC encryptedkey2 = code.GenerateEncryptedSecret().EncryptedKey;
Key.Parse(encryptedkey2.ToString(), "abc", Network.Main);
}
......@@ -105,7 +105,7 @@ namespace NBitcoin.Tests
//Can generate unencrypted key with password and encrypted key
var encryptedKey = new BitcoinEncryptedSecretEC(test.Encrypted, Network.Main);
Assert.Null(encryptedKey.LotSequence);
var actualKey = encryptedKey.GetKey(test.Passphrase);
Key actualKey = encryptedKey.GetKey(test.Passphrase);
Assert.Equal(test.Unencrypted, actualKey.GetBitcoinSecret(Network.Main).ToString());
Assert.Equal(test.Address, actualKey.PubKey.GetAddress(Network.Main).ToString());
Assert.Equal(test.Compressed, actualKey.IsCompressed);
......@@ -118,7 +118,7 @@ namespace NBitcoin.Tests
Assert.Equal(passCode.ToString(), actualPassCode.ToString());
//Can generate encrypted key from passcode
var generatedEncryptedKey = passCode.GenerateEncryptedSecret(test.Compressed).EncryptedKey;
BitcoinEncryptedSecretEC generatedEncryptedKey = passCode.GenerateEncryptedSecret(test.Compressed).EncryptedKey;
AssertEx.CollectionEquals(passCode.OwnerEntropy, generatedEncryptedKey.OwnerEntropy);
Assert.Equal(test.Compressed, generatedEncryptedKey.IsCompressed);
}
......@@ -157,7 +157,7 @@ namespace NBitcoin.Tests
//Can generate unencrypted key with password and encrypted key
var encryptedKey = new BitcoinEncryptedSecretEC(test.Encrypted, Network.Main);
AssertSequenceEquals(test.LotSequence, encryptedKey.LotSequence);
var actualKey = encryptedKey.GetKey(test.Passphrase);
Key actualKey = encryptedKey.GetKey(test.Passphrase);
Assert.Equal(test.Unencrypted, actualKey.GetBitcoinSecret(Network.Main).ToString());
Assert.Equal(test.Address, actualKey.PubKey.GetAddress(Network.Main).ToString());
Assert.Equal(test.Compressed, actualKey.IsCompressed);
......@@ -175,7 +175,7 @@ namespace NBitcoin.Tests
Assert.True(confirmation.Check(test.Passphrase, new BitcoinPubKeyAddress(test.Address, Network.Main)));
//Can generate encrypted key from passcode
var generatedEncryptedKey = passCode.GenerateEncryptedSecret(test.Compressed).EncryptedKey;
BitcoinEncryptedSecretEC generatedEncryptedKey = passCode.GenerateEncryptedSecret(test.Compressed).EncryptedKey;
AssertEx.CollectionEquals(passCode.OwnerEntropy, generatedEncryptedKey.OwnerEntropy);
Assert.Equal(test.Compressed, generatedEncryptedKey.IsCompressed);
}
......@@ -193,7 +193,7 @@ namespace NBitcoin.Tests
public void CanParseLotSequence()
{
var sequence = new LotSequence(1048575, 1024);
var bytes = sequence.ToBytes();
byte[] bytes = sequence.ToBytes();
var sequence2 = new LotSequence(bytes);
Assert.True(sequence.Lot == sequence2.Lot && sequence.Sequence == sequence.Sequence);
}
......@@ -203,23 +203,23 @@ namespace NBitcoin.Tests
public void EncryptedSecretECmultiplyNoLotSimple()
{
var compressedValues = new[] { false, true };
foreach(var compressed in compressedValues)
foreach(bool compressed in compressedValues)
{
var code = new BitcoinPassphraseCode("test", Network.Main, null);
Assert.Null(code.LotSequence);
var result = code.GenerateEncryptedSecret(compressed);
EncryptedKeyResult result = code.GenerateEncryptedSecret(compressed);
Assert.True(result.ConfirmationCode.Check("test", result.GeneratedAddress));
Assert.False(result.ConfirmationCode.Check("toto", result.GeneratedAddress));
Assert.False(result.ConfirmationCode.Check("test", new Key().PubKey.GetAddress(Network.Main)));
var decryptedKey = result.EncryptedKey.GetKey("test");
Key decryptedKey = result.EncryptedKey.GetKey("test");
Assert.Equal(result.GeneratedAddress.ToString(), decryptedKey.PubKey.GetAddress(Network.Main).ToString());
Assert.Throws<SecurityException>(() => result.EncryptedKey.GetKey("wrong"));
//Can regenerate same result with same seed
var result2 = code.GenerateEncryptedSecret(compressed, seedb: result.Seed);
var decryptedKey2 = result.EncryptedKey.GetKey("test");
EncryptedKeyResult result2 = code.GenerateEncryptedSecret(compressed, seedb: result.Seed);
Key decryptedKey2 = result.EncryptedKey.GetKey("test");
AssertEx.CollectionEquals(decryptedKey2.ToBytes(), decryptedKey.ToBytes());
}
}
......@@ -231,8 +231,8 @@ namespace NBitcoin.Tests
//Test easily debuggable
var seed = new byte[24];
var derived = new byte[64];
var encrypted = BitcoinEncryptedSecret.EncryptSeed(seed, derived);
var actualSeed = BitcoinEncryptedSecret.DecryptSeed(encrypted, derived);
byte[] encrypted = BitcoinEncryptedSecret.EncryptSeed(seed, derived);
byte[] actualSeed = BitcoinEncryptedSecret.DecryptSeed(encrypted, derived);
Assert.Equal(seed, actualSeed);
//The real deal
......@@ -242,7 +242,7 @@ namespace NBitcoin.Tests
derived = RandomUtils.GetBytes(64);
encrypted = BitcoinEncryptedSecret.EncryptSeed(seed, derived);
var encryptedBefore = encrypted.ToArray();
byte[] encryptedBefore = encrypted.ToArray();
for(int u = 8; u < 16; u++)
{
encrypted[u] = 0;
......@@ -260,8 +260,8 @@ namespace NBitcoin.Tests
//Test easily debuggable
var key = new byte[32];
var derived = new byte[64];
var encrypted = BitcoinEncryptedSecret.EncryptKey(key, derived);
var actualSeed = BitcoinEncryptedSecret.DecryptKey(encrypted, derived);
byte[] encrypted = BitcoinEncryptedSecret.EncryptKey(key, derived);
byte[] actualSeed = BitcoinEncryptedSecret.DecryptKey(encrypted, derived);
Assert.Equal(key, actualSeed);
//The real deal
......
......@@ -41,7 +41,7 @@ namespace NBitcoin.Tests
[Fact]
public void CanDetectError()
{
var bech = Encoders.Bech32("bc");
Bech32Encoder bech = Encoders.Bech32("bc");
byte wit;
var ex = Assert.Throws<Bech32FormatException>(() => bech.Decode("bc1zw508e6qejxtdg4y5r3zarvaryvg6kdaj", out wit));
Assert.Single(ex.ErrorIndexes);
......@@ -56,41 +56,41 @@ namespace NBitcoin.Tests
[Fact]
public void ValidateValidChecksum()
{
foreach(var test in VALID_CHECKSUM)
foreach(string test in VALID_CHECKSUM)
{
var bech = Bech32Encoder.ExtractEncoderFromString(test);
var pos = test.LastIndexOf('1');
var test2 = test.Substring(0, pos + 1) + ((test[pos + 1]) ^ 1) + test.Substring(pos + 2);
Bech32Encoder bech = Bech32Encoder.ExtractEncoderFromString(test);
int pos = test.LastIndexOf('1');
string test2 = test.Substring(0, pos + 1) + ((test[pos + 1]) ^ 1) + test.Substring(pos + 2);
Assert.Throws<FormatException>(() => bech.DecodeData(test2));
}
}
Bech32Encoder bech32 = Encoders.Bech32("bc");
Bech32Encoder tbech32 = Encoders.Bech32("tb");
private Bech32Encoder bech32 = Encoders.Bech32("bc");
private Bech32Encoder tbech32 = Encoders.Bech32("tb");
[Fact]
public void ValidAddress()
{
foreach(var address in VALID_ADDRESS)
foreach(string[] address in VALID_ADDRESS)
{
byte witVer;
byte[] witProg;
Bech32Encoder encoder = bech32;
Bech32Encoder encoder = this.bech32;
try
{
witProg = bech32.Decode(address[0], out witVer);
encoder = bech32;
witProg = this.bech32.Decode(address[0], out witVer);
encoder = this.bech32;
}
catch
{
witProg = tbech32.Decode(address[0], out witVer);
encoder = tbech32;
witProg = this.tbech32.Decode(address[0], out witVer);
encoder = this.tbech32;
}
var scriptPubkey = Scriptpubkey(witVer, witProg);
var hex = string.Join("", scriptPubkey.Select(x => x.ToString("x2")));
byte[] scriptPubkey = Scriptpubkey(witVer, witProg);
string hex = string.Join("", scriptPubkey.Select(x => x.ToString("x2")));
Assert.Equal(hex, address[1]);
var addr = encoder.Encode(witVer, witProg);
string addr = encoder.Encode(witVer, witProg);
Assert.Equal(address[0].ToLowerInvariant(), addr);
}
}
......@@ -98,17 +98,17 @@ namespace NBitcoin.Tests
[Fact]
public void InvalidAddress()
{
foreach(var test in INVALID_ADDRESS)
foreach(string test in INVALID_ADDRESS)
{
byte witver;
try
{
bech32.Decode(test, out witver);
this.bech32.Decode(test, out witver);
}
catch(FormatException) { }
try
{
tbech32.Decode(test, out witver);
this.tbech32.Decode(test, out witver);
}
catch(FormatException) { }
}
......@@ -116,7 +116,7 @@ namespace NBitcoin.Tests
private static byte[] Scriptpubkey(byte witver, byte[] witprog)
{
var v = witver > 0 ? witver + 0x50 : 0;
int v = witver > 0 ? witver + 0x50 : 0;
return (new[] { (byte)v, (byte)witprog.Length }).Concat(witprog);
}
}
......
This diff is collapsed.
This diff is collapsed.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NBitcoin;
using Xunit;
namespace Stratis.Bitcoin.IntegrationTests
namespace NBitcoin.Tests
{
public class ConstructorsForSerializableClassesTest
{
......@@ -14,23 +12,24 @@ namespace Stratis.Bitcoin.IntegrationTests
{
// This list contain types that inherit IBitcoinSerializable but don't have a public
// parameterless constructor for a good reason so they should not fail this test.
List<Type> exceptionalTypes = new List<Type>()
var exceptionalTypes = new List<Type>()
{
typeof(NBitcoin.ExtKey),
typeof(NBitcoin.ExtPubKey),
typeof(NBitcoin.PubKey),
typeof(NBitcoin.PosBlock),
typeof(NBitcoin.PosBlockHeader),
typeof(NBitcoin.PosTransaction),
typeof(NBitcoin.Protocol.CompactVarInt),
typeof(BlockHeader),
typeof(ExtKey),
typeof(ExtPubKey),
typeof(PubKey),
typeof(PosBlock),
typeof(PosBlockHeader),
typeof(PosTransaction),
typeof(Protocol.CompactVarInt),
};
var types = AppDomain.CurrentDomain.GetAssemblies()
.Where(x =>x.FullName.Contains("Stratis") || x.FullName.Contains("NBitcoin"))
IEnumerable<Type> types = AppDomain.CurrentDomain.GetAssemblies()
.Where(x => x.FullName.Contains("Stratis") || x.FullName.Contains("NBitcoin"))
.SelectMany(s => s.GetTypes())
.Where(p => typeof(IBitcoinSerializable).IsAssignableFrom(p) && !p.IsInterface && p.IsClass);
foreach (var type in types)
foreach (Type type in types)
{
if (exceptionalTypes.Contains(type))
continue;
......@@ -41,23 +40,5 @@ namespace Stratis.Bitcoin.IntegrationTests
"but doesn't have a parameterless constructor which is needed for serialization and deserialization process!");
}
}
/// <summary>
/// Serializes input and returns deserialized object.
/// </summary>
/// <remarks>Needed for troubleshooting this test.</remarks>
private T CloneViaSerializeDeserialize<T>(T input) where T : IBitcoinSerializable
{
MemoryStream ms = new MemoryStream();
BitcoinStream bitcoinStream = new BitcoinStream(ms, true);
input.ReadWrite(bitcoinStream);
ms.Position = 0;
bitcoinStream = new BitcoinStream(bitcoinStream.Inner, false);
var obj = Activator.CreateInstance<T>();
obj.ReadWrite(bitcoinStream);
return obj;
}
}
}
......@@ -86,13 +86,13 @@ namespace NBitcoin.Tests
foreach(var test in tests)
{
var input = Encoding.UTF8.GetBytes(test.Input);
var encoded = test.Encoder.EncodeData(input);
byte[] input = Encoding.UTF8.GetBytes(test.Input);
string encoded = test.Encoder.EncodeData(input);
Assert.Equal(test.Expected, encoded);
try
{
var decoded = test.Encoder.DecodeData(encoded);
byte[] decoded = test.Encoder.DecodeData(encoded);
AssertEx.CollectionEquals(input, decoded);
}
catch(NotSupportedException)
......@@ -100,13 +100,13 @@ namespace NBitcoin.Tests
}
}
var expectedText = "2189xoVGsHC6VbVPUrKeH3fhT429VDruzdgUJFk37PNskG";
var input1 = Encoding.UTF8.GetBytes("---é ^ç hello \"12345\" wooorld---");
var encoded1 = Encoders.Base58Check.EncodeData(input1, 3, input1.Length - 6);
string expectedText = "2189xoVGsHC6VbVPUrKeH3fhT429VDruzdgUJFk37PNskG";
byte[] input1 = Encoding.UTF8.GetBytes("---é ^ç hello \"12345\" wooorld---");
string encoded1 = Encoders.Base58Check.EncodeData(input1, 3, input1.Length - 6);
Assert.Equal(expectedText, encoded1);
var decoded1 = Encoders.Base58Check.DecodeData(encoded1);
byte[] arr = new byte[input1.Length - 6];
byte[] decoded1 = Encoders.Base58Check.DecodeData(encoded1);
var arr = new byte[input1.Length - 6];
Array.Copy(input1,3, arr, 0, arr.Length);
AssertEx.CollectionEquals(input1.SafeSubarray(3, input1.Length - 6), decoded1);
}
......
......@@ -5,6 +5,7 @@ using System.Text;
using System.Text.RegularExpressions;
using NBitcoin.BouncyCastle.Asn1;
using NBitcoin.BouncyCastle.Asn1.Sec;
using NBitcoin.BouncyCastle.Asn1.X9;
using NBitcoin.BouncyCastle.Crypto.Parameters;
using NBitcoin.BouncyCastle.Math;
using NBitcoin.BouncyCastle.Math.EC;
......@@ -36,14 +37,14 @@ namespace NBitcoin.Tests
}
static Dictionary<string, DerObjectIdentifier> curves;
private static Dictionary<string, DerObjectIdentifier> curves;
public DeterministicSignatureTests()
{
}
class DeterministicSigTest
private class DeterministicSigTest
{
public BigInteger K
......@@ -109,9 +110,9 @@ namespace NBitcoin.Tests
var dsa = new DeterministicECDSA(GetHash(test.Hash));
dsa.setPrivateKey(key);
dsa.update(Encoding.UTF8.GetBytes(test.Message));
var result = dsa.sign();
byte[] result = dsa.sign();
var signature = ECDSASignature.FromDER(result);
ECDSASignature signature = ECDSASignature.FromDER(result);
Assert.Equal(test.S, signature.S);
Assert.Equal(test.R, signature.R);
}
......@@ -146,7 +147,7 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void DeterministicSignatureTestVectors()
{
foreach(var test in ParseTestsDump(File.ReadAllText("Data/determiniticECDSA.txt")))
foreach(DeterministicSigTest test in ParseTestsDump(File.ReadAllText(TestDataLocations.GetFileFromDataFolder("determiniticECDSA.txt"))))
{
TestSig(test);
}
......@@ -154,17 +155,17 @@ namespace NBitcoin.Tests
private IEnumerable<DeterministicSigTest> ParseTestsDump(string testDump)
{
foreach(var curveTest in testDump.Split(new string[] { "Key pair:" }, StringSplitOptions.RemoveEmptyEntries))
foreach(string curveTest in testDump.Split(new string[] { "Key pair:" }, StringSplitOptions.RemoveEmptyEntries))
{
var tests = curveTest.Split(new string[] { "Signatures:" }, StringSplitOptions.RemoveEmptyEntries);
string[] tests = curveTest.Split(new string[] { "Signatures:" }, StringSplitOptions.RemoveEmptyEntries);
if(tests.Length == 1)
continue;
if(tests.Length != 2)
throw new Exception("Test bug");
var key = tests[0];
var signatures = tests[1];
var privateKey = ParseKey(key);
foreach(var test in ParseTests(signatures))
string key = tests[0];
string signatures = tests[1];
ECPrivateKeyParameters privateKey = ParseKey(key);
foreach(DeterministicSigTest test in ParseTests(signatures))
{
test.Key = privateKey;
yield return test;
......@@ -175,9 +176,9 @@ namespace NBitcoin.Tests
private IEnumerable<DeterministicSigTest> ParseTests(string tests)
{
foreach(var test in tests.Split(new string[] { "With " }, StringSplitOptions.RemoveEmptyEntries))
foreach(string test in tests.Split(new string[] { "With " }, StringSplitOptions.RemoveEmptyEntries))
{
var result = ParseTest("With " + test);
DeterministicSigTest result = ParseTest("With " + test);
if(result != null)
yield return result;
}
......@@ -185,7 +186,7 @@ namespace NBitcoin.Tests
private DeterministicSigTest ParseTest(string data)
{
var match = Regex.Match(data, "With (.*?), message = \"?(.*?)\"?:");
Match match = Regex.Match(data, "With (.*?), message = \"?(.*?)\"?:");
if(!match.Success)
return null;
data = data.Replace(match.Value, "");
......@@ -204,13 +205,14 @@ namespace NBitcoin.Tests
private static Dictionary<string, string> ToDictionnary(string data)
{
Dictionary<string, string> values = new Dictionary<string, string>();
var values = new Dictionary<string, string>();
var lines = data.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
// The state of the line separators may be affected by copy operations - so do an environment independent line split...
string[] lines = data.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
string previous = null;
foreach(var line in lines)
foreach(string line in lines)
{
var kv = line.Replace("\t", "")
string[] kv = line.Replace("\t", "")
.Replace(" ", "")
.Split(new string[] { ":", "=" }, StringSplitOptions.RemoveEmptyEntries);
if(kv.Length != 2)
......@@ -231,8 +233,8 @@ namespace NBitcoin.Tests
{
Dictionary<string, string> values = ToDictionnary(data);
var curveName = values["curve"].Replace("NIST", "");
var curve = SecNamedCurves.GetByOid(curves[curveName]);
string curveName = values["curve"].Replace("NIST", "");
X9ECParameters curve = SecNamedCurves.GetByOid(curves[curveName]);
var domain = new ECDomainParameters(curve.Curve, curve.G, new BigInteger(values["q"], 16), curve.H);
Assert.Equal(domain.N, curve.N);
......
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<TargetFramework>netcoreapp2.1</TargetFramework>
<RuntimeFrameworkVersion>2.1.1</RuntimeFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>TRACE;DEBUG;NOHTTPSERVER;NOWEBCLIENT;NETCOREAPP1_1;NETCOREAPP1_1;NETCORE;NETCOREAPP1_1</DefineConstants>
<DefineConstants>TRACE;DEBUG;NETCORE;</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DefineConstants>TRACE;RELEASE;NOHTTPSERVER;NOWEBCLIENT;NETCOREAPP1_1;NETCOREAPP1_1;NETCORE;NETCOREAPP1_1</DefineConstants>
<DefineConstants>TRACE;RELEASE;NETCORE;</DefineConstants>
</PropertyGroup>
<ItemGroup>
......@@ -18,7 +19,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.7.2" />
<PackageReference Include="xunit" Version="2.3.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" />
</ItemGroup>
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
#if !NOSOCKET
using System;
using System;
using System.Collections.Generic;
namespace NBitcoin.Tests
......@@ -108,7 +107,7 @@ namespace NBitcoin.Tests
_Server1.Dispose();
_Server2.Dispose();
*/
foreach(var dispo in _Disposables)
foreach(IDisposable dispo in this._Disposables)
dispo.Dispose();
}
......@@ -116,10 +115,10 @@ namespace NBitcoin.Tests
public static string NATRuleName = "NBitcoin Tests";
List<IDisposable> _Disposables = new List<IDisposable>();
private List<IDisposable> _Disposables = new List<IDisposable>();
internal void AddDisposable(IDisposable disposable)
{
_Disposables.Add(disposable);
this._Disposables.Add(disposable);
}
}
public class ProtocolTests
......@@ -708,4 +707,3 @@ namespace NBitcoin.Tests
*/ }
}
#endif
\ No newline at end of file
This diff is collapsed.
......@@ -54,7 +54,7 @@ namespace NBitcoin.Tests
//https://github.com/libbitcoin/libbitcoin/blob/master/test/stealth.cpp
public void BitFieldCorrectlyMatchData()
{
var bit = (uint)1358086238;
uint bit = (uint)1358086238;
var o = new BitField(bit, 32);
var tests = new[]
{
......@@ -76,7 +76,7 @@ namespace NBitcoin.Tests
};
foreach(var test in tests)
{
BitField field = new BitField(test.Encoded, test.BitCount);
var field = new BitField(test.Encoded, test.BitCount);
Assert.Equal(test.Match, field.Match(Utils.ToUInt32(TestUtils.ParseHex(test.Data), true)));
}
}
......@@ -114,10 +114,10 @@ namespace NBitcoin.Tests
foreach(var test in tests)
{
var field = new BitField(TestUtils.ParseHex(test.Encoded), test.BitCount);
Transaction transaction = new Transaction();
var transaction = new Transaction();
transaction.FromBytes(TestUtils.ParseHex(test.Transaction));
var stealthOutput = field.GetPayments(transaction).FirstOrDefault();
StealthPayment stealthOutput = field.GetPayments(transaction).FirstOrDefault();
Assert.NotNull(stealthOutput);
Assert.True(field.Match(stealthOutput.Metadata.BitField));
......@@ -218,28 +218,28 @@ namespace NBitcoin.Tests
}
};
foreach(var test in tests)
foreach(CanCreatePaymentData test in tests)
{
var scan = AssertKeys(test.ScanSecret, test.ScanPubKey);
var spend = AssertKeys(test.SpendSecret, test.SpendPubKey);
var ephem = AssertKeys(test.EphemSecret, test.EphemPubKey);
var stealth = AssertKeys(test.StealthSecret, test.StealthPubKey);
Key scan = AssertKeys(test.ScanSecret, test.ScanPubKey);
Key spend = AssertKeys(test.SpendSecret, test.SpendPubKey);
Key ephem = AssertKeys(test.EphemSecret, test.EphemPubKey);
Key stealth = AssertKeys(test.StealthSecret, test.StealthPubKey);
var address = spend.PubKey.CreateStealthAddress(scan.PubKey, Network.Main);
BitcoinStealthAddress address = spend.PubKey.CreateStealthAddress(scan.PubKey, Network.Main);
Assert.Equal(test.StealthAddress, address.ToString());
//Try roundtrip
address = new BitcoinStealthAddress(address.ToBytes(), Network.Main);
Assert.Equal(test.StealthAddress, address.ToString());
var payment = address.CreatePayment(ephem);
var generatedKey = spend.Uncover(scan, payment.Metadata.EphemKey);
StealthPayment payment = address.CreatePayment(ephem);
Key generatedKey = spend.Uncover(scan, payment.Metadata.EphemKey);
if(stealth != null)
{
Assert.Equal(stealth.PubKey.Hash, payment.StealthKeys[0].ID);
Assert.Equal(stealth.ToBytes(), generatedKey.ToBytes());
}
var uncoveredSender = spend.PubKey.UncoverSender(ephem, scan.PubKey);
var uncovertedReceiver = spend.PubKey.UncoverReceiver(scan, ephem.PubKey);
PubKey uncoveredSender = spend.PubKey.UncoverSender(ephem, scan.PubKey);
PubKey uncovertedReceiver = spend.PubKey.UncoverReceiver(scan, ephem.PubKey);
AssertEx.CollectionEquals(uncoveredSender.ToBytes(), uncovertedReceiver.ToBytes());
AssertEx.CollectionEquals(generatedKey.PubKey.ToBytes(), uncovertedReceiver.ToBytes());
......@@ -253,10 +253,10 @@ namespace NBitcoin.Tests
{
if(key == null)
return null;
Key k = new Key(TestUtils.ParseHex(key));
var k = new Key(TestUtils.ParseHex(key));
if(pub != null)
{
PubKey p = new PubKey(TestUtils.ParseHex(pub));
var p = new PubKey(TestUtils.ParseHex(pub));
AssertEx.Equal(k.PubKey.ToBytes(), p.ToBytes());
}
return k;
......@@ -324,7 +324,7 @@ namespace NBitcoin.Tests
{
for(int i = 0; i < count; i++)
{
CanCreatePaymentData data = new CanCreatePaymentData();
var data = new CanCreatePaymentData();
var spend = new Key();
var scan = new Key();
var ephem = new Key();
......@@ -347,19 +347,19 @@ namespace NBitcoin.Tests
public override string ToString()
{
return
"StealthAddress = \"" + StealthAddress + "\",\r\n" +
"StealthAddress = \"" + this.StealthAddress + "\",\r\n" +
"ScanSecret = \"" + ScanSecret + "\",\r\n" +
"ScanPubKey = \"" + ScanPubKey + "\",\r\n" +
"ScanSecret = \"" + this.ScanSecret + "\",\r\n" +
"ScanPubKey = \"" + this.ScanPubKey + "\",\r\n" +
"SpendSecret = \"" + SpendSecret + "\",\r\n" +
"SpendPubKey = \"" + SpendPubKey + "\",\r\n" +
"SpendSecret = \"" + this.SpendSecret + "\",\r\n" +
"SpendPubKey = \"" + this.SpendPubKey + "\",\r\n" +
"EphemSecret = \"" + EphemSecret + "\",\r\n" +
"EphemPubKey = \"" + EphemPubKey + "\",\r\n" +
"EphemSecret = \"" + this.EphemSecret + "\",\r\n" +
"EphemPubKey = \"" + this.EphemPubKey + "\",\r\n" +
"StealthSecret = \"" + StealthSecret + "\",\r\n" +
"StealthPubKey = \"" + StealthPubKey + "\",\r\n";
"StealthSecret = \"" + this.StealthSecret + "\",\r\n" +
"StealthPubKey = \"" + this.StealthPubKey + "\",\r\n";
}
}
}
......@@ -21,9 +21,9 @@ namespace NBitcoin.Tests
public static TestCase[] read_json(string fileName)
{
using(var fs = File.Open(fileName, FileMode.Open))
using(FileStream fs = File.Open(fileName, FileMode.Open))
{
Newtonsoft.Json.JsonSerializer seria = new Newtonsoft.Json.JsonSerializer();
var seria = new JsonSerializer();
var result = (TestCase[])seria.Deserialize(new StreamReader(fs), typeof(TestCase[]));
for(int i = 0; i < result.Length; i++)
{
......
using System.IO;
#if NOWEBCLIENT
//using nStratis.Tests;
#endif
namespace NBitcoin.Tests
{
public class TestDataLocations
{
public static string BlockFolderLocation
public static string GetFileFromDataFolder(string filename)
{
get
{
EnsureDownloaded(@"download\posblocks\blk0001.dat", "https://onedrive.live.com/download.aspx?cid=3E5405DC8E6A9F4F&resid=3E5405DC8E6A9F4F%21120&canary=WEXg5NdVyhofKGNJlW0V0e8AbKxmTjJ1yP47KsA8hyU%3D8&ithint=%2Edat");
return @"download\posblocks";
}
return Path.Combine("data", filename);
}
public static string Block0001Location
public static string GetFileFromDataBlockFolder(string filename)
{
get
{
EnsureDownloaded(@"download\posblocks\blk0001.dat", "https://onedrive.live.com/download.aspx?cid=3E5405DC8E6A9F4F&resid=3E5405DC8E6A9F4F%21120&canary=WEXg5NdVyhofKGNJlW0V0e8AbKxmTjJ1yP47KsA8hyU%3D8&ithint=%2Edat");
return @"download\posblocks\blk0001.dat";
}
return Path.Combine("data", "blocks", filename);
}
public static string BlockHeadersLocation
public static string GetFileFromDataPosFolder(string filename)
{
get
{
EnsureDownloaded(@"download\posblocks\Headers.dat", "https://onedrive.live.com/download.aspx?cid=3E5405DC8E6A9F4F&resid=3E5405DC8E6A9F4F%21123&canary=HTsPi6qeFsOy7di8KBD7GIYBmHaRRumiJ%2FQnNMvz%2Fh0%3D4&ithint=%2Edat");
return @"download\posblocks\Headers.dat";
}
return Path.Combine("data_pos", filename);
}
private static void EnsureDownloaded(string file, string url)
public static string GetFileFromDataPosBlockFolder(string filename)
{
if (File.Exists(file))
return;
if (!Directory.Exists(Path.GetDirectoryName(file)))
Directory.CreateDirectory(Path.GetDirectoryName(file));
WebClient client = new WebClient();
client.DownloadFile(url, file);
}
public static string DataBlockFolder(string file)
{
var p = Path.DirectorySeparatorChar;
var folder = DataFolder("blocks");
return $@"{folder}\{file}".Replace('\\', p);
}
public static string DataFolder(string file)
{
var p = Path.DirectorySeparatorChar;
var current = AssemblyDirectory;
if (Directory.Exists($@"{current}\data_pos".Replace('\\', p)))
{
return $@"{current}\data_pos\{file}".Replace('\\', p);
}
if (Directory.Exists($@"{current}\bin\Debug\netcoreapp1.0\data_pos".Replace('\\', p)))
{
return $@"{current}\bin\Debug\netcoreapp1.0\data_pos\{file}".Replace('\\', p);
}
if (Directory.Exists($@"{current}\bin\Debug\netcoreapp1.1\data_pos".Replace('\\', p)))
{
return $@"{current}\bin\Debug\netcoreapp1.1\data_pos\{file}".Replace('\\', p);
}
throw new DirectoryNotFoundException();
}
public static string AssemblyDirectory
{
get
{
#if NETCORE
return System.AppContext.BaseDirectory;
#else
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
#endif
}
return Path.Combine("data_pos", "blocks", filename);
}
}
}
......@@ -5,7 +5,7 @@ using NBitcoin.DataEncoders;
namespace NBitcoin.Tests
{
class TestUtils
internal class TestUtils
{
public static void Eventually(Func<bool> act)
{
......@@ -19,7 +19,7 @@ namespace NBitcoin.Tests
public static byte[] ToBytes(string str)
{
byte[] result = new byte[str.Length];
var result = new byte[str.Length];
for(int i = 0; i < str.Length; i++)
{
result[i] = (byte)str[i];
......@@ -42,7 +42,7 @@ namespace NBitcoin.Tests
public static Block CreateFakeBlock()
{
var block = TestUtils.CreateFakeBlock(new Transaction());
Block block = CreateFakeBlock(new Transaction());
block.Header.HashPrevBlock = new uint256(RandomUtils.GetBytes(32));
block.Header.Nonce = RandomUtils.GetUInt32();
return block;
......
#if NOWEBCLIENT
using System;
using System.IO;
using System.Net.Http;
namespace NBitcoin.Tests
{
public class WebClient
{
public void DownloadFile(string url, string file)
{
HttpClient client = new HttpClient();
// The default value is 100,000 milliseconds (100 seconds) and
// that's not long enough to download Bitcoin on slower connections.
client.Timeout = TimeSpan.FromMinutes(5);
var bytes = client.GetByteArrayAsync(url).GetAwaiter().GetResult();
File.WriteAllBytes(file, bytes);
}
}
}
#endif
\ No newline at end of file
namespace NBitcoin.Tests
{
public class alert_tests
{
/*
* TODO: Consider importing to FN.
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanParseAlertAndChangeUpdatePayloadAndSignature()
{
var alertStr = "73010000003766404f00000000b305434f00000000f2030000f1030000001027000048ee00000064000000004653656520626974636f696e2e6f72672f666562323020696620796f7520686176652074726f75626c6520636f6e6e656374696e67206166746572203230204665627275617279004730450221008389df45f0703f39ec8c1cc42c13810ffcae14995bb648340219e353b63b53eb022009ec65e1c1aaeec1fd334c6b684bde2b3f573060d5b70c3a46723326e4e8a4f1";
AlertPayload alert = new AlertPayload();
alert.FromBytes(TestUtils.ParseHex(alertStr));
Assert.True(alert.CheckSignature(Network.Main));
Assert.Equal("See bitcoin.org/feb20 if you have trouble connecting after 20 February", alert.StatusBar);
alert.StatusBar = "Changing...";
Assert.True(alert.CheckSignature(Network.Main));
alert.UpdatePayload();
Assert.False(alert.CheckSignature(Network.Main));
Key key = new Key();
alert.UpdateSignature(key);
Assert.True(alert.CheckSignature(key.PubKey));
}
[Fact]
[Trait("Core", "Core")]
public void AlertApplies()
{
var alerts = ReadAlerts();
foreach(var alert in alerts)
{
Assert.True(alert.CheckSignature(Network.Main));
Assert.True(!alert.CheckSignature(Network.TestNet));
alert.Now = Utils.UnixTimeToDateTime(11);
}
Assert.True(alerts.Length >= 3);
// Matches:
Assert.True(alerts[0].AppliesTo(1, ""));
Assert.True(alerts[0].AppliesTo(999001, ""));
Assert.True(alerts[0].AppliesTo(1, "/Satoshi:11.11.11/"));
Assert.True(alerts[1].AppliesTo(1, "/Satoshi:0.1.0/"));
Assert.True(alerts[1].AppliesTo(999001, "/Satoshi:0.1.0/"));
Assert.True(alerts[2].AppliesTo(1, "/Satoshi:0.1.0/"));
Assert.True(alerts[2].AppliesTo(1, "/Satoshi:0.2.0/"));
// Don't match:
Assert.True(!alerts[0].AppliesTo(-1, ""));
Assert.True(!alerts[0].AppliesTo(999002, ""));
Assert.True(!alerts[1].AppliesTo(1, ""));
Assert.True(!alerts[1].AppliesTo(1, "Satoshi:0.1.0"));
Assert.True(!alerts[1].AppliesTo(1, "/Satoshi:0.1.0"));
Assert.True(!alerts[1].AppliesTo(1, "Satoshi:0.1.0/"));
Assert.True(!alerts[1].AppliesTo(-1, "/Satoshi:0.1.0/"));
Assert.True(!alerts[1].AppliesTo(999002, "/Satoshi:0.1.0/"));
Assert.True(!alerts[1].AppliesTo(1, "/Satoshi:0.2.0/"));
Assert.True(!alerts[2].AppliesTo(1, "/Satoshi:0.3.0/"));
}
private AlertPayload[] ReadAlerts()
{
List<AlertPayload> alerts = new List<AlertPayload>();
using(var fs = File.OpenRead("data/alertTests.raw"))
{
BitcoinStream stream = new BitcoinStream(fs, false);
while(stream.Inner.Position != stream.Inner.Length)
{
AlertPayload payload = null;
stream.ReadWrite(ref payload);
alerts.Add(payload);
}
}
return alerts.ToArray();
}
*/
}
}
......@@ -33,11 +33,11 @@ namespace NBitcoin.Tests
[Fact]
public void ShouldEncodeProperly()
{
foreach(var i in DataSet)
foreach(object[] i in DataSet)
{
string data = (string)i[0];
string encoded = (string)i[1];
var testBytes = Encoders.Hex.DecodeData(data);
byte[] testBytes = Encoders.Hex.DecodeData(data);
Assert.Equal(encoded, Encoders.Base58.EncodeData(testBytes));
}
}
......@@ -45,11 +45,11 @@ namespace NBitcoin.Tests
[Fact]
public void ShouldDecodeProperly()
{
foreach(var i in DataSet)
foreach(object[] i in DataSet)
{
string data = (string)i[0];
string encoded = (string)i[1];
var testBytes = Encoders.Base58.DecodeData(encoded);
byte[] testBytes = Encoders.Base58.DecodeData(encoded);
AssertEx.CollectionEquals(Encoders.Hex.DecodeData(data), testBytes);
}
}
......@@ -62,8 +62,8 @@ namespace NBitcoin.Tests
// check that DecodeBase58 skips whitespace, but still fails with unexpected non-whitespace at the end.
Assert.Throws<FormatException>(() => Encoders.Base58.DecodeData(" \t\n\v\f\r skip \r\f\v\n\t a"));
var result = Encoders.Base58.DecodeData(" \t\n\v\f\r skip \r\f\v\n\t ");
var expected2 = Encoders.Hex.DecodeData("971a55");
byte[] result = Encoders.Base58.DecodeData(" \t\n\v\f\r skip \r\f\v\n\t ");
byte[] expected2 = Encoders.Hex.DecodeData("971a55");
AssertEx.CollectionEquals(result, expected2);
}
......@@ -72,9 +72,9 @@ namespace NBitcoin.Tests
[Trait("Core", "Core")]
public void base58_keys_valid_parse()
{
var tests = TestCase.read_json("Data\\base58_keys_valid.json");
TestCase[] tests = TestCase.read_json(TestDataLocations.GetFileFromDataFolder("base58_keys_valid.json"));
Network network;
foreach(var test in tests)
foreach(TestCase test in tests)
{
string strTest = test.ToString();
if(test.Count < 3) // Allow for extra stuff (useful for comments)
......@@ -99,7 +99,7 @@ namespace NBitcoin.Tests
// Must be valid private key
// Note: CBitcoinSecret::SetString tests isValid, whereas CBitcoinAddress does not!
var secret = network.CreateBitcoinSecret(exp_base58string);
BitcoinSecret secret = network.CreateBitcoinSecret(exp_base58string);
//If not valid exception would throw
Key privkey = secret.PrivateKey;
......@@ -113,7 +113,7 @@ namespace NBitcoin.Tests
{
string exp_addrType = (string)test.GetDynamic(2).addrType; // "script" or "pubkey"
// Must be valid public key
var addr = network.CreateBitcoinAddress(exp_base58string);
BitcoinAddress addr = network.CreateBitcoinAddress(exp_base58string);
Assert.True((addr is BitcoinScriptAddress) == (exp_addrType == "script"), "isScript mismatch" + strTest);
if(exp_addrType == "script")
......@@ -132,11 +132,11 @@ namespace NBitcoin.Tests
[Trait("Core", "Core")]
public void base58_keys_valid_gen()
{
var tests = TestCase.read_json("data/base58_keys_valid.json");
tests = tests.Concat(TestCase.read_json("data/base58_keys_valid2.json")).ToArray();
TestCase[] tests = TestCase.read_json(TestDataLocations.GetFileFromDataFolder("base58_keys_valid.json"));
tests = tests.Concat(TestCase.read_json(TestDataLocations.GetFileFromDataFolder("base58_keys_valid2.json"))).ToArray();
Network network = null;
foreach(var test in tests)
foreach(TestCase test in tests)
{
string strTest = test.ToString();
if(test.Count < 3) // Allow for extra stuff (useful for comments)
......@@ -157,7 +157,7 @@ namespace NBitcoin.Tests
if(isPrivkey)
{
bool isCompressed = metadata.isCompressed;
Key key = new Key(exp_payload, fCompressedIn: isCompressed);
var key = new Key(exp_payload, fCompressedIn: isCompressed);
BitcoinSecret secret = network.CreateBitcoinSecret(key);
Assert.True(secret.ToString() == exp_base58string, "result mismatch: " + strTest);
}
......@@ -209,7 +209,7 @@ namespace NBitcoin.Tests
{
get
{
var dataset = TestCase.read_json("data/base58_keys_invalid.json");
TestCase[] dataset = TestCase.read_json(TestDataLocations.GetFileFromDataFolder("base58_keys_invalid.json"));
return dataset.Select(x => x.ToArray());
}
}
......@@ -218,7 +218,7 @@ namespace NBitcoin.Tests
[Fact]
public void base58_keys_invalid()
{
foreach(var i in InvalidKeys)
foreach(object[] i in InvalidKeys)
{
string data = (string)i[0];
// must be invalid as public and as private key
......
......@@ -7,27 +7,27 @@ namespace NBitcoin.Tests
{
public class bip32_tests
{
class TestDerivation
private class TestDerivation
{
public string pub;
public string prv;
public uint nChild;
};
class TestVector
private class TestVector
{
public string strHexMaster;
public List<TestDerivation> vDerive = new List<TestDerivation>();
public TestVector(string strHexMasterIn)
{
strHexMaster = strHexMasterIn;
this.strHexMaster = strHexMasterIn;
}
public TestVector Add(string pub, string prv, uint nChild)
{
vDerive.Add(new TestDerivation());
TestDerivation der = vDerive.Last();
this.vDerive.Add(new TestDerivation());
TestDerivation der = this.vDerive.Last();
der.pub = pub;
der.prv = prv;
der.nChild = nChild;
......@@ -35,7 +35,7 @@ namespace NBitcoin.Tests
}
};
TestVector test1 =
private TestVector test1 =
new TestVector("000102030405060708090a0b0c0d0e0f")
.Add("xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8",
"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
......@@ -56,7 +56,7 @@ namespace NBitcoin.Tests
"xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76",
0);
TestVector test2 =
private TestVector test2 =
new TestVector("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542")
.Add("xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB",
"xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
......@@ -81,14 +81,14 @@ namespace NBitcoin.Tests
[Trait("Core", "Core")]
public void bip32_test1()
{
RunTest(test1);
RunTest(this.test1);
}
[Fact]
[Trait("Core", "Core")]
public void bip32_test2()
{
RunTest(test2);
RunTest(this.test2);
}
[Fact]
......@@ -108,10 +108,10 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void CanRecoverExtKeyFromExtPubKeyAndOneChildExtKey()
{
ExtKey key = ExtKey.Parse("xprv9s21ZrQH143K3Z9EwCXrA5VbypnvWGiE9z22S1cLLPi7r8DVUkTabBvMjeirS8KCyppw24KoD4sFmja8UDU4VL32SBdip78LY6sz3X2GPju")
ExtKey key = ExtKey.Parse("xprv9s21ZrQH143K3Z9EwCXrA5VbypnvWGiE9z22S1cLLPi7r8DVUkTabBvMjeirS8KCyppw24KoD4sFmja8UDU4VL32SBdip78LY6sz3X2GPju", Network.Main)
.Derive(1);
var pubkey = key.Neuter();
var childKey = key.Derive(1);
ExtPubKey pubkey = key.Neuter();
ExtKey childKey = key.Derive(1);
ExtKey recovered = childKey.GetParentExtKey(pubkey);
Assert.Equal(recovered.ToString(Network.Main), key.ToString(Network.Main));
......@@ -127,11 +127,11 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void CanRecoverExtKeyFromExtPubKeyAndOneChildExtKey2()
{
for(int i = 0; i < 255; i++)
for (int i = 0; i < 255; i++)
{
ExtKey key = new ExtKey().Derive((uint)i);
var childKey = key.Derive((uint)i);
var pubKey = key.Neuter();
ExtKey childKey = key.Derive((uint)i);
ExtPubKey pubKey = key.Neuter();
ExtKey recovered = childKey.GetParentExtKey(pubKey);
Assert.Equal(recovered.ToString(Network.Main), key.ToString(Network.Main));
}
......@@ -142,9 +142,9 @@ namespace NBitcoin.Tests
public void CanRecoverExtKeyFromExtPubKeyAndSecret()
{
ExtKey key = new ExtKey().Derive(1);
var underlying = key.PrivateKey.GetBitcoinSecret(Network.Main);
var pubKey = key.Neuter().GetWif(Network.Main);
ExtKey key2 = new ExtKey(pubKey, underlying);
BitcoinSecret underlying = key.PrivateKey.GetBitcoinSecret(Network.Main);
BitcoinExtPubKey pubKey = key.Neuter().GetWif(Network.Main);
var key2 = new ExtKey(pubKey, underlying);
Assert.Equal(key.ToString(Network.Main), key2.ToString(Network.Main));
}
......@@ -152,7 +152,7 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void CanUseKeyPath()
{
var keyPath = KeyPath.Parse("0/1/2/3");
KeyPath keyPath = KeyPath.Parse("0/1/2/3");
Assert.Equal("0/1/2/3", keyPath.ToString());
var key = new ExtKey();
Assert.Equal(key
......@@ -162,7 +162,7 @@ namespace NBitcoin.Tests
.Derive(3)
.ToString(Network.Main), key.Derive(keyPath).ToString(Network.Main));
var neuter = key.Neuter();
ExtPubKey neuter = key.Neuter();
Assert.Equal(neuter
.Derive(0)
.Derive(1)
......@@ -209,7 +209,7 @@ namespace NBitcoin.Tests
public void CanRoundTripExtKeyBase58Data()
{
var key = new ExtKey();
var pubkey = key.Neuter();
ExtPubKey pubkey = key.Neuter();
Assert.True(ExtKey.Parse(key.ToString(Network.Main)).ToString(Network.Main) == key.ToString(Network.Main));
Assert.True(ExtPubKey.Parse(pubkey.ToString(Network.Main)).ToString(Network.Main) == pubkey.ToString(Network.Main));
}
......@@ -218,7 +218,7 @@ namespace NBitcoin.Tests
public void CanCheckChildKey()
{
var parent = new ExtKey();
var child = parent.Derive(1);
ExtKey child = parent.Derive(1);
var notchild = new ExtKey();
Assert.True(child.IsChildOf(parent));
......@@ -231,16 +231,16 @@ namespace NBitcoin.Tests
Assert.False(notchild.Neuter().IsChildOf(parent.Neuter()));
Assert.False(parent.Neuter().IsParentOf(notchild.Neuter()));
var keyA = parent.Neuter();
ExtPubKey keyA = parent.Neuter();
var keyB = new ExtPubKey(keyA.ToBytes());
AssertEx.CollectionEquals(keyA.ToBytes(), keyB.ToBytes());
}
private void RunTest(TestVector test)
{
var seed = TestUtils.ParseHex(test.strHexMaster);
ExtKey key = new ExtKey(seed);
byte[] seed = TestUtils.ParseHex(test.strHexMaster);
var key = new ExtKey(seed);
ExtPubKey pubkey = key.Neuter();
foreach(TestDerivation derive in test.vDerive)
foreach (TestDerivation derive in test.vDerive)
{
byte[] data = key.ToBytes();
Assert.Equal(74, data.Length);
......@@ -255,7 +255,7 @@ namespace NBitcoin.Tests
// Derive new keys
ExtKey keyNew = key.Derive(derive.nChild);
ExtPubKey pubkeyNew = keyNew.Neuter();
if(!((derive.nChild & 0x80000000) != 0))
if (!((derive.nChild & 0x80000000) != 0))
{
// Compare with public derivation
ExtPubKey pubkeyNew2 = pubkey.Derive(derive.nChild);
......
......@@ -16,7 +16,7 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void CanGenerateMnemonicOfSpecificLength()
{
foreach(var count in new[] { WordCount.Twelve, WordCount.TwentyFour, WordCount.TwentyOne, WordCount.Fifteen, WordCount.Eighteen })
foreach(WordCount count in new[] { WordCount.Twelve, WordCount.TwentyFour, WordCount.TwentyOne, WordCount.Fifteen, WordCount.Eighteen })
{
Assert.Equal((int)count, new Mnemonic(Wordlist.English, count).Words.Length);
}
......@@ -36,14 +36,14 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void EngTest()
{
var test = JObject.Parse(File.ReadAllText("data/bip39_vectors.json"));
JObject test = JObject.Parse(File.ReadAllText(TestDataLocations.GetFileFromDataFolder("bip39_vectors.json")));
foreach(var language in test.Properties())
foreach(JProperty language in test.Properties())
{
var lang = GetList(language.Name);
foreach(var langTest in ((JArray)language.Value).OfType<JArray>().Take(2))
Wordlist lang = GetList(language.Name);
foreach(JArray langTest in ((JArray)language.Value).OfType<JArray>().Take(2))
{
var entropy = Encoders.Hex.DecodeData(langTest[0].ToString());
byte[] entropy = Encoders.Hex.DecodeData(langTest[0].ToString());
string mnemonicStr = langTest[1].ToString();
string seed = langTest[2].ToString();
var mnemonic = new Mnemonic(mnemonicStr, lang);
......@@ -62,8 +62,8 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void KDTableCanNormalize()
{
var input = "あおぞら";
var expected = "あおぞら";
string input = "あおぞら";
string expected = "あおぞら";
Assert.False(input == expected);
Assert.Equal(expected, KDTable.NormalizeKD(input));
}
......@@ -72,19 +72,19 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void JapTest()
{
var test = JArray.Parse(File.ReadAllText("data/bip39_JP.json", Encoding.UTF32));
JArray test = JArray.Parse(File.ReadAllText(TestDataLocations.GetFileFromDataFolder("bip39_JP.json"), Encoding.UTF32));
foreach(var unitTest in test.OfType<JObject>())
foreach(JObject unitTest in test.OfType<JObject>())
{
var entropy = Encoders.Hex.DecodeData(unitTest["entropy"].ToString());
byte[] entropy = Encoders.Hex.DecodeData(unitTest["entropy"].ToString());
string mnemonicStr = unitTest["mnemonic"].ToString();
string seed = unitTest["seed"].ToString();
string passphrase = unitTest["passphrase"].ToString();
var mnemonic = new Mnemonic(mnemonicStr, Wordlist.Japanese);
Assert.True(mnemonic.IsValidChecksum);
Assert.Equal(seed, Encoders.Hex.EncodeData(mnemonic.DeriveSeed(passphrase)));
var bip32 = unitTest["bip32_xprv"].ToString();
var bip32Actual = mnemonic.DeriveExtKey(passphrase).ToString(Network.Main);
string bip32 = unitTest["bip32_xprv"].ToString();
string bip32Actual = mnemonic.DeriveExtKey(passphrase).ToString(Network.Main);
Assert.Equal(bip32, bip32Actual.ToString());
mnemonic = new Mnemonic(Wordlist.Japanese, entropy);
Assert.True(mnemonic.IsValidChecksum);
......@@ -150,28 +150,28 @@ namespace NBitcoin.Tests
throw new NotSupportedException(lang);
}
}
#if !PORTABLE
public class bip39_Codegen
{
//[Fact]
private void GenerateHardcodedBIP39Dictionary()
{
StringBuilder builder = new StringBuilder();
foreach(var lang in new[] { Language.ChineseSimplified, Language.ChineseTraditional, Language.English, Language.Japanese, Language.Spanish, Language.French })
var builder = new StringBuilder();
foreach(Language lang in new[] { Language.ChineseSimplified, Language.ChineseTraditional, Language.English, Language.Japanese, Language.Spanish, Language.French })
{
string name = Wordlist.GetLanguageFileName(lang);
builder.AppendLine("dico.Add(\"" + name + "\",\"" + GetLanguage(lang) + "\");");
}
var dico = builder.ToString();
string dico = builder.ToString();
}
[Fact]
public void GenerateHardcodedNormalization()
{
StringBuilder builder = new StringBuilder();
var builder = new StringBuilder();
builder.Append("\"");
HashSet<char> chars = new HashSet<char>();
List<CharRangeT> ranges = new List<CharRangeT>();
var chars = new HashSet<char>();
var ranges = new List<CharRangeT>();
ranges.Add(CharRange(0, 1000)); //Some latin language accent
ranges.Add(CharRange(0x3040, 0x309F)); //Hiragana
ranges.Add(CharRange(0x30A0, 0x30FF)); //Katakana
......@@ -193,7 +193,7 @@ namespace NBitcoin.Tests
ranges.Add(CharRange(0x2000, 0x206F));
ranges.Add(CharRange(0x20A0, 0x20CF));
foreach(var letter in ranges.SelectMany(c => c).OrderBy(c => c))
foreach(char letter in ranges.SelectMany(c => c).OrderBy(c => c))
{
string nonNormal = new String(new[] { letter });
try
......@@ -210,19 +210,19 @@ namespace NBitcoin.Tests
}
builder.Append("\"");
var substitutionTable = builder.ToString();
string substitutionTable = builder.ToString();
builder = new StringBuilder();
builder.AppendLine("{");
foreach(var range in ranges)
foreach(CharRangeT range in ranges)
{
builder.AppendLine("new[]{" + range.From + "," + range.To + "},");
}
builder.AppendLine("}");
var rangeTable = builder.ToString();
string rangeTable = builder.ToString();
}
class CharRangeT : IEnumerable<char>
private class CharRangeT : IEnumerable<char>
{
public int From;
public int To;
......@@ -232,7 +232,7 @@ namespace NBitcoin.Tests
public IEnumerator<char> GetEnumerator()
{
return Chars.GetEnumerator();
return this.Chars.GetEnumerator();
}
......@@ -244,8 +244,8 @@ namespace NBitcoin.Tests
private CharRangeT CharRange(char[] chars)
{
var min = chars.Select(c => (int)c).Min();
var max = chars.Select(c => (int)c).Max();
int min = chars.Select(c => (int)c).Min();
int max = chars.Select(c => (int)c).Max();
return CharRange(min, max);
}
......@@ -261,10 +261,9 @@ namespace NBitcoin.Tests
private string GetLanguage(Language lang)
{
string name = Wordlist.GetLanguageFileName(lang);
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
var data = client.GetAsync("https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/" + name + ".txt").Result.Content.ReadAsStringAsync().Result;
var client = new System.Net.Http.HttpClient();
string data = client.GetAsync("https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/" + name + ".txt").Result.Content.ReadAsStringAsync().Result;
return data.Replace("\n", "\\n");
}
}
#endif
}
This diff is collapsed.
#if !NOFILEIO
using System.IO;
using System.IO;
using NBitcoin.DataEncoders;
using Xunit;
......@@ -11,10 +10,9 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void CanCalculateMerkleRoot()
{
Block block = new Block();
block.ReadWrite(Encoders.Hex.DecodeData(File.ReadAllText(@"data\block169482.txt")));
var block = new Block();
block.ReadWrite(Encoders.Hex.DecodeData(File.ReadAllText(TestDataLocations.GetFileFromDataFolder("block169482.txt"))), Network.Main.Consensus.ConsensusFactory);
Assert.Equal(block.Header.HashMerkleRoot, block.GetMerkleRoot().Hash);
}
}
}
}
#endif
\ No newline at end of file
......@@ -48,7 +48,7 @@ namespace NBitcoin.Tests
in = 00 01 02 ... 3e (63 bytes)
from: https://131002.net/siphash/siphash24.c
*/
ulong[] siphash_4_2_testvec = new ulong[]{
private ulong[] siphash_4_2_testvec = new ulong[]{
0x726fdb47dd0e0e31, 0x74f839c593dc67fd, 0x0d6c8009d9a94f5a, 0x85676696d7fb7e2d,
0xcf2794e0277187b7, 0x18765564cd99a68d, 0xcbc9466e58fee3ce, 0xab0200f58b01d137,
0x93f5f5799a932462, 0x9e0082df0ba9e4b0, 0x7a5dbbc594ddb9f3, 0xf4b32f46226bada7,
......@@ -71,23 +71,23 @@ namespace NBitcoin.Tests
[Trait("Core", "Core")]
public void siphash()
{
Hashes.SipHasher hasher = new Hashes.SipHasher(0x0706050403020100UL, 0x0F0E0D0C0B0A0908UL);
var hasher = new Hashes.SipHasher(0x0706050403020100UL, 0x0F0E0D0C0B0A0908UL);
Assert.Equal(0x726fdb47dd0e0e31UL, hasher.Finalize());
byte[] t0 = new byte[]{ 0 };
var t0 = new byte[]{ 0 };
hasher.Write(t0);
Assert.Equal(0x74f839c593dc67fdUL, hasher.Finalize());
byte[] t1 = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
var t1 = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
hasher.Write(t1);
Assert.Equal(0x93f5f5799a932462UL, hasher.Finalize());
hasher.Write(0x0F0E0D0C0B0A0908UL);
Assert.Equal(0x3f2acc7f57c29bdbUL, hasher.Finalize());
byte[] t2 = new byte[] { 16, 17 };
var t2 = new byte[] { 16, 17 };
hasher.Write(t2);
Assert.Equal(0x4bc1b3f0968dd39cUL, hasher.Finalize());
byte[] t3 = new byte[] { 18, 19, 20, 21, 22, 23, 24, 25, 26 };
var t3 = new byte[] { 18, 19, 20, 21, 22, 23, 24, 25, 26 };
hasher.Write(t3);
Assert.Equal(0x2f2e6163076bcfadUL, hasher.Finalize());
byte[] t4 = new byte[]{ 27, 28, 29, 30, 31 };
var t4 = new byte[]{ 27, 28, 29, 30, 31 };
hasher.Write(t4);
Assert.Equal(0x7127512f72f27cceUL, hasher.Finalize());
hasher.Write(0x2726252423222120UL);
......@@ -98,17 +98,17 @@ namespace NBitcoin.Tests
Assert.Equal(0x7127512f72f27cceUL, Hashes.SipHash(0x0706050403020100UL, 0x0F0E0D0C0B0A0908UL, new uint256("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100")));
// Check test vectors from spec, one byte at a time
Hashes.SipHasher hasher2 = new Hashes.SipHasher(0x0706050403020100UL, 0x0F0E0D0C0B0A0908UL);
for(byte x = 0; x < siphash_4_2_testvec.Length; ++x)
var hasher2 = new Hashes.SipHasher(0x0706050403020100UL, 0x0F0E0D0C0B0A0908UL);
for(byte x = 0; x < this.siphash_4_2_testvec.Length; ++x)
{
Assert.Equal(hasher2.Finalize(), siphash_4_2_testvec[x]);
Assert.Equal(hasher2.Finalize(), this.siphash_4_2_testvec[x]);
hasher2.Write(new byte[] { x });
}
// Check test vectors from spec, eight bytes at a time
Hashes.SipHasher hasher3 = new Hashes.SipHasher(0x0706050403020100UL, 0x0F0E0D0C0B0A0908UL);
for(var x = 0; x < siphash_4_2_testvec.Length; x += 8)
var hasher3 = new Hashes.SipHasher(0x0706050403020100UL, 0x0F0E0D0C0B0A0908UL);
for(int x = 0; x < this.siphash_4_2_testvec.Length; x += 8)
{
Assert.Equal(hasher3.Finalize(), siphash_4_2_testvec[x]);
Assert.Equal(hasher3.Finalize(), this.siphash_4_2_testvec[x]);
hasher3.Write(uint64_t(x) | (uint64_t(x + 1) << 8) | (uint64_t(x + 2) << 16) | (uint64_t(x + 3) << 24) |
(uint64_t(x + 4) << 32) | (uint64_t(x + 5) << 40) | (uint64_t(x + 6) << 48) | (uint64_t(x + 7) << 56));
}
......@@ -131,7 +131,7 @@ namespace NBitcoin.Tests
public void hash160()
{
var data = new byte[] { 1, 2, 3, 4 };
var result = Hashes.Hash160(data);
uint160 result = Hashes.Hash160(data);
Assert.Equal("706ea1768da7f0c489bf931b362c2d26d8cbd2ec", result.ToString());
}
......
This diff is collapsed.
#if !NOSOCKET
namespace NBitcoin.Tests
namespace NBitcoin.Tests
{
public class pos_ProtocolTests
{
......@@ -573,5 +572,3 @@ namespace NBitcoin.Tests
*/ }
}
#endif
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
......@@ -11,13 +11,13 @@ namespace NBitcoin.Tests
[Trait("UnitTest", "UnitTest")]
public void CanCalculatePowCorrectly()
{
ConcurrentChain chain = new ConcurrentChain(Network.Main);
var chain = new ConcurrentChain(Network.Main);
EnsureDownloaded("MainChain.dat", "https://aois.blob.core.windows.net/public/MainChain.dat");
chain.Load(File.ReadAllBytes("MainChain.dat"));
foreach(var block in chain.EnumerateAfter(chain.Genesis))
foreach(ChainedHeader block in chain.EnumerateAfter(chain.Genesis))
{
var thisWork = block.GetWorkRequired(Network.Main);
var thisWork2 = block.Previous.GetNextWorkRequired(Network.Main);
Target thisWork = block.GetWorkRequired(Network.Main);
Target thisWork2 = block.Previous.GetNextWorkRequired(Network.Main);
Assert.Equal(thisWork, thisWork2);
Assert.True(block.CheckProofOfWorkAndTarget(Network.Main));
}
......@@ -27,9 +27,9 @@ namespace NBitcoin.Tests
{
if(File.Exists(file))
return;
HttpClient client = new HttpClient();
var client = new HttpClient();
client.Timeout = TimeSpan.FromMinutes(5);
var data = client.GetByteArrayAsync(url).GetAwaiter().GetResult();
byte[] data = client.GetByteArrayAsync(url).GetAwaiter().GetResult();
File.WriteAllBytes(file, data);
}
}
......
This diff is collapsed.
......@@ -6,9 +6,9 @@ namespace NBitcoin.Tests
{
public class sighash_tests
{
static Random rand = new Random();
private static Random rand = new Random();
static Script RandomScript()
private static Script RandomScript()
{
OpcodeType[] oplist = { OpcodeType.OP_FALSE, OpcodeType.OP_1, OpcodeType.OP_2, OpcodeType.OP_3, OpcodeType.OP_CHECKSIG, OpcodeType.OP_IF, OpcodeType.OP_VERIF, OpcodeType.OP_RETURN, OpcodeType.OP_CODESEPARATOR };
var script = new Script();
......@@ -47,11 +47,11 @@ namespace NBitcoin.Tests
[Trait("Core", "Core")]
public void sighash_from_data()
{
var tests = TestCase.read_json("Data/sighash.json");
TestCase[] tests = TestCase.read_json(TestDataLocations.GetFileFromDataFolder("sighash.json"));
foreach(var test in tests)
foreach(TestCase test in tests)
{
var strTest = test.ToString();
string strTest = test.ToString();
if(test.Count < 1) // Allow for extra stuff (useful for comments)
{
Assert.True(false, "Bad test: " + strTest);
......@@ -62,8 +62,8 @@ namespace NBitcoin.Tests
string raw_tx, raw_script, sigHashHex;
int nIn, nHashType;
Transaction tx = new Transaction();
Script scriptCode = new Script();
var tx = new Transaction();
var scriptCode = new Script();
// deserialize test data
......@@ -74,12 +74,12 @@ namespace NBitcoin.Tests
sigHashHex = (string)test[4];
tx.ReadWrite(ParseHex(raw_tx));
tx.ReadWrite(ParseHex(raw_tx), Network.Main.Consensus.ConsensusFactory);
var raw = ParseHex(raw_script);
byte[] raw = ParseHex(raw_script);
scriptCode = new Script(raw);
var sh = Script.SignatureHash(Network.Main, scriptCode, tx, nIn, (SigHash)nHashType);
uint256 sh = Script.SignatureHash(Network.Main, scriptCode, tx, nIn, (SigHash)nHashType);
Assert.True(sh.ToString() == sigHashHex, strTest);
}
}
......@@ -88,4 +88,4 @@ namespace NBitcoin.Tests
return Encoders.Hex.DecodeData(data);
}
}
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment