Beispiel #1
0
        public void TestBlockHeaderEquality()
        {
            var randomBlockHeader = RandomData.RandomBlockHeader();

            var sameBlockHeader = new BlockHeader(randomBlockHeader.Version, randomBlockHeader.PreviousBlock, randomBlockHeader.MerkleRoot, randomBlockHeader.Time, randomBlockHeader.Bits, randomBlockHeader.Nonce);

            var differentBlockHeaderVersion = randomBlockHeader.With(Version: ~randomBlockHeader.Version);
            var differentBlockHeaderPreviousBlock = randomBlockHeader.With(PreviousBlock: ~randomBlockHeader.PreviousBlock);
            var differentBlockHeaderMerkleRoot = randomBlockHeader.With(MerkleRoot: ~randomBlockHeader.MerkleRoot);
            var differentBlockHeaderTime = randomBlockHeader.With(Time: ~randomBlockHeader.Time);
            var differentBlockHeaderBits = randomBlockHeader.With(Bits: ~randomBlockHeader.Bits);
            var differentBlockHeaderNonce = randomBlockHeader.With(Nonce: ~randomBlockHeader.Nonce);

            Assert.IsTrue(randomBlockHeader.Equals(sameBlockHeader));
            Assert.IsTrue(randomBlockHeader == sameBlockHeader);
            Assert.IsFalse(randomBlockHeader != sameBlockHeader);

            Assert.IsFalse(randomBlockHeader.Equals(differentBlockHeaderVersion));
            Assert.IsFalse(randomBlockHeader == differentBlockHeaderVersion);
            Assert.IsTrue(randomBlockHeader != differentBlockHeaderVersion);

            Assert.IsFalse(randomBlockHeader.Equals(differentBlockHeaderPreviousBlock));
            Assert.IsFalse(randomBlockHeader == differentBlockHeaderPreviousBlock);
            Assert.IsTrue(randomBlockHeader != differentBlockHeaderPreviousBlock);

            Assert.IsFalse(randomBlockHeader.Equals(differentBlockHeaderMerkleRoot));
            Assert.IsFalse(randomBlockHeader == differentBlockHeaderMerkleRoot);
            Assert.IsTrue(randomBlockHeader != differentBlockHeaderMerkleRoot);

            Assert.IsFalse(randomBlockHeader.Equals(differentBlockHeaderTime));
            Assert.IsFalse(randomBlockHeader == differentBlockHeaderTime);
            Assert.IsTrue(randomBlockHeader != differentBlockHeaderTime);

            Assert.IsFalse(randomBlockHeader.Equals(differentBlockHeaderBits));
            Assert.IsFalse(randomBlockHeader == differentBlockHeaderBits);
            Assert.IsTrue(randomBlockHeader != differentBlockHeaderBits);

            Assert.IsFalse(randomBlockHeader.Equals(differentBlockHeaderNonce));
            Assert.IsFalse(randomBlockHeader == differentBlockHeaderNonce);
            Assert.IsTrue(randomBlockHeader != differentBlockHeaderNonce);
        }
Beispiel #2
0
 public BlockHeader FindLowestCommonAncestor(BlockHeader firstDescendant, BlockHeader secondDescendant, long maxSearchDepth)
 {
     return(_blockTree.FindLowestCommonAncestor(firstDescendant, secondDescendant, maxSearchDepth));
 }
Beispiel #3
0
 public AddBlockResult SuggestHeader(BlockHeader header)
 {
     return(_blockTree.SuggestHeader(header));
 }
Beispiel #4
0
 public bool Verify(BlockHeader blockHeader)
 {
     throw new NotImplementedException();
 }
Beispiel #5
0
 private bool AddToChain(BlockHeader blockHeader)
 {
     return(Chain.TrySetTip(blockHeader.GetHash(), blockHeader.HashPrevBlock, true));
 }
Beispiel #6
0
        //BlockChainのテスト(分岐がない場合・無効ブロックなどを追加しようとした場合)
        public static void Test18()
        {
            string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            BlockchainAccessDB bcadb = new BlockchainAccessDB(basepath);
            string bcadbPath = bcadb.GetPath();

            if (File.Exists(bcadbPath))
                File.Delete(bcadbPath);

            BlockManagerDB bmdb = new BlockManagerDB(basepath);
            string bmdbPath = bmdb.GetPath();

            if (File.Exists(bmdbPath))
                File.Delete(bmdbPath);

            BlockDB bdb = new BlockDB(basepath);
            string bdbPath = bdb.GetPath(0);

            if (File.Exists(bdbPath))
                File.Delete(bdbPath);

            BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath);
            string bfpPath = bfpdb.GetPath();

            if (File.Exists(bfpPath))
                File.Delete(bfpPath);

            UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath);
            string ufadbPath = ufadb.GetPath();

            if (File.Exists(ufadbPath))
                File.Delete(ufadbPath);

            UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath);
            string ufpdbPath = ufpdb.GetPath();

            if (File.Exists(ufpdbPath))
                File.Delete(ufpdbPath);

            UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath);
            string ufptempdbPath = ufptempdb.GetPath();

            if (File.Exists(ufptempdbPath))
                File.Delete(ufptempdbPath);

            UtxoDB utxodb = new UtxoDB(basepath);
            string utxodbPath = utxodb.GetPath();

            if (File.Exists(utxodbPath))
                File.Delete(utxodbPath);

            BlockChain blockchain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb);

            BlockGenerator bg = new BlockGenerator();

            Block[] blks = new Block[10];
            BlockContext[] blkCons = new BlockContext[blks.Length];
            for (int i = 0; i < blks.Length; i++)
            {
                blkCons[i] = bg.CreateNextValidBlock();
                blks[i] = blkCons[i].block;

                Console.WriteLine("block" + i.ToString() + " created.");
            }

            Block[] blks2 = new Block[blks.Length];
            byte[] nonce = null;

            Func<long, TransactionalBlock> _indexToBlock = (index) => blks2[index] as TransactionalBlock;

            for (int i = 0; i < blks.Length; i++)
            {
                if (i == 0)
                {
                    blks2[i] = blks[i];

                    continue;
                }

                TransactionalBlock tblk = blks[i] as TransactionalBlock;

                TransactionalBlock tblk2 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock, 0);

                nonce = new byte[10];

                while (true)
                {
                    tblk2.UpdateTimestamp(DateTime.Now);
                    tblk2.UpdateNonce(nonce);

                    if (tblk2.Id.CompareTo(tblk2.header.difficulty.Target) <= 0)
                    {
                        blks2[i] = tblk2;

                        Console.WriteLine("block" + i.ToString() + " mined.");

                        break;
                    }

                    int index = nonce.Length.RandomNum();
                    int value = 256.RandomNum();

                    nonce[index] = (byte)value;
                }
            }

            if (blockchain.blocksCurrent.value != 0)
                throw new Exception("test18_1");
            for (int i = 0; i < blockchain.pendingBlocks.Length; i++)
            {
                if (blockchain.pendingBlocks[i] != null)
                    throw new Exception("test18_2");
                if (blockchain.rejectedBlocks[i] != null)
                    throw new Exception("test18_3");
            }

            TransactionalBlock blk1 = blks2[1] as TransactionalBlock;
            TransactionalBlock blk2 = blks2[2] as TransactionalBlock;

            Creahash hashzero = new Creahash();

            BlockHeader bh5 = new BlockHeader();
            bh5.LoadVersion0(100, hashzero, DateTime.Now, blk1.Difficulty, new byte[10]);

            BlockHeader bh6 = new BlockHeader();
            bh6.LoadVersion0(101, hashzero, DateTime.Now, blk1.Difficulty, new byte[10]);

            TransactionalBlock blk100 = new NormalBlock();
            blk100.LoadVersion0(bh5, blk1.coinbaseTxToMiner, blk1.transferTxs);
            blk100.UpdateMerkleRootHash();

            TransactionalBlock blk101 = new NormalBlock();
            blk101.LoadVersion0(bh6, blk1.coinbaseTxToMiner, blk1.transferTxs);
            blk101.UpdateMerkleRootHash();

            blockchain.pendingBlocks[101] = new Dictionary<Creahash, Block>();
            blockchain.rejectedBlocks[101] = new Dictionary<Creahash, Block>();

            BlockChain.UpdateChainReturnType type1 = blockchain.UpdateChain(blks[0]);

            if (type1 != BlockChain.UpdateChainReturnType.updated)
                throw new Exception("test18_5");

            if (blockchain.blocksCurrent.value != 1)
                throw new Exception("test18_6");
            for (int i = 0; i < blockchain.pendingBlocks.Length; i++)
            {
                if (blockchain.pendingBlocks[i] != null)
                    throw new Exception("test18_7");
                if (blockchain.rejectedBlocks[i] != null)
                    throw new Exception("test18_8");
            }

            bool flag2 = false;
            try
            {
                blockchain.UpdateChain(blk101);
            }
            catch (InvalidOperationException)
            {
                flag2 = true;
            }
            if (!flag2)
                throw new Exception("test18_9");

            BlockChain.UpdateChainReturnType type2 = blockchain.UpdateChain(blk100);

            if (type2 != BlockChain.UpdateChainReturnType.pending)
                throw new Exception("test18_10");

            if (blockchain.blocksCurrent.value != 1)
                throw new Exception("test18_11");
            for (int i = 0; i < blockchain.pendingBlocks.Length; i++)
            {
                if (i == 101)
                {
                    if (blockchain.pendingBlocks[i] == null)
                        throw new Exception("test18_12");
                    if (blockchain.pendingBlocks[i].Count != 1)
                        throw new Exception("test18_13");
                    if (!blockchain.pendingBlocks[i].Keys.Contains(blk100.Id))
                        throw new Exception("test18_14");
                }
                else
                {
                    if (blockchain.pendingBlocks[i] != null)
                        throw new Exception("test18_15");
                }

                if (blockchain.rejectedBlocks[i] != null)
                    throw new Exception("test18_16");
            }

            BlockHeader bh1 = new BlockHeader();
            bh1.LoadVersion0(1, hashzero, DateTime.Now, blk1.Difficulty, new byte[10]);

            TransactionalBlock blk1_2 = new NormalBlock();
            blk1_2.LoadVersion0(bh1, blk1.coinbaseTxToMiner, blk1.transferTxs);
            blk1_2.UpdateMerkleRootHash();

            BlockChain.UpdateChainReturnType type3 = blockchain.UpdateChain(blk1_2);

            if (type3 != BlockChain.UpdateChainReturnType.pending)
                throw new Exception("test18_17");

            if (blockchain.blocksCurrent.value != 1)
                throw new Exception("test18_18");
            for (int i = 0; i < blockchain.pendingBlocks.Length; i++)
            {
                if (i == 2)
                {
                    if (blockchain.pendingBlocks[i] == null)
                        throw new Exception("test18_19");
                    if (blockchain.pendingBlocks[i].Count != 1)
                        throw new Exception("test18_20");
                    if (!blockchain.pendingBlocks[i].Keys.Contains(blk1_2.Id))
                        throw new Exception("test18_21");
                }
                else if (i == 101)
                {
                    if (blockchain.pendingBlocks[i] == null)
                        throw new Exception("test18_22");
                    if (blockchain.pendingBlocks[i].Count != 1)
                        throw new Exception("test18_23");
                    if (!blockchain.pendingBlocks[i].Keys.Contains(blk100.Id))
                        throw new Exception("test18_24");
                }
                else
                {
                    if (blockchain.pendingBlocks[i] != null)
                        throw new Exception("test18_25");
                }

                if (blockchain.rejectedBlocks[i] != null)
                    throw new Exception("test18_26");
            }

            BlockHeader bh2 = new BlockHeader();
            bh2.LoadVersion0(1, blks[0].Id, DateTime.Now, blk1.Difficulty, new byte[10]);

            TransactionalBlock blk1_3 = new NormalBlock();
            blk1_3.LoadVersion0(bh2, blk1.coinbaseTxToMiner, blk1.transferTxs);
            blk1_3.UpdateMerkleRootHash();

            BlockChain.UpdateChainReturnType type4 = blockchain.UpdateChain(blk1_3);

            if (type4 != BlockChain.UpdateChainReturnType.rejected)
                throw new Exception("test18_27");

            if (blockchain.blocksCurrent.value != 1)
                throw new Exception("test18_28");
            for (int i = 0; i < blockchain.pendingBlocks.Length; i++)
            {
                if (i == 2)
                {
                    if (blockchain.pendingBlocks[i] == null)
                        throw new Exception("test18_29");
                    if (blockchain.pendingBlocks[i].Count != 1)
                        throw new Exception("test18_30");
                    if (!blockchain.pendingBlocks[i].Keys.Contains(blk1_2.Id))
                        throw new Exception("test18_31");

                    if (blockchain.rejectedBlocks[i] == null)
                        throw new Exception("test18_32");
                    if (blockchain.rejectedBlocks[i].Count != 1)
                        throw new Exception("test18_33");
                    if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_3.Id))
                        throw new Exception("test18_34");
                }
                else if (i == 101)
                {
                    if (blockchain.pendingBlocks[i] == null)
                        throw new Exception("test18_35");
                    if (blockchain.pendingBlocks[i].Count != 1)
                        throw new Exception("test18_36");
                    if (!blockchain.pendingBlocks[i].Keys.Contains(blk100.Id))
                        throw new Exception("test18_37");

                    if (blockchain.rejectedBlocks[i] != null)
                        throw new Exception("test18_38");
                }
                else
                {
                    if (blockchain.pendingBlocks[i] != null)
                        throw new Exception("test18_39");

                    if (blockchain.rejectedBlocks[i] != null)
                        throw new Exception("test18_40");
                }
            }

            TransactionalBlock blk1_4 = TransactionalBlock.GetBlockTemplate(1, blk1.coinbaseTxToMiner, blk2.transferTxs, _indexToBlock, 0);

            while (true)
            {
                blk1_4.UpdateTimestamp(DateTime.Now);
                blk1_4.UpdateNonce(nonce);

                if (blk1_4.Id.CompareTo(blk1_4.header.difficulty.Target) <= 0)
                {
                    Console.WriteLine("block1_4 mined.");

                    break;
                }

                int index = nonce.Length.RandomNum();
                int value = 256.RandomNum();

                nonce[index] = (byte)value;
            }

            BlockChain.UpdateChainReturnType type5 = blockchain.UpdateChain(blk1_4);

            if (type5 != BlockChain.UpdateChainReturnType.rejected)
                throw new Exception("test18_41");

            if (blockchain.blocksCurrent.value != 1)
                throw new Exception("test18_42");
            for (int i = 0; i < blockchain.pendingBlocks.Length; i++)
            {
                if (i == 2)
                {
                    if (blockchain.pendingBlocks[i] == null)
                        throw new Exception("test18_43");
                    if (blockchain.pendingBlocks[i].Count != 1)
                        throw new Exception("test18_44");
                    if (!blockchain.pendingBlocks[i].Keys.Contains(blk1_2.Id))
                        throw new Exception("test18_45");

                    if (blockchain.rejectedBlocks[i] == null)
                        throw new Exception("test18_46");
                    if (blockchain.rejectedBlocks[i].Count != 2)
                        throw new Exception("test18_47");
                    if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_3.Id))
                        throw new Exception("test18_48");
                    if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_4.Id))
                        throw new Exception("test18_49");
                }
                else if (i == 101)
                {
                    if (blockchain.pendingBlocks[i] == null)
                        throw new Exception("test18_50");
                    if (blockchain.pendingBlocks[i].Count != 1)
                        throw new Exception("test18_51");
                    if (!blockchain.pendingBlocks[i].Keys.Contains(blk100.Id))
                        throw new Exception("test18_52");

                    if (blockchain.rejectedBlocks[i] != null)
                        throw new Exception("test18_53");
                }
                else
                {
                    if (blockchain.pendingBlocks[i] != null)
                        throw new Exception("test18_54");

                    if (blockchain.rejectedBlocks[i] != null)
                        throw new Exception("test18_55");
                }
            }

            BlockChain.UpdateChainReturnType type8 = blockchain.UpdateChain(blk1_3);

            if (type8 != BlockChain.UpdateChainReturnType.invariable)
                throw new Exception("test18_56");

            if (blockchain.blocksCurrent.value != 1)
                throw new Exception("test18_57");
            for (int i = 0; i < blockchain.pendingBlocks.Length; i++)
            {
                if (i == 2)
                {
                    if (blockchain.pendingBlocks[i] == null)
                        throw new Exception("test18_58");
                    if (blockchain.pendingBlocks[i].Count != 1)
                        throw new Exception("test18_59");
                    if (!blockchain.pendingBlocks[i].Keys.Contains(blk1_2.Id))
                        throw new Exception("test18_60");

                    if (blockchain.rejectedBlocks[i] == null)
                        throw new Exception("test18_61");
                    if (blockchain.rejectedBlocks[i].Count != 2)
                        throw new Exception("test18_62");
                    if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_3.Id))
                        throw new Exception("test18_63");
                    if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_4.Id))
                        throw new Exception("test18_64");
                }
                else if (i == 101)
                {
                    if (blockchain.pendingBlocks[i] == null)
                        throw new Exception("test18_65");
                    if (blockchain.pendingBlocks[i].Count != 1)
                        throw new Exception("test18_66");
                    if (!blockchain.pendingBlocks[i].Keys.Contains(blk100.Id))
                        throw new Exception("test18_67");

                    if (blockchain.rejectedBlocks[i] != null)
                        throw new Exception("test18_68");
                }
                else
                {
                    if (blockchain.pendingBlocks[i] != null)
                        throw new Exception("test18_69");

                    if (blockchain.rejectedBlocks[i] != null)
                        throw new Exception("test18_70");
                }
            }

            BlockChain.UpdateChainReturnType type6 = blockchain.UpdateChain(blk1);

            if (type6 != BlockChain.UpdateChainReturnType.updated)
                throw new Exception("test18_71");

            BlockChain.UpdateChainReturnType type7 = blockchain.UpdateChain(blk1_3);

            if (type7 != BlockChain.UpdateChainReturnType.invariable)
                throw new Exception("test18_72");

            if (blockchain.blocksCurrent.value != 2)
                throw new Exception("test18_73");
            for (int i = 0; i < blockchain.pendingBlocks.Length; i++)
            {
                if (i == 2)
                {
                    if (blockchain.pendingBlocks[i] == null)
                        throw new Exception("test18_74");
                    if (blockchain.pendingBlocks[i].Count != 1)
                        throw new Exception("test18_75");
                    if (!blockchain.pendingBlocks[i].Keys.Contains(blk1_2.Id))
                        throw new Exception("test18_76");

                    if (blockchain.rejectedBlocks[i] == null)
                        throw new Exception("test18_77");
                    if (blockchain.rejectedBlocks[i].Count != 2)
                        throw new Exception("test18_78");
                    if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_3.Id))
                        throw new Exception("test18_79");
                    if (!blockchain.rejectedBlocks[i].Keys.Contains(blk1_4.Id))
                        throw new Exception("test18_80");
                }
                else if (i == 101)
                {
                    if (blockchain.pendingBlocks[i] == null)
                        throw new Exception("test18_81");
                    if (blockchain.pendingBlocks[i].Count != 1)
                        throw new Exception("test18_82");
                    if (!blockchain.pendingBlocks[i].Keys.Contains(blk100.Id))
                        throw new Exception("test18_83");

                    if (blockchain.rejectedBlocks[i] != null)
                        throw new Exception("test18_84");
                }
                else
                {
                    if (blockchain.pendingBlocks[i] != null)
                        throw new Exception("test18_85");

                    if (blockchain.rejectedBlocks[i] != null)
                        throw new Exception("test18_86");
                }
            }

            BlockHeader bh3 = new BlockHeader();
            bh3.LoadVersion0(2, hashzero, DateTime.Now, blk2.Difficulty, new byte[10]);

            TransactionalBlock blk2_2 = new NormalBlock();
            blk2_2.LoadVersion0(bh3, blk2.coinbaseTxToMiner, blk2.transferTxs);
            blk2_2.UpdateMerkleRootHash();

            BlockChain.UpdateChainReturnType type9 = blockchain.UpdateChain(blk2_2);

            if (type9 != BlockChain.UpdateChainReturnType.pending)
                throw new Exception("test18_87");

            BlockHeader bh4 = new BlockHeader();
            bh4.LoadVersion0(2, blk1_2.Id, DateTime.Now, blk2.Difficulty, new byte[10]);

            TransactionalBlock blk2_3 = new NormalBlock();
            blk2_3.LoadVersion0(bh4, blk2.coinbaseTxToMiner, blk2.transferTxs);
            blk2_3.UpdateMerkleRootHash();

            BlockChain.UpdateChainReturnType type10 = blockchain.UpdateChain(blk2_3);

            if (type10 != BlockChain.UpdateChainReturnType.pending)
                throw new Exception("test18_88");

            BlockHeader bh7 = new BlockHeader();
            bh7.LoadVersion0(2, blk1_3.Id, DateTime.Now, blk2.Difficulty, new byte[10]);

            TransactionalBlock blk2_4 = new NormalBlock();
            blk2_4.LoadVersion0(bh7, blk2.coinbaseTxToMiner, blk2.transferTxs);
            blk2_4.UpdateMerkleRootHash();

            BlockChain.UpdateChainReturnType type13 = blockchain.UpdateChain(blk2_4);

            if (type13 != BlockChain.UpdateChainReturnType.rejected)
                throw new Exception("test18_91");

            for (int i = 2; i < blks2.Length; i++)
            {
                BlockChain.UpdateChainReturnType type11 = blockchain.UpdateChain(blks2[i]);

                if (type11 != BlockChain.UpdateChainReturnType.updated)
                    throw new Exception("test18_89");
            }

            TransactionalBlock blk10 = TransactionalBlock.GetBlockTemplate(10, blk2.coinbaseTxToMiner, blk2.transferTxs, _indexToBlock, 0);

            while (true)
            {
                blk10.UpdateTimestamp(DateTime.Now);
                blk10.UpdateNonce(nonce);

                if (blk10.Id.CompareTo(blk10.header.difficulty.Target) <= 0)
                {
                    Console.WriteLine("block10 mined.");

                    break;
                }

                int index = nonce.Length.RandomNum();
                int value = 256.RandomNum();

                nonce[index] = (byte)value;
            }

            BlockChain.UpdateChainReturnType type12 = blockchain.UpdateChain(blk10);

            if (type12 != BlockChain.UpdateChainReturnType.rejected)
                throw new Exception("test18_90");

            Console.WriteLine("test18_succeeded");
        }
 private void Init(uint256 txId, BalanceId balanceId, uint256 blockId, BlockHeader blockHeader, int height)
 {
     BlockId = blockId;
     SeenUtc = blockHeader == null ? DateTime.UtcNow : blockHeader.BlockTime.UtcDateTime;
     Height = blockId == null ? UnconfirmedBalanceLocator.UnconfHeight : height;
     TransactionId = txId;
     BalanceId = balanceId;
 }
Beispiel #8
0
		private ConcurrentChain CreateChain(BlockHeader genesis, int height)
		{
			var chain = new ConcurrentChain(genesis);
			for(int i = 0; i < height; i++)
			{
				var b = TestUtils.CreateFakeBlock();
				b.Header.HashPrevBlock = chain.Tip.HashBlock;
				chain.SetTip(b.Header);
			}
			return chain;
		}
 public bool ValidateSeal(BlockHeader header)
 {
     return(true);
 }
 public bool ValidateParams(Block parent, BlockHeader header)
 {
     return(true);
 }
Beispiel #11
0
        public IAuRaValidator CreateValidatorProcessor(AuRaParameters.Validator validator, BlockHeader parentHeader = null, long?startBlock = null)
        {
            IValidatorContract GetValidatorContract() => new ValidatorContract(_transactionProcessor, _abiEncoder, validator.GetContractAddress(), _stateProvider, _readOnlyTxProcessorSource, _signer);
            IReportingValidatorContract GetReportingValidatorContract() => new ReportingValidatorContract(_abiEncoder, validator.GetContractAddress(), _signer);

            var  validSealerStrategy = new ValidSealerStrategy();
            long startBlockNumber    = startBlock ?? AuRaValidatorBase.DefaultStartBlockNumber;

            ContractBasedValidator GetContractBasedValidator() =>
            new ContractBasedValidator(
                GetValidatorContract(),
                _blockTree,
                _receiptFinder,
                _validatorStore,
                validSealerStrategy,
                _finalizationManager,
                parentHeader,
                _logManager,
                startBlockNumber,
                _posdaoTransition,
                _forSealing);

            return(validator.ValidatorType switch
            {
                AuRaParameters.ValidatorType.List =>
                new ListBasedValidator(
                    validator,
                    validSealerStrategy,
                    _validatorStore,
                    _logManager,
                    startBlockNumber,
                    _forSealing),

                AuRaParameters.ValidatorType.Contract => GetContractBasedValidator(),

                AuRaParameters.ValidatorType.ReportingContract =>
                new ReportingContractBasedValidator(
                    GetContractBasedValidator(),
                    GetReportingValidatorContract(),
                    _posdaoTransition,
                    _txSender,
                    _txPool,
                    _miningConfig,
                    _stateProvider,
                    _reportingValidatorCache,
                    _specProvider,
                    _logManager),

                AuRaParameters.ValidatorType.Multi =>
                new MultiValidator(
                    validator,
                    this,
                    _blockTree,
                    _validatorStore,
                    _finalizationManager,
                    parentHeader,
                    _logManager,
                    _forSealing),

                _ => throw new ArgumentOutOfRangeException()
            });
Beispiel #12
0
 public bool IsAllowed(Transaction tx, BlockHeader parentHeader) => true;
 public UInt256 Calculate(BlockHeader header, BlockHeader parent) => header.Timestamp;
 public Block Prepare(BlockHeader header) => PrepareBlock(header);
Beispiel #15
0
        private async Task <string> GetNextMinerPubkey(BlockHeader blockHeader)
        {
            var broadcastList = await _broadcastPrivilegedPubkeyListProvider.GetPubkeyList(blockHeader);

            return(broadcastList.IsNullOrEmpty() ? null : broadcastList[0]);
        }
Beispiel #16
0
		public void WriteBlockHeader(BlockHeader header)
		{
			Block block = new Block(header);
			_HeaderStore.Put(block);
		}
Beispiel #17
0
			public BlockHeaderWithTxCount(BlockHeader header)
			{
				_Header = header;
			}
            public On CreateNode(PrivateKey privateKey, bool withGenesisAlreadyProcessed = false)
            {
                if (_logger.IsInfo)
                {
                    _logger.Info($"CREATING NODE {privateKey.Address}");
                }
                _logManagers[privateKey] = LimboLogs.Instance;
//                _logManagers[privateKey] = new OneLoggerLogManager(new ConsoleAsyncLogger(LogLevel.Debug, $"{privateKey.Address} "));
                var nodeLogManager = _logManagers[privateKey];

                AutoResetEvent newHeadBlockEvent = new AutoResetEvent(false);

                _blockEvents.Add(privateKey, newHeadBlockEvent);

                MemDb blocksDb    = new MemDb();
                MemDb headersDb   = new MemDb();
                MemDb blockInfoDb = new MemDb();

                ISnapshotableDb stateDb = new StateDb();
                ISnapshotableDb codeDb  = new StateDb();
                IDb             traceDb = new MemDb();

                ISpecProvider specProvider = RinkebySpecProvider.Instance;

                StateProvider stateProvider = new StateProvider(stateDb, codeDb, nodeLogManager);

                stateProvider.CreateAccount(TestItem.PrivateKeyD.Address, 100.Ether());
                stateProvider.Commit(GoerliSpecProvider.Instance.GenesisSpec);

                TxPool txPool = new TxPool(new InMemoryTxStorage(), _timestamper, _ethereumEcdsa, GoerliSpecProvider.Instance, new TxPoolConfig(), stateProvider, _logManager);

                _pools[privateKey] = txPool;

                BlockTree blockTree = new BlockTree(blocksDb, headersDb, blockInfoDb, new ChainLevelInfoRepository(blockInfoDb), GoerliSpecProvider.Instance, txPool, nodeLogManager);

                blockTree.NewHeadBlock += (sender, args) => { _blockEvents[privateKey].Set(); };

                BlockhashProvider blockhashProvider = new BlockhashProvider(blockTree, LimboLogs.Instance);

                _blockTrees.Add(privateKey, blockTree);

                IBasicWallet    wallet          = new BasicWallet(privateKey);
                SnapshotManager snapshotManager = new SnapshotManager(_cliqueConfig, blocksDb, blockTree, _ethereumEcdsa, nodeLogManager);

                _snapshotManager[privateKey] = snapshotManager;
                CliqueSealer cliqueSealer = new CliqueSealer(wallet, _cliqueConfig, snapshotManager, privateKey.Address, nodeLogManager);



                _genesis.StateRoot       = _genesis3Validators.StateRoot = stateProvider.StateRoot;
                _genesis.Hash            = BlockHeader.CalculateHash(_genesis.Header);
                _genesis3Validators.Hash = BlockHeader.CalculateHash(_genesis3Validators.Header);

                StorageProvider      storageProvider      = new StorageProvider(stateDb, stateProvider, nodeLogManager);
                TransactionProcessor transactionProcessor = new TransactionProcessor(GoerliSpecProvider.Instance, stateProvider, storageProvider, new VirtualMachine(stateProvider, storageProvider, blockhashProvider, specProvider, nodeLogManager), nodeLogManager);
                BlockProcessor       blockProcessor       = new BlockProcessor(GoerliSpecProvider.Instance, AlwaysValidBlockValidator.Instance, NoBlockRewards.Instance, transactionProcessor, stateDb, codeDb, traceDb, stateProvider, storageProvider, txPool, NullReceiptStorage.Instance, nodeLogManager);
                BlockchainProcessor  processor            = new BlockchainProcessor(blockTree, blockProcessor, new AuthorRecoveryStep(snapshotManager), nodeLogManager, false, false);

                processor.Start();

                StateProvider        minerStateProvider        = new StateProvider(stateDb, codeDb, nodeLogManager);
                StorageProvider      minerStorageProvider      = new StorageProvider(stateDb, minerStateProvider, nodeLogManager);
                VirtualMachine       minerVirtualMachine       = new VirtualMachine(minerStateProvider, minerStorageProvider, blockhashProvider, specProvider, nodeLogManager);
                TransactionProcessor minerTransactionProcessor = new TransactionProcessor(GoerliSpecProvider.Instance, minerStateProvider, minerStorageProvider, minerVirtualMachine, nodeLogManager);
                BlockProcessor       minerBlockProcessor       = new BlockProcessor(GoerliSpecProvider.Instance, AlwaysValidBlockValidator.Instance, NoBlockRewards.Instance, minerTransactionProcessor, stateDb, codeDb, traceDb, minerStateProvider, minerStorageProvider, txPool, NullReceiptStorage.Instance, nodeLogManager);
                BlockchainProcessor  minerProcessor            = new BlockchainProcessor(blockTree, minerBlockProcessor, new AuthorRecoveryStep(snapshotManager), nodeLogManager, false, false);

                if (withGenesisAlreadyProcessed)
                {
                    ProcessGenesis(privateKey);
                }

                CliqueBlockProducer blockProducer = new CliqueBlockProducer(txPool, minerProcessor, blockTree, _timestamper, new CryptoRandom(), minerStateProvider, snapshotManager, cliqueSealer, privateKey.Address, _cliqueConfig, nodeLogManager);

                blockProducer.Start();

                _producers.Add(privateKey, blockProducer);

                return(this);
            }
        public static IEnumerable<OrderedBalanceChange> ExtractScriptBalances(uint256 txId, Transaction transaction, uint256 blockId, BlockHeader blockHeader, int height)
        {
            if(transaction == null)
                throw new ArgumentNullException("transaction");
            if(txId == null)
                txId = transaction.GetHash();

            if(blockId == null && blockHeader != null)
                blockId = blockHeader.GetHash();

            Dictionary<Script, OrderedBalanceChange> changeByScriptPubKey = new Dictionary<Script, OrderedBalanceChange>();
            uint i = 0;
            foreach(var input in transaction.Inputs)
            {
                if(transaction.IsCoinBase)
                {
                    i++;
                    break;
                }
                TxDestination signer = null;
                if(input.ScriptSig.Length != 0)
                {
                    signer = input.ScriptSig.GetSigner();
                }
                else
                {
                    signer = GetSigner(input.WitScript);
                }
                if(signer != null)
                {
                    OrderedBalanceChange entry = null;
                    if(!changeByScriptPubKey.TryGetValue(signer.ScriptPubKey, out entry))
                    {
                        entry = new OrderedBalanceChange(txId, signer.ScriptPubKey, blockId, blockHeader, height);
                        changeByScriptPubKey.Add(signer.ScriptPubKey, entry);
                    }
                    entry.SpentOutpoints.Add(input.PrevOut);
                    entry.SpentIndices.Add(i);
                }
                i++;
            }

            i = 0;
            bool hasOpReturn = false;
            foreach(var output in transaction.Outputs)
            {
                var bytes = output.ScriptPubKey.ToBytes(true);
                if(bytes.Length != 0 && bytes[0] == (byte)OpcodeType.OP_RETURN)
                {
                    hasOpReturn = true;
                    i++;
                    continue;
                }

                OrderedBalanceChange entry = null;
                if(!changeByScriptPubKey.TryGetValue(output.ScriptPubKey, out entry))
                {
                    entry = new OrderedBalanceChange(txId, output.ScriptPubKey, blockId, blockHeader, height);
                    changeByScriptPubKey.Add(output.ScriptPubKey, entry);
                }
                entry.ReceivedCoins.Add(new Coin()
                {
                    Outpoint = new OutPoint(txId, i),
                    TxOut = output
                });
                i++;
            }

            foreach(var entity in changeByScriptPubKey)
            {
                entity.Value.HasOpReturn = hasOpReturn;
                entity.Value.IsCoinbase = transaction.IsCoinBase;
            }

            return changeByScriptPubKey.Values;
        }
Beispiel #20
0
        private List <string> RunAssertions(BlockchainTest test, Block headBlock, IStorageProvider storageProvider, IStateProvider stateProvider)
        {
            if (test.PostStateRoot != null)
            {
                return(test.PostStateRoot != stateProvider.StateRoot ? new List <string> {
                    "state root mismatch"
                } : Enumerable.Empty <string>().ToList());
            }

            TestBlockHeaderJson testHeaderJson = test.Blocks
                                                 .Where(b => b.BlockHeader != null)
                                                 .SingleOrDefault(b => new Keccak(b.BlockHeader.Hash) == headBlock.Hash)?.BlockHeader ?? test.GenesisBlockHeader;
            BlockHeader   testHeader  = JsonToEthereumTest.Convert(testHeaderJson);
            List <string> differences = new List <string>();

            var deletedAccounts = test.Pre.Where(pre => !test.PostState.ContainsKey(pre.Key));

            foreach (KeyValuePair <Address, AccountState> deletedAccount in deletedAccounts)
            {
                if (stateProvider.AccountExists(deletedAccount.Key))
                {
                    differences.Add($"Pre state account {deletedAccount.Key} was not deleted as expected.");
                }
            }

            foreach (KeyValuePair <Address, AccountState> accountState in test.PostState)
            {
                int differencesBefore = differences.Count;

                if (differences.Count > 8)
                {
                    Console.WriteLine("More than 8 differences...");
                    break;
                }

                bool    accountExists = stateProvider.AccountExists(accountState.Key);
                UInt256?balance       = accountExists ? stateProvider.GetBalance(accountState.Key) : (UInt256?)null;
                UInt256?nonce         = accountExists ? stateProvider.GetNonce(accountState.Key) : (UInt256?)null;

                if (accountState.Value.Balance != balance)
                {
                    differences.Add($"{accountState.Key} balance exp: {accountState.Value.Balance}, actual: {balance}, diff: {balance - accountState.Value.Balance}");
                }

                if (accountState.Value.Nonce != nonce)
                {
                    differences.Add($"{accountState.Key} nonce exp: {accountState.Value.Nonce}, actual: {nonce}");
                }

                byte[] code = accountExists ? stateProvider.GetCode(accountState.Key) : new byte[0];
                if (!Bytes.AreEqual(accountState.Value.Code, code))
                {
                    differences.Add($"{accountState.Key} code exp: {accountState.Value.Code?.Length}, actual: {code?.Length}");
                }

                if (differences.Count != differencesBefore)
                {
                    _logger.Info($"ACCOUNT STATE ({accountState.Key}) HAS DIFFERENCES");
                }

                differencesBefore = differences.Count;

                KeyValuePair <UInt256, byte[]>[] clearedStorages = new KeyValuePair <UInt256, byte[]> [0];
                if (test.Pre.ContainsKey(accountState.Key))
                {
                    clearedStorages = test.Pre[accountState.Key].Storage.Where(s => !accountState.Value.Storage.ContainsKey(s.Key)).ToArray();
                }

                foreach (KeyValuePair <UInt256, byte[]> clearedStorage in clearedStorages)
                {
                    byte[] value = !stateProvider.AccountExists(accountState.Key) ? Bytes.Empty : storageProvider.Get(new StorageCell(accountState.Key, clearedStorage.Key));
                    if (!value.IsZero())
                    {
                        differences.Add($"{accountState.Key} storage[{clearedStorage.Key}] exp: 0x00, actual: {value.ToHexString(true)}");
                    }
                }

                foreach (KeyValuePair <UInt256, byte[]> storageItem in accountState.Value.Storage)
                {
                    byte[] value = !stateProvider.AccountExists(accountState.Key) ? Bytes.Empty : storageProvider.Get(new StorageCell(accountState.Key, storageItem.Key)) ?? new byte[0];
                    if (!Bytes.AreEqual(storageItem.Value, value))
                    {
                        differences.Add($"{accountState.Key} storage[{storageItem.Key}] exp: {storageItem.Value.ToHexString(true)}, actual: {value.ToHexString(true)}");
                    }
                }

                if (differences.Count != differencesBefore)
                {
                    _logger.Info($"ACCOUNT STORAGE ({accountState.Key}) HAS DIFFERENCES");
                }
            }

            BigInteger gasUsed = headBlock.Header.GasUsed;

            if ((testHeader?.GasUsed ?? 0) != gasUsed)
            {
                differences.Add($"GAS USED exp: {testHeader?.GasUsed ?? 0}, actual: {gasUsed}");
            }

            if (headBlock.Transactions.Any() && testHeader.Bloom.ToString() != headBlock.Header.Bloom.ToString())
            {
                differences.Add($"BLOOM exp: {testHeader.Bloom}, actual: {headBlock.Header.Bloom}");
            }

            if (testHeader.StateRoot != stateProvider.StateRoot)
            {
                differences.Add($"STATE ROOT exp: {testHeader.StateRoot}, actual: {stateProvider.StateRoot}");
            }

            if (testHeader.TxRoot != headBlock.Header.TxRoot)
            {
                differences.Add($"TRANSACTIONS ROOT exp: {testHeader.TxRoot}, actual: {headBlock.Header.TxRoot}");
            }

            if (testHeader.ReceiptsRoot != headBlock.Header.ReceiptsRoot)
            {
                differences.Add($"RECEIPT ROOT exp: {testHeader.ReceiptsRoot}, actual: {headBlock.Header.ReceiptsRoot}");
            }

            if (test.LastBlockHash != headBlock.Hash)
            {
                differences.Add($"LAST BLOCK HASH exp: {test.LastBlockHash}, actual: {headBlock.Hash}");
            }

            foreach (string difference in differences)
            {
                _logger.Info(difference);
            }

            return(differences);
        }
Beispiel #21
0
		private static BlockHeader ParseBlockHeader(RPCResponse resp)
		{
			var header = new BlockHeader();
			header.Version = (int)resp.Result["version"];
			header.Nonce = (uint)resp.Result["nonce"];
			header.Bits = new Target(Encoders.Hex.DecodeData((string)resp.Result["bits"]));
			if (resp.Result["previousblockhash"] != null)
			{
				header.HashPrevBlock = uint256.Parse((string)resp.Result["previousblockhash"]);
			}
			if (resp.Result["time"] != null)
			{
				header.BlockTime = Utils.UnixTimeToDateTime((uint)resp.Result["time"]);
			}
			if (resp.Result["merkleroot"] != null)
			{
				header.HashMerkleRoot = uint256.Parse((string)resp.Result["merkleroot"]);
			}
			return header;
		}
Beispiel #22
0
        public static (IFederationManager federationManager, IFederationHistory federationHistory) CreateFederationManager(object caller, Network network, LoggerFactory loggerFactory, ISignals signals)
        {
            string dir = TestBase.CreateTestDir(caller);

            var dbreezeSerializer = new DBreezeSerializer(network.Consensus.ConsensusFactory);

            var nodeSettings = new NodeSettings(network, args: new string[] { $"-datadir={dir}" });

            Key federationKey = new Mnemonic("lava frown leave wedding virtual ghost sibling able mammal liar wide wisdom").DeriveExtKey().PrivateKey;

            new KeyTool(nodeSettings.DataFolder).SavePrivateKey(federationKey);

            var consensusManager = new Mock <IConsensusManager>();

            consensusManager.Setup(c => c.Tip).Returns(new ChainedHeader(network.GetGenesis().Header, network.GenesisHash, 0));

            var fullNode = new Mock <IFullNode>();

            fullNode.Setup(x => x.NodeService <IConsensusManager>(false)).Returns(consensusManager.Object);

            var counterChainSettings = new CounterChainSettings(nodeSettings, new CounterChainNetworkWrapper(new StraxRegTest()));

            var federationManager  = new FederationManager(counterChainSettings, fullNode.Object, network, nodeSettings, loggerFactory, signals);
            var asyncProvider      = new AsyncProvider(loggerFactory, signals, new Mock <INodeLifetime>().Object);
            var finalizedBlockRepo = new FinalizedBlockInfoRepository(new KeyValueRepository(nodeSettings.DataFolder, dbreezeSerializer), loggerFactory, asyncProvider);

            finalizedBlockRepo.LoadFinalizedBlockInfoAsync(network).GetAwaiter().GetResult();

            var chainIndexerMock = new Mock <ChainIndexer>();
            var header           = new BlockHeader();

            chainIndexerMock.Setup(x => x.Tip).Returns(new ChainedHeader(header, header.GetHash(), 0));
            var votingManager = new VotingManager(federationManager, loggerFactory,
                                                  new Mock <IPollResultExecutor>().Object, new Mock <INodeStats>().Object, nodeSettings.DataFolder, dbreezeSerializer, signals, finalizedBlockRepo, network);

            var federationHistory = new Mock <IFederationHistory>();

            federationHistory.Setup(x => x.GetFederationMemberForBlock(It.IsAny <ChainedHeader>())).Returns <ChainedHeader>((chainedHeader) =>
            {
                List <IFederationMember> members = ((PoAConsensusOptions)network.Consensus.Options).GenesisFederationMembers;
                return(members[chainedHeader.Height % members.Count]);
            });

            federationHistory.Setup(x => x.GetFederationMemberForBlock(It.IsAny <ChainedHeader>(), It.IsAny <List <IFederationMember> >())).Returns <ChainedHeader, List <IFederationMember> >((chainedHeader, members) =>
            {
                members = members ?? ((PoAConsensusOptions)network.Consensus.Options).GenesisFederationMembers;
                return(members[chainedHeader.Height % members.Count]);
            });

            federationHistory.Setup(x => x.GetFederationForBlock(It.IsAny <ChainedHeader>())).Returns <ChainedHeader>((chainedHeader) =>
            {
                return(((PoAConsensusOptions)network.Consensus.Options).GenesisFederationMembers);
            });

            federationHistory
            .Setup(x => x.GetFederationMemberForTimestamp(It.IsAny <uint>(), It.IsAny <PoAConsensusOptions>()))
            .Returns <uint, PoAConsensusOptions>((headerUnixTimestamp, poAConsensusOptions) =>
            {
                List <IFederationMember> federationMembers = poAConsensusOptions.GenesisFederationMembers;

                uint roundTime = (uint)(federationMembers.Count * poAConsensusOptions.TargetSpacingSeconds);

                // Time when current round started.
                uint roundStartTimestamp = (headerUnixTimestamp / roundTime) * roundTime;

                // Slot number in current round.
                int currentSlotNumber = (int)((headerUnixTimestamp - roundStartTimestamp) / poAConsensusOptions.TargetSpacingSeconds);

                return(federationMembers[currentSlotNumber]);
            });

            votingManager.Initialize(federationHistory.Object);
            fullNode.Setup(x => x.NodeService <VotingManager>(It.IsAny <bool>())).Returns(votingManager);
            federationManager.Initialize();

            return(federationManager, federationHistory.Object);
        }
Beispiel #23
0
        //Blockのテスト1
        public static void Test11()
        {
            GenesisBlock gblk = new GenesisBlock();

            if (gblk.Index != 0)
                throw new Exception("test11_1");
            if (gblk.PrevId != null)
                throw new Exception("test11_2");
            if (gblk.Difficulty.Diff != 0.00000011)
                throw new Exception("test11_3");
            if (gblk.Transactions.Length != 0)
                throw new Exception("test11_4");

            byte[] gblkBytes = gblk.ToBinary();

            if (gblkBytes.Length != 68)
                throw new Exception("test11_5");

            GenesisBlock gblkRestore = SHAREDDATA.FromBinary<GenesisBlock>(gblkBytes);

            if (!gblk.Id.Equals(gblkRestore.Id))
                throw new Exception("test11_6");

            byte[] gblkBytes2 = SHAREDDATA.ToBinary<Block>(gblk);

            if (gblkBytes2.Length != 88)
                throw new Exception("test11_7");

            GenesisBlock gblkRestore2 = SHAREDDATA.FromBinary<Block>(gblkBytes2) as GenesisBlock;

            if (!gblk.Id.Equals(gblkRestore2.Id))
                throw new Exception("test11_8");

            BlockHeader bh = new BlockHeader();

            bool flag = false;
            try
            {
                bh.LoadVersion0(0, null, DateTime.Now, null, new byte[10]);
            }
            catch (ArgumentOutOfRangeException)
            {
                flag = true;
            }
            if (!flag)
                throw new Exception("test11_9");

            bool flag2 = false;
            try
            {
                bh.LoadVersion0(1, null, DateTime.Now, null, new byte[9]);
            }
            catch (ArgumentOutOfRangeException)
            {
                flag2 = true;
            }
            if (!flag2)
                throw new Exception("test11_10");

            Difficulty<Creahash> diff = new Difficulty<Creahash>(HASHBASE.FromHash<Creahash>(new byte[] { 0, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }));
            Sha256Sha256Hash hash = new Sha256Sha256Hash(new byte[] { 1 });
            DateTime dt = DateTime.Now;
            byte[] nonce = new byte[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            bh.LoadVersion0(1, gblk.Id, DateTime.Now, diff, new byte[10]);

            bool flag3 = false;
            try
            {
                bh.UpdateNonce(new byte[11]);
            }
            catch (ArgumentOutOfRangeException)
            {
                flag3 = true;
            }
            if (!flag3)
                throw new Exception("test11_11");

            bh.UpdateMerkleRootHash(hash);
            bh.UpdateTimestamp(dt);
            bh.UpdateNonce(nonce);

            if (bh.index != 1)
                throw new Exception("test11_12");
            if (bh.prevBlockHash != gblk.Id)
                throw new Exception("test11_13");
            if (bh.merkleRootHash != hash)
                throw new Exception("test11_14");
            if (bh.timestamp != dt)
                throw new Exception("test11_15");
            if (bh.difficulty != diff)
                throw new Exception("test11_16");
            if (bh.nonce != nonce)
                throw new Exception("test11_17");

            byte[] bhBytes = bh.ToBinary();

            if (bhBytes.Length != 95)
                throw new Exception("test11_18");

            BlockHeader bhRestore = SHAREDDATA.FromBinary<BlockHeader>(bhBytes);

            if (bh.index != bhRestore.index)
                throw new Exception("test11_19");
            if (!bh.prevBlockHash.Equals(bhRestore.prevBlockHash))
                throw new Exception("test11_20");
            if (!bh.merkleRootHash.Equals(bhRestore.merkleRootHash))
                throw new Exception("test11_21");
            if (bh.timestamp != bhRestore.timestamp)
                throw new Exception("test11_22");
            if (bh.difficulty.Diff != bhRestore.difficulty.Diff)
                throw new Exception("test11_23");
            if (!bh.nonce.BytesEquals(bhRestore.nonce))
                throw new Exception("test11_24");

            bool flag4 = false;
            try
            {
                TransactionalBlock.GetBlockType(0, 0);
            }
            catch (ArgumentOutOfRangeException)
            {
                flag4 = true;
            }
            if (!flag4)
                throw new Exception("test11_25");

            Type type1 = TransactionalBlock.GetBlockType(60 * 24 - 1, 0);
            Type type2 = TransactionalBlock.GetBlockType(60 * 24, 0);
            Type type3 = TransactionalBlock.GetBlockType(60 * 24 + 1, 0);

            if (type1 != typeof(NormalBlock))
                throw new Exception("test11_26");
            if (type2 != typeof(FoundationalBlock))
                throw new Exception("test11_27");
            if (type3 != typeof(NormalBlock))
                throw new Exception("test11_28");

            bool flag5 = false;
            try
            {
                TransactionalBlock.GetRewardToAll(0, 0);
            }
            catch (ArgumentOutOfRangeException)
            {
                flag5 = true;
            }
            if (!flag5)
                throw new Exception("test11_29");

            bool flag6 = false;
            try
            {
                TransactionalBlock.GetRewardToMiner(0, 0);
            }
            catch (ArgumentOutOfRangeException)
            {
                flag6 = true;
            }
            if (!flag6)
                throw new Exception("test11_30");

            bool flag7 = false;
            try
            {
                TransactionalBlock.GetRewardToFoundation(0, 0);
            }
            catch (ArgumentOutOfRangeException)
            {
                flag7 = true;
            }
            if (!flag7)
                throw new Exception("test11_31");

            bool flag8 = false;
            try
            {
                TransactionalBlock.GetRewardToFoundationInterval(0, 0);
            }
            catch (ArgumentOutOfRangeException)
            {
                flag8 = true;
            }
            if (!flag8)
                throw new Exception("test11_32");

            bool flag9 = false;
            try
            {
                TransactionalBlock.GetRewardToFoundationInterval(1, 0);
            }
            catch (ArgumentException)
            {
                flag9 = true;
            }
            if (!flag9)
                throw new Exception("test11_33");

            CurrencyUnit initial = new Creacoin(60.0m);
            decimal rate = 1.25m;
            for (int i = 0; i < 8; i++)
            {
                CurrencyUnit reward1 = i != 0 ? TransactionalBlock.GetRewardToAll((60 * 24 * 365 * i) - 1, 0) : null;
                CurrencyUnit reward2 = i != 0 ? TransactionalBlock.GetRewardToAll(60 * 24 * 365 * i, 0) : null;
                CurrencyUnit reward3 = TransactionalBlock.GetRewardToAll((60 * 24 * 365 * i) + 1, 0);

                CurrencyUnit reward7 = i != 0 ? TransactionalBlock.GetRewardToMiner((60 * 24 * 365 * i) - 1, 0) : null;
                CurrencyUnit reward8 = i != 0 ? TransactionalBlock.GetRewardToMiner(60 * 24 * 365 * i, 0) : null;
                CurrencyUnit reward9 = TransactionalBlock.GetRewardToMiner((60 * 24 * 365 * i) + 1, 0);

                CurrencyUnit reward10 = i != 0 ? TransactionalBlock.GetRewardToFoundation((60 * 24 * 365 * i) - 1, 0) : null;
                CurrencyUnit reward11 = i != 0 ? TransactionalBlock.GetRewardToFoundation(60 * 24 * 365 * i, 0) : null;
                CurrencyUnit reward12 = TransactionalBlock.GetRewardToFoundation((60 * 24 * 365 * i) + 1, 0);

                CurrencyUnit reward19 = i != 0 ? TransactionalBlock.GetRewardToFoundationInterval(((365 * i) - 1) * 60 * 24, 0) : null;
                CurrencyUnit reward20 = i != 0 ? TransactionalBlock.GetRewardToFoundationInterval(60 * 24 * 365 * i, 0) : null;
                CurrencyUnit reward21 = TransactionalBlock.GetRewardToFoundationInterval(((365 * i) + 1) * 60 * 24, 0);

                if (i != 0 && reward1.rawAmount != initial.rawAmount * rate)
                    throw new Exception("test11_34");
                if (i != 0 && reward7.rawAmount != initial.rawAmount * rate * 0.9m)
                    throw new Exception("test11_35");
                if (i != 0 && reward10.rawAmount != initial.rawAmount * rate * 0.1m)
                    throw new Exception("test11_36");
                if (i != 0 && reward19.rawAmount != initial.rawAmount * rate * 0.1m * 60m * 24m)
                    throw new Exception("test11_37");

                rate *= 0.8m;

                if (i != 0 && reward2.rawAmount != initial.rawAmount * rate)
                    throw new Exception("test11_38");
                if (i != 0 && reward8.rawAmount != initial.rawAmount * rate * 0.9m)
                    throw new Exception("test11_39");
                if (i != 0 && reward11.rawAmount != initial.rawAmount * rate * 0.1m)
                    throw new Exception("test11_40");
                if (i != 0 && reward20.rawAmount != initial.rawAmount * rate * 0.1m * 60m * 24m)
                    throw new Exception("test11_41");

                if (reward3.rawAmount != initial.rawAmount * rate)
                    throw new Exception("test11_42");
                if (reward9.rawAmount != initial.rawAmount * rate * 0.9m)
                    throw new Exception("test11_43");
                if (reward12.rawAmount != initial.rawAmount * rate * 0.1m)
                    throw new Exception("test11_44");
                if (reward21.rawAmount != initial.rawAmount * rate * 0.1m * 60m * 24m)
                    throw new Exception("test11_45");
            }

            CurrencyUnit reward4 = TransactionalBlock.GetRewardToAll((60 * 24 * 365 * 8) - 1, 0);
            CurrencyUnit reward5 = TransactionalBlock.GetRewardToAll(60 * 24 * 365 * 8, 0);
            CurrencyUnit reward6 = TransactionalBlock.GetRewardToAll((60 * 24 * 365 * 8) + 1, 0);

            CurrencyUnit reward13 = TransactionalBlock.GetRewardToMiner((60 * 24 * 365 * 8) - 1, 0);
            CurrencyUnit reward14 = TransactionalBlock.GetRewardToMiner(60 * 24 * 365 * 8, 0);
            CurrencyUnit reward15 = TransactionalBlock.GetRewardToMiner((60 * 24 * 365 * 8) + 1, 0);

            CurrencyUnit reward16 = TransactionalBlock.GetRewardToFoundation((60 * 24 * 365 * 8) - 1, 0);
            CurrencyUnit reward17 = TransactionalBlock.GetRewardToFoundation(60 * 24 * 365 * 8, 0);
            CurrencyUnit reward18 = TransactionalBlock.GetRewardToFoundation((60 * 24 * 365 * 8) + 1, 0);

            CurrencyUnit reward22 = TransactionalBlock.GetRewardToFoundationInterval(((365 * 8) - 1) * 60 * 24, 0);
            CurrencyUnit reward23 = TransactionalBlock.GetRewardToFoundationInterval(60 * 24 * 365 * 8, 0);
            CurrencyUnit reward24 = TransactionalBlock.GetRewardToFoundationInterval(((365 * 8) + 1) * 60 * 24, 0);

            if (reward4.rawAmount != initial.rawAmount * rate)
                throw new Exception("test11_46");
            if (reward13.rawAmount != initial.rawAmount * rate * 0.9m)
                throw new Exception("test11_47");
            if (reward16.rawAmount != initial.rawAmount * rate * 0.1m)
                throw new Exception("test11_48");
            if (reward22.rawAmount != initial.rawAmount * rate * 0.1m * 60m * 24m)
                throw new Exception("test11_49");

            if (reward5.rawAmount != 0)
                throw new Exception("test11_50");
            if (reward14.rawAmount != 0)
                throw new Exception("test11_51");
            if (reward17.rawAmount != 0)
                throw new Exception("test11_52");
            if (reward23.rawAmount != 0)
                throw new Exception("test11_53");

            if (reward6.rawAmount != 0)
                throw new Exception("test11_54");
            if (reward15.rawAmount != 0)
                throw new Exception("test11_55");
            if (reward18.rawAmount != 0)
                throw new Exception("test11_56");
            if (reward24.rawAmount != 0)
                throw new Exception("test11_57");

            Console.WriteLine("test11_succeeded");
        }
Beispiel #24
0
 public (bool Allowed, string Reason) IsAllowed(Transaction tx, BlockHeader parentHeader) => (true, string.Empty);
 public bool Validate(BlockHeader header, bool isUncle)
 {
     return(_headerValidator.Validate(header, isUncle));
 }
 public bool Validate(BlockHeader blockHeader, bool isOmmer = false)
 {
     return(_alwaysSameResult ?? _validationResults.Dequeue());
 }
Beispiel #27
0
 public AddBlockResult Insert(BlockHeader header)
 {
     return(_blockTree.Insert(header));
 }
 private string GetBlockHeaderBits(BlockHeader header)
 {
     byte[] bytes = this.GetBytes(header.Bits.ToCompact());
     return(Encoders.Hex.EncodeData(bytes));
 }
Beispiel #29
0
 public bool IsMainChain(BlockHeader blockHeader)
 {
     return(_blockTree.IsMainChain(blockHeader));
 }
Beispiel #30
0
        public bool Open(IFilter imageFilter)
        {
            byte[] magicB = new byte[4];
            Stream stream = imageFilter.GetDataForkStream();
            stream.Read(magicB, 0, 4);
            uint magic = BitConverter.ToUInt32(magicB, 0);

            if(magic != DFI_MAGIC &&
               magic != DFI_MAGIC2)
                return false;

            TrackOffsets = new SortedDictionary<int, long>();
            TrackLengths = new SortedDictionary<int, long>();
            int    t            = -1;
            ushort lastCylinder = 0, lastHead = 0;
            long   offset       = 0;

            while(stream.Position < stream.Length)
            {
                long thisOffset = stream.Position;

                byte[] blk = new byte[Marshal.SizeOf<BlockHeader>()];
                stream.Read(blk, 0, Marshal.SizeOf<BlockHeader>());
                BlockHeader blockHeader = Marshal.ByteArrayToStructureBigEndian<BlockHeader>(blk);

                AaruConsole.DebugWriteLine("DiscFerret plugin", "block@{0}.cylinder = {1}", thisOffset,
                                           blockHeader.cylinder);

                AaruConsole.DebugWriteLine("DiscFerret plugin", "block@{0}.head = {1}", thisOffset, blockHeader.head);

                AaruConsole.DebugWriteLine("DiscFerret plugin", "block@{0}.sector = {1}", thisOffset,
                                           blockHeader.sector);

                AaruConsole.DebugWriteLine("DiscFerret plugin", "block@{0}.length = {1}", thisOffset,
                                           blockHeader.length);

                if(stream.Position + blockHeader.length > stream.Length)
                {
                    AaruConsole.DebugWriteLine("DiscFerret plugin", "Invalid track block found at {0}", thisOffset);

                    break;
                }

                stream.Position += blockHeader.length;

                if(blockHeader.cylinder > 0 &&
                   blockHeader.cylinder > lastCylinder)
                {
                    lastCylinder = blockHeader.cylinder;
                    lastHead     = 0;
                    TrackOffsets.Add(t, offset);
                    TrackLengths.Add(t, (thisOffset - offset) + 1);
                    offset = thisOffset;
                    t++;
                }
                else if(blockHeader.head > 0 &&
                        blockHeader.head > lastHead)
                {
                    lastHead = blockHeader.head;
                    TrackOffsets.Add(t, offset);
                    TrackLengths.Add(t, (thisOffset - offset) + 1);
                    offset = thisOffset;
                    t++;
                }

                if(blockHeader.cylinder > _imageInfo.Cylinders)
                    _imageInfo.Cylinders = blockHeader.cylinder;

                if(blockHeader.head > _imageInfo.Heads)
                    _imageInfo.Heads = blockHeader.head;
            }

            _imageInfo.Heads++;
            _imageInfo.Cylinders++;

            _imageInfo.Application        = "DiscFerret";
            _imageInfo.ApplicationVersion = magic == DFI_MAGIC2 ? "2.0" : "1.0";

            throw new NotImplementedException("Flux decoding is not yet implemented.");
        }
Beispiel #31
0
 public BlockHeader GetBlockHeader(uint256 blockHash)
 {
     var resp = SendCommand("getblock", blockHash.ToString());
     BlockHeader header = new BlockHeader();
     header.Version = (int)resp.Result["version"];
     header.Nonce = (uint)resp.Result["nonce"];
     header.Bits = new Target(Encoders.Hex.DecodeData((string)resp.Result["bits"]));
     if(resp.Result["previousblockhash"] != null)
     {
         header.HashPrevBlock = new uint256(Encoders.Hex.DecodeData((string)resp.Result["previousblockhash"]),false);
     }
     if(resp.Result["time"] != null)
     {
         header.BlockTime = Utils.UnixTimeToDateTime((uint)resp.Result["time"]);
     }
     if(resp.Result["merkleroot"] != null)
     {
         header.HashMerkleRoot = new uint256(Encoders.Hex.DecodeData((string)resp.Result["merkleroot"]),false);
     }
     return header;
 }
 /// <summary>
 /// Get current validator set (last enacted or initial if no changes ever made)
 /// function getValidators() constant returns (address[] _validators);
 /// </summary>
 public Address[] GetValidators(BlockHeader parentHeader) => Constant.Call <Address[]>(parentHeader, nameof(GetValidators), Address.Zero);
			public void Return(BlockHeader header, int height)
			{
				_Return = new ChainedBlock(header, height);
			}
 /// <summary>
 /// Called when an initiated change reaches finality and is activated.
 /// Only valid when msg.sender == SUPER_USER (EIP96, 2**160 - 2)
 ///
 /// Also called when the contract is first enabled for consensus. In this case,
 /// the "change" finalized is the activation of the initial set.
 /// function finalizeChange();
 /// </summary>
 public void FinalizeChange(BlockHeader blockHeader) => TryCall(blockHeader, nameof(FinalizeChange), Address.SystemUser, UnlimitedGas, out _);
Beispiel #35
0
		private ChainedBlock AddBlock(ConcurrentChain chain)
		{
			BlockHeader header = new BlockHeader();
			header.Nonce = RandomUtils.GetUInt32();
			header.HashPrevBlock = chain.Tip.HashBlock;
			chain.SetTip(header);
			return chain.GetBlock(header.GetHash());
		}
Beispiel #36
0
 public SyncingContext BestSuggestBlockIs(BlockHeader blockHeader)
 {
     Assert.AreSame(blockHeader, BlockTree.BestSuggestedHeader);
     return(this);
 }
 public static IEnumerable<OrderedBalanceChange> ExtractWalletBalances(
                                                                     uint256 txId,
                                                                     Transaction tx,
                                                                     uint256 blockId,
                                                                     BlockHeader blockHeader,
                                                                     int height,
                                                                     WalletRuleEntryCollection walletCollection)
 {
     Dictionary<string, OrderedBalanceChange> entitiesByWallet = new Dictionary<string, OrderedBalanceChange>();
     var scriptBalances = ExtractScriptBalances(txId, tx, blockId, blockHeader, height);
     foreach(var scriptBalance in scriptBalances)
     {
         foreach(var walletRuleEntry in walletCollection.GetRulesFor(scriptBalance.ScriptPubKey))
         {
             OrderedBalanceChange walletEntity = null;
             if(!entitiesByWallet.TryGetValue(walletRuleEntry.WalletId, out walletEntity))
             {
                 walletEntity = new OrderedBalanceChange(walletRuleEntry.WalletId, scriptBalance);
                 entitiesByWallet.Add(walletRuleEntry.WalletId, walletEntity);
             }
             walletEntity.Merge(scriptBalance, walletRuleEntry.Rule);
         }
     }
     foreach(var b in entitiesByWallet.Values)
         b.UpdateToScriptCoins();
     return entitiesByWallet.Values;
 }
Beispiel #38
0
 public SyncingContext HeaderIs(BlockHeader header)
 {
     _logger.Info($"ASSERTING THAT HEADER IS {header.Number} (WHEN ACTUALLY IS {_blockHeader?.Number})");
     Assert.AreSame(header, _blockHeader, "header");
     return(this);
 }
 internal OrderedBalanceChange(uint256 txId, Script scriptPubKey, uint256 blockId, BlockHeader blockHeader, int height)
     : this()
 {
     var balanceId = new BalanceId(scriptPubKey);
     Init(txId, balanceId, blockId, blockHeader, height);
     if(!balanceId.ContainsScript)
     {
         _ScriptPubKey = scriptPubKey;
     }
 }
Beispiel #40
0
 public SyncingContext HeaderIs(BlockHeader header, out bool isSuccess)
 {
     _logger.Info($"ASSERTING THAT HEADER IS {header.Number} (WHEN ACTUALLY IS {_blockHeader?.Number})");
     isSuccess = ReferenceEquals(header, _blockHeader);
     return(this);
 }
 internal OrderedBalanceChange(uint256 txId, string walletId, Script scriptPubKey, uint256 blockId, BlockHeader blockHeader, int height)
     : this()
 {
     Init(txId, new BalanceId(walletId), blockId, blockHeader, height);
     _ScriptPubKey = scriptPubKey;
 }
        /// <summary>
        /// Sets the tip of this chain based upon another block header.
        /// </summary>
        /// <param name="header">The block header to set to tip.</param>
        /// <returns>Whether the tip was set successfully.</returns>
        public static bool SetTip(this ChainIndexer chainIndexer, BlockHeader header)
        {
            ChainedHeader chainedHeader;

            return(chainIndexer.TrySetTip(header, out chainedHeader));
        }
Beispiel #43
0
        public async Task Can_process_mined_blocks()
        {
            int timeMultiplier = 1; // for debugging

            TimeSpan miningDelay = TimeSpan.FromMilliseconds(50 * timeMultiplier);

            /* logging & instrumentation */
//            OneLoggerLogManager logger = new OneLoggerLogManager(new SimpleConsoleLogger(true));
            ILogManager logManager = NullLogManager.Instance;
            ILogger     logger     = logManager.GetClassLogger();

            /* spec */
            FakeSealer sealer = new FakeSealer(miningDelay);

            RopstenSpecProvider specProvider = RopstenSpecProvider.Instance;

            /* store & validation */

            EthereumEcdsa ethereumEcdsa = new EthereumEcdsa(specProvider, logManager);
            MemDb         receiptsDb    = new MemDb();
            MemDb         traceDb       = new MemDb();
            TxPool        txPool        = new TxPool(new NullTransactionStorage(),
                                                     new PendingTransactionThresholdValidator(), new Timestamp(), ethereumEcdsa, specProvider, logManager);
            IReceiptStorage      receiptStorage       = new PersistentReceiptStorage(receiptsDb, specProvider);
            BlockTree            blockTree            = new BlockTree(new MemDb(), new MemDb(), new MemDb(), specProvider, txPool, logManager);
            Timestamp            timestamp            = new Timestamp();
            DifficultyCalculator difficultyCalculator = new DifficultyCalculator(specProvider);
            HeaderValidator      headerValidator      = new HeaderValidator(blockTree, sealer, specProvider, logManager);
            OmmersValidator      ommersValidator      = new OmmersValidator(blockTree, headerValidator, logManager);
            TxValidator          txValidator          = new TxValidator(ChainId.Ropsten);
            BlockValidator       blockValidator       = new BlockValidator(txValidator, headerValidator, ommersValidator, specProvider, logManager);

            /* state & storage */
            StateDb         codeDb          = new StateDb();
            StateDb         stateDb         = new StateDb();
            StateProvider   stateProvider   = new StateProvider(stateDb, codeDb, logManager);
            StorageProvider storageProvider = new StorageProvider(stateDb, stateProvider, logManager);

            TestTransactionsGenerator generator = new TestTransactionsGenerator(txPool, ethereumEcdsa, TimeSpan.FromMilliseconds(5 * timeMultiplier), NullLogManager.Instance);

            generator.Start();

            /* blockchain processing */
            BlockhashProvider    blockhashProvider = new BlockhashProvider(blockTree);
            VirtualMachine       virtualMachine    = new VirtualMachine(stateProvider, storageProvider, blockhashProvider, logManager);
            TransactionProcessor processor         = new TransactionProcessor(specProvider, stateProvider, storageProvider, virtualMachine, logManager);
            RewardCalculator     rewardCalculator  = new RewardCalculator(specProvider);
            BlockProcessor       blockProcessor    = new BlockProcessor(specProvider, blockValidator, rewardCalculator,
                                                                        processor, stateDb, codeDb, traceDb, stateProvider, storageProvider, txPool, receiptStorage, new SyncConfig(), logManager);
            BlockchainProcessor blockchainProcessor = new BlockchainProcessor(blockTree, blockProcessor, new TxSignaturesRecoveryStep(ethereumEcdsa, NullTxPool.Instance), logManager, false, false);

            /* load ChainSpec and init */
            ChainSpecLoader loader = new ChainSpecLoader(new EthereumJsonSerializer());
            string          path   = "chainspec.json";

            logManager.GetClassLogger().Info($"Loading ChainSpec from {path}");
            ChainSpec chainSpec = loader.Load(File.ReadAllBytes(path));

            foreach (var allocation in chainSpec.Allocations)
            {
                stateProvider.CreateAccount(allocation.Key, allocation.Value);
            }

            stateProvider.Commit(specProvider.GenesisSpec);
            chainSpec.Genesis.Header.StateRoot = stateProvider.StateRoot; // TODO: shall it be HeaderSpec and not BlockHeader?
            chainSpec.Genesis.Header.Hash      = BlockHeader.CalculateHash(chainSpec.Genesis.Header);
            if (chainSpec.Genesis.Hash != new Keccak("0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d"))
            {
                throw new Exception("Unexpected genesis hash");
            }

            /* start processing */
            blockTree.SuggestBlock(chainSpec.Genesis);
            blockchainProcessor.Start();

            MinedBlockProducer minedBlockProducer = new MinedBlockProducer(difficultyCalculator, txPool, blockchainProcessor, sealer, blockTree, timestamp, NullLogManager.Instance);

            minedBlockProducer.Start();

            ManualResetEventSlim manualResetEvent = new ManualResetEventSlim(false);

            blockTree.NewHeadBlock += (sender, args) =>
            {
                if (args.Block.Number == 6)
                {
                    manualResetEvent.Set();
                }
            };

            manualResetEvent.Wait(miningDelay * 12 * timeMultiplier);
            await minedBlockProducer.StopAsync();

            int previousCount = 0;
            int totalTx       = 0;

            for (int i = 0; i < 6; i++)
            {
                Block block = blockTree.FindBlock(i);
                logger.Info($"Block {i} with {block.Transactions.Length} txs");

                ManualResetEventSlim blockProcessedEvent = new ManualResetEventSlim(false);
                blockchainProcessor.ProcessingQueueEmpty += (sender, args) => blockProcessedEvent.Set();
                blockchainProcessor.SuggestBlock(block.Hash, ProcessingOptions.ForceProcessing | ProcessingOptions.StoreReceipts | ProcessingOptions.ReadOnlyChain);
                blockProcessedEvent.Wait(1000);

                Tracer tracer = new Tracer(blockchainProcessor, receiptStorage, blockTree, new MemDb());

                int currentCount = receiptsDb.Keys.Count;
                logger.Info($"Current count of receipts {currentCount}");
                logger.Info($"Previous count of receipts {previousCount}");

                if (block.Transactions.Length > 0)
                {
                    GethLikeTxTrace trace = tracer.Trace(block.Transactions[0].Hash);
                    Assert.AreSame(GethLikeTxTrace.QuickFail, trace);
                    Assert.AreNotEqual(previousCount, currentCount, $"receipts at block {i}");
                    totalTx += block.Transactions.Length;
                }

                previousCount = currentCount;
            }

            Assert.AreNotEqual(0, totalTx, "no tx in blocks");
        }
        private async Task <List <TransactionResult> > GetTransactionResultsAsync(List <Hash> transactionIds, BlockHeader blockHeader)
        {
            var transactionResults = new List <TransactionResult>();

            foreach (var transactionId in transactionIds)
            {
                var result = await _transactionResultManager.GetTransactionResultAsync(transactionId, blockHeader.GetDisambiguatingHash());

                if (result != null)
                {
                    transactionResults.Add(result);
                }
            }

            return(transactionResults);
        }
Beispiel #45
0
        //BlockChainのテスト(分岐がある場合・採掘・後ろが無効な場合)
        public static void Test24()
        {
            string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            BlockchainAccessDB bcadb = new BlockchainAccessDB(basepath);
            string bcadbPath = bcadb.GetPath();

            if (File.Exists(bcadbPath))
                File.Delete(bcadbPath);

            BlockManagerDB bmdb = new BlockManagerDB(basepath);
            string bmdbPath = bmdb.GetPath();

            if (File.Exists(bmdbPath))
                File.Delete(bmdbPath);

            BlockDB bdb = new BlockDB(basepath);
            string bdbPath = bdb.GetPath(0);

            if (File.Exists(bdbPath))
                File.Delete(bdbPath);

            BlockFilePointersDB bfpdb = new BlockFilePointersDB(basepath);
            string bfpPath = bfpdb.GetPath();

            if (File.Exists(bfpPath))
                File.Delete(bfpPath);

            UtxoFileAccessDB ufadb = new UtxoFileAccessDB(basepath);
            string ufadbPath = ufadb.GetPath();

            if (File.Exists(ufadbPath))
                File.Delete(ufadbPath);

            UtxoFilePointersDB ufpdb = new UtxoFilePointersDB(basepath);
            string ufpdbPath = ufpdb.GetPath();

            if (File.Exists(ufpdbPath))
                File.Delete(ufpdbPath);

            UtxoFilePointersTempDB ufptempdb = new UtxoFilePointersTempDB(basepath);
            string ufptempdbPath = ufptempdb.GetPath();

            if (File.Exists(ufptempdbPath))
                File.Delete(ufptempdbPath);

            UtxoDB utxodb = new UtxoDB(basepath);
            string utxodbPath = utxodb.GetPath();

            if (File.Exists(utxodbPath))
                File.Delete(utxodbPath);

            BlockChain blockchain = new BlockChain(bcadb, bmdb, bdb, bfpdb, ufadb, ufpdb, ufptempdb, utxodb, 100, 300, 1000, 1000);

            BlockGenerator bg = new BlockGenerator();

            Block[] blks = new Block[10];
            BlockContext[] blkCons = new BlockContext[blks.Length];
            for (int i = 0; i < blks.Length; i++)
            {
                blkCons[i] = bg.CreateNextValidBlock();
                blks[i] = blkCons[i].block;

                Console.WriteLine("block" + i.ToString() + " created.");
            }

            Block[] blks2 = new Block[blks.Length];
            double cumulativeDiff1 = 0.0;
            byte[] nonce = null;

            Func<long, TransactionalBlock> _indexToBlock = (index) => blks2[index] as TransactionalBlock;

            for (int i = 0; i < blks.Length; i++)
            {
                if (i == 0)
                {
                    blks2[i] = blks[i];
                    cumulativeDiff1 += blks2[i].Difficulty.Diff;

                    Console.WriteLine("block" + i.ToString() + "_1 " + blks2[i].Difficulty.Diff.ToString() + " " + cumulativeDiff1.ToString());

                    continue;
                }

                TransactionalBlock tblk = blks[i] as TransactionalBlock;

                TransactionalBlock tblk2 = TransactionalBlock.GetBlockTemplate(tblk.Index, tblk.coinbaseTxToMiner, tblk.transferTxs, _indexToBlock, 0);

                nonce = new byte[10];

                while (true)
                {
                    tblk2.UpdateTimestamp(DateTime.Now);
                    tblk2.UpdateNonce(nonce);

                    if (tblk2.Id.CompareTo(tblk2.header.difficulty.Target) <= 0)
                    {
                        blks2[i] = tblk2;
                        cumulativeDiff1 += blks2[i].Difficulty.Diff;

                        Console.WriteLine("block" + i.ToString() + "_1 mined. " + blks2[i].Difficulty.Diff.ToString() + " " + cumulativeDiff1.ToString());

                        break;
                    }

                    int index = nonce.Length.RandomNum();
                    int value = 256.RandomNum();

                    nonce[index] = (byte)value;
                }
            }

            TransactionalBlock tblk2_1 = blks2[1] as TransactionalBlock;
            TransactionalBlock tblk2_2 = blks2[2] as TransactionalBlock;

            TransactionalBlock blk3_2 = TransactionalBlock.GetBlockTemplate(2, tblk2_2.coinbaseTxToMiner, tblk2_2.transferTxs, _indexToBlock, 0);

            while (true)
            {
                blk3_2.UpdateTimestamp(DateTime.Now);
                blk3_2.UpdateNonce(nonce);

                if (blk3_2.Id.CompareTo(blk3_2.header.difficulty.Target) <= 0)
                {
                    Console.WriteLine("block3_2 mined. " + blk3_2.Difficulty.Diff.ToString());

                    break;
                }

                int index = nonce.Length.RandomNum();
                int value = 256.RandomNum();

                nonce[index] = (byte)value;
            }

            BlockHeader bh3 = new BlockHeader();
            bh3.LoadVersion0(3, blk3_2.Id, DateTime.Now, blks2[1].Difficulty, new byte[10]);
            NormalBlock blk3_3 = new NormalBlock();
            blk3_3.LoadVersion0(bh3, tblk2_1.coinbaseTxToMiner, tblk2_1.transferTxs);
            blk3_3.UpdateMerkleRootHash();

            int forkLength = (int)Math.Floor(cumulativeDiff1 / blks2[1].Difficulty.Diff + 10);

            TransactionalBlock[] blks3 = new TransactionalBlock[forkLength];

            blks3[0] = blk3_3;

            for (int i = 1; i < blks3.Length; i++)
            {
                BlockHeader bh = new BlockHeader();
                bh.LoadVersion0(i + 3, blks3[i - 1].Id, DateTime.Now, blks2[1].Difficulty, new byte[10]);
                NormalBlock blk3 = new NormalBlock();
                blk3.LoadVersion0(bh, tblk2_1.coinbaseTxToMiner, tblk2_1.transferTxs);
                blk3.UpdateMerkleRootHash();

                blks3[i] = blk3;
            }

            BlockHeader bh4 = new BlockHeader();
            bh4.LoadVersion0(4, blk3_3.Id, DateTime.Now, blks2[1].Difficulty, new byte[10]);
            NormalBlock blk4 = new NormalBlock();
            blk4.LoadVersion0(bh4, tblk2_1.coinbaseTxToMiner, tblk2_1.transferTxs);
            blk4.UpdateMerkleRootHash();

            BlockHeader bh10 = new BlockHeader();
            bh10.LoadVersion0(10, blks2[9].Id, DateTime.Now, blks2[1].Difficulty, new byte[10]);
            NormalBlock blk5_10 = new NormalBlock();
            blk5_10.LoadVersion0(bh10, tblk2_1.coinbaseTxToMiner, tblk2_1.transferTxs);
            blk5_10.UpdateMerkleRootHash();

            TransactionalBlock[] blks5 = new TransactionalBlock[5];

            blks5[0] = blk5_10;

            for (int i = 1; i < blks5.Length; i++)
            {
                BlockHeader bh = new BlockHeader();
                bh.LoadVersion0(i + 10, blks5[i - 1].Id, DateTime.Now, blks2[1].Difficulty, new byte[10]);
                NormalBlock blk5 = new NormalBlock();
                blk5.LoadVersion0(bh, tblk2_1.coinbaseTxToMiner, tblk2_1.transferTxs);
                blk5.UpdateMerkleRootHash();

                blks5[i] = blk5;
            }

            BlockChain.UpdateChainReturnType type5 = blockchain.UpdateChain(blks2[0]);

            if (type5 != BlockChain.UpdateChainReturnType.updated)
                throw new Exception("test24_5");

            BlockChain.UpdateChainReturnType type = blockchain.UpdateChain(blk4);

            if (type != BlockChain.UpdateChainReturnType.pending)
                throw new Exception("test24_1");

            for (int i = 2; i < blks2.Length; i++)
            {
                BlockChain.UpdateChainReturnType type2 = blockchain.UpdateChain(blks2[i]);

                if (type2 != BlockChain.UpdateChainReturnType.pending)
                    throw new Exception("test24_2");
            }

            for (int i = 0; i < blks5.Length; i++)
            {
                BlockChain.UpdateChainReturnType type2 = blockchain.UpdateChain(blks5[i]);

                if (type2 != BlockChain.UpdateChainReturnType.pending)
                    throw new Exception("test24_3");
            }

            BlockChain.UpdateChainReturnType type3 = blockchain.UpdateChain(blk3_2);

            if (type3 != BlockChain.UpdateChainReturnType.pending)
                throw new Exception("test24_1");

            for (int i = 0; i < blks3.Length; i++)
            {
                BlockChain.UpdateChainReturnType type2 = blockchain.UpdateChain(blks3[i]);

                if (type2 != BlockChain.UpdateChainReturnType.pending)
                    throw new Exception("test24_4");
            }

            BlockChain.UpdateChainReturnType type4 = blockchain.UpdateChain(blks2[1]);

            if (type4 != BlockChain.UpdateChainReturnType.updatedAndRejected)
                throw new Exception("test24_6");
            if (blockchain.blocksCurrent.value != 10)
                throw new Exception("test19_2");

            Console.WriteLine("test24_succeeded");
        }
Beispiel #46
0
 public async Task AddTransactionResultsAsync(IList <TransactionResult> transactionResults,
                                              BlockHeader blockHeader)
 {
     await _transactionResultManager.AddTransactionResultsAsync(transactionResults,
                                                                blockHeader.GetDisambiguatingHash());
 }
Beispiel #47
0
        public BlockContext CreateNextValidBlock()
        {
            currentBIndex++;

            if (currentBIndex == 0)
            {
                Block blk = new GenesisBlock();

                blks.Add(blk);

                Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> unspentTxOutsDictClone2 = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>();
                Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> spentTxOutsDictClone2 = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>();

                for (int i = 0; i < keyPairs.Length; i++)
                {
                    unspentTxOutsDictClone2.Add(addresses[i], new List<TransactionOutputContext>());
                    foreach (var toc in unspentTxOutsDict[addresses[i]])
                        unspentTxOutsDictClone2[addresses[i]].Add(toc);
                    spentTxOutsDictClone2.Add(addresses[i], new List<TransactionOutputContext>());
                    foreach (var toc in spentTxOutsDict[addresses[i]])
                        spentTxOutsDictClone2[addresses[i]].Add(toc);
                }

                return new BlockContext(blk, new TransactionOutput[][] { }, 0, unspentTxOutsDictClone2, spentTxOutsDictClone2);
            }

            int numOfSpendTxs = maxNumOfSpendTxs.RandomNum() + 1;
            int[] numOfSpendTxOutss = new int[numOfSpendTxs];
            for (int i = 0; i < numOfSpendTxOutss.Length; i++)
                numOfSpendTxOutss[i] = maxNumOfSpendTxOuts.RandomNum() + 1;

            TransactionOutputContext[][] spendTxOutss = new TransactionOutputContext[numOfSpendTxs][];
            for (int i = 0; i < spendTxOutss.Length; i++)
            {
                if (unspentTxOuts.Count == 0)
                    break;

                spendTxOutss[i] = new TransactionOutputContext[numOfSpendTxOutss[i]];

                for (int j = 0; j < spendTxOutss[i].Length; j++)
                {
                    int index = unspentTxOuts.Count.RandomNum();

                    spendTxOutss[i][j] = unspentTxOuts[index];

                    spentTxOutsDict[unspentTxOuts[index].address].Add(unspentTxOuts[index]);
                    unspentTxOutsDict[unspentTxOuts[index].address].Remove(unspentTxOuts[index]);

                    spentTxOuts.Add(unspentTxOuts[index]);
                    unspentTxOuts.RemoveAt(index);

                    if (unspentTxOuts.Count == 0)
                        break;
                }
            }

            long fee = 0;
            List<TransferTransaction> transferTxs = new List<TransferTransaction>();
            List<TransactionOutput[]> prevTxOutsList = new List<TransactionOutput[]>();
            for (int i = 0; i < spendTxOutss.Length; i++)
            {
                if (spendTxOutss[i] == null)
                    break;

                long sumRawAmount = 0;

                List<TransactionInput> txInputsList = new List<TransactionInput>();
                for (int j = 0; j < spendTxOutss[i].Length; j++)
                {
                    if (spendTxOutss[i][j] == null)
                        break;

                    txInputsList.Add(spendTxOutss[i][j].GenerateTransactionInput());

                    sumRawAmount += spendTxOutss[i][j].amount.rawAmount;
                }

                TransactionInput[] txIns = txInputsList.ToArray();

                int num = sumRawAmount > 1000000 ? (int)Math.Ceiling(((avgIORatio - 1) * 2) * 1.RandomDouble() * txIns.Length) : 1;

                TransactionOutputContext[] txOutsCon = new TransactionOutputContext[num];
                TransactionOutput[] txOuts = new TransactionOutput[num];
                for (int j = 0; j < txOutsCon.Length; j++)
                {
                    long outAmount = 0;
                    if (sumRawAmount > 1000000)
                    {
                        long sumRawAmountDivided = sumRawAmount / 1000000;

                        int subtract = ((int)sumRawAmountDivided / 2).RandomNum() + 1;

                        outAmount = (long)subtract * 1000000;
                    }
                    else
                        outAmount = sumRawAmount;

                    sumRawAmount -= outAmount;

                    int index = numOfKeyPairs.RandomNum();

                    txOutsCon[j] = new TransactionOutputContext(currentBIndex, i + 1, j, new CurrencyUnit(outAmount), addresses[index], keyPairs[index]);
                    txOuts[j] = txOutsCon[j].GenerateTrasactionOutput();
                }

                fee += sumRawAmount;

                for (int j = 0; j < txOutsCon.Length; j++)
                {
                    unspentTxOutsDict[txOutsCon[j].address].Add(txOutsCon[j]);

                    unspentTxOuts.Add(txOutsCon[j]);
                }

                TransactionOutput[] prevTxOuts = new TransactionOutput[txIns.Length];
                Ecdsa256PrivKey[] privKeys = new Ecdsa256PrivKey[txIns.Length];
                for (int j = 0; j < prevTxOuts.Length; j++)
                {
                    prevTxOuts[j] = spendTxOutss[i][j].GenerateTrasactionOutput();
                    privKeys[j] = spendTxOutss[i][j].keyPair.privKey;
                }

                TransferTransaction tTx = new TransferTransaction();
                tTx.LoadVersion0(txIns, txOuts);
                tTx.Sign(prevTxOuts, privKeys);

                transferTxs.Add(tTx);
                prevTxOutsList.Add(prevTxOuts);
            }

            long rewardAndFee = TransactionalBlock.GetRewardToMiner(currentBIndex, 0).rawAmount + fee;

            TransactionOutputContext[] coinbaseTxOutsCon = new TransactionOutputContext[numOfCoinbaseTxOuts];
            TransactionOutput[] coinbaseTxOuts = new TransactionOutput[numOfCoinbaseTxOuts];
            for (int i = 0; i < coinbaseTxOutsCon.Length; i++)
            {
                long outAmount2 = 0;
                if (i != coinbaseTxOutsCon.Length - 1)
                {
                    long rewardAndFeeDevided = rewardAndFee / 1000000;

                    int subtract2 = ((int)rewardAndFeeDevided / 2).RandomNum() + 1;

                    outAmount2 = (long)subtract2 * 1000000;

                    rewardAndFee -= outAmount2;
                }
                else
                    outAmount2 = rewardAndFee;

                int index = numOfKeyPairs.RandomNum();

                coinbaseTxOutsCon[i] = new TransactionOutputContext(currentBIndex, 0, i, new CurrencyUnit(outAmount2), addresses[index], keyPairs[index]);
                coinbaseTxOuts[i] = coinbaseTxOutsCon[i].GenerateTrasactionOutput();
            }

            CoinbaseTransaction coinbaseTx = new CoinbaseTransaction();
            coinbaseTx.LoadVersion0(coinbaseTxOuts);

            for (int i = 0; i < coinbaseTxOutsCon.Length; i++)
            {
                unspentTxOutsDict[coinbaseTxOutsCon[i].address].Add(coinbaseTxOutsCon[i]);

                unspentTxOuts.Add(coinbaseTxOutsCon[i]);
            }

            prevTxOutsList.Insert(0, new TransactionOutput[] { });

            Difficulty<Creahash> diff = new Difficulty<Creahash>(HASHBASE.FromHash<Creahash>(new byte[] { 0, 127, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }));
            byte[] nonce = new byte[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            BlockHeader bh = new BlockHeader();
            bh.LoadVersion0(currentBIndex, blks[blks.Count - 1].Id, DateTime.Now, diff, nonce);

            NormalBlock nblk = new NormalBlock();
            nblk.LoadVersion0(bh, coinbaseTx, transferTxs.ToArray());
            nblk.UpdateMerkleRootHash();

            blks.Add(nblk);

            Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> unspentTxOutsDictClone = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>();
            Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>> spentTxOutsDictClone = new Dictionary<Sha256Ripemd160Hash, List<TransactionOutputContext>>();

            for (int i = 0; i < keyPairs.Length; i++)
            {
                unspentTxOutsDictClone.Add(addresses[i], new List<TransactionOutputContext>());
                foreach (var toc in unspentTxOutsDict[addresses[i]])
                    unspentTxOutsDictClone[addresses[i]].Add(toc);
                spentTxOutsDictClone.Add(addresses[i], new List<TransactionOutputContext>());
                foreach (var toc in spentTxOutsDict[addresses[i]])
                    spentTxOutsDictClone[addresses[i]].Add(toc);
            }

            BlockContext blkCon = new BlockContext(nblk, prevTxOutsList.ToArray(), fee, unspentTxOutsDictClone, spentTxOutsDictClone);

            return blkCon;
        }
Beispiel #48
0
 /// <summary>
 /// Reads a block from the underlying stream and compresses it
 /// </summary>
 /// <returns>
 /// True if data was read and compressed
 /// False if the end of the underlying stream was reached
 /// </returns>
 private Boolean ReadAndCompress()
 {
     this.streamOffset = this.streamLength = 0;
      // read the uncompressed block into the read buffer
      var decoded = ReadBlock(this.readBuffer, this.readBuffer.Length);
      if (decoded > 0)
      {
     // compress the block into the stream buffer,
     // leaving room for the header
     var encoded = Encode(
        this.readBuffer,
        0,
        decoded,
        this.streamBuffer,
        BlockHeader.Size
     );
     // copy the length header into the stream buffer
     var header = new BlockHeader()
     {
        EncodedLength = encoded,
        DecodedLength = decoded
     };
     this.streamLength += header.Encode(this.streamBuffer);
     this.streamLength += encoded;
     return true;
      }
      return false;
 }