Пример #1
0
        // версия размер(версия+подпись) подпись(версия+информация)

        private async Task CheckVersion(byte[] data, IPEndPoint source)
        {
            string version;

            byte[] signature = new byte[0];
            byte[] last_data;
            string file_size = string.Empty;

            TwoBytesArrays temp = new TwoBytesArrays();

            temp      = ByteArrayCut(data, version_size);
            version   = BytesToOperation(temp.part1);
            last_data = temp.part2;

            temp      = ByteArrayCut(last_data, size_size);
            file_size = BytesToOperation(temp.part1);
            signature = temp.part2;

            window.WriteLine("Siganture: " + cryptography.HashToString(signature));

            if (String.CompareOrdinal(version, info.version) > 0)
            {
                last_data = Encoding.UTF8.GetBytes(source.Address.ToString());
                last_data = AddOperation("update|give", UDPServer.operation_size, last_data);
                await server.Send(source, last_data);
                await UpdateSelf(file_size, signature, source, version);
            }
            else
            {
                window.WriteLine("no updates");
            }
        }
Пример #2
0
        // HEADER: 1|username (16)|private_key size in bytes| walletdata

        public async Task MaketheWallet(string wallet_path, string username)
        {
            try
            {
                byte[] wallet = new byte[0];
                string header;
                string key;

                TwoBytesArrays temp = new TwoBytesArrays();
                key        = RsaCryptoService.ToXmlString(true);
                temp.part1 = Encoding.UTF8.GetBytes(key);

                key        = RsaCryptoService.ToXmlString(false);
                temp.part2 = Encoding.UTF8.GetBytes(key);

                wallet = ByteArrayJoin(temp);

                header = "1|" + username + "|" + temp.part1.Length;
                wallet = AddOperation(header, header_size, wallet);

                wallet_path = wallet_path + @"\wallet";
                int r = await filesystem.AddInfoToFileAsync(wallet_path, wallet, true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Пример #3
0
        public static byte[] ByteArrayJoin(TwoBytesArrays data)
        {
            byte[] resultArray = new byte[data.part1.Length + data.part2.Length];

            Array.Copy(data.part1, 0, resultArray, 0, data.part1.Length);
            Array.Copy(data.part2, 0, resultArray, data.part1.Length, data.part2.Length);

            return(resultArray);
        }
Пример #4
0
        public byte[] MakeTMessage(Transaction transaction, string private_key)
        {
            byte[] result_data = new byte[0];

            try
            {
                byte[] body_data;
                string header;
                string tempstr    = string.Empty;
                string operations = string.Empty;
                string key        = private_key;
                int    info       = 0;

                TwoBytesArrays temp            = new TwoBytesArrays();
                byte[]         additional_info = new byte[0];

                info = transaction.information.Length;

                operations = transaction.input.put
                             + "|" + transaction.input.value
                             + "|" + transaction.output.put
                             + "|" + transaction.output.value
                             + "|" + GetDate()
                             + "|" + transaction.public_key;

                temp.part1 = Encoding.UTF8.GetBytes(operations);
                temp.part2 = ByteArrayFill(transaction.information, Transactions.size_info_in_transaction);
                body_data  = ByteArrayJoin(temp);

                temp.part1 = body_data;
                temp.part2 = cryptography.Sign(body_data, key);
                body_data  = ByteArrayJoin(temp);

                //window.WriteLine("Body hash: " + cryptography.HashToString(cryptography.GetSHA256Hash(temp.part1)));
                //window.WriteLine("Signature hash: " + cryptography.HashToString(cryptography.GetSHA256Hash(temp.part2)));

                header = transaction.version + "|" + temp.part1.Length + "|" + info;

                result_data = AddOperation(header, Transactions.size_header, body_data);

                Transaction tmp = ParseTMessage(result_data);

                //WriteToConsole(tmp);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            return(result_data);
        }
Пример #5
0
        // версия+информация
        private async Task UpdateSelf(string size_str, byte[] signature, IPEndPoint source, string new_version)
        {
            try
            {
                window.WriteLine("Client pending: " + size_str);
                window.WriteLine("nv: " + new_version);

                int    size   = Convert.ToInt32(size_str);
                byte[] buffer = await filetransfering.TcpDataGet(source, size);

                byte[] hash = cryptography.GetSHA256Hash(buffer);

                window.WriteLine("Client got: " + buffer.Length + " bytes");

                TwoBytesArrays temp = new TwoBytesArrays();
                temp = ByteArrayCut(buffer, version_size);
                string version = string.Empty;

                version = BytesToOperation(temp.part1);

                window.WriteLine("Version " + version + " ready");
                window.WriteLine("Client: " + temp.part1.Length + " + " + temp.part2.Length + " = " + (temp.part1.Length + temp.part2.Length));
                window.WriteLine("Siganture: " + cryptography.HashToString(signature));
                window.WriteLine("Hash to check: " + cryptography.HashToString(hash));

                // hash(version[15] + hash(row_data)[64]);

                window.WriteLine("exe hash: " + cryptography.HashToString(cryptography.GetSHA256Hash(temp.part2)));

                if (cryptography.VerifySign(hash, signature, Information.admin_public_key))
                {
                    window.WriteLine("Update to version: " + version + " started");
                    update_data = temp.part2;
                    window.WriteLine("Update to : " + update_data.Length);

                    window.ShowUpdateAvailable(version, update_data);
                }
                else
                {
                    window.WriteLine("Wrong signature");
                }
            }
            catch (Exception e)
            {
                window.WriteLine(e.ToString());
            }
        }
Пример #6
0
        public string GetBlockName(byte[] block)
        {
            string result = string.Empty;

            if (block != null)
            {
                TwoBytesArrays temp = new TwoBytesArrays();

                temp = ByteArrayCut(block, Blocks.header_info_size);
                int header_size = Convert.ToInt32(BytesToOperation(temp.part1));
                temp = ByteArrayCut(temp.part2, header_size);

                result = cryptography.HashToString(cryptography.GetSHA256Hash(temp.part1));
            }

            return(result);
        }
Пример #7
0
        public async Task <List <string> > OpentheWallet(string path)
        {
            List <string> result = new List <string>(0);

            if (File.Exists(path))
            {
                string         header = string.Empty;
                byte[]         keys;
                TwoBytesArrays temp   = new TwoBytesArrays();
                List <string>  sizes  = new List <string>();
                byte[]         wallet = new byte[0];

                wallet = await filesystem.GetFromFileAsync(path);

                temp   = ByteArrayCut(wallet, header_size);
                header = BytesToOperation(temp.part1);
                keys   = temp.part2;

                if (header[0] == '1')
                {
                    //Console.WriteLine("Correct password");

                    sizes.AddRange(header.Split('|'));
                }

                temp = ByteArrayCut(temp.part2, Convert.ToInt32(sizes[2]));

                private_key = BytesToOperation(temp.part1);
                public_key  = BytesToOperation(temp.part2);

                /*
                 * Console.WriteLine(private_key);
                 * Console.WriteLine("===========================");
                 * Console.WriteLine(public_key);
                 */
                RsaCryptoService.FromXmlString(private_key);
                RsaCryptoService.FromXmlString(public_key);

                result.Add(sizes[1]);
                result.Add(private_key);
                result.Add(public_key);
            }

            return(result);
        }
Пример #8
0
        public async Task <int> Initialize(Cryptography main_cryptography, Blocks mine, FileSystem main_filesystem, UDPServer server, bool main_debug)
        {
            byte[] data;
            try
            {
                cryptography = main_cryptography;
                filesystem   = main_filesystem;
                debug        = main_debug;

                version       = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                self_location = System.Reflection.Assembly.GetExecutingAssembly().Location;

                data = await filesystem.GetFromFileAsync(self_location);

                self_size = data.Length;

                exe_hash = cryptography.GetSHA256Hash(data);

                TwoBytesArrays temp = new TwoBytesArrays();
                temp.part1 = OperationToBytes(version, Updating.version_size);
                temp.part2 = data;

                data = ByteArrayJoin(temp);

                signed_hash = cryptography.GetSHA256Hash(data);

                block_version = Blocks.block_version;

                await ActualizeSelfSignature();

                filesystem_version = filesystem.FSConfig.version;

                port = server.Port;

                //window.WriteLine("class Information: initialized");

                return(1);
            }
            catch (Exception e)
            {
                Debug.WriteLine("class Information: FAILED");
                Debug.WriteLine(e.ToString());
                return(0);
            }
        }
Пример #9
0
        public async Task <string> BlockChainCheckLeft(byte[] block)
        {
            string result = string.Empty;

            TwoBytesArrays temp      = new TwoBytesArrays();
            Block          new_block = new Block();
            string         path      = filesystem.FSConfig.db_blocks_path;
            string         str;

            byte[] data = new byte[0];


            string real_name = GetBlockName(block);

            if (CheckBlockHash(real_name))
            {
                new_block = BlockDeSerialize(block);

                if (new_block.previous != Blocks.first_block)
                {
                    data = await SearchBlock(new_block.previous);

                    if (data.Length != 0)
                    {
                        str = await BlockChainCheckLeft(data);

                        if (str == Blocks.first_block)
                        {
                            result = real_name;
                        }
                    }
                }
                else
                {
                    result = real_name;
                }
            }
            else
            {
                window.WriteLine("[block]: wrong type");
            }

            return(result);
        }
Пример #10
0
        public async Task SwitchLogic(byte[] incoming_data, IPEndPoint source)
        {
            try
            {
                string         operation = string.Empty;
                string         path      = string.Empty;
                TwoBytesArrays temp      = new TwoBytesArrays();

                temp = ByteArrayCut(incoming_data, AdminClass.command_size);

                operation  = BytesToOperation(temp.part1);
                temp.part1 = Encoding.UTF8.GetBytes(operation);

                window.WriteLine("[admin]: " + operation);

                if (admin.CheckAdminSignature(temp.part1, temp.part2))
                {
                    switch (operation)
                    {
                    case "update":
                        window.WriteLine("[admin] updating");
                        await update.CheckForUpdate();

                        break;

                    case "scan":
                        window.WriteLine("[admin] scanning");
                        break;

                    default:
                        break;
                    }
                }
                else
                {
                    window.WriteLine("Hacking trying");
                }
            }
            catch (Exception ex)
            {
                window.WriteLine(ex.ToString());
            }
        }
Пример #11
0
        public static TwoBytesArrays ByteArrayCut(byte[] data, int part)
        {
            TwoBytesArrays result = new TwoBytesArrays();

            result.part1 = new byte[part];
            if (data.Length >= part)
            {
                result.part2 = new byte[data.Length - part];
            }

            if (data.Length >= part)
            {
                Array.Copy(data, result.part1, part);
                Array.Copy(data, part, result.part2, 0, result.part2.Length);
            }
            else
            {
                result.part1 = data;
            }

            return(result);
        }
Пример #12
0
        private async Task AnswerLogic(byte[] incoming_data, IPEndPoint source)
        {
            try
            {
                TwoBytesArrays TWdata    = new TwoBytesArrays();
                byte[]         data      = new byte[0];
                string         operation = string.Empty;
                string         path      = string.Empty;
                int            size      = 0;
                string         name;

                TWdata    = ByteArrayCut(incoming_data, GetLogic.operation_size);
                operation = BytesToOperation(TWdata.part1);

                window.WriteLine("Got AnswerLogic: " + operation);
                if (TWdata.part2.Length != 0)
                {
                    switch (operation)
                    {
                    case "signature":
                        path = filesystem.FSConfig.root_path + @"\signature";
                        window.WriteLine("Writing: " + path + " " + TWdata.part2.Length);
                        await filesystem.AddInfoToFileAsync(path, TWdata.part2, true);

                        await information.ActualizeSelfSignature();

                        break;

                    case "actualblock":
                        if (waitingforactual)
                        {
                            string new_actual = Encoding.UTF8.GetString(TWdata.part2);
                            path = filesystem.FSConfig.db_blocks_path + @"\actualblock";

                            window.WriteLine("AnswerLogic.actualblock " + new_actual);
                            data = await blocks.SearchBlock(new_actual);

                            if (data.Length == 0)
                            {
                                waitingfornewactual = true;
                            }
                            else
                            {
                                await filesystem.AddInfoToFileAsync(path, TWdata.part2, true);

                                path = filesystem.FSConfig.db_blocks_path;
                                string current       = Encoding.UTF8.GetString(await filesystem.GetFromFileAsync(path));
                                byte[] current_array = await filesystem.GetFromFileAsync(path + @"\" + current);

                                byte[] new_array = await filesystem.GetFromFileAsync(path + @"\" + new_actual);

                                Block current_block = new Block();
                                Block new_block     = new Block();

                                current_block = blocks.BlockDeSerialize(current_array);
                                new_block     = blocks.BlockDeSerialize(new_array);

                                if (current_block.time < new_block.time)
                                {
                                    await blocks.ActualBlockSet(new_actual);
                                }
                            }
                            waitingforactual = false;
                        }
                        break;

                    case "block":
                        //window.WriteLine("Got AnswerLogic block");

                        size = Convert.ToInt32(Encoding.UTF8.GetString(TWdata.part2));
                        window.WriteLine("getting block from: " + source.ToString());
                        data = await filetransfering.TcpDataGet(source, size);

                        window.WriteLine("Block got");
                        name = blocks.GetBlockName(data);

                        if (name != string.Empty)
                        {
                            path = filesystem.FSConfig.db_blocks_path + @"\" + name;
                            window.WriteLine("new block: " + path);
                            await filesystem.AddInfoToFileAsync(path, data, true);

                            if (waitingfornewactual)
                            {
                                waitingfornewactual = false;
                                await blocks.ActualBlockSet(name);
                            }
                            else
                            {
                                await blocks.BlockChainActualize();
                            }
                        }

                        if (name.Length != 0)
                        {
                            window.WriteLine("block got: " + name);
                        }
                        else
                        {
                            window.WriteLine("wrong block");
                        }
                        break;

                    case "newblock":
                        //window.WriteLine("Got AnswerLogic block");

                        size = Convert.ToInt32(Encoding.UTF8.GetString(TWdata.part2));
                        window.WriteLine("getting newblock from: " + source.ToString());
                        data = await filetransfering.TcpDataGet(source, size);

                        window.WriteLine("newBlock got");
                        name = blocks.GetBlockName(data);

                        if (name != string.Empty)
                        {
                            path = filesystem.FSConfig.db_blocks_path + @"\" + name;
                            window.WriteLine("new block: " + path);
                            await filesystem.AddInfoToFileAsync(path, data, true);

                            await blocks.ActualBlockSet(name);
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                window.WriteLine(ex.ToString());
            }
        }
Пример #13
0
        public Transaction ParseTMessage(byte[] data)
        {
            Transaction result = new Transaction();

            try
            {
                byte[]   result_data = new byte[0];
                byte[]   signature   = new byte[0];
                string   operations  = string.Empty;
                string   tmp         = string.Empty;
                string[] tmp_list    = new string[0];
                byte[]   body_data   = new byte[0];
                int      info        = 0;
                int      bd_length   = 0;

                TwoBytesArrays temp = new TwoBytesArrays();

                temp     = ByteArrayCut(data, Transactions.size_header);
                tmp      = BytesToOperation(temp.part1);
                tmp_list = tmp.Split('|');

                result.version = Convert.ToInt32(tmp_list[0]);
                bd_length      = Convert.ToInt32(tmp_list[1]);
                info           = Convert.ToInt32(tmp_list[2]);

                temp      = ByteArrayCut(temp.part2, bd_length); //transaction
                signature = temp.part2;

                temp       = ByteArrayCut(temp.part1, temp.part1.Length - Transactions.size_info_in_transaction);
                operations = Encoding.UTF8.GetString(temp.part1);
                //Debug.WriteLine("operations[1]: " + cryptography.GetHashString(operations));
                //Debug.WriteLine("info[1]: " + cryptography.HashToString(cryptography.GetSHA256Hash(temp.part2)));

                tmp_list            = operations.Split('|');
                result.input.put    = tmp_list[0];
                result.input.value  = Convert.ToInt32(tmp_list[1]);
                result.output.put   = tmp_list[2];
                result.output.value = Convert.ToInt32(tmp_list[3]);
                result.date         = Convert.ToInt32(tmp_list[4]);
                result.public_key   = tmp_list[5];

                operations = string.Empty;
                operations = result.input.put
                             + "|" + result.input.value
                             + "|" + result.output.put
                             + "|" + result.output.value
                             + "|" + result.date
                             + "|" + result.public_key;


                result.information = ByteArrayGet(temp.part2, info);

                temp.part1 = Encoding.UTF8.GetBytes(operations);
                temp.part2 = ByteArrayFill(result.information, Transactions.size_info_in_transaction);
                body_data  = ByteArrayJoin(temp);

                //Debug.WriteLine("operations[2]: " + cryptography.GetHashString(operations));
                //Debug.WriteLine("info[2]: " + cryptography.HashToString(cryptography.GetSHA256Hash(temp.part2)));

                //window.WriteLine("Body hash: " + cryptography.HashToString(cryptography.GetSHA256Hash(body_data)));
                //window.WriteLine("Signature hash: " + cryptography.HashToString(cryptography.GetSHA256Hash(signature)));

                if (cryptography.VerifySign(body_data, signature, result.public_key))
                {
                    result.signature = signature;
                    result.name      = cryptography.HashToString(cryptography.GetSHA256Hash(data));
                }
                else
                {
                    window.WriteLine("Transaction checking error");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            return(result);
        }
Пример #14
0
        /// <summary>
        /// Проверка транзакции
        /// </summary>
        /// <param name="transaction"></param>
        /// <returns>
        /// 0 - не найдена транзакция-предшественник
        /// 1 - найдена глобальная (подтвержденная) транзакция-предшественник
        /// 2 - найдена локальная транзакция-предшественник, ссылающаяся на подтвержденную
        /// 9 - подпись неверна
        /// </returns>
        public async Task <int> CheckTransaction(Transaction transaction)
        {
            int result = 0;

            Transaction    temp_transaction = new Transaction();
            TwoBytesArrays temp             = new TwoBytesArrays();

            byte[] body_data;
            byte[] signature;
            string operations;

            operations = transaction.input.put
                         + "|" + transaction.input.value
                         + "|" + transaction.output.put
                         + "|" + transaction.output.value
                         + "|" + GetDate()
                         + "|" + transaction.public_key;

            temp.part1 = Encoding.UTF8.GetBytes(operations);
            temp.part2 = ByteArrayFill(transaction.information, Transactions.size_info_in_transaction);
            body_data  = ByteArrayJoin(temp);

            signature = transaction.signature;

            window.WriteLine("[tr] checking");
            WriteToConsole(transaction);

            if (cryptography.VerifySign(body_data, signature, transaction.public_key))
            {
                string search = transaction.input.put;

                if (search == "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918") //admin
                {
                    if (transaction.public_key == Information.admin_public_key)
                    {
                        result = 1;
                    }
                }
                else
                {
                    temp_transaction = await SearchTransactionLocal(search);

                    if (temp_transaction.public_key != null)
                    {
                        result = await CheckTransaction(temp_transaction);
                    }
                    else
                    {
                        result = 3;
                    }

                    if (temp_transaction.public_key != null)
                    {
                        result = 2;
                    }
                }
            }
            else
            {
                result = 9;
            }

            return(result);
        }
Пример #15
0
        public async Task GetLogic(IPEndPoint source, byte[] data)
        {
            try
            {
                TwoBytesArrays tran = new TwoBytesArrays();
                tran = ByteArrayCut(data, Transactions.size_suboperation);

                string   sub_operation = BytesToOperation(tran.part1);
                string[] sub           = sub_operation.Split('|');
                string   name;
                string   path;

                List <string> ip_list     = new List <string>(0);
                Transaction   transaction = new Transaction();

                window.WriteLine("[45]: " + sub[0] + " from " + source.ToString());
                window.WriteLine("[46]: " + sub_operation);

                if (sub[0] == "new")
                {
                    transaction = ParseTMessage(tran.part2);
                    window.WriteLine("[tr] Transaction got: ");
                    int check = await CheckTransaction(transaction);

                    window.WriteLine("[tr] Checking result: " + check);

                    if ((check == 2) || (check == 1))
                    {
                        name = cryptography.HashToString(cryptography.GetSHA256Hash(tran.part2));
                        path = filesystem.FSConfig.db_path + @"\" + name;

                        int status = await filesystem.AddInfoToFileAsync(path, tran.part2, true);

                        if (status != 3)
                        {
                            byte[] message = Encoding.UTF8.GetBytes(name);
                            message = AddOperation("confirm", Transactions.size_suboperation, message);
                            message = AddOperation("transaction", UDPServer.operation_size, message);

                            await server.Send(source, message);

                            if (debug)
                            {
                                window.WriteLine("Transaction (" + name + ") confirmed to " + source.ToString());
                            }
                        }


                        int sub_times = Convert.ToInt32(sub[1]) - 1;

                        if (sub_times >= 1)
                        {
                            List <string> known_hosts = await server.GetKnownList();

                            List <string> black_list = new List <string>(0);


                            black_list.Add(source.Address.ToString());
                            black_list.AddRange(server.myIpAddresses);

                            known_hosts = server.RemoveIPAddresses(known_hosts, black_list);

                            //await SendTransaction(tran.part2, sub_times, known_hosts);
                        }
                    }
                }

                if (sub[0] == "confirm")
                {
                    name = Encoding.UTF8.GetString(tran.part2);
                    if (debug)
                    {
                        window.WriteLine("Transaction (" + name + ") confirmed by " + source.ToString());
                    }
                }

                ip_list.Add(source.Address.ToString());
                await server.AddToKnownList(ip_list);
            }
            catch (Exception ex)
            {
                window.WriteLine(ex.ToString());
            }
        }
Пример #16
0
        private async void OnUdpData(IAsyncResult result)
        {
            // this is what had been passed into BeginReceive as the second parameter:
            //socket = result.AsyncState as UdpClient;
            // points towards whoever had sent the message:
            IPEndPoint source = new IPEndPoint(0, port);


            // get the actual message and fill out the source:
            try
            {
                byte[] message = socket.EndReceive(result, ref source);

                string operation_str = "status";


                TwoBytesArrays data = new TwoBytesArrays();
                data = ByteArrayCut(message, UDPServer.operation_size);

                operation_str = BytesToOperation(data.part1);

                string[] operations = operation_str.Split('|');


                foreach (var operation in operations)
                {
                    window.WriteLine("[operation]: " + operation);
                }


                switch (operations[0])
                {
                case "status":
                    ReturnStatus(source);
                    window.WriteLine("errrr");
                    break;

                case "registration":
                    List <string> reg_ip = new List <string>(1)
                    {
                        source.Address.ToString()
                    };
                    reg_ip = RemoveIPAddresses(reg_ip, myIpAddresses);

                    window.WriteLine(operations[0] + @"|" + operations[1] + " from " + source);

                    if (reg_ip.Count > 0)
                    {
                        await AddToKnownList(reg_ip);

                        if (operations[1] == "1")
                        {
                            byte[] temp = AddOperation("registration|0", operation_size, Encoding.UTF8.GetBytes("123456"));
                            await Send(source, temp);
                        }
                    }
                    break;

                case "update":
                    await update.UpdateLogic(operations[1], data.part2, source);

                    break;

                case "newupdate":
                    socket.Close();
                    window.WriteLine("New update from: " + source.Address.ToString());

                    break;

                case "transaction":
                    await transactions.GetLogic(source, data.part2);

                    break;

                case "message":
                    ShowMessage(source, data.part2);
                    break;

                case "get":
                    await getlogic.SwitchLogic(operations[1], data.part2, source);

                    break;

                case "block":
                    await blocks.Logic(operations, data.part2, source);

                    break;

                case "admin":
                    window.WriteLine("data2: " + data.part2.Length.ToString());
                    await adminlogic.SwitchLogic(data.part2, source);

                    break;

                default:
                    break;
                }

                // schedule the next receive operation once reading is done:
                socket.BeginReceive(new AsyncCallback(OnUdpData), socket);
            }
            catch (Exception e)
            {
                window.WriteLine("Exception in: Server.UDPServer.OnUdpData");
                window.WriteLine(e.ToString());
            }
        }
Пример #17
0
        public async Task <int> BlockCreate(bool admin = false)
        {
            int result = 0;

            try
            {
                string previous  = cryptography.GetHashString("system");    // system hash bbc5e661e106c6dcd8dc6dd186454c2fcba3c710fb4d8e71a60c93eaf077f073
                string previous2 = cryptography.GetHashString("system");    // system hash bbc5e661e106c6dcd8dc6dd186454c2fcba3c710fb4d8e71a60c93eaf077f073
                string path;
                string name;

                previous = await ActualBlockGet();

                if (admin)
                {
                    previous = cryptography.GetHashString("system");
                }

                byte[]         transactions      = new byte[0];
                List <string>  transactions_list = new List <string>();
                byte[]         transaction       = new byte[0];
                string         transaction_hash  = string.Empty;
                string         hash             = string.Empty;
                string         transaction_info = string.Empty;
                TwoBytesArrays temp             = new TwoBytesArrays();
                temp.part1 = new byte[0];
                int    counter = 0;
                byte[] block;

                path = filesystem.FSConfig.db_path;
                transactions_list = filesystem.GetFilesListFromDirectory(path);

                foreach (string element in transactions_list)
                {
                    path        = filesystem.FSConfig.db_path + @"\" + element;
                    transaction = await filesystem.GetFromFileAsync(path);

                    transaction_hash = cryptography.HashToString((cryptography.GetSHA256Hash(transaction)));
                    hash            += transaction_hash;
                    hash             = cryptography.GetHashString(hash);


                    transaction_info += transaction_hash + "#" + counter.ToString() + "|";

                    temp.part2 = transaction;
                    temp.part1 = ByteArrayJoin(temp);

                    transaction = temp.part1;

                    counter++;
                    if (!File.Exists(filesystem.FSConfig.db_temp_path + @"\" + element))
                    {
                        File.Move(filesystem.FSConfig.db_path + @"\" + element, filesystem.FSConfig.db_temp_path + @"\" + element);
                    }
                    else
                    {
                        File.Delete(filesystem.FSConfig.db_path + @"\" + element);
                    }
                }
                transactions = temp.part2;

                int count = transactions_list.Count;

                byte[] header;
                header = await Task.Run(() => BlockGenerate(previous, count, Encoding.UTF8.GetBytes(hash), Encoding.UTF8.GetBytes(transaction_info)));

                name = cryptography.HashToString(cryptography.GetSHA256Hash(header));

                window.WriteLine("Header size: " + header.Length);

                previous2 = await ActualBlockGet();

                if (admin)
                {
                    previous2 = cryptography.GetHashString("system");
                }


                if ((previous == previous2) && (previous.Length != 0))
                {
                    path = filesystem.FSConfig.db_blocks_path + @"\" + name;

                    block = AddOperation(header.Length.ToString(), Blocks.header_info_size, header);

                    temp.part1 = block;
                    temp.part2 = transaction;

                    block = ByteArrayJoin(temp);

                    window.WriteLine("[block]: transactions part (" + transaction.Length + ")");

                    await filesystem.AddInfoToFileAsync(path, block, true);

                    window.WriteLine("[block]: block created(" + path + ")");

                    if (!admin)
                    {
                        await SayNewBlock(name);
                    }

                    await ActualBlockSet(name);

                    result = 1;
                }
                else
                {
                    result = 2;
                }
            }
            catch (Exception ex)
            {
                window.WriteLine(ex.ToString());
            }

            return(result);
        }
Пример #18
0
        //int version, int timestamp, string previous_block, string root_hash, int number_of_transaction, byte[] transactions

        private byte[] BlockGenerate(string previous_block, int count, byte[] root_hash, byte[] transaction_info)
        {
            byte[] block = new byte[0];
            try
            {
                TwoBytesArrays pre_block = new TwoBytesArrays();
                TwoBytesArrays temp      = new TwoBytesArrays();

                int time = GetDate();

                UInt64 flowing = 0;

                pre_block.part1 = IntToBytes(block_version);
                window.WriteLine("Version: " + BytesToInt(pre_block.part1) + " [" + pre_block.part1.Length + "]");

                pre_block.part2 = IntToBytes(time);
                window.WriteLine("Time: " + BytesToInt(pre_block.part2) + " [" + pre_block.part2.Length + "]");

                pre_block.part1 = ByteArrayJoin(pre_block);

                pre_block.part2 = Encoding.UTF8.GetBytes(previous_block);
                window.WriteLine("[block] Previous: " + Encoding.UTF8.GetString(pre_block.part2) + " [" + pre_block.part2.Length + "]");

                pre_block.part1 = ByteArrayJoin(pre_block);

                pre_block.part2 = IntToBytes(count);
                window.WriteLine("Count: " + BytesToInt(pre_block.part2) + " [" + pre_block.part2.Length + "]");

                pre_block.part1 = ByteArrayJoin(pre_block);

                pre_block.part2 = root_hash;
                window.WriteLine("root_hash: " + Encoding.UTF8.GetString(pre_block.part2) + " [" + pre_block.part2.Length + "]");

                pre_block.part1 = ByteArrayJoin(pre_block);

                pre_block.part2 = IntToBytes(transaction_info.Length);
                window.WriteLine("T_info.lenght: " + BytesToInt(pre_block.part2) + " [" + pre_block.part2.Length + "]");

                pre_block.part1 = ByteArrayJoin(pre_block);

                pre_block.part2 = transaction_info;
                window.WriteLine("T_info: " + Encoding.UTF8.GetString(pre_block.part2) + " [" + pre_block.part2.Length + "]");

                byte[] backup = ByteArrayJoin(pre_block);

                string temp_str = "fail";

                bool trigger = false;

                while (!trigger)
                {
                    temp.part2 = Uint64ToBytes(flowing);
                    temp.part1 = backup;
                    temp.part1 = ByteArrayJoin(temp);

                    temp_str = cryptography.HashToString(cryptography.GetSHA256Hash(temp.part1));
                    trigger  = CheckBlockHash(temp_str);

                    flowing++;
                }
                window.WriteLine("Flowing: " + BytesToUint64(temp.part2) + " [" + temp.part2.Length + "]");

                block = temp.part1;


                window.WriteLine("Block: " + temp_str);
            }
            catch (Exception ex)
            {
                window.WriteLine(ex.ToString());
            }
            return(block);
        }
Пример #19
0
        private async Task RequestsLogic(byte[] incoming_data, IPEndPoint source)
        {
            try
            {
                TwoBytesArrays TWdata    = new TwoBytesArrays();
                byte[]         data      = new byte[0];
                byte[]         message   = new byte[0];
                string         operation = string.Empty;
                string         path      = string.Empty;

                TWdata    = ByteArrayCut(incoming_data, GetLogic.operation_size);
                operation = BytesToOperation(TWdata.part1);

                window.WriteLine("Got RequestsLogic: " + operation);

                switch (operation)
                {
                case "signature":
                    path = filesystem.FSConfig.root_path + @"\signature";
                    if (File.Exists(path))
                    {
                        data = await filesystem.GetFromFileAsync(path);

                        data = AddOperation(operation, UDPServer.operation_size, data);
                        data = AddOperation(answer_template, GetLogic.operation_size, data);
                        await server.Send(source, data);
                    }
                    break;

                case "actualblock":
                    path = filesystem.FSConfig.db_blocks_path + @"\actualblock";
                    if (File.Exists(path))
                    {
                        data = await filesystem.GetFromFileAsync(path);

                        data = AddOperation(operation, UDPServer.operation_size, data);
                        data = AddOperation(answer_template, GetLogic.operation_size, data);

                        window.WriteLine("Sending actual block..");
                        await server.Send(source, data);
                    }
                    break;

                case "block":
                    if (TWdata.part2.Length != 0)
                    {
                        path = filesystem.FSConfig.db_blocks_path + @"\" + Encoding.UTF8.GetString(TWdata.part2);
                        data = await filesystem.GetFromFileAsync(path);

                        message = Encoding.UTF8.GetBytes(data.Length.ToString());
                        message = AddOperation("block", UDPServer.operation_size, message);
                        message = AddOperation(answer_template, GetLogic.operation_size, message);

                        await server.Send(source, message);

                        window.WriteLine("Sending block: " + Encoding.UTF8.GetString(TWdata.part2));
                        filetransfering.TcpDataSend(data);
                    }

                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
Пример #20
0
        public Block BlockDeSerialize(byte[] block)
        {
            Block full_block = new Block();

            try
            {
                TwoBytesArrays temp         = new TwoBytesArrays();
                byte[]         transactions = new byte[0];

                temp = ByteArrayCut(block, Blocks.header_info_size);
                string header = BytesToOperation(temp.part1);

                //window.WriteLine("Header size: " + Convert.ToInt32(header));

                temp         = ByteArrayCut(temp.part2, Convert.ToInt32(header));
                transactions = temp.part2;

                full_block.name = cryptography.HashToString(cryptography.GetSHA256Hash(temp.part1));

                //window.WriteLine("[last]: " + temp.part1.Length);

                temp = ByteArrayCut(temp.part1, 4);
                full_block.version = BytesToInt(temp.part1);

                //window.WriteLine("[last]: " + temp.part2.Length);

                temp            = ByteArrayCut(temp.part2, 4);
                full_block.time = BytesToInt(temp.part1);

                //window.WriteLine("[last]: " + temp.part2.Length);

                temp = ByteArrayCut(temp.part2, 64);
                full_block.previous = Encoding.UTF8.GetString(temp.part1);

                //window.WriteLine("[last]: " + temp.part2.Length);

                temp = ByteArrayCut(temp.part2, 4);
                full_block.transactions_count = BytesToInt(temp.part1);

                //window.WriteLine("[last]: " + temp.part2.Length);

                temp = ByteArrayCut(temp.part2, 64);
                full_block.root_hash = Encoding.UTF8.GetString(temp.part1);

                //window.WriteLine("[last]: " + temp.part2.Length);

                temp = ByteArrayCut(temp.part2, 4);
                int t_info_length = BytesToInt(temp.part1);
                full_block.transactions_info_size = t_info_length;

                //window.WriteLine("[last]: " + temp.part2.Length);

                temp = ByteArrayCut(temp.part2, t_info_length);
                full_block.transactions_info = Encoding.UTF8.GetString(temp.part1);

                //window.WriteLine("[last]: " + temp.part2.Length);

                full_block.flowing      = BytesToUint64(temp.part2);
                full_block.transactions = transactions;

                if (debug)
                {
                    window.WriteLine("Name: " + full_block.name);
                    window.WriteLine("Version: " + full_block.version);
                    window.WriteLine("Time: " + full_block.time);
                    window.WriteLine("Previous: " + full_block.previous);
                    window.WriteLine("Count: " + full_block.transactions_count);
                    window.WriteLine("root_hash: " + full_block.root_hash);
                    window.WriteLine("T_info.lenght: " + full_block.transactions_info_size);
                    window.WriteLine("Transactions [info]: " + full_block.transactions_info);
                    window.WriteLine("Flowing: " + full_block.flowing);


                    window.WriteLine("Transactions [full]: " + transactions.Length / 712 + " [" + transactions.Length + "]");
                }
            }
            catch (Exception ex)
            {
                window.WriteLine("Exception in BlockDeSerialize");
                window.WriteLine(ex.ToString());
            }
            return(full_block);
        }