Exemplo n.º 1
0
        public void AddBlockTest()
        {
            var bc = new BlockChain();

            //Create first transaction
            var transaction1 = new Transaction("Stevano", "Valentino", 3.0, 0.3);

            //{
            //    Sender = "Stevano",
            //    Recipient = "Valentino",
            //    Amount = 3.0,
            //    Fee = 0.3
            //};

            bc.TransactionsPool.AddTransaction(transaction1);
            bc.AddBlock();
            Assert.Equal(2, bc.Count);

            //Create 2nd transaction
            var transaction2 = new Transaction("Budiawan", "Norita", 2.5, 0.2);

            //{
            //    Sender = "Budiawan",
            //    Recipient = "Norita",
            //    Amount = 2.5,
            //    Fee = 0.2
            //};

            bc.TransactionsPool.AddTransaction(transaction2);
            bc.AddBlock();
            Assert.Equal(3, bc.Count);
        }
Exemplo n.º 2
0
        private Block Add(string parentHash, string data)
        {
            var block = new Block(parentHash, data);

            blockChain.AddBlock(block);
            return(block);
        }
Exemplo n.º 3
0
        public void TestAddBlockTest()
        {
            var bc = new BlockChain();

            var lsTrx = new List <Transaction>();

            //Create 1st transaction
            var trx1 = new Transaction
            {
                Sender    = "Stevano",
                Recipient = "Valentino",
                Amount    = 3.0,
                Fee       = 0.3
            };

            lsTrx.Add(trx1);
            bc.AddBlock(lsTrx.ToArray());
            Assert.That(2, Is.EqualTo(bc.Blocks.Count));

            //Create 2nd transaction
            trx1 = new Transaction
            {
                Sender    = "Budiawan",
                Recipient = "Norita",
                Amount    = 2.5,
                Fee       = 0.2
            };

            lsTrx = new List <Transaction>();
            lsTrx.Add(trx1);
            bc.AddBlock(lsTrx.ToArray());
            Assert.That(3, Is.EqualTo(bc.Blocks.Count));
        }
Exemplo n.º 4
0
        public static void SendNewBlock(string content)
        {
            var block = new Block(DateTime.Now, null, content);

            blockChain.AddBlock(block);
            var obj = JsonConvert.SerializeObject(block);

            client.Send(obj);
        }
Exemplo n.º 5
0
        public static byte[] EencodeMessage(string content)
        {
            var block = new Block(DateTime.Now, null, content);

            blockChain.AddBlock(block);
            var obj = JsonConvert.SerializeObject(block);

            return(Encoding.UTF8.GetBytes(obj));
        }
Exemplo n.º 6
0
        private static void Demo()
        {
            // Initialize blockchain
            var transactionPool = new TransactionPool();
            var blockChain      = new BlockChain(transactionPool);

            // Create new transactions.
            var transaction1 = new Transaction(sender: "Bob", recipient: "Billy", amount: 10, fee: 0.01);
            var transaction2 = new Transaction(sender: "John", recipient: "Ivanka", amount: 20, fee: 0.01);
            var transaction3 = new Transaction(sender: "Robert", recipient: "Antonio", amount: 30, fee: 0.01);

            // Add transactions to transactions pool
            blockChain.TransactionsPool.AddTransaction(transaction1);
            blockChain.TransactionsPool.AddTransaction(transaction2);
            blockChain.TransactionsPool.AddTransaction(transaction3);

            // Forging a block - BlockChain will add a new block to the chain and add transactions to it
            blockChain.AddBlock();

            // Create another transactions.
            transaction1 = new Transaction(sender: "Asen", recipient: "Ivan", amount: 110, fee: 0.01);
            transaction2 = new Transaction(sender: "Gosho", recipient: "Boqn", amount: 220, fee: 0.01);
            transaction3 = new Transaction(sender: "Pesho", recipient: "Martin", amount: 330, fee: 0.01);

            // Add transactions to transactions pool
            blockChain.TransactionsPool.AddTransaction(transaction1);
            blockChain.TransactionsPool.AddTransaction(transaction2);
            blockChain.TransactionsPool.AddTransaction(transaction3);

            // Forging another block
            blockChain.AddBlock();

            // We have 2 blocks and 6 transactions
            // Chain explorer will output data from block on console
            var chainExplorer = new ConsoleChainExplorer(blockChain);

            chainExplorer.PrintGenesisBlock();
            chainExplorer.PrintLastBlock();
            chainExplorer.PrintBalance("Robert");
            chainExplorer.PrintBalance("Antonio");
            chainExplorer.PrintBalance("Martin");

            chainExplorer.PrintTransactionHistory("Robert");
            chainExplorer.PrintTransactionHistory("Gosho");
            chainExplorer.PrintTransactionHistory("Boqn");

            Console.WriteLine();
            chainExplorer.PrintBlocks();

            Console.WriteLine("Press enter to close application");
            Console.ReadLine();
        }
        public void ValidatesAValidChainTest()
        {
            blockChain  = new BlockChain();
            blockChain2 = new BlockChain();

            blockChain2.AddBlock("foo");

            Assert.True(blockChain.IsValidChain(blockChain2.Chain));
        }
        public void voidAddsANewBlockTest()
        {
            blockChain = new BlockChain();
            var data = "foo";

            blockChain.AddBlock(data);

            Assert.Equal(data, blockChain.Chain.LastOrDefault().Data);
        }
        public void InvalidatesACorruptChain()
        {
            blockChain  = new BlockChain();
            blockChain2 = new BlockChain();

            blockChain2.AddBlock("foo");
            blockChain2.Chain.LastOrDefault().Data = "Not Foo";

            Assert.False(blockChain.IsValidChain(blockChain2.Chain));
        }
Exemplo n.º 10
0
        public UnitTestFixture()
        {
            BlockChain = new BlockChain <Transaction>();

            const int blocksToAdd = 2;

            for (var i = 0; i < blocksToAdd; i++)
            {
                BlockChain.AddBlock(GetBlock());
            }
        }
Exemplo n.º 11
0
 public void AddBlockToChain(BlockData newBlockData)
 {
     try
     {
         _blockChain.AddBlock(newBlockData);
     }
     catch (Exception e)
     {
         _logger.LogCritical(e.Message, e);
     }
 }
        public void ItDoesNotReplaceACahinWithLengththatIsEqualOrLessThanItSelf()
        {
            blockChain  = new BlockChain();
            blockChain2 = new BlockChain();

            blockChain.AddBlock("goo");

            blockChain.ReplaceChain(blockChain2.Chain);

            Assert.NotEqual(blockChain2.Chain.Count, blockChain.Chain.Count);
        }
        public void ItReplacesTheChainWithAValidChainTest()
        {
            blockChain  = new BlockChain();
            blockChain2 = new BlockChain();

            blockChain2.AddBlock("goo");

            blockChain.ReplaceChain(blockChain2.Chain);

            Assert.Equal(blockChain2.Chain.Count, blockChain.Chain.Count);
        }
Exemplo n.º 14
0
        public IActionResult SetStudentsValuation(WebModel model)
        {
            Teacher   teacher     = _dbContext.GetTeacherById(model.Id);
            Valuation valuation   = new Valuation(teacher, model.Amount, model.Description);
            Block     block       = new Block(DateTime.Now, null, valuation);
            string    subjectName = model.Subject;

            foreach (string id in model.StudentIds)
            {
                Student student = _dbContext.GetStudentById(id);
                if (student.Subjects.Count > 0)
                {
                    foreach (var subject in student.Subjects.Values)
                    {
                        if (subject.Subject == subjectName)
                        {
                            student.Subjects[subjectName].AddBlock(block);
                            _dbContext.UpdateStudent(student);
                        }
                        else
                        {
                            BlockChain blockChain = new BlockChain(subjectName);
                            blockChain.AddBlock(block);
                            student.Subjects.Add(subjectName, blockChain);
                            _dbContext.UpdateStudent(student);
                        }
                    }
                }
                else
                {
                    BlockChain blockChain = new BlockChain(subjectName);
                    blockChain.AddBlock(block);
                    student.Subjects.Add(subjectName, blockChain);
                    _dbContext.UpdateStudent(student);
                }
            }
            List <Student> students = _dbContext.GetStudentsByGroup(model.Group);
            List <Group>   groups   = _dbContext.GetGroups();

            model.Students = students;
            model.Subjects = teacher.Subjects;
            model.Groups   = groups;
            return(RedirectToRoute(new {
                controller = "Teacher",
                action = "Index"
            }));
        }
Exemplo n.º 15
0
        private async Task <bool> AddBlockToChain(Block MinedBlock)
        {
            //Adding block to main PureMedChain
            PureMedBlockChain.AddBlock(MinedBlock);

            //Adding and storing in database
            var newBlockChains = await blockChainsDbContext.AllBlockChains.SingleOrDefaultAsync(m => m.ID == 1);

            newBlockChains.PureMedBlockChain    = JsonConvert.SerializeObject(PureMedBlockChain.Chain);
            newBlockChains.Verifier_1BlockChain = JsonConvert.SerializeObject(Verifier1Chain.Chain);
            newBlockChains.Verifier_2BlockChain = JsonConvert.SerializeObject(Verifier2Chain.Chain);
            newBlockChains.Verifier_3BlockChain = JsonConvert.SerializeObject(Verifier3Chain.Chain);
            blockChainsDbContext.AllBlockChains.Update(newBlockChains);
            await blockChainsDbContext.SaveChangesAsync();

            return(true);
        }
Exemplo n.º 16
0
        public IHttpActionResult Get(string qr)
        {
            if (!keyHandler.CheckApiKey(this.Request))
            {
                return(new ForbiddenActionResult(Request, "access denied"));
            }

            try
            {
                var result = mapper.GetProductByQr(qr);

                if (result != null)
                {
                    result.Process          = mapper.GetProcess(result.ProcessId);
                    result.CurrentTreatment = mapper.GetTreatment(result.CurrrentTreatmentId);

                    #region bc test

                    if (result.CurrentTreatment != null && result.CurrentTreatment.OutgoingState.Final)
                    {
                        BlockChain bc = new BlockChain(2);

                        foreach (var step in result.Process.Steps)
                        {
                            string stateAsString = JsonConvert.SerializeObject(step);
                            Block  bs            = bc.NewBlock(stateAsString);
                            bc.AddBlock(bs);
                        }

                        FileDistributor fd = new FileDistributor();
                        fd.SaveBlockChain(bc, result.QRCode);
                    }

                    #endregion

                    return(Ok(result));
                }

                return(NotFound());
            }
            catch (Exception e)
            {
                return(BadRequest());
            }
        }
Exemplo n.º 17
0
        private void HandleNewBlockMined(CommandMessage rxMsg)
        {
            try
            {
                handlingNewBlock = true;
                PauseMining(); //pause mining if mining

                Block minedBlock   = new Block().DeSerialize(rxMsg.Data);
                var   transactions = minedBlock.Transactions;
                logger.Debug("Recieved block, somebody mined: " + Convert.ToBase64String(minedBlock.Hash));

                var isValid = IsPreviousHashValid(minedBlock.PreviousHash);

                if (!isValid)
                {
                    logger.Debug("Previous hash invalid, try add to fork subchain");
                    if (!VerifyTransactions(transactions))
                    {
                        logger.Debug("Transactions  not valid");
                        ResumeMining();
                        handlingNewBlock = false;
                        return;
                    }

                    //try to add to fork chains
                    var added = false;
                    foreach (var memChain in InMemoryBlockChains)
                    {
                        if (memChain.BelongsToThisChain(minedBlock))
                        {
                            added = memChain.AddBlock(minedBlock);
                            RemoveTransactionsFromPool(minedBlock.Transactions);
                            logger.Debug("Added to subchain");
                        }
                    }

                    if (!added)
                    {
                        var newForkChain = new InMemoryBlockChain();
                        newForkChain.AddBlock(minedBlock);
                        InMemoryBlockChains.Add(newForkChain);
                        logger.Debug("Created new subchain");
                    }
                    PrintCurrentForkChains(InMemoryBlockChains);
                }
                else
                {
                    logger.Debug("Previous hash VALID, add to local chain");

                    if (!VerifyTransactions(transactions))
                    {
                        ResumeMining();
                        handlingNewBlock             = false;
                        timeSkewBetweenHandlingBlock = DateTime.Now;
                        return;
                    }

                    BreakMining();
                    RemoveTransactionsFromPool(minedBlock.Transactions); //remove new block transactions from pool
                    chain.AddBlock(minedBlock);
                    //30.4
                    var utxoSet = new UTXOSet(chain);
                    utxoSet.Update(minedBlock);
                    //
                }

                if (InMemoryBlockChains.Count > 0)
                {
                    logger.Debug("Find best chain");
                    InMemoryBlockChain bestChain = null;
                    var count     = 1;
                    var bestIndex = chain.GetBestHeight();     //local blockchain

                    foreach (var chain in InMemoryBlockChains) //subchains
                    {
                        var currentIndex = chain.GetLastIndex();

                        if (currentIndex > bestIndex)
                        {
                            bestIndex = currentIndex;
                            count     = 1;
                            bestChain = chain;
                        }
                        else if (currentIndex == bestIndex)
                        {
                            count++;
                        }
                    }
                    if (count == 1)
                    {
                        logger.Debug("Best chain found");
                        BreakMining();

                        if (bestChain != null)
                        {
                            logger.Debug("Best chain found in subchains, restructualize chain");
                            //if not restruct to new one
                            chain.RestructualizeSubchain(bestChain);
                            InMemoryBlockChains.Clear(); //clear InMemoryChains
                        }
                        else
                        {
                            //if bestChain is null, chain stays local
                            logger.Debug("Best chain found in localchain, do nothing");
                        }
                    }
                    else
                    {
                        logger.Debug("Best chain not found");
                    }
                }

                WholeChainDownloaded?.Invoke(this, EventArgs.Empty);
                chain.ReindexUTXO(); // asynch
                handlingNewBlock = false;
                if (IncomingMinedNewBlocksMessages.Count > 0)
                {
                    ProcessMessage(IncomingMinedNewBlocksMessages.Dequeue());
                }
            }
            catch (Exception e)
            {
                logger.Error(e.Message);
                logger.Error(e.StackTrace);
            }
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            // Make blockchain
            var bc = new BlockChain();

            //Create new transaction
            var trx1 = new Transaction
            {
                Sender    = "Genesis Account",
                Recipient = "Ricardo",
                Amount    = 300,
                Fee       = 0.001
            };

            //Create new transaction
            var trx2 = new Transaction
            {
                Sender    = "Genesis Account",
                Recipient = "Frodo",
                Amount    = 250,
                Fee       = 0.001
            };

            //Create new transaction
            var trx3 = new Transaction
            {
                Sender    = "Ricardo",
                Recipient = "Madona",
                Amount    = 20,
                Fee       = 0.0001
            };

            //Create list of transactions
            var lsTrx = new List <Transaction>
            {
                trx1,
                trx2
            };

            var transactions = lsTrx.ToArray();

            bc.AddBlock(transactions);

            lsTrx = new List <Transaction>
            {
                trx3
            };

            transactions = lsTrx.ToArray();
            bc.AddBlock(transactions);

            //Print all blocks
            bc.PrintBlocks();

            try
            {
                //Check balance for each account account
                var balance = bc.GetBalance("Genesis Account");
                Console.WriteLine("Genesis Account balance: {0}", balance);

                balance = bc.GetBalance("Ricardo");
                Console.WriteLine("Ricardo balance: {0}", balance);

                balance = bc.GetBalance("Frodo");
                Console.WriteLine("Frodo  balance: {0}", balance);


                balance = bc.GetBalance("Madona");
                Console.WriteLine("Madona balance: {0}", balance);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error has occurred: {ex.Message}");
            }


            Console.ReadKey();
        }