Beispiel #1
0
        public void CanBuildChainFromBlocks()
        {
            var             store = new BlockStore(TestDataLocations.DataFolder(@"blocks"), Network.StratisMain);
            ConcurrentChain chain = store.GetChain();

            Assert.True(chain.Height == 3999);
        }
Beispiel #2
0
        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);
        }
Beispiel #3
0
        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);
        }
Beispiel #4
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());
            }
        }
Beispiel #5
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);
        }
 public void DeterministicSignatureTestVectors()
 {
     foreach (var test in ParseTestsDump(File.ReadAllText(TestDataLocations.DataFolder("determiniticECDSA.txt"))))
     {
         TestSig(test);
     }
 }
Beispiel #7
0
        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);
        }
Beispiel #8
0
        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());
        }
Beispiel #9
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")));
        }
        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);
        }
Beispiel #11
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());
            }
        }
Beispiel #12
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());
        }
Beispiel #13
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());
        }
Beispiel #14
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;
                }
            }
        }
Beispiel #15
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
            }
        }
Beispiel #16
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(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);
            }
        }
Beispiel #17
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);
            }
        }
Beispiel #18
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());
                }
            }
        }
Beispiel #19
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());
            }
        }
Beispiel #20
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")));
                }
            }
        }
Beispiel #21
0
        public void CanSerializeDeserializePeerTable()
        {
            AddressManager addrman = new AddressManager();

            addrman.SavePeerFile("strat-CanSerializeDeserializePeerTable.dat", Network.StratisMain);
            AddressManager.LoadPeerFile("strat-CanSerializeDeserializePeerTable.dat", Network.StratisMain);

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

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

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

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

            Assert.True(original.SequenceEqual(after));
        }
Beispiel #22
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();

            var stakeChain = new MemoryStakeChain(Network.Main);
            var indexStore = new IndexedBlockStore(new InMemoryNoSqlRepository(), store);
            var reindexed  = indexStore.ReIndex();

            Assert.Equal(reindexed, 103952);

            var lastIndex = 0;

            foreach (var history in histories)
            {
                var height         = int.Parse(history.Split(',')[0]);
                var expectedTarget = new Target(new BigInteger(history.Split(',')[1].Trim(), 10));

                var chainedBlock = chain.GetBlock(height);
                for (int i = height; i > lastIndex; i--)
                {
                    var g     = chain.GetBlock(i);
                    var block = indexStore.Get(g.HashBlock);
                    stakeChain.Set(g.HashBlock, new BlockStake(block));
                }
                lastIndex = height;

                Assert.Equal(expectedTarget, chainedBlock.Header.Bits);
                var target = stakeChain.GetWorkRequired(chainedBlock, stakeChain.Get(chainedBlock.HashBlock), Network.Main.Consensus);
                //var target = chain.GetWorkRequired(Network.Main, height);
                Assert.Equal(expectedTarget, target);
            }
        }
Beispiel #23
0
        public void base58_keys_valid_gen()
        {
            var tests = TestCase.read_json(TestDataLocations.DataFolder(@"base58_keys_valid.json"));

            tests = tests.Concat(TestCase.read_json(TestDataLocations.DataFolder(@"base58_keys_valid2.json"))).ToArray();
            Network network = null;

            foreach (var test in tests)
            {
                string strTest = test.ToString();
                if (test.Count < 3)                // Allow for extra stuff (useful for comments)
                {
                    Assert.False(true, "Bad test: " + strTest);
                    continue;
                }
                string  exp_base58string = (string)test[0];
                byte[]  exp_payload      = TestUtils.ParseHex((string)test[1]);
                dynamic metadata         = test.GetDynamic(2);
                bool    isPrivkey        = (bool)metadata.isPrivkey;
                bool    isTestnet        = (bool)metadata.isTestnet;

                if (isTestnet)
                {
                    continue;                     // todo: consider to sadd the bitcoin testnet network
                }
                //network = Network.TestNet;
                else
                {
                    network = BitcoinNetwork.Main;
                }

                if (isPrivkey)
                {
                    bool          isCompressed = metadata.isCompressed;
                    Key           key          = new Key(exp_payload, fCompressedIn: isCompressed);
                    BitcoinSecret secret       = network.CreateBitcoinSecret(key);
                    Assert.True(secret.ToString() == exp_base58string, "result mismatch: " + strTest);
                }
                else
                {
                    string        exp_addrType = (string)metadata.addrType;
                    TxDestination dest;
                    if (exp_addrType == "pubkey")
                    {
                        dest = new KeyId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "script")
                    {
                        dest = new ScriptId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "p2wpkh")
                    {
                        dest = new WitKeyId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "p2wsh")
                    {
                        dest = new WitScriptId(exp_payload);
                    }
                    else if (exp_addrType == "none")
                    {
                        continue;
                    }
                    else
                    {
                        Assert.True(false, "Bad addrtype: " + strTest);
                        continue;
                    }
                    try
                    {
                        BitcoinAddress addrOut = dest.GetAddress(network);
                        Assert.True(addrOut.ToString() == exp_base58string, "mismatch: " + strTest);
                        Assert.True(addrOut.ScriptPubKey == dest.ScriptPubKey);
                        Assert.True(dest.ScriptPubKey.GetDestination() == dest);
                    }
                    catch (ArgumentException)
                    {
                        Assert.True(dest.GetType() == typeof(TxDestination));
                    }
                }
            }
        }
Beispiel #24
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));
                }
            }
        }