示例#1
0
        public FederatedPegFeature(
            ILoggerFactory loggerFactory,
            IConnectionManager connectionManager,
            IFederatedPegSettings federatedPegSettings,
            IFullNode fullNode,
            IFederationWalletManager federationWalletManager,
            IFederationWalletSyncManager walletSyncManager,
            Network network,
            ChainIndexer chainIndexer,
            INodeStats nodeStats,
            ICrossChainTransferStore crossChainTransferStore,
            IPartialTransactionRequester partialTransactionRequester,
            ISignedMultisigTransactionBroadcaster signedBroadcaster,
            IMaturedBlocksSyncManager maturedBlocksSyncManager,
            IWithdrawalHistoryProvider withdrawalHistoryProvider,
            ICollateralChecker collateralChecker = null)
        {
            this.loggerFactory           = loggerFactory;
            this.connectionManager       = connectionManager;
            this.federatedPegSettings    = federatedPegSettings;
            this.fullNode                = fullNode;
            this.chainIndexer            = chainIndexer;
            this.federationWalletManager = federationWalletManager;
            this.walletSyncManager       = walletSyncManager;
            this.network = network;
            this.crossChainTransferStore     = crossChainTransferStore;
            this.partialTransactionRequester = partialTransactionRequester;
            this.maturedBlocksSyncManager    = maturedBlocksSyncManager;
            this.withdrawalHistoryProvider   = withdrawalHistoryProvider;
            this.signedBroadcaster           = signedBroadcaster;

            this.logger = loggerFactory.CreateLogger(this.GetType().FullName);

            // add our payload
            var payloadProvider = (PayloadProvider)this.fullNode.Services.ServiceProvider.GetService(typeof(PayloadProvider));

            payloadProvider.AddPayload(typeof(RequestPartialTransactionPayload));

            nodeStats.RegisterStats(this.AddComponentStats, StatsType.Component);
            nodeStats.RegisterStats(this.AddInlineStats, StatsType.Inline, 800);
        }
示例#2
0
        public void GetStakingInfo_StartStaking()
        {
            IFullNode fullNode = StratisBitcoinPosRunner.BuildStakingNode(TestBase.CreateTestDir(this), false);
            var       node     = fullNode as FullNode;

            Task fullNodeRunTask = fullNode.RunAsync();

            var nodeLifetime = fullNode.NodeService <INodeLifetime>();

            nodeLifetime.ApplicationStarted.WaitHandle.WaitOne();
            var controller = fullNode.Services.ServiceProvider.GetService <MiningRPCController>();

            var walletManager = node.NodeService <IWalletManager>() as WalletManager;

            string password = "******";

            // create the wallet
            walletManager.CreateWallet(password, "test");

            Assert.NotNull(fullNode.NodeService <IPosMinting>(true));

            GetStakingInfoModel info = controller.GetStakingInfo();

            Assert.NotNull(info);
            Assert.False(info.Enabled);
            Assert.False(info.Staking);

            controller.StartStaking("test", "test");

            info = controller.GetStakingInfo();

            Assert.NotNull(info);
            Assert.True(info.Enabled);
            Assert.False(info.Staking);

            nodeLifetime.StopApplication();
            nodeLifetime.ApplicationStopped.WaitHandle.WaitOne();
            fullNode.Dispose();

            Assert.False(fullNodeRunTask.IsFaulted);
        }
示例#3
0
        public static async Task MainAsync(string[] args)
        {
            try
            {
                var nodeSettings = new NodeSettings(networksSelector: CirrusNetwork.NetworksSelector, protocolVersion: ProtocolVersion.CIRRUS_VERSION, args: args)
                {
                    MinProtocolVersion = ProtocolVersion.ALT_PROTOCOL_VERSION
                };

                IFullNode node = GetSideChainFullNode(nodeSettings);

                if (node != null)
                {
                    await node.RunAsync();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("There was a problem initializing the node. Details: '{0}'", ex.Message);
            }
        }
示例#4
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;
        }
示例#5
0
        /// <summary>
        /// Installs handlers for graceful shutdown in the console, starts a full node and waits until it terminates.
        /// </summary>
        /// <param name="node">Full node to run.</param>
        /// <returns><placeholder>A <see cref="Task"/> representing the asynchronous operation.</placeholder></returns>
        async Task RunAsync(IFullNode node)
        {
            var done = new ManualResetEventSlim(false);

            using (var cts = new CancellationTokenSource())
            {
                Action shutdown = () =>
                {
                    if (!cts.IsCancellationRequested)
                    {
                        Console.WriteLine(@"Application is shutting down.");
                        try
                        {
                            cts.Cancel();
                        }
                        catch (ObjectDisposedException exception)
                        {
                            Console.WriteLine(exception.Message);
                        }
                    }

                    done.Wait();
                };

                FullNodeStopRequested += (sender, eventArgs) =>
                {
                    shutdown();
                };

                try
                {
                    await node.RunAsync(cts.Token).ConfigureAwait(false);
                }
                finally
                {
                    done.Set();
                    _fullNode = null;
                }
            }
        }
        public void CanHaveAllFullnodeServicesTest()
        {
            // This test is put in the mempool feature because the
            // mempool requires all the features to be a fullnode.

            var nodeSettings = new NodeSettings(KnownNetworks.TestNet, args: new string[] {
                $"-datadir=Blockcore.Features.MemoryPool.Tests/TestData/FullNodeBuilderTest/CanHaveAllServicesTest"
            });

            var persistenceManager = new TestPersistenceProviderManager(nodeSettings);

            var       fullNodeBuilder = new FullNodeBuilder(nodeSettings, persistenceManager);
            IFullNode fullNode        = fullNodeBuilder
                                        .UseBlockStore()
                                        .UsePowConsensus()
                                        .UseMempool()
                                        .Build();

            IServiceProvider serviceProvider = fullNode.Services.ServiceProvider;
            var network             = serviceProvider.GetService <Network>();
            var settings            = serviceProvider.GetService <NodeSettings>();
            var consensusManager    = serviceProvider.GetService <IConsensusManager>() as ConsensusManager;
            var chain               = serviceProvider.GetService <ChainIndexer>();
            var chainState          = serviceProvider.GetService <IChainState>() as ChainState;
            var consensusRuleEngine = serviceProvider.GetService <IConsensusRuleEngine>();

            consensusRuleEngine.SetupRulesEngineParent();
            var mempoolManager    = serviceProvider.GetService <MempoolManager>();
            var connectionManager = serviceProvider.GetService <IConnectionManager>() as ConnectionManager;

            Assert.NotNull(fullNode);
            Assert.NotNull(network);
            Assert.NotNull(settings);
            Assert.NotNull(consensusManager);
            Assert.NotNull(chain);
            Assert.NotNull(chainState);
            Assert.NotNull(consensusRuleEngine);
            Assert.NotNull(mempoolManager);
            Assert.NotNull(connectionManager);
        }
示例#7
0
        public void CanCall_AddNode_AddsNodeToCollection()
        {
            var initialBlockSignature = Block.BlockSignature;

            try
            {
                Block.BlockSignature = false;
                string testDirectory = CreateTestDir(this);

                IFullNode fullNode = this.BuildServicedNode(testDirectory);

                ConnectionManagerController controller = fullNode.Services.ServiceProvider.GetService <ConnectionManagerController>();

                var connectionManager = fullNode.NodeService <IConnectionManager>();
                controller.AddNode("0.0.0.0", "add");
                Assert.Single(connectionManager.ConnectionSettings.AddNode);
            }
            finally
            {
                Block.BlockSignature = initialBlockSignature;
            }
        }
        /// <summary>
        /// Starts a full node, sets up cancellation tokens for its shutdown, and waits until it terminates.
        /// </summary>
        /// <param name="node">Full node to run.</param>
        /// <param name="cancellationToken">Cancellation token that triggers when the node should be shut down.</param>
        /// <param name="shutdownMessage">Message to display on the console to instruct the user on how to invoke the shutdown.</param>
        /// <param name="shutdownCompleteMessage">Message to display on the console when the shutdown is complete.</param>
        public static void Run(this IFullNode node, CancellationToken cancellationToken, string shutdownMessage, string shutdownCompleteMessage)
        {
            using (node)
            {
                node.Start();

                if (!string.IsNullOrEmpty(shutdownMessage))
                {
                    Console.WriteLine();
                    Console.WriteLine(shutdownMessage);
                    Console.WriteLine();
                }

                cancellationToken.Register(state =>
                {
                    ((INodeLifetime)state).StopApplication();
                },
                                           node.NodeLifetime);

                var waitForStop = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);
                node.NodeLifetime.ApplicationStopping.Register(obj =>
                {
                    var tcs = (TaskCompletionSource <object>)obj;
                    tcs.TrySetResult(null);
                }, waitForStop);

                //await waitForStop.Task;
                waitForStop.Task.GetAwaiter().GetResult();

                node.Stop();

                if (!string.IsNullOrEmpty(shutdownCompleteMessage))
                {
                    Console.WriteLine();
                    Console.WriteLine(shutdownCompleteMessage);
                    Console.WriteLine();
                }
            }
        }
        /// <summary>
        /// Installs handlers for graceful shutdown in the console, starts a full node and waits until it terminates.
        /// </summary>
        /// <param name="node">Full node to run.</param>
        public static async Task RunAsync(this IFullNode node)
        {
            var done = new ManualResetEventSlim(false);

            using (CancellationTokenSource cts = new CancellationTokenSource())
            {
                Action shutdown = () =>
                {
                    if (!cts.IsCancellationRequested)
                    {
                        Console.WriteLine("Application is shutting down...");
                        try
                        {
                            cts.Cancel();
                        }
                        catch (ObjectDisposedException exception)
                        {
                            Console.WriteLine(exception.Message);
                        }
                    }

                    done.Wait();
                };
#if !NOASSEMBLYCONTEXT
                var assemblyLoadContext = AssemblyLoadContext.GetLoadContext(typeof(FullNode).GetTypeInfo().Assembly);
                assemblyLoadContext.Unloading += context => shutdown();
#endif
                Console.CancelKeyPress += (sender, eventArgs) =>
                {
                    shutdown();
                    // Don't terminate the process immediately, wait for the Main thread to exit gracefully.
                    eventArgs.Cancel = true;
                };

                await node.RunAsync(cts.Token, "Application started. Press Ctrl+C to shut down.", "Application stopped.").ConfigureAwait(false);

                done.Set();
            }
        }
        public void CanHaveAllFullnodeServicesTest()
        {
            // This test is put in the mempool feature because the
            // mempool requires all the features to be a fullnode


            NodeSettings nodeSettings = new NodeSettings(args: new string[] {
                $"-datadir=Stratis.Bitcoin.Features.MemoryPool.Tests/TestData/FullNodeBuilderTest/CanHaveAllServicesTest"
            });
            var       fullNodeBuilder = new FullNodeBuilder(nodeSettings);
            IFullNode fullNode        = fullNodeBuilder
                                        .UseBlockStore()
                                        .UsePowConsensus()
                                        .UseMempool()
                                        .Build();

            IServiceProvider serviceProvider = fullNode.Services.ServiceProvider;
            var network           = serviceProvider.GetService <Network>();
            var settings          = serviceProvider.GetService <NodeSettings>();
            var consensusLoop     = serviceProvider.GetService <IConsensusLoop>() as ConsensusLoop;
            var chain             = serviceProvider.GetService <NBitcoin.ConcurrentChain>();
            var chainState        = serviceProvider.GetService <IChainState>() as ChainState;
            var blockStoreManager = serviceProvider.GetService <BlockStoreManager>();
            var consensusRules    = serviceProvider.GetService <IConsensusRules>();

            consensusRules.Register(serviceProvider.GetService <IRuleRegistration>());
            var mempoolManager    = serviceProvider.GetService <MempoolManager>();
            var connectionManager = serviceProvider.GetService <IConnectionManager>() as ConnectionManager;

            Assert.NotNull(fullNode);
            Assert.NotNull(network);
            Assert.NotNull(settings);
            Assert.NotNull(consensusLoop);
            Assert.NotNull(chain);
            Assert.NotNull(chainState);
            Assert.NotNull(blockStoreManager);
            Assert.NotNull(mempoolManager);
            Assert.NotNull(connectionManager);
        }
        public void BuildWithInitialServicesSetupConfiguresFullNodeUsingConfiguration()
        {
            string dataDir      = "TestData/FullNodeBuilder/BuildWithInitialServicesSetup";
            var    nodeSettings = new NodeSettings(KnownNetworks.StratisRegTest, args: new string[] { $"-datadir={dataDir}" });

            this.fullNodeBuilder = new FullNodeBuilder(nodeSettings, this.serviceCollectionDelegates, this.serviceProviderDelegates, this.featureCollectionDelegates, this.featureCollection);

            this.fullNodeBuilder.ConfigureServices(e =>
            {
                e.AddSingleton <FullNode>();
                e.AddSingleton(nodeSettings.LoggerFactory);
            });

            this.fullNodeBuilder.ConfigureFeature(e =>
            {
                e.AddFeature <DummyFeature>();
            });

            IFullNode result = this.fullNodeBuilder.UsePosConsensus().Build();

            Assert.NotNull(result);
        }
        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 FullNodeController(
     IFullNode fullNode                             = null,
     NodeSettings nodeSettings                      = null,
     Network network                                = null,
     ConsensusValidator consensusValidator          = null,
     ConcurrentChain chain                          = null,
     ChainBehavior.ChainState chainState            = null,
     BlockStoreManager blockManager                 = null,
     MempoolManager mempoolManager                  = null,
     Connection.ConnectionManager connectionManager = null)
     : base(
         fullNode: fullNode,
         nodeSettings: nodeSettings,
         network: network,
         consensusValidator: consensusValidator,
         chain: chain,
         chainState: chainState,
         blockManager: blockManager,
         mempoolManager: mempoolManager,
         connectionManager: connectionManager)
 {
 }
        public void CanHaveAllFullnodeServicesTest()
        {
            // This test is put in the mempool feature because the
            // mempool requires all the features to be a fullnode


            var nodeSettings = NodeSettings.Default();

            nodeSettings.DataDir = "Stratis.Bitcoin.Features.MemoryPool.Tests/TestData/FullNodeBuilderTest/CanHaveAllServicesTest";
            var       fullNodeBuilder = new FullNodeBuilder(nodeSettings);
            IFullNode fullNode        = fullNodeBuilder
                                        .UseConsensus()
                                        .UseBlockStore()
                                        .UseMempool()
                                        .Build();

            IServiceProvider serviceProvider = fullNode.Services.ServiceProvider;
            var network           = serviceProvider.GetService <Network>();
            var settings          = serviceProvider.GetService <NodeSettings>();
            var consensusLoop     = serviceProvider.GetService <IConsensusLoop>() as ConsensusLoop;
            var consensus         = serviceProvider.GetService <IPowConsensusValidator>() as PowConsensusValidator;
            var chain             = serviceProvider.GetService <NBitcoin.ConcurrentChain>();
            var chainState        = serviceProvider.GetService <IChainState>() as ChainState;
            var blockStoreManager = serviceProvider.GetService <BlockStoreManager>();
            var mempoolManager    = serviceProvider.GetService <MempoolManager>();
            var connectionManager = serviceProvider.GetService <IConnectionManager>() as ConnectionManager;

            Assert.NotNull(fullNode);
            Assert.NotNull(network);
            Assert.NotNull(settings);
            Assert.NotNull(consensusLoop);
            Assert.NotNull(consensus);
            Assert.NotNull(chain);
            Assert.NotNull(chainState);
            Assert.NotNull(blockStoreManager);
            Assert.NotNull(mempoolManager);
            Assert.NotNull(connectionManager);
        }
示例#15
0
        public FederatedPegFeature(
            IConnectionManager connectionManager,
            IFederatedPegSettings federatedPegSettings,
            IFullNode fullNode,
            IFederationWalletManager federationWalletManager,
            IFederationWalletSyncManager walletSyncManager,
            Network network,
            INodeStats nodeStats,
            ICrossChainTransferStore crossChainTransferStore,
            IPartialTransactionRequester partialTransactionRequester,
            MempoolCleaner mempoolCleaner,
            ISignedMultisigTransactionBroadcaster signedBroadcaster,
            IMaturedBlocksSyncManager maturedBlocksSyncManager,
            IInputConsolidator inputConsolidator,
            ICollateralChecker collateralChecker = null)
        {
            this.connectionManager       = connectionManager;
            this.federatedPegSettings    = federatedPegSettings;
            this.fullNode                = fullNode;
            this.federationWalletManager = federationWalletManager;
            this.walletSyncManager       = walletSyncManager;
            this.network = network;
            this.crossChainTransferStore     = crossChainTransferStore;
            this.partialTransactionRequester = partialTransactionRequester;
            this.mempoolCleaner           = mempoolCleaner;
            this.maturedBlocksSyncManager = maturedBlocksSyncManager;
            this.signedBroadcaster        = signedBroadcaster;
            this.inputConsolidator        = inputConsolidator;

            this.logger = LogManager.GetCurrentClassLogger();

            // add our payload
            var payloadProvider = (PayloadProvider)this.fullNode.Services.ServiceProvider.GetService(typeof(PayloadProvider));

            payloadProvider.AddPayload(typeof(RequestPartialTransactionPayload));

            nodeStats.RegisterStats(this.AddComponentStats, StatsType.Component, this.GetType().Name);
        }
        public BlockObserverTests()
        {
            this.minimumDepositConfirmations = 10;

            this.federationGatewaySettings = Substitute.For <IFederationGatewaySettings>();
            this.federationGatewaySettings.MinimumDepositConfirmations.Returns(this.minimumDepositConfirmations);

            this.federationWalletSyncManager = Substitute.For <IFederationWalletSyncManager>();
            this.fullNode = Substitute.For <IFullNode>();
            this.federationGatewayClient = Substitute.For <IFederationGatewayClient>();
            this.chain = Substitute.ForPartsOf <ConcurrentChain>();
            this.fullNode.NodeService <ConcurrentChain>().Returns(this.chain);
            this.loggerFactory        = Substitute.For <ILoggerFactory>();
            this.opReturnDataReader   = Substitute.For <IOpReturnDataReader>();
            this.consensusManager     = Substitute.For <IConsensusManager>();
            this.withdrawalExtractor  = Substitute.For <IWithdrawalExtractor>();
            this.extractedWithdrawals = TestingValues.GetWithdrawals(2);
            this.withdrawalExtractor.ExtractWithdrawalsFromBlock(null, 0).ReturnsForAnyArgs(this.extractedWithdrawals);

            this.withdrawalReceiver = Substitute.For <IWithdrawalReceiver>();

            this.signals = Substitute.For <ISignals>();
            this.signals.OnBlockConnected.Returns(Substitute.For <EventNotifier <ChainedHeaderBlock> >());

            this.depositExtractor = new DepositExtractor(
                this.loggerFactory,
                this.federationGatewaySettings,
                this.opReturnDataReader,
                this.fullNode);

            this.blockObserver = new BlockObserver(
                this.federationWalletSyncManager,
                this.depositExtractor,
                this.withdrawalExtractor,
                this.withdrawalReceiver,
                this.federationGatewayClient,
                this.signals);
        }
示例#17
0
        public static async Task MainAsync(string[] args)
        {
            try
            {
                // set the console window title to identify this as a Cirrus full node (for clarity when running Strax and Cirrus on the same machine)
                Console.Title = "Cirrus Full Node";
                var nodeSettings = new NodeSettings(networksSelector: CirrusNetwork.NetworksSelector, protocolVersion: ProtocolVersion.CIRRUS_VERSION, args: args)
                {
                    MinProtocolVersion = ProtocolVersion.ALT_PROTOCOL_VERSION
                };

                IFullNode node = GetSideChainFullNode(nodeSettings);

                if (node != null)
                {
                    await node.RunAsync();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("There was a problem initializing the node. Details: '{0}'", ex.Message);
            }
        }
        public DepositExtractorTests()
        {
            this.network = FederatedPegNetwork.NetworksSelector.Regtest();

            this.loggerFactory      = Substitute.For <ILoggerFactory>();
            this.settings           = Substitute.For <IFederationGatewaySettings>();
            this.opReturnDataReader = Substitute.For <IOpReturnDataReader>();
            this.fullNode           = Substitute.For <IFullNode>();
            this.fullNode.NodeService <ConcurrentChain>().Returns(this.chain);

            this.addressHelper = new MultisigAddressHelper(this.network);

            this.settings.MultiSigRedeemScript.Returns(this.addressHelper.PayToMultiSig);
            this.opReturnDataReader.TryGetTargetAddress(null, out string address).Returns(callInfo => { callInfo[1] = null; return(false); });

            this.transactionBuilder = new TestTransactionBuilder();

            this.depositExtractor = new DepositExtractor(
                this.loggerFactory,
                this.settings,
                this.opReturnDataReader,
                this.fullNode);
        }
        public void CallWithDependencies()
        {
            string             dir        = AssureEmptyDir("Stratis.Bitcoin.Tests/TestData/GetInfoActionTests/CallWithDependencies");
            IFullNode          fullNode   = this.BuildServicedNode(dir);
            FullNodeController controller = fullNode.Services.ServiceProvider.GetService <FullNodeController>();

            GetInfoModel info = controller.GetInfo();

            uint expectedProtocolVersion = (uint)NodeSettings.Default().ProtocolVersion;
            var  expectedRelayFee        = MempoolValidator.MinRelayTxFee.FeePerK.ToUnit(NBitcoin.MoneyUnit.BTC);

            Assert.NotNull(info);
            Assert.Equal(0, info.blocks);
            Assert.NotEqual <uint>(0, info.version);
            Assert.Equal(expectedProtocolVersion, info.protocolversion);
            Assert.Equal(0, info.timeoffset);
            Assert.Equal(0, info.connections);
            Assert.NotNull(info.proxy);
            Assert.Equal(0, info.difficulty);
            Assert.False(info.testnet);
            Assert.Equal(expectedRelayFee, info.relayfee);
            Assert.Empty(info.errors);
        }
示例#20
0
        public static async Task MainAsync(string[] args)
        {
            try
            {
                if (!args.Any(a => a.Contains("apiport")))
                {
                    args = args.Concat(new[] { "apiport=38225" }).ToArray();
                }

                var nodeSettings = new NodeSettings(networksSelector: FederatedPegNetwork.NetworksSelector, protocolVersion: ProtocolVersion.ALT_PROTOCOL_VERSION, args: args);

                IFullNode node = GetFederatedPegFullNode(nodeSettings);

                if (node != null)
                {
                    await node.RunAsync();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("There was a problem initializing the node. Details: '{0}'", ex.Message);
            }
        }
        public void BuildConfiguresFullNodeUsingConfiguration()
        {
            string dataDir      = "TestData/FullNodeBuilder/BuildConfiguresFullNodeUsingConfiguration";
            var    nodeSettings = new NodeSettings(args: new string[] { $"-datadir={dataDir}" });

            this.fullNodeBuilder.ConfigureServices(e =>
            {
                e.AddSingleton(nodeSettings);
                e.AddSingleton(nodeSettings.LoggerFactory);
                e.AddSingleton(nodeSettings.Network);
                e.AddSingleton <FullNode>();
                e.AddSingleton <IDateTimeProvider, DateTimeProvider>();
            });

            this.fullNodeBuilder.ConfigureFeature(e =>
            {
                e.AddFeature <DummyFeature>();
            });

            IFullNode result = this.fullNodeBuilder.Build();

            Assert.NotNull(result);
        }
 public BaseRPCController(
     IFullNode fullNode        = null,
     NodeSettings nodeSettings = null,
     Network network           = null,
     PowConsensusValidator consensusValidator = null,
     ConsensusLoop consensusLoop    = null,
     ConcurrentChain chain          = null,
     ChainState chainState          = null,
     BlockStoreManager blockManager = null,
     MempoolManager mempoolManager  = null,
     Connection.IConnectionManager connectionManager = null)
 {
     this.FullNode           = fullNode;
     this.Settings           = nodeSettings;
     this.Network            = network;
     this.ConsensusValidator = consensusValidator;
     this.ConsensusLoop      = consensusLoop;
     this.Chain             = chain;
     this.ChainState        = chainState;
     this.BlockManager      = blockManager;
     this.MempoolManager    = mempoolManager;
     this.ConnectionManager = connectionManager;
 }
示例#23
0
        public void CanCall_AddNode()
        {
            var initialBlockSignature = Block.BlockSignature;

            try
            {
                Block.BlockSignature = false;
                string testDirectory = CreateTestDir(this);


                IFullNode fullNode = this.BuildServicedNode(testDirectory);
                ConnectionManagerController controller = fullNode.Services.ServiceProvider.GetService <ConnectionManagerController>();

                Assert.ThrowsAny <System.Net.Sockets.SocketException>(() => { controller.AddNode("0.0.0.0", "onetry"); });
                Assert.Throws <ArgumentException>(() => { controller.AddNode("0.0.0.0", "notarealcommand"); });
                Assert.Throws <FormatException>(() => { controller.AddNode("a.b.c.d", "onetry"); });
                Assert.True(controller.AddNode("0.0.0.0", "remove"));
            }
            finally
            {
                Block.BlockSignature = initialBlockSignature;
            }
        }
示例#24
0
 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;
 }
        public static void Run(this IFullNode node)
        {
            var done = new ManualResetEventSlim(false);

            using (CancellationTokenSource cts = new CancellationTokenSource())
            {
                Action shutdown = () =>
                {
                    if (!cts.IsCancellationRequested)
                    {
                        Logs.FullNode.LogInformation("Application is shutting down...");
                        try
                        {
                            cts.Cancel();
                        }
                        catch (ObjectDisposedException exception)
                        {
                            Logs.FullNode.LogError(exception.Message);
                        }
                    }

                    done.Wait();
                };

                var assemblyLoadContext = AssemblyLoadContext.GetLoadContext(typeof(FullNode).GetTypeInfo().Assembly);
                assemblyLoadContext.Unloading += context => shutdown();
                Console.CancelKeyPress        += (sender, eventArgs) =>
                {
                    shutdown();
                    // Don't terminate the process immediately, wait for the Main thread to exit gracefully.
                    eventArgs.Cancel = true;
                };

                node.Run(cts.Token, "Application started. Press Ctrl+C to shut down.");
                done.Set();
            }
        }
示例#26
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;
 }
示例#27
0
        /// <summary>
        /// Starts a full node, sets up cancellation tokens for its shutdown, and waits until it terminates.
        /// </summary>
        /// <param name="node">Full node to run.</param>
        /// <param name="cancellationToken">Cancellation token that triggers when the node should be shut down.</param>
        public static async Task RunAsync(this IFullNode node, CancellationToken cancellationToken)
        {
            // node.NodeLifetime is not initialized yet. Use this temporary variable as to avoid side-effects to node.
            var nodeLifetime = node.Services.ServiceProvider.GetRequiredService <INodeLifetime>() as NodeLifetime;

            cancellationToken.Register(state =>
            {
                ((INodeLifetime)state).StopApplication();
            },
                                       nodeLifetime);

            var waitForStop = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);

            nodeLifetime.ApplicationStopping.Register(obj =>
            {
                var tcs = (TaskCompletionSource <object>)obj;
                tcs.TrySetResult(null);
            }, waitForStop);

            Console.WriteLine();
            Console.WriteLine("Application starting, press Ctrl+C to cancel.");
            Console.WriteLine();

            node.Start();

            Console.WriteLine();
            Console.WriteLine("Application started, press Ctrl+C to stop.");
            Console.WriteLine();

            await waitForStop.Task.ConfigureAwait(false);

            node.Dispose();

            Console.WriteLine();
            Console.WriteLine("Application stopped.");
            Console.WriteLine();
        }
示例#28
0
        public static async Task MainAsync(string[] args)
        {
            try
            {
                bool isMainchainNode = args.FirstOrDefault(a => a.ToLower() == MainchainArgument) != null;
                bool isSidechainNode = args.FirstOrDefault(a => a.ToLower() == SidechainArgument) != null;
                bool startInDevMode  = args.Any(a => a.ToLower().Contains($"-{NodeSettings.DevModeParam}"));

                IFullNode fullNode = null;

                if (startInDevMode)
                {
                    fullNode = BuildDevCirrusMiningNode(args);
                }
                else
                {
                    if (isSidechainNode == isMainchainNode)
                    {
                        throw new ArgumentException($"Gateway node needs to be started specifying either a {SidechainArgument} or a {MainchainArgument} argument");
                    }

                    fullNode = isMainchainNode ? BuildStraxNode(args) : BuildCirrusMiningNode(args);

                    // set the console window title to identify which node this is (for clarity when running Strax and Cirrus on the same machine)
                    Console.Title = isMainchainNode ? $"Strax Full Node {fullNode.Network.NetworkType}" : $"Cirrus Full Node {fullNode.Network.NetworkType}";
                }

                if (fullNode != null)
                {
                    await fullNode.RunAsync();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("There was a problem initializing the node. Details: '{0}'", ex.Message);
            }
        }
示例#29
0
        public FederationGatewayFeature(
            ILoggerFactory loggerFactory,
            ICrossChainTransactionMonitor crossChainTransactionMonitor,
            Signals signals,
            IConnectionManager connectionManager,
            FederationGatewaySettings federationGatewaySettings,
            IFullNode fullNode,
            IFederationWalletManager federationWalletManager,
            IFederationWalletSyncManager walletSyncManager,
            Network network,
            ConcurrentChain chain,
            IMonitorChainSessionManager monitorChainSessionManager,
            ICounterChainSessionManager counterChainSessionManager,
            INodeStats nodeStats)
        {
            this.loggerFactory = loggerFactory;
            this.crossChainTransactionMonitor = crossChainTransactionMonitor;
            this.signals                   = signals;
            this.connectionManager         = connectionManager;
            this.federationGatewaySettings = federationGatewaySettings;
            this.fullNode                  = fullNode;
            this.chain = chain;
            this.federationWalletManager = federationWalletManager;
            this.walletSyncManager       = walletSyncManager;
            this.network = network;

            this.counterChainSessionManager = counterChainSessionManager;
            this.monitorChainSessionManager = monitorChainSessionManager;

            // add our payload
            var payloadProvider = (PayloadProvider)this.fullNode.Services.ServiceProvider.GetService(typeof(PayloadProvider));

            payloadProvider.AddPayload(typeof(RequestPartialTransactionPayload));

            nodeStats.RegisterStats(this.AddComponentStats, StatsType.Component);
            nodeStats.RegisterStats(this.AddInlineStats, StatsType.Inline, 800);
        }
        public void GetStakingInfo_StakingEnabled()
        {
            IFullNode fullNode        = StratisBitcoinPosRunner.BuildStakingNode(TestBase.CreateTestDir(this));
            Task      fullNodeRunTask = fullNode.RunAsync();

            var nodeLifetime = fullNode.NodeService <INodeLifetime>();

            nodeLifetime.ApplicationStarted.WaitHandle.WaitOne();
            var controller = fullNode.NodeController <StakingRpcController>();

            Assert.NotNull(fullNode.NodeService <IPosMinting>(true));

            GetStakingInfoModel info = controller.GetStakingInfo();

            Assert.NotNull(info);
            Assert.True(info.Enabled);
            Assert.False(info.Staking);

            nodeLifetime.StopApplication();
            nodeLifetime.ApplicationStopped.WaitHandle.WaitOne();
            fullNode.Dispose();

            Assert.False(fullNodeRunTask.IsFaulted);
        }