Exemplo n.º 1
0
        public void Base58EncodingLeadingZero()
        {
            const string privkey = "91axuYLa8xK796DnBXXsMbjuc8pDYxYgJyQMvFzrZ6UfXaGYuqL";
            var          key     = new DumpedPrivateKey(NetworkParameters.TestNet(), privkey).Key;

            Assert.AreEqual(privkey, key.GetPrivateKeyEncoded(NetworkParameters.TestNet()).ToString());
            Assert.AreEqual(0, key.GetPrivKeyBytes()[0]);
        }
Exemplo n.º 2
0
        public void Base58Encoding()
        {
            const string addr    = "mqAJmaxMcG5pPHHc3H3NtyXzY7kGbJLuMF";
            const string privkey = "92shANodC6Y4evT5kFzjNFQAdjqTtHAnDTLzqBBq4BbKUPyx6CD";
            var          key     = new DumpedPrivateKey(NetworkParameters.TestNet(), privkey).Key;

            Assert.AreEqual(privkey, key.GetPrivateKeyEncoded(NetworkParameters.TestNet()).ToString());
            Assert.AreEqual(addr, key.ToAddress(NetworkParameters.TestNet()).ToString());
        }
Exemplo n.º 3
0
 public void Base58EncodingStress()
 {
     // Replace the loop bound with 1000 to get some keys with leading zero byte
     for (var i = 0; i < 20; i++)
     {
         var key  = new EcKey();
         var key1 = new DumpedPrivateKey(NetworkParameters.TestNet(),
                                         key.GetPrivateKeyEncoded(NetworkParameters.TestNet()).ToString()).Key;
         Assert.AreEqual(Utils.BytesToHexString(key.GetPrivKeyBytes()),
                         Utils.BytesToHexString(key1.GetPrivKeyBytes()));
     }
 }
Exemplo n.º 4
0
        public static void Run(string[] args)
        {
            var file   = new FileInfo(args[0]);
            var wallet = Wallet.LoadFromFile(file);

            Console.WriteLine(wallet.ToString());

            // Set up the components and link them together.
            var @params    = NetworkParameters.TestNet();
            var blockStore = new MemoryBlockStore(@params);
            var conn       = new NetworkConnection(IPAddress.Loopback, @params,
                                                   blockStore.GetChainHead().Height, 60000);
            var chain = new BlockChain(@params, wallet, blockStore);
            var peer  = new Peer(@params, conn, chain);

            peer.Start();

            wallet.CoinsReceived +=
                (sender, e) =>
            {
                Console.WriteLine();
                Console.WriteLine("Received tx " + e.Tx.HashAsString);
                Console.WriteLine(e.Tx.ToString());
            };

            // Now download and process the block chain.
            var progress = peer.StartBlockChainDownload();
            var max      = progress.Count; // Racy but no big deal.

            if (max > 0)
            {
                Console.WriteLine("Downloading block chain. " + (max > 1000 ? "This may take a while." : ""));
                var current = max;
                while (current > 0)
                {
                    var pct = 100.0 - (100.0 * (current / (double)max));
                    Console.WriteLine(string.Format("Chain download {0}% done", (int)pct));
                    progress.Await(TimeSpan.FromSeconds(1));
                    current = progress.Count;
                }
            }
            peer.Disconnect();
            wallet.SaveToFile(file);
            Console.WriteLine();
            Console.WriteLine("Done!");
            Console.WriteLine();
            Console.WriteLine(wallet.ToString());
        }
Exemplo n.º 5
0
        public void TestBadDifficulty()
        {
            Assert.True(_testNetChain.Add(GetBlock1()));
            var b2 = GetBlock2();

            Assert.True(_testNetChain.Add(b2));
            var params2 = NetworkParameters.TestNet();
            var bad     = new Block(params2);

            // Merkle root can be anything here, doesn't matter.
            bad.MerkleRoot = Hex.Decode("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            // Nonce was just some number that made the hash < difficulty limit set below, it can be anything.
            bad.Nonce         = 140548933;
            bad.Time          = 1279242649;
            bad.PrevBlockHash = b2.Hash;
            // We're going to make this block so easy 50% of solutions will pass, and check it gets rejected for having a
            // bad difficulty target. Unfortunately the encoding mechanism means we cannot make one that accepts all
            // solutions.
            bad.DifficultyTarget = Block.EasiestDifficultyTarget;
            try
            {
                _testNetChain.Add(bad);
                // The difficulty target above should be rejected on the grounds of being easier than the networks
                // allowable difficulty.
                Assert.Fail();
            }
            catch (VerificationException e)
            {
                Assert.True(e.Message.IndexOf("Difficulty target is bad") >= 0, e.Message);
            }

            // Accept any level of difficulty now.
            params2.ProofOfWorkLimit = new BigInteger("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16);
            try
            {
                _testNetChain.Add(bad);
                // We should not get here as the difficulty target should not be changing at this point.
                Assert.Fail();
            }
            catch (VerificationException e)
            {
                Assert.True(e.Message.IndexOf("Unexpected change in difficulty") >= 0, e.Message);
            }

            // TODO: Test difficulty change is not out of range when a transition period becomes valid.
        }
Exemplo n.º 6
0
        public static void Run(string[] args)
        {
            var file   = new FileInfo(args[0]);
            var wallet = Wallet.LoadFromFile(file);

            Console.WriteLine(wallet.ToString());

            // Set up the components and link them together.
            var networkParams = NetworkParameters.TestNet();

            using (var blockStore = new MemoryBlockStore(networkParams))
            {
                var chain = new BlockChain(networkParams, wallet, blockStore);

                var peerGroup = new PeerGroup(blockStore, networkParams, chain);
                peerGroup.AddAddress(new PeerAddress(IPAddress.Loopback));
                peerGroup.Start();

                wallet.CoinsReceived +=
                    (sender, e) =>
                {
                    Console.WriteLine();
                    Console.WriteLine("Received tx " + e.Tx.HashAsString);
                    Console.WriteLine(e.Tx.ToString());
                };

                // Now download and process the block chain.
                peerGroup.DownloadBlockChain();
                peerGroup.Stop();
            }

            wallet.SaveToFile(file);
            Console.WriteLine();
            Console.WriteLine("Done!");
            Console.WriteLine();
            Console.WriteLine(wallet.ToString());
        }
Exemplo n.º 7
0
        public static void Run(string[] args)
        {
            var testNet    = args.Length > 0 && string.Equals(args[0], "testnet", StringComparison.InvariantCultureIgnoreCase);
            var @params    = testNet ? NetworkParameters.TestNet() : NetworkParameters.ProdNet();
            var filePrefix = testNet ? "pingservice-testnet" : "pingservice-prodnet";

            // Try to read the wallet from storage, create a new one if not possible.
            Wallet wallet;
            var    walletFile = new FileInfo(filePrefix + ".wallet");

            try
            {
                wallet = Wallet.LoadFromFile(walletFile);
            }
            catch (IOException)
            {
                wallet = new Wallet(@params);
                wallet.Keychain.Add(new EcKey());
                wallet.SaveToFile(walletFile);
            }
            // Fetch the first key in the wallet (should be the only key).
            var key = wallet.Keychain[0];

            Console.WriteLine(wallet);

            // Load the block chain, if there is one stored locally.
            Console.WriteLine("Reading block store from disk");
            using (var blockStore = new BoundedOverheadBlockStore(@params, new FileInfo(filePrefix + ".blockchain")))
            {
                // Connect to the localhost node. One minute timeout since we won't try any other peers
                Console.WriteLine("Connecting ...");
                var chain = new BlockChain(@params, wallet, blockStore);

                var peerGroup = new PeerGroup(blockStore, @params, chain);
                peerGroup.AddAddress(new PeerAddress(IPAddress.Loopback));
                peerGroup.Start();

                // We want to know when the balance changes.
                wallet.CoinsReceived +=
                    (sender, e) =>
                {
                    // Running on a peer thread.
                    Debug.Assert(!e.NewBalance.Equals(0));
                    // It's impossible to pick one specific identity that you receive coins from in BitCoin as there
                    // could be inputs from many addresses. So instead we just pick the first and assume they were all
                    // owned by the same person.
                    var input = e.Tx.Inputs[0];
                    var from  = input.FromAddress;
                    var value = e.Tx.GetValueSentToMe(wallet);
                    Console.WriteLine("Received " + Utils.BitcoinValueToFriendlyString(value) + " from " + from);
                    // Now send the coins back!
                    var sendTx = wallet.SendCoins(peerGroup, from, value);
                    Debug.Assert(sendTx != null);     // We should never try to send more coins than we have!
                    Console.WriteLine("Sent coins back! Transaction hash is " + sendTx.HashAsString);
                    wallet.SaveToFile(walletFile);
                };

                peerGroup.DownloadBlockChain();
                Console.WriteLine("Send coins to: " + key.ToAddress(@params));
                Console.WriteLine("Waiting for coins to arrive. Press Ctrl-C to quit.");
                // The PeerGroup thread keeps us alive until something kills the process.
            }
        }
Exemplo n.º 8
0
        public static void Run(string[] args)
        {
            var testNet    = args.Length > 0 && string.Equals(args[0], "testnet", StringComparison.InvariantCultureIgnoreCase);
            var @params    = testNet ? NetworkParameters.TestNet() : NetworkParameters.ProdNet();
            var filePrefix = testNet ? "pingservice-testnet" : "pingservice-prodnet";

            // Try to read the wallet from storage, create a new one if not possible.
            Wallet wallet;
            var    walletFile = new FileInfo(filePrefix + ".wallet");

            try
            {
                wallet = Wallet.LoadFromFile(walletFile);
            }
            catch (IOException)
            {
                wallet = new Wallet(@params);
                wallet.Keychain.Add(new EcKey());
                wallet.SaveToFile(walletFile);
            }
            // Fetch the first key in the wallet (should be the only key).
            var key = wallet.Keychain[0];

            // Load the block chain, if there is one stored locally.
            Console.WriteLine("Reading block store from disk");
            using (var blockStore = new BoundedOverheadBlockStore(@params, new FileInfo(filePrefix + ".blockchain")))
            {
                // Connect to the localhost node. One minute timeout since we won't try any other peers
                Console.WriteLine("Connecting ...");
                using (var conn = new NetworkConnection(IPAddress.Loopback, @params, blockStore.GetChainHead().Height, 60000))
                {
                    var chain = new BlockChain(@params, wallet, blockStore);
                    var peer  = new Peer(@params, conn, chain);
                    peer.Start();

                    // We want to know when the balance changes.
                    wallet.CoinsReceived +=
                        (sender, e) =>
                    {
                        // Running on a peer thread.
                        Debug.Assert(!e.NewBalance.Equals(0));
                        // It's impossible to pick one specific identity that you receive coins from in BitCoin as there
                        // could be inputs from many addresses. So instead we just pick the first and assume they were all
                        // owned by the same person.
                        var input = e.Tx.Inputs[0];
                        var from  = input.FromAddress;
                        var value = e.Tx.GetValueSentToMe(wallet);
                        Console.WriteLine("Received " + Utils.BitcoinValueToFriendlyString(value) + " from " + from);
                        // Now send the coins back!
                        var sendTx = wallet.SendCoins(peer, from, value);
                        Debug.Assert(sendTx != null);     // We should never try to send more coins than we have!
                        Console.WriteLine("Sent coins back! Transaction hash is " + sendTx.HashAsString);
                        wallet.SaveToFile(walletFile);
                    };

                    var progress = peer.StartBlockChainDownload();
                    var max      = progress.Count; // Racy but no big deal.
                    if (max > 0)
                    {
                        Console.WriteLine("Downloading block chain. " + (max > 1000 ? "This may take a while." : ""));
                        var current     = max;
                        var lastPercent = 0;
                        while (current > 0)
                        {
                            var pct = 100.0 - (100.0 * (current / (double)max));
                            if ((int)pct != lastPercent)
                            {
                                Console.WriteLine(string.Format("Chain download {0}% done", (int)pct));
                                lastPercent = (int)pct;
                            }
                            progress.Await(TimeSpan.FromSeconds(1));
                            current = progress.Count;
                        }
                    }
                    Console.WriteLine("Send coins to: " + key.ToAddress(@params));
                    Console.WriteLine("Waiting for coins to arrive. Press Ctrl-C to quit.");
                    // The peer thread keeps us alive until something kills the process.
                }
            }
        }