public void Clone_CreatesCloneOfModel()
        {
            var model = new GetStakingInfoModel()
            {
                CurrentBlockSize = 15,
                CurrentBlockTx   = 12,
                Difficulty       = 1.2,
                Enabled          = true,
                Errors           = "Error",
                ExpectedTime     = 10,
                NetStakeWeight   = 12000,
                PooledTx         = 56,
                SearchInterval   = 13,
                Staking          = true,
                Weight           = 34
            };

            var clone = (GetStakingInfoModel)model.Clone();

            Assert.Equal(model.CurrentBlockSize, clone.CurrentBlockSize);
            Assert.Equal(model.CurrentBlockTx, clone.CurrentBlockTx);
            Assert.Equal(model.Difficulty, clone.Difficulty);
            Assert.Equal(model.Enabled, clone.Enabled);
            Assert.Equal(model.Errors, clone.Errors);
            Assert.Equal(model.ExpectedTime, clone.ExpectedTime);
            Assert.Equal(model.NetStakeWeight, clone.NetStakeWeight);
            Assert.Equal(model.PooledTx, clone.PooledTx);
            Assert.Equal(model.SearchInterval, clone.SearchInterval);
            Assert.Equal(model.Staking, clone.Staking);
            Assert.Equal(model.Weight, clone.Weight);
        }
Exemple #2
0
        public void GetStakingInfo_StakingEnabled()
        {
            string    dir      = AssureEmptyDir("TestData/GetStakingInfoActionTests/GetStakingInfo_StakingEnabled");
            IFullNode fullNode = this.BuildStakingNode(dir);

            Task.Run(() =>
            {
                fullNode.Run();
            });

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

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

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

            GetStakingInfoModel info = controller.GetStakingInfo();

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

            nodeLifetime.StopApplication();
            nodeLifetime.ApplicationStopped.WaitHandle.WaitOne();
            fullNode.Dispose();
        }
Exemple #3
0
        public void GetStakingInfo_StakingEnabled()
        {
            using (var dir = TestDirectory.Create())
            {
                IFullNode fullNode        = PurpleBitcoinPosRunner.BuildStakingNode(dir.FolderName);
                var       fullNodeRunTask = fullNode.RunAsync();

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

                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);
            }
        }
        public void GetStakingInfoDeserializeTest()
        {
            IOrderedEnumerable <string> expectedSortedPropertyNames = ModelPropertyNames.OrderBy(name => name);
            string json = "{\n"
                          + "  \"enabled\": true,\n"
                          + "  \"staking\": true,\n"
                          + "  \"errors\": \"Block rejected by peers\",\n"
                          + "  \"currentBlockSize\": 151,\n"
                          + "  \"currentBlockTx\": 1,\n"
                          + "  \"pooledTx\": 120,\n"
                          + "  \"difficulty\": 77856.9675875571,\n"
                          + "  \"searchInterval\": 16,\n"
                          + "  \"weight\": 98076279000000,\n"
                          + "  \"netStakeWeight\": 101187415332927,\n"
                          + "  \"expectedTime\": 66\n"
                          + "}\n";

            JObject obj = JObject.Parse(json);
            IOrderedEnumerable <string> actualSortedPropertyNames = obj.Children().Select(o => (o as JProperty)?.Name).OrderBy(name => name);
            GetStakingInfoModel         model = Newtonsoft.Json.JsonConvert.DeserializeObject <GetStakingInfoModel>(json);

            Assert.Equal(expectedSortedPropertyNames, actualSortedPropertyNames);
            Assert.True(model.Enabled);
            Assert.True(model.Staking);
            Assert.Equal("Block rejected by peers", model.Errors);
            Assert.Equal(151, model.CurrentBlockSize);
            Assert.Equal(1, model.CurrentBlockTx);
            Assert.Equal(120, model.PooledTx);
            Assert.Equal(77856.9675875571, model.Difficulty);
            Assert.Equal(16, model.SearchInterval);
            Assert.Equal(98076279000000, model.Weight);
            Assert.Equal(101187415332927, model.NetStakeWeight);
            Assert.Equal(66, model.ExpectedTime);
        }
        public void GetStakingInfo_WithoutPosMinting_ReturnsEmptyStakingInfoModel()
        {
            this.stakingRpcController = new StakingRpcController(this.fullNode.Object, this.LoggerFactory.Object, this.walletManager.Object, null);

            GetStakingInfoModel result = this.stakingRpcController.GetStakingInfo(true);

            Assert.Equal(JsonConvert.SerializeObject(new GetStakingInfoModel()), JsonConvert.SerializeObject(result));
        }
 private void staking_is_enabled_but_nothing_is_staked()
 {
     var miningRpcController = this.nodes[PosNode].FullNode.NodeService<StakingRpcController>();
     GetStakingInfoModel stakingInfo = miningRpcController.GetStakingInfo();
     stakingInfo.Should().NotBeNull();
     stakingInfo.Enabled.Should().BeTrue();
     stakingInfo.Staking.Should().BeFalse();
 }
Exemple #7
0
        public void CanStartStakingViaAPI()
        {
            try
            {
                using (NodeBuilder builder = NodeBuilder.Create())
                {
                    CoreNode nodeA = builder.CreateStratisPosNode(false, fullNodeBuilder =>
                    {
                        fullNodeBuilder
                        .UseStratisConsensus()
                        .UseBlockStore()
                        .UseMempool()
                        .UseWallet()
                        .AddPowPosMining()
                        .UseApi()
                        .AddRPC();
                    });

                    builder.StartAll();

                    var fullNode = nodeA.FullNode;
                    var ApiURI   = fullNode.Settings.ApiUri;

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

                    using (Node nodeB = nodeA.CreateNodeClient())
                    {
                        WalletManager walletManager = fullNode.NodeService <IWalletManager>() as WalletManager;

                        // create the wallet
                        var model = new StartStakingRequest {
                            Name = "apitest", Password = "******"
                        };
                        var mnemonic = walletManager.CreateWallet(model.Password, model.Name);

                        var content  = new StringContent(model.ToString(), Encoding.UTF8, "application/json");
                        var response = client.PostAsync(ApiURI + "api/miner/startstaking", content).GetAwaiter().GetResult();
                        Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);

                        var responseText = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                        Assert.Equal("", responseText);

                        MiningRPCController controller = fullNode.NodeService <MiningRPCController>();
                        GetStakingInfoModel info       = controller.GetStakingInfo();

                        Assert.NotNull(info);
                        Assert.True(info.Enabled);
                        Assert.False(info.Staking);
                    }
                }
            }
            finally
            {
                // Revert global side-effects of StratisBitcoinPosRunner.InitStratisRegTest()
                Block.BlockSignature  = false;
                Transaction.TimeStamp = false;
            }
        }
Exemple #8
0
        private void staking_is_enabled_but_nothing_is_staked()
        {
            var miningRpcController         = this.stratisPosApiNode.FullNode.NodeController <StakingRpcController>();
            GetStakingInfoModel stakingInfo = miningRpcController.GetStakingInfo();

            stakingInfo.Should().NotBeNull();
            stakingInfo.Enabled.Should().BeTrue();
            stakingInfo.Staking.Should().BeFalse();
        }
Exemple #9
0
        public GetStakingInfoModel GetStakingInfo(bool isJsonFormat = true)
        {
            if (!isJsonFormat)
            {
                this.logger.LogError("Binary serialization is not supported for RPC '{0}'.", nameof(this.GetStakingInfo));
                throw new NotImplementedException();
            }

            GetStakingInfoModel model = this.posMinting != null?this.posMinting.GetGetStakingInfoModel() : new GetStakingInfoModel();

            return(model);
        }
        public void GetStakingInfoSerializeTest()
        {
            IOrderedEnumerable <string> expectedSortedPropertyNames = ModelPropertyNames.OrderBy(name => name);
            var model = new GetStakingInfoModel();

            JObject obj = ModelToJObject(model);

            Assert.True(obj.HasValues);
            IEnumerable <string> actualOrderedPropertyNames = obj.Children().Select(o => (o as JProperty)?.Name).OrderBy(name => name);

            Assert.Equal(expectedSortedPropertyNames, actualOrderedPropertyNames);
        }
        public void StopStake_DisposesResources()
        {
            var asyncLoop = new Mock <IAsyncLoop>();

            Func <CancellationToken, Task> stakingLoopFunction = null;
            CancellationToken stakingLoopToken = default(CancellationToken);

            this.asyncProvider.Setup(a => a.CreateAndRunAsyncLoop("PosMining.Stake",
                                                                  It.IsAny <Func <CancellationToken, Task> >(), It.IsAny <CancellationToken>(),
                                                                  It.Is <TimeSpan>(t => t.Milliseconds == 500), TimeSpans.Second))
            .Callback <string, Func <CancellationToken, Task>, CancellationToken, TimeSpan?, TimeSpan?>((name, func, token, repeat, start) =>
            {
                stakingLoopFunction = func;
                stakingLoopToken    = token;
            })
            .Returns(asyncLoop.Object)
            .Verifiable();

            bool isSystemTimeOutOfSyncCalled = false;

            this.timeSyncBehaviorState.Setup(c => c.IsSystemTimeOutOfSync)
            .Returns(() =>
            {
                if (!isSystemTimeOutOfSyncCalled)
                {
                    isSystemTimeOutOfSyncCalled = true;
                    // generates an error in the stakinginfomodel.
                    throw new MinerException("Mining error.");
                }

                this.posMinting.StopStake();    // stop the staking.
                throw new InvalidOperationException("End the loop");
            });

            this.posMinting.Stake(new List <WalletSecret>()
            {
                new WalletSecret()
                {
                    WalletName = "wallet1", WalletPassword = "******"
                }
            });
            stakingLoopFunction(stakingLoopToken);
            stakingLoopFunction(stakingLoopToken);

            Assert.True(stakingLoopToken.IsCancellationRequested);
            asyncLoop.Verify(a => a.Dispose());
            GetStakingInfoModel model = this.posMinting.GetGetStakingInfoModel();

            Assert.Null(model.Errors);
            Assert.False(model.Enabled);
        }
        public IActionResult GetStakingInfo()
        {
            try
            {
                GetStakingInfoModel model = this.posMinting != null?this.posMinting.GetGetStakingInfoModel() : new GetStakingInfoModel();

                return(this.Json(model));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public void GetStakingInfo_WithPosMinting_ReturnsPosMintingStakingInfoModel()
        {
            this.posMinting.Setup(p => p.GetGetStakingInfoModel())
            .Returns(new GetStakingInfoModel()
            {
                Enabled          = true,
                CurrentBlockSize = 150000
            }).Verifiable();

            GetStakingInfoModel result = this.stakingRpcController.GetStakingInfo(true);

            Assert.True(result.Enabled);
            Assert.Equal(150000, result.CurrentBlockSize);
            this.posMinting.Verify();
        }
 public StakingInfoClientEvent(GetStakingInfoModel stakingInfoModel)
 {
     if (null != stakingInfoModel)
     {
         this.Enabled          = stakingInfoModel.Enabled;
         this.Staking          = stakingInfoModel.Staking;
         this.Difficulty       = stakingInfoModel.Difficulty;
         this.Immature         = stakingInfoModel.Immature;
         this.Weight           = stakingInfoModel.Weight;
         this.NetStakeWeight   = stakingInfoModel.NetStakeWeight;
         this.ExpectedTime     = stakingInfoModel.ExpectedTime;
         this.PooledTx         = stakingInfoModel.PooledTx;
         this.SearchInterval   = stakingInfoModel.SearchInterval;
         this.CurrentBlockSize = stakingInfoModel.CurrentBlockSize;
         this.CurrentBlockTx   = stakingInfoModel.CurrentBlockTx;
     }
 }
Exemple #15
0
        public void GetStakingInfo_StartStaking()
        {
            string    dir      = AssureEmptyDir("TestData/GetStakingInfoActionTests/GetStakingInfo_StartStaking");
            IFullNode fullNode = this.BuildStakingNode(dir, false);
            var       node     = fullNode as FullNode;

            Task.Run(() =>
            {
                fullNode.Run();
            });

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

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

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

            var password = "******";

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


            Assert.NotNull(fullNode.NodeService <PosMinting>(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();
        }
Exemple #16
0
        public void GetStakingInfo_StartStaking()
        {
            using (var dir = TestDirectory.Create())
            {
                IFullNode fullNode = StratisBitcoinPosRunner.BuildStakingNode(dir.FolderName, false);
                var       node     = fullNode as FullNode;

                var fullNodeRunTask = fullNode.RunAsync();

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

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

                var password = "******";

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


                Assert.NotNull(fullNode.NodeService <PosMinting>(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);
            }
        }
Exemple #17
0
        public IActionResult GetStakingInfo()
        {
            try
            {
                if (!this.fullNode.Network.Consensus.IsProofOfStake)
                {
                    return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.MethodNotAllowed, "Method not allowed", "Method not available for Proof of Stake"));
                }

                GetStakingInfoModel model = this.posMinting != null?this.posMinting.GetGetStakingInfoModel() : new GetStakingInfoModel();

                return(this.Json(model));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        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.NodeController <StakingRpcController>();

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

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

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

            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);
        }
        public void Stake_StakingLoopThrowsConsensusErrorException_AddsErrorToRpcStakingInfoModel()
        {
            var asyncLoop = new AsyncLoop("PosMining.Stake2", this.FullNodeLogger.Object, token => { return(Task.CompletedTask); });

            this.asyncProvider.Setup(a => a.CreateAndRunAsyncLoop("PosMining.Stake",
                                                                  It.IsAny <Func <CancellationToken, Task> >(), It.IsAny <CancellationToken>(),
                                                                  It.Is <TimeSpan>(t => t.Milliseconds == 500), TimeSpans.Second))
            .Callback <string, Func <CancellationToken, Task>, CancellationToken, TimeSpan?, TimeSpan?>((name, func, token, repeat, start) =>
            {
                func(token);
            })
            .Returns(asyncLoop)
            .Verifiable();

            bool isSystemTimeOutOfSyncCalled = false;

            this.timeSyncBehaviorState.Setup(c => c.IsSystemTimeOutOfSync)
            .Returns(() =>
            {
                if (!isSystemTimeOutOfSyncCalled)
                {
                    isSystemTimeOutOfSyncCalled = true;
                    throw new ConsensusErrorException(new ConsensusError("15", "Consensus error."));
                }
                this.cancellationTokenSource.Cancel();
                throw new InvalidOperationException("End the loop");
            });

            this.posMinting.Stake(new List <WalletSecret>()
            {
                new WalletSecret()
                {
                    WalletName = "wallet1", WalletPassword = "******"
                }
            });
            asyncLoop.Run();

            GetStakingInfoModel model = this.posMinting.GetGetStakingInfoModel();

            Assert.Equal("Consensus error.", model.Errors);
        }
        public IActionResult GetStakingInfo()
        {
            try
            {
                // checks the request is valid
                if (!this.ModelState.IsValid)
                {
                    var errors = this.ModelState.Values.SelectMany(e => e.Errors.Select(m => m.ErrorMessage));
                    return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Formatting error", string.Join(Environment.NewLine, errors)));
                }

                GetStakingInfoModel model = this.posMinting != null?this.posMinting.GetGetStakingInfoModel() : new GetStakingInfoModel();

                return(this.Json(model));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public void CanStartStakingViaAPI()
        {
            try
            {
                var fullNode = this.apiTestsFixture.stratisStakeNode.FullNode;
                var apiURI   = fullNode.NodeService <ApiSettings>().ApiUri;

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

                using (client = new HttpClient())
                {
                    WalletManager walletManager = fullNode.NodeService <IWalletManager>() as WalletManager;

                    // create the wallet
                    var model = new StartStakingRequest {
                        Name = "apitest", Password = "******"
                    };
                    var mnemonic = walletManager.CreateWallet(model.Password, model.Name);

                    var content  = new StringContent(model.ToString(), Encoding.UTF8, "application/json");
                    var response = client.PostAsync(apiURI + "api/miner/startstaking", content).GetAwaiter().GetResult();
                    Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);

                    var responseText = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    Assert.Equal("", responseText);

                    MiningRPCController controller = fullNode.NodeService <MiningRPCController>();
                    GetStakingInfoModel info       = controller.GetStakingInfo();

                    Assert.NotNull(info);
                    Assert.True(info.Enabled);
                    Assert.False(info.Staking);
                }
            }
            finally
            {
                this.Dispose();
            }
        }
        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);
        }
 public StakingInfoClientEvent(GetStakingInfoModel stakingInfoModel)
 {
     this.StakingInfo = stakingInfoModel;
 }