Example #1
0
 public NodeServices(DataFolder dataFolder, ChainIndexer chainIndexer, Network network,
                     IBroadcasterManager broadcasterManager, ILoggerFactory loggerFactory,
                     INodeLifetime nodeLifetime, ISignals signals, IBlockStore blockStore,
                     ITimeSyncBehaviorState timeSyncBehaviorState, IInitialBlockDownloadState initialBlockDownloadState,
                     IBlockProvider blockProvider, IConsensusManager consensusManager, IStakeChain stakeChain,
                     ICoinView coinView, IDateTimeProvider dateTimeProvider, IChainState chainState)
 {
     C.Network = network;
     Log.SetLogger(loggerFactory.CreateLogger(nameof(X1Wallet)));
     this.LoggerFactory             = loggerFactory;
     this.DataFolder                = dataFolder;
     this.ChainIndexer              = chainIndexer;
     this.BroadcasterManager        = broadcasterManager;
     this.NodeLifetime              = nodeLifetime;
     this.InitialBlockDownloadState = initialBlockDownloadState;
     this.Signals               = signals;
     this.BlockStore            = blockStore;
     this.TimeSyncBehaviorState = timeSyncBehaviorState;
     this.BlockProvider         = blockProvider;
     this.ConsensusManager      = consensusManager;
     this.PosCoinviewRule       = consensusManager?.ConsensusRules.GetRule <PosCoinviewRule>();
     this.StakeChain            = stakeChain;
     this.DateTimeProvider      = dateTimeProvider;
     this.CoinView              = coinView;
     this.ChainState            = chainState;
 }
Example #2
0
 public PowMining(
     IAsyncLoopFactory asyncLoopFactory,
     IBlockProvider blockProvider,
     IConsensusLoop consensusLoop,
     ConcurrentChain chain,
     IDateTimeProvider dateTimeProvider,
     ITxMempool mempool,
     MempoolSchedulerLock mempoolLock,
     Network network,
     INodeLifetime nodeLifetime,
     ILoggerFactory loggerFactory)
 {
     this.asyncLoopFactory = asyncLoopFactory;
     this.blockProvider    = blockProvider;
     this.chain            = chain;
     this.consensusLoop    = consensusLoop;
     this.dateTimeProvider = dateTimeProvider;
     this.loggerFactory    = loggerFactory;
     this.logger           = loggerFactory.CreateLogger(this.GetType().FullName);
     this.mempool          = mempool;
     this.mempoolLock      = mempoolLock;
     this.network          = network;
     this.nodeLifetime     = nodeLifetime;
     this.miningCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(new[] { this.nodeLifetime.ApplicationStopping });
 }
Example #3
0
        public PowMining(
            IAsyncProvider asyncProvider,
            IBlockProvider blockProvider,
            IConsensusManager consensusManager,
            ChainIndexer chainIndexer,
            IDateTimeProvider dateTimeProvider,
            ITxMempool mempool,
            MempoolSchedulerLock mempoolLock,
            Network network,
            INodeLifetime nodeLifetime,
            ILoggerFactory loggerFactory,
            IInitialBlockDownloadState initialBlockDownloadState,
            MinerSettings minerSettings)
        {
            this.asyncProvider             = asyncProvider;
            this.blockProvider             = blockProvider;
            this.chainIndexer              = chainIndexer;
            this.consensusManager          = consensusManager;
            this.dateTimeProvider          = dateTimeProvider;
            this.loggerFactory             = loggerFactory;
            this.initialBlockDownloadState = initialBlockDownloadState;
            this.minerSettings             = minerSettings;
            this.logger       = loggerFactory.CreateLogger(GetType().FullName);
            this.mempool      = mempool;
            this.mempoolLock  = mempoolLock;
            this.network      = network;
            this.nodeLifetime = nodeLifetime;
            this.miningCancellationTokenSource =
                CancellationTokenSource.CreateLinkedTokenSource(this.nodeLifetime.ApplicationStopping);

            if (minerSettings.UseOpenCL)
            {
                this.openCLMiner = new OpenCLMiner(minerSettings, loggerFactory);
            }
        }
Example #4
0
 public PowMining(
     IAsyncLoopFactory asyncLoopFactory,
     IBlockProvider blockProvider,
     IConsensusManager consensusManager,
     ChainIndexer chainIndexer,
     IDateTimeProvider dateTimeProvider,
     ITxMempool mempool,
     MempoolSchedulerLock mempoolLock,
     Network network,
     INodeLifetime nodeLifetime,
     ILoggerFactory loggerFactory,
     IInitialBlockDownloadState initialBlockDownloadState)
 {
     this.asyncLoopFactory          = asyncLoopFactory;
     this.blockProvider             = blockProvider;
     this.chainIndexer              = chainIndexer;
     this.consensusManager          = consensusManager;
     this.dateTimeProvider          = dateTimeProvider;
     this.loggerFactory             = loggerFactory;
     this.initialBlockDownloadState = initialBlockDownloadState;
     this.logger       = loggerFactory.CreateLogger("Impleum.Bitcoin.FullNode");
     this.mempool      = mempool;
     this.mempoolLock  = mempoolLock;
     this.network      = network;
     this.nodeLifetime = nodeLifetime;
     this.miningCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(new[] { this.nodeLifetime.ApplicationStopping });
 }
Example #5
0
 public static VertexPositionNormalColorTexture[] RenderBlock(IBlockProvider provider, BlockDescriptor descriptor,
     VisibleFaces faces, Vector3 offset, int indiciesOffset, out int[] indicies)
 {
     var textureMap = provider.GetTextureMap(descriptor.Metadata);
     if (textureMap == null)
         textureMap = new Tuple<int, int>(0, 0); // TODO: handle this better
     return Renderers[descriptor.ID].Render(descriptor, offset, faces, textureMap, indiciesOffset, out indicies);
 }
Example #6
0
 public BlockService(IBlockProvider blockProvider,
                     IBlockRepository blockRepository,
                     ITransactionService transactionService
                     )
 {
     BlockProvider       = blockProvider;
     BlockRepository     = blockRepository;
     _transactionService = transactionService;
 }
Example #7
0
        public static VertexPositionNormalColorTexture[] RenderBlock(IBlockProvider provider, BlockDescriptor descriptor,
                                                                     VisibleFaces faces, Vector3 offset, int indiciesOffset, out int[] indicies)
        {
            var textureMap = provider.GetTextureMap(descriptor.Metadata);

            if (textureMap == null)
            {
                textureMap = new Tuple <int, int>(0, 0); // TODO: handle this better
            }
            return(Renderers[descriptor.ID].Render(descriptor, offset, faces, textureMap, indiciesOffset, out indicies));
        }
Example #8
0
        public override void ItemUsedOnBlock(Coordinates3D coordinates, ItemStack item, BlockFace face, IWorld world, IRemoteClient user)
        {
            coordinates += MathHelper.BlockFaceToCoordinates(face);
            IBlockProvider supportingBlock = world.BlockRepository.GetBlockProvider(world.GetBlockID(coordinates + Coordinates3D.Down));

            if (supportingBlock.Opaque)
            {
                world.SetBlockID(coordinates, RedstoneDustBlock.BlockID);
                item.Count--;
                user.Inventory[user.SelectedSlot] = item;
            }
        }
Example #9
0
 public ChainProvider(ITransactionProvider transactionProvider,
                      IBlockProvider blockProvider,
                      IAddressProvider addressProvider,
                      IInfoAdapter infoAdapter,
                      ILoggerFactory loggerFactory)
 {
     _transactionProvider = transactionProvider;
     _blockProvider       = blockProvider;
     _addressProvider     = addressProvider;
     _infoAdapter         = infoAdapter;
     _log = loggerFactory.CreateLogger(GetType());
 }
Example #10
0
        //////////////////////////////////////////////////////////////////////////
        public GameManager(int height, int width, IBoardEventHandler eventHandler = null,
                           IBlockProvider blockProvider = null)
        {
            var gameBoard = new bool[height][];

            for (var i = 0; i < height; i++)
            {
                gameBoard[i] = new bool[width];
            }

            boardManager  = new BoardManager(gameBoard, null, new GameStats(), eventHandler);
            BlockProvider = blockProvider;
        }
 public BlockchainProvider(ITransactionProvider transactionProvider,
                           IBlockProvider blockProvider,
                           IAddressProvider addressProvider,
                           IAssetProvider assetProvider,
                           IMetadataProvider metadataProvider,
                           ILog log)
 {
     TransactionProvider = transactionProvider;
     BlockProvider       = blockProvider;
     AddressProvider     = addressProvider;
     AssetProvider       = assetProvider;
     MetadataProvider    = metadataProvider;
     Log = log;
 }
Example #12
0
 public MiningService(IBlockchainService blockchainService, IConsensusService consensusService,
                      IStatisticService statisticService, IServiceProvider serviceProvider, IBlockProvider blockProvider,
                      IMiningQueue miningQueue, IBackgroundQueue backgroundQueue, IConfigurationService configurationService,
                      ITransactionStorage transactionStorage) : base(configurationService)
 {
     _blockchainService  = blockchainService;
     _consensusService   = consensusService;
     _statisticService   = statisticService;
     _serviceProvider    = serviceProvider;
     _blockProvider      = blockProvider;
     _miningQueue        = miningQueue;
     _backgroundQueue    = backgroundQueue;
     _transactionStorage = transactionStorage;
 }
Example #13
0
        /// <summary>
        /// Creates a new <see cref="Web"/> object using a given provider and listen address.
        /// </summary>
        /// <param name="blockProvider">Provider for blocks to use.</param>
        /// <param name="url">Address that the server listens on.</param>
        public WebServer(IBlockProvider blockProvider, IAnimalProvider animalProvider, IPlantProvider plantProvider, string url, string webRoot)
        {
            if (blockProvider == null)
            {
                throw new ArgumentNullException(nameof(blockProvider));
            }
            if (animalProvider == null)
            {
                throw new ArgumentNullException(nameof(animalProvider));
            }
            if (plantProvider == null)
            {
                throw new ArgumentNullException(nameof(plantProvider));
            }

            if (Instance != null)
            {
                throw new InvalidOperationException(nameof(WebServer) + " is a singleton class and may not be instantiated multiple times.");
            }

            Instance = this;

            // Set the providers
            BlockProvider  = blockProvider;
            AnimalProvider = animalProvider;
            PlantProvider  = plantProvider;

            try
            {
                // Start the server (/Katana/OWIN pipeline)
                var options = new StartOptions();
                options.Urls.Add(url);
                _webServer = WebApp.Start(url, (app) => new Web.Startup(webRoot).Configuration(app));
            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                // Because those exceptions usually are not helpful ("an invocation target has something something"), we'll rather throw the inner exception
                if (ex.InnerException == null)
                {
                    throw;
                }

                System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
            }

            // Get the hub contexts
            _mapHubContext = GlobalHost.ConnectionManager.GetHubContext <Web.MapHub>();
        }
Example #14
0
 public static void RenderBlockIcon(TrueCraftGame game, IBlockProvider provider, byte metadata, Rectangle destination)
 {
     var mesh = BlockMeshes[provider.ID];
     if (mesh != null)
     {
         RenderEffect.World = Matrix.Identity
             * Matrix.CreateScale(0.6f)
             * Matrix.CreateRotationY(-MathHelper.PiOver4)
             * Matrix.CreateRotationX(MathHelper.ToRadians(30))
             * Matrix.CreateScale(new Vector3(destination.Width, destination.Height, 1))
             * Matrix.CreateTranslation(new Vector3(
                 destination.X, -(destination.Y - game.GraphicsDevice.Viewport.Height / 2) + game.GraphicsDevice.Viewport.Height / 2, 0))
             * Matrix.CreateTranslation(new Vector3(destination.Width / 2, -destination.Height / 2, 0));
         mesh.Draw(RenderEffect);
     }
 }
Example #15
0
        public static void RenderBlockIcon(TrueCraftGame game, IBlockProvider provider, byte metadata, Rectangle destination)
        {
            var mesh = BlockMeshes[provider.ID];

            if (mesh != null)
            {
                RenderEffect.World = Matrix.Identity
                                     * Matrix.CreateScale(0.6f)
                                     * Matrix.CreateRotationY(-MathHelper.PiOver4)
                                     * Matrix.CreateRotationX(MathHelper.ToRadians(30))
                                     * Matrix.CreateScale(new Vector3(destination.Width, destination.Height, 1))
                                     * Matrix.CreateTranslation(new Vector3(
                                                                    destination.X, -(destination.Y - game.GraphicsDevice.Viewport.Height / 2) + game.GraphicsDevice.Viewport.Height / 2, 0))
                                     * Matrix.CreateTranslation(new Vector3(destination.Width / 2, -destination.Height / 2, 0));
                mesh.Draw(RenderEffect);
            }
        }
 /// <summary>
 /// Creates a new stream on top of a block provider
 /// </summary>
 /// <param name="provider">The block provider</param>
 /// <param name="path">The path to the block store</param>
 /// <param name="fileMode">The file mode that the stream should simulate. Currently only FileMode.Open and FileMode.Append are supported</param>
 public BlockProviderStream(IBlockProvider provider, string path, FileMode fileMode = FileMode.Open)
 {
     _blockProvider = provider;
     _path = path;
     _block = new byte[provider.BlockSize];
     _blockOffset = -1;
     switch(fileMode)
     {
         case FileMode.Append:
             _Seek(0, SeekOrigin.End);
             break;
         case FileMode.Open:
             break;
         default:
             throw new NotSupportedException("BlockProviderStream does not support file mode: " + fileMode);
     }
 }
Example #17
0
        /// <summary>
        /// Creates a new stream on top of a block provider
        /// </summary>
        /// <param name="provider">The block provider</param>
        /// <param name="path">The path to the block store</param>
        /// <param name="fileMode">The file mode that the stream should simulate. Currently only FileMode.Open and FileMode.Append are supported</param>
        public BlockProviderStream(IBlockProvider provider, string path, FileMode fileMode = FileMode.Open)
        {
            _blockProvider = provider;
            _path          = path;
            _block         = new byte[provider.BlockSize];
            _blockOffset   = -1;
            switch (fileMode)
            {
            case FileMode.Append:
                _Seek(0, SeekOrigin.End);
                break;

            case FileMode.Open:
                break;

            default:
                throw new NotSupportedException("BlockProviderStream does not support file mode: " + fileMode);
            }
        }
 public StraxMinting(
     IBlockProvider blockProvider,
     IConsensusManager consensusManager,
     ChainIndexer chainIndexer,
     Network network,
     IDateTimeProvider dateTimeProvider,
     IInitialBlockDownloadState initialBlockDownloadState,
     INodeLifetime nodeLifetime,
     ICoinView coinView,
     IStakeChain stakeChain,
     IStakeValidator stakeValidator,
     MempoolSchedulerLock mempoolLock,
     ITxMempool mempool,
     IWalletManager walletManager,
     IAsyncProvider asyncProvider,
     ITimeSyncBehaviorState timeSyncBehaviorState,
     ILoggerFactory loggerFactory,
     MinerSettings minerSettings) : base(blockProvider, consensusManager, chainIndexer, network, dateTimeProvider,
                                         initialBlockDownloadState, nodeLifetime, coinView, stakeChain, stakeValidator, mempoolLock, mempool,
                                         walletManager, asyncProvider, timeSyncBehaviorState, loggerFactory, minerSettings)
 {
 }
Example #19
0
        /// <summary>
        /// Creates a new <see cref="Web"/> object using a given provider and listen address.
        /// </summary>
        /// <param name="blockProvider">Provider for blocks to use.</param>
        /// <param name="url">Address that the server listens on.</param>
        public WebServer(IBlockProvider blockProvider, IAnimalProvider animalProvider, IPlantProvider plantProvider, string url, string webRoot)
        {
            if (blockProvider == null)
                throw new ArgumentNullException(nameof(blockProvider));
            if (animalProvider == null)
                throw new ArgumentNullException(nameof(animalProvider));
            if (plantProvider == null)
                throw new ArgumentNullException(nameof(plantProvider));

            if (Instance != null)
                throw new InvalidOperationException(nameof(WebServer) + " is a singleton class and may not be instantiated multiple times.");

            Instance = this;

            // Set the providers
            BlockProvider = blockProvider;
            AnimalProvider = animalProvider;
            PlantProvider = plantProvider;

            try
            {
                // Start the server (/Katana/OWIN pipeline)
                var options = new StartOptions();
                options.Urls.Add(url);
                _webServer = WebApp.Start(url, (app) => new Web.Startup(webRoot).Configuration(app));
            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                // Because those exceptions usually are not helpful ("an invocation target has something something"), we'll rather throw the inner exception
                if (ex.InnerException == null)
                    throw;

                System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
            }

            // Get the hub contexts
            _mapHubContext = GlobalHost.ConnectionManager.GetHubContext<Web.MapHub>();
        }
Example #20
0
        public void Process(Chain mainChain, IBlockProvider blockProvider)
        {
            bool newChain = false;

            if (!Chain.Initialized)
            {
                newChain = true;

                var firstBlock = mainChain.GetBlock(StartHeight);
                Chain.Initialize(firstBlock.Header, StartHeight);
            }
            var forkBlock = mainChain.FindFork(Chain);

            if (forkBlock.HashBlock != Chain.Tip.HashBlock)
            {
                Chain.SetTip(Chain.GetBlock(forkBlock.Height));
                foreach (var e in Account.GetInChain(Chain, false)
                         .Where(e => e.Reason != AccountEntryReason.ChainBlockChanged))
                {
                    var neutralized = e.Neutralize();
                    Account.PushAccountEntry(neutralized);
                }
            }

            var unprocessedBlocks = mainChain.ToEnumerable(true)
                                    .TakeWhile(block => block != forkBlock)
                                    .Concat(newChain ? new ChainedBlock[] { forkBlock } : new ChainedBlock[0])
                                    .Reverse().ToArray();

            foreach (var block in unprocessedBlocks)
            {
                List <byte[]> searchedData = new List <byte[]>();
                Scanner.GetScannedPushData(searchedData);
                foreach (var unspent in Account.Unspent)
                {
                    searchedData.Add(unspent.OutPoint.ToBytes());
                }

                var fullBlock = blockProvider.GetBlock(block.HashBlock, searchedData);
                if (fullBlock != null)
                {
                    foreach (var spent in Scanner.FindSpent(fullBlock, Account.Unspent))
                    {
                        var entry = new AccountEntry(AccountEntryReason.Outcome,
                                                     block.HashBlock,
                                                     spent, -spent.TxOut.Value);
                        Account.PushAccountEntry(entry);
                    }
                    foreach (var coins in Scanner.ScanCoins(fullBlock, (int)block.Height))
                    {
                        int i = 0;
                        foreach (var output in coins.Coins.Outputs)
                        {
                            if (!output.IsNull)
                            {
                                var entry = new AccountEntry(AccountEntryReason.Income, block.HashBlock,
                                                             new Spendable(new OutPoint(coins.TxId, i), output), output.Value);
                                Account.PushAccountEntry(entry);
                            }
                            i++;
                        }
                    }
                }
                Chain.GetOrAdd(block.Header);
            }
        }
 /// <summary>
 /// Creates a new caching block provider
 /// </summary>
 /// <param name="rawBlockProvider">The provider that is wrapped by this caching provider</param>
 /// <param name="cache">The cache used to store the cached blocks</param>
 public CachingBlockProvider(IBlockProvider rawBlockProvider, ICache cache)
 {
     _blockProvider = rawBlockProvider;
     _cache         = cache;
 }
Example #22
0
 public BlockStream(IBlockProvider <T> provider)
 {
     Provider = provider ?? throw new ArgumentNullException(nameof(provider));
 }
Example #23
0
 public void RegisterBlockProvider(IBlockProvider provider)
 {
     BlockProviders[provider.ID] = provider;
 }
Example #24
0
 public CachedBlockProvider(IBlockProvider blockSourceProvider, IRepository <uint256, Block> blockRepository)
 {
     BlockRepository     = blockRepository;
     BlockSourceProvider = blockSourceProvider;
 }
Example #25
0
 public void RegisterBlockProvider(IBlockProvider provider)
 {
     BlockProviders[provider.Id] = provider;
 }
 /// <summary>
 /// Creates a new caching block provider
 /// </summary>
 /// <param name="rawBlockProvider">The provider that is wrapped by this caching provider</param>
 /// <param name="cache">The cache used to store the cached blocks</param>
 public CachingBlockProvider(IBlockProvider rawBlockProvider, ICache cache)
 {
     _blockProvider = rawBlockProvider;
     _cache = cache;
 }
Example #27
0
 public SmartBlockProvider(IBlockProvider provider, IMemoryCache cache)
 {
     InnerBlockProvider = provider;
     Cache = cache;
 }
		public CachedBlockProvider(IBlockProvider inner)
		{
			_Inner = inner;
			MaxCachedBlock = 50;
		}
Example #29
0
        public bool Process(ChainBase mainChain, IBlockProvider blockProvider)
        {
            var chainCopy       = Chain.Clone();
            var chainPosition   = chainCopy.Changes.Position;
            var accountCopy     = Account.Clone();
            var accountPosition = accountCopy.Entries.Position;

            bool newChain = false;

            if (!chainCopy.Initialized)
            {
                newChain = true;

                var firstBlock = mainChain.GetBlock(StartHeight);
                chainCopy.Initialize(firstBlock.Header, StartHeight);
            }
            var forkBlock = mainChain.FindFork(chainCopy);

            if (forkBlock.HashBlock != chainCopy.Tip.HashBlock)
            {
                var subChain = chainCopy.CreateSubChain(forkBlock, false, chainCopy.Tip, true);
                chainCopy.SetTip(chainCopy.GetBlock(forkBlock.Height));
                foreach (var e in accountCopy.GetInChain(subChain, true)
                         .Where(c => c.Reason != AccountEntryReason.Lock && c.Reason != AccountEntryReason.Unlock)
                         .Reverse())
                {
                    var neutralized = e.Neutralize();
                    accountCopy.PushAccountEntry(neutralized);
                }
            }

            var unprocessedBlocks = mainChain.ToEnumerable(true)
                                    .TakeWhile(block => block != forkBlock)
                                    .Concat(newChain ? new ChainedBlock[] { forkBlock } : new ChainedBlock[0])
                                    .Reverse().ToArray();

            foreach (var block in unprocessedBlocks)
            {
                List <byte[]> searchedData = new List <byte[]>();
                Scanner.GetScannedPushData(searchedData);
                foreach (var unspent in accountCopy.Unspent)
                {
                    searchedData.Add(unspent.OutPoint.ToBytes());
                }

                var fullBlock = blockProvider.GetBlock(block.HashBlock, searchedData);
                if (fullBlock == null)
                {
                    continue;
                }

                List <Tuple <OutPoint, AccountEntry> > spents = new List <Tuple <OutPoint, AccountEntry> >();
                foreach (var spent in FindSpent(fullBlock, accountCopy.Unspent))
                {
                    var entry = new AccountEntry(AccountEntryReason.Outcome,
                                                 block.HashBlock,
                                                 spent.Spendable, -spent.Spendable.TxOut.Value, spent.TxId);
                    spents.Add(Tuple.Create(entry.Spendable.OutPoint, entry));
                }

                if (CheckDoubleSpend)
                {
                    var spentsDico = spents.ToDictionary(t => t.Item1, t => t.Item2);
                    foreach (var spent in Scanner.FindSpent(fullBlock))
                    {
                        if (!spentsDico.ContainsKey(spent.PrevOut))
                        {
                            return(false);
                        }
                    }
                }

                foreach (var spent in spents)
                {
                    if (accountCopy.PushAccountEntry(spent.Item2) == null)
                    {
                        return(false);
                    }
                }

                foreach (var coins in Scanner.ScanCoins(fullBlock, (int)block.Height))
                {
                    int i = 0;
                    foreach (var output in coins.Coins.Outputs)
                    {
                        if (!output.IsNull)
                        {
                            var entry = new AccountEntry(AccountEntryReason.Income, block.HashBlock,
                                                         new Spendable(new OutPoint(coins.TxId, i), output), output.Value, null);
                            if (accountCopy.PushAccountEntry(entry) == null)
                            {
                                return(false);
                            }
                        }
                        i++;
                    }
                }

                chainCopy.SetTip(block);
            }

            accountCopy.Entries.GoTo(accountPosition);
            Account.PushAccountEntries(accountCopy.Entries);

            chainCopy.Changes.GoTo(chainPosition);
            Chain.PushChanges(chainCopy.Changes);
            return(true);
        }
Example #30
0
 public BlockDataProvider(object underlayingStructure) : base(underlayingStructure)
 {
     objectValidation <IBlockProvider>(underlayingStructure);
     _blockProvider = (IBlockProvider)underlayingStructure;
 }
Example #31
0
        public void Process(Chain mainChain, IBlockProvider blockProvider)
        {
            bool newChain = false;
            if(!Chain.Initialized)
            {
                newChain = true;

                var firstBlock = mainChain.GetBlock(StartHeight);
                Chain.Initialize(firstBlock.Header, StartHeight);
            }
            var forkBlock = mainChain.FindFork(Chain);
            if(forkBlock.HashBlock != Chain.Tip.HashBlock)
            {
                Chain.SetTip(Chain.GetBlock(forkBlock.Height));
                foreach(var e in Account.GetInChain(Chain, false)
                                            .Where(e => e.Reason != AccountEntryReason.ChainBlockChanged))
                {
                    var neutralized = e.Neutralize();
                    Account.PushAccountEntry(neutralized);
                }
            }

            var unprocessedBlocks = mainChain.ToEnumerable(true)
                                       .TakeWhile(block => block != forkBlock)
                                       .Concat(newChain ? new ChainedBlock[] { forkBlock } : new ChainedBlock[0])
                                       .Reverse().ToArray();
            foreach(var block in unprocessedBlocks)
            {
                List<byte[]> searchedData = new List<byte[]>();
                Scanner.GetScannedPushData(searchedData);
                foreach(var unspent in Account.Unspent)
                {
                    searchedData.Add(unspent.OutPoint.ToBytes());
                }

                var fullBlock = blockProvider.GetBlock(block.HashBlock, searchedData);
                if(fullBlock != null)
                {
                    foreach(var spent in Scanner.FindSpent(fullBlock, Account.Unspent))
                    {
                        var entry = new AccountEntry(AccountEntryReason.Outcome,
                                                    block.HashBlock,
                                                    spent, -spent.TxOut.Value);
                        Account.PushAccountEntry(entry);
                    }
                    foreach(var coins in Scanner.ScanCoins(fullBlock, (int)block.Height))
                    {
                        int i = 0;
                        foreach(var output in coins.Coins.Outputs)
                        {
                            if(!output.IsNull)
                            {
                                var entry = new AccountEntry(AccountEntryReason.Income, block.HashBlock,
                                                    new Spendable(new OutPoint(coins.TxId, i), output), output.Value);
                                Account.PushAccountEntry(entry);
                            }
                            i++;
                        }
                    }
                }
                Chain.GetOrAdd(block.Header);
            }
        }
Example #32
0
        public bool Process(Chain mainChain, IBlockProvider blockProvider)
        {
            var chain = Chain.Clone();
            var chainPosition = chain.Changes.Position;
            var account = Account.Clone();
            var accountPosition = account.Entries.Position;

            bool newChain = false;
            if(!chain.Initialized)
            {
                newChain = true;

                var firstBlock = mainChain.GetBlock(StartHeight);
                chain.Initialize(firstBlock.Header, StartHeight);
            }
            var forkBlock = mainChain.FindFork(chain);
            if(forkBlock.HashBlock != chain.Tip.HashBlock)
            {
                var subChain = chain.CreateSubChain(forkBlock, false, chain.Tip, true);
                chain.SetTip(chain.GetBlock(forkBlock.Height));
                foreach(var e in account.GetInChain(subChain, true)
                                        .Where(c => c.Reason != AccountEntryReason.Lock && c.Reason != AccountEntryReason.Unlock)
                                        .Reverse())
                {
                    var neutralized = e.Neutralize();
                    account.PushAccountEntry(neutralized);
                }
            }

            var unprocessedBlocks = mainChain.ToEnumerable(true)
                                       .TakeWhile(block => block != forkBlock)
                                       .Concat(newChain ? new ChainedBlock[] { forkBlock } : new ChainedBlock[0])
                                       .Reverse().ToArray();
            foreach(var block in unprocessedBlocks)
            {
                List<byte[]> searchedData = new List<byte[]>();
                Scanner.GetScannedPushData(searchedData);
                foreach(var unspent in account.Unspent)
                {
                    searchedData.Add(unspent.OutPoint.ToBytes());
                }

                var fullBlock = blockProvider.GetBlock(block.HashBlock, searchedData);
                if(fullBlock == null)
                    continue;

                List<Tuple<OutPoint, AccountEntry>> spents = new List<Tuple<OutPoint, AccountEntry>>();
                foreach(var spent in FindSpent(fullBlock, account.Unspent))
                {
                    var entry = new AccountEntry(AccountEntryReason.Outcome,
                                                block.HashBlock,
                                                spent, -spent.TxOut.Value);
                    spents.Add(Tuple.Create(entry.Spendable.OutPoint, entry));
                }

                if(CheckDoubleSpend)
                {
                    var spentsDico = spents.ToDictionary(t => t.Item1, t => t.Item2);
                    foreach(var spent in Scanner.FindSpent(fullBlock))
                    {
                        if(!spentsDico.ContainsKey(spent.PrevOut))
                            return false;
                    }
                }

                foreach(var spent in spents)
                {
                    if(account.PushAccountEntry(spent.Item2) == null)
                        return false;
                }

                foreach(var coins in Scanner.ScanCoins(fullBlock, (int)block.Height))
                {
                    int i = 0;
                    foreach(var output in coins.Coins.Outputs)
                    {
                        if(!output.IsNull)
                        {
                            var entry = new AccountEntry(AccountEntryReason.Income, block.HashBlock,
                                                new Spendable(new OutPoint(coins.TxId, i), output), output.Value);
                            if(account.PushAccountEntry(entry) == null)
                                return false;
                        }
                        i++;
                    }
                }

                chain.GetOrAdd(block.Header);
            }

            account.Entries.GoTo(accountPosition);
            Account.Entries.WriteNext(account.Entries);
            Account.Process();

            chain.Changes.GoTo(chainPosition);
            Chain.Changes.WriteNext(chain.Changes);
            Chain.Process();
            return true;
        }
Example #33
0
 public BlockCollisionObject(IBlockProvider blockProvider)
 {
     BlockProvider = blockProvider;
 }
Example #34
0
 public CachedBlockProvider(IBlockProvider inner)
 {
     _Inner         = inner;
     MaxCachedBlock = 50;
 }