예제 #1
0
        public void Hooks_Test()
        {
            var config = ConfigDeserializer.Deserialize("hooks.yml");

            var manager = new HooksManager();

            manager.RegisterHooks(config.Hooks);

            Assert.AreEqual(manager.Hooks[0], new Hook {
                Mode    = HookMode.Common,
                Type    = HookType.Post,
                Event   = HookEvent.AssetsMerge,
                Command = "a"
            });

            Assert.AreEqual(manager.Hooks[1], new Hook
            {
                Mode    = HookMode.Common,
                Type    = HookType.Post,
                Event   = HookEvent.AssetsMerge,
                Command = "b"
            });

            Assert.AreEqual(manager.Hooks[2], new Hook
            {
                Mode    = HookMode.Test,
                Type    = HookType.Post,
                Event   = HookEvent.SubtitlesUpdate,
                Command = "d"
            });
        }
예제 #2
0
        private async ValueTask <LanguageExt.Option <Config> > LoadConfig()
        {
            var(config, errors) = await serializer.Deserialize((FileInfoBase)options.Configuration);

            logger.LogTrace("config values: {@config}", config);
            if (errors.Any())
            {
                logger.LogError("Config file loading errors: {@errors}", errors);
                console.WriteLine(
                    new ContainerSpan(
                        "Error: there was a problem loading the config file:".StyleFailure(),
                        new ContainerSpan(
                            errors
                            .SelectMany(x => new[] {
                    EgretConsole.NewLine,
                    EgretConsole.SoftTab,
                    x.Message.StyleFailure()
                })
                            .ToArray()
                            )
                        )
                    );
                return(None);
            }

            return(config);
        }
예제 #3
0
        /// <summary>
        /// Loads a config from a file.
        /// If an instance is provided, the config will be loaded to that instance
        /// otherwise a new instance is created
        /// </summary>
        /// <param name="pathToFile">absolute path to the config file. '/' will be replaced with the DirectorySeparatorChar</param>
        /// <param name="instance">optional - instance of the existing config</param>
        /// <param name="configOptions">use this to configure the de/serializer</param>
        /// <typeparam name="TConfigType">type of the config to load</typeparam>
        /// <returns>instance of the loaded config</returns>
        public static TConfigType LoadConfigFile <TConfigType>(string pathToFile, [CanBeNull] TConfigType instance, ConfigOptions configOptions = null)
        {
            pathToFile = pathToFile.Replace('/', Path.DirectorySeparatorChar);
            if (!File.Exists(pathToFile))
            {
                if (instance == null)
                {
                    instance = (TConfigType)Activator.CreateInstance(typeof(TConfigType));
                }
                IEnumerable <string> lines = new ConfigSerializer(configOptions).Serialize(instance);

                using (StreamWriter writer = new StreamWriter(pathToFile, false)) {
                    foreach (string line in lines)
                    {
                        writer.WriteLine(line);
                    }
                }
                return(instance);
            }

            try {
                using (StreamReader reader = File.OpenText(pathToFile)) {
                    List <string> lines = new List <string>();
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            lines.Add(line);
                        }
                    }
                    ConfigDeserializer <TConfigType> deserializer = new ConfigDeserializer <TConfigType>(DeserializerUtils.Tokenize(lines).ToList(), configOptions);
                    return(instance == null?deserializer.Deserialize() : deserializer.Deserialize(instance));
                }
            } catch (Exception e) {
                Debug.LogError("Failed to load config at path: '" + pathToFile + "', caught exception: " + e);
                return(default);
        public void Test_Deserialize_SingleFieldType()
        {
            ExampleSingleFieldConfig expectedConfig = new ExampleSingleFieldConfig
            {
                firstField = new ExampleSingleFieldConfig.SingleFieldType1 {
                    secondField = new ExampleSingleFieldConfig.SingleFieldType2 {
                        a = 1, b = 2
                    }
                }
            };
            const string configString = @"
- a = 1
- b = 2
";

            ConfigDeserializer <ExampleSingleFieldConfig> configDeserializer = new ConfigDeserializer <ExampleSingleFieldConfig>(
                DeserializerUtils.Tokenize(new LineReader(new StringReader(configString))).ToList(),
                new ConfigOptions()
                );
            ExampleSingleFieldConfig deserializeResult = configDeserializer.Deserialize();

            Assert.AreEqual(expectedConfig, deserializeResult);
        }
        public void Test_Deserialize_ExistingSingleFieldType()
        {
            ExampleSingleFieldConfig targetInstance = new ExampleSingleFieldConfig
            {
                firstField = new ExampleSingleFieldConfig.SingleFieldType1 {
                    secondField = new ExampleSingleFieldConfig.SingleFieldType2 {
                        a = 1, b = 2
                    }
                }
            };
            const string configString = @"
- a = 3
- b = 4
";
            ConfigDeserializer <ExampleSingleFieldConfig> configDeserializer = new ConfigDeserializer <ExampleSingleFieldConfig>(
                DeserializerUtils.Tokenize(new LineReader(new StringReader(configString))).ToList(),
                new ConfigOptions()
                );

            configDeserializer.Deserialize(targetInstance);

            Assert.AreEqual(3, targetInstance.firstField.secondField.a);
            Assert.AreEqual(4, targetInstance.firstField.secondField.b);
        }
예제 #6
0
        public static void Main(string[] args)
        {
            var configFilepath = args[0];
            var password       = args[1];

            // config
            var nodeConfig      = ConfigDeserializer.Deserialize <NodeConfig>(configFilepath);
            var console         = ConsoleFactory.Build(nodeConfig.IsMiningNode);
            var ipAddress       = IpAddressProvider.GetLocalIpAddress();
            var electionEndTime = nodeConfig.IsClassDemo ? DateTime.Now.AddSeconds(120) : nodeConfig.ElectionEndTime;

            // password check
            var voterDb    = new VoterDatabaseFacade(nodeConfig.VoterDbFilepath);
            var foundMiner = voterDb.TryGetVoterEncryptedKeyPair(password, out var encryptedKeyPair);

            if (!foundMiner)
            {
                Console.WriteLine("incorrect password: you may not mine!");
                return;
            }

            // blockchain
            var blockchain = new Blockchain();

            // networking
            var registrarClientFactory     = new RegistrarClientFactory();
            var registrarClient            = registrarClientFactory.Build(ipAddress, RegistrarPort);
            var registrationRequestFactory = new RegistrationRequestFactory();
            var myConnectionInfo           = new NodeConnectionInfo(ipAddress, nodeConfig.Port);
            var knownNodeStore             = new KnownNodeStore();
            var nodeClientFactory          = new NodeClientFactory();
            var handshakeRequestFactory    = new HandshakeRequestFactory(blockchain);
            var nodeClientStore            = new NodeClientStore();
            var nodeServerFactory          = new NodeServerFactory();

            // votes
            var protoVoteFactory = new ProtoVoteFactory();
            var voteForwarder    = new VoteForwarder(nodeClientStore, protoVoteFactory);
            var voteMemoryPool   = new VoteMemoryPool(voteForwarder, console);

            // blocks
            var merkleNodeFactory = new MerkleNodeFactory();
            var merkleTreeFactory = new MerkleTreeFactory(merkleNodeFactory);
            var minerId           = encryptedKeyPair.PublicKey.GetBase64String();
            var blockFactory      = new BlockFactory(merkleTreeFactory, minerId);
            var protoBlockFactory = new ProtoBlockFactory(protoVoteFactory);
            var blockForwarder    = new BlockForwarder(nodeClientStore, protoBlockFactory);
            var voteValidator     = new VoteValidator(blockchain, voterDb, electionEndTime);
            var blockValidator    = new BlockValidator(blockFactory, voteValidator);
            var blockchainAdder   = new BlockchainAdder(blockchain, voteMemoryPool, blockForwarder, console);

            // mining
            var difficultyTarget = TargetFactory.Build(BlockHeader.DefaultBits);
            var miner            = new Miner(
                blockchain,
                voteMemoryPool,
                difficultyTarget,
                blockFactory,
                blockchainAdder,
                console);

            // interaction
            var voteSerializer           = new VoteSerializer();
            var electionAlgorithmFactory = new ElectionAlgorithmFactory(voteSerializer);
            var electionAlgorithm        = electionAlgorithmFactory.Build(nodeConfig.ElectionType);
            var electionResultProvider   = new ElectionResultProvider(
                electionAlgorithm,
                electionEndTime,
                voteMemoryPool,
                blockchain);
            var voterTerminal = new VoterTerminal.VoterTerminal(
                voterDb,
                nodeConfig.Candidates.ToArray(),
                voteSerializer,
                voteMemoryPool,
                electionResultProvider,
                blockchain);
            var votingBooth = new VoterTerminal.VoterBooth(voterTerminal, nodeConfig.ElectionType);

            // startup
            var nodeServer = nodeServerFactory.Build(
                myConnectionInfo,
                knownNodeStore,
                nodeClientFactory,
                nodeClientStore,
                voteMemoryPool,
                blockchain,
                miner,
                voteValidator,
                blockValidator,
                blockchainAdder,
                console);
            var boostrapper = new Bootstrapper(
                MinNetworkSize,
                knownNodeStore,
                nodeClientFactory,
                handshakeRequestFactory,
                nodeClientStore,
                registrarClient,
                registrationRequestFactory,
                nodeServer);

            Console.WriteLine("bootstrapping node network...");
            boostrapper.Bootstrap(myConnectionInfo);
            Console.WriteLine($"{MinNetworkSize} nodes in network! bootstrapping complete");

            if (nodeConfig.IsMiningNode)
            {
                Console.WriteLine("starting miner...");
                miner.Start();

                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("Press any key to quit");
                Console.ReadKey();
            }
            else
            {
                votingBooth.LaunchBooth();
            }
        }
        public void Test_Deserialize_Implicitly()
        {
            /* Scenarios to check:
             *  - explicit by default, no override
             *    + implicit by default, override both types
             *  - explicit by default, override outer type
             *    + implicit by default, override inner type
             *  - explicit by default, override inner type
             *    + implicit by default, override outer type
             *  - explicit by default, override both types
             *    + implicit by default, no override
             */

            IEnumerable <string> GetLines(bool outerIsExplicit, bool innerIsExplicit)
            {
                if (!outerIsExplicit)
                {
                    yield return("- a = 3");
                }
                yield return("- b = 4");

                if (!outerIsExplicit)
                {
                    yield return("- subClass :");

                    if (!innerIsExplicit)
                    {
                        yield return("-- a = 5");
                    }
                    yield return("-- b = 6");
                }
            }

            void RunTest(bool outerIsExplicit, bool innerIsExplicit, ConfigOptions configOptions)
            {
                ConfigDeserializer <ImplicitConfig> configDeserializer = new ConfigDeserializer <ImplicitConfig>(
                    DeserializerUtils.Tokenize(new LineReader(GetLines(outerIsExplicit, innerIsExplicit))).ToList(),
                    configOptions);
                ImplicitConfig result = configDeserializer.Deserialize();

                if (outerIsExplicit)
                {
                    Assert.AreEqual(0, result.a);
                    Assert.AreEqual(4, result.c);
                    Assert.AreEqual(null, result.subClass);
                }
                else
                {
                    Assert.AreEqual(3, result.a);
                    Assert.AreEqual(4, result.c);
                    Assert.NotNull(result.subClass);
                    Assert.AreEqual(innerIsExplicit ? 0 : 5, result.subClass.a);
                    Assert.AreEqual(6, result.subClass.c);
                }
            }

            Type outerType = typeof(ImplicitConfig);
            Type innerType = typeof(ImplicitConfig.SubClass);

            RunTest(true, true, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Explicit, verifyAllKeysSet = true
            });
            RunTest(true, true, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Implicit, explicitTypes = new List <Type> {
                    outerType, innerType
                }, verifyAllKeysSet = true
            });
            RunTest(false, true, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Explicit, implicitTypes = new List <Type> {
                    outerType
                }, verifyAllKeysSet = true
            });
            RunTest(false, true, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Implicit, explicitTypes = new List <Type> {
                    innerType
                }, verifyAllKeysSet = true
            });
            RunTest(true, false, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Explicit, implicitTypes = new List <Type> {
                    innerType
                }, verifyAllKeysSet = true
            });
            RunTest(true, false, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Implicit, explicitTypes = new List <Type> {
                    outerType
                }, verifyAllKeysSet = true
            });
            RunTest(false, false, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Explicit, implicitTypes = new List <Type> {
                    outerType, innerType
                }, verifyAllKeysSet = true
            });
            RunTest(false, false, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Implicit, verifyAllKeysSet = true
            });
        }
        public void Test_Deserialize_NullDeserializeToDefault()
        {
            ExampleNullableConfig expectedConfig = new ExampleNullableConfig {
                intValue     = 0,
                stringValue  = null,
                stringValue2 = "~",
                intList      = new List <int> {
                    0, 1
                },
                stringList = new List <string> {
                    null, "~"
                },
                subClassList = new List <ExampleNullableConfig.ExampleNullableSubClass> {
                    new ExampleNullableConfig.ExampleNullableSubClass {
                        a = null, b = 0
                    },
                    new ExampleNullableConfig.ExampleNullableSubClass {
                        a = "~", b = 1
                    }
                },
                intDict = new Dictionary <int, int> {
                    { 0, 0 },
                    { 1, 1 }
                },
                stringDict = new Dictionary <string, string> {
                    { "str1", null },
                    { "~", "~" }
                },
                subClassDict = new Dictionary <string, ExampleNullableConfig.ExampleNullableSubClass> {
                    { "str1", new ExampleNullableConfig.ExampleNullableSubClass {
                          a = null, b = 0
                      } },
                    { "~", new ExampleNullableConfig.ExampleNullableSubClass {
                          a = "~", b = 1
                      } }
                }
            };

            const string configString = @"
- intValue = ~
- stringValue = ~
- stringValue2 = ""~""
- intList :
-- ~
-- 1
- stringList :
-- ~
-- ""~""
- subClassList :
-- :
--- a = ~
--- b = ~
-- :
--- a = ""~""
--- b = 1
- intDict :
-- ~ = ~
-- 1 = 1
- stringDict :
-- str1 = ~
-- ""~"" = ""~""
- subClassDict :
-- str1 :
--- a = ~
--- b = ~
-- ""~"" :
--- a = ""~""
--- b = 1
";

            ConfigDeserializer <ExampleNullableConfig> configDeserializer = new ConfigDeserializer <ExampleNullableConfig>(
                DeserializerUtils.Tokenize(new LineReader(new StringReader(configString))).ToList(),
                new ConfigOptions()
                );
            ExampleNullableConfig deserializeResult = configDeserializer.Deserialize();

            Assert.AreEqual(expectedConfig, deserializeResult);
        }