Esempio n. 1
0
        public void GiveMoney(Money amount, Account account, KeyId returnAddress, KeyId to, params Chain[] chains)
        {
            var entries = account.GetEntriesToCover(amount);
            var tx = new Transaction();
            foreach(var entry in entries)
            {
                tx.Inputs.Add(new TxIn(entry.OutPoint));
            }
            var refund = entries.Select(e => e.TxOut.Value).Sum() - amount;
            if(refund < 0)
                throw new InvalidOperationException("Not enough money in account");
            if(refund > 0)
            {
                tx.Outputs.Add(new TxOut(refund, returnAddress));
            }
            tx.Outputs.Add(new TxOut(amount, to));

            var block = TestUtils.CreateFakeBlock(tx);
            if(chains != null)
            {
                foreach(var c in chains)
                {
                    var localBlock = block.Clone();
                    localBlock.Header.HashPrevBlock = c.Tip.Header.GetHash();
                    c.GetOrAdd(localBlock.Header);
                    _Index.Put(localBlock);
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GpgApi.GpgChangePassword"/> class.
        /// </summary>
        /// <param name="keyId"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgChangePassword(KeyId keyId)
        {
            if (keyId == null)
                throw new ArgumentNullException("keyId");

            KeyId = keyId;
        }
Esempio n. 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GpgApi.GpgDeleteUserId"/> class.
        /// </summary>
        /// <param name="keyId"></param>
        /// <param name="index"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgDeleteUserId(KeyId keyId, UInt32 index)
        {
            if (keyId == null)
                throw new ArgumentNullException("keyId");

            KeyId = keyId;
            Index = index;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GpgApi.GpgChangeExpiration"/> class.
        /// </summary>
        /// <param name="keyId"></param>
        /// <param name="expirationDate"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgChangeExpiration(KeyId keyId, DateTime expirationDate)
        {
            if (keyId == null)
                throw new ArgumentNullException("keyId");

            KeyId = keyId;
            ExpirationDate = expirationDate;
        }
Esempio n. 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GpgApi.GpgExportKey"/> class.
        /// </summary>
        /// <param name="keyId"></param>
        /// <param name="privateKey"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgExportKey(KeyId keyId, Boolean privateKey)
        {
            if (keyId == null)
                throw new ArgumentNullException("keyId");

            KeyId = keyId;
            PrivateKey = privateKey;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GpgApi.GpgChangeOwnerTrust"/> class.
        /// </summary>
        /// <param name="keyId"></param>
        /// <param name="ownerTrust"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgChangeOwnerTrust(KeyId keyId, KeyOwnerTrust ownerTrust)
        {
            if (keyId == null)
                throw new ArgumentNullException("keyId");

            KeyId = keyId;
            OwnerTrust = ownerTrust;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GpgApi.GpgChangePrimaryUserInfo"/> class.
        /// </summary>
        /// <param name="keyId"></param>
        /// <param name="index"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgChangePrimaryUserInfo(KeyId keyId, UInt32 index)
        {
            if (keyId == null)
                throw new ArgumentNullException("keyId");

            KeyId = keyId;
            Index = index;
        }
Esempio n. 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GpgApi.GpgLoadPhoto"/> class.
        /// </summary>
        /// <param name="keyId"></param>
        /// <param name="index"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgLoadPhoto(KeyId keyId, UInt32 index)
        {
            if (keyId == null)
                throw new ArgumentNullException("keyId");

            KeyId = keyId;
            Index = index;
            Image = null;
        }
Esempio n. 9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GpgApi.GpgEncrypt"/> class.
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="encryptedFileName"></param>
 /// <param name="armored"></param>
 /// <param name="hideUserIds"></param>
 /// <param name="signatureKeyId"></param>
 /// <param name="recipients"></param>
 /// <param name="cipherAlgorithm"></param>
 public GpgEncrypt(String fileName, String encryptedFileName, Boolean armored, Boolean hideUserIds, KeyId signatureKeyId, IEnumerable<KeyId> recipients, CipherAlgorithm cipherAlgorithm)
 {
     FileName = fileName;
     EncryptedFileName = encryptedFileName;
     Armored = armored;
     HideUserIds = hideUserIds;
     SignatureKeyId = signatureKeyId;
     Recipients = recipients;
     CipherAlgorithm = cipherAlgorithm;
 }
Esempio n. 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GpgApi.GpgAddPhoto"/> class.
        /// </summary>
        /// <param name="keyId"></param>
        /// <param name="photoPath"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgAddPhoto(KeyId keyId, String photoPath)
        {
            if (keyId == null)
                throw new ArgumentNullException("keyId");

            if (photoPath == null)
                throw new ArgumentNullException("photoPath");

            KeyId = keyId;
            PhotoPath = photoPath;
        }
Esempio n. 11
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="signatureKeyId"></param>
        /// <param name="fileName"></param>
        /// <param name="signedFileName"></param>
        /// <param name="armored"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgSign(KeyId signatureKeyId, String fileName, String signedFileName, Boolean armored)
        {
            if (signatureKeyId == null)
                throw new ArgumentNullException("signatureKeyId");

            SignatureKeyId = signatureKeyId;
            FileName = fileName;
            SignedFileName = signedFileName;
            Armored = armored;
            Signed = false;
            KeyAlgorithm = KeyAlgorithm.None;
            DigestAlgorithm = DigestAlgorithm.None;
        }
Esempio n. 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GpgApi.GpgImportKey"/> class.
        /// </summary>
        /// <param name="keyId"></param>
        /// <param name="servers"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgImportKey(KeyId keyId, IEnumerable<Uri> servers)
        {
            if (keyId == null)
                throw new ArgumentNullException("keyId");

            if (servers == null)
                throw new ArgumentNullException("servers");

            FileName = null;
            KeyId = keyId;
            Servers = servers;
            FingerPrint = null;
            Import = Import.None;
        }
Esempio n. 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GpgApi.GpgAddUserInfo"/> class.
        /// </summary>
        /// <param name="keyId"></param>
        /// <param name="name"></param>
        /// <param name="email"></param>
        /// <param name="comment"></param>
        /// <exception cref="System.ArgumentNullException"/>
        public GpgAddUserInfo(KeyId keyId, Name name, Email email, String comment)
        {
            if (keyId == null)
                throw new ArgumentNullException("keyId");

            if (name == null)
                throw new ArgumentNullException("name");

            if (email == null)
                throw new ArgumentNullException("email");

            KeyId = keyId;
            Name = name;
            Email = email;
            Comment = comment;
        }
Esempio n. 14
0
 public System.Collections.Generic.List <InputBind> GetBinds(KeyId id)
 {
     return(_bindConfig.GetBinds(id));
 }
Esempio n. 15
0
        /// <summary>
        ///     提交添加
        /// </summary>
        private bool SubmintAdd()
        {
            //生成调度单
            LHSalaryDriver dispatch = new LHSalaryDriver();

            //调度单号生成
            string newKeyId = SequenceService.CreateSequence("PC", CurrentUser.AccountComId);

            dispatch.KeyId       = newKeyId; lblKeyId.Text = newKeyId;
            dispatch.FBeginDate  = dptBeginDate.SelectedDate;
            dispatch.FEndDate    = dptEnd.SelectedDate;
            dispatch.FVehicleNum = ddlFVehicleNum.SelectedValue;
            dispatch.FDriver     = GasHelper.GetDropDownListArrayString(ddlFDriver.SelectedItemArray);
            dispatch.FSupercargo = GasHelper.GetDropDownListArrayString(ddlFSupercargo.SelectedItemArray);
            dispatch.FLogistics  = ddlLogistics.SelectedText;
            dispatch.FFrom       = ddlFrom.SelectedValue;
            dispatch.FTo         = ddlTo.SelectedValue;
            dispatch.FAuditFlag  = "0";

            DispatchCenterService.Add(dispatch);


            string[] keys = KeyId.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string key in keys)
            {
                if (!string.IsNullOrEmpty(key))
                {
                    //状态
                    LHBillStatus flow = new LHBillStatus
                    {
                        KeyId      = key,
                        FCompanyId = CurrentUser.AccountComId,
                        FDeptId    = CurrentUser.AccountOrgId,
                        FOperator  = CurrentUser.AccountName,
                        FDate      = Convert.ToDateTime(dptBeginDate.SelectedDate),

                        FActionName = "配车",

                        FMemo = string.Format(@"单据号{0}被{1}作配车业务处理。", key, CurrentUser.AccountName)
                    };

                    BillStatusService.Add(flow);

                    LHStockOut info = new StockOutService().FirstOrDefault(p => p.KeyId == key && p.FCompanyId == CurrentUser.AccountComId);

                    if (info != null)
                    {
                        Dictionary <string, object> infoParms = new Dictionary <string, object>();
                        infoParms.Clear();

                        infoParms.Add("@keyid", info.FLogisticsNumber);
                        infoParms.Add("@companyId", CurrentUser.AccountComId);
                        infoParms.Add("@FVehicleNum", ddlFVehicleNum.SelectedValue);
                        infoParms.Add("@FDriver", GasHelper.GetDropDownListArrayString(ddlFDriver.SelectedItemArray));
                        infoParms.Add("@FSupercargo", GasHelper.GetDropDownListArrayString(ddlFSupercargo.SelectedItemArray));
                        infoParms.Add("@FDispatchNum", newKeyId); //调度单号

                        SqlService.ExecuteProcedureCommand("proc_DispatchCenter", infoParms);
                    }


                    //变更单据上的司机、押韵员、车牌号
                    Dictionary <string, object> parms = new Dictionary <string, object>();
                    parms.Clear();

                    parms.Add("@keyid", key);
                    parms.Add("@companyId", CurrentUser.AccountComId);
                    parms.Add("@FVehicleNum", ddlFVehicleNum.SelectedValue);
                    parms.Add("@FDriver", GasHelper.GetDropDownListArrayString(ddlFDriver.SelectedItemArray));
                    parms.Add("@FSupercargo", GasHelper.GetDropDownListArrayString(ddlFSupercargo.SelectedItemArray));
                    parms.Add("@FDispatchNum", newKeyId); //调度单号

                    SqlService.ExecuteProcedureCommand("proc_DispatchCenter", parms);

                    List <LHStockOut> outs  = new List <LHStockOut>();
                    List <LHPassCard> cards = new List <LHPassCard>();
                }
            }

            return(true);
        }
Esempio n. 16
0
        public async Task <object> Find(string data)
        {
            data = data.Trim();
            var b58 = NoException(() => WhatIsBase58.GetFromBase58Data(data));

            if (b58 != null)
            {
                if (b58 is WhatIsAddress)
                {
                    var address = (WhatIsAddress)b58;
                    TryFetchRedeemOrPubKey(address);
                }
                return(b58);
            }

            if (data.Length == 0x40)
            {
                try
                {
                    return(await Controller.JsonTransaction(uint256.Parse(data), false));
                }
                catch
                {
                }
            }
            var b = NoException(() => Controller.JsonBlock(BlockFeature.Parse(data), true));

            if (b != null)
            {
                return(b);
            }

            if (data.Length == 0x28) //Hash of pubkey or script
            {
                TxDestination dest    = new KeyId(data);
                var           address = new WhatIsAddress(dest.GetAddress(Network));
                if (TryFetchRedeemOrPubKey(address))
                {
                    return(address);
                }

                dest    = new ScriptId(data);
                address = new WhatIsAddress(dest.GetAddress(Network));
                if (TryFetchRedeemOrPubKey(address))
                {
                    return(address);
                }
            }


            var script = NoException(() => GetScriptFromBytes(data));

            if (script != null)
            {
                return(new WhatIsScript(script, Network));
            }
            script = NoException(() => GetScriptFromText(data));
            if (script != null)
            {
                return(new WhatIsScript(script, Network));
            }

            var sig = NoException(() => new TransactionSignature(Encoders.Hex.DecodeData(data)));

            if (sig != null)
            {
                return(new WhatIsTransactionSignature(sig));
            }

            var pubkeyBytes = NoException(() => Encoders.Hex.DecodeData(data));

            if (pubkeyBytes != null && PubKey.Check(pubkeyBytes, true))
            {
                var pubKey = NoException(() => new PubKey(data));
                if (pubKey != null)
                {
                    return(new WhatIsPublicKey(pubKey, Network));
                }
            }

            if (data.Length == 80 * 2)
            {
                var blockHeader = NoException(() =>
                {
                    var h = new BlockHeader();
                    h.ReadWrite(Encoders.Hex.DecodeData(data));
                    return(h);
                });
                if (blockHeader != null)
                {
                    return(new WhatIsBlockHeader(blockHeader));
                }
            }
            return(null);
        }
Esempio n. 17
0
 public void RemoveBinds(KeyId id)
 {
     _bindConfig.RemoveBinds(id);
 }
Esempio n. 18
0
        public static IServiceCollection AddRSAHttpMessageSigning(this IServiceCollection services, KeyId keyId, RSA rsa)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            if (rsa == null)
            {
                throw new ArgumentNullException(nameof(rsa));
            }

            return(services.AddRSAHttpMessageSigning(keyId, rsa, settings => {}));
        }
Esempio n. 19
0
        /// <summary>
        /// Creates cold staking setup <see cref="Transaction"/>.
        /// </summary>
        /// <remarks>
        /// The <paramref name="coldWalletAddress"/> and <paramref name="hotWalletAddress"/> would be expected to be
        /// from different wallets and typically also different physical machines under normal circumstances. The following
        /// rules are enforced by this method and would lead to a <see cref="WalletException"/> otherwise:
        /// <list type="bullet">
        /// <item><description>The cold and hot wallet addresses are expected to belong to different wallets.</description></item>
        /// <item><description>Either the cold or hot wallet address must belong to a cold staking account in the wallet identified
        /// by <paramref name="walletName"/></description></item>
        /// <item><description>The account specified in <paramref name="walletAccount"/> can't be a cold staking account.</description></item>
        /// </list>
        /// </remarks>
        /// <param name="walletTransactionHandler">The wallet transaction handler. Contains the <see cref="WalletTransactionHandler.BuildTransaction"/> method.</param>
        /// <param name="coldWalletAddress">The cold wallet address generated by <see cref="GetColdStakingAddress"/>.</param>
        /// <param name="hotWalletAddress">The hot wallet address generated by <see cref="GetColdStakingAddress"/>.</param>
        /// <param name="walletName">The name of the wallet.</param>
        /// <param name="walletAccount">The wallet account.</param>
        /// <param name="walletPassword">The wallet password.</param>
        /// <param name="amount">The amount to cold stake.</param>
        /// <param name="feeAmount">The fee to pay for the cold staking setup transaction.</param>
        /// <param name="useSegwitChangeAddress">Use a segwit style change address.</param>
        /// <param name="payToScript">Indicate script staking (P2SH or P2WSH outputs).</param>
        /// <returns>The <see cref="Transaction"/> for setting up cold staking.</returns>
        /// <exception cref="WalletException">Thrown if any of the rules listed in the remarks section of this method are broken.</exception>
        internal Transaction GetColdStakingSetupTransaction(IWalletTransactionHandler walletTransactionHandler,
                                                            string coldWalletAddress, string hotWalletAddress, string walletName, string walletAccount,
                                                            string walletPassword, Money amount, Money feeAmount, bool useSegwitChangeAddress = false, bool payToScript = false)
        {
            Guard.NotNull(walletTransactionHandler, nameof(walletTransactionHandler));
            Guard.NotEmpty(coldWalletAddress, nameof(coldWalletAddress));
            Guard.NotEmpty(hotWalletAddress, nameof(hotWalletAddress));
            Guard.NotEmpty(walletName, nameof(walletName));
            Guard.NotEmpty(walletAccount, nameof(walletAccount));
            Guard.NotNull(amount, nameof(amount));
            Guard.NotNull(feeAmount, nameof(feeAmount));

            Wallet.Types.Wallet wallet = this.GetWalletByName(walletName);

            // Get/create the cold staking accounts.
            HdAccount coldAccount = this.GetOrCreateColdStakingAccount(walletName, true, walletPassword);
            HdAccount hotAccount  = this.GetOrCreateColdStakingAccount(walletName, false, walletPassword);

            HdAddress coldAddress = coldAccount?.ExternalAddresses.FirstOrDefault(s => s.Address == coldWalletAddress || s.Bech32Address == coldWalletAddress);
            HdAddress hotAddress  = hotAccount?.ExternalAddresses.FirstOrDefault(s => s.Address == hotWalletAddress || s.Bech32Address == hotWalletAddress);

            bool thisIsColdWallet = coldAddress != null;
            bool thisIsHotWallet  = hotAddress != null;

            this.logger.LogDebug("Local wallet '{0}' does{1} contain cold wallet address '{2}' and does{3} contain hot wallet address '{4}'.",
                                 walletName, thisIsColdWallet ? "" : " NOT", coldWalletAddress, thisIsHotWallet ? "" : " NOT", hotWalletAddress);

            if (thisIsColdWallet && thisIsHotWallet)
            {
                this.logger.LogTrace("(-)[COLDSTAKE_BOTH_HOT_AND_COLD]");
                throw new WalletException("You can't use this wallet as both hot wallet and cold wallet.");
            }

            if (!thisIsColdWallet && !thisIsHotWallet)
            {
                this.logger.LogTrace("(-)[COLDSTAKE_ADDRESSES_NOT_IN_ACCOUNTS]");
                throw new WalletException("The hot and cold wallet addresses could not be found in the corresponding accounts.");
            }

            Script destination    = null;
            KeyId  hotPubKeyHash  = null;
            KeyId  coldPubKeyHash = null;

            // Check if this is a segwit address
            if (coldAddress?.Bech32Address == coldWalletAddress || hotAddress?.Bech32Address == hotWalletAddress)
            {
                hotPubKeyHash  = new BitcoinWitPubKeyAddress(hotWalletAddress, wallet.Network).Hash.AsKeyId();
                coldPubKeyHash = new BitcoinWitPubKeyAddress(coldWalletAddress, wallet.Network).Hash.AsKeyId();
                destination    = ColdStakingScriptTemplate.Instance.GenerateScriptPubKey(hotPubKeyHash, coldPubKeyHash);

                if (payToScript)
                {
                    HdAddress address = coldAddress ?? hotAddress;
                    address.RedeemScript = destination;
                    destination          = destination.WitHash.ScriptPubKey;
                }
            }
            else
            {
                hotPubKeyHash  = new BitcoinPubKeyAddress(hotWalletAddress, wallet.Network).Hash;
                coldPubKeyHash = new BitcoinPubKeyAddress(coldWalletAddress, wallet.Network).Hash;
                destination    = ColdStakingScriptTemplate.Instance.GenerateScriptPubKey(hotPubKeyHash, coldPubKeyHash);

                if (payToScript)
                {
                    HdAddress address = coldAddress ?? hotAddress;
                    address.RedeemScript = destination;
                    destination          = destination.Hash.ScriptPubKey;
                }
            }

            // Only normal accounts should be allowed.
            if (this.GetAccounts(walletName).All(a => a.Name != walletAccount))
            {
                this.logger.LogTrace("(-)[COLDSTAKE_ACCOUNT_NOT_FOUND]");
                throw new WalletException($"Can't find wallet account '{walletAccount}'.");
            }

            var context = new TransactionBuildContext(wallet.Network)
            {
                AccountReference       = new WalletAccountReference(walletName, walletAccount),
                TransactionFee         = feeAmount,
                MinConfirmations       = 0,
                Shuffle                = false,
                UseSegwitChangeAddress = useSegwitChangeAddress,
                WalletPassword         = walletPassword,
                Recipients             = new List <Recipient>()
                {
                    new Recipient {
                        Amount = amount, ScriptPubKey = destination
                    }
                }
            };

            if (payToScript)
            {
                // In the case of P2SH and P2WSH, to avoid the possibility of lose track of funds
                // we add an opreturn with the hot and cold key hashes to the setup transaction
                // this will allow a user to recreate the redeem script of the output in case they lose
                // access to one of the keys.
                // The special marker will help a wallet that is tracking cold staking accounts to monitor
                // the hot and cold keys, if a special marker is found then the keys are in the opreturn are checked
                // against the current wallet, if found and validated the wallet will track that ScriptPubKey

                var opreturnKeys = new List <byte>();
                opreturnKeys.AddRange(hotPubKeyHash.ToBytes());
                opreturnKeys.AddRange(coldPubKeyHash.ToBytes());

                context.OpReturnRawData = opreturnKeys.ToArray();
                TxNullDataTemplate template = this.network.StandardScriptsRegistry.GetScriptTemplates.OfType <TxNullDataTemplate>().First();
                if (template.MinRequiredSatoshiFee > 0)
                {
                    context.OpReturnAmount = Money.Satoshis(template.MinRequiredSatoshiFee); // mandatory fee must be paid.
                }
                // The P2SH and P2WSH hide the cold stake keys in the script hash so the wallet cannot track
                // the ouputs based on the derived keys when the trx is subbmited to the network.
                // So we add the output script manually.
            }

            // Register the cold staking builder extension with the transaction builder.
            context.TransactionBuilder.Extensions.Add(new ColdStakingBuilderExtension(false));

            // Build the transaction.
            Transaction transaction = walletTransactionHandler.BuildTransaction(context);

            this.logger.LogTrace("(-)");
            return(transaction);
        }
Esempio n. 20
0
        public static IServiceCollection AddRSAHttpMessageSigning(this IServiceCollection services, KeyId keyId, RSA rsa, Action <SigningSettings> signingSettingsConfig)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            if (rsa == null)
            {
                throw new ArgumentNullException(nameof(rsa));
            }

            return(services.AddRSAHttpMessageSigning(
                       prov => keyId,
                       prov => rsa,
                       (prov, settings) => signingSettingsConfig(settings)
                       ));
        }
Esempio n. 21
0
 public bool IsKeyUp(KeyId id)
 {
     return(_inputController.IsKeyUp(id));
 }
Esempio n. 22
0
 public ScannerUser CreateScannerUser(KeyId keyId, int start)
 {
     scanner++;
     ScannerUser user = new ScannerUser(keyId, start, this);
     return user;
 }
Esempio n. 23
0
		public void base58_keys_valid_gen()
		{
			var tests = TestCase.read_json("data/base58_keys_valid.json");
			tests = tests.Concat(TestCase.read_json("data/base58_keys_valid2.json")).ToArray();
			Network network = null;

			foreach(var test in tests)
			{
				string strTest = test.ToString();
				if(test.Count < 3) // Allow for extra stuff (useful for comments)
				{
					Assert.False(true, "Bad test: " + strTest);
					continue;
				}
				string exp_base58string = (string)test[0];
				byte[] exp_payload = TestUtils.ParseHex((string)test[1]);
				dynamic metadata = test.GetDynamic(2);
				bool isPrivkey = (bool)metadata.isPrivkey;
				bool isTestnet = (bool)metadata.isTestnet;

				if(isTestnet)
					network = Network.TestNet;
				else
					network = Network.Main;
				if(isPrivkey)
				{
					bool isCompressed = metadata.isCompressed;
					Key key = new Key(exp_payload, fCompressedIn: isCompressed);
					BitcoinSecret secret = network.CreateBitcoinSecret(key);
					Assert.True(secret.ToString() == exp_base58string, "result mismatch: " + strTest);
				}
				else
				{
					string exp_addrType = (string)metadata.addrType;
					TxDestination dest;
					if(exp_addrType == "pubkey")
					{
						dest = new KeyId(new uint160(exp_payload));
					}
					else if(exp_addrType == "script")
					{
						dest = new ScriptId(new uint160(exp_payload));
					}
					else if(exp_addrType == "p2wpkh")
					{
						network = network == Network.TestNet ? Network.SegNet : network;
						dest = new WitKeyId(new uint160(exp_payload));
					}
					else if(exp_addrType == "p2wsh")
					{
						network = network == Network.TestNet ? Network.SegNet : network;
						dest = new WitScriptId(exp_payload);
					}
					else if(exp_addrType == "none")
					{
						continue;
					}
					else
					{
						Assert.True(false, "Bad addrtype: " + strTest);
						continue;
					}
					try
					{
						BitcoinAddress addrOut = dest.GetAddress(network);
						Assert.True(addrOut.ToString() == exp_base58string, "mismatch: " + strTest);
						Assert.True(addrOut.ScriptPubKey == dest.ScriptPubKey);
						Assert.True(dest.ScriptPubKey.GetDestination() == dest);
					}
					catch(ArgumentException)
					{
						Assert.True(dest.GetType() == typeof(TxDestination));
					}
				}
			}
		}
Esempio n. 24
0
        private List<GameMessage> GetMessageListFromEnumerator(IEnumerator<KeyId> e, int count, bool level)
        {
            var messageList = new List<GameMessage>();

            if (count == 0)
                return messageList;

            if (count == 1)
            {
                AttributeSetValueMessage msg = new AttributeSetValueMessage();
                if (!e.MoveNext())
                    throw new Exception("Expected value in enumerator.");

                var keyid = e.Current;
                var value = _attributeValues[keyid];

                int id = keyid.Id;
                msg.ActorID = _parent.DynamicID;
                msg.Field1 = new Mooege.Net.GS.Message.Fields.NetAttributeKeyValue();
                msg.Field1.Field0 = keyid.Key;
                // FIXME: need to rework NetAttributeKeyValue, and maybe rename GameAttribute to NetAttribute?
                msg.Field1.Attribute = GameAttribute.Attributes[id]; // FIXME
                if (msg.Field1.Attribute.IsInteger)
                    msg.Field1.Int = value.Value;
                else
                    msg.Field1.Float = value.ValueF;

                messageList.Add(msg);
            }
            else
            {
                // FIXME: probably need to rework AttributesSetValues as well a bit
                if (count >= 15)
                {
                    for (; count >= 15; count -= 15)
                    {
                        AttributesSetValuesMessage msg = new AttributesSetValuesMessage();
                        msg.ActorID = _parent.DynamicID;
                        msg.atKeyVals = new Mooege.Net.GS.Message.Fields.NetAttributeKeyValue[15];
                        for (int i = 0; i < 15; i++)
                            msg.atKeyVals[i] = new Mooege.Net.GS.Message.Fields.NetAttributeKeyValue();
                        for (int i = 0; i < 15; i++)
                        {
                            KeyId keyid;
                            if (!e.MoveNext())
                            {
                                if (level)
                                {
                                    keyid = new KeyId { Id = GameAttribute.Level.Id };
                                    level = false;
                                }
                                else
                                {
                                    throw new Exception("Expected values in enumerator.");
                                }
                            }
                            else
                            {
                                keyid = e.Current;
                            }

                            var kv = msg.atKeyVals[i];
                            if (level && keyid.Id == GameAttribute.Level.Id)
                            {
                                i--;
                                continue;
                            }

                            var value = _attributeValues[keyid];
                            var id = keyid.Id;

                            kv.Field0 = keyid.Key;
                            kv.Attribute = GameAttribute.Attributes[id];
                            if (kv.Attribute.IsInteger)
                                kv.Int = value.Value;
                            else
                                kv.Float = value.ValueF;
                        }
                        messageList.Add(msg);
                    }
                }

                if (count > 0)
                {
                    AttributesSetValuesMessage msg = new AttributesSetValuesMessage();
                    msg.ActorID = _parent.DynamicID;
                    msg.atKeyVals = new Mooege.Net.GS.Message.Fields.NetAttributeKeyValue[count];
                    for (int i = 0; i < count; i++)
                    {
                        KeyId keyid;
                        if (!e.MoveNext())
                        {
                            if (level)
                            {
                                keyid = new KeyId { Id = GameAttribute.Level.Id };
                                level = false;
                            }
                            else
                            {
                                throw new Exception("Expected values in enumerator.");
                            }
                        }
                        else
                        {
                            keyid = e.Current;
                        }
                        var kv = new Mooege.Net.GS.Message.Fields.NetAttributeKeyValue();
                        msg.atKeyVals[i] = kv;

                        if (level && keyid.Id == GameAttribute.Level.Id)
                        {
                            i--;
                            continue;
                        }

                        var value = _attributeValues[keyid];
                        var id = keyid.Id;

                        kv.Field0 = keyid.Key;
                        kv.Attribute = GameAttribute.Attributes[id];
                        if (kv.Attribute.IsInteger)
                            kv.Int = value.Value;
                        else
                            kv.Float = value.ValueF;
                    }
                    messageList.Add(msg);
                }

            }
            return messageList;
        }
Esempio n. 25
0
        // internal AND protected
        internal override GpgInterfaceResult ProcessLine(String line)
        {
            if (!GNUCheck(ref line))
                return GpgInterfaceResult.Success;

            switch (GetKeyword(ref line))
            {
                case GpgKeyword.GOODSIG:
                {
                    IsSigned = true;
                    IsGoodSignature = true;
                    SignatureKeyId = new KeyId(line.Split(' ')[0]);
                    break;
                }

                case GpgKeyword.BADSIG:
                {
                    IsSigned = true;
                    IsGoodSignature = false;
                    SignatureKeyId = new KeyId(line.Split(' ')[0]);
                    break;
                }

                case GpgKeyword.VALIDSIG:
                {
                    String[] parts = line.Split(' ');

                    String datetime = parts[2];
                    if (datetime.Contains("T"))
                    {
                        // ISO 8601
                        SignatureDateTime = DateTime.ParseExact(datetime, "s", CultureInfo.InvariantCulture);
                    }
                    else
                        SignatureDateTime = Utils.ConvertTimestamp(Double.Parse(datetime, CultureInfo.InvariantCulture));

                    break;
                }

                case GpgKeyword.TRUST_UNDEFINED:
                case GpgKeyword.TRUST_NEVER:
                {
                    SignatureTrust = KeyOwnerTrust.None;
                    break;
                }

                case GpgKeyword.TRUST_MARGINAL:
                {
                    SignatureTrust = KeyOwnerTrust.Marginal;
                    break;
                }

                case GpgKeyword.TRUST_FULLY:
                {
                    SignatureTrust = KeyOwnerTrust.Full;
                    break;
                }

                case GpgKeyword.TRUST_ULTIMATE:
                {
                    SignatureTrust = KeyOwnerTrust.Ultimate;
                    break;
                }
            }

            return GpgInterfaceResult.Success;
        }
Esempio n. 26
0
 protected void AddKeyMap(KeyId keyId, T keyCode)
 {
     _mapTo.Add(keyId, keyCode);
 }
Esempio n. 27
0
 public T ConvertTo(KeyId id)
 {
     Assert.IsTrue(_mapTo.ContainsKey(id), "Key Map not found " + id);
     return(_mapTo[id]);
 }
Esempio n. 28
0
        public string encryptString(string toEncrypt, string target, string sign = null, CipherAlgorithm algorithm = CipherAlgorithm.Aes256, bool armour = true, bool hideuserid = false)
        {
            List<KeyId> recipients = new List<KeyId>();
            recipients.Add(new KeyId(target));

            KeyId signkey = new KeyId(defaultsign);

            GpgInterface.ExePath = ExePath;

            string path = Directory.GetCurrentDirectory() + "\\" + GetUniqueKey() + ".txt";
            string pathout = path + ".out";

            System.IO.File.WriteAllText(path, toEncrypt);

            GpgEncrypt encrypt = new GpgEncrypt(path, pathout, armour, hideuserid, signkey, recipients, algorithm);

            encrypt.AskPassphrase = GetPassword;

            GpgInterfaceResult result = encrypt.Execute();

            System.IO.File.Delete(path);

            if (result.Status == GpgInterfaceStatus.Success)
            {
                string toReturn = System.IO.File.ReadAllText(pathout);
                System.IO.File.Delete(pathout);
                return toReturn;
            }
            else
            {
                throw new Exception("Encryption Failed");
            }
        }
Esempio n. 29
0
 public void RemoveBind(KeyId id, string action)
 {
     _bindConfig.RemoveBind(id, action);
 }
Esempio n. 30
0
        private TransactionBuildContext GetSetupTransactionBuildContext(IWalletTransactionHandler walletTransactionHandler,
                                                                        string coldWalletAddress, string hotWalletAddress, string walletName, string walletAccount,
                                                                        string walletPassword, Money amount, Money feeAmount, bool subtractFeeFromAmount, bool offline, bool useSegwitChangeAddress, int splitCount, ExtPubKey extPubKey = null)
        {
            Guard.NotNull(walletTransactionHandler, nameof(walletTransactionHandler));
            Guard.NotEmpty(coldWalletAddress, nameof(coldWalletAddress));
            Guard.NotEmpty(hotWalletAddress, nameof(hotWalletAddress));
            Guard.NotEmpty(walletName, nameof(walletName));
            Guard.NotEmpty(walletAccount, nameof(walletAccount));
            Guard.NotNull(amount, nameof(amount));

            Wallet.Wallet wallet = this.GetWallet(walletName);

            KeyId hotPubKeyHash  = null;
            KeyId coldPubKeyHash = null;

            if (!offline)
            {
                // Get/create the cold staking accounts.
                HdAccount coldAccount = this.GetOrCreateColdStakingAccount(walletName, true, walletPassword, extPubKey);
                HdAccount hotAccount  = this.GetOrCreateColdStakingAccount(walletName, false, walletPassword, extPubKey);

                HdAddress coldAddress = coldAccount?.ExternalAddresses.FirstOrDefault(s => s.Address == coldWalletAddress || s.Bech32Address == coldWalletAddress);
                HdAddress hotAddress  = hotAccount?.ExternalAddresses.FirstOrDefault(s => s.Address == hotWalletAddress || s.Bech32Address == hotWalletAddress);

                bool thisIsColdWallet = coldAddress != null;
                bool thisIsHotWallet  = hotAddress != null;

                this.logger.LogDebug("Local wallet '{0}' does{1} contain cold wallet address '{2}' and does{3} contain hot wallet address '{4}'.",
                                     walletName, thisIsColdWallet ? "" : " NOT", coldWalletAddress, thisIsHotWallet ? "" : " NOT", hotWalletAddress);

                if (thisIsColdWallet && thisIsHotWallet)
                {
                    this.logger.LogTrace("(-)[COLDSTAKE_BOTH_HOT_AND_COLD]");
                    throw new WalletException("You can't use this wallet as both the hot wallet and cold wallet.");
                }

                if (!thisIsColdWallet && !thisIsHotWallet)
                {
                    this.logger.LogTrace("(-)[COLDSTAKE_ADDRESSES_NOT_IN_ACCOUNTS]");
                    throw new WalletException("The hot and cold wallet addresses could not be found in the corresponding accounts.");
                }

                // Check if this is a segwit address.
                if (coldAddress?.Bech32Address == coldWalletAddress || hotAddress?.Bech32Address == hotWalletAddress)
                {
                    hotPubKeyHash  = new BitcoinWitPubKeyAddress(hotWalletAddress, wallet.Network).Hash.AsKeyId();
                    coldPubKeyHash = new BitcoinWitPubKeyAddress(coldWalletAddress, wallet.Network).Hash.AsKeyId();
                }
                else
                {
                    hotPubKeyHash  = new BitcoinPubKeyAddress(hotWalletAddress, wallet.Network).Hash;
                    coldPubKeyHash = new BitcoinPubKeyAddress(coldWalletAddress, wallet.Network).Hash;
                }
            }
            else
            {
                // In offline mode we relax all the restrictions to enable simpler setup. The user should ensure they are using separate wallets, or the cold private key could be inadvertently loaded on the online node.
                IDestination hot  = BitcoinAddress.Create(hotWalletAddress, this.network);
                IDestination cold = BitcoinAddress.Create(coldWalletAddress, this.network);

                if (hot is BitcoinPubKeyAddress && cold is BitcoinPubKeyAddress)
                {
                    hotPubKeyHash  = new BitcoinPubKeyAddress(hotWalletAddress, wallet.Network).Hash;
                    coldPubKeyHash = new BitcoinPubKeyAddress(coldWalletAddress, wallet.Network).Hash;
                }

                if (hot is BitcoinWitPubKeyAddress && cold is BitcoinWitPubKeyAddress)
                {
                    hotPubKeyHash  = new BitcoinWitPubKeyAddress(hotWalletAddress, wallet.Network).Hash.AsKeyId();
                    coldPubKeyHash = new BitcoinWitPubKeyAddress(coldWalletAddress, wallet.Network).Hash.AsKeyId();
                }
            }

            if (hotPubKeyHash == null || coldPubKeyHash == null)
            {
                this.logger.LogTrace("(-)[PUBKEYHASH_NOT_AVAILABLE]");
                throw new WalletException($"Unable to compute the needed hashes from the given addresses.");
            }

            Script destination = ColdStakingScriptTemplate.Instance.GenerateScriptPubKey(hotPubKeyHash, coldPubKeyHash);

            // Only normal accounts should be allowed.
            if (!this.GetAccounts(walletName).Any(a => a.Name == walletAccount))
            {
                this.logger.LogTrace("(-)[COLDSTAKE_ACCOUNT_NOT_FOUND]");
                throw new WalletException($"Can't find wallet account '{walletAccount}'.");
            }

            List <Recipient> recipients = GetRecipients(destination, amount, subtractFeeFromAmount, splitCount);

            var context = new TransactionBuildContext(wallet.Network)
            {
                AccountReference       = new WalletAccountReference(walletName, walletAccount),
                TransactionFee         = feeAmount,
                MinConfirmations       = 0,
                Shuffle                = false,
                UseSegwitChangeAddress = useSegwitChangeAddress,
                WalletPassword         = walletPassword,
                Recipients             = recipients
            };

            // Register the cold staking builder extension with the transaction builder.
            context.TransactionBuilder.Extensions.Add(new ColdStakingBuilderExtension(false));

            return(context);
        }
Esempio n. 31
0
        public void base58_keys_valid_gen()
        {
            var tests = TestCase.read_json("data/base58_keys_valid.json");

            tests = tests.Concat(TestCase.read_json("data/base58_keys_valid2.json")).ToArray();
            Network network = null;

            foreach (var test in tests)
            {
                string strTest = test.ToString();
                if (test.Count < 3) // Allow for extra stuff (useful for comments)
                {
                    Assert.False(true, "Bad test: " + strTest);
                    continue;
                }
                string  exp_base58string = (string)test[0];
                byte[]  exp_payload      = TestUtils.ParseHex((string)test[1]);
                dynamic metadata         = test.GetDynamic(2);
                bool    isPrivkey        = (bool)metadata.isPrivkey;
                bool    isTestnet        = (bool)metadata.isTestnet;

                if (isTestnet)
                {
                    network = Network.TestNet;
                }
                else
                {
                    network = Network.Main;
                }
                if (isPrivkey)
                {
                    bool          isCompressed = metadata.isCompressed;
                    Key           key          = new Key(exp_payload, fCompressedIn: isCompressed);
                    BitcoinSecret secret       = network.CreateBitcoinSecret(key);
                    Assert.True(secret.ToString() == exp_base58string, "result mismatch: " + strTest);
                }
                else
                {
                    string        exp_addrType = (string)metadata.addrType;
                    TxDestination dest;
                    if (exp_addrType == "pubkey")
                    {
                        dest = new KeyId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "script")
                    {
                        dest = new ScriptId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "p2wpkh")
                    {
                        dest = new WitKeyId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "p2wsh")
                    {
                        dest = new WitScriptId(exp_payload);
                    }
                    else if (exp_addrType == "none")
                    {
                        continue;
                    }
                    else
                    {
                        Assert.True(false, "Bad addrtype: " + strTest);
                        continue;
                    }
                    try
                    {
                        BitcoinAddress addrOut = dest.GetAddress(network);
                        Assert.True(addrOut.ToString() == exp_base58string, "mismatch: " + strTest);
                        Assert.True(addrOut.ScriptPubKey == dest.ScriptPubKey);
                        Assert.True(dest.ScriptPubKey.GetDestination(Network.Main) == dest);
                    }
                    catch (ArgumentException)
                    {
                        Assert.True(dest.GetType() == typeof(TxDestination));
                    }
                }
            }
        }
Esempio n. 32
0
 public PubKeyHashScanner(KeyId pubKeyHash)
 {
     if(pubKeyHash == null)
         throw new ArgumentNullException("pubKeyHash");
     _PubKeyHash = pubKeyHash;
 }
Esempio n. 33
0
 public bool DoesBindExist(KeyId id, string action)
 {
     return(_bindConfig.DoesBindExist(id, action));
 }
Esempio n. 34
0
		public StealthSpendKey(KeyId id, StealthPayment payment)
		{
			_ID = id;
			_Payment = payment;
		}
Esempio n. 35
0
        public ScannerUser(KeyId keyId, int start, ScannerTester tester)
        {
            var folder = Path.Combine(tester._FolderName, tester.scanner.ToString());
            TestUtils.EnsureNew(folder);

            var chainStream = new StreamObjectStream<ChainChange>(File.Open(Path.Combine(folder, "Chain"), FileMode.OpenOrCreate));
            var accountStream = new StreamObjectStream<AccountEntry>(File.Open(Path.Combine(folder, "Entries"), FileMode.OpenOrCreate));
            _Id = keyId;
            _Scanner = new PubKeyHashScanner(keyId);
            _ScanState = new ScanState(new PubKeyHashScanner(keyId),
                            new Chain(chainStream),
                            new Account(accountStream),
                            start);
            _Tester = tester;
        }
Esempio n. 36
0
        private void button1_Click(object sender, EventArgs e) //读取
        {
            textBox2.Text = "";
            Console.WriteLine("start get");

            string privateKeyStr = PrivateKey;
            //string privateKeyStr = "cUvazeu9ucqD4trygt8xMEQKZfR3SZ5BdiAWb3eEwbQ48iPwYKSB";
            BitcoinSecret  privateKey = new BitcoinSecret(privateKeyStr);
            Network        network    = privateKey.Network;
            PubKey         pubKey     = privateKey.PubKey;
            string         pubKeyStr  = pubKey.ToHex();
            KeyId          pkhash     = pubKey.Hash;
            string         pkhashStr  = pkhash.ToString();
            BitcoinAddress addres     = pkhash.GetAddress(network);
            string         address    = addres.ToString();
            string         networkStr = bsvConfiguration_class.testNetwork;
            string         uri        = bsvConfiguration_class.RestApiUri;

            //获取链上的交易历史
            Task <RestApiAddressHistoryTx[]> t = Task <RestApiAddressHistoryTx[]> .Run(() =>
            {
                RestApiAddressHistoryTx[] addrHistory = RestApi_class.getAddressHistory(uri, networkStr, address);
                return(addrHistory);
            });

            t.Wait();
            int num = t.Result.Length;

            Console.WriteLine("链上交易数目:" + num);
            //读取链上信息
            Task <RestApiTransaction[]> gettxs = null;

            if (num > 0)
            {
                string[] txHashs = new string[num];
                for (int i = 0; i < num; i++)
                {
                    txHashs[i] = t.Result[i].TxHash;
                }

                gettxs = Task <RestApiTransaction[]> .Run(() =>
                {
                    RestApiTransaction[] txs = RestApi_class.getTransactions(uri, networkStr, txHashs);
                    return(txs);
                });
            }

            for (int i = 0; i < num; i++)
            {
                RestApiTransaction tx = gettxs.Result[i];
                string             s  = RestApi_class.getOpReturnData(tx, bsvConfiguration_class.encoding);
                if (s != null)
                {
                    //解密
                    byte[]        encryptedBytes;
                    Base58Encoder base58Encoder = new Base58Encoder();
                    encryptedBytes = base58Encoder.DecodeData(s);
                    string data = AES_class.AesDecrypt(encryptedBytes, privateKeyStr);
                    textBox2.Text += data;
                    textBox2.Text += "\r\n";
                    textBox2.Text += System.Environment.NewLine;
                    textBox2.Text += "------------------------------------------------------------------------------------";
                    textBox2.Text += "\r\n";
                    textBox2.Text += System.Environment.NewLine;
                    Console.WriteLine("链上内容:" + s);
                }
            }
        }
Esempio n. 37
0
 public bool IsKeyHeldDown(KeyId id)
 {
     return(_inputController.IsKeyHeldDown(id));
 }
Esempio n. 38
0
        // internal AND protected
        internal override GpgInterfaceResult ProcessLine(String line)
        {
            if (!GNUCheck(ref line))
                return GpgInterfaceResult.Success;

            switch (GetKeyword(ref line))
            {
                case GpgKeyword.ENC_TO:
                {
                    String[] parts = line.Split(' ');

                    if (parts[0] != _last_enc_to)
                    {
                        _last_enc_to = parts[0];
                        ResetTries();
                    }

                    break;
                }

                case GpgKeyword.NEED_PASSPHRASE_SYM:
                {
                    _isSymmetric = true;
                    break;
                }

                case GpgKeyword.NEED_PASSPHRASE:
                {
                    String[] parts = line.Split(' ');
                    _keyId = parts[1];
                    _isSymmetric = false;
                    break;
                }

                case GpgKeyword.BEGIN_DECRYPTION:
                    return new GpgInterfaceResult(GpgInterfaceStatus.Processing, GpgInterfaceMessage.BeginDecryption);

                case GpgKeyword.END_DECRYPTION:
                    return new GpgInterfaceResult(GpgInterfaceStatus.Processing, GpgInterfaceMessage.EndDecryption);

                case GpgKeyword.DECRYPTION_OKAY:
                    return new GpgInterfaceResult(GpgInterfaceStatus.Processing, GpgInterfaceMessage.DecryptionOk);

                case GpgKeyword.DECRYPTION_FAILED:
                    return _googPassphrase ? new GpgInterfaceResult(GpgInterfaceStatus.Error, GpgInterfaceMessage.DecryptionFailed) : GpgInterfaceResult.BadPassphrase;

                case GpgKeyword.PLAINTEXT_LENGTH:
                {
                    DecryptedDataLength = Int32.Parse(line, CultureInfo.InvariantCulture);
                    break;
                }

                case GpgKeyword.PLAINTEXT:
                {
                    String[] parts = line.Split(' ');

                    String datatype = parts[0];
                    switch (datatype)
                    {
                        case "62": DecryptedDataType = DataType.Binary; break;
                        case "74": DecryptedDataType = DataType.Text; break;
                        case "75": DecryptedDataType = DataType.Utf8Text; break;
                    }

                    EncryptionDateTime = Utils.ConvertTimestamp(Double.Parse(parts[1], CultureInfo.InvariantCulture));
                    OriginalFileName = Uri.UnescapeDataString(parts[2]);

                    break;
                }

                case GpgKeyword.GET_HIDDEN:
                {
                    if (String.Equals(line, "passphrase.enter", StringComparison.Ordinal))
                    {
                        SecureString password = InternalAskPassphrase(_keyId, false, _isSymmetric);
                        if (IsNullOrEmpty(password))
                            return GpgInterfaceResult.UserAbort;
                        WritePassword(password);
                    }

                    break;
                }

                case GpgKeyword.GOOD_PASSPHRASE:
                {
                    _googPassphrase = true;
                    break;
                }

                case GpgKeyword.GOODSIG:
                {
                    IsSigned = true;
                    IsGoodSignature = true;
                    SignatureKeyId = new KeyId(line.Split(' ')[0]);
                    break;
                }

                case GpgKeyword.BADSIG:
                {
                    IsSigned = true;
                    IsGoodSignature = false;
                    SignatureKeyId = new KeyId(line.Split(' ')[0]);
                    break;
                }

                case GpgKeyword.VALIDSIG:
                {
                    String[] parts = line.Split(' ');

                    String datetime = parts[2];
                    if (datetime.Contains("T"))
                    {
                        // ISO 8601
                        SignatureDateTime = DateTime.ParseExact(datetime, "s", CultureInfo.InvariantCulture);
                    }
                    else
                        SignatureDateTime = Utils.ConvertTimestamp(Double.Parse(datetime, CultureInfo.InvariantCulture));

                    break;
                }

                case GpgKeyword.NO_PUBKEY:
                    return new GpgInterfaceResult(GpgInterfaceStatus.Error, GpgInterfaceMessage.NoPublicKey, line);

                case GpgKeyword.NO_SECKEY:
                {
                    if (_googPassphrase)
                        return GpgInterfaceResult.Success;
                    else
                        return new GpgInterfaceResult(GpgInterfaceStatus.Error, GpgInterfaceMessage.NoSecretKey, line);
                }

                case GpgKeyword.NODATA:
                case GpgKeyword.UNEXPECTED:
                    return new GpgInterfaceResult(GpgInterfaceStatus.Error, GpgInterfaceMessage.DataError);

                case GpgKeyword.TRUST_UNDEFINED:
                case GpgKeyword.TRUST_NEVER:
                {
                    SignatureTrust = KeyOwnerTrust.None;
                    break;
                }

                case GpgKeyword.TRUST_MARGINAL:
                {
                    SignatureTrust = KeyOwnerTrust.Marginal;
                    break;
                }

                case GpgKeyword.TRUST_FULLY:
                {
                    SignatureTrust = KeyOwnerTrust.Full;
                    break;
                }

                case GpgKeyword.TRUST_ULTIMATE:
                {
                    SignatureTrust = KeyOwnerTrust.Ultimate;
                    break;
                }

                case GpgKeyword.GET_BOOL:
                {
                    if (String.Equals(line, "openfile.overwrite.okay", StringComparison.Ordinal))
                        WriteLine("YES");
                    break;
                }
            }

            return GpgInterfaceResult.Success;
        }
        public async Task <Client> Get(KeyId clientId)
        {
            if (clientId == KeyId.Empty)
            {
                throw new ArgumentException("Value cannot be null or empty.", nameof(clientId));
            }

            IList <ClientDataRecord> matches;

            using (var connection = new SqlConnection(_settings.ConnectionString)) {
                var results = await connection.QueryAsync <ClientDataRecord, ClaimDataRecord, ClientDataRecord>(
                    _getSql.Value,
                    (client, claim) => {
                    // ReSharper disable once ConvertToNullCoalescingCompoundAssignment
                    client.Claims = client.Claims ?? new List <ClaimDataRecord>();
                    client.Claims.Add(claim);
                    return(client);
                },
                    new { ClientId = clientId.Value },
                    splitOn : nameof(ClaimDataRecord.ClientId))
                              .ConfigureAwait(continueOnCapturedContext: false);

                matches = results
                          .GroupBy(clientDataRecord => clientDataRecord.Id)
                          .Select(_ => {
                    var client    = _.First();
                    client.Claims = _.SelectMany(c => c.Claims).ToList();
                    return(client);
                })
                          .ToList();
            }

            if (!matches.Any())
            {
                return(null);
            }

            var match = matches.Single();

            var nonceLifetime = !match.NonceLifetime.HasValue || match.NonceLifetime.Value <= 0.0
                ? ClientOptions.Default.NonceLifetime
                : TimeSpan.FromSeconds(match.NonceLifetime.Value);

            var clockSkew = !match.ClockSkew.HasValue || match.ClockSkew.Value <= 0.0
                ? ClientOptions.Default.ClockSkew
                : TimeSpan.FromSeconds(match.ClockSkew.Value);

            var requestTargetEscaping = RequestTargetEscaping.RFC3986;

            if (!string.IsNullOrEmpty(match.RequestTargetEscaping))
            {
                if (Enum.TryParse <RequestTargetEscaping>(match.RequestTargetEscaping, ignoreCase: true, out var parsed))
                {
                    requestTargetEscaping = parsed;
                }
            }

            var signatureAlgorithm = _signatureAlgorithmConverter.ToSignatureAlgorithm(match, _settings.SharedSecretEncryptionKey);

            return(new Client(
                       match.Id,
                       match.Name,
                       signatureAlgorithm,
                       nonceLifetime,
                       clockSkew,
                       requestTargetEscaping,
                       match.Claims?.Select(c => c.ToClaim())?.ToArray()));
        }