Example #1
0
		public static async Task<MnemonicReference> ParseAsync
			(ChainBase chain,
			IBlockRepository blockRepository,
			Wordlist wordList,
			string sentence)
		{
			var w = wordList.GetWords(sentence).Length;
			var finalAddress = wordList.ToBits(sentence);
			var rawAddress = DecryptFinalAddress(finalAddress);

			int blockHeight;
			int x = DecodeBlockHeight(rawAddress, out blockHeight);

			var header = chain.GetBlock(blockHeight);
			if(header == null)
				throw new InvalidBrainAddressException("This block does not exists");
			var block = await blockRepository.GetBlockAsync(header.HashBlock).ConfigureAwait(false);
			if(block == null || block.GetHash() != header.HashBlock)
				throw new InvalidBrainAddressException("This block does not exists");

			int y1 = BitCount((int)block.Transactions.Count);
			int y2 = 11 * w - 1 - x - c;
			int y = Math.Min(y1, y2);
			int txIndex = Decode(Substring(rawAddress, x, y));
			if(txIndex >= block.Transactions.Count)
				throw new InvalidBrainAddressException("The Transaction Index is out of the bound of the block");

			var transaction = block.Transactions[(int)txIndex];
			return Parse(chain, wordList, sentence, transaction, block);
		}
Example #2
0
        public bool ValidCactusPosition(BlockDescriptor descriptor, IBlockRepository repository, IWorld world, bool checkNeighbor = true, bool checkSupport = true)
        {
            if (checkNeighbor)
            {
                var adjacent = new Coordinates3D[]
                {
                    descriptor.Coordinates + Coordinates3D.North,
                    descriptor.Coordinates + Coordinates3D.East,
                    descriptor.Coordinates + Coordinates3D.South,
                    descriptor.Coordinates + Coordinates3D.West,
                };

                foreach (var coords in adjacent)
                    if (world.GetBlockID(coords) != AirBlock.BlockID)
                        return false;
            }

            if (checkSupport)
            {
                var supportingBlock = repository.GetBlockProvider(world.GetBlockID(descriptor.Coordinates + Coordinates3D.Down));
                if ((supportingBlock.ID != CactusBlock.BlockID) && (supportingBlock.ID != SandBlock.BlockID))
                    return false;
            }

            return true;
        }
Example #3
0
 public bool ValidBedPosition(BlockDescriptor descriptor, IBlockRepository repository, IWorld world, bool checkNeighbor = true, bool checkSupport = false)
 {
     if (checkNeighbor)
     {
         var other = Coordinates3D.Zero;
         switch ((BedDirection)(descriptor.Metadata & 0x3))
         {
             case BedDirection.East:
                 other = Coordinates3D.East;
                 break;
             case BedDirection.West:
                 other = Coordinates3D.West;
                 break;
             case BedDirection.North:
                 other = Coordinates3D.North;
                 break;
             case BedDirection.South:
                 other = Coordinates3D.South;
                 break;
         }
         if ((descriptor.Metadata & (byte)BedType.Head) == (byte)BedType.Head)
             other = -other;
         if (world.GetBlockID(descriptor.Coordinates + other) != BedBlock.BlockID)
             return false;
     }
     if (checkSupport)
     {
         var supportingBlock = repository.GetBlockProvider(world.GetBlockID(descriptor.Coordinates + Coordinates3D.Down));
         if (!supportingBlock.Opaque)
             return false;
     }
     return true;
 }
Example #4
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="chain"></param>
		/// <param name="blockRepository"></param>
		/// <param name="blockHeight"></param>
		/// <param name="txIndex"></param>
		/// <param name="txOutIndex"></param>
		/// <exception cref="NBitcoin.InvalidBrainAddressException"></exception>
		/// <returns></returns>
		public static async Task<MnemonicReference> CreateAsync
			(ChainBase chain,
			IBlockRepository blockRepository,
			int blockHeight, int txIndex, int txOutIndex)
		{
			var header = chain.GetBlock(blockHeight);
			if(header == null)
				throw new InvalidBrainAddressException("This block does not exists");
			var block = await blockRepository.GetBlockAsync(header.HashBlock).ConfigureAwait(false);
			if(block == null || block.GetHash() != header.HashBlock)
				throw new InvalidBrainAddressException("This block does not exists");
			return Create(chain, block, blockHeight, txIndex, txOutIndex);
		}
Example #5
0
 public WorldLighting(IWorld world, IBlockRepository blockRepository)
 {
     BlockRepository = blockRepository;
     World = world;
     PendingOperations = new List<LightingOperation>();
     HeightMaps = new Dictionary<Coordinates2D, byte[,]>();
     world.ChunkGenerated += (sender, e) => GenerateHeightMap(e.Chunk);
     world.ChunkLoaded += (sender, e) => GenerateHeightMap(e.Chunk);
     world.BlockChanged += (sender, e) =>
     {
         if (e.NewBlock.ID != e.OldBlock.ID)
             UpdateHeightMap(e.Position);
     };
     foreach (var chunk in world)
         GenerateHeightMap(chunk);
 }
        public PPLNSPaymentScheme(IConnectionFactory cf,
                                  IShareRepository shareRepo,
                                  IBlockRepository blockRepo,
                                  IBalanceRepository balanceRepo)
        {
            Assertion.RequiresNonNull(cf, nameof(cf));
            Assertion.RequiresNonNull(shareRepo, nameof(shareRepo));
            Assertion.RequiresNonNull(blockRepo, nameof(blockRepo));
            Assertion.RequiresNonNull(balanceRepo, nameof(balanceRepo));

            this.cf          = cf;
            this.shareRepo   = shareRepo;
            this.blockRepo   = blockRepo;
            this.balanceRepo = balanceRepo;

            BuildFaultHandlingPolicy();
        }
        public MoneroPayoutHandler(
            IComponentContext ctx,
            IConnectionFactory cf,
            IMapper mapper,
            IShareRepository shareRepo,
            IBlockRepository blockRepo,
            IBalanceRepository balanceRepo,
            IPaymentRepository paymentRepo,
            NotificationService notificationService) :
            base(cf, mapper, shareRepo, blockRepo, balanceRepo, paymentRepo, notificationService)
        {
            Contract.RequiresNonNull(ctx, nameof(ctx));
            Contract.RequiresNonNull(balanceRepo, nameof(balanceRepo));
            Contract.RequiresNonNull(paymentRepo, nameof(paymentRepo));

            this.ctx = ctx;
        }
Example #8
0
 public PruneBlockStoreService(
     IAsyncLoopFactory asyncLoopFactory,
     IBlockRepository blockRepository,
     IPrunedBlockRepository prunedBlockRepository,
     IChainState chainState,
     ILoggerFactory loggerFactory,
     INodeLifetime nodeLifetime,
     StoreSettings storeSettings)
 {
     this.asyncLoopFactory      = asyncLoopFactory;
     this.blockRepository       = blockRepository;
     this.prunedBlockRepository = prunedBlockRepository;
     this.chainState            = chainState;
     this.logger        = loggerFactory.CreateLogger(this.GetType().FullName);
     this.nodeLifetime  = nodeLifetime;
     this.storeSettings = storeSettings;
 }
Example #9
0
        public ApiServer(
            IMapper mapper,
            IConnectionFactory cf,
            IBlockRepository blocksRepo,
            IPaymentRepository paymentsRepo,
            IStatsRepository statsRepo,
            IMasterClock clock,
            IMessageBus messageBus)
        {
            Contract.RequiresNonNull(cf, nameof(cf));
            Contract.RequiresNonNull(statsRepo, nameof(statsRepo));
            Contract.RequiresNonNull(blocksRepo, nameof(blocksRepo));
            Contract.RequiresNonNull(paymentsRepo, nameof(paymentsRepo));
            Contract.RequiresNonNull(mapper, nameof(mapper));
            Contract.RequiresNonNull(clock, nameof(clock));
            Contract.RequiresNonNull(messageBus, nameof(messageBus));

            this.cf           = cf;
            this.statsRepo    = statsRepo;
            this.blocksRepo   = blocksRepo;
            this.paymentsRepo = paymentsRepo;
            this.mapper       = mapper;
            this.clock        = clock;

            messageBus.Listen <BlockNotification>().Subscribe(OnBlockNotification);

            requestMap = new Dictionary <Regex, Func <HttpContext, Match, Task> >
            {
                { new Regex("^/api/pools$", RegexOptions.Compiled), GetPoolInfosAsync },
                { new Regex("^/api/pools/(?<poolId>[^/]+)/performance$", RegexOptions.Compiled), GetPoolPerformanceAsync },
                { new Regex("^/api/pools/(?<poolId>[^/]+)/miners$", RegexOptions.Compiled), PagePoolMinersAsync },
                { new Regex("^/api/pools/(?<poolId>[^/]+)/blocks$", RegexOptions.Compiled), PagePoolBlocksPagedAsync },
                { new Regex("^/api/pools/(?<poolId>[^/]+)/payments$", RegexOptions.Compiled), PagePoolPaymentsAsync },
                { new Regex("^/api/pools/(?<poolId>[^/]+)$", RegexOptions.Compiled), GetPoolInfoAsync },
                { new Regex("^/api/pools/(?<poolId>[^/]+)/miners/(?<address>[^/]+)/payments$", RegexOptions.Compiled), PageMinerPaymentsAsync },
                { new Regex("^/api/pools/(?<poolId>[^/]+)/miners/(?<address>[^/]+)/balancechanges$", RegexOptions.Compiled), PageMinerBalanceChangesAsync },
                { new Regex("^/api/pools/(?<poolId>[^/]+)/miners/(?<address>[^/]+)/performance$", RegexOptions.Compiled), GetMinerPerformanceAsync },
                { new Regex("^/api/pools/(?<poolId>[^/]+)/miners/(?<address>[^/]+)$", RegexOptions.Compiled), GetMinerInfoAsync },
            };

            requestMapAdmin = new Dictionary <Regex, Func <HttpContext, Match, Task> >
            {
                { new Regex("^/api/admin/forcegc$", RegexOptions.Compiled), HandleForceGcAsync },
                { new Regex("^/api/admin/stats/gc$", RegexOptions.Compiled), HandleGcStatsAsync },
            };
        }
Example #10
0
        public void ExistAsyncWithExistingBlockReturnsTrue()
        {
            string dir   = CreateTestDir(this);
            Block  block = this.Network.Consensus.ConsensusFactory.CreateBlock();

            using (var engine = new DBreezeEngine(dir))
            {
                DBreeze.Transactions.Transaction transaction = engine.GetTransaction();
                transaction.Insert <byte[], byte[]>("Block", block.GetHash().ToBytes(), block.ToBytes());
                transaction.Commit();
            }

            using (IBlockRepository repository = this.SetupRepository(this.Network, dir))
            {
                Assert.True(repository.Exist(block.GetHash()));
            }
        }
Example #11
0
 public InitalJobAssigner(
     IBlockIndexingJobFactory blockIndexingFactory,
     IBlockRepository blockRepository,
     IErc20BalanceIndexingJobFactory erc20BalanceIndexingJobFactory,
     IErc20ContractIndexingJobFactory erc20ContractIndexingJobFactory,
     IIndexerInstanceSettings indexerInstanceSettings,
     ILog logger,
     IRpcBlockReader rpcBlockReader)
 {
     _blockIndexingFactory            = blockIndexingFactory;
     _blockRepository                 = blockRepository;
     _erc20BalanceIndexingJobFactory  = erc20BalanceIndexingJobFactory;
     _erc20ContractIndexingJobFactory = erc20ContractIndexingJobFactory;
     _indexerInstanceSettings         = indexerInstanceSettings;
     _logger         = logger;
     _rpcBlockReader = rpcBlockReader;
 }
Example #12
0
        // Thanks to http://gamedev.stackexchange.com/questions/47362/cast-ray-to-select-block-in-voxel-game

        public static Tuple <Coordinates3D, BlockFace> Cast(ReadOnlyWorld world,
                                                            Ray ray, IBlockRepository repository, int posmax, int negmax)
        {
            // TODO: There are more efficient ways of doing this, fwiw

            double min  = negmax * 2;
            var    pick = -Coordinates3D.One;
            var    face = BlockFace.PositiveY;

            for (int x = -posmax; x <= posmax; x++)
            {
                for (int y = -negmax; y <= posmax; y++)
                {
                    for (int z = -posmax; z <= posmax; z++)
                    {
                        var coords = (Coordinates3D)(new Vector3(x, y, z) + ray.Position).Round();
                        if (!world.IsValidPosition(coords))
                        {
                            continue;
                        }
                        var id = world.GetBlockID(coords);
                        if (id != 0)
                        {
                            var provider = repository.GetBlockProvider(id);
                            var box      = provider.InteractiveBoundingBox;
                            if (box != null)
                            {
                                BlockFace _face;
                                var       distance = ray.Intersects(box.Value.OffsetBy(coords), out _face);
                                if (distance != null && distance.Value < min)
                                {
                                    min  = distance.Value;
                                    pick = coords;
                                    face = _face;
                                }
                            }
                        }
                    }
                }
            }
            if (pick == -Coordinates3D.One)
            {
                return(null);
            }
            return(new Tuple <Coordinates3D, BlockFace>(pick, face));
        }
Example #13
0
        public static void CreateBlocks(TrueCraftGame game, IBlockRepository repository)
        {
            for (int i = 0; i < 0x100; i++)
            {
                var provider = repository.GetBlockProvider((byte)i);
                if (provider == null || provider.GetIconTexture(0) != null)
                    continue;
                int[] indicies;
                var verticies = BlockRenderer.RenderBlock(provider,
                    new BlockDescriptor { ID = provider.ID }, VisibleFaces.All, new Vector3(-0.5f),
                    0, out indicies);
                var mesh = new Mesh(game, verticies, indicies);
                BlockMeshes[provider.ID] = mesh;
            }

            PrepareEffects(game);
        }
Example #14
0
        public BitcoinPayoutHandler(
            IComponentContext ctx,
            IConnectionFactory cf,
            IMapper mapper,
            IShareRepository shareRepo,
            IBlockRepository blockRepo,
            IBalanceRepository balanceRepo,
            IPaymentRepository paymentRepo,
            IEnumerable <Meta <INotificationSender, NotificationSenderMetadataAttribute> > notificationSenders) :
            base(cf, mapper, shareRepo, blockRepo, balanceRepo, paymentRepo, notificationSenders)
        {
            Contract.RequiresNonNull(ctx, nameof(ctx));
            Contract.RequiresNonNull(balanceRepo, nameof(balanceRepo));
            Contract.RequiresNonNull(paymentRepo, nameof(paymentRepo));

            this.ctx = ctx;
        }
        public void GetTrxBlockIdAsyncWithoutTxIndexReturnsDefaultId()
        {
            string dir = CreateTestDir(this);

            using (var engine = new DBreezeEngine(dir))
            {
                DBreeze.Transactions.Transaction transaction = engine.GetTransaction();
                transaction.Insert <byte[], byte[]>("Common", new byte[0], this.DBreezeSerializer.Serialize(new HashHeightPair(uint256.Zero, 1)));
                transaction.Insert <byte[], bool>("Common", new byte[1], false);
                transaction.Commit();
            }

            using (IBlockRepository repository = this.SetupRepository(this.Network, dir))
            {
                Assert.Equal(default(uint256), repository.GetBlockIdByTransactionId(new uint256(26)));
            }
        }
Example #16
0
        public void InitializesGenesisBlockAndTxIndexOnFirstLoad()
        {
            string dir = CreateTestDir(this);

            using (IBlockRepository repository = this.SetupRepository(this.Network, dir))
            {
            }

            using (var engine = RocksDb.Open(this.dbOptions, dir))
            {
                byte[] blockRow   = engine.Get(BlockRepositoryConstants.CommonTableName, new byte[0]);
                bool   txIndexRow = BitConverter.ToBoolean(engine.Get(BlockRepositoryConstants.CommonTableName, new byte[1]));

                Assert.Equal(this.Network.GetGenesis().GetHash(), this.DBreezeSerializer.Deserialize <HashHeightPair>(blockRow).Hash);
                Assert.False(txIndexRow);
            }
        }
Example #17
0
        public static bool CheckKernel(IBlockRepository blockStore, ITransactionRepository trasnactionStore,
                                       IBlockTransactionMapStore mapStore,
                                       ChainedBlock pindexPrev, uint nBits, uint nTime, OutPoint prevout, uint pBlockTime)
        {
            uint256 hashProofOfStake = null, targetProofOfStake = null;

            var txPrev = trasnactionStore.Get(prevout.Hash);

            if (txPrev == null)
            {
                return(false);
            }

            // Read block header
            var blockHashPrev = mapStore.GetBlockHash(prevout.Hash);
            var block  = blockHashPrev == null ? null : blockStore.GetBlock(blockHashPrev);

            if (block == null)
            {
                return(false);
            }

            if (IsProtocolV3((int)nTime))
            {
                int nDepth = 0;
                if (IsConfirmedInNPrevBlocks(blockStore, txPrev, pindexPrev, StakeMinConfirmations - 1, ref nDepth))
                {
                    return(false);                    // tx.DoS(100, error("CheckProofOfStake() : tried to stake at depth %d", nDepth + 1));
                }
            }
            else
            {
                var nTimeBlockFrom = block.Header.Time;
                if (nTimeBlockFrom + StakeMinAge > nTime)
                {
                    return(false);                    // error("CheckProofOfStake() : min age violation");
                }
            }

            // todo: check this unclear logic
            //if (pBlockTime)
            //	pBlockTime = block.Header.Time;

            return(CheckStakeKernelHash(pindexPrev, nBits, block, txPrev, prevout, nTime, out hashProofOfStake, out targetProofOfStake, false));
        }
        public void ExistAsyncWithExistingBlockReturnsTrue()
        {
            string dir   = CreateTestDir(this);
            Block  block = this.Network.Consensus.ConsensusFactory.CreateBlock();

            using (var engine = new DB(new Options()
            {
                CreateIfMissing = true
            }, dir))
            {
                engine.Put(DBH.Key(BlockRepository.BlockTableName, block.GetHash().ToBytes()), block.ToBytes());
            }

            using (IBlockRepository repository = this.SetupRepository(this.Network, dir))
            {
                Assert.True(repository.Exist(block.GetHash()));
            }
        }
Example #19
0
        public void GetTrxBlockIdAsyncWithoutTxIndexReturnsDefaultId()
        {
            string dir = CreateTestDir(this);

            using (var engine = new DB(new Options()
            {
                CreateIfMissing = true
            }, dir))
            {
                engine.Put(BlockRepositoryConstants.CommonTableName, new byte[0], this.DBreezeSerializer.Serialize(new HashHeightPair(uint256.Zero, 1)));
                engine.Put(BlockRepositoryConstants.CommonTableName, new byte[1], BitConverter.GetBytes(false));
            }

            using (IBlockRepository repository = this.SetupRepository(this.Network, dir))
            {
                Assert.Equal(default(uint256), repository.GetBlockIdByTransactionId(new uint256(26)));
            }
        }
        public BlockchainNodeTests()
        {
            _receiver   = A.Fake <IReceiver>();
            _parameters = new StaticNetworkParameters()
            {
                BlockTime = TimeSpan.FromSeconds(1)
            };
            _loggerFactory              = A.Fake <ILoggerFactory>();
            _blockRepository            = A.Fake <IBlockRepository>();
            _blockVerifier              = A.Fake <IBlockVerifier>();
            _forkRebaser                = A.Fake <IForkRebaser>();
            _peerNetwork                = A.Fake <IPeerNetwork>();
            _unconfirmedTransactionPool = A.Fake <IUnconfirmedTransactionPool>();
            _difficultyCalculator       = A.Fake <IDifficultyCalculator>();

            _subject = new BlockchainNode(_blockRepository, _blockVerifier, _receiver, _loggerFactory, _forkRebaser, _parameters, _unconfirmedTransactionPool, _peerNetwork, _difficultyCalculator);
            _subject.PollTimer.Dispose();
        }
Example #21
0
    public PROPPaymentScheme(
        IConnectionFactory cf,
        IShareRepository shareRepo,
        IBlockRepository blockRepo,
        IBalanceRepository balanceRepo)
    {
        Contract.RequiresNonNull(cf);
        Contract.RequiresNonNull(shareRepo);
        Contract.RequiresNonNull(blockRepo);
        Contract.RequiresNonNull(balanceRepo);

        this.cf          = cf;
        this.shareRepo   = shareRepo;
        this.blockRepo   = blockRepo;
        this.balanceRepo = balanceRepo;

        BuildFaultHandlingPolicy();
    }
        public void GetTrxBlockIdAsyncWithoutExistingTransactionReturnsNull()
        {
            string dir = CreateTestDir(this);

            using (var engine = new DB(new Options()
            {
                CreateIfMissing = true
            }, dir))
            {
                engine.Put(DBH.Key(BlockRepository.CommonTableName, new byte[0]), this.DataStoreSerializer.Serialize(new HashHeightPair(uint256.Zero, 1)));
                engine.Put(DBH.Key(BlockRepository.CommonTableName, new byte[1]), BitConverter.GetBytes(true));
            }

            using (IBlockRepository repository = this.SetupRepository(this.Network, dir))
            {
                Assert.Null(repository.GetBlockIdByTransactionId(new uint256(26)));
            }
        }
        public void GetTrxAsyncWithoutTransactionInIndexReturnsNull()
        {
            string dir = CreateTestDir(this);

            using (var engine = new DBreezeEngine(dir))
            {
                DBreeze.Transactions.Transaction transaction = engine.GetTransaction();
                var blockId = new uint256(8920);
                transaction.Insert <byte[], byte[]>("Common", new byte[0], this.DBreezeSerializer.Serialize(new HashHeightPair(uint256.Zero, 1)));
                transaction.Insert <byte[], bool>("Common", new byte[1], true);
                transaction.Commit();
            }

            using (IBlockRepository repository = this.SetupRepository(this.Network, dir))
            {
                Assert.Null(repository.GetTransactionById(new uint256(65)));
            }
        }
        public CommerciumPayoutHandler(
            IComponentContext ctx,
            IConnectionFactory cf,
            IMapper mapper,
            IShareRepository shareRepo,
            IBlockRepository blockRepo,
            IBalanceRepository balanceRepo,
            IPaymentRepository paymentRepo,
            IMasterClock clock,
            IMessageBus messageBus) :
            base(cf, mapper, shareRepo, blockRepo, balanceRepo, paymentRepo, clock, messageBus)
        {
            Contract.RequiresNonNull(ctx, nameof(ctx));
            Contract.RequiresNonNull(balanceRepo, nameof(balanceRepo));
            Contract.RequiresNonNull(paymentRepo, nameof(paymentRepo));

            this.ctx = ctx;
        }
        public BlockStoreBehavior(ConcurrentChain chain, IBlockRepository blockRepository, IBlockStoreCache blockStoreCache, ILogger logger)
        {
            Guard.NotNull(chain, nameof(chain));
            Guard.NotNull(blockRepository, nameof(blockRepository));
            Guard.NotNull(blockStoreCache, nameof(blockStoreCache));
            Guard.NotNull(blockStoreCache, nameof(logger));

            this.chain           = chain;
            this.blockRepository = blockRepository;
            this.blockStoreCache = blockStoreCache;
            this.logger          = logger;

            this.CanRespondToGetBlocksPayload = false;
            this.CanRespondeToGetDataPayload  = true;

            this.PreferHeaders      = false;
            this.preferHeaderAndIDs = false;
        }
        public void GetTrxAsyncWithoutTransactionIndexReturnsNewTransaction()
        {
            string dir = CreateTestDir(this);

            using (var engine = new DB(new Options()
            {
                CreateIfMissing = true
            }, dir))
            {
                engine.Put(DBH.Key(BlockRepository.CommonTableName, new byte[0]), this.DataStoreSerializer.Serialize(new HashHeightPair(uint256.Zero, 1)));
                engine.Put(DBH.Key(BlockRepository.CommonTableName, new byte[1]), BitConverter.GetBytes(false));
            }

            using (IBlockRepository repository = this.SetupRepository(this.Network, dir))
            {
                Assert.Equal(default(Transaction), repository.GetTransactionById(uint256.Zero));
            }
        }
        public BitcoinPayoutHandler(
            IComponentContext ctx,
            IConnectionFactory cf,
            IMapper mapper,
            IShareRepository shareRepo,
            IBlockRepository blockRepo,
            IBalanceRepository balanceRepo,
            IPaymentRepository paymentRepo,
            IMasterClock clock,
            WebhookNotificationService notificationService) :
            base(cf, mapper, shareRepo, blockRepo, balanceRepo, paymentRepo, clock, notificationService)
        {
            Assertion.RequiresNonNull(ctx, nameof(ctx));
            Assertion.RequiresNonNull(balanceRepo, nameof(balanceRepo));
            Assertion.RequiresNonNull(paymentRepo, nameof(paymentRepo));

            this.ctx = ctx;
        }
Example #28
0
        public BlockchainNode(IBlockRepository blockRepository, IBlockVerifier blockVerifier, IReceiver receiver, ILoggerFactory loggerFactory, IForkRebaser forkRebaser, INetworkParameters parameters, IUnconfirmedTransactionPool unconfirmedTransactionPool, IPeerNetwork peerNetwork, IDifficultyCalculator difficultyCalculator)
        {
            _blockRepository            = blockRepository;
            _blockVerifier              = blockVerifier;
            _receiver                   = receiver;
            _parameters                 = parameters;
            _forkRebaser                = forkRebaser;
            _unconfirmedTransactionPool = unconfirmedTransactionPool;
            _peerNetwork                = peerNetwork;
            _difficultyCalculator       = difficultyCalculator;
            //_expectedBlockList = expectedBlockList;
            _logger = loggerFactory.CreateLogger <BlockchainNode>();

            _receiver.OnReceiveBlock       += RecieveBlock;
            _receiver.OnRecieveTransaction += RecieveTransaction;

            PollTimer = new Timer(GetMissingBlocks, null, TimeSpan.FromSeconds(5), _parameters.BlockTime);
        }
Example #29
0
        const uint ModifierInterval     = 10 * 60; // time to elapse before new modifier is computed

        public static bool CheckAndComputeStake(IBlockRepository blockStore, ITransactionRepository trasnactionStore, IBlockTransactionMapStore mapStore,
                                                ChainBase chainIndex, ChainedBlock pindex, Block block)
        {
            if (block.GetHash() != pindex.HashBlock)
            {
                throw new ArgumentException();
            }

            var pindexPrev = pindex.Previous;

            uint256 hashProof = null;

            // Verify hash target and signature of coinstake tx
            if (pindex.Header.PosParameters.IsProofOfStake())
            {
                uint256 targetProofOfStake;
                if (!CheckProofOfStake(blockStore, trasnactionStore, mapStore, pindexPrev, block.Transactions[1],
                                       pindex.Header.Bits.ToCompact(), out hashProof, out targetProofOfStake))
                {
                    return(false);                    // error("AcceptBlock() : check proof-of-stake failed for block %s", hash.ToString());
                }
            }

            // PoW is checked in CheckBlock()
            if (pindex.Header.PosParameters.IsProofOfWork())
            {
                hashProof = pindex.Header.GetPoWHash();
            }

            // todo: is this the same as chain work?
            // compute chain trust score
            //pindexNew.nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();

            // compute stake entropy bit for stake modifier
            if (!pindex.Header.PosParameters.SetStakeEntropyBit(pindex.Header.PosParameters.GetStakeEntropyBit()))
            {
                return(false);                //error("AddToBlockIndex() : SetStakeEntropyBit() failed");
            }
            // Record proof hash value
            pindex.Header.PosParameters.HashProof = hashProof;

            // compute stake modifier
            return(ComputeStakeModifier(chainIndex, pindex));
        }
        public void ReIndexAsync_TxIndex_OffToOn()
        {
            string      dir         = CreateTestDir(this);
            Block       block       = this.Network.CreateBlock();
            Transaction transaction = this.Network.CreateTransaction();

            block.Transactions.Add(transaction);

            // Set up database to mimic that created when TxIndex was off. No transactions stored.
            using (var engine = new DB(new Options()
            {
                CreateIfMissing = true
            }, dir))
            {
                engine.Put(DBH.Key(BlockRepository.BlockTableName, block.GetHash().ToBytes()), block.ToBytes());
            }

            // Turn TxIndex on and then reindex database, as would happen on node startup if -txindex and -reindex are set.
            using (IBlockRepository repository = this.SetupRepository(this.Network, dir))
            {
                repository.SetTxIndex(true);
                repository.ReIndex();
            }

            // Check that after indexing database, the transaction inside the block is now indexed.
            using (var engine = new DB(new Options()
            {
                CreateIfMissing = true
            }, dir))
            {
                Dictionary <byte[], byte[]> blockDict = engine.SelectDictionary(BlockRepository.BlockTableName);
                Dictionary <byte[], byte[]> transDict = engine.SelectDictionary(BlockRepository.TransactionTableName);

                // Block stored as expected.
                Assert.Single(blockDict);
                Assert.Equal(block.GetHash(), this.DataStoreSerializer.Deserialize <Block>(blockDict.FirstOrDefault().Value).GetHash());

                // Transaction row in database stored as expected.
                Assert.Single(transDict);
                KeyValuePair <byte[], byte[]> savedTransactionRow = transDict.FirstOrDefault();
                Assert.Equal(transaction.GetHash().ToBytes(), savedTransactionRow.Key);
                Assert.Equal(block.GetHash().ToBytes(), savedTransactionRow.Value);
            }
        }
Example #31
0
        public void ReIndexAsync_TxIndex_OffToOn()
        {
            string      dir         = CreateTestDir(this);
            Block       block       = this.Network.CreateBlock();
            Transaction transaction = this.Network.CreateTransaction();

            block.Transactions.Add(transaction);

            // Set up database to mimic that created when TxIndex was off. No transactions stored.
            using (var engine = new DBreezeEngine(dir))
            {
                DBreeze.Transactions.Transaction dbreezeTransaction = engine.GetTransaction();
                dbreezeTransaction.Insert <byte[], byte[]>("Block", block.GetHash().ToBytes(), block.ToBytes());
                dbreezeTransaction.Commit();
            }

            // Turn TxIndex on and then reindex database, as would happen on node startup if -txindex and -reindex are set.
            using (IBlockRepository repository = this.SetupRepository(this.Network, dir))
            {
                Task setIndexTask = repository.SetTxIndexAsync(true);
                setIndexTask.Wait();

                Task reindexTask = repository.ReIndexAsync();
                reindexTask.Wait();
            }

            // Check that after indexing database, the transaction inside the block is now indexed.
            using (var engine = new DBreezeEngine(dir))
            {
                DBreeze.Transactions.Transaction dbreezeTransaction = engine.GetTransaction();
                Dictionary <byte[], Block>       blockDict          = dbreezeTransaction.SelectDictionary <byte[], Block>("Block");
                Dictionary <byte[], byte[]>      transDict          = dbreezeTransaction.SelectDictionary <byte[], byte[]>("Transaction");

                // Block stored as expected.
                Assert.Single(blockDict);
                Assert.Equal(block.GetHash(), blockDict.FirstOrDefault().Value.GetHash());

                // Transaction row in database stored as expected.
                Assert.Single(transDict);
                KeyValuePair <byte[], byte[]> savedTransactionRow = transDict.FirstOrDefault();
                Assert.Equal(transaction.GetHash().ToBytes(), savedTransactionRow.Key);
                Assert.Equal(block.GetHash().ToBytes(), savedTransactionRow.Value);
            }
        }
Example #32
0
        public BlockStoreCache(
            IBlockRepository blockRepository,
            IDateTimeProvider dateTimeProvider,
            ILoggerFactory loggerFactory,
            NodeSettings nodeSettings)
        {
            Guard.NotNull(blockRepository, nameof(blockRepository));

            // Initialize 'MaxCacheBlocksCount' with default value of maximum 300 blocks or with user defined value.
            // Value of 300 is chosen because it covers most of the cases when not synced node is connected and trying to sync from us.
            this.MaxCacheBlocksCount = nodeSettings.ConfigReader.GetOrDefault("maxCacheBlocksCount", 300);

            this.cache = new MemoryCache <uint256, Block>(this.MaxCacheBlocksCount);

            this.blockRepository    = blockRepository;
            this.dateTimeProvider   = dateTimeProvider;
            this.PerformanceCounter = this.BlockStoreCachePerformanceCounterFactory();
            this.logger             = loggerFactory.CreateLogger(this.GetType().FullName);
        }
        private MaturedBlocksProvider GetMaturedBlocksProvider(IFederatedPegSettings federatedPegSettings)
        {
            IBlockRepository blockRepository = Substitute.For <IBlockRepository>();

            blockRepository.GetBlocks(Arg.Any <List <uint256> >()).ReturnsForAnyArgs((x) =>
            {
                List <uint256> hashes = x.ArgAt <List <uint256> >(0);
                var blocks            = new List <Block>();

                foreach (uint256 hash in hashes)
                {
                    blocks.Add(this.network.CreateBlock());
                }

                return(blocks);
            });

            return(new MaturedBlocksProvider(this.consensusManager, this.depositExtractor, federatedPegSettings, this.loggerFactory));
        }
Example #34
0
        public void InitializesGenBlockAndTxIndexOnFirstLoad()
        {
            string dir = CreateTestDir(this);

            using (IBlockRepository repository = this.SetupRepository(this.Network, dir))
            {
            }

            using (var engine = new DBreezeEngine(dir))
            {
                DBreeze.Transactions.Transaction transaction = engine.GetTransaction();

                Row <byte[], HashHeightPair> blockRow   = transaction.Select <byte[], HashHeightPair>("Common", new byte[0]);
                Row <byte[], bool>           txIndexRow = transaction.Select <byte[], bool>("Common", new byte[1]);

                Assert.Equal(this.Network.GetGenesis().GetHash(), blockRow.Value.Hash);
                Assert.False(txIndexRow.Value);
            }
        }
Example #35
0
        private static bool IsConfirmedInNPrevBlocks(IBlockRepository blockStore, Transaction txPrev, ChainedBlock pindexFrom, int maxDepth, ref int actualDepth)
        {
            // note: this method can be optimized by ensuring that blockstore keeps
            // in memory at least maxDepth blocks twards genesis

            var hashPrev = txPrev.GetHash();

            for (var pindex = pindexFrom; pindex != null && pindexFrom.Height - pindex.Height < maxDepth; pindex = pindex.Previous)
            {
                var block = blockStore.GetBlock(pindex.HashBlock);
                if (block.Transactions.Any(b => b.GetHash() == hashPrev))                 //pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
                {
                    actualDepth = pindexFrom.Height - pindex.Height;
                    return(true);
                }
            }

            return(false);
        }
Example #36
0
        public void GetTrxAsyncWithoutTransactionInIndexReturnsNull()
        {
            string dir = CreateTestDir(this);

            using (var engine = new DB(new Options()
            {
                CreateIfMissing = true
            }, dir))
            {
                var blockId = new uint256(8920);
                engine.Put(BlockRepositoryConstants.CommonTableName, new byte[0], this.DBreezeSerializer.Serialize(new HashHeightPair(uint256.Zero, 1)));
                engine.Put(BlockRepositoryConstants.CommonTableName, new byte[1], BitConverter.GetBytes(true));
            }

            using (IBlockRepository repository = this.SetupRepository(this.Network, dir))
            {
                Assert.Null(repository.GetTransactionById(new uint256(65)));
            }
        }
Example #37
0
        // Thanks to http://gamedev.stackexchange.com/questions/47362/cast-ray-to-select-block-in-voxel-game

        public static Tuple<Coordinates3D, BlockFace> Cast(ReadOnlyWorld world,
            Ray ray, IBlockRepository repository, int posmax, int negmax)
        {
            // TODO: There are more efficient ways of doing this, fwiw

            double min = negmax * 2;
            var pick = -Coordinates3D.One;
            var face = BlockFace.PositiveY;
            for (int x = -posmax; x <= posmax; x++)
            {
                for (int y = -negmax; y <= posmax; y++)
                {
                    for (int z = -posmax; z <= posmax; z++)
                    {
                        var coords = (Coordinates3D)(new Vector3(x, y, z) + ray.Position).Round();
                        if (!world.IsValidPosition(coords))
                            continue;
                        var id = world.GetBlockID(coords);
                        if (id != 0)
                        {
                            var provider = repository.GetBlockProvider(id);
                            var box = provider.InteractiveBoundingBox;
                            if (box != null)
                            {
                                BlockFace _face;
                                var distance = ray.Intersects(box.Value.OffsetBy(coords), out _face);
                                if (distance != null && distance.Value < min)
                                {
                                    min = distance.Value;
                                    pick = coords;
                                    face = _face;
                                }
                            }
                        }
                    }
                }
            }
            if (pick == -Coordinates3D.One)
                return null;
            return new Tuple<Coordinates3D, BlockFace>(pick, face);
        }
Example #38
0
        public TasklingClient(IConfigurationReader configurationReader,
            ITaskRepository taskRepository = null,
            ITasklingConfiguration configuration = null,
            ITaskExecutionRepository taskExecutionRepository = null,
            IExecutionTokenRepository executionTokenRepository = null,
            ICommonTokenRepository commonTokenRepository = null,
            IEventsRepository eventsRepository = null,
            ICriticalSectionRepository criticalSectionRepository = null,
            IBlockFactory blockFactory = null,
            IBlockRepository blockRepository = null,
            IRangeBlockRepository rangeBlockRepository = null,
            IListBlockRepository listBlockRepository = null,
            IObjectBlockRepository objectBlockRepository = null,
            ICleanUpService cleanUpService = null,
            ICleanUpRepository cleanUpRepository = null)
        {
            if (taskRepository == null)
                taskRepository = new TaskRepository();

            if (configuration == null)
                _configuration = new TasklingConfiguration(configurationReader);

            if (commonTokenRepository == null)
                commonTokenRepository = new CommonTokenRepository();

            if (executionTokenRepository == null)
                executionTokenRepository = new ExecutionTokenRepository(commonTokenRepository);

            if (eventsRepository == null)
                eventsRepository = new EventsRepository();

            if (taskExecutionRepository != null)
                _taskExecutionRepository = taskExecutionRepository;
            else
                _taskExecutionRepository = new TaskExecutionRepository(taskRepository, executionTokenRepository, eventsRepository);

            if (criticalSectionRepository != null)
                _criticalSectionRepository = criticalSectionRepository;
            else
                _criticalSectionRepository = new CriticalSectionRepository(taskRepository, commonTokenRepository);

            if (blockRepository == null)
                blockRepository = new BlockRepository(taskRepository);

            if (rangeBlockRepository != null)
                _rangeBlockRepository = rangeBlockRepository;
            else
                _rangeBlockRepository = new RangeBlockRepository(taskRepository);

            if (listBlockRepository != null)
                _listBlockRepository = listBlockRepository;
            else
                _listBlockRepository = new ListBlockRepository(taskRepository);

            if (objectBlockRepository != null)
                _objectBlockRepository = objectBlockRepository;
            else
                _objectBlockRepository = new ObjectBlockRepository(taskRepository);

            if (blockFactory != null)
                _blockFactory = blockFactory;
            else
                _blockFactory = new BlockFactory(blockRepository, _rangeBlockRepository, _listBlockRepository, _objectBlockRepository, _taskExecutionRepository);

            if (cleanUpRepository == null)
                cleanUpRepository = new CleanUpRepository(taskRepository);

            if (cleanUpService != null)
                _cleanUpService = cleanUpService;
            else
                _cleanUpService = new CleanUpService(_configuration, cleanUpRepository);
        }
Example #39
0
 public BlockService(IBlockRepository blockRepository)
 {
     _blockRepository = blockRepository;
 }
Example #40
0
 public BlockService( IBlockRepository BlockRepository )
 {
     _repository = BlockRepository;
 }
Example #41
0
        // Thanks to http://gamedev.stackexchange.com/questions/47362/cast-ray-to-select-block-in-voxel-game
        public static Tuple<Coordinates3D, BlockFace> Cast(ReadOnlyWorld world,
            Ray ray, IBlockRepository repository, double max)
        {
            var origin = ray.Position.Floor();
            var direction = ray.Direction;
            var step = new Vector3(SigNum(ray.Direction.X), SigNum(ray.Direction.Y), SigNum(ray.Direction.Z));
            var tMax = new Vector3(
                IntBound(origin.X, direction.X),
                IntBound(origin.Y, direction.Y),
                IntBound(origin.Z, direction.Z));
            var tDelta = new Vector3(
                step.X / direction.X,
                step.Y / direction.Y,
                step.Z / direction.Z);
            BlockFace face = BlockFace.PositiveY;

            if (ray.Direction == Vector3.Zero)
                return null;

            max /= Math.Sqrt(ray.Direction.X * ray.Direction.X
                + ray.Direction.Y * ray.Direction.Y
                + ray.Direction.Z * ray.Direction.Z);

            while (world.IsValidPosition((Coordinates3D)origin))
            {
                var provider = repository.GetBlockProvider(world.GetBlockID((Coordinates3D)origin));
                var _box = provider.BoundingBox;
                if (_box != null)
                {
                    var box = _box.Value.OffsetBy((Coordinates3D)origin);
                    if (ray.Intersects(box) != null)
                        return new Tuple<Coordinates3D, BlockFace>((Coordinates3D)origin, face);
                }

                if (tMax.X < tMax.Y)
                {
                    if (tMax.X < tMax.Z)
                    {
                        if (tMax.X > max)
                            return null;
                        // Update which cube we are now in.
                        origin.X += step.X;
                        // Adjust tMaxX to the next X-oriented boundary crossing.
                        tMax.X += tDelta.X;
                        // Record the normal vector of the cube face we entered.
                        if (step.X < 0)
                            face = BlockFace.PositiveX;
                        else
                            face = BlockFace.NegativeX;
                    }
                    else
                    {
                        if (tMax.Z > max)
                            return null;
                        origin.Z += step.Z;
                        tMax.Z += tDelta.Z;
                        if (step.Z < 0)
                            face = BlockFace.PositiveZ;
                        else
                            face = BlockFace.NegativeZ;
                    }
                }
                else
                {
                    if (tMax.Y < tMax.Z)
                    {
                        if (tMax.Y > max)
                            return null;
                        origin.Y += step.Y;
                        tMax.Y += tDelta.Y;
                        if (step.Y < 0)
                            face = BlockFace.PositiveY;
                        else
                            face = BlockFace.NegativeY;
                    }
                    else
                    {
                        // Identical to the second case, repeated for simplicity in
                        // the conditionals.
                        if (tMax.Z > max)
                            break;
                        origin.Z += step.Z;
                        tMax.Z += tDelta.Z;
                        if (step.Z < 0)
                            face = BlockFace.PositiveZ;
                        else
                            face = BlockFace.NegativeZ;
                    }
                }
            }

            return null;
        }