public void CanCalculateMerkleRoot() { var block = new Block(); block.ReadWrite(Encoders.Hex.DecodeData(File.ReadAllText(TestDataLocations.GetFileFromDataFolder("block169482.txt")))); Assert.Equal(block.Header.HashMerkleRoot, block.GetMerkleRoot().Hash); }
public void CanReIndex() { var source = new BlockStore(TestDataLocations.DataFolder(@"blocks"), Network.StratisMain); BlockStore store = CreateBlockStore("CanReIndexFolder"); store.AppendAll(source.Enumerate(false).Take(100).Select(b => b.Item)); var test = new IndexedBlockStore(new InMemoryNoSqlRepository(), store); var reIndexed = test.ReIndex(); Assert.Equal(100, reIndexed); int i = 0; foreach (StoredBlock b in store.Enumerate(true)) { Block result = test.Get(b.Item.GetHash()); Assert.Equal(result.GetHash(), b.Item.GetHash()); i++; } Assert.Equal(100, i); StoredBlock last = source.Enumerate(false).Skip(100).FirstOrDefault(); store.Append(last.Item); reIndexed = test.ReIndex(); Assert.Equal(1, reIndexed); reIndexed = test.ReIndex(); Assert.Equal(0, reIndexed); }
public void CanReadPaymentRequest() { foreach (var provider in new ICertificateServiceProvider[] { #if WIN new WindowsCertificateServiceProvider(X509VerificationFlags.IgnoreNotTimeValid | X509VerificationFlags.AllowUnknownCertificateAuthority | X509VerificationFlags.IgnoreRootRevocationUnknown | X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown | X509VerificationFlags.IgnoreEndRevocationUnknown) #endif }) { PaymentRequest.DefaultCertificateServiceProvider = provider; var request = LoadPaymentRequest(TestDataLocations.DataFolder(@"payreq1_sha1.paymentrequest")); AssertEx.CollectionEquals(request.ToBytes(), File.ReadAllBytes(TestDataLocations.DataFolder(@"payreq1_sha1.paymentrequest"))); Assert.True(request.VerifySignature()); request.Details.Memo = "lol"; Assert.False(request.VerifySignature()); request.Details.Memo = "this is a memo"; Assert.True(request.VerifySignature()); Assert.True(request.VerifyChain()); request = LoadPaymentRequest(TestDataLocations.DataFolder(@"payreq2_sha1.paymentrequest")); AssertEx.CollectionEquals(request.ToBytes(), File.ReadAllBytes(TestDataLocations.DataFolder(@"payreq2_sha1.paymentrequest"))); Assert.True(request.VerifySignature()); } }
public static void CanParseRev() { BlockUndoStore src = new BlockUndoStore(TestDataLocations.DataFolder(@"blocks"), Network.StratisMain); BlockUndoStore dest = CreateBlockUndoStore(); int count = 0; foreach (StoredItem <BlockUndo> un in src.EnumerateFolder()) { var expectedSize = un.Header.ItemSize; var actualSize = (uint)un.Item.GetSerializedSize(); Assert.Equal(expectedSize, actualSize); dest.Append(un.Item); count++; } Assert.Equal(8, count); count = 0; foreach (StoredItem <BlockUndo> un in dest.EnumerateFolder()) { var expectedSize = un.Header.ItemSize; var actualSize = (uint)un.Item.GetSerializedSize(); Assert.Equal(expectedSize, actualSize); count++; } Assert.Equal(8, count); }
public void DeterministicSignatureTestVectors() { foreach (var test in ParseTestsDump(File.ReadAllText(TestDataLocations.DataFolder("determiniticECDSA.txt")))) { TestSig(test); } }
public void CanBuildChainFromBlocks() { var store = new BlockStore(TestDataLocations.DataFolder(@"blocks"), Network.StratisMain); ConcurrentChain chain = store.GetChain(); Assert.True(chain.Height == 3999); }
public void CanEnumerateBlockInAFileRange() { var store = new BlockStore(TestDataLocations.DataFolder(@"blocks"), Network.StratisMain); var result = store.Enumerate(new DiskBlockPosRange(new DiskBlockPos(1, 0), new DiskBlockPos(2, 0))).ToList(); Assert.Equal(2000, result.Count); }
public void CanCalculateMerkleRoot() { Block block = Network.Main.CreateBlock(); block.ReadWrite(Encoders.Hex.DecodeData(File.ReadAllText(TestDataLocations.GetFileFromDataFolder("block169482.txt"))), Network.Main.Consensus.ConsensusFactory); Assert.Equal(block.Header.HashMerkleRoot, block.GetMerkleRoot().Hash); }
public void CanParseBlockJSON() { JObject jobj = JObject.Parse(File.ReadAllText(TestDataLocations.GetFileFromDataBlockFolder("Block1.json"))); var array = (JArray)jobj["mrkl_tree"]; List <uint256> expected = array.OfType <JValue>().Select(v => uint256.Parse(v.ToString())).ToList(); Block block = Block.ParseJson(KnownNetworks.Main, File.ReadAllText(TestDataLocations.GetFileFromDataBlockFolder("Block1.json"))); Assert.Equal("000000000000000040cd080615718eb68f00a0138706e7afd4068f3e08d4ca20", block.GetHash().ToString()); Assert.True(block.CheckMerkleRoot()); }
public void CanEnumerateBlockCountRange() { var store = new BlockStore(TestDataLocations.DataFolder(@"blocks"), Network.StratisMain); StoredBlock expectedBlock = store.Enumerate(false).Skip(4).First(); StoredBlock[] actualBlocks = store.Enumerate(false, 4, 2).ToArray(); Assert.Equal(2, actualBlocks.Length); Assert.Equal(expectedBlock.Item.Header.GetHash(), actualBlocks[0].Item.Header.GetHash()); Assert.True(actualBlocks[0].Item.CheckMerkleRoot()); }
//[Fact] //[Trait("UnitTest", "UnitTest")] public void CanParsePaymentACK() { var ack = LoadPaymentACK(TestDataLocations.DataFolder(@"paymentack.data")); Assert.Equal("thanks customer !", ack.Memo); Assert.Equal("thanks merchant !", ack.Payment.Memo); Assert.Equal(2, ack.Payment.Transactions.Count); Assert.Equal(2, ack.Payment.RefundTo.Count); AssertEx.CollectionEquals(ack.ToBytes(), PaymentACK.Load(ack.ToBytes()).ToBytes()); AssertEx.CollectionEquals(ack.ToBytes(), File.ReadAllBytes(TestDataLocations.DataFolder(@"paymentack.data"))); }
public void CanReadStoredBlockFolder() { var blk0 = StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat"), (uint)1, network: Network.StratisMain).ToList(); var blk1 = StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0002.dat"), (uint)2, network: Network.StratisMain).ToList(); int count = 0; foreach (var stored in StoredBlock.EnumerateFolder(TestDataLocations.DataFolder(@"blocks"), network: Network.StratisMain)) { if (count == 0) { Assert.Equal(blk0[0].Item.GetHash(), stored.Item.GetHash()); } if (count == 2000) { Assert.Equal(blk1[0].Item.GetHash(), stored.Item.GetHash()); } Assert.True(stored.Item.Check()); count++; } Assert.Equal(4000, count); count = 0; foreach (var stored in StoredBlock.EnumerateFolder(TestDataLocations.DataFolder(@"blocks"), new DiskBlockPosRange(blk1[1998].BlockPosition), network: Network.StratisMain)) { count++; } Assert.Equal(2, count); count = 0; foreach (var stored in StoredBlock.EnumerateFolder(TestDataLocations.DataFolder(@"blocks"), new DiskBlockPosRange(blk0[1998].BlockPosition), network: Network.StratisMain)) { count++; } Assert.Equal(2002, count); count = 0; foreach (var stored in StoredBlock.EnumerateFolder(TestDataLocations.DataFolder(@"blocks"), new DiskBlockPosRange(blk0[1998].BlockPosition, blk1[2].BlockPosition), network: Network.StratisMain)) { count++; } Assert.Equal(4, count); count = 0; foreach (var stored in StoredBlock.EnumerateFolder(TestDataLocations.DataFolder(@"blocks"), new DiskBlockPosRange(blk0[30].BlockPosition, blk0[34].BlockPosition), network: Network.StratisMain)) { count++; } Assert.Equal(4, count); }
public void CanStoreInBlockRepository() { BlockRepository blockRepository = CreateBlockRepository(); StoredBlock firstblk1 = StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat"), network: Network.StratisMain).First(); blockRepository.WriteBlockHeader(firstblk1.Item.Header); Block result = blockRepository.GetBlock(firstblk1.Item.GetHash()); Assert.True(result.HeaderOnly); blockRepository.WriteBlock(firstblk1.Item); result = blockRepository.GetBlock(firstblk1.Item.GetHash()); Assert.False(result.HeaderOnly); }
public void CanIndexBlock() { var index = CreateIndexedStore(); foreach (var block in StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat"), network: Network.StratisMain).Take(50)) { index.Put(block.Item); } var genesis = index.Get(uint256.Parse("0x0000066e91e46e5a264d42c89e1204963b2ee6be230b443e9159020539d972af")); Assert.NotNull(genesis); var invalidBlock = index.Get(uint256.Parse("0x0000066e91e46e5a264d42c89e1204963b2ee6be230b443e9159020539d972ae")); Assert.Null(invalidBlock); }
public void CanVerifyValidChain() { foreach (var provider in new ICertificateServiceProvider[] { #if WIN new WindowsCertificateServiceProvider(X509VerificationFlags.IgnoreNotTimeValid, X509RevocationMode.NoCheck) #endif }) { PaymentRequest.DefaultCertificateServiceProvider = provider; var req = LoadPaymentRequest(TestDataLocations.DataFolder(@"payreq3_validchain.paymentrequest")); Assert.True(req.VerifyChain()); Assert.True(req.VerifySignature()); } }
public void CanStoreBlocksInMultipleFiles() { var store = CreateBlockStore(); store.MaxFileSize = 10; //Verify break all block in one respective file with extreme settings var allBlocks = StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat"), network: Network.StratisMain).Take(10).ToList(); foreach (var s in allBlocks) { store.Append(s.Item); } var storedBlocks = store.Enumerate(true).ToList(); Assert.Equal(allBlocks.Count, storedBlocks.Count); Assert.Equal(11, store.Folder.GetFiles().Length); //10 files + lock file }
public void CanCreatePaymentMessageAndACK() { var request = LoadPaymentRequest(TestDataLocations.DataFolder(@"payreq1_sha1.paymentrequest")); var payment = request.CreatePayment(); AssertEx.CollectionEquals(request.Details.MerchantData, payment.MerchantData); AssertEx.CollectionEquals(payment.ToBytes(), PaymentMessage.Load(payment.ToBytes()).ToBytes()); payment.Memo = "thanks merchant !"; AssertEx.CollectionEquals(payment.ToBytes(), PaymentMessage.Load(payment.ToBytes()).ToBytes()); var ack = payment.CreateACK(); AssertEx.CollectionEquals(ack.Payment.ToBytes(), PaymentMessage.Load(payment.ToBytes()).ToBytes()); AssertEx.CollectionEquals(ack.ToBytes(), PaymentACK.Load(ack.ToBytes()).ToBytes()); ack.Memo = "thanks customer !"; AssertEx.CollectionEquals(ack.ToBytes(), PaymentACK.Load(ack.ToBytes()).ToBytes()); }
private AlertPayload[] ReadAlerts() { List <AlertPayload> alerts = new List <AlertPayload>(); using (var fs = File.OpenRead(TestDataLocations.DataFolder(@"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()); }
public void CanCalculateDifficulty() { var main = new ConcurrentChain(LoadMainChain()); var histories = File.ReadAllText(TestDataLocations.GetFileFromDataFolder("targethistory.csv")).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (var history in histories) { var height = int.Parse(history.Split(',')[0]); var expectedTarget = new Target(new BouncyCastle.Math.BigInteger(history.Split(',')[1], 10)); var block = main.GetBlock(height).Header; Assert.Equal(expectedTarget, block.Bits); var target = main.GetWorkRequired(Network.Main, height); Assert.Equal(expectedTarget, target); } }
void ListenerCallback(IAsyncResult ar) { try { var context = _Listener.EndGetContext(ar); var type = context.Request.QueryString.Get("type"); var businessId = int.Parse(context.Request.QueryString.Get("id")); if (type == "Request") { Assert.Equal(PaymentRequest.MediaType, context.Request.AcceptTypes[0]); context.Response.ContentType = PaymentRequest.MediaType; PaymentRequest request = new PaymentRequest(); request.Details.MerchantData = BitConverter.GetBytes(businessId); request.Details.PaymentUrl = new Uri(_Prefix + "?id=" + businessId + "&type=Payment"); request.Sign(File.ReadAllBytes(TestDataLocations.DataFolder(@"PaymentMerchant.pfx")), PKIType.X509SHA256); request.WriteTo(context.Response.OutputStream); } else if (type == "Payment") { Assert.Equal(PaymentMessage.MediaType, context.Request.ContentType); Assert.Equal(PaymentACK.MediaType, context.Request.AcceptTypes[0]); var payment = PaymentMessage.Load(context.Request.InputStream); Assert.Equal(businessId, BitConverter.ToInt32(payment.MerchantData, 0)); context.Response.ContentType = PaymentACK.MediaType; var ack = payment.CreateACK(); ack.WriteTo(context.Response.OutputStream); } else { Assert.False(true, "Impossible"); } context.Response.Close(); _Listener.BeginGetContext(ListenerCallback, null); } catch (Exception) { if (!_Stopped) { throw; } } }
public void CanCalculateDifficulty() { var main = new ChainIndexer(this.network).Load(this.LoadMainChain()); // The state of the line separators may be affected by copy operations - so do an environment independent line split... string[] histories = File.ReadAllText(TestDataLocations.GetFileFromDataFolder("targethistory.csv")).Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string history in histories) { int height = int.Parse(history.Split(',')[0]); var expectedTarget = new Target(new BouncyCastle.Math.BigInteger(history.Split(',')[1], 10)); BlockHeader block = main.GetHeader(height).Header; Assert.Equal(expectedTarget, block.Bits); Target target = main.GetHeader(height).GetWorkRequired(network); Assert.Equal(expectedTarget, target); } }
public void CanReadStoredBlockFile() { int count = 0; foreach (var stored in StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat"), network: Network.StratisMain)) { Assert.True(stored.Item.Check()); count++; } Assert.Equal(2000, count); count = 0; var twoLast = StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat"), network: Network.StratisMain).Skip(1998).ToList(); foreach (var stored in StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat"), network: Network.StratisMain, range: new DiskBlockPosRange(twoLast[0].BlockPosition))) { count++; } Assert.Equal(2, count); }
public void CanStoreBlocks() { var store = CreateBlockStore(); var allBlocks = StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat")).Take(50).ToList(); foreach (var s in allBlocks) { store.Append(s.Item); } var storedBlocks = store.Enumerate(true).ToList(); Assert.Equal(allBlocks.Count, storedBlocks.Count); foreach (var s in allBlocks) { var retrieved = store.Enumerate(true).First(b => b.Item.GetHash() == s.Item.GetHash()); Assert.True(retrieved.Item.HeaderOnly); } }
public void CanCreatePaymentRequest() { foreach (var provider in new ICertificateServiceProvider[] { #if WIN new WindowsCertificateServiceProvider(X509VerificationFlags.IgnoreNotTimeValid) #endif }) { PaymentRequest.DefaultCertificateServiceProvider = provider; var cert = File.ReadAllBytes(TestDataLocations.DataFolder(@"PaymentMerchant.pfx")); CanCreatePaymentRequestCore(cert); #if WIN if (provider is WindowsCertificateServiceProvider) { CanCreatePaymentRequestCore(new X509Certificate2(cert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet)); } #endif } }
public void CanCalculateDifficulty() { var histories = File.ReadAllLines(TestDataLocations.DataFolder(@"targethistory.csv")); var store = new BlockStore(TestDataLocations.BlockFolderLocation, Network.Main); // todo: load the chain with a header only file ConcurrentChain chain = store.GetChain(); foreach (var history in histories) { var height = int.Parse(history.Split(',')[0]); var expectedTarget = new Target(new BigInteger(history.Split(',')[1].Trim(), 10)); var block = chain.GetBlock(height).Header; Assert.Equal(expectedTarget, block.Bits); var target = chain.GetWorkRequired(Network.Main, height); Assert.Equal(expectedTarget, target); } }
//Compare between new old implementation of signature in reference bitcoin. But NBitcoin is like the old one, so we don't care about this test //[Fact] //public void sighash_test() //{ // int nRandomTests = 50000; // for(int i = 0 ; i < nRandomTests ; i++) // { // int nHashType = rand.Next(); // Transaction txTo = RandomTransaction((nHashType & 0x1f) == SigHash.Single); // Script scriptCode = RandomScript(); // int nIn = rand.Next() % txTo.VIn.Length; // var sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType); // var sh = scriptCode.SignatureHash(txTo, nIn, (SigHash)nHashType); // Assert.True(sh == sho); // } //} // Goal: check that SignatureHash generates correct hash //[Fact] //[Trait("Core", "Core")] public void sighash_from_data() { // test diabled for now as it requires specific test data var tests = TestCase.read_json(TestDataLocations.DataFolder(@"sighash.json")); foreach (var test in tests) { var strTest = test.ToString(); if (test.Count < 1) // Allow for extra stuff (useful for comments) { Assert.True(false, "Bad test: " + strTest); continue; } if (test.Count == 1) { continue; // comment } string raw_tx, raw_script, sigHashHex; int nIn, nHashType; Transaction tx = new Transaction(); Script scriptCode = new Script(); // deserialize test data raw_tx = (string)test[0]; raw_script = (string)test[1]; nIn = (int)(long)test[2]; nHashType = (int)(long)test[3]; sigHashHex = (string)test[4]; tx.ReadWrite(ParseHex(raw_tx)); var raw = ParseHex(raw_script); scriptCode = new Script(raw); var sh = Script.SignatureHash(scriptCode, tx, nIn, (SigHash)nHashType); Assert.True(sh.ToString() == sigHashHex, strTest); } }
public void EngTest() { var test = JObject.Parse(File.ReadAllText(TestDataLocations.DataFolder(@"bip39_vectors.json"))); foreach (var language in test.Properties()) { var lang = GetList(language.Name); foreach (var langTest in ((JArray)language.Value).OfType <JArray>().Take(2)) { var entropy = Encoders.Hex.DecodeData(langTest[0].ToString()); string mnemonicStr = langTest[1].ToString(); string seed = langTest[2].ToString(); var mnemonic = new Mnemonic(mnemonicStr, lang); Assert.True(mnemonic.IsValidChecksum); Assert.Equal(seed, Encoders.Hex.EncodeData(mnemonic.DeriveSeed("TREZOR"))); mnemonic = new Mnemonic(lang, entropy); Assert.True(mnemonic.IsValidChecksum); Assert.Equal(seed, Encoders.Hex.EncodeData(mnemonic.DeriveSeed("TREZOR"))); } } }
public void CanReadTestVectorPayments() { var tests = new[] { TestDataLocations.DataFolder(@"payreq1_sha256_omitteddefault.paymentrequest"), TestDataLocations.DataFolder(@"payreq1_sha256.paymentrequest"), TestDataLocations.DataFolder(@"payreq2_sha256_omitteddefault.paymentrequest"), TestDataLocations.DataFolder(@"payreq2_sha256.paymentrequest"), TestDataLocations.DataFolder(@"payreq1_sha1_omitteddefault.paymentrequest"), TestDataLocations.DataFolder(@"payreq1_sha1.paymentrequest"), TestDataLocations.DataFolder(@"payreq2_sha1_omitteddefault.paymentrequest"), TestDataLocations.DataFolder(@"payreq2_sha1.paymentrequest"), }; foreach (var provider in new ICertificateServiceProvider[] { #if WIN new WindowsCertificateServiceProvider(X509VerificationFlags.IgnoreNotTimeValid | X509VerificationFlags.AllowUnknownCertificateAuthority | X509VerificationFlags.IgnoreRootRevocationUnknown | X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown | X509VerificationFlags.IgnoreEndRevocationUnknown) #endif }) { PaymentRequest.DefaultCertificateServiceProvider = provider; foreach (var test in tests) { var bytes = File.ReadAllBytes(test); var request = PaymentRequest.Load(bytes); AssertEx.Equal(request.ToBytes(), bytes); Assert.True(request.VerifySignature()); request = PaymentRequest.Load(PaymentRequest.Load(bytes).ToBytes()); Assert.True(request.VerifySignature()); Assert.True(request.VerifyChain()); } } }
public void sighash_from_data() { TestCase[] tests = TestCase.read_json(TestDataLocations.GetFileFromDataFolder("sighash.json")); foreach (TestCase test in tests) { string strTest = test.ToString(); if (test.Count < 1) // Allow for extra stuff (useful for comments) { Assert.True(false, "Bad test: " + strTest); continue; } if (test.Count == 1) { continue; // comment } string raw_tx, raw_script, sigHashHex; int nIn, nHashType; var tx = new Transaction(); var scriptCode = new Script(); // deserialize test data raw_tx = (string)test[0]; raw_script = (string)test[1]; nIn = (int)(long)test[2]; nHashType = (int)(long)test[3]; sigHashHex = (string)test[4]; tx.ReadWrite(ParseHex(raw_tx), this.networkMain.Consensus.ConsensusFactory); byte[] raw = ParseHex(raw_script); scriptCode = new Script(raw); uint256 sh = Script.SignatureHash(KnownNetworks.Main, scriptCode, tx, nIn, (SigHash)nHashType); Assert.True(sh.ToString() == sigHashHex, strTest); } }
public void JapTest() { var test = JArray.Parse(File.ReadAllText(TestDataLocations.DataFolder(@"bip39_JP.json"), Encoding.UTF32)); foreach (var unitTest in test.OfType <JObject>()) { var 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); Assert.Equal(bip32, bip32Actual.ToString()); mnemonic = new Mnemonic(Wordlist.Japanese, entropy); Assert.True(mnemonic.IsValidChecksum); bip32Actual = mnemonic.DeriveExtKey(passphrase).ToString(Network.Main); Assert.Equal(bip32, bip32Actual.ToString()); } }