private static void GeneratePublicPrivateKeys()
        {
            // Generate keys for signing.
            var    mnemonicForSigningKey = new Mnemonic(Wordlist.English, WordCount.Twelve);
            PubKey signingPubKey         = mnemonicForSigningKey.DeriveExtKey().PrivateKey.PubKey;

            // Generate keys for migning.
            var tool = new KeyTool(new DataFolder(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));
            Key key  = tool.GeneratePrivateKey();

            string savePath = tool.GetPrivateKeySavePath();

            tool.SavePrivateKey(key);
            PubKey miningPubKey = key.PubKey;

            Console.WriteLine($"-----------------------------------------------------------------------------");
            Console.WriteLine($"-- Please give the following 2 public keys to the federation administrator --");
            Console.WriteLine($"-----------------------------------------------------------------------------");
            Console.WriteLine($"1. Your signing pubkey: {Encoders.Hex.EncodeData(signingPubKey.ToBytes(false))}");
            Console.WriteLine($"2. Your mining pubkey: {Encoders.Hex.EncodeData(miningPubKey.ToBytes(false))}");
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine($"------------------------------------------------------------------------------------------");
            Console.WriteLine($"-- Please keep the following 12 words for yourself and note them down in a secure place --");
            Console.WriteLine($"------------------------------------------------------------------------------------------");
            Console.WriteLine($"Your signing mnemonic: {string.Join(" ", mnemonicForSigningKey.Words)}");
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine($"------------------------------------------------------------------------------------------------------------");
            Console.WriteLine($"-- Please save the following file in a secure place, you'll need it when the federation has been created. --");
            Console.WriteLine($"------------------------------------------------------------------------------------------------------------");
            Console.WriteLine($"File path: {savePath}");
            Console.WriteLine(Environment.NewLine);
        }
Example #2
0
        public Task Invoke(HttpContext context)
        {
            string token = "";

            if (context.Request.Cookies.TryGetValue("MRCTOKEN", out token))
            {
                string userinfo  = EncryptHelper.DesDecrypt(token, KeyTool.GetEncryptKey());
                string orginInfo = RedisHelper.Get(userinfo);
                if (orginInfo.IsNullOrEmpty())
                {
                    context.Items["islogin"] = false;
                    return(this._next(context));
                }
                ;
                AdminSession userSession = JsonHelper.Deserialize <AdminSession>(orginInfo);
                if (context.GetClientIP() != userSession.LoginIP)
                {
                    context.Items["islogin"] = false;
                }
                else
                {
                    context.Items["user"]    = userSession;
                    context.Items["islogin"] = true;
                }
            }
            return(this._next(context));
        }
        public void GetMiningTimestamp()
        {
            var tool = new KeyTool(null);
            Key key  = tool.GeneratePrivateKey();

            this.network = new TestPoANetwork(new List <PubKey>()
            {
                tool.GeneratePrivateKey().PubKey, key.PubKey, tool.GeneratePrivateKey().PubKey
            });

            var fedManager = new FederationManager(NodeSettings.Default(this.network), this.network, new LoggerFactory());

            this.slotsManager = new SlotsManager(this.network, fedManager, new LoggerFactory());

            List <PubKey> fedKeys    = this.consensusOptions.FederationPublicKeys;
            uint          roundStart = this.consensusOptions.TargetSpacingSeconds * (uint)fedKeys.Count * 5;

            fedManager.SetPrivatePropertyValue(nameof(FederationManager.IsFederationMember), true);
            fedManager.SetPrivatePropertyValue(nameof(FederationManager.FederationMemberKey), key);

            Assert.Equal(roundStart + this.consensusOptions.TargetSpacingSeconds, this.slotsManager.GetMiningTimestamp(roundStart));
            Assert.Equal(roundStart + this.consensusOptions.TargetSpacingSeconds, this.slotsManager.GetMiningTimestamp(roundStart + 4));

            roundStart += this.consensusOptions.TargetSpacingSeconds * (uint)fedKeys.Count;
            Assert.Equal(roundStart + this.consensusOptions.TargetSpacingSeconds, this.slotsManager.GetMiningTimestamp(roundStart - 5));
            Assert.Equal(roundStart + this.consensusOptions.TargetSpacingSeconds, this.slotsManager.GetMiningTimestamp(roundStart - this.consensusOptions.TargetSpacingSeconds + 1));

            Assert.True(this.slotsManager.IsValidTimestamp(this.slotsManager.GetMiningTimestamp(roundStart - 5)));
        }
Example #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="oldPassword">明文</param>
        /// <param name="newPassword">明文</param>
        public void ChangePassword(string userID, string oldPassword, string newPassword)
        {
            //EncryptHelper.DesEncrypt(newPassword);



            Sys_UserLogOn userLogOn = this.DbContext.Query <Sys_UserLogOn>().Where(a => a.UserId == userID).First();

            string encryptedOldPassword = EncryptHelper.DesEncrypt(oldPassword, userLogOn.UserSecretkey);

            if (encryptedOldPassword != userLogOn.UserPassword)
            {
                throw new InvalidInputException("旧密码不正确");
            }

            string newUserSecretkey     = KeyTool.GetEncryptKey();
            string newEncryptedPassword = EncryptHelper.DesEncrypt(newPassword, newUserSecretkey);

            this.DbContext.DoWithTransaction(() =>
            {
                this.DbContext.Update <Sys_UserLogOn>(a => a.UserId == userID, a => new Sys_UserLogOn()
                {
                    UserSecretkey = newUserSecretkey, UserPassword = newEncryptedPassword
                });
            });
        }
Example #5
0
        public void GetMiningTimestamp()
        {
            var tool = new KeyTool(new DataFolder(string.Empty));
            Key key  = tool.GeneratePrivateKey();

            this.network = new TestPoANetwork(new List <PubKey>()
            {
                tool.GeneratePrivateKey().PubKey, key.PubKey, tool.GeneratePrivateKey().PubKey
            });

            FederationManager fedManager = PoATestsBase.CreateFederationManager(this, this.network, new ExtendedLoggerFactory());

            this.slotsManager = new SlotsManager(this.network, fedManager, new LoggerFactory());

            List <PubKey> fedKeys    = this.federationManager.GetFederationMembers();
            uint          roundStart = this.consensusOptions.TargetSpacingSeconds * (uint)fedKeys.Count * 5;

            fedManager.SetPrivatePropertyValue(nameof(FederationManager.IsFederationMember), true);
            fedManager.SetPrivatePropertyValue(nameof(FederationManager.FederationMemberKey), key);

            Assert.Equal(roundStart + this.consensusOptions.TargetSpacingSeconds, this.slotsManager.GetMiningTimestamp(roundStart));
            Assert.Equal(roundStart + this.consensusOptions.TargetSpacingSeconds, this.slotsManager.GetMiningTimestamp(roundStart + 4));

            roundStart += this.consensusOptions.TargetSpacingSeconds * (uint)fedKeys.Count;
            Assert.Equal(roundStart + this.consensusOptions.TargetSpacingSeconds, this.slotsManager.GetMiningTimestamp(roundStart - 5));
            Assert.Equal(roundStart + this.consensusOptions.TargetSpacingSeconds, this.slotsManager.GetMiningTimestamp(roundStart - this.consensusOptions.TargetSpacingSeconds + 1));

            Assert.True(this.slotsManager.IsValidTimestamp(this.slotsManager.GetMiningTimestamp(roundStart - 5)));
        }
        public async Task <PubKey> JoinFederationAsync(JoinFederationRequestModel request, CancellationToken cancellationToken)
        {
            // Get the address pub key hash.
            var   address    = BitcoinAddress.Create(request.CollateralAddress, this.counterChainSettings.CounterChainNetwork);
            KeyId addressKey = PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(address.ScriptPubKey);

            // Get mining key.
            var keyTool  = new KeyTool(this.settings.DataFolder);
            Key minerKey = keyTool.LoadPrivateKey();

            if (minerKey == null)
            {
                throw new Exception($"The private key file ({KeyTool.KeyFileDefaultName}) has not been configured.");
            }

            var expectedCollateralAmount = CollateralFederationMember.GetCollateralAmountForPubKey(this.network, minerKey.PubKey);

            Money collateralAmount = new Money(expectedCollateralAmount, MoneyUnit.BTC);

            var joinRequest = new JoinFederationRequest(minerKey.PubKey, collateralAmount, addressKey);

            // Populate the RemovalEventId.
            var collateralFederationMember = new CollateralFederationMember(minerKey.PubKey, false, joinRequest.CollateralAmount, request.CollateralAddress);

            byte[] federationMemberBytes = (this.network.Consensus.ConsensusFactory as CollateralPoAConsensusFactory).SerializeFederationMember(collateralFederationMember);
            var    votingManager         = this.fullNode.NodeService <VotingManager>();
            Poll   poll = votingManager.GetFinishedPolls().FirstOrDefault(x => x.IsExecuted &&
                                                                          x.VotingData.Key == VoteKey.KickFederationMember && x.VotingData.Data.SequenceEqual(federationMemberBytes));

            joinRequest.RemovalEventId = (poll == null) ? Guid.Empty : new Guid(poll.PollExecutedBlockData.Hash.ToBytes().TakeLast(16).ToArray());

            // Get the signature by calling the counter-chain "signmessage" API.
            var signMessageRequest = new SignMessageRequest()
            {
                Message         = joinRequest.SignatureMessage,
                WalletName      = request.CollateralWalletName,
                Password        = request.CollateralWalletPassword,
                ExternalAddress = request.CollateralAddress
            };

            var    walletClient = new WalletClient(this.loggerFactory, this.httpClientFactory, $"http://{this.counterChainSettings.CounterChainApiHost}", this.counterChainSettings.CounterChainApiPort);
            string signature    = await walletClient.SignMessageAsync(signMessageRequest, cancellationToken);

            if (signature == null)
            {
                throw new Exception("Operation was cancelled during call to counter-chain to sign the collateral address.");
            }

            joinRequest.AddSignature(signature);

            var         walletTransactionHandler = this.fullNode.NodeService <IWalletTransactionHandler>();
            var         encoder = new JoinFederationRequestEncoder(this.loggerFactory);
            Transaction trx     = JoinFederationRequestBuilder.BuildTransaction(walletTransactionHandler, this.network, joinRequest, encoder, request.WalletName, request.WalletAccount, request.WalletPassword);

            var walletService = this.fullNode.NodeService <IWalletService>();
            await walletService.SendTransaction(new SendTransactionRequest(trx.ToHex()), cancellationToken);

            return(minerKey.PubKey);
        }
Example #7
0
        public PoAHeaderSignatureTests()
        {
            string testRootPath = Path.Combine(Path.GetTempPath(), this.GetType().Name);
            var    dataFolder   = new DataFolder(testRootPath);

            this.tool = new KeyTool(dataFolder);

            this.validator = new PoABlockHeaderValidator(new ExtendedLoggerFactory());
        }
Example #8
0
        public KeyToolTests()
        {
            string testRootPath = Path.Combine(Path.GetTempPath(), this.GetType().Name + "_" + nameof(this.CanSaveLoadKey));

            Directory.CreateDirectory(testRootPath);

            this.dataFolder = new DataFolder(testRootPath);
            this.tool       = new KeyTool(this.dataFolder);
        }
        public void GetMiningTimestamp()
        {
            var tool = new KeyTool(new DataFolder(string.Empty));
            Key key  = tool.GeneratePrivateKey();

            this.network = new TestPoANetwork(new List <PubKey>()
            {
                tool.GeneratePrivateKey().PubKey, key.PubKey, tool.GeneratePrivateKey().PubKey
            });

            (IFederationManager fedManager, IFederationHistory federationHistory) = PoATestsBase.CreateFederationManager(this, this.network, new ExtendedLoggerFactory(), new Signals.Signals(new LoggerFactory(), null));
            var header = new BlockHeader();

            this.chainIndexer.Setup(x => x.Tip).Returns(new ChainedHeader(header, header.GetHash(), 0));
            this.slotsManager = new SlotsManager(this.network, fedManager, federationHistory, this.chainIndexer.Object);

            List <IFederationMember> federationMembers = fedManager.GetFederationMembers();
            uint roundStart = this.consensusOptions.TargetSpacingSeconds * (uint)federationMembers.Count * 5;

            fedManager.SetPrivatePropertyValue(typeof(FederationManager), nameof(IFederationManager.CurrentFederationKey), key);
            fedManager.SetPrivatePropertyValue(typeof(FederationManager), nameof(this.federationManager.IsFederationMember), true);

            Assert.Equal(roundStart + this.consensusOptions.TargetSpacingSeconds, this.slotsManager.GetMiningTimestamp(roundStart));
            Assert.Equal(roundStart + this.consensusOptions.TargetSpacingSeconds, this.slotsManager.GetMiningTimestamp(roundStart + 4));

            roundStart += this.consensusOptions.TargetSpacingSeconds * (uint)federationMembers.Count;
            Assert.Equal(roundStart + this.consensusOptions.TargetSpacingSeconds, this.slotsManager.GetMiningTimestamp(roundStart - 5));
            Assert.Equal(roundStart + this.consensusOptions.TargetSpacingSeconds, this.slotsManager.GetMiningTimestamp(roundStart - this.consensusOptions.TargetSpacingSeconds + 1));

            Assert.True(this.slotsManager.IsValidTimestamp(this.slotsManager.GetMiningTimestamp(roundStart - 5)));

            uint thisTurnTimestamp = roundStart + this.consensusOptions.TargetSpacingSeconds;
            uint nextTurnTimestamp = thisTurnTimestamp + this.consensusOptions.TargetSpacingSeconds * (uint)federationMembers.Count;

            // If we are past our last timestamp's turn, always give us the NEXT timestamp.
            uint justPastOurTurnTime = thisTurnTimestamp + (this.consensusOptions.TargetSpacingSeconds / 2) + 1;

            Assert.Equal(nextTurnTimestamp, this.slotsManager.GetMiningTimestamp(justPastOurTurnTime));

            // If we are only just past our last timestamp, but still in the "range" and we haven't mined a block yet, get THIS turn's timestamp.
            Assert.Equal(thisTurnTimestamp, this.slotsManager.GetMiningTimestamp(thisTurnTimestamp + 1));

            // If we are only just past our last timestamp, but we've already mined a block there, then get the NEXT turn's timestamp.
            header = new BlockHeader
            {
                Time = thisTurnTimestamp
            };

            Mock.Get(federationHistory).Setup(x => x.GetFederationMemberForBlock(It.IsAny <ChainedHeader>())).Returns <ChainedHeader>((chainedHeader) =>
            {
                return(federationMembers[1]);
            });

            this.chainIndexer.Setup(x => x.Tip).Returns(new ChainedHeader(header, header.GetHash(), 0));
            this.slotsManager = new SlotsManager(this.network, fedManager, federationHistory, this.chainIndexer.Object);
            Assert.Equal(nextTurnTimestamp, this.slotsManager.GetMiningTimestamp(thisTurnTimestamp + 1));
        }
Example #10
0
        public CoreNode CreateWhitelistedContractPoANode(SmartContractsPoARegTest network, int nodeIndex)
        {
            string dataFolder = this.GetNextDataFolderName();

            CoreNode node     = this.CreateNode(new WhitelistedContractPoARunner(dataFolder, network, this.TimeProvider), "poa.conf");
            var      settings = new NodeSettings(network, args: new string[] { "-conf=poa.conf", "-datadir=" + dataFolder });

            var tool = new KeyTool(settings.DataFolder);

            tool.SavePrivateKey(network.FederationKeys[nodeIndex]);
            return(node);
        }
Example #11
0
        private bool CreateFederationKey()
        {
            var keyFilePath = Path.Combine(this.rootDataDir, this.sidechainNetwork.RootFolderName, this.sidechainNetwork.Name, KeyTool.KeyFileDefaultName);

            if (File.Exists(keyFilePath))
            {
                Console.WriteLine($"Your masternode public key file already exists.");
                return(true);
            }

            Console.Clear();
            Console.WriteLine($"Your masternode public key will now be generated.");

            string publicKeyPassphrase;

            do
            {
                Console.WriteLine($"Please enter a passphrase (this can be anything, but please write it down):");
                publicKeyPassphrase = Console.ReadLine();

                if (!string.IsNullOrEmpty(publicKeyPassphrase))
                {
                    break;
                }

                Console.WriteLine("ERROR: Please ensure that you enter a valid passphrase.");
            } while (true);



            // Generate keys for mining.
            var tool = new KeyTool(keyFilePath);

            Key key = tool.GeneratePrivateKey();

            string savePath = tool.GetPrivateKeySavePath();

            tool.SavePrivateKey(key);
            PubKey miningPubKey = key.PubKey;

            Console.WriteLine($"Your Masternode Public Key (PubKey) is: {Encoders.Hex.EncodeData(miningPubKey.ToBytes(false))}");

            if (publicKeyPassphrase != null)
            {
                Console.WriteLine(Environment.NewLine);
                Console.WriteLine($"Your passphrase: {publicKeyPassphrase}");
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine($"It has been saved in the root Cirrus data folder: {savePath}");
            Console.WriteLine($"Please ensure that you take a backup of this file.");
            return(true);
        }
Example #12
0
        public CoreNode CreatePoANode(PoANetwork network, Key key)
        {
            string   dataFolder = this.GetNextDataFolderName();
            CoreNode node       = this.CreateNode(new PoANodeRunner(dataFolder, network, this.TimeProvider), "poa.conf");

            var settings = new NodeSettings(network, args: new string[] { "-conf=poa.conf", "-datadir=" + dataFolder });
            var tool     = new KeyTool(settings.DataFolder);

            tool.SavePrivateKey(key);

            return(node);
        }
Example #13
0
        public CoreNode CreateSidechainNode(Network network, Key key)
        {
            var      agentName  = $"sidechain{Interlocked.Increment(ref agentCount)}";
            string   dataFolder = this.GetNextDataFolderName(agentName);
            CoreNode node       = this.CreateNode(new SidechainNodeRunner(dataFolder, agentName, network, this.TimeProvider), "poa.conf");

            var settings = new NodeSettings(network, args: new string[] { "-conf=poa.conf", "-datadir=" + dataFolder });
            var tool     = new KeyTool(settings.DataFolder);

            tool.SavePrivateKey(key);

            return(node);
        }
Example #14
0
        public void CreateDebugKeyStoreWithStrongPassword()
        {
            string keyfile = Path.Combine(TestName, "debug.keystore");
            string pass    = "******";

            if (File.Exists(keyfile))
            {
                File.Delete(keyfile);
            }
            var task = new AndroidCreateDebugKey {
                BuildEngine  = engine,
                KeyStore     = keyfile,
                StorePass    = pass,
                KeyAlias     = "teststringkey",
                KeyPass      = pass,
                KeyAlgorithm = "RSA",
                Validity     = 10000,
                StoreType    = "pkcs12",
                Command      = "-genkeypair",
                ToolPath     = keyToolPath,
            };

            Assert.IsTrue(task.Execute(), "Task should have succeeded.");
            Assert.AreEqual(0, errors.Count, "Task should have no errors.");
            Assert.AreEqual(0, warnings.Count, "Task should have no warnings.");
            Assert.AreEqual(0, task.ExitCode, "ExitCode should have been 0");

            messages.Clear();
            var keyToolTask = new KeyTool {
                BuildEngine = engine,
                KeyStore    = keyfile,
                StorePass   = pass,
                KeyAlias    = "teststringkey",
                KeyPass     = pass,
                Command     = "-list",
                ToolPath    = keyToolPath,
            };

            Assert.IsTrue(keyToolTask.Execute(), "Task should have succeeded.");
            Assert.AreEqual(0, errors.Count, "Task should have no errors.");
            Assert.AreEqual(0, warnings.Count, "Task should have no warnings.");
            Assert.AreEqual(0, task.ExitCode, "ExitCode should have been 0");
            string output = string.Join(" ", messages.Select(x => x.Message));

            Assert.IsTrue(output.Contains("Certificate fingerprint (SHA"), "Certificate SHA1 or SHA-256 should have been printed.");
        }
Example #15
0
        private static void GeneratePublicPrivateKeys(string passphrase, string keyPath, bool isMultiSigOutput = true)
        {
            // Generate keys for signing.
            var    mnemonicForSigningKey = new Mnemonic(Wordlist.English, WordCount.Twelve);
            PubKey signingPubKey         = mnemonicForSigningKey.DeriveExtKey(passphrase).PrivateKey.PubKey;

            // Generate keys for migning.
            var tool = new KeyTool(keyPath);

            Key key = tool.GeneratePrivateKey();

            string savePath = tool.GetPrivateKeySavePath();

            tool.SavePrivateKey(key);
            PubKey miningPubKey = key.PubKey;

            Console.WriteLine($"Your Masternode Public Key: {Encoders.Hex.EncodeData(miningPubKey.ToBytes(false))}");
            Console.WriteLine($"-----------------------------------------------------------------------------");

            if (isMultiSigOutput)
            {
                Console.WriteLine(
                    $"Your Masternode Signing Key: {Encoders.Hex.EncodeData(signingPubKey.ToBytes(false))}");
                Console.WriteLine(Environment.NewLine);
                Console.WriteLine(
                    $"------------------------------------------------------------------------------------------");
                Console.WriteLine(
                    $"-- Please keep the following 12 words for yourself and note them down in a secure place --");
                Console.WriteLine(
                    $"------------------------------------------------------------------------------------------");
                Console.WriteLine($"Your signing mnemonic: {string.Join(" ", mnemonicForSigningKey.Words)}");
            }

            if (passphrase != null)
            {
                Console.WriteLine(Environment.NewLine);
                Console.WriteLine($"Your passphrase: {passphrase}");
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine($"------------------------------------------------------------------------------------------------------------");
            Console.WriteLine($"-- Please save the following file in a secure place, you'll need it when the federation has been created. --");
            Console.WriteLine($"------------------------------------------------------------------------------------------------------------");
            Console.WriteLine($"File path: {savePath}");
            Console.WriteLine(Environment.NewLine);
        }
Example #16
0
        public void SignatureIsValidated()
        {
            var validationContext = new ValidationContext()
            {
                ChainedHeaderToValidate = this.currentHeader
            };
            var ruleContext = new RuleContext(validationContext, DateTimeOffset.Now);

            Key randomKey = new KeyTool(new DataFolder(string.Empty)).GeneratePrivateKey();

            this.poaHeaderValidator.Sign(randomKey, this.currentHeader.Header as PoABlockHeader);

            Assert.Throws <ConsensusErrorException>(() => this.signatureRule.Run(ruleContext));

            this.poaHeaderValidator.Sign(key, this.currentHeader.Header as PoABlockHeader);

            this.signatureRule.Run(ruleContext);
        }
Example #17
0
        private static bool RequiresKeyGeneration(NodeSettings nodeSettings)
        {
            bool generateSetting = nodeSettings.ConfigReader.GetOrDefault("generateKeyPair", false);

            if (generateSetting)
            {
                return(true);
            }

            var tool = new KeyTool(nodeSettings.DataFolder);

            if (tool.LoadPrivateKey() == null)
            {
                return(true);
            }

            return(false);
        }
Example #18
0
        public void ListSuccessWithPassword()
        {
            GetValidKeyStore();

            var task = new KeyTool {
                BuildEngine = engine,
                KeyStore    = temp,
                StorePass   = "******",
                KeyAlias    = "mykey",
                KeyPass     = "******",
                Command     = "-list",
                ToolPath    = keyToolPath,
            };

            Assert.IsTrue(task.Execute(), "Task should have succeeded.");
            Assert.AreEqual(0, errors.Count, "Task should have no errors.");
            Assert.AreEqual(0, warnings.Count, "Task should have no warnings.");
        }
Example #19
0
        public void ListEmptyKey()
        {
            var task = new KeyTool {
                BuildEngine = engine,
                KeyStore    = temp,
                StorePass   = "******",
                KeyAlias    = "mykey",
                KeyPass     = "******",
                Command     = "-list",
                ToolPath    = keyToolPath,
            };

            Assert.IsFalse(task.Execute(), "Task should have failed.");
            Assert.AreEqual(1, errors.Count, "Task should have one error.");
            Assert.AreEqual(0, warnings.Count);
            var error = errors [0];

            Assert.AreEqual($"keytool error: java.lang.Exception: Keystore file exists, but is empty: {temp}", error.Message);
            Assert.AreEqual("ANDKT0000", error.Code);
        }
        public void SignatureIsValidated()
        {
            var validationContext = new ValidationContext()
            {
                ChainedHeaderToValidate = this.currentHeader
            };
            var ruleContext = new RuleContext(validationContext, DateTimeOffset.Now);

            Key randomKey = new KeyTool(new DataFolder(string.Empty)).GeneratePrivateKey();

            this.poaHeaderValidator.Sign(randomKey, this.currentHeader.Header as PoABlockHeader);

            this.chainState.ConsensusTip = new ChainedHeader(this.network.GetGenesis().Header, this.network.GetGenesis().GetHash(), 0);

            Assert.Throws <ConsensusErrorException>(() => this.signatureRule.RunAsync(ruleContext).GetAwaiter().GetResult());

            this.poaHeaderValidator.Sign(key, this.currentHeader.Header as PoABlockHeader);

            this.signatureRule.RunAsync(ruleContext).GetAwaiter().GetResult();
        }
Example #21
0
        /// <summary>
        /// This locates the required discount, Purchase or Sale.
        /// </summary>
        /// <param name="discountFullyLoaded"></param>
        /// <param name="discountType"></param>
        /// <returns></returns>
        private Discount FindGivenDiscount(Discount discountFullyLoaded, DiscountTypeENUM discountType)
        {
            //Initialize the DALs
            //DiscountDAL discountDAL = new DiscountDAL(_db, _user);
            DiscountPrecedenceDAL     discountPrecedenceDAL  = new DiscountPrecedenceDAL(_db, _user);
            List <DiscountPrecedence> discountPrecedenceList = new List <DiscountPrecedence>();

            switch (discountType)
            {
            case DiscountTypeENUM.Unknown:
                return(null);

            case DiscountTypeENUM.Sale:
                discountPrecedenceList = discountPrecedenceDAL.FindAllRulesByRankSale().ToList();
                break;

            case DiscountTypeENUM.Purchase:
                discountPrecedenceList = discountPrecedenceDAL.FindAllRulesByRankPurchase().ToList();
                break;

            default:
                return(null);
            }



            //now search them according to the precede
            if (!discountPrecedenceList.IsNullOrEmpty())
            {
                //Break out of this loop if a discount is found
                foreach (var rule in discountPrecedenceList)
                {
                    //Load the rule into the fully loaded Discount for which we are checking
                    KeyTool  k             = new KeyTool(discountFullyLoaded, rule.DiscountRuleEnum);
                    Discount discountFound = FindForDiscountKey(k.Key);

                    return(discountFound);
                }
            }
            return(null);
        }
Example #22
0
        private static void GenerateFederationKey(DataFolder dataFolder)
        {
            var tool = new KeyTool(dataFolder);
            Key key  = tool.GeneratePrivateKey();

            string savePath = tool.GetPrivateKeySavePath();

            tool.SavePrivateKey(key);

            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine($"Federation key pair was generated and saved to {savePath}.");
            stringBuilder.AppendLine("Make sure to back it up!");
            stringBuilder.AppendLine($"Your public key is {key.PubKey}.");
            stringBuilder.AppendLine();
            stringBuilder.AppendLine("Press eny key to exit...");

            Console.WriteLine(stringBuilder.ToString());

            Console.ReadKey();
        }
Example #23
0
        public MainWindowViewModel(Window window, KeyTool keyTool, CommandExecutor executor,
                                   TemplatesModule templatesModule)
        {
            _window          = window ?? throw new ArgumentNullException(nameof(window));
            _keyTool         = keyTool ?? throw new ArgumentNullException(nameof(keyTool));
            _executor        = executor ?? throw new ArgumentNullException(nameof(executor));
            _templatesModule = templatesModule ?? throw new ArgumentNullException(nameof(templatesModule));

            _executor.LogMessage += PrintMessage;

            this.WhenAnyValue(x => x.BundlePath, x => x.ApksPath)
            .Where(t => string.IsNullOrWhiteSpace(t.Item2))
            .Where(t => !string.IsNullOrWhiteSpace(t.Item1))
            .Where(t => string.Equals(Path.GetExtension(t.Item1) !.Substring(1), ExtAab))
            .Select(t => Path.ChangeExtension(t.Item1, ExtApks))
            .Subscribe(path => ApksPath = path);

            this.WhenAnyValue(x => x.KeystorePath, x => x.KeystorePassword)
            .Select(x => new { Path = x.Item1, Pass = x.Item2 })
            .Where(x => !string.IsNullOrWhiteSpace(x.Path))
            .Where(x => !string.IsNullOrWhiteSpace(x.Pass))
            .Where(x => (File.GetAttributes(x.Path) & FileAttributes.Directory) != FileAttributes.Directory)
            .Where(x => File.Exists(x.Path))
            .Subscribe(x => UpdateAliases());

            _executeModes = new[]
            {
                ExecuteMode.BuildApks,
                ExecuteMode.InstallApks,
                ExecuteMode.ShowApkSize
            };

            ExecuteModesNames = new ObservableCollection <string>(_executeModes.Select(m => m.GetModeName()));
            AvailableAliases  = new ObservableCollection <string>();

            _isOnBuildMode = this.WhenAnyValue(x => x.SelectedExecuteModeIndex)
                             .Select(index => _executeModes[index])
                             .Select(mode => mode == ExecuteMode.BuildApks)
                             .ToProperty(this, x => x.IsOnBuildMode);
        }
Example #24
0
        private static void GenerateServiceNodeKey(NodeSettings nodeSettings)
        {
            var tool = new KeyTool(nodeSettings.DataFolder);
            Key key  = tool.GeneratePrivateKey();

            string savePath = tool.GetPrivateKeySavePath();

            tool.SavePrivateKey(key);

            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine($"ServiceNode key pair was generated and saved to {savePath}.");
            stringBuilder.AppendLine("Make sure to back it up!");
            stringBuilder.AppendLine($"Your public key is {key.PubKey}.");
            stringBuilder.AppendLine();
            stringBuilder.AppendLine("You can now restart the node to use the key pair. If you need to re-generate add generateKeyPair to settings");
            stringBuilder.AppendLine("Press eny key to exit...");

            Console.WriteLine(stringBuilder.ToString());

            Console.ReadKey();
        }
Example #25
0
        public void ListInvalidAlias()
        {
            GetValidKeyStore();

            var task = new KeyTool {
                BuildEngine = engine,
                KeyStore    = temp,
                StorePass   = "******",
                KeyAlias    = "asdf",
                KeyPass     = "******",
                Command     = "-list",
                ToolPath    = keyToolPath,
            };

            Assert.IsFalse(task.Execute(), "Task should have failed.");
            Assert.AreEqual(1, errors.Count, "Task should have one error.");
            Assert.AreEqual(0, warnings.Count, "Task should have no warnings.");
            var error = errors [0];

            Assert.AreEqual($"keytool error: java.lang.Exception: Alias <{task.KeyAlias}> does not exist", error.Message);
            Assert.AreEqual("ANDKT0000", error.Code);
        }
Example #26
0
        public void ListInvalidPassword()
        {
            GetValidKeyStore();

            var task = new KeyTool {
                BuildEngine = engine,
                KeyStore    = temp,
                StorePass   = "******",
                KeyAlias    = "mykey",
                KeyPass     = "******",
                Command     = "-list",
                ToolPath    = keyToolPath,
            };

            Assert.IsFalse(task.Execute(), "Task should have failed.");
            Assert.AreEqual(1, errors.Count, "Task should have one error.");
            Assert.AreEqual(0, warnings.Count, "Task should have no warnings.");
            var error = errors [0];

            Assert.AreEqual("keytool error: java.io.IOException: Keystore was tampered with, or password was incorrect", error.Message);
            Assert.AreEqual("ANDKT0000", error.Code);
        }
        public void CheckSignaturesEqual()
        {
            Block block = this.network.Consensus.ConsensusFactory.CreateBlock();

            var validationContext = new ValidationContext()
            {
                ChainedHeaderToValidate = this.currentHeader, BlockToValidate = block
            };
            var ruleContext = new RuleContext(validationContext, DateTimeOffset.Now);

            var tool = new KeyTool(new DataFolder(string.Empty));
            Key key1 = tool.GeneratePrivateKey();
            Key key2 = tool.GeneratePrivateKey();

            this.poaHeaderValidator.Sign(key1, this.currentHeader.Header as PoABlockHeader);
            this.poaHeaderValidator.Sign(key2, block.Header as PoABlockHeader);

            Assert.Throws <ConsensusErrorException>(() => this.integritySignatureRule.Run(ruleContext));

            (block.Header as PoABlockHeader).BlockSignature = (this.currentHeader.Header as PoABlockHeader).BlockSignature;

            this.integritySignatureRule.Run(ruleContext);
        }
Example #28
0
        public virtual void Start()
        {
            LoadServiceNodes();

            // TODO: what if load fails? Shouldn't we sync again

            if (this.ServiceNodes == null)
            {
                this.ServiceNodes = new List <IServiceNode>();
                SaveServiceNodes();
            }

            this.Logger.LogInformation("Network contains {0} service nodes. Their public keys are: {1}",
                                       this.ServiceNodes.Count, Environment.NewLine + string.Join(Environment.NewLine, this.ServiceNodes));

            // Load key.
            Key key = new KeyTool(this.settings.DataFolder).LoadPrivateKey();

            this.CurrentServiceNodeKey = key;
            SetIsServiceNode();

            if (this.CurrentServiceNodeKey == null)
            {
                this.Logger.LogTrace("(-)[NOT_SERVICE_NODE]");
                return;
            }

            // Loaded key has to be a key for current service node.
            if (this.ServiceNodes.All(x => x.EcdsaPubKey != this.CurrentServiceNodeKey.PubKey))
            {
                string message = "Key provided is not registered on the network!";

                this.Logger.LogWarning(message);
            }

            this.Logger.LogInformation("ServiceNode key pair was successfully loaded. Your public key is: '{0}'.", this.CurrentServiceNodeKey.PubKey);
        }
Example #29
0
        public void CreateDebugKeyStore()
        {
            string keyfile = Path.Combine(TestName, "debug.keystore");

            if (File.Exists(keyfile))
            {
                File.Delete(keyfile);
            }
            var task = new AndroidCreateDebugKey {
                BuildEngine  = engine,
                KeyStore     = keyfile,
                StorePass    = "******",
                KeyAlias     = "androiddebugkey",
                KeyPass      = "******",
                KeyAlgorithm = "RSA",
                Validity     = 10000,
                StoreType    = "pkcs12",
                Command      = "-genkeypair",
                ToolPath     = keyToolPath,
            };

            Assert.IsTrue(task.Execute(), "Task should have succeeded.");
            Assert.AreEqual(0, errors.Count, "Task should have no errors.");
            Assert.AreEqual(0, warnings.Count, "Task should have no warnings.");

            var keyToolTask = new KeyTool {
                BuildEngine = engine,
                KeyStore    = keyfile,
                StorePass   = "******",
                KeyAlias    = "androiddebugkey",
                KeyPass     = "******",
                Command     = "-list",
                ToolPath    = keyToolPath,
            };

            Assert.IsTrue(keyToolTask.Execute(), "Task should have succeeded.");
        }
        public async Task <IActionResult> RegisterAsync(RegisterServiceNodeRequest request)
        {
            try
            {
                var registration = new ServiceNodeRegistration(this.network,
                                                               this.nodeSettings,
                                                               this.broadcasterManager,
                                                               this.walletTransactionHandler,
                                                               this.walletManager,
                                                               this.serviceNodeManager);

                Key key = new KeyTool(this.nodeSettings.DataFolder).LoadPrivateKey();

                (KeyId collateralPubKeyHash, KeyId rewardPubKeyHash) = GetPubKeyHashes(this.serviceNodeSettings, request.WalletName, request.AccountName);

                var config = new ServiceNodeRegistrationConfig
                {
                    ProtocolVersion      = (int)ServiceNodeProtocolVersion.INITIAL,
                    Ipv4Address          = this.serviceNodeSettings.Ipv4Address ?? IPAddress.None,
                    Ipv6Address          = this.serviceNodeSettings.Ipv6Address ?? IPAddress.IPv6None,
                    OnionAddress         = null,
                    Port                 = this.serviceNodeSettings.Port,
                    PrivateKey           = key,
                    CollateralPubKeyHash = collateralPubKeyHash,
                    RewardPubKeyHash     = rewardPubKeyHash,
                    TxFeeValue           = this.serviceNodeSettings.TxFeeValue,
                    TxOutputValue        = this.serviceNodeSettings.TxOutputValue,
                    ServiceEndpoint      = this.serviceNodeSettings.ServiceEndpoint
                };

                if (!registration.CheckExistingRegistration(config))
                {
                    this.logger.LogInformation("{Time} Creating or updating node registration", DateTime.Now);
                    Transaction regTx = await registration.PerformRegistrationAsync(config, request.WalletName, request.Password, request.AccountName);

                    if (regTx != null)
                    {
                        this.logger.LogInformation("{Time} Submitted node registration transaction {TxId} for broadcast", DateTime.Now, regTx.GetHash().ToString());
                    }
                    else
                    {
                        this.logger.LogInformation("{Time} Unable to broadcast transaction", DateTime.Now);
                        Environment.Exit(0);
                    }

                    return(Ok(new RegisterServiceNodeResponse
                    {
                        CollateralPubKeyHash = collateralPubKeyHash.ToString(),
                        RewardPubKeyHash = rewardPubKeyHash.ToString(),
                        RegistrationTxHash = regTx.GetHash().ToString()
                    }));
                }
                else
                {
                    logger.LogInformation("{Time} Node registration has already been performed", DateTime.Now);
                    return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Node registration failed", "Registration has already been performed successfully, you can't do it again."));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }