public PeerAddressManagerBehaviourTests()
        {
            this.extendedLoggerFactory     = ExtendedLoggerFactory.Create();
            this.connectionManagerSettings = new ConnectionManagerSettings(NodeSettings.Default(this.Network));
            this.signals       = new Bitcoin.Signals.Signals(this.extendedLoggerFactory, null);
            this.asyncProvider = new AsyncProvider(this.extendedLoggerFactory, this.signals);

            this.networkPeerFactory = new NetworkPeerFactory(this.Network,
                                                             DateTimeProvider.Default,
                                                             this.extendedLoggerFactory,
                                                             new PayloadProvider().DiscoverPayloads(),
                                                             new SelfEndpointTracker(this.extendedLoggerFactory, this.connectionManagerSettings),
                                                             new Mock <IInitialBlockDownloadState>().Object,
                                                             this.connectionManagerSettings,
                                                             this.asyncProvider,
                                                             new Mock <IPeerAddressManager>().Object);
        }
        public void CompatibileNodesStayConnectedAfterHardFork()
        {
            // Set the hard-fork parameters.
            this.Network.Consensus.Options.EnforceMinProtocolVersionAtBlockHeight = 5;
            this.Network.Consensus.Options.EnforcedMinProtocolVersion             = ProtocolVersion.CIRRUS_VERSION;

            // Configure local node version.
            var nodeSettings = NodeSettings.Default(this.Network, ProtocolVersion.CIRRUS_VERSION);

            nodeSettings.MinProtocolVersion = ProtocolVersion.ALT_PROTOCOL_VERSION;

            // Create the ChainIndexer.
            var chain = new ChainIndexer(this.Network);

            // Create behaviour using the test wraper which exposes protected properties and methods
            ILoggerFactory loggerFactory = ExtendedLoggerFactory.Create();
            EnforcePeerVersionCheckBehaviorWrapper behavior = new EnforcePeerVersionCheckBehaviorWrapper(chain, nodeSettings, this.Network, loggerFactory);

            // Intentionally set Peer Version to 0 as its value it shouldn't be used anythere in the test.
            var localPeer = CreateNetworkPeer(0);

            behavior.Attach(localPeer);

            var remotePeer = CreateNetworkPeer(ProtocolVersion.CIRRUS_VERSION);

            // Set the initial block height to 1.
            for (int i = 0; i < 4; i++)
            {
                this.AppendBlock(chain);
                behavior.TestOnMessageReceivedAsync(remotePeer, null);
                Assert.Equal(NetworkPeerState.Connected, localPeer.State);
            }

            // Nodes shouldn't disconnect when reaching and exceeding the EnforceMinProtocolVersionAtBlockHeight height.
            for (int i = 0; i < 5; i++)
            {
                this.AppendBlock(chain);
                behavior.TestOnMessageReceivedAsync(remotePeer, null);
                Assert.Equal(NetworkPeerState.Connected, localPeer.State);
            }

            // New connections established after the hard-fork should not be disconnected.
            remotePeer = CreateNetworkPeer(ProtocolVersion.CIRRUS_VERSION);
            behavior.TestOnMessageReceivedAsync(remotePeer, null);
            Assert.Equal(NetworkPeerState.Connected, localPeer.State);
        }
        public void PeerBanning_Resetting_Expired_BannedPeer()
        {
            DataFolder dataFolder = CreateDataFolder(this);

            var loggerFactory = new ExtendedLoggerFactory();

            loggerFactory.AddConsoleWithFilters();

            IPAddress ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var       endpoint  = new IPEndPoint(ipAddress, 80);

            var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, dataFolder, loggerFactory, new Mock <ISelfEndpointTracker>().Object);

            peerAddressManager.AddPeer(endpoint, IPAddress.Loopback);

            var nodeSettings = new NodeSettings(new StratisRegTest());
            var connectionManagerSettings = new ConnectionManagerSettings(nodeSettings);

            var peerCollection = new Mock <IReadOnlyNetworkPeerCollection>();

            peerCollection.Setup(p => p.FindByIp(It.IsAny <IPAddress>())).Returns(new List <INetworkPeer>());

            var connectionManager = new Mock <IConnectionManager>();

            connectionManager.Setup(c => c.ConnectionSettings).Returns(connectionManagerSettings);
            connectionManager.Setup(c => c.ConnectedPeers).Returns(peerCollection.Object);

            var peerBanning = new PeerBanning(connectionManager.Object, loggerFactory, DateTimeProvider.Default, peerAddressManager);

            peerBanning.BanAndDisconnectPeer(endpoint, 1, nameof(PeerBanningTest));

            peerAddressManager.SavePeers();

            // Wait one second for ban to expire.
            Thread.Sleep(1000);

            peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, dataFolder, loggerFactory, new Mock <ISelfEndpointTracker>().Object);
            peerAddressManager.LoadPeers();

            PeerAddress peer = peerAddressManager.FindPeer(endpoint);

            Assert.Null(peer.BanTimeStamp);
            Assert.Null(peer.BanUntil);
            Assert.Empty(peer.BanReason);
        }
        public void PeerBanning_Add_Peers_To_Address_Manager_And_Ban_IP_Range()
        {
            var dataFolder = CreateDataFolder(this);

            var loggerFactory = ExtendedLoggerFactory.Create();

            var ipAddress80 = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint80  = new IPEndPoint(ipAddress80, 80);

            var ipAddress81 = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint81  = new IPEndPoint(ipAddress81, 81);

            var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, dataFolder, loggerFactory, new Mock <ISelfEndpointTracker>().Object);

            peerAddressManager.AddPeer(endpoint80, IPAddress.Loopback);
            peerAddressManager.AddPeer(endpoint81, IPAddress.Loopback);

            var nodeSettings = new NodeSettings(new StratisRegTest());
            var connectionManagerSettings = new ConnectionManagerSettings(nodeSettings);

            var peerCollection = new Mock <IReadOnlyNetworkPeerCollection>();

            peerCollection.Setup(p => p.FindByIp(It.IsAny <IPAddress>())).Returns(new List <INetworkPeer>());

            var connectionManager = new Mock <IConnectionManager>();

            connectionManager.Setup(c => c.ConnectionSettings).Returns(connectionManagerSettings);
            connectionManager.Setup(c => c.ConnectedPeers).Returns(peerCollection.Object);

            var peerBanning = new PeerBanning(connectionManager.Object, loggerFactory, DateTimeProvider.Default, peerAddressManager);

            peerBanning.BanAndDisconnectPeer(endpoint80, connectionManagerSettings.BanTimeSeconds, nameof(PeerBanningTest));

            // Both endpoints should be banned.
            PeerAddress peer = peerAddressManager.FindPeer(endpoint80);

            Assert.True(peer.BanUntil.HasValue);
            Assert.NotNull(peer.BanUntil);
            Assert.NotEmpty(peer.BanReason);

            peer = peerAddressManager.FindPeer(endpoint81);
            Assert.True(peer.BanUntil.HasValue);
            Assert.NotNull(peer.BanUntil);
            Assert.NotEmpty(peer.BanReason);
        }
 public ContractExecutorTestContext()
 {
     this.Network             = new SmartContractsRegTest();
     this.KeyEncodingStrategy = BasicKeyEncodingStrategy.Default;
     this.LoggerFactory       = ExtendedLoggerFactory.Create();
     this.State = new StateRepositoryRoot(new NoDeleteSource <byte[], byte[]>(new MemoryDictionarySource()));
     this.ContractPrimitiveSerializer = new ContractPrimitiveSerializerV2(this.Network);
     this.Serializer             = new Serializer(this.ContractPrimitiveSerializer);
     this.AddressGenerator       = new AddressGenerator();
     this.Validator              = new SmartContractValidator();
     this.AssemblyLoader         = new ContractAssemblyLoader();
     this.ModuleDefinitionReader = new ContractModuleDefinitionReader();
     this.ContractCache          = new ContractAssemblyCache();
     this.Vm                        = new ReflectionVirtualMachine(this.Validator, this.LoggerFactory, this.AssemblyLoader, this.ModuleDefinitionReader, this.ContractCache);
     this.StateProcessor            = new StateProcessor(this.Vm, this.AddressGenerator);
     this.InternalTxExecutorFactory = new InternalExecutorFactory(this.LoggerFactory, this.StateProcessor);
     this.SmartContractStateFactory = new SmartContractStateFactory(this.ContractPrimitiveSerializer, this.InternalTxExecutorFactory, this.Serializer);
 }
        public CoreNode(NodeRunner runner, NodeBuilder builder, Network network, string configfile)
        {
            this.runner = runner;

            this.State = CoreNodeState.Stopped;
            var pass = Encoders.Hex.EncodeData(RandomUtils.GetBytes(20));

            this.creds  = new NetworkCredential(pass, pass);
            this.Config = Path.Combine(this.runner.DataFolder, configfile);
            this.ConfigParameters.Import(builder.ConfigParameters);
            this.ports = new int[2];
            this.FindPorts(this.ports);

            var loggerFactory = new ExtendedLoggerFactory();

            loggerFactory.AddConsoleWithFilters();

            this.networkPeerFactory = new NetworkPeerFactory(network, DateTimeProvider.Default, loggerFactory, new PayloadProvider().DiscoverPayloads(), new SelfEndpointTracker());
        }
Exemple #7
0
        public void PeerBanning_SavingAndLoading_BannedPeerToAddressManager()
        {
            DataFolder dataFolder = CreateDataFolder(this);

            var loggerFactory = ExtendedLoggerFactory.Create();

            IPAddress ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var       endpoint  = new IPEndPoint(ipAddress, 80);

            var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, dataFolder, loggerFactory, new Mock <ISelfEndpointTracker>().Object);

            peerAddressManager.AddPeer(endpoint, IPAddress.Loopback);

            var nodeSettings = new NodeSettings(new StraxTest());
            var connectionManagerSettings = new ConnectionManagerSettings(nodeSettings);

            var peerCollection = new Mock <IReadOnlyNetworkPeerCollection>();

            peerCollection.Setup(p => p.FindByIp(It.IsAny <IPAddress>())).Returns(new List <INetworkPeer>());

            var connectionManager = new Mock <IConnectionManager>();

            connectionManager.Setup(c => c.ConnectionSettings).Returns(connectionManagerSettings);
            connectionManager.Setup(c => c.ConnectedPeers).Returns(peerCollection.Object);

            var peerBanning = new PeerBanning(connectionManager.Object, loggerFactory, DateTimeProvider.Default, peerAddressManager);

            peerBanning.BanAndDisconnectPeer(endpoint, connectionManagerSettings.BanTimeSeconds, nameof(PeerBanningTest));

            peerAddressManager.SavePeers();
            peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, dataFolder, loggerFactory, new Mock <ISelfEndpointTracker>().Object);
            peerAddressManager.LoadPeers();

            PeerAddress peer = peerAddressManager.FindPeer(endpoint);

            Assert.NotNull(peer.BanTimeStamp);
            Assert.NotNull(peer.BanUntil);
            Assert.NotEmpty(peer.BanReason);
        }
        public CanGetSenderRuleTest()
        {
            var loggerFactory = ExtendedLoggerFactory.Create();

            this.network         = new SmartContractsRegTest();
            this.senderRetriever = new Mock <ISenderRetriever>();
            this.rule            = new CanGetSenderRule(this.senderRetriever.Object);
            this.mempoolRule     = new CanGetSenderMempoolRule(this.network, new Mock <ITxMempool>().Object, new MempoolSettings(new NodeSettings(this.network)), new ChainIndexer(this.network), this.senderRetriever.Object, new Mock <ILoggerFactory>().Object);
            this.rule.Parent     = new PowConsensusRuleEngine(
                this.network,
                new Mock <ILoggerFactory>().Object,
                new Mock <IDateTimeProvider>().Object,
                new ChainIndexer(this.network),
                new NodeDeployments(KnownNetworks.RegTest, new ChainIndexer(this.network)),
                new ConsensusSettings(NodeSettings.Default(this.network)), new Mock <ICheckpoints>().Object, new Mock <ICoinView>().Object, new Mock <IChainState>().Object,
                new InvalidBlockHashStore(null),
                new NodeStats(null, loggerFactory),
                new AsyncProvider(new Mock <ILoggerFactory>().Object, new Mock <ISignals>().Object),
                new ConsensusRulesContainer());

            this.rule.Initialize();
        }
        public void ReflectionVirtualMachineFeature_OnInitialize_RulesAdded()
        {
            Network network = KnownNetworks.StratisRegTest;

            var chain           = new ConcurrentChain(network);
            var contractState   = new ContractStateRepositoryRoot();
            var executorFactory = new Mock <ISmartContractExecutorFactory>();
            var loggerFactory   = new ExtendedLoggerFactory();

            var consensusRules = new SmartContractPowConsensusRuleEngine(
                chain, new Mock <ICheckpoints>().Object, new Configuration.Settings.ConsensusSettings(),
                DateTimeProvider.Default, executorFactory.Object, loggerFactory, network,
                new Base.Deployments.NodeDeployments(network, chain), contractState,
                new Mock <ILookaheadBlockPuller>().Object,
                new Mock <IReceiptRepository>().Object,
                new Mock <ICoinView>().Object);

            var feature = new ReflectionVirtualMachineFeature(loggerFactory, network);

            feature.Initialize();

            Assert.Single(network.Consensus.Rules.Where(r => r.GetType() == typeof(SmartContractFormatRule)));
        }
        public void PeerBanning_Add_Peer_To_Address_Manager_And_Ban()
        {
            var dataFolder = CreateDataFolder(this);

            var loggerFactory = new ExtendedLoggerFactory();

            loggerFactory.AddConsoleWithFilters();

            var ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint  = new IPEndPoint(ipAddress, 80);

            var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, dataFolder, loggerFactory, new Mock <ISelfEndpointTracker>().Object);

            peerAddressManager.AddPeer(endpoint, endpoint.Address.MapToIPv6());

            var nodeSettings = new NodeSettings(new StratisRegTest());
            var connectionManagerSettings = new ConnectionManagerSettings(nodeSettings);

            var peerCollection = new Mock <IReadOnlyNetworkPeerCollection>();

            peerCollection.Setup(p => p.FindByIp(It.IsAny <IPAddress>())).Returns(new List <INetworkPeer>());

            var connectionManager = new Mock <IConnectionManager>();

            connectionManager.Setup(c => c.ConnectionSettings).Returns(connectionManagerSettings);
            connectionManager.Setup(c => c.ConnectedPeers).Returns(peerCollection.Object);

            var peerBanning = new PeerBanning(connectionManager.Object, loggerFactory, DateTimeProvider.Default, peerAddressManager);

            peerBanning.BanAndDisconnectPeer(endpoint, connectionManagerSettings.BanTimeSeconds, nameof(PeerBanningTest));

            PeerAddress peer = peerAddressManager.FindPeer(endpoint);

            Assert.True(peer.BanUntil.HasValue);
            Assert.NotNull(peer.BanUntil);
            Assert.NotEmpty(peer.BanReason);
        }
        public TestContext()
        {
            var chain = new ConcurrentChain(this.Network);
            var extendedLoggerFactory   = new ExtendedLoggerFactory();
            var powConsensusRulesEngine = new PowConsensusRuleEngine(this.Network, extendedLoggerFactory, DateTimeProvider.Default, chain,
                                                                     new NodeDeployments(this.Network, chain), this.ConsensusSettings, this.Checkpoints.Object, new Mock <ICoinView>().Object, this.ChainState.Object, new InvalidBlockHashStore(new DateTimeProvider()));

            this.PartialValidation = new PartialValidator(powConsensusRulesEngine, extendedLoggerFactory);
            this.FullValidation    = new FullValidator(powConsensusRulesEngine, extendedLoggerFactory);
            this.HeaderValidator   = new Mock <IHeaderValidator>();
            this.HeaderValidator.Setup(hv => hv.ValidateHeader(It.IsAny <ChainedHeader>())).Returns(new ValidationContext());

            this.ChainedHeaderTree = new ChainedHeaderTree(
                this.Network,
                extendedLoggerFactory,
                this.HeaderValidator.Object,
                this.Checkpoints.Object,
                this.ChainState.Object,
                this.FinalizedBlockMock.Object,
                this.ConsensusSettings,
                new InvalidBlockHashStore(new DateTimeProvider()));

            this.ConsensusManager = CreateConsensusManager();
        }
 public ConsensusManagerBehaviorTestsHelper()
 {
     this.loggerFactory = ExtendedLoggerFactory.Create();
 }
Exemple #13
0
        /// <summary>
        /// Initializes a new instance of the object.
        /// </summary>
        /// <param name="network">The network the node runs on - regtest/testnet/mainnet.</param>
        /// <param name="protocolVersion">Supported protocol version for which to create the configuration.</param>
        /// <param name="agent">The nodes user agent that will be shared with peers.</param>
        /// <param name="args">The command-line arguments.</param>
        /// <param name="networksSelector">A selector class that delayed load a network for either - regtest/testnet/mainnet.</param>
        /// <exception cref="ConfigurationException">Thrown in case of any problems with the configuration file or command line arguments.</exception>
        /// <remarks>
        /// Processing depends on whether a configuration file is passed via the command line.
        /// There are two main scenarios here:
        /// - The configuration file is passed via the command line. In this case we need
        ///   to read it earlier so that it can provide defaults for "testnet" and "regtest".
        /// - Alternatively, if the file name is not supplied then a network-specific file
        ///   name would be determined. In this case we first need to determine the network.
        /// </remarks>
        public NodeSettings(Network network = null, ProtocolVersion protocolVersion = SupportedProtocolVersion,
                            string agent    = "ImpleumNode", string[] args          = null, NetworksSelector networksSelector = null)
        {
            // Create the default logger factory and logger.
            var loggerFactory = new ExtendedLoggerFactory();

            this.LoggerFactory = loggerFactory;
            this.LoggerFactory.AddConsoleWithFilters();
            this.LoggerFactory.AddNLog();
            this.Logger = this.LoggerFactory.CreateLogger(typeof(NodeSettings).FullName);

            // Record arguments.
            this.Network         = network;
            this.ProtocolVersion = protocolVersion;
            this.Agent           = agent;
            this.ConfigReader    = new TextFileConfiguration(args ?? new string[] { });

            // Log arguments.
            this.Logger.LogDebug("Arguments: network='{0}', protocolVersion='{1}', agent='{2}', args='{3}'.",
                                 this.Network == null ? "(None)" : this.Network.Name,
                                 this.ProtocolVersion,
                                 this.Agent,
                                 args == null ? "(None)" : string.Join(" ", args));

            // By default, we look for a file named '<network>.conf' in the network's data directory,
            // but both the data directory and the configuration file path may be changed using the -datadir and -conf command-line arguments.
            this.ConfigurationFile = this.ConfigReader.GetOrDefault <string>("conf", null, this.Logger)?.NormalizeDirectorySeparator();
            this.DataDir           = this.ConfigReader.GetOrDefault <string>("datadir", null, this.Logger)?.NormalizeDirectorySeparator();
            this.DataDirRoot       = this.ConfigReader.GetOrDefault <string>("datadirroot", "ImpleumNode", this.Logger);

            // If the configuration file is relative then assume it is relative to the data folder and combine the paths.
            if (this.DataDir != null && this.ConfigurationFile != null)
            {
                bool isRelativePath = Path.GetFullPath(this.ConfigurationFile).Length > this.ConfigurationFile.Length;
                if (isRelativePath)
                {
                    this.ConfigurationFile = Path.Combine(this.DataDir, this.ConfigurationFile);
                }
            }

            // If the configuration file has been specified on the command line then read it now
            // so that it can provide the defaults for testnet and regtest.
            if (this.ConfigurationFile != null)
            {
                // If the configuration file was specified on the command line then it must exist.
                if (!File.Exists(this.ConfigurationFile))
                {
                    throw new ConfigurationException($"Configuration file does not exist at {this.ConfigurationFile}.");
                }

                // Sets the ConfigReader based on the arguments and the configuration file if it exists.
                this.ReadConfigurationFile();
            }

            // If the network is not known then derive it from the command line arguments.
            if (this.Network == null)
            {
                if (networksSelector == null)
                {
                    throw new ConfigurationException("Network or NetworkSelector not provided.");
                }

                // Find out if we need to run on testnet or regtest from the config file.
                bool testNet = this.ConfigReader.GetOrDefault <bool>("testnet", false, this.Logger);
                bool regTest = this.ConfigReader.GetOrDefault <bool>("regtest", false, this.Logger);

                if (testNet && regTest)
                {
                    throw new ConfigurationException("Invalid combination of regtest and testnet.");
                }

                this.Network = testNet ? networksSelector.Testnet() : regTest?networksSelector.Regtest() : networksSelector.Mainnet();

                this.Logger.LogDebug("Network set to '{0}'.", this.Network.Name);
            }

            // Ensure the network being used is registered and we have the correct Network object reference.
            this.Network = NetworkRegistration.Register(this.Network);

            // Set the full data directory path.
            if (this.DataDir == null)
            {
                // Create the data directories if they don't exist.
                this.DataDir = this.CreateDefaultDataDirectories(Path.Combine(this.DataDirRoot, this.Network.RootFolderName), this.Network);
            }
            else
            {
                // Combine the data directory with the network's root folder and name.
                string directoryPath = Path.Combine(this.DataDir, this.Network.RootFolderName, this.Network.Name);
                this.DataDir = Directory.CreateDirectory(directoryPath).FullName;
                this.Logger.LogDebug("Data directory initialized with path {0}.", this.DataDir);
            }

            // Set the data folder.
            this.DataFolder = new DataFolder(this.DataDir);

            // Attempt to load NLog configuration from the DataFolder.
            loggerFactory.LoadNLogConfiguration(this.DataFolder);

            // Get the configuration file name for the network if it was not specified on the command line.
            if (this.ConfigurationFile == null)
            {
                this.ConfigurationFile = Path.Combine(this.DataDir, this.Network.DefaultConfigFilename);
                this.Logger.LogDebug("Configuration file set to '{0}'.", this.ConfigurationFile);

                if (File.Exists(this.ConfigurationFile))
                {
                    this.ReadConfigurationFile();
                }
            }

            // Create the custom logger factory.
            this.Log = new LogSettings();
            this.Log.Load(this.ConfigReader);
            this.LoggerFactory.AddFilters(this.Log, this.DataFolder);
            this.LoggerFactory.ConfigureConsoleFilters(this.LoggerFactory.GetConsoleSettings(), this.Log);

            // Load the configuration.
            this.LoadConfiguration();
        }
 public PeerSelectorTests()
 {
     this.extendedLoggerFactory     = ExtendedLoggerFactory.Create();
     this.connectionManagerSettings = new ConnectionManagerSettings(NodeSettings.Default(new StratisRegTest()));
 }
        public CheckCollateralFullValidationRuleTests()
        {
            this.ibdMock = new Mock <IInitialBlockDownloadState>();
            this.collateralCheckerMock = new Mock <ICollateralChecker>();
            this.slotsManagerMock      = new Mock <ISlotsManager>();

            this.ibdMock.Setup(x => x.IsInitialBlockDownload()).Returns(false);
            this.ruleContext = new RuleContext(new ValidationContext(), DateTimeOffset.Now);
            var header = new BlockHeader()
            {
                Time = 5234
            };

            this.ruleContext.ValidationContext.BlockToValidate         = new Block(header);
            this.ruleContext.ValidationContext.ChainedHeaderToValidate = new ChainedHeader(header, header.GetHash(), 0);

            Block block = this.ruleContext.ValidationContext.BlockToValidate;

            block.AddTransaction(new Transaction());

            var     loggerFactory = new ExtendedLoggerFactory();
            ILogger logger        = loggerFactory.CreateLogger(this.GetType().FullName);

            var votingDataEncoder = new VotingDataEncoder(loggerFactory);
            var votes             = new List <VotingData>
            {
                new VotingData()
                {
                    Key  = VoteKey.WhitelistHash,
                    Data = new uint256(0).ToBytes()
                }
            };

            byte[] encodedVotingData = votingDataEncoder.Encode(votes);

            var votingData = new List <byte>(VotingDataEncoder.VotingOutputPrefixBytes);

            votingData.AddRange(encodedVotingData);

            var votingOutputScript = new Script(OpcodeType.OP_RETURN, Op.GetPushOp(votingData.ToArray()));

            block.Transactions[0].AddOutput(Money.Zero, votingOutputScript);

            var commitmentHeightEncoder = new CollateralHeightCommitmentEncoder(logger);

            byte[] encodedHeight        = commitmentHeightEncoder.EncodeCommitmentHeight(1000);
            var    commitmentHeightData = new Script(OpcodeType.OP_RETURN, Op.GetPushOp(encodedHeight));

            block.Transactions[0].AddOutput(Money.Zero, commitmentHeightData);

            var fullnode = new Mock <IFullNode>();

            fullnode.Setup(x => x.NodeService <CounterChainNetworkWrapper>(false)).Returns(new CounterChainNetworkWrapper(new StraxMain()));
            var consensusManager = new Mock <IConsensusManager>();

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

            var federationHistory = new Mock <IFederationHistory>();

            federationHistory
            .Setup(x => x.GetFederationMemberForBlock(It.IsAny <ChainedHeader>()))
            .Returns(new CollateralFederationMember(new Key().PubKey, false, new Money(1), "addr1"));

            this.rule = new CheckCollateralFullValidationRule(this.ibdMock.Object, this.collateralCheckerMock.Object, new Mock <IDateTimeProvider>().Object, new PoANetwork(), federationHistory.Object)
            {
                Logger = logger
            };

            this.rule.Initialize();
        }
Exemple #16
0
 public PeerSelectorTests()
 {
     this.extendedLoggerFactory = new ExtendedLoggerFactory();
     this.extendedLoggerFactory.AddConsoleWithFilters();
     this.connectionManagerSettings = new ConnectionManagerSettings(NodeSettings.Default(new StratisRegTest()));
 }
 public NetworkPeerServerTests(ITestOutputHelper output)
 {
     this.testOutput            = output;
     this.extendedLoggerFactory = ExtendedLoggerFactory.Create();
 }
Exemple #18
0
        /// <summary>
        /// Creates the test chain with some default blocks and txs.
        /// </summary>
        /// <param name="network">Network to create the chain on.</param>
        /// <param name="scriptPubKey">Public key to create blocks/txs with.</param>
        /// <returns>Context object representing the test chain.</returns>
        public static async Task <ITestChainContext> CreateAsync(Network network, Script scriptPubKey, string dataDir)
        {
            NodeSettings nodeSettings = new NodeSettings(network.Name, network).LoadArguments(new string[] { $"-datadir={dataDir}" });

            if (dataDir != null)
            {
                nodeSettings.DataDir = dataDir;
            }

            var loggerFactory = new ExtendedLoggerFactory();
            IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;

            network.Consensus.Options = new PowConsensusOptions();
            ConsensusSettings     consensusSettings  = new ConsensusSettings(nodeSettings, loggerFactory);
            PowConsensusValidator consensusValidator = new PowConsensusValidator(network, new Checkpoints(), dateTimeProvider, loggerFactory);
            ConcurrentChain       chain              = new ConcurrentChain(network);
            CachedCoinView        cachedCoinView     = new CachedCoinView(new InMemoryCoinView(chain.Tip.HashBlock), DateTimeProvider.Default, loggerFactory);
            NetworkPeerFactory    networkPeerFactory = new NetworkPeerFactory(network, dateTimeProvider, loggerFactory);

            var peerAddressManager = new PeerAddressManager(nodeSettings.DataFolder, loggerFactory);
            var peerDiscovery      = new PeerDiscovery(new AsyncLoopFactory(loggerFactory), loggerFactory, Network.PurpleMain, networkPeerFactory, new NodeLifetime(), nodeSettings, peerAddressManager);
            var connectionManager  = new ConnectionManager(dateTimeProvider, loggerFactory, network, networkPeerFactory, nodeSettings, new NodeLifetime(), new NetworkPeerConnectionParameters(), peerAddressManager, new IPeerConnector[] { }, peerDiscovery);

            LookaheadBlockPuller blockPuller    = new LookaheadBlockPuller(chain, connectionManager, new LoggerFactory());
            PeerBanning          peerBanning    = new PeerBanning(connectionManager, loggerFactory, dateTimeProvider, nodeSettings);
            NodeDeployments      deployments    = new NodeDeployments(network, chain);
            ConsensusRules       consensusRules = new ConsensusRules(network, loggerFactory, dateTimeProvider, chain, deployments, consensusSettings, new Checkpoints()).Register(new FullNodeBuilderConsensusExtension.CoreConsensusRules());
            ConsensusLoop        consensus      = new ConsensusLoop(new AsyncLoopFactory(loggerFactory), consensusValidator, new NodeLifetime(), chain, cachedCoinView, blockPuller, deployments, loggerFactory, new ChainState(new InvalidBlockHashStore(dateTimeProvider)), connectionManager, dateTimeProvider, new Signals.Signals(), consensusSettings, nodeSettings, peerBanning, consensusRules);
            await consensus.StartAsync();

            BlockPolicyEstimator blockPolicyEstimator = new BlockPolicyEstimator(new MempoolSettings(nodeSettings), loggerFactory, nodeSettings);
            TxMempool            mempool     = new TxMempool(dateTimeProvider, blockPolicyEstimator, loggerFactory, nodeSettings);
            MempoolSchedulerLock mempoolLock = new MempoolSchedulerLock();

            // Simple block creation, nothing special yet:
            PowBlockAssembler blockAssembler = CreatePowBlockAssembler(network, consensus, chain, mempoolLock, mempool, dateTimeProvider, loggerFactory);
            BlockTemplate     newBlock       = blockAssembler.CreateNewBlock(scriptPubKey);

            chain.SetTip(newBlock.Block.Header);
            await consensus.ValidateAndExecuteBlockAsync(new RuleContext(new BlockValidationContext {
                Block = newBlock.Block
            }, network.Consensus, consensus.Tip) { CheckPow = false, CheckMerkleRoot = false });

            List <BlockInfo> blockinfo = CreateBlockInfoList();

            // We can't make transactions until we have inputs
            // Therefore, load 100 blocks :)
            int                baseheight = 0;
            List <Block>       blocks     = new List <Block>();
            List <Transaction> srcTxs     = new List <Transaction>();

            for (int i = 0; i < blockinfo.Count; ++i)
            {
                Block currentBlock = newBlock.Block.Clone(); // pointer for convenience
                currentBlock.Header.HashPrevBlock = chain.Tip.HashBlock;
                currentBlock.Header.Version       = 1;
                currentBlock.Header.Time          = Utils.DateTimeToUnixTime(chain.Tip.GetMedianTimePast()) + 1;
                Transaction txCoinbase = currentBlock.Transactions[0].Clone();
                txCoinbase.Inputs.Clear();
                txCoinbase.Version = 1;
                txCoinbase.AddInput(new TxIn(new Script(new[] { Op.GetPushOp(blockinfo[i].extraNonce), Op.GetPushOp(chain.Height) })));
                // Ignore the (optional) segwit commitment added by CreateNewBlock (as the hardcoded nonces don't account for this)
                txCoinbase.AddOutput(new TxOut(Money.Zero, new Script()));
                currentBlock.Transactions[0] = txCoinbase;

                if (srcTxs.Count == 0)
                {
                    baseheight = chain.Height;
                }
                if (srcTxs.Count < 4)
                {
                    srcTxs.Add(currentBlock.Transactions[0]);
                }
                currentBlock.UpdateMerkleRoot();

                currentBlock.Header.Nonce = blockinfo[i].nonce;

                chain.SetTip(currentBlock.Header);
                await consensus.ValidateAndExecuteBlockAsync(new RuleContext(new BlockValidationContext {
                    Block = currentBlock
                }, network.Consensus, consensus.Tip) { CheckPow = false, CheckMerkleRoot = false });

                blocks.Add(currentBlock);
            }

            // Just to make sure we can still make simple blocks
            blockAssembler = CreatePowBlockAssembler(network, consensus, chain, mempoolLock, mempool, dateTimeProvider, loggerFactory);
            newBlock       = blockAssembler.CreateNewBlock(scriptPubKey);

            MempoolValidator mempoolValidator = new MempoolValidator(mempool, mempoolLock, consensusValidator, dateTimeProvider, new MempoolSettings(nodeSettings), chain, cachedCoinView, loggerFactory, nodeSettings);

            return(new TestChainContext {
                MempoolValidator = mempoolValidator, SrcTxs = srcTxs
            });
        }
Exemple #19
0
        /// <summary>
        ///     Initializes a new instance of the object.
        /// </summary>
        /// <param name="masterNode">The masternode the server runs on</param>
        /// <param name="protocolVersion">Supported protocol version for which to create the configuration.</param>
        /// <param name="agent">The servers user agent that will be shared with peers.</param>
        /// <param name="args">The command-line arguments.</param>
        /// <exception cref="ConfigurationException">
        ///     Thrown in case of any problems with the configuration file or command line
        ///     arguments.
        /// </exception>
        /// <remarks>
        ///     Processing depends on whether a configuration file is passed via the command line.
        ///     There are two main scenarios here:
        ///     - The configuration file is passed via the command line. In this case we need
        ///     to read it earlier so that it can provide defaults for "testnet" and "regtest".
        ///     - Alternatively, if the file name is not supplied then a masternode-specific file
        ///     name would be determined. In this case we first need to determine the masternode.
        /// </remarks>
        public ServerSettings(MasterNodeBase masterNode,
                              ProtocolVersion protocolVersion = ProtocolVersion.PROTOCOL_VERSION, string agent = "x42",
                              string[] args = null)
        {
            MasterNode = masterNode;
            // Create the default logger factory and logger.
            ExtendedLoggerFactory loggerFactory = new ExtendedLoggerFactory();

            LoggerFactory = loggerFactory;
            LoggerFactory.AddConsoleWithFilters();
            LoggerFactory.AddNLog();
            Logger = LoggerFactory.CreateLogger(typeof(ServerSettings).FullName);

            ProtocolVersion = protocolVersion;
            Agent           = agent;
            ConfigReader    = new TextFileConfiguration(args ?? new string[] { });

            // Log arguments.
            Logger.LogDebug("Arguments: masternode='{0}', protocolVersion='{1}', agent='{2}', args='{3}'.",
                            string.IsNullOrEmpty(ServerName) ? "(None)" : ServerName,
                            ProtocolVersion,
                            Agent,
                            args == null ? "(None)" : string.Join(" ", args));

            // By default, we look for a file named '<masternode>.conf' in the masternode's data directory,
            // but both the data directory and the configuration file path may be changed using the -datadir and -conf command-line arguments.
            ConfigurationFile = ConfigReader.GetOrDefault <string>("conf", null, Logger)?.NormalizeDirectorySeparator();
            DataDir           = ConfigReader.GetOrDefault <string>("datadir", null, Logger)?.NormalizeDirectorySeparator();
            DataDirRoot       = ConfigReader.GetOrDefault("datadirroot", "x42Server", Logger);

            // If the configuration file is relative then assume it is relative to the data folder and combine the paths.
            if (DataDir != null && ConfigurationFile != null)
            {
                bool isRelativePath = Path.GetFullPath(ConfigurationFile).Length > ConfigurationFile.Length;
                if (isRelativePath)
                {
                    ConfigurationFile = Path.Combine(DataDir, ConfigurationFile);
                }
            }

            // If the configuration file has been specified on the command line then read it now
            // so that it can provide the defaults for testnet and regtest.
            if (ConfigurationFile != null)
            {
                // If the configuration file was specified on the command line then it must exist.
                if (!File.Exists(ConfigurationFile))
                {
                    throw new ConfigurationException($"Configuration file does not exist at {ConfigurationFile}.");
                }

                // Sets the ConfigReader based on the arguments and the configuration file if it exists.
                ReadConfigurationFile();
            }

            // Set the full data directory path.
            if (DataDir == null)
            {
                // Create the data directories if they don't exist.
                DataDir = CreateDefaultDataDirectories(ServerName);
            }
            else
            {
                // Combine the data directory with the masternode's root folder and name.
                string directoryPath = Path.Combine(DataDir, ServerName);
                DataDir = Directory.CreateDirectory(directoryPath).FullName;
                Logger.LogDebug("Data directory initialized with path {0}.", DataDir);
            }

            // Set the data folder.
            DataFolder = new DataFolder(DataDir);

            // Attempt to load NLog configuration from the DataFolder.
            loggerFactory.LoadNLogConfiguration(DataFolder);

            // Get the configuration file name for the masternode if it was not specified on the command line.
            if (ConfigurationFile == null)
            {
                ConfigurationFile = Path.Combine(DataDir, MasterNode.DefaultConfigFilename);
                Logger.LogDebug("Configuration file set to '{0}'.", ConfigurationFile);

                if (File.Exists(ConfigurationFile))
                {
                    ReadConfigurationFile();
                }
            }

            // Create the custom logger factory.
            Log = new LogSettings();
            Log.Load(ConfigReader);
            LoggerFactory.AddFilters(Log, DataFolder);
            LoggerFactory.ConfigureConsoleFilters(LoggerFactory.GetConsoleSettings(), Log);

            // Load the configuration.
            LoadConfiguration();
        }
Exemple #20
0
 public ContractRefundProcessorTests()
 {
     this.loggerFactory   = ExtendedLoggerFactory.Create();
     this.network         = new SmartContractsRegTest();
     this.refundProcessor = new ContractRefundProcessor(this.loggerFactory);
 }
Exemple #21
0
 public SelfEndpointTrackerTests()
 {
     this.extendedLoggerFactory = new ExtendedLoggerFactory();
     this.selfEndpointTracker   = new SelfEndpointTracker(this.extendedLoggerFactory);
 }
Exemple #22
0
 public ContractTransferProcessorTests()
 {
     this.loggerFactory     = ExtendedLoggerFactory.Create();
     this.network           = new SmartContractsRegTest();
     this.transferProcessor = new ContractTransferProcessor(this.loggerFactory, this.network);
 }
Exemple #23
0
            public async Task InitializeAsync()
            {
                this.blockinfo = new List <Blockinfo>();
                var lst = blockinfoarr.Cast <long>().ToList();

                for (int i = 0; i < lst.Count; i += 2)
                {
                    this.blockinfo.Add(new Blockinfo {
                        extranonce = (int)lst[i], nonce = (uint)lst[i + 1]
                    });
                }

                // Note that by default, these tests run with size accounting enabled.
                this.network = Network.Main;
                var hex = Encoders.Hex.DecodeData("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f");

                this.scriptPubKey = new Script(new[] { Op.GetPushOp(hex), OpcodeType.OP_CHECKSIG });
                this.newBlock     = new BlockTemplate(this.network);

                this.entry = new TestMemPoolEntryHelper();
                this.chain = new ConcurrentChain(this.network);
                this.network.Consensus.Options = new PowConsensusOptions();
                IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;

                this.cachedCoinView = new CachedCoinView(new InMemoryCoinView(this.chain.Tip.HashBlock), dateTimeProvider, new LoggerFactory());

                var loggerFactory = new ExtendedLoggerFactory();

                loggerFactory.AddConsoleWithFilters();

                NodeSettings nodeSettings      = new NodeSettings(args: new string[] { "-checkpoints" });
                var          consensusSettings = new ConsensusSettings().Load(nodeSettings);

                PowConsensusValidator consensusValidator = new PowConsensusValidator(this.network, new Checkpoints(), dateTimeProvider, loggerFactory);
                NetworkPeerFactory    networkPeerFactory = new NetworkPeerFactory(this.network, dateTimeProvider, loggerFactory, new PayloadProvider().DiscoverPayloads(), new SelfEndpointTracker());

                var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, nodeSettings.DataFolder, loggerFactory, new SelfEndpointTracker());
                var peerDiscovery      = new PeerDiscovery(new AsyncLoopFactory(loggerFactory), loggerFactory, Network.Main, networkPeerFactory, new NodeLifetime(), nodeSettings, peerAddressManager);
                var connectionSettings = new ConnectionManagerSettings();

                connectionSettings.Load(nodeSettings);
                var connectionManager = new ConnectionManager(dateTimeProvider, loggerFactory, this.network, networkPeerFactory, nodeSettings, new NodeLifetime(), new NetworkPeerConnectionParameters(), peerAddressManager, new IPeerConnector[] { }, peerDiscovery, connectionSettings);

                LookaheadBlockPuller blockPuller    = new LookaheadBlockPuller(this.chain, connectionManager, new LoggerFactory());
                PeerBanning          peerBanning    = new PeerBanning(connectionManager, loggerFactory, dateTimeProvider, peerAddressManager);
                NodeDeployments      deployments    = new NodeDeployments(this.network, this.chain);
                ConsensusRules       consensusRules = new PowConsensusRules(this.network, loggerFactory, dateTimeProvider, this.chain, deployments, consensusSettings, new Checkpoints(), this.cachedCoinView, blockPuller).Register(new FullNodeBuilderConsensusExtension.PowConsensusRulesRegistration());

                this.consensus = new ConsensusLoop(new AsyncLoopFactory(loggerFactory), consensusValidator, new NodeLifetime(), this.chain, this.cachedCoinView, blockPuller, new NodeDeployments(this.network, this.chain), loggerFactory, new ChainState(new InvalidBlockHashStore(dateTimeProvider)), connectionManager, dateTimeProvider, new Signals.Signals(), consensusSettings, nodeSettings, peerBanning, consensusRules);
                await this.consensus.StartAsync();

                this.entry.Fee(11);
                this.entry.Height(11);
                var date1 = new MemoryPoolTests.DateTimeProviderSet();

                date1.time            = dateTimeProvider.GetTime();
                date1.timeutc         = dateTimeProvider.GetUtcNow();
                this.DateTimeProvider = date1;
                this.mempool          = new TxMempool(dateTimeProvider, new BlockPolicyEstimator(new MempoolSettings(nodeSettings), new LoggerFactory(), nodeSettings), new LoggerFactory(), nodeSettings);
                this.mempoolLock      = new MempoolSchedulerLock();

                // Simple block creation, nothing special yet:
                this.newBlock = AssemblerForTest(this).Build(this.chain.Tip, this.scriptPubKey);
                this.chain.SetTip(this.newBlock.Block.Header);
                await this.consensus.ValidateAndExecuteBlockAsync(new RuleContext(new BlockValidationContext {
                    Block = this.newBlock.Block
                }, this.network.Consensus, this.consensus.Tip) { CheckPow = false, CheckMerkleRoot = false });

                // We can't make transactions until we have inputs
                // Therefore, load 100 blocks :)
                this.baseheight = 0;
                List <Block> blocks = new List <Block>();

                this.txFirst = new List <Transaction>();
                for (int i = 0; i < this.blockinfo.Count; ++i)
                {
                    var pblock = this.newBlock.Block.Clone(); // pointer for convenience
                    pblock.Header.HashPrevBlock = this.chain.Tip.HashBlock;
                    pblock.Header.Version       = 1;
                    pblock.Header.Time          = Utils.DateTimeToUnixTime(this.chain.Tip.GetMedianTimePast()) + 1;
                    Transaction txCoinbase = pblock.Transactions[0].Clone();
                    txCoinbase.Inputs.Clear();
                    txCoinbase.Version = 1;
                    txCoinbase.AddInput(new TxIn(new Script(new[] { Op.GetPushOp(this.blockinfo[i].extranonce), Op.GetPushOp(this.chain.Height) })));
                    // Ignore the (optional) segwit commitment added by CreateNewBlock (as the hardcoded nonces don't account for this)
                    txCoinbase.AddOutput(new TxOut(Money.Zero, new Script()));
                    pblock.Transactions[0] = txCoinbase;

                    if (this.txFirst.Count == 0)
                    {
                        this.baseheight = this.chain.Height;
                    }
                    if (this.txFirst.Count < 4)
                    {
                        this.txFirst.Add(pblock.Transactions[0]);
                    }
                    pblock.UpdateMerkleRoot();

                    pblock.Header.Nonce = this.blockinfo[i].nonce;

                    this.chain.SetTip(pblock.Header);
                    await this.consensus.ValidateAndExecuteBlockAsync(new RuleContext(new BlockValidationContext {
                        Block = pblock
                    }, this.network.Consensus, this.consensus.Tip) { CheckPow = false, CheckMerkleRoot = false });

                    blocks.Add(pblock);
                }

                // Just to make sure we can still make simple blocks
                this.newBlock = AssemblerForTest(this).Build(this.chain.Tip, this.scriptPubKey);
                Assert.NotNull(this.newBlock);
            }
 public PeerSelectorTests()
 {
     this.extendedLoggerFactory = new ExtendedLoggerFactory();
     this.extendedLoggerFactory.AddConsoleWithFilters();
 }
Exemple #25
0
            public async Task InitializeAsync()
            {
                this.blockinfo = new List <Blockinfo>();
                List <long> lst = blockinfoarr.Cast <long>().ToList();

                for (int i = 0; i < lst.Count; i += 2)
                {
                    this.blockinfo.Add(new Blockinfo {
                        extranonce = (int)lst[i], nonce = (uint)lst[i + 1]
                    });
                }

                // Note that by default, these tests run with size accounting enabled.
                this.network = KnownNetworks.RegTest;
                byte[] hex = Encoders.Hex.DecodeData("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f");
                this.scriptPubKey = new Script(new[] { Op.GetPushOp(hex), OpcodeType.OP_CHECKSIG });

                this.entry = new TestMemPoolEntryHelper();
                this.chain = new ConcurrentChain(this.network);
                this.network.Consensus.Options = new ConsensusOptions();

                new FullNodeBuilderConsensusExtension.PowConsensusRulesRegistration().RegisterRules(this.network.Consensus);

                IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;

                this.cachedCoinView = new CachedCoinView(new InMemoryCoinView(this.chain.Tip.HashBlock), dateTimeProvider, new LoggerFactory());

                var loggerFactory = new ExtendedLoggerFactory();

                loggerFactory.AddConsoleWithFilters();

                var nodeSettings      = new NodeSettings(args: new string[] { "-checkpoints" });
                var consensusSettings = new ConsensusSettings(nodeSettings);

                var networkPeerFactory = new NetworkPeerFactory(this.network, dateTimeProvider, loggerFactory, new PayloadProvider().DiscoverPayloads(), new SelfEndpointTracker(loggerFactory), new Mock <IInitialBlockDownloadState>().Object, new ConnectionManagerSettings());

                var peerAddressManager  = new PeerAddressManager(DateTimeProvider.Default, nodeSettings.DataFolder, loggerFactory, new SelfEndpointTracker(loggerFactory));
                var peerDiscovery       = new PeerDiscovery(new AsyncLoopFactory(loggerFactory), loggerFactory, this.network, networkPeerFactory, new NodeLifetime(), nodeSettings, peerAddressManager);
                var connectionSettings  = new ConnectionManagerSettings(nodeSettings);
                var selfEndpointTracker = new SelfEndpointTracker(loggerFactory);
                var connectionManager   = new ConnectionManager(dateTimeProvider, loggerFactory, this.network, networkPeerFactory,
                                                                nodeSettings, new NodeLifetime(), new NetworkPeerConnectionParameters(), peerAddressManager, new IPeerConnector[] { },
                                                                peerDiscovery, selfEndpointTracker, connectionSettings, new VersionProvider(), new Mock <INodeStats>().Object);

                var peerBanning = new PeerBanning(connectionManager, loggerFactory, dateTimeProvider, peerAddressManager);
                var deployments = new NodeDeployments(this.network, this.chain);

                var genesis = this.network.GetGenesis();

                var chainState = new ChainState()
                {
                    BlockStoreTip = new ChainedHeader(genesis.Header, genesis.GetHash(), 0)
                };

                this.ConsensusRules = new PowConsensusRuleEngine(this.network, loggerFactory, dateTimeProvider, this.chain, deployments, consensusSettings,
                                                                 new Checkpoints(), this.cachedCoinView, chainState, new InvalidBlockHashStore(dateTimeProvider)).Register();

                this.consensus = ConsensusManagerHelper.CreateConsensusManager(this.network);
                await this.consensus.InitializeAsync(chainState.BlockStoreTip);

                this.entry.Fee(11);
                this.entry.Height(11);

                var dateTimeProviderSet = new MemoryPoolTests.DateTimeProviderSet
                {
                    time    = dateTimeProvider.GetTime(),
                    timeutc = dateTimeProvider.GetUtcNow()
                };

                this.DateTimeProvider = dateTimeProviderSet;
                this.mempool          = new TxMempool(dateTimeProvider, new BlockPolicyEstimator(new MempoolSettings(nodeSettings), loggerFactory, nodeSettings), loggerFactory, nodeSettings);
                this.mempoolLock      = new MempoolSchedulerLock();

                // We can't make transactions until we have inputs
                // Therefore, load 100 blocks :)
                this.baseheight = 0;
                var blocks = new List <Block>();

                this.txFirst = new List <Transaction>();

                this.nonce = 0;

                for (int i = 0; i < this.blockinfo.Count; ++i)
                {
                    Block block = this.network.CreateBlock();
                    block.Header.HashPrevBlock = this.chain.Tip.HashBlock;
                    block.Header.Version       = 1;
                    block.Header.Time          = Utils.DateTimeToUnixTime(this.chain.Tip.GetMedianTimePast()) + 1;

                    Transaction txCoinbase = this.network.CreateTransaction();
                    txCoinbase.Version = 1;
                    txCoinbase.AddInput(new TxIn(new Script(new[] { Op.GetPushOp(this.blockinfo[i].extranonce), Op.GetPushOp(this.chain.Height) })));
                    // Ignore the (optional) segwit commitment added by CreateNewBlock (as the hardcoded nonces don't account for this)
                    txCoinbase.AddOutput(new TxOut(Money.Zero, new Script()));
                    block.AddTransaction(txCoinbase);

                    if (this.txFirst.Count == 0)
                    {
                        this.baseheight = this.chain.Height;
                    }

                    if (this.txFirst.Count < 4)
                    {
                        this.txFirst.Add(block.Transactions[0]);
                    }

                    block.Header.Bits = block.Header.GetWorkRequired(this.network, this.chain.Tip);

                    block.UpdateMerkleRoot();

                    while (!block.CheckProofOfWork())
                    {
                        block.Header.Nonce = ++this.nonce;
                    }

                    // Serialization sets the BlockSize property.
                    block = Block.Load(block.ToBytes(), this.network);

                    await this.consensus.BlockMinedAsync(block);

                    blocks.Add(block);
                }

                // Just to make sure we can still make simple blocks
                this.newBlock = AssemblerForTest(this).Build(this.chain.Tip, this.scriptPubKey);
                Assert.NotNull(this.newBlock);
            }
Exemple #26
0
 public NetworkPeerServerTests(ITestOutputHelper output)
 {
     this.testOutput            = output;
     this.extendedLoggerFactory = new ExtendedLoggerFactory();
     this.extendedLoggerFactory.AddConsoleWithFilters();
 }
 public SelfEndpointTrackerTests()
 {
     this.extendedLoggerFactory = new ExtendedLoggerFactory();
     this.selfEndpointTracker   = new SelfEndpointTracker(this.extendedLoggerFactory,
                                                          new ConnectionManagerSettings(NodeSettings.Default(new StratisRegTest())));
 }
Exemple #28
0
            public async Task InitializeAsync()
            {
                this.blockinfo = new List <Blockinfo>();
                List <long> lst = blockinfoarr.Cast <long>().ToList();

                for (int i = 0; i < lst.Count; i += 2)
                {
                    this.blockinfo.Add(new Blockinfo {
                        extranonce = (int)lst[i], nonce = (uint)lst[i + 1]
                    });
                }

                // Note that by default, these tests run with size accounting enabled.
                this.network = KnownNetworks.RegTest;
                byte[] hex = Encoders.Hex.DecodeData("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f");
                this.scriptPubKey = new Script(new[] { Op.GetPushOp(hex), OpcodeType.OP_CHECKSIG });

                this.entry        = new TestMemPoolEntryHelper();
                this.ChainIndexer = new ChainIndexer(this.network);
                this.network.Consensus.Options = new ConsensusOptions();

                IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;

                var loggerFactory = ExtendedLoggerFactory.Create();

                var nodeSettings      = new NodeSettings(this.network, args: new string[] { "-checkpoints" });
                var consensusSettings = new ConsensusSettings(nodeSettings);

                var inMemoryCoinView = new InMemoryCoinView(new HashHeightPair(this.ChainIndexer.Tip));
                var nodeStats        = new NodeStats(dateTimeProvider, loggerFactory);

                this.cachedCoinView = new CachedCoinView(this.network, new Checkpoints(), inMemoryCoinView, dateTimeProvider, new LoggerFactory(), nodeStats, consensusSettings);

                var signals       = new Signals.Signals(loggerFactory, null);
                var asyncProvider = new AsyncProvider(loggerFactory, signals, new NodeLifetime());

                var deployments = new NodeDeployments(this.network, this.ChainIndexer);

                var genesis = this.network.GetGenesis();

                var chainState = new ChainState()
                {
                    BlockStoreTip = new ChainedHeader(genesis.Header, genesis.GetHash(), 0)
                };

                var consensusRulesContainer = new ConsensusRulesContainer();

                foreach (var ruleType in this.network.Consensus.ConsensusRules.HeaderValidationRules)
                {
                    consensusRulesContainer.HeaderValidationRules.Add(Activator.CreateInstance(ruleType) as HeaderValidationConsensusRule);
                }
                foreach (var ruleType in this.network.Consensus.ConsensusRules.FullValidationRules)
                {
                    FullValidationConsensusRule rule = null;
                    if (ruleType == typeof(FlushUtxosetRule))
                    {
                        rule = new FlushUtxosetRule(new Mock <IInitialBlockDownloadState>().Object);
                    }
                    else
                    {
                        rule = Activator.CreateInstance(ruleType) as FullValidationConsensusRule;
                    }

                    consensusRulesContainer.FullValidationRules.Add(rule);
                }

                this.ConsensusRules = new PowConsensusRuleEngine(this.network, loggerFactory, dateTimeProvider, this.ChainIndexer, deployments, consensusSettings,
                                                                 new Checkpoints(), this.cachedCoinView, chainState, new InvalidBlockHashStore(dateTimeProvider), nodeStats, asyncProvider, consensusRulesContainer).SetupRulesEngineParent();

                this.consensus = ConsensusManagerHelper.CreateConsensusManager(this.network, chainState: chainState, inMemoryCoinView: inMemoryCoinView, chainIndexer: this.ChainIndexer, consensusRules: this.ConsensusRules);

                await this.consensus.InitializeAsync(chainState.BlockStoreTip);

                this.entry.Fee(11);
                this.entry.Height(11);

                var dateTimeProviderSet = new DateTimeProviderSet
                {
                    time    = dateTimeProvider.GetTime(),
                    timeutc = dateTimeProvider.GetUtcNow()
                };

                this.DateTimeProvider = dateTimeProviderSet;
                this.mempool          = new TxMempool(dateTimeProvider, new BlockPolicyEstimator(new MempoolSettings(nodeSettings), loggerFactory, nodeSettings), loggerFactory, nodeSettings);
                this.mempoolLock      = new MempoolSchedulerLock();

                // We can't make transactions until we have inputs
                // Therefore, load 100 blocks :)
                this.baseheight = 0;
                var blocks = new List <Block>();

                this.txFirst = new List <Transaction>();

                this.nonce = 0;

                for (int i = 0; i < this.blockinfo.Count; ++i)
                {
                    Block block = this.network.CreateBlock();
                    block.Header.HashPrevBlock = this.consensus.Tip.HashBlock;
                    block.Header.Version       = 1;
                    block.Header.Time          = Utils.DateTimeToUnixTime(this.ChainIndexer.Tip.GetMedianTimePast()) + 1;

                    Transaction txCoinbase = this.network.CreateTransaction();
                    txCoinbase.Version = 1;
                    txCoinbase.AddInput(new TxIn(new Script(new[] { Op.GetPushOp(this.blockinfo[i].extranonce), Op.GetPushOp(this.ChainIndexer.Height) })));
                    // Ignore the (optional) segwit commitment added by CreateNewBlock (as the hardcoded nonces don't account for this)
                    txCoinbase.AddOutput(new TxOut(Money.Zero, new Script()));
                    block.AddTransaction(txCoinbase);

                    if (this.txFirst.Count == 0)
                    {
                        this.baseheight = this.ChainIndexer.Height;
                    }

                    if (this.txFirst.Count < 4)
                    {
                        this.txFirst.Add(block.Transactions[0]);
                    }

                    block.Header.Bits = block.Header.GetWorkRequired(this.network, this.ChainIndexer.Tip);

                    block.UpdateMerkleRoot();

                    while (!block.CheckProofOfWork())
                    {
                        block.Header.Nonce = ++this.nonce;
                    }

                    // Serialization sets the BlockSize property.
                    block = Block.Load(block.ToBytes(), this.network.Consensus.ConsensusFactory);

                    var res = await this.consensus.BlockMinedAsync(block);

                    if (res == null)
                    {
                        throw new InvalidOperationException();
                    }

                    blocks.Add(block);
                }

                // Just to make sure we can still make simple blocks
                this.newBlock = AssemblerForTest(this).Build(this.ChainIndexer.Tip, this.scriptPubKey);
                Assert.NotNull(this.newBlock);
            }
        public void CanDiscoverAndConnectToPeersOnTheNetwork()
        {
            var parameters = new NetworkPeerConnectionParameters();

            var testFolder = TestDirectory.Create("CanDiscoverAndConnectToPeersOnTheNetwork");

            var nodeSettings = new NodeSettings
            {
                DataDir = testFolder.FolderName
            };

            nodeSettings.DataFolder = new DataFolder(nodeSettings);

            var peerAddressManager          = new PeerAddressManager(nodeSettings.DataFolder);
            var peerAddressManagerBehaviour = new PeerAddressManagerBehaviour(new DateTimeProvider(), peerAddressManager)
            {
                PeersToDiscover = 3
            };

            parameters.TemplateBehaviors.Add(peerAddressManagerBehaviour);

            var loggerFactory = new ExtendedLoggerFactory();

            loggerFactory.AddConsoleWithFilters();

            var networkPeerFactory = new NetworkPeerFactory(DateTimeProvider.Default, loggerFactory);

            var peerConnectorDiscovery = new PeerConnectorDiscovery(
                new AsyncLoopFactory(loggerFactory),
                loggerFactory,
                Network.Main,
                networkPeerFactory,
                new NodeLifetime(),
                nodeSettings,
                peerAddressManager);

            var peerDiscovery = new PeerDiscovery(
                new AsyncLoopFactory(loggerFactory),
                loggerFactory,
                Network.Main,
                networkPeerFactory,
                new NodeLifetime(),
                nodeSettings,
                peerAddressManager);

            IConnectionManager connectionManager = new ConnectionManager(
                new AsyncLoopFactory(loggerFactory),
                new DateTimeProvider(),
                loggerFactory,
                Network.Main,
                networkPeerFactory,
                nodeSettings,
                new NodeLifetime(),
                parameters,
                peerAddressManager,
                new IPeerConnector[] { peerConnectorDiscovery },
                peerDiscovery);

            NetworkPeerConnectionParameters cloned = parameters.Clone();

            cloned.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, connectionManager, loggerFactory));

            peerDiscovery.DiscoverPeers(cloned);

            // Wait until we have discovered 3 peers.
            TestHelper.WaitLoop(() => peerAddressManager.Peers.Count > 3);

            // Wait until at least one successful connection has been made.
            while (true)
            {
                try
                {
                    var         peerOne = peerAddressManager.SelectPeerToConnectTo();
                    NetworkPeer node    = networkPeerFactory.CreateConnectedNetworkPeer(Network.Main, peerOne, parameters);
                    node.VersionHandshake();
                    node.Disconnect();

                    break;
                }
                catch
                {
                }
            }
            ;
        }