public void SetUp()
 {
     _wallet = new Wallet(_params);
     _blockStore = new MemoryBlockStore(_params);
     var chain = new BlockChain(_params, _wallet, _blockStore);
     _peerGroup = new PeerGroup(_blockStore, _params, chain);
 }
Example #2
0
        public ODBFSImpl(IBlockStore blockStore)
        {
            if (blockStore == null)
            {
                throw new ArgumentNullException("blockStore");
            }
            _blockStore = blockStore;

            var xBuff = new byte[blockStore.BlockSize];
            blockStore.Retrieve(0, new ArraySegment<byte>(xBuff));

            if (ByteConverter.ReadUInt32(xBuff, 0) != ODBFSMagic)
            {
                throw new Exception("Blockstore doesn't contain an ODBFS system!");
            }

            _virtualBlockSize = ByteConverter.ReadUInt32(xBuff, 4);
            if (_virtualBlockSize % blockStore.BlockSize != 0)
            {
                throw new Exception("Corrupt data!");
            }
            _rawBlocksPerVirtualBlock = _virtualBlockSize / blockStore.BlockSize;
            _metaGroupItemsPerVirtualBlock = (_virtualBlockSize - 32) / 32;
            LoadConfiguration();
        }
Example #3
0
 public void SetUp()
 {
     var myKey = new EcKey();
     _myAddress = myKey.ToAddress(_params);
     _wallet = new Wallet(_params);
     _wallet.AddKey(myKey);
     _blockStore = new MemoryBlockStore(_params);
 }
 public void SetUp()
 {
     _unitTestParams = NetworkParameters.UnitTests();
     _wallet = new Wallet(_unitTestParams);
     _wallet.AddKey(new EcKey());
     _chainBlockStore = new MemoryBlockStore(_unitTestParams);
     _chain = new BlockChain(_unitTestParams, _wallet, _chainBlockStore);
     _coinbaseTo = _wallet.Keychain[0].ToAddress(_unitTestParams);
     _someOtherGuy = new EcKey().ToAddress(_unitTestParams);
 }
 public SimpleUsageCountStore(IBlockStore backend)
 {
     if (backend == null)
     {
         throw new ArgumentNullException("backend");
     }
     _backend = backend;
     _rawBlockUsagesPerBlock = backend.BlockSize / 8;
     _entryCount = backend.BlockCount * 8;
     _blockBuffPool = new ObjectPool<ArraySegment<byte>>(() => new ArraySegment<byte>(new byte[_backend.BlockSize]));
 }
        public SimpleReadCachingBlockStore(IBlockStore store, uint cacheCapacity = 512)
        {
            if (store == null)
            {
                throw new ArgumentNullException("store");
            }
            _store = store;

            _blockCache = new SimpleRecentItemCache<byte[]>();
            _blockCache.CacheCapacity = cacheCapacity;
            _blockCache.ItemRemovedFromCache = ItemRemovedFromCache;
            _blockCache.OnCacheMiss = CacheMiss;
            _blockBuffPool = new ObjectPool<byte[]>(() => new byte[store.BlockSize]);
        }
 // Emulates receiving a valid block that builds on top of the chain.
 public static BlockPair CreateFakeBlock(NetworkParameters @params, IBlockStore blockStore, params Transaction[] transactions)
 {
     var b = MakeTestBlock(@params, blockStore);
     // Coinbase tx was already added.
     foreach (var tx in transactions)
         b.AddTransaction(tx);
     b.Solve();
     var pair = new BlockPair();
     pair.Block = b;
     pair.StoredBlock = blockStore.GetChainHead().Build(b);
     blockStore.Put(pair.StoredBlock);
     blockStore.SetChainHead(pair.StoredBlock);
     return pair;
 }
        public SimpleReadWriteCachingBlockStore(IBlockStore store, uint capacity = 512)
        {
            if (store == null)
            {
                throw new ArgumentNullException("store");
            }
            _store = store;
            _blockSize = _store.BlockSize;

            _itemPool = new ObjectPool<CacheItem>(() => new CacheItem(_blockSize));

            _blockCache = new SimpleRecentItemCache<CacheItem>();
            _blockCache.CacheCapacity = capacity;
            _blockCache.ItemRemovedFromCache = ItemRemovedFromCache;
            _blockCache.OnCacheMiss = CacheMiss;
        }
Example #9
0
 public static void Format(IBlockStore blockStore, uint blockSize)
 {
     if (blockSize % blockStore.BlockSize != 0)
     {
         throw new Exception("Virtual BlockSize should be multiple of backend blocksize!");
     }
     var xRawBlockBuff = new byte[blockSize];
     var xRawSeg = new ArraySegment<byte>(xRawBlockBuff);
     ByteConverter.WriteBytes(ODBFSMagic, xRawBlockBuff, 0);
     ByteConverter.WriteBytes(blockSize, xRawBlockBuff, 4);
     var xRawBlocksPerVBlock = blockSize / blockStore.BlockSize;
     var xIds = new ulong[xRawBlocksPerVBlock];
     for(uint i = 0; i < xRawBlocksPerVBlock;i++)
     {
         xIds[i] = i;
     }
     blockStore.Store(xIds, xRawSeg);
 }
        public BlockDividingBlockStore(IBlockStore baseStore, uint blockSize)
        {
            if (baseStore == null)
            {
                throw new ArgumentNullException("baseStore");
            }
            _baseStore = baseStore;

            if (baseStore.BlockSize % blockSize != 0)
            {
                throw new Exception("Unsupported division. BaseStore.BlockSize % blockSize should be 0");
            }
            _blockSize = blockSize;
            _blockCount = (_baseStore.BlockCount * _baseStore.BlockSize) / blockSize;
            _blocksPerBackendBlock = _baseStore.BlockSize / blockSize;

            _bufferPool = new ObjectPool<ArraySegment<byte>>(() => new ArraySegment<byte>(new byte[_baseStore.BlockSize]));
        }
        public DeduplicatingBlockStore(IBlockManager virtualBlockManager, IBlockStore virtualBlockStore, IBlockStore rawBlockStore, IBlockManager rawBlockManager, ulong virtualBlockCount, IUsageCountStore rawBlockUsageCountStore, IHashManager<uint> rawBlockHashManager)
        {
            if (virtualBlockManager == null)
            {
                throw new ArgumentNullException("virtualBlockManager");
            }
            if (virtualBlockStore == null)
            {
                throw new ArgumentNullException("virtualBlockStore");
            }
            if (rawBlockStore == null)
            {
                throw new ArgumentNullException("rawBlockStore");
            }
            if (rawBlockManager == null)
            {
                throw new ArgumentNullException("rawBlockManager");
            }
            if (rawBlockUsageCountStore == null)
            {
                throw new ArgumentNullException("rawBlockUsageCountStore");
            }
            if (rawBlockHashManager == null)
            {
                throw new ArgumentNullException("rawBlockHashManager");
            }
            _virtualBlockManager = virtualBlockManager;
            _virtualBlockStore = virtualBlockStore;
            _rawBlockStore = rawBlockStore;
            _rawBlockManager = rawBlockManager;
            _virtualBlockCount = virtualBlockCount;
            _rawBlockUsageCountStore = rawBlockUsageCountStore;
            _rawBlockHashManager = rawBlockHashManager;

            _blockSize = rawBlockStore.BlockSize;

            if (virtualBlockStore.BlockCount != _virtualBlockCount)
            {
                throw new Exception(String.Format("BlockCount of VirtualBlockStore not correct! (Expected = {0}, Actual = {1})", _virtualBlockCount, virtualBlockStore.BlockCount));
            }

            _rawBlockBufferPool = new ObjectPool<ArraySegment<byte>>(() => new ArraySegment<byte>(new byte[_blockSize]));
            _virtualBlockBufferPool = new ObjectPool<ArraySegment<byte>>(() => new ArraySegment<byte>(new byte[8]));
        }
Example #12
0
        public BlockStoreController(
            Network network,
            ILoggerFactory loggerFactory,
            IBlockStore blockStore,
            IChainState chainState,
            ChainIndexer chainIndexer,
            IAddressIndexer addressIndexer)
        {
            Guard.NotNull(network, nameof(network));
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(chainState, nameof(chainState));
            Guard.NotNull(addressIndexer, nameof(addressIndexer));

            this.addressIndexer = addressIndexer;
            this.network        = network;
            this.blockStore     = blockStore;
            this.chainState     = chainState;
            this.chainIndexer   = chainIndexer;
            this.logger         = loggerFactory.CreateLogger(this.GetType().FullName);
        }
#pragma warning restore 649

        /// <inheritdoc />
        public WatchOnlyWalleRPCController(
            IFullNode fullNode,
            IConsensusManager consensusManager,
            ChainIndexer chainIndexer,
            Network network,
            WalletSettings walletSettings,
            IWalletManager walletManager,
            IWatchOnlyWalletManager watchOnlyWalletManager,
            IBlockStore blockStore,
            IChainState chainState) : base(fullNode: fullNode, consensusManager: consensusManager, chainIndexer: chainIndexer, network: network)
        {
            this.fullNode               = fullNode;
            this.chainIndexer           = chainIndexer;
            this.network                = network;
            this.walletSettings         = walletSettings;
            this.walletManager          = walletManager;
            this.watchOnlyWalletManager = watchOnlyWalletManager;
            this.blockStore             = blockStore;
            this.chainState             = chainState;
        }
        public FederationWalletSyncManager(IFederationWalletManager walletManager, ChainIndexer chain, Network network,
                                           IBlockStore blockStore, StoreSettings storeSettings, INodeLifetime nodeLifetime, IAsyncProvider asyncProvider)
        {
            Guard.NotNull(walletManager, nameof(walletManager));
            Guard.NotNull(chain, nameof(chain));
            Guard.NotNull(network, nameof(network));
            Guard.NotNull(blockStore, nameof(blockStore));
            Guard.NotNull(storeSettings, nameof(storeSettings));
            Guard.NotNull(nodeLifetime, nameof(nodeLifetime));
            Guard.NotNull(asyncProvider, nameof(asyncProvider));

            this.federationWalletManager = walletManager;
            this.chain               = chain;
            this.blockStore          = blockStore;
            this.coinType            = (CoinType)network.Consensus.CoinType;
            this.storeSettings       = storeSettings;
            this.nodeLifetime        = nodeLifetime;
            this.asyncProvider       = asyncProvider;
            this.logger              = LogManager.GetCurrentClassLogger();
            this.blockQueueProcessor = new BlockQueueProcessor(this.asyncProvider, this.OnProcessBlockWrapperAsync, MaxQueueSize, nameof(FederationWalletSyncManager));
        }
Example #15
0
        public WalletSyncManager(ILoggerFactory loggerFactory, IWalletManager walletManager, ChainIndexer chainIndexer,
                                 Network network, IBlockStore blockStore, StoreSettings storeSettings, ISignals signals)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(walletManager, nameof(walletManager));
            Guard.NotNull(chainIndexer, nameof(chainIndexer));
            Guard.NotNull(network, nameof(network));
            Guard.NotNull(blockStore, nameof(blockStore));
            Guard.NotNull(storeSettings, nameof(storeSettings));
            Guard.NotNull(signals, nameof(signals));

            this.walletManager = walletManager;
            this.chainIndexer  = chainIndexer;
            this.blockStore    = blockStore;
            this.storeSettings = storeSettings;
            this.signals       = signals;
            this.logger        = loggerFactory.CreateLogger("Impleum.Bitcoin.FullNode");
            this.blocksQueue   = new AsyncQueue <Block>(this.OnProcessBlockAsync);

            this.blocksQueueSize = 0;
        }
        public WalletSyncManager(ILoggerFactory loggerFactory, IWalletManager walletManager, ConcurrentChain chain,
                                 Network network, IBlockStore blockStore, StoreSettings storeSettings, INodeLifetime nodeLifetime)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(walletManager, nameof(walletManager));
            Guard.NotNull(chain, nameof(chain));
            Guard.NotNull(network, nameof(network));
            Guard.NotNull(blockStore, nameof(blockStore));
            Guard.NotNull(storeSettings, nameof(storeSettings));
            Guard.NotNull(nodeLifetime, nameof(nodeLifetime));

            this.walletManager = walletManager;
            this.chain         = chain;
            this.blockStore    = blockStore;
            this.storeSettings = storeSettings;
            this.nodeLifetime  = nodeLifetime;
            this.logger        = loggerFactory.CreateLogger(this.GetType().FullName);
            this.blocksQueue   = new AsyncQueue <Block>(this.OnProcessBlockAsync);

            this.blocksQueueSize = 0;
        }
Example #17
0
        public MockChainNode(CoreNode coreNode, IMockChain chain, Mnemonic mnemonic = null)
        {
            this.CoreNode = coreNode;
            this.chain    = chain;

            // Set up address and mining
            (Wallet wallet, _) = this.CoreNode.FullNode.WalletManager().CreateWallet(this.Password, this.WalletName, this.Passphrase, mnemonic);
            HdAccount account = wallet.GetAccount(this.AccountName);

            this.MinerAddress = account.GetFirstUnusedReceivingAddress();

            Key key = wallet.GetExtendedPrivateKeyForAddress(this.Password, this.MinerAddress).PrivateKey;

            this.CoreNode.SetMinerSecret(new BitcoinSecret(key, this.CoreNode.FullNode.Network));

            // Set up services for later
            this.smartContractWalletController = this.CoreNode.FullNode.NodeController <SmartContractWalletController>();
            this.smartContractsController      = this.CoreNode.FullNode.NodeController <SmartContractsController>();
            this.stateRoot  = this.CoreNode.FullNode.NodeService <IStateRepositoryRoot>();
            this.blockStore = this.CoreNode.FullNode.NodeService <IBlockStore>();
        }
        public SmarterReadCachingBlockStore(IBlockStore backend, uint cacheBlockSize, uint cacheCapacity = SimpleRecentItemCache<byte[]>.DefaultCacheSize)
        {
            if (backend == null)
            {
                throw new ArgumentNullException("backend");
            }

            _backend = backend;
            _cacheBlockSize = cacheBlockSize;
            if (cacheBlockSize % _backend.BlockSize != 0)
            {
                throw new Exception("Wrong CacheBlockSize value. Should be perfect multiple of backend block size");
            }
            _backendBlocksPerCacheBlock=cacheBlockSize/_backend.BlockSize;

            _bufferPool = new ObjectPool<byte[]>(() => new byte[cacheBlockSize]);

            _cache = new SimpleRecentItemCache<byte[]>(cacheCapacity);
            _cache.ItemRemovedFromCache = ItemRemovedFromCache;
            _cache.OnCacheMiss = CacheMiss;
        }
Example #19
0
        public NodeController(
            ChainIndexer chainIndexer,
            IChainState chainState,
            IConnectionManager connectionManager,
            IDateTimeProvider dateTimeProvider,
            IFullNode fullNode,
            ILoggerFactory loggerFactory,
            NodeSettings nodeSettings,
            Network network,
            IAsyncProvider asyncProvider,
            ISelfEndpointTracker selfEndpointTracker,
            IConsensusManager consensusManager,
            IBlockStore blockStore,
            IInitialBlockDownloadState initialBlockDownloadState,
            ISignals signals,
            IGetUnspentTransaction getUnspentTransaction             = null,
            INetworkDifficulty networkDifficulty                     = null,
            IPooledGetUnspentTransaction pooledGetUnspentTransaction = null,
            IPooledTransaction pooledTransaction                     = null)
        {
            this.asyncProvider       = asyncProvider;
            this.chainIndexer        = chainIndexer;
            this.chainState          = chainState;
            this.connectionManager   = connectionManager;
            this.dateTimeProvider    = dateTimeProvider;
            this.fullNode            = fullNode;
            this.logger              = loggerFactory.CreateLogger(this.GetType().FullName);
            this.network             = network;
            this.nodeSettings        = nodeSettings;
            this.selfEndpointTracker = selfEndpointTracker;
            this.signals             = signals;

            this.consensusManager            = consensusManager;
            this.blockStore                  = blockStore;
            this.getUnspentTransaction       = getUnspentTransaction;
            this.initialBlockDownloadState   = initialBlockDownloadState;
            this.networkDifficulty           = networkDifficulty;
            this.pooledGetUnspentTransaction = pooledGetUnspentTransaction;
            this.pooledTransaction           = pooledTransaction;
        }
        public FederationWalletSyncManager(ILoggerFactory loggerFactory, IFederationWalletManager walletManager, ChainIndexer chain,
                                           Network network, IBlockStore blockStore, StoreSettings storeSettings, INodeLifetime nodeLifetime, IAsyncProvider asyncProvider)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(walletManager, nameof(walletManager));
            Guard.NotNull(chain, nameof(chain));
            Guard.NotNull(network, nameof(network));
            Guard.NotNull(blockStore, nameof(blockStore));
            Guard.NotNull(storeSettings, nameof(storeSettings));
            Guard.NotNull(nodeLifetime, nameof(nodeLifetime));
            Guard.NotNull(asyncProvider, nameof(asyncProvider));

            this.walletManager       = walletManager;
            this.chain               = chain;
            this.blockStore          = blockStore;
            this.coinType            = (CoinType)network.Consensus.CoinType;
            this.storeSettings       = storeSettings;
            this.nodeLifetime        = nodeLifetime;
            this.asyncProvider       = asyncProvider;
            this.logger              = loggerFactory.CreateLogger("Impleum.Bitcoin.Fullnode");
            this.blockQueueProcessor = new BlockQueueProcessor(this.logger, this.asyncProvider, this.OnProcessBlockWrapperAsync, MaxQueueSize, nameof(FederationWalletSyncManager));
        }
        public NodeController(
            ConcurrentChain chain,
            IChainState chainState,
            IConnectionManager connectionManager,
            IDateTimeProvider dateTimeProvider,
            IFullNode fullNode,
            ILoggerFactory loggerFactory,
            NodeSettings nodeSettings,
            Network network,
            IBlockStore blockStore = null,
            IGetUnspentTransaction getUnspentTransaction             = null,
            INetworkDifficulty networkDifficulty                     = null,
            IPooledGetUnspentTransaction pooledGetUnspentTransaction = null,
            IPooledTransaction pooledTransaction                     = null)
        {
            Guard.NotNull(fullNode, nameof(fullNode));
            Guard.NotNull(network, nameof(network));
            Guard.NotNull(chain, nameof(chain));
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(nodeSettings, nameof(nodeSettings));
            Guard.NotNull(chainState, nameof(chainState));
            Guard.NotNull(connectionManager, nameof(connectionManager));
            Guard.NotNull(dateTimeProvider, nameof(dateTimeProvider));

            this.chain             = chain;
            this.chainState        = chainState;
            this.connectionManager = connectionManager;
            this.dateTimeProvider  = dateTimeProvider;
            this.fullNode          = fullNode;
            this.logger            = loggerFactory.CreateLogger(this.GetType().FullName);
            this.network           = network;
            this.nodeSettings      = nodeSettings;

            this.blockStore                  = blockStore;
            this.getUnspentTransaction       = getUnspentTransaction;
            this.networkDifficulty           = networkDifficulty;
            this.pooledGetUnspentTransaction = pooledGetUnspentTransaction;
            this.pooledTransaction           = pooledTransaction;
        }
        public FederationWalletSyncManager(ILoggerFactory loggerFactory, IFederationWalletManager walletManager, ChainIndexer chain,
                                           Network network, IBlockStore blockStore, StoreSettings storeSettings, INodeLifetime nodeLifetime)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(walletManager, nameof(walletManager));
            Guard.NotNull(chain, nameof(chain));
            Guard.NotNull(network, nameof(network));
            Guard.NotNull(blockStore, nameof(blockStore));
            Guard.NotNull(storeSettings, nameof(storeSettings));
            Guard.NotNull(nodeLifetime, nameof(nodeLifetime));

            this.walletManager = walletManager;
            this.chain         = chain;
            this.blockStore    = blockStore;
            this.coinType      = (CoinType)network.Consensus.CoinType;
            this.storeSettings = storeSettings;
            this.nodeLifetime  = nodeLifetime;
            this.logger        = loggerFactory.CreateLogger("Impleum.Bitcoin.FullNode");
            this.blocksQueue   = new AsyncQueue <Block>(this.OnProcessBlockAsync);

            this.blocksQueueSize = 0;
        }
Example #23
0
        public WalletSyncManager(ILoggerFactory loggerFactory, IWalletManager walletManager, ChainIndexer chainIndexer,
                                 Network network, IBlockStore blockStore, StoreSettings storeSettings, ISignals signals, IAsyncProvider asyncProvider)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(walletManager, nameof(walletManager));
            Guard.NotNull(chainIndexer, nameof(chainIndexer));
            Guard.NotNull(network, nameof(network));
            Guard.NotNull(blockStore, nameof(blockStore));
            Guard.NotNull(storeSettings, nameof(storeSettings));
            Guard.NotNull(signals, nameof(signals));
            Guard.NotNull(asyncProvider, nameof(asyncProvider));

            this.walletManager = walletManager;
            this.chainIndexer  = chainIndexer;
            this.blockStore    = blockStore;
            this.storeSettings = storeSettings;
            this.signals       = signals;
            this.asyncProvider = asyncProvider;
            this.logger        = loggerFactory.CreateLogger(this.GetType().FullName);
            this.blocksQueue   = this.asyncProvider.CreateAndRunAsyncDelegateDequeuer <Block>($"{nameof(WalletSyncManager)}-{nameof(this.blocksQueue)}", this.OnProcessBlockAsync);

            this.blocksQueueSize = 0;
        }
        public Unity3dController(ILoggerFactory loggerFactory, IAddressIndexer addressIndexer,
                                 IBlockStore blockStore, IChainState chainState, Network network, ICoinView coinView, WalletController walletController, ChainIndexer chainIndexer, IStakeChain stakeChain = null,
                                 IContractPrimitiveSerializer primitiveSerializer = null, IStateRepositoryRoot stateRoot = null, IContractAssemblyCache contractAssemblyCache                   = null,
                                 IReceiptRepository receiptRepository             = null, ISmartContractTransactionService smartContractTransactionService = null, ILocalExecutor localExecutor = null)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            this.logger           = loggerFactory.CreateLogger(this.GetType().FullName);
            this.addressIndexer   = Guard.NotNull(addressIndexer, nameof(addressIndexer));
            this.blockStore       = Guard.NotNull(blockStore, nameof(blockStore));
            this.chainState       = Guard.NotNull(chainState, nameof(chainState));
            this.network          = Guard.NotNull(network, nameof(network));
            this.coinView         = Guard.NotNull(coinView, nameof(coinView));
            this.walletController = Guard.NotNull(walletController, nameof(walletController));
            this.chainIndexer     = Guard.NotNull(chainIndexer, nameof(chainIndexer));
            this.stakeChain       = stakeChain;

            this.primitiveSerializer             = primitiveSerializer;
            this.stateRoot                       = stateRoot;
            this.contractAssemblyCache           = contractAssemblyCache;
            this.receiptRepository               = receiptRepository;
            this.smartContractTransactionService = smartContractTransactionService;
            this.localExecutor                   = localExecutor;
        }
Example #25
0
 public void ChangeStore(IBlockStore newStore)
 {
     lock (this) {
         if (lockCount > 0)
         {
             blockStore.Close();
             newStore.Open();
         }
         if (newStore is FileBlockStore)
         {
             isCompressed = false;
         }
         else if (newStore is CompressedBlockStore)
         {
             isCompressed = true;
         }
         else
         {
             throw new ApplicationException("Unknown block_store type");
         }
         blockStore = newStore;
     }
 }
 public WalletRPCController(
     IBlockStore blockStore,
     IBroadcasterManager broadcasterManager,
     ChainIndexer chainIndexer,
     IConsensusManager consensusManager,
     IFullNode fullNode,
     ILoggerFactory loggerFactory,
     Network network,
     IScriptAddressReader scriptAddressReader,
     StoreSettings storeSettings,
     IWalletManager walletManager,
     WalletSettings walletSettings,
     IWalletTransactionHandler walletTransactionHandler) : base(fullNode: fullNode, consensusManager: consensusManager, chainIndexer: chainIndexer, network: network)
 {
     this.blockStore               = blockStore;
     this.broadcasterManager       = broadcasterManager;
     this.logger                   = loggerFactory.CreateLogger(this.GetType().FullName);
     this.scriptAddressReader      = scriptAddressReader;
     this.storeSettings            = storeSettings;
     this.walletManager            = walletManager;
     this.walletSettings           = walletSettings;
     this.walletTransactionHandler = walletTransactionHandler;
 }
Example #27
0
 public FullNodeController(
     ILoggerFactory loggerFactory,
     IPooledTransaction pooledTransaction = null,
     IPooledGetUnspentTransaction pooledGetUnspentTransaction = null,
     IGetUnspentTransaction getUnspentTransaction             = null,
     INetworkDifficulty networkDifficulty = null,
     IFullNode fullNode        = null,
     NodeSettings nodeSettings = null,
     Network network           = null,
     ChainIndexer chainIndexer = null,
     IChainState chainState    = null,
     Connection.IConnectionManager connectionManager = null,
     IConsensusManager consensusManager  = null,
     IBlockStore blockStore              = null,
     StoreSettings storeSettings         = null,
     IInitialBlockDownloadState ibdState = null,
     IStakeChain stakeChain              = null)
     : base(
         fullNode: fullNode,
         network: network,
         nodeSettings: nodeSettings,
         chainIndexer: chainIndexer,
         chainState: chainState,
         connectionManager: connectionManager,
         consensusManager: consensusManager)
 {
     this.logger                      = loggerFactory.CreateLogger(this.GetType().FullName);
     this.pooledTransaction           = pooledTransaction;
     this.pooledGetUnspentTransaction = pooledGetUnspentTransaction;
     this.getUnspentTransaction       = getUnspentTransaction;
     this.networkDifficulty           = networkDifficulty;
     this.consensusManager            = consensusManager;
     this.blockStore                  = blockStore;
     this.storeSettings               = storeSettings;
     this.ibdState                    = ibdState;
     this.stakeChain                  = stakeChain;
 }
Example #28
0
 public BitmapBlockManager(IBlockStore baseStore, Stream bitmap)
 {
     if (baseStore == null)
     {
         throw new ArgumentNullException("baseStore");
     }
     if (bitmap == null)
     {
         throw new ArgumentNullException("bitmap");
     }
     var xExpectedBitmapSize = ((baseStore.BlockCount * baseStore.BlockSize) / 8U);
     if ((ulong)bitmap.Length != xExpectedBitmapSize)
     {
         throw new Exception(string.Format("Wrong Bitmap stream size! (Expected = {0}, Actual = {1})", xExpectedBitmapSize, bitmap.Length));
     }
     if (xExpectedBitmapSize < baseStore.BlockSize)
     {
         mBitmap = new FileBitmap(bitmap, 1, (uint)xExpectedBitmapSize);
     }
     else
     {
         mBitmap = new FileBitmap(bitmap, baseStore.BlockCount / 8, baseStore.BlockSize);
     }
 }
Example #29
0
        public FederationWalletSyncManager(ILoggerFactory loggerFactory, IFederationWalletManager walletManager, ChainIndexer chain,
                                           Network network, IBlockStore blockStore, StoreSettings storeSettings, INodeLifetime nodeLifetime, IAsyncProvider asyncProvider)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(walletManager, nameof(walletManager));
            Guard.NotNull(chain, nameof(chain));
            Guard.NotNull(network, nameof(network));
            Guard.NotNull(blockStore, nameof(blockStore));
            Guard.NotNull(storeSettings, nameof(storeSettings));
            Guard.NotNull(nodeLifetime, nameof(nodeLifetime));
            Guard.NotNull(asyncProvider, nameof(asyncProvider));

            this.walletManager = walletManager;
            this.chain         = chain;
            this.blockStore    = blockStore;
            this.coinType      = (CoinType)network.Consensus.CoinType;
            this.storeSettings = storeSettings;
            this.nodeLifetime  = nodeLifetime;
            this.asyncProvider = asyncProvider;
            this.logger        = loggerFactory.CreateLogger(this.GetType().FullName);
            this.blocksQueue   = asyncProvider.CreateAndRunAsyncDelegateDequeuer <Block>($"{nameof(FederationWalletSyncManager)}-{nameof(this.blocksQueue)}", this.OnProcessBlockAsync);

            this.blocksQueueSize = 0;
        }
Example #30
0
 /// <summary>
 /// Constructs a BlockChain connected to the given list of wallets and a store.
 /// </summary>
 /// <exception cref="BlockStoreException"/>
 public BlockChain(NetworkParameters networkParams, IEnumerable <Wallet> wallets, IBlockStore blockStore)
 {
     _blockStore = blockStore;
     _chainHead  = blockStore.GetChainHead();
     Log.InfoFormat("chain head is:{0}{1}", Environment.NewLine, _chainHead.Header);
     _params  = networkParams;
     _wallets = new List <Wallet>(wallets);
 }
 public BlockProcessor(BlockChain chain, IBlockStore store)
 {
     this.chain        = chain;
     this.orphansStore = store;
 }
Example #32
0
 /// <summary>
 /// Creates an instance of Chain. Don't use directly use <code>ChainFactory.Create()</code> instead.
 /// </summary>
 /// <param name="store">An instance of IBlockStore to store blocks</param>
 /// <param name="cryptographyHelper">An instance of ICryptographyHelper to compute hash</param>
 public Chain(IBlockStore <TContent, THash> store, ICryptographyHelper <THash> cryptographyHelper)
 {
     this.store = store;
     this.cryptographyHelper = cryptographyHelper;
 }
Example #33
0
 /// <summary>
 /// Constructs a BlockChain connected to the given list of wallets and a store.
 /// </summary>
 /// <exception cref="BlockStoreException"/>
 public BlockChain(NetworkParameters @params, IEnumerable<Wallet> wallets, IBlockStore blockStore)
 {
     _blockStore = blockStore;
     _chainHead = blockStore.GetChainHead();
     _log.InfoFormat("chain head is:{0}{1}", Environment.NewLine, _chainHead.Header);
     _params = @params;
     _wallets = new List<Wallet>(wallets);
 }
Example #34
0
 /// <summary>
 /// Create a blockchain with custom store using SHA1 hash function
 /// </summary>
 /// <typeparam name="TContent">Type of the content in blockchain</typeparam>
 /// <param name="store">IBlockStore instance to store the records</param>
 /// <returns>Instance of a chain containing operations for the blockchain</returns>
 public static Chain <TContent, byte[]> Create <TContent>(IBlockStore <TContent, byte[]> store)
 {
     return(Create(store, new Sha1CryptographyHelper()));
 }
Example #35
0
 public WalletSyncManagerOverride(ILoggerFactory loggerFactory, IWalletManager walletManager, ConcurrentChain chain,
                                  Network network, IBlockStore blockStore, StoreSettings storeSettings, ISignals signals)
     : base(loggerFactory, walletManager, chain, network, blockStore, storeSettings, signals)
 {
 }
Example #36
0
 private void ResetBlockStore()
 {
     _blockStore = new MemoryBlockStore(_unitTestParams);
 }
Example #37
0
 public void SetUp()
 {
     var myKey = new EcKey();
     _myAddress = myKey.ToAddress(Params);
     _defaultWallet = new DefaultWallet(Params);
     _defaultWallet.AddKey(myKey);
     _blockStore = new MemoryBlockStore(Params);
 }
Example #38
0
 /// <summary>
 ///     Constructs a BlockChain connected to the given wallet and store. To obtain a <see cref="BitcoinSharp.Wallet.DefaultWallet" /> you can
 ///     construct
 ///     one from scratch, or you can deserialize a saved wallet from disk using <see cref="BitcoinSharp.Wallet.DefaultWallet.LoadFromFile" />.
 /// </summary>
 /// <remarks>
 ///     For the store you can use a <see cref="BitcoinSharp.Blockchain.Store.MemoryBlockStore" /> if you don't care about saving the downloaded data, or
 ///     a
 ///     <see cref="BitcoinSharp.Blockchain.Store.BoundedOverheadBlockStore" /> if you'd like to ensure fast start-up the next time you run the program.
 /// </remarks>
 /// <exception cref="BitcoinSharp.Blockchain.Store.BlockStoreException" />
 public BlockChain(NetworkParameters networkParameters, IDefaultWallet defaultWallet, IBlockStore blockStore)
     : this(networkParameters, new List<IDefaultWallet>(), blockStore)
 {
     if (defaultWallet != null)
         AddWallet(defaultWallet);
 }
Example #39
0
 /// <summary>
 /// Create a blockchain with custom store and hash function
 /// </summary>
 /// <typeparam name="TContent">Type of the content in blockchain</typeparam>
 /// <typeparam name="THash">Type of the hash used in cryptography helper</typeparam>
 /// <param name="store">IBlockStore instance to store the records</param>
 /// <param name="cryptographyHelper">ICryptographyHelper used to compute hash</param>
 /// <returns>Instance of a chain containing operations for the blockchain</returns>
 public static Chain <TContent, THash> Create <TContent, THash>(IBlockStore <TContent, THash> store, ICryptographyHelper <THash> cryptographyHelper)
 {
     return(new Chain <TContent, THash>(store, cryptographyHelper));
 }
Example #40
0
 /// <summary>
 /// Given a block store, looks up the previous block in this chain. Convenience method for doing
 /// <tt>store.get(this.getHeader().getPrevBlockHash())</tt>.
 /// </summary>
 /// <returns>The previous block in the chain or null if it was not found in the store.</returns>
 /// <exception cref="BitcoinSharp.Blockchain.Store.BlockStoreException"/>
 public StoredBlock GetPrev(IBlockStore blockStore)
 {
     return blockStore.Get(BlockHeader.PreviousBlockHash);
 }
Example #41
0
 /// <summary>
 ///     Constructs a BlockChain connected to the given list of wallets and a store.
 /// </summary>
 /// <exception cref="BitcoinSharp.Blockchain.Store.BlockStoreException" />
 public BlockChain(NetworkParameters networkParameters, IEnumerable<IDefaultWallet> wallets, IBlockStore blockStore)
 {
     _blockStore = blockStore;
     _chainHead = blockStore.GetChainHead();
     Log.InfoFormat("chain head is:{0}{1}", Environment.NewLine, _chainHead.BlockHeader);
     _networkParameters = networkParameters;
     _wallets = new List<IDefaultWallet>(wallets);
 }
 /// <summary>
 /// Creates a PeerGroup with the given parameters and a default 5 second connection timeout.
 /// </summary>
 public PeerGroup(IBlockStore blockStore, NetworkParameters @params, BlockChain chain)
     : this(blockStore, @params, chain, DefaultConnectionDelayMillis)
 {
 }
Example #43
0
 /// <summary>
 /// Constructs a BlockChain that has no wallet at all. This is helpful when you don't actually care about sending
 /// and receiving coins but rather, just want to explore the network data structures.
 /// </summary>
 /// <exception cref="BlockStoreException"/>
 public BlockChain(NetworkParameters @params, IBlockStore blockStore)
     : this(@params, new List<Wallet>(), blockStore)
 {
 }
        /// <summary>
        /// Creates a PeerGroup with the given parameters. The connectionDelayMillis parameter controls how long the
        /// PeerGroup will wait between attempts to connect to nodes or read from any added peer discovery sources.
        /// </summary>
        public PeerGroup(IBlockStore blockStore, NetworkParameters @params, BlockChain chain, int connectionDelayMillis)
        {
            _blockStore = blockStore;
            _params = @params;
            _chain = chain;
            _connectionDelayMillis = connectionDelayMillis;

            _inactives = new LinkedBlockingQueue<PeerAddress>();
            _peers = new SynchronizedHashSet<Peer>();
            _peerDiscoverers = new SynchronizedHashSet<IPeerDiscovery>();
            _peerPool = new ThreadPoolExecutor(_coreThreads, _defaultConnections,
                                               TimeSpan.FromSeconds(_threadKeepAliveSeconds),
                                               new LinkedBlockingQueue<IRunnable>(1),
                                               new PeerGroupThreadFactory());
        }
Example #45
0
 /// <summary>
 /// Constructs a BlockChain connected to the given wallet and store. To obtain a <see cref="Wallet"/> you can construct
 /// one from scratch, or you can deserialize a saved wallet from disk using <see cref="Wallet.LoadFromFile"/>.
 /// </summary>
 /// <remarks>
 /// For the store you can use a <see cref="MemoryBlockStore"/> if you don't care about saving the downloaded data, or a
 /// <see cref="BoundedOverheadBlockStore"/> if you'd like to ensure fast start-up the next time you run the program.
 /// </remarks>
 /// <exception cref="BlockStoreException"/>
 public BlockChain(NetworkParameters @params, Wallet wallet, IBlockStore blockStore)
     : this(@params, new List<Wallet>(), blockStore)
 {
     if (wallet != null)
         AddWallet(wallet);
 }
Example #46
0
        /// <summary>
        /// Creates a PeerGroup with the given parameters. The connectionDelayMillis parameter controls how long the
        /// PeerGroup will wait between attempts to connect to nodes or read from any added peer discovery sources.
        /// </summary>
        public PeerGroup(IBlockStore blockStore, NetworkParameters networkNetworkParams, BlockChain chain)
        {
            _blockStore = blockStore;
            this.networkParams = networkNetworkParams;
            _chain = chain;

            peerConnectionPool = new ThreadWorkerPool(MaxPeerConnections);

            _inactives = new ConcurrentQueue<PeerAddress>();
            _peers = new List<Peer>();
            _peerDiscoverers = new List<IPeerDiscovery>();
            peerGroupTimer = new SingleEntryTimer(PeerGroupTimerCallback);
        }
Example #47
0
 public BlockProcessor()
 {
     this.store = new InMemoryBlockStore();
 }
 public WalletSyncManagerOverride(ILoggerFactory loggerFactory, IWalletManager walletManager, ChainIndexer chainIndexer,
                                  Network network, IBlockStore blockStore, StoreSettings storeSettings, ISignals signals, IAsyncProvider asyncProvider)
     : base(loggerFactory, walletManager, chainIndexer, network, blockStore, storeSettings, signals, asyncProvider)
 {
 }
Example #49
0
 /// <summary>
 /// Constructs a BlockChain connected to the given wallet and store. To obtain a <see cref="Wallet">Wallet</see> you can construct
 /// one from scratch, or you can deserialize a saved wallet from disk using <see cref="Wallet.LoadFromFile(System.IO.FileInfo)">Wallet.LoadFromFile(System.IO.FileInfo)</see><p />
 /// </summary>
 /// <remarks>
 /// For the store you can use a <see cref="MemoryBlockStore">MemoryBlockStore</see> if you don't care about saving the downloaded data, or a
 /// <see cref="BoundedOverheadBlockStore">BoundedOverheadBlockStore</see> if you'd like to ensure fast start-up the next time you run the program.
 /// </remarks>
 public BlockChain(NetworkParameters @params, Wallet wallet, IBlockStore blockStore)
 {
     _blockStore = blockStore;
     _chainHead = blockStore.GetChainHead();
     _log.InfoFormat("chain head is:{0}{1}", Environment.NewLine, _chainHead.Header);
     _params = @params;
     _wallet = wallet;
 }
Example #50
0
 /// <summary>
 /// Creates a PeerGroup with the given parameters and a default 5 second connection timeout.
 /// </summary>
 public PeerGroup(IBlockStore blockStore, NetworkParameters @params, BlockChain chain)
     : this(blockStore, @params, chain, DefaultConnectionDelayMillis)
 {
 }
Example #51
0
 /// <summary>
 /// Given a block store, looks up the previous block in this chain. Convenience method for doing
 /// <tt>store.get(this.getHeader().getPrevBlockHash())</tt>.
 /// </summary>
 /// <returns>The previous block in the chain or null if it was not found in the store.</returns>
 /// <exception cref="BlockStoreException"/>
 public StoredBlock GetPrev(IBlockStore store)
 {
     return(store.Get(Header.PrevBlockHash));
 }
Example #52
0
        private static bool Bootstrap()
        {
            IConfiguration config = new ConfigurationBuilder()
                                    .AddEnvironmentVariables()
                                    .AddJsonFile("chain.json")
                                    .Build();

            var loggerFactory = new LoggerFactory();

            loggerFactory.AddConsole();

            var chain = new ChainSettings();

            config.Bind(chain);

            System.Console.Title = chain.Name;

            var logger = loggerFactory.CreateLogger(chain.Name);

            TaskScheduler.UnobservedTaskException += (s, e) => { UnhandledException(logger, e.Exception); };

            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                UnhandledException(logger, e.ExceptionObject as Exception);
            };

            try
            {
                var hashProvider = new ObjectHashProvider();
                var typeProvider = new BlockObjectTypeProvider();

                if (chain.GenesisBlock == null)
                {
                    logger.LogCritical("Chain genesis block is missing");
                    goto failfast;
                }

                if (chain.GenesisBlock.Hash == null)
                {
                    logger.LogCritical("Chain genesis block hash is missing");
                    goto failfast;
                }

                var genesisHash = chain.GenesisBlock.ToHashBytes(hashProvider);

#if DEBUG
                var genesisHashDebug = "[";
                foreach (var c in genesisHash)
                {
                    genesisHashDebug += c + ", ";
                }
                genesisHashDebug += "]";
                logger.LogDebug($"Expected genesisHash = {genesisHashDebug}");
#endif

                if (!chain.GenesisBlock.Hash.ConstantTimeEquals(genesisHash))
                {
                    logger.LogCritical($"Chain genesis block hash '{genesisHash.ToHex()}' is invalid");
                    goto failfast;
                }

                var chainHash = hashProvider.ComputeHashBytes(chain);

#if DEBUG
                var chainHashDebug = "[";
                foreach (var c in chainHash)
                {
                    chainHashDebug += c + ", ";
                }
                chainHashDebug += "]";
                logger.LogDebug($"Expected chainHash = {chainHashDebug}");
#endif

                if (!chain.Hash.ConstantTimeEquals(chainHash))
                {
                    logger.LogCritical("Chain configuration hash is missing or invalid");
                    goto failfast;
                }

                //
                // Storage:
                //
                IBlockStore blocks = null;
                if (!string.IsNullOrWhiteSpace(chain.StorageEngine))
                {
                    switch (chain.StorageEngine?.ToUpperInvariant())
                    {
                    case "SQLITE":
                    {
                        string baseDirectory =
                            chain.StorageDirectory ?? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                        blocks = new SqliteBlockStore(baseDirectory, chain.Name, "blocks", chain.GenesisBlock,
                                                      typeProvider, loggerFactory.CreateLogger <SqliteBlockStore>());
                        break;
                    }
                    }
                }

                //
                // Blockchain:
                //
                if (blocks == null)
                {
                    logger.LogCritical("Could not find a supported storage engine for the chain.");
                    goto failfast;
                }

                _blockchain = new Blockchain(blocks, new NoProofOfWork(), hashProvider,
                                             loggerFactory.CreateLogger <Blockchain>());
            }
            catch (Exception ex)
            {
                UnhandledException(logger, ex);
            }

            logger.LogInformation($"{chain.Name} is running.");
            return(true);

failfast:
            logger.LogInformation("Press any key to shut down.");
            return(false);
        }
Example #53
0
 /// <summary>
 ///     Constructs a BlockChain that has no wallet at all. This is helpful when you don't actually care about sending
 ///     and receiving coins but rather, just want to explore the network data structures.
 /// </summary>
 /// <exception cref="BitcoinSharp.Blockchain.Store.BlockStoreException" />
 public BlockChain(NetworkParameters networkParameters, IBlockStore blockStore)
     : this(networkParameters, new List<IDefaultWallet>(), blockStore)
 {
 }
Example #54
0
 /// <summary>
 /// Constructs a BlockChain that has no wallet at all. This is helpful when you don't actually care about sending
 /// and receiving coins but rather, just want to explore the network data structures.
 /// </summary>
 /// <exception cref="BlockStoreException"/>
 public BlockChain(NetworkParameters @params, IBlockStore blockStore)
     : this(@params, new List <Wallet>(), blockStore)
 {
 }
Example #55
0
        public void SetUp()
        {
            _testNetChainBlockStore = new MemoryBlockStore(_testNet);
            _testNetChain = new BlockChain(_testNet, new DefaultWallet(_testNet), _testNetChainBlockStore);
            _unitTestParams = NetworkParameters.UnitTests();
            _defaultWallet = new DefaultWallet(_unitTestParams);
            _defaultWallet.AddKey(new EcKey());

            ResetBlockStore();
            _chain = new BlockChain(_unitTestParams, _defaultWallet, _blockStore);

            _coinbaseTo = _defaultWallet.Keychain[0].ToAddress(_unitTestParams);
        }
 /// <exception cref="BlockStoreException"/>
 public static Block MakeSolvedTestBlock(NetworkParameters @params, IBlockStore blockStore)
 {
     var b = blockStore.GetChainHead().Header.CreateNextBlock(new EcKey().ToAddress(@params));
     b.Solve();
     return b;
 }
Example #57
0
 /// <summary>
 /// Given a block store, looks up the previous block in this chain. Convenience method for doing
 /// <tt>store.get(this.getHeader().getPrevBlockHash())</tt>.
 /// </summary>
 /// <returns>The previous block in the chain or null if it was not found in the store.</returns>
 /// <exception cref="BlockStoreException"/>
 public StoredBlock GetPrev(IBlockStore store)
 {
     return store.Get(Header.PrevBlockHash);
 }
 /// <exception cref="BlockStoreException"/>
 public static Block MakeTestBlock(NetworkParameters @params, IBlockStore blockStore)
 {
     return blockStore.GetChainHead().Header.CreateNextBlock(new EcKey().ToAddress(@params));
 }
 public ColdStakingManagerTest(WalletFixture walletFixture)
 {
     this.blockStore    = new Mock <IBlockStore>().Object;
     this.walletFixture = walletFixture;
     this.Network.StandardScriptsRegistry.RegisterStandardScriptTemplate(ColdStakingScriptTemplate.Instance);
 }
 public WalletSyncManagerOverride(ILoggerFactory loggerFactory, IWalletManager walletManager, ConcurrentChain chain,
                                  Network network, IBlockStore blockStore, StoreSettings storeSettings, INodeLifetime nodeLifetime)
     : base(loggerFactory, walletManager, chain, network, blockStore, storeSettings, nodeLifetime)
 {
 }