/// <summary>
        /// Derive a child address from extended public key
        /// </summary>
        /// <param name="extPubKeyWif"></param>
        private static BitcoinPubKeyAddress DeriveChildAddress(string extPubKeyWif, string keyDerivationPath)
        {
            ExtPubKey            extPubKey    = ExtPubKey.Parse(extPubKeyWif, _network);
            BitcoinPubKeyAddress childAddress = extPubKey.Derive(KeyPath.Parse(keyDerivationPath)).PubKey.GetAddress(_network);

            return(childAddress);
        }
Example #2
0
        public static ExtPubKey BetterParseExtPubKey(string extPubKeyString)
        {
            extPubKeyString = Guard.NotNullOrEmptyOrWhitespace(nameof(extPubKeyString), extPubKeyString, trim: true);

            ExtPubKey epk;

            try
            {
                epk = ExtPubKey.Parse(extPubKeyString, NBitcoin.Altcoins.Litecoin.Instance.Mainnet);                 // Starts with "ExtPubKey": "xpub...
            }
            catch
            {
                try
                {
                    epk = ExtPubKey.Parse(extPubKeyString, NBitcoin.Altcoins.Litecoin.Instance.Testnet);                     // Starts with "ExtPubKey": "xpub...
                }
                catch
                {
                    try
                    {
                        epk = ExtPubKey.Parse(extPubKeyString, NBitcoin.Altcoins.Litecoin.Instance.Regtest);                         // Starts with "ExtPubKey": "xpub...
                    }
                    catch
                    {
                        // Try hex, Old wallet format was like this.
                        // Doesn't make sense for LTC Litecoin because there's no legacy wallet format to support :
                        epk = new ExtPubKey(ByteHelpers.FromHex(extPubKeyString));                         // Starts with "ExtPubKey": "hexbytes...
                    }
                }
            }

            return(epk);
        }
Example #3
0
        public static ExtPubKey BetterParseExtPubKey(string extPubKeyString)
        {
            extPubKeyString = Guard.NotNullOrEmptyOrWhitespace(nameof(extPubKeyString), extPubKeyString, trim: true);

            ExtPubKey epk;

            try
            {
                epk = ExtPubKey.Parse(extPubKeyString, Network.Main);                 // Starts with "ExtPubKey": "xpub...
            }
            catch
            {
                try
                {
                    epk = ExtPubKey.Parse(extPubKeyString, Network.TestNet);                     // Starts with "ExtPubKey": "xpub...
                }
                catch
                {
                    try
                    {
                        epk = ExtPubKey.Parse(extPubKeyString, Network.RegTest);                         // Starts with "ExtPubKey": "xpub...
                    }
                    catch
                    {
                        // Try hex, Old wallet format was like this.
                        epk = new ExtPubKey(ByteHelpers.FromHex(extPubKeyString));                         // Starts with "ExtPubKey": "hexbytes...
                    }
                }
            }

            return(epk);
        }
        public static (PubKey PubKey, BitcoinPubKeyAddress Address) GenerateAddressKeys(Bitcoin.Features.Wallet.Wallet wallet, string accountExtendedPubKey, string keyPath)
        {
            var addressPubKey = ExtPubKey.Parse(accountExtendedPubKey).Derive(new KeyPath(keyPath)).PubKey;
            var address       = addressPubKey.GetAddress(wallet.Network);

            return(addressPubKey, address);
        }
Example #5
0
        public static object Interpret(string what)
        {
            if (what == null)
            {
                return(null);
            }

            what = what.Trim();
            Base58Type?type    = GetBase58Type(what);
            Network    network = Network.TestNet;

            if (type == null)
            {
                return(null);
            }

            switch (type)
            {
            case Base58Type.ASSET_ID:                                       // AssetId(BitcoinAddress).GetWif(Network.TestNet);
                return(new BitcoinAssetId(what));

            case Base58Type.COLORED_ADDRESS:                                // BitcoinColoredAddress(BitcoinAddress);
                return(new BitcoinColoredAddress(what, network));

            case Base58Type.CONFIRMATION_CODE:                              // Key.ConfirmationCode
                return(new BitcoinConfirmationCode(what, network));

            case Base58Type.ENCRYPTED_SECRET_KEY_EC:                        // BitcoinPassphraseCode("my secret", Network.TestNet, null).GenerateEncryptedSecret().EncryptedKey
                return(new BitcoinEncryptedSecretEC(what, network));

            case Base58Type.ENCRYPTED_SECRET_KEY_NO_EC:                     // BitcoinEncryptedSecretNoEC(Key,"Password", Network.TestNet);
                return(new BitcoinEncryptedSecretNoEC(what, network));

            case Base58Type.EXT_PUBLIC_KEY:                                 // Key.PubKey;
                return(ExtPubKey.Parse(what, Network.TestNet));

            case Base58Type.EXT_SECRET_KEY:                                 // BitcoinExtKey(ExtKey.GetWif(Network.TestNet), Network.TestNet);
                return(new BitcoinExtKey(what, network));

            case Base58Type.PASSPHRASE_CODE:                                // BitcoinPassphraseCode("my secret", Network.TestNet, null);
                return(new BitcoinPassphraseCode(what, network));

            case Base58Type.PUBKEY_ADDRESS:                                 // Key.PubKey.GetAddress(Network.TestNet);
                return(new BitcoinAddress(what, network));

            case Base58Type.SCRIPT_ADDRESS:                                 // PubKey.ScriptPubKey.GetScriptAddress(Network.TestNet)
                return(new BitcoinScriptAddress(what, network));

            case Base58Type.SECRET_KEY:                                     // Key.GetBitcoinSecret(Network.TestNet)
                return(new BitcoinSecret(what, network));

            case Base58Type.STEALTH_ADDRESS:                                // BitcoinStealthAddress( Key.PubKey, new[] { Key.PubKey }, 1, null, Network.TestNet);
                return(new BitcoinStealthAddress(what, network));

            case Base58Type.MAX_BASE58_TYPES:
            default:
                return(null);
            }
        }
        private PubKey GenerateAddress(string accountExtPubKey, int index, bool isChange, Network network)
        {
            int       change    = isChange ? 1 : 0;
            KeyPath   keyPath   = new KeyPath($"{change}/{index}");
            ExtPubKey extPubKey = ExtPubKey.Parse(accountExtPubKey).Derive(keyPath);

            return(extPubKey.PubKey);
        }
Example #7
0
        public void CanRoundTripExtKeyBase58Data()
        {
            var key    = new ExtKey();
            var pubkey = key.Neuter();

            Assert.True(ExtKey.Parse(key.ToString(Network.Main)).ToString(Network.Main) == key.ToString(Network.Main));
            Assert.True(ExtPubKey.Parse(pubkey.ToString(Network.Main)).ToString(Network.Main) == pubkey.ToString(Network.Main));
        }
Example #8
0
        /// <summary>
        /// Generates an HD public key derived from an extended public key.
        /// </summary>
        /// <param name="accountExtPubKey">The extended public key used to generate child keys.</param>
        /// <param name="index">The index of the child key to generate.</param>
        /// <param name="isChange">A value indicating whether the public key to generate corresponds to a change address.</param>
        /// <returns>
        /// An HD public key derived from an extended public key.
        /// </returns>
        public static PubKey GeneratePublicKey(string accountExtPubKey, int index, bool isChange)
        {
            Guard.NotEmpty(accountExtPubKey, nameof(accountExtPubKey));

            int       change    = isChange ? 1 : 0;
            KeyPath   keyPath   = new KeyPath($"{change}/{index}");
            ExtPubKey extPubKey = ExtPubKey.Parse(accountExtPubKey).Derive(keyPath);

            return(extPubKey.PubKey);
        }
        /// <summary>
        /// Generates an HD public key derived from an extended public key.
        /// </summary>
        /// <param name="accountExtPubKey">The extended public key used to generate child keys.</param>
        /// <param name="index">The index of the child key to generate.</param>
        /// <param name="isChange">A value indicating whether the public key to generate corresponds to a change address.</param>
        /// <returns>
        /// An HD public key derived from an extended public key.
        /// </returns>
        public static PubKey GeneratePublicKey(string accountExtPubKey, int index, bool isChange)
        {
            Guard.NotEmpty(accountExtPubKey, nameof(accountExtPubKey));

            int change  = isChange ? 1 : 0;
            var keyPath = new KeyPath($"{change}/{index}");
            // TODO: Should probably explicitly be passing the network into Parse
            ExtPubKey extPubKey = ExtPubKey.Parse(accountExtPubKey).Derive(keyPath);

            return(extPubKey.PubKey);
        }
Example #10
0
        /// <summary>
        /// Acquire bech32 xpub on path: m/84h/0h/0h
        /// https://github.com/bitcoin-core/HWI/blob/master/docs/examples.md
        /// </summary>
        public static async Task <ExtPubKey> GetXpubAsync(HardwareWalletInfo hardwareWalletInfo)
        {
            var    networkString = Network == Network.Main ? "" : "--testnet ";
            JToken jtok          = await SendCommandAsync($"{networkString}--device-type \"{hardwareWalletInfo.Type.ToString().ToLowerInvariant()}\" --device-path \"{hardwareWalletInfo.Path}\" getxpub m/84h/0h/0h");

            JObject json = jtok as JObject;
            string  xpub = json.Value <string>("xpub");

            ExtPubKey extpub = ExtPubKey.Parse(xpub);

            return(extpub);
        }
Example #11
0
        public void ShouldFindPublicKeysAccountUsingIndexInitialisingWithWif(string address, int index)
        {
            var wallet    = new Wallet(Words, Password);
            var wif       = wallet.GetMasterExtPubKey().GetWif(Network.Main).ToWif();
            var extPubKey = ExtPubKey.Parse(wif, Network.Main);

            Console.WriteLine(wif);
            var publicWallet = new PublicWallet(extPubKey);

            var account = publicWallet.GetAddress(index);

            Assert.Equal(address, account);
        }
Example #12
0
        public Tuple <string, string> CreateTransactionElectrum(string xpubkey1, string xpubkey2, decimal amount1, decimal amount2)
        {
            if (amount1 <= 0m && amount2 <= 0m)
            {
                throw new ArgumentException("Amount is less or equal zero");
            }

            ExtPubKey pubKey1;
            ExtPubKey pubKey2;

            try
            {
                pubKey1 = ExtPubKey.Parse(xpubkey1, Network.Main);
                pubKey2 = ExtPubKey.Parse(xpubkey2, Network.Main);
            }
            catch (Exception e)
            {
                throw new ArgumentException("Extended public key is incorrect");
            }

            decimal estimateFeeSize = 500m;
            var     fee             = this.Fee(estimateFeeSize);

            if (fee == null)
            {
                throw new Exception("Cannot get fee");
            }

            var pub1 = GetPubKey(pubKey1, Money.Coins(amount1) + fee / 2);
            var pub2 = GetPubKey(pubKey2, Money.Coins(amount2) + fee / 2);

            if (pub1 != null && pub2 != null)
            {
                Script scriptPubKey =
                    PayToMultiSigTemplate.Instance.GenerateScriptPubKey(
                        2,
                        pub1.Item1, pub2.Item1);

                var t = new Transaction();
                t.AddOutput(Money.Coins(amount1) + Money.Coins(amount2), scriptPubKey.Hash);

                int index = 0;

                this.AddInputs(t, pubKey1, pub1.Item3, pub1.Item2, ref index, Money.Coins(amount1) + fee / 2);
                this.AddInputs(t, pubKey2, pub2.Item3, pub2.Item2, ref index, Money.Coins(amount2) + fee / 2);

                return(new Tuple <string, string>(t.ToHex().Replace("594c5701ff4c53ff", "5701ff4c53ff"), scriptPubKey.ToString()));
            }

            return(null);
        }
        public IActionResult RecoverViaExtPubKey([FromBody] WalletExtPubRecoveryRequest request)
        {
            Guard.NotNull(request, nameof(request));
            this.logger.LogTrace("({0}.{1}:'{2}')", nameof(request), nameof(request.Name), request.Name);

            if (!this.ModelState.IsValid)
            {
                this.logger.LogTrace("(-)[MODEL_STATE_INVALID]");
                return(BuildErrorResponse(this.ModelState));
            }

            try
            {
                string accountExtPubKey =
                    this.network.IsBitcoin()
                        ? request.ExtPubKey
                        : LegacyExtPubKeyConverter.ConvertIfInLegacyStratisFormat(request.ExtPubKey, this.network);

                this.walletManager.RecoverWallet(request.Name, ExtPubKey.Parse(accountExtPubKey), request.AccountIndex,
                                                 request.CreationDate);

                this.walletSyncManager.SyncFromDate(request.CreationDate);

                this.logger.LogTrace("(-)");
                return(this.Ok());
            }
            catch (WalletException e)
            {
                // Wallet already exists.
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.Conflict, e.Message, e.ToString()));
            }
            catch (FileNotFoundException e)
            {
                // Wallet does not exist.
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.NotFound, "Wallet not found.", e.ToString()));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
            finally
            {
                this.logger.LogTrace("(-)");
            }
        }
        /// <inheritdoc />
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var       s = (string)reader.Value;
            ExtPubKey epk;

            try
            {
                epk = ExtPubKey.Parse(s);
            }
            catch
            {
                // Try hex, Old wallet format was like this.
                epk = new ExtPubKey(ByteHelpers.FromHex(s));
            }
            return(epk);
        }
Example #15
0
        private string GetTargetWallet(string currencyCode)
        {
            switch (currencyCode)
            {
            case "BTC": {
                uint   index = (uint)_db.Orders.Where(o => o.CurrencyCode == "BTC").Count();
                string xpub  = _env.IsDevelopment() ? _configuration["XPubKeys:Dev:BTC"] : _configuration["XPubKeys:Prod:BTC"];

                var pubKey  = ExtPubKey.Parse(xpub);
                var address = pubKey.Derive(0).Derive(index).PubKey.GetSegwitAddress(_env.IsDevelopment() ? Network.TestNet : Network.Main);

                return(address.ToString());
            };

            default: throw new Exception("Unsupported currency");
            }
        }
 private void JackpotCounter()
 {
     Task.Run(() =>
     {
         var totalJackpot = 0.0;
         var pubkey       = ExtPubKey.Parse(_drawSettings.PublicKey);
         for (int i = 0; i <= _settings.GetIterator(); i++)
         {
             var depositAddress           = pubkey.Derive(0).Derive((uint)i).PubKey.GetAddress(Network.StratisMain).ToString();
             var rc                       = new RestClient($"https://stratis.guru/api/address/{depositAddress}");
             var rq                       = new RestRequest(Method.GET);
             var response                 = rc.Execute(rq);
             dynamic stratisAdressRequest = JsonConvert.DeserializeObject(response.Content);
             totalJackpot                += (double)stratisAdressRequest.balance;
         }
         _memoryCache.Set("Jackpot", totalJackpot);
     });
 }
        public IActionResult Participate(string id)
        {
            ViewBag.Features = _featuresSettings;
            ViewBag.Setup    = _setupSettings;

            if (HttpContext.Session.GetString("HaveBeginParticipation") == null)
            {
                return(RedirectToAction("Lottery"));
            }
            ViewBag.NextDraw    = long.Parse(_memoryCache.Get("NextDraw").ToString());
            ViewBag.Jackpot     = _memoryCache.Get("Jackpot");
            ViewBag.Players     = _participation.GetPlayers(_draws.GetLastDraw());
            ViewBag.Participate = true;

            var pubkey = ExtPubKey.Parse(_drawSettings.PublicKey);

            ViewBag.DepositAddress = pubkey.Derive(0).Derive(_settings.GetIterator()).PubKey.GetAddress(Network.StratisMain);

            return(View("Lottery"));
        }
        private static string GetAddressFromXPUB(string XPUB, uint index, Network network)
        {
            ExtPubKey pubKey = null;

            try {
                pubKey = ExtPubKey.Parse(XPUB);
            }
            catch (Exception e) {
                Exception ex = new Exception($"Invalid {CurrencyName} XPUB - {XPUB}", e);
                throw ex;
            }

            try {
                string address = pubKey.Derive(0).Derive(index).PubKey.GetScriptAddress(network).ToString();
                return(address);
            }
            catch (Exception e) {
                Exception ex = new Exception($"Unable to generate {CurrencyName} address from XPUB - {XPUB}", e);
                throw ex;
            }
        }
Example #19
0
        public static object InterpretKey(string what)
        {
            if (what == null)
            {
                return(null);
            }

            what = what.Trim();
            Base58Type?type    = GetBase58Type(what);
            Network    network = Network.TestNet;

            if (type == null)
            {
                return(null);
            }

            switch (type)
            {
            case Base58Type.ENCRYPTED_SECRET_KEY_EC:                        // BitcoinPassphraseCode("my secret", Network.TestNet, null).GenerateEncryptedSecret().EncryptedKey
                return(new BitcoinEncryptedSecretEC(what, network));

            case Base58Type.ENCRYPTED_SECRET_KEY_NO_EC:                     // BitcoinEncryptedSecretNoEC(Key,"Password", Network.TestNet);
                return(new BitcoinEncryptedSecretNoEC(what, network));

            case Base58Type.EXT_PUBLIC_KEY:                                 // Key.PubKey;
                return(ExtPubKey.Parse(what, Network.TestNet));

            case Base58Type.EXT_SECRET_KEY:                                 // BitcoinExtKey(ExtKey.GetWif(Network.TestNet), Network.TestNet);
                return(new BitcoinExtKey(what, network));

            case Base58Type.SECRET_KEY:                                     // Key.GetBitcoinSecret(Network.TestNet)
                return(new BitcoinSecret(what, network));

            case Base58Type.PASSPHRASE_CODE:                                // BitcoinPassphraseCode("my secret", Network.TestNet, null);
                return(new BitcoinPassphraseCode(what, network));

            default:
                return(null);
            }
        }
        public IActionResult CreateColdStakingAccount([FromBody] CreateColdStakingAccountRequest request)
        {
            Guard.NotNull(request, nameof(request));

            // Checks that the request is valid.
            if (!this.ModelState.IsValid)
            {
                this.logger.LogTrace("(-)[MODEL_STATE_INVALID]");
                return(ModelStateErrors.BuildErrorResponse(this.ModelState));
            }

            try
            {
                ExtPubKey extPubKey = null;

                try
                {
                    extPubKey = ExtPubKey.Parse(request.ExtPubKey);
                }
                catch
                {
                }

                var model = new CreateColdStakingAccountResponse
                {
                    AccountName = this.ColdStakingManager.GetOrCreateColdStakingAccount(request.WalletName, request.IsColdWalletAccount, request.WalletPassword, extPubKey).Name
                };

                this.logger.LogTrace("(-):'{0}'", model);
                return(this.Json(model));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                this.logger.LogTrace("(-)[ERROR]");
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
Example #21
0
        //get child keys for given extended public key
        public static List <Tuple <string, string> > GetDerivedKeys(string extPublicKey, uint start, uint cnt, bool chg, bool testnet)      //public
        {
            CheckNullOrEmpty(new object[] { extPublicKey }, new string[] { "extPublicKey" });

            //key path  -44'\1'\0'\0   << public addresses (0' is wallet [hardened])
            //key path  -44'\1'\0'\1   << change addresses

            //https://programmingblockchain.gitbooks.io/programmingblockchain/content/key_generation/key_generation.html#hd-wallet-bip-32

            Network   ntwk = testnet ? Network.TestNet : Network.Main;
            ExtPubKey k    = ExtPubKey.Parse(extPublicKey); //xpub6BszcyR5c6gyrgchEk3XUrdFv4YfWEQzPXJBDN9WE7BEP5mwuSMnbuBv2khudobtUdKwLv1yvRACexYKgStbyKEPcKFTtQzQNdvy61rfLLC
            List <Tuple <string, string> > lst = new List <Tuple <string, string> >();
            uint addrType = chg ? 1u : 0u;                  //if change address, type=1. Else type=0 (receive)

            for (uint ctr = start; ctr < start + cnt; ctr++)
            {
                //return short address and long address needed by nbitcoin transaction
                lst.Add(new Tuple <string, string>(
                            k.Derive(addrType).Derive(ctr).PubKey.GetAddress(ntwk).ToString(), //short
                            k.Derive(addrType).Derive(ctr).PubKey.ToString()));                //long
            }
            return(lst);
        }
        public IActionResult CheckPayment()
        {
            ViewBag.Features = _featuresSettings;
            ViewBag.Setup    = _setupSettings;

            var pubkey         = ExtPubKey.Parse(_drawSettings.PublicKey);
            var depositAddress = pubkey.Derive(0).Derive(_settings.GetIterator()).PubKey.GetAddress(Network.StratisMain).ToString();

            ViewBag.DepositAddress = depositAddress;

            var     rc                   = new RestClient($"https://stratis.guru/api/address/{depositAddress}");
            var     rq                   = new RestRequest(Method.GET);
            var     response             = rc.Execute(rq);
            dynamic stratisAdressRequest = JsonConvert.DeserializeObject(response.Content);

            if (stratisAdressRequest.unconfirmedBalance + stratisAdressRequest.balance > 0)
            {
                HttpContext.Session.SetString("Deposited", depositAddress);
                HttpContext.Session.SetString("DepositedAmount", ((double)(stratisAdressRequest.unconfirmedBalance + stratisAdressRequest.balance)).ToString());
                return(Json(true));
            }
            return(BadRequest());
        }
        public static BitcoinExtPubKey BetterParseExtPubKey(string extPubKeyString, Network network, bool ignoreInvalidNetwork)
        {
            extPubKeyString = Guard.NotNullOrEmptyOrWhitespace(nameof(extPubKeyString), extPubKeyString, trim: true);

            ExtPubKey epk;

            try
            {
                epk = ExtPubKey.Parse(extPubKeyString, network); // Starts with "ExtPubKey": "xpub...
            }
            catch
            {
                try
                {
                    // Try hex, Old wallet format was like this.
                    epk = new ExtPubKey(ByteHelpers.FromHex(extPubKeyString)); // Starts with "ExtPubKey": "hexbytes...
                }
                catch when(ignoreInvalidNetwork)
                {
                    // Let's replace the version prefix
                    var data         = Encoders.Base58Check.DecodeData(extPubKeyString);
                    var versionBytes = network.GetVersionBytes(Base58Type.EXT_PUBLIC_KEY, true);

                    if (versionBytes.Length > data.Length)
                    {
                        throw;
                    }
                    for (int i = 0; i < versionBytes.Length; i++)
                    {
                        data[i] = versionBytes[i];
                    }
                    extPubKeyString = Encoders.Base58Check.EncodeData(data);
                    epk             = ExtPubKey.Parse(extPubKeyString, network);
                }
            }
            return(epk.GetWif(network));
        }
Example #24
0
        private ExtKey GetMasterKey()
        {
            if (String.IsNullOrEmpty(WalletExtendedPublicKey))
            {
                return(ExtKey.Parse(WalletPrivateKey));
            }

            var xpub     = ExtPubKey.Parse(WalletExtendedPublicKey);
            var password = default(SecureString);

            try
            {
                var encrypted = BitcoinEncryptedSecret.Create(WalletPrivateKey);
                password = GetPassword();

                return(new ExtKey(xpub, encrypted.GetKey(new NetworkCredential(String.Empty, password).Password)));
            }
            catch (FormatException)
            {
                return(new ExtKey(xpub, Key.Parse(WalletPrivateKey)));
            }
            catch (SecurityException)
            {
                Console.WriteLine("Invalid password.");
#if DEBUG
                Console.WriteLine("Press Any Key To Exit...");
                Console.Read();
#endif
                Environment.Exit(1);
                return(null);
            }
            finally
            {
                password?.Dispose();
            }
        }
Example #25
0
        public void Add(HdAccount account)
        {
            account.WalletAccounts = this;

            if (this.walletRepository == null)
            {
                this.accounts.Add(account);
                return;
            }

            this.walletRepository.CreateAccount(this.wallet.Name, account.Index, account.Name,
                                                (account.ExtendedPubKey == null) ? null : ExtPubKey.Parse(account.ExtendedPubKey), account.CreationTime);
        }
Example #26
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var extPubKeyString = (string)reader.Value;

            return(ExtPubKey.Parse(extPubKeyString, BitcoinNode.Network));
        }
Example #27
0
        private async Task Run()
        {
            _currentUser = UserPrincipal.Current;

            System.Console.WriteLine("Welcome to the KeepKey C# example console!");
            System.Console.WriteLine("Attempting to find KeepKey...");

            using (var kk = new KeepKeyDevice())
            {
                kk.Connected    += KkOnConnected;
                kk.Disconnected += KkOnDisconnected;

                if (!kk.TryOpenDevice())
                {
                    System.Console.WriteLine();
                    System.Console.WriteLine("No KeepKey connected.  Please connect KeepKey to the computer NOW. (Leave the console running)");

                    await kk.WaitForKeepKeyConnectionAsync();
                }

                System.Console.WriteLine();
                System.Console.WriteLine("Getting features...");

                // Step 1.  Initialize the device and get a list of it's features
                var features = kk.Initialize();

                // Print features to console - ouch!
                System.Console.WriteLine("Vendor:     {0}", features.Vendor);
                System.Console.WriteLine("DeviceId:   {0}", features.DeviceId);
                System.Console.WriteLine("Label:      {0}", features.Label);
                System.Console.WriteLine("Version:    {0}.{1}.{2}", features.MajorVersion.GetValueOrDefault(), features.MinorVersion.GetValueOrDefault(), features.PatchVersion.GetValueOrDefault());
                System.Console.WriteLine("Coins:      {0}", features.Coins.Select(c => $"{c.CoinName} ({c.CoinShortcut})").Aggregate((c, n) => $"{c}, {n}"));
                if (features.Policies.Any())
                {
                    System.Console.WriteLine("Policies:   {0}", features.Policies.Select(p => p.PolicyName).Aggregate((c, n) => $"{c}, {n}"));
                }
                System.Console.Write("Protection: ");
                var proPin  = features.PinProtection.GetValueOrDefault();
                var proPass = features.PassphraseProtection.GetValueOrDefault();
                if (proPin && proPass)
                {
                    System.Console.WriteLine("Pin, Passphrase");
                }
                else if (proPin && !proPass)
                {
                    System.Console.WriteLine("Pin ONLY");
                }
                else if (!proPin && proPass)
                {
                    System.Console.WriteLine("Passphrase ONLY");
                }
                else
                {
                    System.Console.WriteLine("Neither!");
                }
                System.Console.Write("Cached:     ");
                var cchPin  = features.PinCached.GetValueOrDefault();
                var cchPass = features.PassphraseCached.GetValueOrDefault();
                if (cchPin && cchPass)
                {
                    System.Console.WriteLine("Pin, Passphrase");
                }
                else if (cchPin && !cchPass)
                {
                    System.Console.WriteLine("Pin");
                }
                else if (!cchPin && cchPass)
                {
                    System.Console.WriteLine("Passphrase");
                }
                else
                {
                    System.Console.WriteLine("[nothing]");
                }

                // Step 2.  Have some fun with Ping!
                System.Console.WriteLine();
                System.Console.WriteLine("Pinging device...  (look at it, hold the button)");
                var name = _currentUser.DisplayName;                            // fullname
                if (name.IndexOf(' ') != -1)
                {
                    name = name.Split(' ')[0].Trim();                           // firstname
                }
                var pingReply = kk.Ping($"Hello {name}!  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam lacinia quis mauris volutpat scelerisque.", true);
                System.Console.WriteLine(pingReply);

                // Step 3a.  Getting the public key MIGHT require the Pin to be entered so lets define a function that allows it be entered via the console
                var pinChallengeFunction = new Func <PinMatrixRequestType?, string>(t =>
                {
                    System.Console.WriteLine();
                    System.Console.WriteLine("PIN CHALLENGE!!");
                    System.Console.WriteLine("┌───┬───┬───┐");
                    System.Console.WriteLine("│ 7 │ 8 │ 9 │");
                    System.Console.WriteLine("├───┼───┼───┤");
                    System.Console.WriteLine("│ 4 │ 5 │ 6 │");
                    System.Console.WriteLine("├───┼───┼───┤");
                    System.Console.WriteLine("│ 1 │ 2 │ 3 │");
                    System.Console.WriteLine("└───┴───┴───┘");
                    System.Console.WriteLine("Match the device screen with the above and enter the numbers of your scrambled pin below, press <enter> to send.");
                    var pin = System.Console.ReadLine();
                    System.Console.WriteLine();
                    return(pin);
                });

                // Step 3b.  Get the public key and extract the address
                for (var acc = 0; acc < 2; acc++)
                {
                    System.Console.WriteLine();
                    System.Console.WriteLine("Getting addresses for Bitcoin account {0}...", acc + 1);
                    System.Console.WriteLine();
                    for (var adr = 0; adr < 10; adr++)
                    {
                        var publicKey = kk.GetPublicKey(pinChallengeFunction, $"44'/0'/{acc}'/0/{adr}");
                        var extPubKey = ExtPubKey.Parse(publicKey.Xpub, Network.Main);
                        var pubKey    = extPubKey.PubKey;
                        var address   = pubKey.GetAddress(Network.Main);
                        System.Console.WriteLine("Address: {0}", address);
                    }
                }

                System.Console.WriteLine();
                System.Console.WriteLine("Press <enter> to quit console gracefully.");
                System.Console.ReadLine();

                kk.CloseDevice();
            }
        }
Example #28
0
        public static string GetDerivedKeysAll(string extKey, uint cnt, bool testnet)         //can pass in ext private or public key
        {
            try
            {
                string  result = "";
                Network ntwk   = testnet ? Network.TestNet : Network.Main;

                bool      IsPrv = extKey.Substring(1, 3) == "prv";            //xprv...
                ExtPubKey epbk;
                if (IsPrv)
                {
                    epbk = ExtKey.Parse(extKey).Neuter();
                }
                else
                {
                    epbk = ExtPubKey.Parse(extKey);
                }

                result += "\n" + (IsPrv ? "Private" : "Public") + " key entered. Testnet=" + (ntwk == Network.TestNet) + "\n";
                bool chg;
                if (IsPrv)                 //show derived private keys
                {
                    ExtKey k = ExtKey.Parse(extKey);
                    result += "\n" + "Ext Private Key: " + k.ToString(ntwk);
                    result += "\n" + "-- Derived Private Keys --";
                    chg     = false;
                    result += "\n" + " >> Recipient Addresses";
                    for (uint ctr = 0; ctr < cnt; ctr++)
                    {
                        result += "\n" + "" + ctr + ") " + k.Derive(chg ? 1u : 0u).Derive(ctr).PrivateKey.ToString(ntwk) + " : " + k.Derive(chg ? 1u : 0u).Derive(ctr).ToString(ntwk);
                    }
                    result += "\n" + " >> Change Addresses";
                    chg     = true;
                    for (uint ctr = 0; ctr < cnt; ctr++)
                    {
                        result += "\n" + "" + ctr + ") " + k.Derive(chg ? 1u : 0u).Derive(ctr).PrivateKey.ToString(ntwk) + " : " + k.Derive(chg ? 1u : 0u).Derive(ctr).ToString(ntwk);
                    }
                    result += "\n";
                }
                result += "\n" + "Ext Public Key: " + epbk.ToString(ntwk);
                result += "\n" + "-- Derived Public Keys --";
                chg     = false;
                result += "\n" + " >> Recipient Addresses";
                for (uint ctr = 0; ctr < cnt; ctr++)
                {
                    result += "\n" + "" + ctr + ") " + epbk.Derive(chg ? 1u : 0u).Derive(ctr).PubKey.GetAddress(ntwk) + " : " + epbk.Derive(chg ? 1u : 0u).Derive(ctr).ToString(ntwk);
                }
                result += "\n" + " >> Change Addresses";
                chg     = true;
                for (uint ctr = 0; ctr < cnt; ctr++)
                {
                    result += "\n" + "" + ctr + ") " + epbk.Derive(chg ? 1u : 0u).Derive(ctr).PubKey.GetAddress(ntwk) + " : " + epbk.Derive(chg ? 1u : 0u).Derive(ctr).ToString(ntwk);
                }

                return(result);
            }
            catch (Exception ex)
            {
                return("Error: " + ex.Message);
            }
        }
Example #29
0
 public string GenerateAddress(int id, string extPubKey)
 {
     return(ExtPubKey.Parse(extPubKey).Derive((uint)id).PubKey.GetAddress(Network.TestNet).ToString());
 }
Example #30
0
        public string CreateOutTransactionElectrum(string redeemScript, string xpubkey1, string xpubkey2, decimal amount1, decimal amount2)
        {
            if (amount1 <= 0m && amount2 <= 0m)
            {
                throw new ArgumentException("Amount is less or equal zero");
            }

            Script scriptPubKey;

            try
            {
                scriptPubKey = new Script(redeemScript);
            }
            catch (Exception e)
            {
                throw new ArgumentException("Redeem script is incorrect");
            }

            ExtPubKey xpubKey1;
            ExtPubKey xpubKey2;

            try
            {
                xpubKey1 = ExtPubKey.Parse(xpubkey1, Network.Main);
                xpubKey2 = ExtPubKey.Parse(xpubkey2, Network.Main);
            }
            catch (Exception e)
            {
                throw new ArgumentException("Extended public key is incorrect");
            }

            decimal estimateFeeSize = 400m;
            var     fee             = this.Fee(estimateFeeSize);

            if (fee == null)
            {
                throw new Exception("Cannot get fee");
            }

            var pubKeys = scriptPubKey.GetDestinationPublicKeys();

            var index1 = this.FindPubKey(xpubKey1, pubKeys[0]);
            var index2 = this.FindPubKey(xpubKey2, pubKeys[1]);

            var unspentCoins = GetUnspentCoins(scriptPubKey);

            var t = new Transaction();

            t.AddOutput(Money.Coins(amount1) - fee / 2, pubKeys[0].Hash);
            t.AddOutput(Money.Coins(amount2) - fee / 2, pubKeys[1].Hash);

            Base58CheckEncoder base58CheckEncoder = new Base58CheckEncoder();
            var    bytes1 = base58CheckEncoder.DecodeData(xpubKey1.GetWif(Network.Main).ToString());
            string hex1   = BitConverter.ToString(bytes1).Replace("-", "").ToLower();

            var    bytes2 = base58CheckEncoder.DecodeData(xpubKey2.GetWif(Network.Main).ToString());
            string hex2   = BitConverter.ToString(bytes2).Replace("-", "").ToLower();

            // special script sig in electrum have to contain these magic vars
            var s = "0001ff01ff4cad524c53ff" + hex1 + "0000"
                    + (index1 > 9 ? index1.ToString() : "0" + index1) + "00" + "4c53ff" + hex2 + "0000"
                    + (index2 > 9 ? index2.ToString() : "0" + index2) + "00" + "52ae";

            int   i          = 0;
            Money spendMoney = Money.Zero;

            foreach (var coin in unspentCoins)
            {
                t.AddInput(new TxIn(coin.Key.Outpoint));
                t.Inputs[i].ScriptSig = new Script(s);
                i++;

                spendMoney += coin.Key.Amount;
                if (spendMoney >= Money.Coins(amount1) + Money.Coins(amount2))
                {
                    if (spendMoney > Money.Coins(amount1) + Money.Coins(amount2))
                    {
                        t.AddOutput(spendMoney - (Money.Coins(amount1) + Money.Coins(amount2)), scriptPubKey.Hash);
                    }

                    spendMoney = null;
                    break;
                }
            }

            if (spendMoney == null)
            {
                return(t.ToHex().Replace("b64cb40001ff01ff4cad524c53ff", "b40001ff01ff4cad524c53ff"));
            }

            return(null);
        }