Ejemplo n.º 1
0
        static void Main()
        {
            const string minerAddress = "miner1";
            const string user1Address = "A";
            const string user2Address = "B";
            BlockChain   blockChain   = new BlockChain(proofOfWorkDifficulty: 2, miningReward: 10);

            blockChain.CreateTransaction(new Transaction(user1Address, user2Address, 200));
            blockChain.CreateTransaction(new Transaction(user2Address, user1Address, 10));
            Console.WriteLine("Is valid: {0}", blockChain.IsValidChain());
            Console.WriteLine();
            Console.WriteLine("--------- Start mining ---------");
            blockChain.MineBlock(minerAddress);
            Console.WriteLine("BALANCE of the miner: {0}", blockChain.GetBalance(minerAddress));
            blockChain.CreateTransaction(new Transaction(user1Address, user2Address, 5));
            Console.WriteLine();
            Console.WriteLine("--------- Start mining ---------");
            blockChain.MineBlock(minerAddress);
            Console.WriteLine("BALANCE of the miner: {0}", blockChain.GetBalance(minerAddress));
            Console.WriteLine();
            PrintChain(blockChain);
            Console.WriteLine();
            Console.WriteLine("Hacking the blockchain...");
            blockChain.Chain[1].Transactions = new List <Transaction> {
                new Transaction(user1Address, minerAddress, 150)
            };
            Console.WriteLine("Is valid: {0}", blockChain.IsValidChain());
            Console.ReadKey();
        }
Ejemplo n.º 2
0
        private static string acc = ""; // tên ví, rỗng là chưa đăng nhập

        // Load , lúc đầu block chỉ có 1 khối, thêm 1 khối giao dịch (cho user1 và user2)
        public void Load()
        {
            blockChain.CreateTransaction(new Transactions(adminAddress, user1Address, 200));
            blockChain.CreateTransaction(new Transactions(adminAddress, user2Address, 200));
            blockChain.MineBlock(minerAddress);
            blockChain.CreateTransaction(new Transactions(adminAddress, user1Address, 20));
            blockChain.CreateTransaction(new Transactions(adminAddress, user2Address, 130));
            blockChain.MineBlock(minerAddress);
        }
Ejemplo n.º 3
0
        public void GetBalanceOfAddress_CheckingValue_ReturningValue()
        {
            BlockChain blockChain = new BlockChain();

            string address1 = "Address1", address2 = "Address2", address3 = "Address3";

            blockChain.CreateTransaction(new Transaction(address1, address2, 25));
            blockChain.CreateTransaction(new Transaction(address2, address1, 10));
            blockChain.CreateTransaction(new Transaction(address3, address1, 30));

            blockChain.MinePendingTransactions(address1);

            blockChain.GetBalanceOfAddress(address1);
        }
Ejemplo n.º 4
0
        public void MinePendingTransactions_ValidMindPending_ValidValue()
        {
            //Поумолчанию то есть в приложении даёт по 100 $.

            BlockChain blockChain = new BlockChain();

            string address1 = "Address1", address2 = "Address2", address3 = "Address3";

            blockChain.CreateTransaction(new Transaction(address1, address2, 25));
            blockChain.CreateTransaction(new Transaction(address2, address1, 10));
            blockChain.CreateTransaction(new Transaction(address3, address1, 30));

            blockChain.MinePendingTransactions(address1);
        }
Ejemplo n.º 5
0
        public void IsChainValid_TrueValue_ReturnTrue()
        {
            BlockChain blockChain = new BlockChain();

            string address1 = "Address1", address2 = "Address2", address3 = "Address3";

            blockChain.CreateTransaction(new Transaction(address1, address2, 25));
            blockChain.CreateTransaction(new Transaction(address2, address1, 10));
            blockChain.CreateTransaction(new Transaction(address3, address1, 30));

            blockChain.MinePendingTransactions(address1);
            blockChain.MinePendingTransactions(address2);

            Assert.IsTrue(blockChain.IsChainValid());
        }
Ejemplo n.º 6
0
        public void Should_add_transaction()
        {
            var bc = new BlockChain(Guid.NewGuid(), new NetworkConsense(1, 5, 0));

            bc.CreateTransaction(new Transaction(Guid.NewGuid(), Guid.NewGuid(), 10));
            bc.PenddingTransactions.Should().HaveCount(1);
        }
Ejemplo n.º 7
0
        public void IsChainVaid_FalsePreviousHash_ReturnFalse()
        {
            BlockChain blockChain = new BlockChain();

            string address1 = "Address1", address2 = "Address2", address3 = "Address3";

            blockChain.CreateTransaction(new Transaction(address1, address2, 25));
            blockChain.CreateTransaction(new Transaction(address2, address1, 10));
            blockChain.CreateTransaction(new Transaction(address3, address1, 30));

            blockChain.MinePendingTransactions(address1);
            blockChain.MinePendingTransactions(address2);

            blockChain.Chain[1].PreviousHash = "WrongHashHackerchangedhash";

            Assert.IsFalse(blockChain.IsChainValid());
        }
Ejemplo n.º 8
0
        public void CreateTransactions_UnValidAdding()
        {
            BlockChain blockChain = new BlockChain();

            Transaction transaction = null;

            Assert.IsFalse(blockChain.CreateTransaction(transaction));
        }
Ejemplo n.º 9
0
        public void CreateTransaction_ValidAdding()
        {
            BlockChain blockChain = new BlockChain();

            Transaction transaction = new Transaction("Address1", "Address2", 100);

            Assert.IsTrue(blockChain.CreateTransaction(transaction));
        }
Ejemplo n.º 10
0
        public static void ProcessPendingTransactions(this BlockChain blocks, string minerAddress)
        {
            IBlock block = new Block(blocks.LastOrDefault().Hash, blocks.PendingTransactions);

            blocks.Add(block);

            blocks.PendingTransactions = new List <Transaction>();
            blocks.CreateTransaction(new Transaction(null, minerAddress, blocks.Reward));
        }
Ejemplo n.º 11
0
        public async Task <string> CreateTransaction(string transaction, string userName, string password)
        {
            var User = await _userContext.UserAccounts.FirstOrDefaultAsync(m => m.UserName == userName);

            if (User != null)
            {
                if (User.Password == password)
                {
                    var AccessRights = JsonConvert.DeserializeObject <List <string> >(User.AccessRights);
                    if (AccessRights.Contains("CreateTransaction") || AccessRights.Contains("Admin"))
                    {
                        Transaction newTransaction = JsonConvert.DeserializeObject <Transaction>(transaction);
                        SupplyBlockChain.CreateTransaction(newTransaction);
                        return("True");
                    }
                }
            }
            return("False");
        }
Ejemplo n.º 12
0
        public ActionResult Index()
        {
            var          Result       = new List <string>();
            const string minerAddress = "miner1";
            const string user1Address = "A";
            const string user2Address = "B";
            BlockChain   blockChain   = new BlockChain()
            {
                ProofOfWorkDifficulty = 2, MiningReward = 10
            };

            blockChain.CreateTransaction(new Transaction()
            {
                From = user1Address, To = user2Address, Amount = 200
            });
            blockChain.CreateTransaction(new Transaction()
            {
                From = user2Address, To = user1Address, Amount = 10
            });
            Result.Add(string.Format("Est valide: {0}", blockChain.IsValidChain()));
            Result.Add("--------- Démarrer l'extraction ---------");
            blockChain.MineBlock(minerAddress);
            Result.Add(string.Format("ÉQUILIBRE du mineur: {0}", blockChain.GetBalance(minerAddress)));
            blockChain.CreateTransaction(new Transaction()
            {
                From = user1Address, To = user2Address, Amount = 5
            });
            Result.Add("--------- Démarrer l'extraction ---------");
            blockChain.MineBlock(minerAddress);
            Result.Add(string.Format("ÉQUILIBRE du mineur: {0}", blockChain.GetBalance(minerAddress)));
            Result.AddRange(PrintChain(blockChain, Result));
            Result.Add("Piratage de la blockchain ...");
            blockChain.Bloks[1].Transactions = new List <Transaction>  {
                new Transaction()
                {
                    From = user1Address, To = minerAddress, Amount = 150
                }
            };
            Result.Add(string.Format("Est valide: {0}", blockChain.IsValidChain()));
            Result.Add("----------------- End Blockchain -----------------");
            ViewBag.Result = Result;
            return(View());
        }
Ejemplo n.º 13
0
        public void Should_validate_a_chain(bool validChain)
        {
            const int size     = 5;
            var       consense = new NetworkConsense(1, size, 0);


            var blockGenesis = new MockBlock(size, Enumerable.Empty <Transaction>(), string.Empty);
            var block1       = new MockBlock(size, Enumerable.Empty <Transaction>(), string.Empty);
            var block2       = new MockBlock(size, Enumerable.Empty <Transaction>(), string.Empty);
            var block3       = new MockBlock(size, Enumerable.Empty <Transaction>(), string.Empty);

            IEnumerable <IBlock> GetNext(string previosHash)
            {
                blockGenesis.PreviousHash = previosHash;
                yield return(blockGenesis);

                block1.PreviousHash = blockGenesis.Hash;
                yield return(block1);

                block2.PreviousHash = validChain ? block1.Hash : "INCORRECT";
                yield return(block2);

                block3.PreviousHash = block2.Hash;
                yield return(block3);
            };

            IEnumerator <IBlock> factoryState = null;

            IBlock factory(DateTime created, string previousHash, int blockSize, IEnumerable <Transaction> pendingTransactions)
            {
                if (factoryState == null)
                {
                    factoryState = GetNext(previousHash).GetEnumerator();
                }

                factoryState.MoveNext();
                return(factoryState.Current);
            }

            var bc           = new BlockChain(Guid.NewGuid(), consense, factory);
            var transactions =
                Enumerable
                .Repeat(new Transaction(Guid.NewGuid(), Guid.NewGuid(), 1), size * 2)
                .ToArray();

            bc.CreateTransaction(transactions);

            while (bc.PenddingTransactions.Count > 1)
            {
                bc.MiningPedingTransactions();
            }

            // lazy test :<
            bc.IsChainValid().Should().Be(validChain);
        }
Ejemplo n.º 14
0
        public void Should_remove_transactions_whens_mines(int blockSize, int transactionCount, int remains)
        {
            var       factory = MockBlock.CreateFactory();
            var       bc      = new BlockChain(Guid.NewGuid(), new NetworkConsense(1, blockSize, 0), factory);
            const int transactionRewardCount = 1;

            var transactions =
                Enumerable.Repeat(new Transaction(Guid.NewGuid(), Guid.NewGuid(), 1), transactionCount)
                .ToArray();

            bc.CreateTransaction(transactions);
            bc.MiningPedingTransactions();
            bc.PenddingTransactions.Should().HaveCount(remains + transactionRewardCount);
        }
Ejemplo n.º 15
0
        public void Should_calc_correct_address_balance()
        {
            var address1 = Guid.NewGuid();
            var address2 = Guid.NewGuid();

            const int reward = 50;

            var factory = MockBlock.CreateFactory();
            var bc      = new BlockChain(address1, new NetworkConsense(1, 5, reward), factory);

            // 50 0
            bc.CreateTransaction(new Transaction(address1, address2, 20)); // 30 20
            bc.CreateTransaction(new Transaction(address2, address1, 10)); // 40 10
            bc.CreateTransaction(new Transaction(address1, address2, 5));  // 35 15

            bc.MiningPedingTransactions();

            var address1balance = bc.GetAddressBalance(address1);
            var address2balance = bc.GetAddressBalance(address2);

            address1balance.Should().Be(35);
            address2balance.Should().Be(15);
        }
Ejemplo n.º 16
0
        public void Should_add_fi_for_a_founded_block()
        {
            var minerAddress = Guid.NewGuid();

            var factory = MockBlock.CreateFactory();
            var bc      = new BlockChain(minerAddress, new NetworkConsense(1, 5, 42), factory);

            var transaction =
                new Transaction(Guid.NewGuid(), Guid.NewGuid(), 1);

            bc.CreateTransaction(transaction);
            bc.MiningPedingTransactions();

            bc.PenddingTransactions.Should().HaveCount(1);
            bc.PenddingTransactions.First().ToAdress.Should().Be(minerAddress);
            bc.PenddingTransactions.First().Amount.Should().Be(42);
        }
Ejemplo n.º 17
0
        public void Should_natural_transactions_be_valid(int transactionCount)
        {
            const int blockSize = 5;
            var       consense  = new NetworkConsense(1, blockSize, 0);
            var       bc        = new BlockChain(Guid.NewGuid(), consense);

            var transactions =
                Enumerable.Repeat(new Transaction(Guid.NewGuid(), Guid.NewGuid(), 1), transactionCount)
                .ToArray();

            bc.CreateTransaction(transactions);

            while (bc.PenddingTransactions.Count > 1)
            {
                bc.MiningPedingTransactions();
            }

            bc.IsChainValid().Should().BeTrue();
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            Console.WriteLine("Start...");

            var myWalletAddress = "myWalletAddress";
            var random          = new Random();
            var myCoin          = new BlockChain();

            Task.Run(() =>
            {
                Console.WriteLine("Starting transactions...");

                while (true)
                {
                    myCoin.CreateTransaction(new Transaction(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), random.Next(1, int.MaxValue)));

                    Thread.Sleep(1000);
                }
            });


            Task.Run(() =>
            {
                Console.WriteLine("Starting the miner...");

                while (true)
                {
                    myCoin.MinePendingTransactions(myWalletAddress);
                    Console.WriteLine($"Balance of my wallet is {myCoin.GetBalanceOfAddress(myWalletAddress)}");

                    Thread.Sleep(2000);
                }
            });

            Console.WriteLine("Done!");
            Console.ReadLine();
        }
Ejemplo n.º 19
0
        static void TestBlockChain(string[] args)
        {
            if (args.Length >= 1)
            {
                Port = int.Parse(args[0]);
            }
            if (args.Length >= 2)
            {
                name = args[1];
            }

            if (Port > 0)
            {
                Server = new P2PServer(ipAddress, Port, PhillyCoin);
                Server.Start();
                Console.WriteLine($"P2P server is running on {ipAddress}:{Port}......");
            }
            if (name != "Unkown")
            {
                Console.WriteLine($"Current user is {name}");
            }

            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 1:
                    Console.WriteLine("Please enter the server URL");
                    string serverURL = Console.ReadLine();
                    Client = new P2PClient(PhillyCoin);
                    Client.Connect($"{serverURL}/Blockchain");
                    break;

                case 2:
                    Console.WriteLine("Please enter the receiver name");
                    string receiverName = Console.ReadLine();
                    Console.WriteLine("Please enter the amount");
                    string amount = Console.ReadLine();
                    PhillyCoin.CreateTransaction(new Transaction(name, receiverName, int.Parse(amount)));
                    PhillyCoin.ProcessPendingTransactions(name);
                    Client = new P2PClient(PhillyCoin);
                    Client.Broadcast(JsonConvert.SerializeObject(PhillyCoin));
                    break;

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

                Console.WriteLine("Please select an action");
                string action = Console.ReadLine();
                selection = int.Parse(action);
            }

            Client.Close();
        }