Example #1
0
        public static void CanParseRev()
        {
            BlockUndoStore src   = new BlockUndoStore(TestDataLocations.DataFolder(@"blocks"), Network.Main);
            BlockUndoStore dest  = CreateBlockUndoStore();
            int            count = 0;

            foreach (var 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 (var un in dest.EnumerateFolder())
            {
                var expectedSize = un.Header.ItemSize;
                var actualSize   = (uint)un.Item.GetSerializedSize();
                Assert.Equal(expectedSize, actualSize);
                count++;
            }
            Assert.Equal(8, count);
        }
Example #2
0
        public void CanEnumerateBlockInAFileRange()
        {
            var store  = new BlockStore(TestDataLocations.DataFolder(@"blocks"), Network.Main);
            var result = store.Enumerate(new DiskBlockPosRange(new DiskBlockPos(1, 0), new DiskBlockPos(2, 0))).ToList();

            Assert.Equal(2000, result.Count);
        }
Example #3
0
        public void CanReIndex()
        {
            var source = new BlockStore(TestDataLocations.DataFolder(@"blocks"), Network.Main);
            var 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 (var b in store.Enumerate(true))
            {
                var result = test.Get(b.Item.GetHash());
                Assert.Equal(result.GetHash(), b.Item.GetHash());
                i++;
            }
            Assert.Equal(100, i);

            var 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);
        }
Example #4
0
        public void CanBuildChainFromBlocks()
        {
            var store = new BlockStore(TestDataLocations.DataFolder(@"blocks"), Network.Main);
            var chain = store.GetChain();

            Assert.True(chain.Height == 3999);
        }
Example #5
0
        public void CanDecodeAndEncodeRawTransaction()
        {
            if (RPCClientTests.noClient)
            {
                return;
            }

            var tests = TestCase.read_json(TestDataLocations.DataFolder(@"tx_raw.json"));

            using (var builder = NodeBuilder.Create())
            {
                var rpc = builder.CreateNode().CreateRPCClient();
                builder.StartAll();
                var index = 0;
                foreach (var test in tests)
                {
                    var format   = (RawFormat)Enum.Parse(typeof(RawFormat), (string)test[0], true);
                    var network  = ((string)test[1]) == "Main" ? Network.Main : Network.TestNet;
                    var testData = ((JObject)test[2]).ToString();

                    Transaction raw = Transaction.Parse(testData, format, network);

                    AssertJsonEquals(raw.ToString(format, network), testData);

                    var raw3 = Transaction.Parse(raw.ToString(format, network), format);
                    Assert.Equal(raw.ToString(format, network), raw3.ToString(format, network));
                    index++;
                }
            }
        }
Example #6
0
        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());
            }
        }
Example #7
0
 public void DeterministicSignatureTestVectors()
 {
     foreach (var test in ParseTestsDump(File.ReadAllText(TestDataLocations.DataFolder("determiniticECDSA.txt"))))
     {
         TestSig(test);
     }
 }
Example #8
0
        public void CanCalculateMerkleRoot()
        {
            Block block = new Block();

            block.ReadWrite(Encoders.Hex.DecodeData(File.ReadAllText(TestDataLocations.DataFolder("block1125.txt"))));
            Assert.Equal(block.Header.HashMerkleRoot, block.GetMerkleRoot().Hash);
        }
Example #9
0
        public void CanEnumerateBlockCountRange()
        {
            var store         = new BlockStore(TestDataLocations.DataFolder(@"blocks"), Network.Main);
            var expectedBlock = store.Enumerate(false).Skip(4).First();
            var 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());
        }
Example #10
0
        //[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")));
        }
Example #11
0
        //[Fact]
        //[Trait("UnitTest", "UnitTest")]
        public void CanParseBlockJSON()
        {
            // disabled for now

            var jobj     = JObject.Parse(File.ReadAllText(TestDataLocations.DataFolder(@"blocks/Block1.json")));
            var array    = (JArray)jobj["mrkl_tree"];
            var expected = array.OfType <JValue>().Select(v => uint256.Parse(v.ToString())).ToList();
            var block    = Block.ParseJson(File.ReadAllText(TestDataLocations.DataFolder(@"blocks/Block1.json")));

            Assert.Equal("000000000000000040cd080615718eb68f00a0138706e7afd4068f3e08d4ca20", block.GetHash().ToString());
            Assert.True(block.CheckMerkleRoot());
        }
Example #12
0
        public void CanStoreInBlockRepository()
        {
            var blockRepository = CreateBlockRepository();
            var firstblk1       = StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat")).First();

            blockRepository.WriteBlockHeader(firstblk1.Item.Header);
            var result = blockRepository.GetBlock(firstblk1.Item.GetHash());

            Assert.True(result.HeaderOnly);

            blockRepository.WriteBlock(firstblk1.Item);
            result = blockRepository.GetBlock(firstblk1.Item.GetHash());
            Assert.False(result.HeaderOnly);
        }
Example #13
0
        public void CanReadStoredBlockFolder()
        {
            var blk0 = StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat"), (uint)1).ToList();
            var blk1 = StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0002.dat"), (uint)2).ToList();

            int count = 0;

            foreach (var stored in StoredBlock.EnumerateFolder(TestDataLocations.DataFolder(@"blocks")))
            {
                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)))
            {
                count++;
            }
            Assert.Equal(2, count);

            count = 0;
            foreach (var stored in StoredBlock.EnumerateFolder(TestDataLocations.DataFolder(@"blocks"), new DiskBlockPosRange(blk0[1998].BlockPosition)))
            {
                count++;
            }
            Assert.Equal(2002, count);

            count = 0;
            foreach (var stored in StoredBlock.EnumerateFolder(TestDataLocations.DataFolder(@"blocks"), new DiskBlockPosRange(blk0[1998].BlockPosition, blk1[2].BlockPosition)))
            {
                count++;
            }
            Assert.Equal(4, count);

            count = 0;
            foreach (var stored in StoredBlock.EnumerateFolder(TestDataLocations.DataFolder(@"blocks"), new DiskBlockPosRange(blk0[30].BlockPosition, blk0[34].BlockPosition)))
            {
                count++;
            }
            Assert.Equal(4, count);
        }
Example #14
0
        public void CanIndexBlock()
        {
            var index = CreateIndexedStore();

            foreach (var block in StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat")).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);
        }
Example #15
0
        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());
            }
        }
Example #16
0
        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());
        }
Example #17
0
        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());
        }
Example #18
0
        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")).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
        }
Example #19
0
        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;
                }
            }
        }
Example #20
0
        public void CanReadStoredBlockFile()
        {
            int count = 0;

            foreach (var stored in StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat")))
            {
                Assert.True(stored.Item.Check());
                count++;
            }
            Assert.Equal(2000, count);
            count = 0;
            var twoLast = StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat")).Skip(1998).ToList();

            foreach (var stored in StoredBlock.EnumerateFile(TestDataLocations.DataBlockFolder("blk0001.dat"), range: new DiskBlockPosRange(twoLast[0].BlockPosition)))
            {
                count++;
            }
            Assert.Equal(2, count);
        }
Example #21
0
        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);
            }
        }
Example #22
0
        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
            }
        }
Example #23
0
        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(BigInteger.Parse(history.Split(',')[1]));

                var block = chain.GetBlock(height).Header;

                Assert.Equal(expectedTarget, block.Bits);
                var target = chain.GetWorkRequired(Network.Main, height);
                Assert.Equal(expectedTarget, target);
            }
        }
Example #24
0
        //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);
            }
        }
Example #25
0
        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());
            }
        }
Example #26
0
        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());
                }
            }
        }
Example #27
0
        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")));
                }
            }
        }
Example #28
0
        public void CanSerializeDeserializePeerTable()
        {
            AddressManager addrman = new AddressManager();

            addrman.SavePeerFile("CanSerializeDeserializePeerTable.dat", Network.Main);
            AddressManager.LoadPeerFile("CanSerializeDeserializePeerTable.dat", Network.Main);

            addrman           = AddressManager.LoadPeerFile(TestDataLocations.DataFolder("peers.dat"), Network.Main);
            addrman.DebugMode = true;
            addrman.Check();
            addrman.SavePeerFile("serializerPeer.dat", Network.Main);

            AddressManager addrman2 = AddressManager.LoadPeerFile("serializerPeer.dat", Network.Main);

            addrman2.DebugMode = true;
            addrman2.Check();
            addrman2.SavePeerFile("serializerPeer2.dat", Network.Main);

            var original = File.ReadAllBytes("serializerPeer2.dat");
            var after    = File.ReadAllBytes("serializerPeer.dat");

            Assert.True(original.SequenceEqual(after));
        }
Example #29
0
        public void base58_keys_valid_parse()
        {
            var     tests = TestCase.read_json(TestDataLocations.DataFolder("base58_keys_valid.json"));
            Network network;

            foreach (var test in tests)
            {
                string strTest = test.ToString();
                if (test.Count < 3)                // Allow for extra stuff (useful for comments)
                {
                    Assert.True(false, "Bad test " + strTest);
                    continue;
                }

                string exp_base58string = (string)test[0];
                byte[] exp_payload      = TestUtils.ParseHex((string)test[1]);
                //const Object &metadata = test[2].get_obj();
                bool isPrivkey = (bool)test.GetDynamic(2).isPrivkey;
                bool isTestnet = (bool)test.GetDynamic(2).isTestnet;

                if (isTestnet)
                {
                    continue;
                }
                //network = Network.TestNet;
                else
                {
                    network = BitcoinNetwork.Main;
                }

                if (isPrivkey)
                {
                    bool isCompressed = (bool)test.GetDynamic(2).isCompressed;

                    // Must be valid private key
                    // Note: CBitcoinSecret::SetString tests isValid, whereas CBitcoinAddress does not!
                    var secret = network.CreateBitcoinSecret(exp_base58string);
                    //If not valid exception would throw

                    Key privkey = secret.PrivateKey;
                    Assert.True(privkey.IsCompressed == isCompressed, "compressed mismatch:" + strTest);
                    Assert.True(Utils.ArrayEqual(privkey.ToBytes(), exp_payload), "key mismatch:" + strTest);

                    // Private key must be invalid public key
                    Assert.Throws <FormatException>(() => network.CreateBitcoinAddress(exp_base58string));
                }
                else
                {
                    string exp_addrType = (string)test.GetDynamic(2).addrType;                     // "script" or "pubkey"
                    // Must be valid public key
                    var addr = network.CreateBitcoinAddress(exp_base58string);
                    Assert.True((addr is BitcoinScriptAddress) == (exp_addrType == "script"), "isScript mismatch" + strTest);

                    if (exp_addrType == "script")
                    {
                        Assert.True(addr.GetType() == typeof(BitcoinScriptAddress));
                    }
                    if (exp_addrType == "pubkey")
                    {
                        Assert.True(addr.GetType() == typeof(BitcoinPubKeyAddress));
                    }

                    Assert.Throws <FormatException>(() => network.CreateBitcoinSecret(exp_base58string));
                }
            }
        }
Example #30
0
            public ColoredCoinTester([CallerMemberName] string test = null)
            {
                var testcase = JsonConvert.DeserializeObject <TestCase[]>(File.ReadAllText(TestDataLocations.DataFolder(@"openasset-known-tx.json")))
                               .First(t => t.test == test);
                NoSqlTransactionRepository repository = new NoSqlTransactionRepository();

                foreach (var tx in testcase.txs)
                {
                    var txObj = Transaction.Parse(tx);
                    repository.Put(txObj.GetHash(), txObj);
                }
                TestedTxId = uint256.Parse(testcase.testedtx);
                Repository = new NullColoredTransactionRepository(repository);
            }