Пример #1
0
        public void Receive(TcpClient client)
        {
            while (listening)
            {
                BlockChain newChain = JsonConvert.DeserializeObject <BlockChain>(Chat.Recieve(client));

                if (newChain.IsValid() && newChain.Chain.Count > Program.Blockchain.Chain.Count)
                {
                    List <Transaction> newTransactions = new List <Transaction>();
                    newTransactions.AddRange(newChain.PendingTransactions);
                    newTransactions.AddRange(Program.Blockchain.PendingTransactions);

                    newChain.PendingTransactions = newTransactions;
                    newChain.PrintExtends(Program.Blockchain);
                    Program.Blockchain = newChain;
                }
            }
        }
        public static void SetMinersTrue(string ip, long blockID)
        {
            int   minerIndex   = FindIndexOfGivenInput(ip);
            var   keyValuePair = GetBlockInProcessingBlock(blockID);
            int   blockIndex   = keyValuePair.Key;
            Block block        = keyValuePair.Value;

            if (block == null)
            {
                return;
            }

            if (miners[minerIndex][blockIndex].Key.BlockID == block.BlockID)
            {
                miners[minerIndex].RemoveAt(blockIndex);
                miners[minerIndex].Add(new KeyValuePair <Block, bool>(block, true));
                BlockChain.TryToAddChain(block);
            }
        }
        public static void UpdateProcessingBlockList(Block block)
        {
            int   myIndex         = FindIndexOfGivenInput(TCP.myIP);
            var   keyValuePair    = GetBlockInProcessingBlock(block.BlockID);
            int   blockIndex      = keyValuePair.Key;
            Block processingBlock = keyValuePair.Value;

            if (processingBlock == null)
            {
                return;
            }

            if (miners[myIndex][blockIndex].Key.Time.CompareTo(block.Time) >= 0)
            {
                miners[myIndex].RemoveAt(blockIndex);
                processingBlock.Time  = block.Time;
                processingBlock.Nonce = block.Nonce;
                processingBlock.Hash  = block.Hash;
                miners[myIndex].Add(new KeyValuePair <Block, bool>(processingBlock, true));
            }
            BlockChain.TryToAddChain(processingBlock);
        }
Пример #4
0
        public void FinishHandshake(TcpClient client)
        {
            string key = ToString(client.Client.RemoteEndPoint);

            if (!_wsDict.ContainsKey(key))
            {
                string recieved = Chat.Recieve(client);

                if (recieved == "HISERVER")
                {
                    Chat.PrintLog("Recieved handshake request!");
                    Chat.Send(client, "HICLIENT");
                }

                recieved = Chat.Recieve(client);
                BlockChain newChain = JsonConvert.DeserializeObject <BlockChain>(recieved);

                if (newChain.IsValid() && newChain.Chain.Count > Program.Blockchain.Chain.Count)
                {
                    List <Transaction> newTransactions = new List <Transaction>();
                    newTransactions.AddRange(newChain.PendingTransactions);
                    newTransactions.AddRange(Program.Blockchain.PendingTransactions);

                    newChain.PendingTransactions = newTransactions;
                    newChain.PrintExtends(Program.Blockchain);
                    Program.Blockchain = newChain;

                    Chat.Send(client, "GOODCHAIN");
                }
                else
                {
                    Chat.Send(client, JsonConvert.SerializeObject(Program.Blockchain));
                }

                _wsDict.Add(key, client);
                Task.Run(() => Receive(client));
            }
        }
Пример #5
0
        public void InitiateHandshake(string address, int port)
        {
            if (!_wsDict.ContainsKey(address + port))
            {
                Chat.PrintLog("Connecting to node...");
                TcpClient client = new TcpClient(address, port);

                Chat.PrintLog("Sending handshake to node...");
                Chat.Send(client, "HISERVER");
                if (Chat.Recieve(client) != "HICLIENT")
                {
                    Chat.PrintLog("Unable to recieve handshake from node.");
                    return;
                }
                Chat.PrintLog("Recieved handshake from node!");

                Chat.Send(client, JsonConvert.SerializeObject(Program.Blockchain));
                string retval = Chat.Recieve(client);
                if (retval != "GOODCHAIN")
                {
                    BlockChain newChain = JsonConvert.DeserializeObject <BlockChain>(retval);
                    if (newChain.IsValid() && newChain.Chain.Count > Program.Blockchain.Chain.Count)
                    {
                        List <Transaction> newTransactions = new List <Transaction>();
                        newTransactions.AddRange(newChain.PendingTransactions);
                        newTransactions.AddRange(Program.Blockchain.PendingTransactions);

                        newChain.PendingTransactions = newTransactions;
                        Program.Blockchain           = newChain;
                    }
                }

                _wsDict.Add(ToString(client.Client.RemoteEndPoint), client);
                Task.Run(() => Receive(client));
            }
        }
Пример #6
0
 public Bloque GetUltimoBloque()
 {
     return(BlockChain.ElementAt(GetI() - 1));
 }
Пример #7
0
 public Bloque GetBloqueIndice(int p_ind)
 {
     return(BlockChain.ElementAt(p_ind));
 }
Пример #8
0
 private BlockChain()
 {
     GetChain();
     blockChainInstance = this;
 }
Пример #9
0
        public static void MainMethod()
        {
            string title = @"
   _____                   _        _____ _           _       
  / ____|                 | |      / ____| |         (_)      
 | (___  _   _ _ __  _ __ | |_   _| |    | |__   __ _ _ _ __  
  \___ \| | | | '_ \| '_ \| | | | | |    | '_ \ / _` | | '_ \ 
  ____) | |_| | |_) | |_) | | |_| | |____| | | | (_| | | | | |
 |_____/ \__,_| .__/| .__/|_|\__, |\_____|_| |_|\__,_|_|_| |_|
              | |   | |       __/ |                           
              |_|   |_|      |___/                            
";

            Console.WriteLine(title);
            Console.WriteLine(
                "Command List: \n" +
                "connect [ip] --> Connect to website and join other miners. [ip] is webserver's ip.\n" +
                "print [id] --> Print block which given id\n" +
                "exit --> Leave the network\n" +
                "quit --> exit application\n");

            while (true)
            {
                string command = Console.ReadLine();
                command = command.ToLower();

                if (command.StartsWith("connect"))
                {
                    if (command.Length > 8)
                    {
                        command = command.Substring(8);
                    }
                    else
                    {
                        Console.WriteLine("Please enter the ip");
                        continue;
                    }
                    if (!command.Contains("."))
                    {
                        Console.WriteLine("Please enter the ip");
                        continue;
                    }
                    TCP.WebServerIp = command;
                    Miners.ConnectToNetwork();
                    continue;
                }
                if (command.StartsWith("print"))
                {
                    command = command.Substring(6);
                    Console.WriteLine(BlockChain.GetBlock(int.Parse(command)).ToString());
                    break;
                }
                if (command.StartsWith("chain"))
                {
                    Console.WriteLine("\n--------BLOCKCHAIN--------");
                    BlockChain.GetChain().ForEach(b => Console.WriteLine(b.ToString()));
                    Console.WriteLine("--------BLOCKCHAIN--------\n");
                }
                if (command.StartsWith("get"))
                {
                    if (BlockChain.GetChain().Count == 1)
                    {
                        TCP.Send(Miners.minerIPs[0], "getChain");
                    }
                    else
                    {
                        Console.WriteLine("Already have chain");
                    }
                }
                if (command.StartsWith("read"))
                {
                    string path = command.Substring(5);
                    string st   = File.ReadAllText(path);
                    object ret  = TCP.JsonDeserialize(st);
                    var    obj  = TCP.Cast(ret, new { list = new List <Block>() });
                    BlockChain.SetChain(obj.list);
                    TCP.SendWebServer("addMeNow");
                }
                if (command.StartsWith("write"))
                {
                    string path = command.Substring(6);
                    string st   = TCP.JsonSerialize(new { list = BlockChain.GetChain() });
                    File.WriteAllText(path, st);
                }
                if (command.Equals("exit"))
                {
                    Console.WriteLine("Leaving network...\nPlease press a key");
                    Console.ReadKey();
                    Console.Clear();
                    MainMethod();
                    break;
                }
                if (command.Equals("quit"))
                {
                    Environment.Exit(0);
                }
            }
        }
        private static void Interpreter(string message, string ip)
        {
            message = message.Replace("SupplyChain", "Blockchain");
            // received miners list
            if (message.StartsWith("minersList"))
            {
                message = message.Substring(10);
                object ret = JsonDeserialize(message);
                var    obj = Cast(ret, new { list = new List <string>() });
                Miners.minerIPs = obj.list;
                Console.WriteLine("Current miner count: " + Miners.minerIPs.Count);

                for (int a = 0; a < Miners.minerIPs.Count; a++)
                {
                    Miners.miners.Add(new List <KeyValuePair <Block, bool> >());
                }

                if (Miners.minerIPs.Count == 0)
                {
                    BlockChain.GetChain();
                    SendWebServer("addMeNow");
                }

                return;
            }

            // received a new block to add
            if (message.StartsWith("addBlock"))
            {
                Data data = (Data)JsonDeserialize(message.Substring(8));
                BlockChain.ReceiveNewBlock(data);
                return;
            }

            if (message.StartsWith("checkNonce"))
            {
                message = message.Substring(10);
                string[] checkNonceArray = message.Split('$');
                Miners.SetMyMinerTrue(DateTime.Parse(checkNonceArray[0]), long.Parse(checkNonceArray[1]), Int32.Parse(checkNonceArray[2]), ip);
                return;
            }

            if (message.StartsWith("nonceIsTrue"))
            {
                message = message.Substring(11);
                Miners.SetMinersTrue(ip, long.Parse(message));
                return;
            }

            if (message.StartsWith("getChain"))
            {
                Send(ip, "receiveChain" + JsonSerialize(new { chain = BlockChain.GetChain() }));
                return;
            }

            if (message.StartsWith("receiveChain"))
            {
                object ret = JsonDeserialize(message.Substring(12));
                var    obj = Cast(ret, new { chain = new List <Block>() });
                BlockChain.ReceiveChain(obj.chain);
                return;
            }

            if (message.StartsWith("newMinerJoined"))
            {
                message = message.Substring(14);
                Miners.minerIPs.Add(message);
                Miners.miners.Add(new List <KeyValuePair <Block, bool> >());
                if (message == myIP)
                {
                    Console.WriteLine("\n-------Connected to network!-------\n");
                }
                else
                {
                    Console.WriteLine("New miner joined to network -> " + message);
                }
                Console.WriteLine("Current miner count: " + Miners.minerIPs.Count);
                return;
            }

            if (message.StartsWith("verify"))
            {
                message = message.Substring(6);
                Product product = BlockChain.GetProductInfo(long.Parse(message));
                SendWebServer("verifyReturn" + JsonSerialize(product));
                return;
            }

            if (message.StartsWith("block"))
            {
                message = message.Substring(5);
                Block takenBlock = (Block)JsonDeserialize(message);

                // wait until the block is inserted into chain
                bool wait = true;
                while (wait)
                {
                    List <Block> chain = BlockChain.GetChain();

                    try {
                        wait = !chain.Exists(b => b.BlockID.Equals(takenBlock.BlockID));
                    }
                    catch { }
                }

                Block currentBlock = BlockChain.GetBlock(takenBlock.BlockID);

                // change time earlier if taken one is earlier
                if (currentBlock.Time.CompareTo(takenBlock.Time) > 0)
                {
                    currentBlock.Time  = takenBlock.Time;
                    currentBlock.Nonce = takenBlock.Nonce;
                    currentBlock.Hash  = currentBlock.CalculateHash();
                }

                // change smaller nonce if the found dates equal
                if (currentBlock.Time.CompareTo(takenBlock.Time) == 0)
                {
                    currentBlock.Nonce = Math.Min(takenBlock.Nonce, currentBlock.Nonce);
                }
            }
        }