Пример #1
0
        static void Main(string[] args)
        {
            myBlockchain.InitializeChain();
            myBlockchain.AddGenesisBlock();
            string type = args[0];

            if (type == "-server")
            {
                server = new Server();
                server.Start(12000);
            }
            else if (type == "-client")
            {
                client.Connect("");
            }

            Console.WriteLine("=========================");
            Console.WriteLine("1. Connect to a server");
            Console.WriteLine("2. Add a transaction");
            Console.WriteLine("3. Display Blockchain");
            Console.WriteLine("4. Exit");
            Console.WriteLine("=========================");
            int selection = 0;

            while (selection != 4)
            {
                switch (selection)
                {
                case 2:
                    Console.WriteLine("Please enter the receiver name");
                    string receiverName = Console.ReadLine();
                    Console.WriteLine("Please enter the amount");
                    string amount = Console.ReadLine();
                    myBlockchain.CreateTransaction(new Transaction("Jacky", "Marley", 10));
                    myBlockchain.ProcessPendingTransaction("Bill");
                    client.Broadcast(JsonConvert.SerializeObject(myBlockchain));
                    break;

                case 3:
                    Console.WriteLine("Blockchain");
                    Console.WriteLine(JsonConvert.SerializeObject(myBlockchain, Formatting.Indented));
                    break;
                }
                Console.WriteLine("Please select an action");
                string action = Console.ReadLine();
                selection = int.Parse(action);
            }
        }
Пример #2
0
        static void Main(string[] args)
        {
            var server = new P2PServer();
            var client = new P2PClient();
            var resp   = Console.ReadLine();

            if (Uri.IsWellFormedUriString(resp, UriKind.Absolute))
            {
                blockchain.AddGenesisBlock();
                client.Connect(resp);
            }
            else if (int.TryParse(resp, out var port))
            {
                server.Start(port);
            }
            Console.ReadLine();
        }
Пример #3
0
        static void Main(string[] args)
        {
            blockchain.Difficulty = 4;

            if (args.Length >= 1)
            {
                Port = int.Parse(args[0]);
            }
            if (args.Length >= 2)
            {
                name = args[1];
            }

            if (Port > 0)
            {
                Server = new P2PServer();
                Server.Start();
            }
            if (name != "Unkown")
            {
                Console.WriteLine($"Current user is {name}");
            }

            blockchain.AddGenesisBlock();

            int selection = 0;

            while (selection != 4)
            {
                switch (selection)
                {
                case 1:
                    Console.WriteLine("Please enter the server URL (enter 0 to cancel the operation)");
                    string serverURL = Console.ReadLine();
                    if (serverURL == "0")
                    {
                        break;
                    }
                    Client.Connect($"{serverURL}/Blockchain");
                    break;

                case 2:
                    Console.WriteLine("Please enter the receiver name (enter 0 to cancel the operation)");
                    string receiverName = Console.ReadLine();
                    if (receiverName == "0")
                    {
                        break;
                    }
                    Console.WriteLine("Please enter the amount (enter 0 to cancel the operation)");
                    string amount = Console.ReadLine();
                    if (amount == "0")
                    {
                        break;
                    }
                    blockchain.CreateTransaction(new Transaction(name, receiverName, int.Parse(amount)));
                    blockchain.ProcessPendingTransactions(name);
                    //Client.Broadcast(JsonConvert.SerializeObject(blockchain));
                    //communicationService.BroadcastBlockchain(blockchain);
                    break;

                case 3:
                    Console.WriteLine("Blockchain");
                    Console.WriteLine(JsonConvert.SerializeObject(blockchain, Formatting.Indented));
                    break;
                }

                Console.WriteLine("=========================");
                Console.WriteLine("1. Connect to a server");
                Console.WriteLine("2. Add a transaction");
                Console.WriteLine("3. Display Blockchain");
                Console.WriteLine("4. Exit");
                Console.WriteLine("=========================");
                Console.WriteLine("Please select an action");
                string action = Console.ReadLine();
                selection = int.Parse(action);
            }

            if (Client != null)
            {
                try
                {
                    Client.Close();
                }
                finally
                {
                    Client = null;
                }
            }
        }
Пример #4
0
        static void Main(string[] args)
        {
            // //1. Senaryo
            // Wallet wallet1 = new Wallet();
            // Wallet wallet2 = new Wallet();

            // Console.WriteLine($"\nWallet1's Private and public keys:");
            // Console.WriteLine($"\nPrivateKey: {SecurityUtil.GetPrivateKeyBase64(wallet1.PrivateKey)}");
            // Console.WriteLine($"\nPublicKey: {SecurityUtil.GetPublicKeyBase64(wallet1.PublicKey)}");

            // Console.WriteLine($"\nWallet2's Private and public keys:");
            // Console.WriteLine($"\nPrivateKey: {SecurityUtil.GetPrivateKeyBase64(wallet2.PrivateKey)}");
            // Console.WriteLine($"\nPublicKey: {SecurityUtil.GetPublicKeyBase64(wallet2.PublicKey)}");

            // Transaction transaction = new Transaction(wallet1.PublicKey, wallet2.PublicKey, 5, null);
            // transaction.GenerateSignature(wallet1.PrivateKey);

            // Console.WriteLine($"\nIs signature verified");
            // Console.WriteLine(transaction.VerifiySignature());

            // Console.ReadLine();

            ////2. Senaryo
            //A instance is taken from BlockChain.
            Blockchain myCoin = new Blockchain();

            List <Wallet> walletList = new List <Wallet>();

            //Create wallets:
            Wallet baseWallet = new Wallet();

            Wallet walletA = new Wallet();

            walletList.Add(walletA);
            Wallet walletB = new Wallet();

            walletList.Add(walletB);
            Wallet walletC = new Wallet();

            walletList.Add(walletC);

            //Create genesis transaction which sends 1000 MyCoin to walletA
            genesisTransaction = new Transaction(baseWallet.PublicKey, walletA.PublicKey, 1000f, null);
            //Signature the genesis transaction	as manually
            genesisTransaction.GenerateSignature(baseWallet.PrivateKey);
            //Set the transactionid	as manually
            genesisTransaction.TransactionID = "0";
            //Add the Transactions Output as manually
            genesisTransaction.OutputList.Add(new TransactionOutput(genesisTransaction.Receiver, genesisTransaction.Amount, genesisTransaction.TransactionID));
            //Genesis Transaction Output must be in blockchain output list. It is important
            Blockchain.UtxOutputList.Add(genesisTransaction.OutputList[0].Id, genesisTransaction.OutputList[0]);

            Console.WriteLine("Creating and Mining Genesis block...");
            myCoin.AddGenesisBlock(genesisTransaction);

            writeWalletsBalance(walletList);

            Block block1 = new Block(DateTime.Now, Blockchain.BlockChain[0].CurrentBlockHash);

            Console.WriteLine("\n * - Wallet1 is generating a transaction to send coins 100 to Wallet2...");
            block1.AddTransaction(walletA.SendCoin(walletB.PublicKey, 100f));
            myCoin.AddBlock(block1);

            writeWalletsBalance(walletList);

            Block block2 = new Block(DateTime.Now, block1.CurrentBlockHash);

            Console.WriteLine("\n * - Wallet2 is generating a transaction to send coins 50 to Wallet1...");
            block2.AddTransaction(walletB.SendCoin(walletA.PublicKey, 50f));
            myCoin.AddBlock(block2);

            writeWalletsBalance(walletList);

            Block block3 = new Block(DateTime.Now, block2.CurrentBlockHash);

            Console.WriteLine("\n * - Wallet2 is is generating a transaction to send coins 30 to Wallet1...");
            block3.AddTransaction(walletB.SendCoin(walletA.PublicKey, 30f));
            myCoin.AddBlock(block3);

            writeWalletsBalance(walletList);

            Block block4 = new Block(DateTime.Now, block3.CurrentBlockHash);

            Console.WriteLine("\n * - Wallet1 is is generating a transaction to send coins 1000 to Wallet2...");
            block4.AddTransaction(walletA.SendCoin(walletB.PublicKey, 1000f));
            myCoin.AddBlock(block4);

            writeWalletsBalance(walletList);

            Block block5 = new Block(DateTime.Now, block4.CurrentBlockHash);

            Console.WriteLine("\n * - Wallet1 is generating a transaction to send coins 300 to Wallet2...");
            block5.AddTransaction(walletA.SendCoin(walletB.PublicKey, 300f));
            myCoin.AddBlock(block5);

            writeWalletsBalance(walletList);

            //Testing multiple transaction inside one block
            Block block6 = new Block(DateTime.Now, block5.CurrentBlockHash);

            Console.WriteLine("\n * - Wallet1 is is generating a transaction to send coins 600 to Wallet3...");
            block6.AddTransaction(walletA.SendCoin(walletC.PublicKey, 600f));
            Console.WriteLine("\n * - Wallet1 is is generating a transaction to send coins 80 to Wallet2...");
            block6.AddTransaction(walletA.SendCoin(walletB.PublicKey, 80f));
            myCoin.AddBlock(block6);

            writeWalletsBalance(walletList);

            //Check blockChain is valid
            Console.WriteLine($"\nState of BlockChain Validation: { myCoin.IsChainValid() }");


            //Last State of BlockChain
            Console.WriteLine(JsonConvert.SerializeObject(Blockchain.BlockChain, Formatting.Indented));

            Console.ReadKey();
        }
Пример #5
0
        private void MessageReceived(byte[] message)
        {
            MessagePack mp = (Blockchain.ByteArrayToObject(message)) as MessagePack;

            if (mp.Text != null)
            {
                string[] tokens = mp.Text.Split(new string[] { @";" }, StringSplitOptions.None);

                string sender   = (tokens[0] == userName) ? "me" : "other";
                string function = tokens[1];

                switch (function)
                {
                case "request":
                    if (sender == "me")
                    {
                        string hash = chain.Chain[chain.Chain.Count() - 1].Hash;
                        mp.Text = "Nobody" + ";requestUpdate;" + hash + ";" + userName;
                        //mp.Val.Add(hash);
                        //mp.Val.Add(length.ToString());
                        byte[] data = Blockchain.ObjectToByteArray(mp);
                        sendingClient.Send(data, data.Length);
                    }
                    break;

                case "requestUpdate":
                    if (sender == "other")
                    {
                        string hash = chain.Chain[chain.Chain.Count() - 1].Hash;
                        if (hash != tokens[2])
                        {
                            mp.Text = userName + ";peerReady;" + tokens[3] + ";" + hash;
                            byte[] data = Blockchain.ObjectToByteArray(mp);
                            sendingClient.Send(data, data.Length);
                        }
                    }
                    break;

                case "peerReady":
                    peerNames.Add(tokens[0]);
                    if (sender == "other" && tokens[2] == userName && peerNames[0] == tokens[0])
                    {
                        int    length = chain.Chain.Count();
                        string hash   = chain.Chain[chain.Chain.Count() - 1].Hash;
                        if (hash != tokens[3] && length != 1)
                        {
                            mp.Text = userName + ";chainRequest;" + tokens[0] + ";" + hash;
                            byte[] data = Blockchain.ObjectToByteArray(mp);
                            sendingClient.Send(data, data.Length);
                        }
                        else if (hash == tokens[3])
                        {
                            MessageBox.Show("Czy padany łańcuch jest poprawny: " + chain.IsValid().ToString());
                            if (chain.IsValid() == false || chain.Chain.Count() == 0)
                            {
                                chain = new Blockchain();
                                chain.AddGenesisBlock();
                                hash    = chain.Chain[chain.Chain.Count() - 1].Hash;
                                mp.Text = "Nobody" + ";requestUpdate;" + hash + ";" + userName;
                                //mp.Val.Add(hash);
                                //mp.Val.Add(length.ToString());
                                byte[] data = Blockchain.ObjectToByteArray(mp);
                                sendingClient.Send(data, data.Length);
                            }
                        }
                        else
                        {
                            rtbChat.Text = null;
                            chain        = new Blockchain();
                            mp.Text      = userName + ";chainRequest;" + tokens[0] + ";" + hash;
                            byte[] data = Blockchain.ObjectToByteArray(mp);
                            sendingClient.Send(data, data.Length);
                        }
                    }
                    break;

                case "chainRequest":
                    if (sender == "other" && tokens[2] == userName)
                    {
                        if (chain.Chain.Find(i => i.Hash == tokens[3]) != null)
                        {
                            Block        lastBlock   = chain.Chain.Find(i => i.Hash == tokens[3]);
                            int          startIndex  = lastBlock.Index + 1;
                            int          finishIndex = lastBlock.Index + 10;
                            int          lastIndex   = chain.Chain[chain.Chain.Count() - 1].Index;
                            List <Block> newBlocks   = new List <Block>();

                            if ((lastIndex - lastBlock.Index) < 10)
                            {
                                finishIndex = lastIndex + 1;
                            }

                            for (int i = startIndex; i < finishIndex; i++)
                            {
                                newBlocks.Add(chain.Chain[i]);
                            }
                            mp.Text         = userName + ";newBlockchain;" + tokens[0];
                            mp.listOfBlocks = newBlocks;
                            byte[] data = Blockchain.ObjectToByteArray(mp);
                            sendingClient.Send(data, data.Length);
                        }
                        else
                        {
                            List <Block> newBlocks = new List <Block>();

                            for (int i = 0; i < 10; i++)
                            {
                                newBlocks.Add(chain.Chain[i]);
                            }
                            mp.Text         = userName + ";newBlockchain;" + tokens[0];
                            mp.listOfBlocks = newBlocks;
                            byte[] data = Blockchain.ObjectToByteArray(mp);
                            sendingClient.Send(data, data.Length);
                        }
                    }
                    break;

                case "newBlockchain":
                    if (sender == "other" && tokens[2] == userName)
                    {
                        foreach (Block el in mp.listOfBlocks)
                        {
                            chain.Chain.Add(el);
                            rtbChat.Text += el.Data + "\n";
                        }
                        string hash = chain.Chain[chain.Chain.Count() - 1].Hash;
                        mp.Text = "Nobody" + ";requestUpdate;" + hash + ";" + userName;
                        //mp.Val.Add(hash);
                        //mp.Val.Add(length.ToString());

                        byte[] data = Blockchain.ObjectToByteArray(mp);
                        sendingClient.Send(data, data.Length);
                        Blockchain.SerializeToJson(chain);
                        peerNames.Clear();
                    }
                    break;
                }
            }
            else
            {
                chain.AddBlock(mp.SmObj);
                rtbChat.Text += chain.Chain[chain.Chain.Count() - 1].Data + "\n";
                Blockchain.SerializeToJson(chain);
            }
        }