public void onReceive(string msg)
        {
            var regex = new Regex(@"ok_sub_spot_(?<input>[^_]*)_(?<output>[^_]*)_ticker");

            //Console.WriteLine(msg);
            if (!regex.IsMatch(msg))
            {
                if (msg == "{\"event\":\"pong\"}")
                {
                    StateChangeAction?.BeginInvoke(1, null, null);
                }
                return;
            }
            try
            {
                var contracts = JsonConvert.DeserializeObject <List <Contract> >(msg);
                if (contracts == null)
                {
                    return;
                }
                foreach (var objContract in contracts)
                {
                    var match = regex.Match(objContract.channel);

                    Group input  = match.Groups["input"];
                    Group output = match.Groups["output"];
                    if (string.IsNullOrEmpty(input.Value) || string.IsNullOrEmpty(output.Value))
                    {
                        continue;
                    }
                    var matchput = $"{input.Value}_{output.Value}";
                    switch (matchput)
                    {
                    case "addChannel":
                        break;

                    default:

                        var currencieName = input.Value;
                        var value         = new Currencie();
                        MemoryDB.dictionary.AddOrUpdate(currencieName, s =>
                        {
                            var currencie = value;
                            return(Clone(output.Value, currencie, objContract));
                        }, (s, currencie) =>
                        {
                            return(Clone(output.Value, currencie, objContract));
                        });
                        MemoryDB.dictionary.TryGetValue(currencieName, out value);
                        UpdateCurrencyBodyAction?.BeginInvoke(matchput, input.Value.ToLower(), value, null, null);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Example #2
0
 public SP_CLASS_PARAMS(int Size, Scopes Scope, DiFunction Function, StateChangeAction State)
 {
     Profile       = 0;
     this.Size     = Size;
     this.Scope    = Scope;
     this.Function = Function;
     this.State    = State;
 }
Example #3
0
        public void StateChangeActionDefaultsTest()
        {
            StateChangeAction sca = new StateChangeAction();

            Assert.Equal(string.Empty, sca.Payload);
            Assert.Equal(string.Empty, sca.PayloadHash);
            Assert.Equal(UpdateMode.Unknown, sca.Mode);
        }
Example #4
0
        public void ShoudThrowOnUnableToPull()
        {
            StateChangeAction changeAction = new StateChangeAction
            {
                Mode        = UpdateMode.Docker,
                Payload     = "parity/parity:v2.3.4",
                PayloadHash = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514"
            };
            NodeState nodeState = new NodeState
            {
                DockerImage    = "parity/parity:v2.3.4",
                DockerChecksum = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514"
            };


            Mock <IDockerControl> mocDcc = new Mock <IDockerControl>(MockBehavior.Loose);

            // Setup image pull mock
            mocDcc.Setup(mock => mock.PullImage(
                             It.IsAny <ImagesCreateParameters>(),
                             It.IsAny <AuthConfig>(),
                             It.IsAny <Progress <JSONMessage> >()))
            .Throws <Exception>()
            .Verifiable("Did not pull correct image");


            MockConfigProvider confProvider = new MockConfigProvider();

            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "http://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = "/some/path",
                DockerControl         = mocDcc.Object,
                ConfigurationProvider = confProvider,
                ContractWrapper       = new MockContractWrapper()
            }, new MockLogger());

            // Run the update action
            Action updateDocker = () => { uw.UpdateDocker(changeAction, nodeState); };

            updateDocker.Should()
            .Throw <UpdateVerificationException>()
            .WithMessage("Unable to pull new image.");

            // Verify the mocks
            mocDcc.Verify();

            // make sure nothing else was called
            mocDcc.VerifyNoOtherCalls();

            // verify no new state was written
            confProvider.CurrentState.Should().BeNull();
        }
Example #5
0
        public void StateChangeActionSetgetTest(string payload, string hash, UpdateMode mode)
        {
            StateChangeAction sca = new StateChangeAction
            {
                Mode        = mode,
                Payload     = payload,
                PayloadHash = hash
            };

            Assert.Equal(payload, sca.Payload);
            Assert.Equal(hash, sca.PayloadHash);
            Assert.Equal(mode, sca.Mode);
        }
Example #6
0
        private IEnumerator ChangeState(StateEnum state, StateChangeAction action, float delay)
        {
            if (delay > 0f)
            {
                yield return(new WaitForSeconds(delay));
            }

            State = state;
            if (action != null)
            {
                action();
            }
        }
    public void SetState(GameState state)
    {
        GameState oldState = _state;

        _state = state;

        StateChangeAction handler = stateChanged;

        if (handler != null)
        {
            handler(oldState, state);
        }
    }
Example #8
0
        private IEnumerator ChangeState(StateEnum state, StateChangeAction action)
        {
            if (delay > 0f)
            {
                yield return(new WaitForSeconds(delay));
            }

            action();

            if (OnStateChanged != null)
            {
                OnStateChanged(state);
            }
        }
        public void ShouldFailtoVerifyWhenCurrentChainspecIsMissing()
        {
            // Test setup
            string expectedUrl  = "https://example.com/chain.json";
            string expectedHash = "8394d0987bd84c677122872aa67f60295b972eceb3f75bec068e83570d3c6999";

            // prepare directory
            string basePath = $"nodecontrol-tests-{Guid.NewGuid()}";
            string path     = Path.Join(Path.GetTempPath(), basePath);

            Directory.CreateDirectory(path);
            Directory.CreateDirectory(Path.Join(path, "config"));

            // get a mock dcc
            MockDockerControl mockDcc = new MockDockerControl();

            StateChangeAction sca = new StateChangeAction
            {
                Mode        = UpdateMode.ChainSpec,
                Payload     = expectedUrl,
                PayloadHash = expectedHash
            };

            // Run the test
            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "http://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = path,
                DockerControl         = mockDcc,
                ConfigurationProvider = new MockConfigProvider(),
                ContractWrapper       = new MockContractWrapper()
            }, new MockLogger());

            Action update = () =>
            {
                uw.UpdateChainSpec(sca);
            };

            // Execute test
            update.Should().Throw <UpdateVerificationException>()
            .WithMessage("Unable to read current chainspec");

            // should not call apply updates
            mockDcc.ApplyChangesCallCount.Should().Be(0);
        }
Example #10
0
        public void UpateChainSpecActionShouldNotVerify(StateChangeAction changeAction, NodeState state, string expectedMessage)
        {
            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "http://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = "/some/path",
                DockerControl         = new MockDockerControl(),
                ConfigurationProvider = new MockConfigProvider(),
                ContractWrapper       = new MockContractWrapper()
            }, new MockLogger());

            Action updateDocker = () => { uw.UpdateDocker(changeAction, state); };

            updateDocker.Should()
            .Throw <UpdateVerificationException>()
            .WithMessage(expectedMessage);
        }
Example #11
0
        private void UpdateSigning(StateChangeAction act)
        {
            if (act.Mode != UpdateMode.ToggleSigning)
            {
                throw new UpdateVerificationException("Action with wrong update mode passed");
            }

            // read current state to modify only signing
            NodeState newState = _configProvider.ReadCurrentState();

            // ReSharper disable once ConvertIfStatementToSwitchStatement - being explicit here
            if (act.Payload == "True")
            {
                newState.IsSigning = true;
            }
            else if (act.Payload == "False")
            {
                newState.IsSigning = false;
            }

            // Image is legit. update docker compose
            Log("Signing mode changed. Updating stack.");

            // modify docker-compose env file

            NodeState stateBeforeUpgrade = _configProvider.ReadCurrentState();

            // Write new config file and try to upgrade
            _configProvider.WriteNewState(newState);

            // restart/upgrade stack
            try
            {
                _dcc.ApplyChangesToStack(_stackPath, false);
            }
            catch
            {
                // Stack upgrade didn't work - rollback to last config file and rethrow
                _configProvider.WriteNewState(stateBeforeUpgrade);
                throw;
            }
        }
Example #12
0
        public void ShoudThrowOnBadHash()
        {
            string expectedImage = "parity/parity:v2.3.4";
            string expectedHash  = "bbbbcc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514";

            StateChangeAction changeAction = new StateChangeAction
            {
                Mode        = UpdateMode.Docker,
                Payload     = "parity/parity:v2.3.4",
                PayloadHash = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514"
            };
            NodeState nodeState = new NodeState
            {
                DockerImage    = "parity/parity:v2.3.4",
                DockerChecksum = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514"
            };


            Mock <IDockerControl> mocDcc = new Mock <IDockerControl>(MockBehavior.Loose);

            // Setup image pull mock
            mocDcc.Setup(mock => mock.PullImage(
                             It.Is <ImagesCreateParameters>(icp => icp.Tag == "v2.3.4" && icp.FromImage == "parity/parity"),
                             It.Is <AuthConfig>(obj => obj == null),
                             It.IsAny <Progress <JSONMessage> >()))
            .Verifiable("Did not pull correct image");

            // Setup inspect image mock
            mocDcc
            .Setup(mock => mock.InspectImage(
                       It.Is <string>(i => i == expectedImage)
                       ))
            .Returns(new ImageInspectResponse
            {
                ID = expectedHash
            })
            .Verifiable("Did not inspect the correct image");


            // setup delete mock
            mocDcc
            .Setup(mock => mock.DeleteImage(expectedImage))
            .Verifiable("Did not correctly delete the wrong image");

            MockConfigProvider confProvider = new MockConfigProvider();

            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "http://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = "/some/path",
                DockerControl         = mocDcc.Object,
                ConfigurationProvider = confProvider,
                ContractWrapper       = new MockContractWrapper()
            }, new MockLogger());

            // Run the update action
            Action updateDocker = () => { uw.UpdateDocker(changeAction, nodeState); };

            updateDocker.Should()
            .Throw <UpdateVerificationException>()
            .WithMessage("Docker image hashes don't match.");

            // Verify the mocks
            mocDcc.Verify();

            // make sure nothing else was called
            mocDcc.VerifyNoOtherCalls();

            // verify no new state was written
            confProvider.CurrentState.Should().BeNull();
        }
Example #13
0
        /// <summary>
        /// Pull and verify a new docker image and update the docker-compose file
        /// </summary>
        /// <param name="act">The action containing the new chainspec url and checksum</param>
        /// <param name="expectedState">The expected state that the action was derived from</param>
        /// <exception cref="UpdateVerificationException">
        /// Thrown when update is not able to be verified. Reasons:
        /// <list type="bullet">
        /// <item>The image is not able to be pulled</item>
        /// <item>Checksum of the downloaded content doesn't match</item>
        /// </list>
        /// </exception>
        public void UpdateDocker(StateChangeAction act, NodeState expectedState)
        {
            if (act.Mode != UpdateMode.Docker)
            {
                throw new UpdateVerificationException("Action with wrong update mode passed");
            }

            if (string.IsNullOrWhiteSpace(act.Payload) || string.IsNullOrWhiteSpace(act.PayloadHash))
            {
                throw new UpdateVerificationException("Payload or hash are empty");
            }

            if (act.Payload != expectedState.DockerImage || act.PayloadHash != expectedState.DockerChecksum)
            {
                throw new UpdateVerificationException("Action vs. node state mismatch");
            }


            Log($"Pulling new parity image [{act.Payload}] ..");

            // Prepare progress logging stub
            Progress <JSONMessage> progress = new Progress <JSONMessage>();

            try
            {
                // pull docker image
                _dcc.PullImage(new ImagesCreateParameters
                {
                    FromImage = act.Payload.Split(':')[0],
                    Tag       = act.Payload.Split(':')[1]
                }, null, progress);
            }
            catch (Exception e)
            {
                throw new UpdateVerificationException("Unable to pull new image.", e);
            }

            // verify docker image id against expected hash
            ImageInspectResponse inspectResult = _dcc.InspectImage(act.Payload);
            string dockerHash = inspectResult.ID.Replace("sha256:", string.Empty);

            if (dockerHash != act.PayloadHash)
            {
                Log("Image hashes don't match. Cancel update.");
                _dcc.DeleteImage(act.Payload);
                Log("Pulled imaged removed.");
                throw new UpdateVerificationException("Docker image hashes don't match.");
            }

            // Image is legit. update docker compose
            Log("Image valid. Updating stack.");

            NodeState stateBeforeUpgrade = _configProvider.ReadCurrentState();

            // Write new config file and try to upgrade
            _configProvider.WriteNewState(expectedState);

            // restart/upgrade stack
            try
            {
                _dcc.ApplyChangesToStack(_stackPath, false);
            }
            catch
            {
                // Stack upgrade didn't work - rollback to last config file and rethrow
                _configProvider.WriteNewState(stateBeforeUpgrade);
                throw;
            }
        }
Example #14
0
        /// <summary>
        /// Downloads, verifies and updates the chain spec file
        /// </summary>
        /// <param name="act">The action containing the new chainspec url and checksum</param>
        /// <param name="httpHandler">Http handler to use for the request (used in unit tests)</param>
        /// <exception cref="UpdateVerificationException">
        /// Thrown when update is not able to verify. This can happen when:
        /// <list type="bullet">
        /// <item>URL to chain file is not https://</item>
        /// <item>Checksum of the downloaded content doesn't match</item>
        /// <item>Unable to read the current chainspec file. Maybe someone messed with the file.</item>
        /// </list>
        /// </exception>
        public void UpdateChainSpec(StateChangeAction act, HttpMessageHandler httpHandler = null)
        {
            // TODO: needs to be moved into abstraction layer to allow unit testing

            if (httpHandler == null)
            {
                httpHandler = new HttpClientHandler();
            }

            if (string.IsNullOrWhiteSpace(act.Payload) || string.IsNullOrWhiteSpace(act.PayloadHash))
            {
                throw new UpdateVerificationException("Payload or hash are empty");
            }

            // verify https
            if (!act.Payload.StartsWith("https://"))
            {
                throw new UpdateVerificationException("Won't download chain spec from unencrypted URL");
            }

            // Check if given directory has a chain spec file
            string chainSpecPath = Path.Combine(_stackPath, "config/chainspec.json");

            if (!File.Exists(chainSpecPath))
            {
                throw new UpdateVerificationException("Unable to read current chainspec");
            }

            // download new chainspec
            string newChainSpec;

            try
            {
                using (HttpClient hc = new HttpClient(httpHandler))
                {
                    newChainSpec = hc.GetStringAsync(act.Payload).Result;
                }
            }
            catch (Exception e)
            {
                throw new UpdateVerificationException("Unable to download new chainspec", e);
            }

            // verify hash
            string newHash = HashString(newChainSpec);

            if (newHash != act.PayloadHash)
            {
                throw new UpdateVerificationException(
                          "Downloaded chainspec don't matches hash from chain");
            }

            // Backup current chainspec
            string fileTimestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString();

            File.Move(chainSpecPath,
                      Path.Combine(_stackPath, $"config/chainspec.json.{fileTimestamp}"));

            // write new
            File.WriteAllText(chainSpecPath, newChainSpec);

            // restart parity
            _dcc.ApplyChangesToStack(_stackPath, true);
        }
Example #15
0
 public SP_CLASS_PARAMS(Scopes Scope, DiFunction Function, StateChangeAction State) : this(8, Scope, Function, State)
 {
 }
        public void ShouldFailtoVerifyWhenUnableToDownload()
        {
            // Test setup
            string expectedUrl  = "https://example.com/chain.json";
            string expectedHash = "8394d0987bd84c677122872aa67f60295b972eceb3f75bec068e83570d3c6999";

            // prepare directory
            string basePath = $"nodecontrol-tests-{Guid.NewGuid()}";
            string path     = Path.Join(Path.GetTempPath(), basePath);

            Directory.CreateDirectory(path);
            Directory.CreateDirectory(Path.Join(path, "config"));

            // write existing dummy chainspec
            string existingChainSpecContent = "This is the existing chainspec file before update";

            File.WriteAllText(Path.Join(path, "config", "chainspec.json"), existingChainSpecContent);

            // get a mock dcc
            MockDockerControl mockDcc = new MockDockerControl();

            StateChangeAction sca = new StateChangeAction
            {
                Mode        = UpdateMode.ChainSpec,
                Payload     = expectedUrl,
                PayloadHash = expectedHash
            };

            // setup mock http handler
            Mock <HttpMessageHandler> handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Loose);

            handlerMock
            .Protected()
            // Setup the PROTECTED method to mock
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            // prepare the expected response of the mocked http call
            .ReturnsAsync((HttpRequestMessage request, CancellationToken cancellationToken)
                          => new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent("error")
            })
            .Verifiable();

            // Run the test
            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "http://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = path,
                DockerControl         = mockDcc,
                ConfigurationProvider = new MockConfigProvider(),
                ContractWrapper       = new MockContractWrapper()
            }, new MockLogger());

            Action update = () =>
            {
                uw.UpdateChainSpec(sca, handlerMock.Object);
            };

            // Execute test
            update.Should().Throw <UpdateVerificationException>()
            .WithMessage("Unable to download new chainspec")
            .WithInnerException <AggregateException>();


            // should not call apply updates
            mockDcc.ApplyChangesCallCount.Should().Be(0);

            // should not touch current chainspec
            string currentChainspecFileContents = File.ReadAllText(Path.Join(path, "config", "chainspec.json"));

            currentChainspecFileContents.Should().Be(existingChainSpecContent);
        }
        public void ShouldDownloadChainspec()
        {
            // Test setup
            string expectedUrl     = "https://example.com/chain.json";
            string expectedPayload = "This would be a complete chainspec file.";
            string expectedHash    = "8394d0987bd84c677122872aa67f60295b972eceb3f75bec068e83570d3c6999";

            // prepare directory
            string basePath = $"nodecontrol-tests-{Guid.NewGuid()}";
            string path     = Path.Join(Path.GetTempPath(), basePath);

            Directory.CreateDirectory(path);
            Directory.CreateDirectory(Path.Join(path, "config"));

            // write existing dummy chainspec
            File.WriteAllText(Path.Join(path, "config", "chainspec.json"), "This is not a chainspec file");

            // get a mock dcc
            MockDockerControl mockDcc = new MockDockerControl();

            StateChangeAction sca = new StateChangeAction
            {
                Mode        = UpdateMode.ChainSpec,
                Payload     = expectedUrl,
                PayloadHash = expectedHash
            };


            bool urlCorrect = false;
            // setup mock http handler
            Mock <HttpMessageHandler> handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            handlerMock
            .Protected()
            // Setup the PROTECTED method to mock
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            // prepare the expected response of the mocked http call
            .ReturnsAsync((HttpRequestMessage request, CancellationToken cancellationToken) =>
            {
                // make sure queried url is correct
                urlCorrect = request.RequestUri.ToString() == expectedUrl;

                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content             = new StringContent(expectedPayload);
                return(response);
            })
            .Verifiable();

            handlerMock
            .Protected()
            // Setup the PROTECTED method to mock
            .Setup(
                "Dispose",
                ItExpr.IsAny <bool>()
                )
            .Verifiable();


            // Run the test
            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "http://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = path,
                DockerControl         = mockDcc,
                ConfigurationProvider = new MockConfigProvider(),
                ContractWrapper       = new MockContractWrapper()
            }, new MockLogger());

            Action update = () =>
            {
                uw.UpdateChainSpec(sca, handlerMock.Object);
            };

            // Execute test
            update.Should().NotThrow();


            // Should have create a backup file

            // Should have written the new payload to file
            string newFileContents = File.ReadAllText(Path.Join(path, "config", "chainspec.json"));

            newFileContents.Should().Be(expectedPayload);

            // should have called with the correct url
            urlCorrect.Should().Be(true);

            // Should have triggered an update
            mockDcc.ApplyChangesCallCount.Should().Be(1);
            mockDcc.SendRestartOnly.Should().Be(true);
            mockDcc.SendPathToStack.Should().Be(path);

            // http client should have been disposed
            Action verifyDispose = () => handlerMock.VerifyAll();

            verifyDispose.Should().NotThrow();
        }
Example #18
0
 public StateMetadata(object value, Type type, StateChangeAction changeAction)
 {
     this.Value        = value;
     this.Type         = type;
     this.ChangeAction = changeAction;
 }
Example #19
0
 public static StateMetadata Create <T>(T value, StateChangeAction changeKind)
 {
     return(new StateMetadata(value, typeof(T), changeKind));
 }